~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(library): recover stale download claims in queue routes (#7887)
creedce971f5c3063
diff --git a/changelog.d/7871.bugfix.md b/changelog.d/7871.bugfix.mdnew file mode 100644index 0000000000..b46dbd5b6a--- /dev/null+++ b/changelog.d/7871.bugfix.md@@ -0,0 +1 @@+Allow manual source downloads and Download All New to retry queue entries left processing by a server restart, while preserving downloads still in progress.diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.pyindex d6e4e60c4d..c843e727ad 100644--- a/src/local_deep_research/web/routers/library.py+++ b/src/local_deep_research/web/routers/library.py@@ -29,6 +29,7 @@ from datetime import UTC, datetimefrom pathlib import Pathfrom loguru import logger+from sqlalchemy import or_from ...database.session_context import get_user_db_sessionfrom ...database.models.research import ResearchResource@@ -1562,9 +1563,9 @@ def _one_resource_per_awaiting_document(URL cannot be queued, the retry manager holds it back, or its latestattempt failed) is kept only when it is being downloaded or no viableone is there. A resource whose PROCESSING entry a restart left behind- comes last, since no reset touches that entry. The others count as- skipped. (Once the document holds its PDF again,- ``DownloadService.download_resource`` reports the document's own+ comes last during this selection; the queueing step can then reset its+ stale claim. The others count as skipped. (Once the document holds its PDF+ again, ``DownloadService.download_resource`` reports the document's ownresource as already downloaded, and for a linked one whose URL theegress policy allows, ``DownloadService._download_pdf`` reuses thatstored PDF instead of fetching it.)@@ -1646,6 +1647,22 @@ def _one_resource_per_awaiting_document(return kept, len(left_out)+def _resettable_download_queue_status(queue_entry):+ """Allow a stale PROCESSING row only while its observed claim is unchanged."""+ resettable = LibraryDownloadQueue.status != DocumentStatus.PROCESSING+ if queue_entry.status == DocumentStatus.PROCESSING and not (+ download_claim_is_live(queue_entry.last_attempt_at)+ ):+ same_claim = (+ LibraryDownloadQueue.last_attempt_at.is_(None)+ if queue_entry.last_attempt_at is None+ else LibraryDownloadQueue.last_attempt_at+ == queue_entry.last_attempt_at+ )+ resettable = or_(resettable, same_claim)+ return resettable++@router.post("/api/queue-all-undownloaded")def queue_all_undownloaded(request: Request, username: Annotated[str, Depends(require_auth)]@@ -1770,22 +1787,16 @@ def queue_all_undownloaded()if existing_queue:- # Reset a non-pending row back to PENDING so it is retried,- # but never one a concurrent download stream has claimed:- # PROCESSING satisfies `!= PENDING`, so an unguarded reset- # un-claims an in-flight row and lets a second stream- # re-download the same resource (issue #4691). The query above- # selects in-flight rows, since a download that has not- # finished has no completed Document yet. The guard lives- # inside the UPDATE, not in an `if` above it, so the check and- # the write cannot straddle another stream's claim.+ # Reset finished rows and claims stranded by a restart, but+ # preserve a download claimed by this running server. Match+ # the observed claim time inside the UPDATE so a new claim+ # cannot be reset between the read and the write.reset = (db_session.query(LibraryDownloadQueue).filter(LibraryDownloadQueue.id == existing_queue.id,LibraryDownloadQueue.status != DocumentStatus.PENDING,- LibraryDownloadQueue.status- != DocumentStatus.PROCESSING,+ _resettable_download_queue_status(existing_queue),).update({@@ -2035,19 +2046,13 @@ async def download_source(db_session.add(queue_entry)db_session.commit()else:- # Reset the row so this manual download can claim it, but never- # one a concurrent stream is already downloading: the reset is- # followed immediately by a download in this request thread, so- # un-claiming an in-flight row starts a second download of the- # same resource (issue #4691). The already-downloaded early- # return above cannot prevent that, because a download still in- # flight has not written a completed Document yet.+ # Reclaim a row stranded by a restart, while preserving an+ # in-flight download and any claim refreshed after our read.reset = (db_session.query(LibraryDownloadQueue).filter(LibraryDownloadQueue.id == queue_entry.id,- LibraryDownloadQueue.status- != DocumentStatus.PROCESSING,+ _resettable_download_queue_status(queue_entry),).update({diff --git a/tests/web/routers/test_download_queue_claim_routes_4691.py b/tests/web/routers/test_download_queue_claim_routes_4691.pyindex a43309fb8b..33e9ada445 100644--- a/tests/web/routers/test_download_queue_claim_routes_4691.py+++ b/tests/web/routers/test_download_queue_claim_routes_4691.py@@ -40,6 +40,7 @@ the status filter is dropped -- which is the entire content of the fix.import asyncioimport jsonfrom contextlib import contextmanager+from datetime import UTC, datetimefrom unittest.mock import MagicMock, patchimport pytest@@ -124,10 +125,13 @@ def _engine_with_pending_row(tmp_path, name, request):return tracked_session_factory, queue_item_id, resource_id-def _set_status(Session, queue_item_id, status):+def _set_status(Session, queue_item_id, status, claimed_at=None):session = Session()+ values = {LibraryDownloadQueue.status: status}+ if claimed_at is not None:+ values[LibraryDownloadQueue.last_attempt_at] = claimed_atsession.query(LibraryDownloadQueue).filter_by(id=queue_item_id).update(- {LibraryDownloadQueue.status: status}, synchronize_session=False+ values, synchronize_session=False)session.commit()session.close()@@ -485,7 +489,9 @@ def test_queue_all_undownloaded_does_not_reset_an_in_flight_claim(tmp_path, "qau_inflight", request)# A concurrent download_bulk stream holds the claim.- _set_status(Session, queue_item_id, DocumentStatus.PROCESSING)+ _set_status(+ Session, queue_item_id, DocumentStatus.PROCESSING, datetime.now(UTC)+ )result = _run_queue_all_undownloaded(Session, [resource_id])@@ -513,6 +519,46 @@ def test_queue_all_undownloaded_still_resets_a_failed_row(tmp_path, request):assert result["queued"] >= 1, result[email protected]("claimed_at", [None, datetime(2000, 1, 1, tzinfo=UTC)])+def test_queue_all_undownloaded_recovers_a_restart_stranded_claim(+ tmp_path, request, claimed_at+):+ Session, queue_item_id, resource_id = _engine_with_pending_row(+ tmp_path, "qau_stale", request+ )+ _set_status(Session, queue_item_id, DocumentStatus.PROCESSING, claimed_at)++ result = _run_queue_all_undownloaded(Session, [resource_id])++ assert result["queued"] == 1+ assert _status_of(Session, queue_item_id) is DocumentStatus.PENDING+++def test_queue_all_undownloaded_preserves_a_claim_replaced_after_read(+ tmp_path, request+):+ Session, queue_item_id, resource_id = _engine_with_pending_row(+ tmp_path, "qau_reclaimed", request+ )+ _set_status(Session, queue_item_id, DocumentStatus.PROCESSING)+ original_filter = library_module._resettable_download_queue_status++ def claim_before_update(observed_entry):+ _set_status(+ Session, queue_item_id, DocumentStatus.PROCESSING, datetime.now(UTC)+ )+ return original_filter(observed_entry)++ with patch.object(+ library_module,+ "_resettable_download_queue_status",+ side_effect=claim_before_update,+ ):+ _run_queue_all_undownloaded(Session, [resource_id])++ assert _status_of(Session, queue_item_id) is DocumentStatus.PROCESSING++# ---------------------------------------------------------------------------# download_source -- the `!= PROCESSING` reset guard (library.py)# ---------------------------------------------------------------------------@@ -572,7 +618,9 @@ def test_download_source_does_not_reset_an_in_flight_claim(tmp_path, request):Session, queue_item_id, _ = _engine_with_pending_row(tmp_path, "dsrc_inflight", request)- _set_status(Session, queue_item_id, DocumentStatus.PROCESSING)+ _set_status(+ Session, queue_item_id, DocumentStatus.PROCESSING, datetime.now(UTC)+ )response, ds_mock = _run_download_source(Session)@@ -622,6 +670,46 @@ def test_download_source_still_resets_and_downloads_a_row_not_in_flight(assert ds_mock.download_resource.called[email protected]("claimed_at", [None, datetime(2000, 1, 1, tzinfo=UTC)])+def test_download_source_recovers_a_restart_stranded_claim(+ tmp_path, request, claimed_at+):+ Session, queue_item_id, _ = _engine_with_pending_row(+ tmp_path, "dsrc_stale", request+ )+ _set_status(Session, queue_item_id, DocumentStatus.PROCESSING, claimed_at)++ response, service = _run_download_source(Session)++ assert response == {"success": True, "message": "Download completed"}+ service.download_resource.assert_called_once()+++def test_download_source_refuses_a_claim_replaced_after_read(tmp_path, request):+ Session, queue_item_id, _ = _engine_with_pending_row(+ tmp_path, "dsrc_reclaimed", request+ )+ _set_status(Session, queue_item_id, DocumentStatus.PROCESSING)+ original_filter = library_module._resettable_download_queue_status++ def claim_before_update(observed_entry):+ _set_status(+ Session, queue_item_id, DocumentStatus.PROCESSING, datetime.now(UTC)+ )+ return original_filter(observed_entry)++ with patch.object(+ library_module,+ "_resettable_download_queue_status",+ side_effect=claim_before_update,+ ):+ response, service = _run_download_source(Session)++ assert response.status_code == 409+ service.download_resource.assert_not_called()+ assert _status_of(Session, queue_item_id) is DocumentStatus.PROCESSING++def test_download_source_does_not_refresh_resource_after_claim(tmp_path, request):