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.

Release manual-download DB scope and preserve retry claims (#7088)

LearningCircuit56736717558e
diff --git a/changelog.d/+manual-download-session-scope.bugfix.md b/changelog.d/+manual-download-session-scope.bugfix.md
new file mode 100644
index 0000000000..49093d4fa0
--- /dev/null
+++ b/changelog.d/+manual-download-session-scope.bugfix.md
@@ -0,0 +1 @@
+Manual library PDF downloads release their queue database scope during the network transfer and capture the resource ID before claiming, reducing connection pressure and preventing a failed database refresh from stranding the download as in progress.
diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.py
index ffe3618b87..2c340d7c20 100644
--- a/src/local_deep_research/web/routers/library.py
+++ b/src/local_deep_research/web/routers/library.py
@@ -29,7 +29,7 @@ from pathlib import Path
from loguru import logger
-from ...database.session_context import get_user_db_session, safe_rollback
+from ...database.session_context import get_user_db_session
from ...database.models.research import ResearchResource
from ...database.models.library import (
Document as Document,
@@ -1881,6 +1881,12 @@ async def download_source(
)
queue_item_id = queue_entry.id
+ # The claim commits and expires ORM rows. Snapshot the resource
+ # ID first so no attribute access can fail between claiming and
+ # the download. Base re-read resource.id after claiming, inside
+ # the try: that refresh raised, and although the handler caught
+ # it and released the claim, the download itself never ran.
+ resource_id = resource.id
# Claim the row before downloading, exactly as download_bulk does,
# so a bulk stream that reaches this row between the reset above and
@@ -1894,28 +1900,41 @@ async def download_source(
status_code=409,
)
- # Start download immediately
+ # The claim above is committed. Leave the thread-local read scope
+ # before the remote download, which may occupy this worker for minutes.
+ try:
+ with DownloadService(username, user_password) as service:
+ success, message = service.download_resource(resource_id)
+ except Exception:
+ # A fresh short-lived session — the download ran outside the read
+ # scope above, so there is no held session to roll back. Pass the
+ # password captured at request start: by the time a multi-minute
+ # transfer ends, logout / password change / the idle sweep may
+ # have cleared the session password store, and the store-less
+ # lookup would raise DatabaseSessionError before the release,
+ # stranding the row in PROCESSING (issue #4691). Guard the
+ # release so a failure here cannot mask the original exception.
try:
- with DownloadService(username, user_password) as service:
- success, message = service.download_resource(resource.id)
+ with get_user_db_session(username, user_password) as db_session:
+ # Release the claim so a later run can retry this row:
+ # the download raised before download_resource recorded a
+ # terminal status (issue #4691).
+ _release_download_queue_item(db_session, queue_item_id)
except Exception:
- safe_rollback(db_session, "download_source")
- # Release the claim so a later run can retry this row: the
- # download raised before download_resource recorded a terminal
- # status (issue #4691).
- _release_download_queue_item(db_session, queue_item_id)
- raise
-
- # download_resource writes a terminal status for the rows it
- # actually downloads, so this is a no-op for those; it fires on the
- # paths that don't (its already-downloaded early return), which
- # would otherwise strand the claim in PROCESSING.
+ logger.exception("Failed to release download-queue claim")
+ raise
+
+ # download_resource writes a terminal status for the rows it actually
+ # downloads, so this is a no-op for those; it fires on early returns,
+ # which would otherwise strand the claim in PROCESSING. The password
+ # must be passed for the same reason as the release above.
+ with get_user_db_session(username, user_password) as db_session:
_finalize_download_queue_item(db_session, queue_item_id, success)
- if success:
- return {"success": True, "message": "Download completed"}
- # Log internal message, but show only generic message to user
- return {"success": False, "message": "Download failed"}
+ if success:
+ return {"success": True, "message": "Download completed"}
+ # Log internal message, but show only generic message to user
+ return {"success": False, "message": "Download failed"}
# Offload the blocking DB + HTTP work so we don't stall the event loop.
return await run_db_sync(_download_sync)
diff --git a/tests/web/routers/test_download_queue_claim_routes_4691.py b/tests/web/routers/test_download_queue_claim_routes_4691.py
index 710b166e8d..3c34dc5ff2 100644
--- a/tests/web/routers/test_download_queue_claim_routes_4691.py
+++ b/tests/web/routers/test_download_queue_claim_routes_4691.py
@@ -43,7 +43,8 @@ from contextlib import contextmanager
from unittest.mock import MagicMock, patch
import pytest
-from sqlalchemy import create_engine
+from sqlalchemy import create_engine, event
+from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import sessionmaker
from starlette.requests import Request
@@ -620,6 +621,49 @@ def test_download_source_still_resets_and_downloads_a_row_not_in_flight(
assert ds_mock.download_resource.called
+def test_download_source_does_not_refresh_resource_after_claim(
+ tmp_path, request
+):
+ """A failed refresh after a committed claim must not strand PROCESSING."""
+ Session, queue_item_id, resource_id = _engine_with_pending_row(
+ tmp_path, "dsrc_expired_resource", request
+ )
+ with Session() as session:
+ engine = session.get_bind()
+ claim_committed = False
+ original_claim = library_module._claim_download_queue_item
+
+ def claim(*args):
+ nonlocal claim_committed
+ claim_committed = original_claim(*args)
+ return claim_committed
+
+ def fail_resource_refresh(
+ connection, cursor, statement, parameters, context, executemany
+ ):
+ if (
+ claim_committed
+ and statement.lstrip().upper().startswith("SELECT")
+ and "research_resources" in statement
+ ):
+ raise OperationalError(
+ statement, parameters, RuntimeError("resource refresh failed")
+ )
+
+ event.listen(engine, "before_cursor_execute", fail_resource_refresh)
+ try:
+ with patch.object(
+ library_module, "_claim_download_queue_item", side_effect=claim
+ ):
+ response, service = _run_download_source(Session)
+ finally:
+ event.remove(engine, "before_cursor_execute", fail_resource_refresh)
+
+ assert response == {"success": True, "message": "Download completed"}
+ service.download_resource.assert_called_once_with(resource_id)
+ assert _status_of(Session, queue_item_id) == DocumentStatus.COMPLETED
+
+
# ---------------------------------------------------------------------------
# queue_research_downloads -- the pre-pass `!= PROCESSING` reset guard
# (research_library/services/download_service.py)
diff --git a/tests/web/routers/test_library_download_outcomes.py b/tests/web/routers/test_library_download_outcomes.py
index bae158941a..63323fd2ca 100644
--- a/tests/web/routers/test_library_download_outcomes.py
+++ b/tests/web/routers/test_library_download_outcomes.py
@@ -151,8 +151,10 @@ class _RecordingQuery:
self._first_result = first_result
self._update_result = update_result
self.updates = []
+ self.filter_bys = []
def filter_by(self, **kwargs):
+ self.filter_bys.append(kwargs)
return self
def filter(self, *args, **kwargs):
@@ -198,6 +200,19 @@ def _resource(resource_id=1, research_id="r1"):
return row
+def _queue_entry(queue_id=42):
+ """A pre-existing ``LibraryDownloadQueue`` row for ``_resource``.
+
+ Distinct from any ``resource_id`` used alongside it on purpose: the
+ resource that gets downloaded and the queue row whose claim is
+ released are different rows, so tests can tell an id swap apart from
+ the correct behaviour.
+ """
+ row = Mock()
+ row.id = queue_id
+ return row
+
+
def _document(document_id="doc-1", status="completed"):
doc = Mock()
doc.id = document_id
@@ -479,6 +494,255 @@ class TestDownloadSourcePositiveControls:
)
[email protected]("download_raises", [False, True])
+def test_manual_download_releases_db_scope_during_transfer(download_raises):
+ """A claimed queue row must not pin a connection during remote I/O."""
+ session = _FakeSession(_resource(), queue_entry=None)
+ scope = {"active": False, "entries": 0}
+
+ @contextmanager
+ def fake_db_session(*args, **kwargs):
+ assert not scope["active"]
+ scope["active"] = True
+ scope["entries"] += 1
+ try:
+ yield session
+ finally:
+ scope["active"] = False
+
+ context, service = _download_service((True, None))
+
+ def download(resource_id):
+ assert resource_id == 1
+ assert session.queue_query.updates, "queue claim must precede download"
+ assert not scope["active"], "download held the queue's DB scope"
+ if download_raises:
+ raise RuntimeError("transfer failed")
+ return True, None
+
+ service.download_resource.side_effect = download
+ with (
+ patch.object(
+ library_module, "get_user_db_session", side_effect=fake_db_session
+ ),
+ patch.object(
+ library_module,
+ "get_authenticated_user_password",
+ return_value="pw",
+ ),
+ patch.object(
+ library_module, "get_document_for_resource", return_value=None
+ ),
+ patch.object(library_module, "DownloadService", return_value=context),
+ ):
+ request = _post_json_request({"research_id": "r1", "url": ARXIV_URL})
+ if download_raises:
+ with pytest.raises(RuntimeError, match="transfer failed"):
+ asyncio.run(download_source(request, username="alice"))
+ else:
+ response = asyncio.run(download_source(request, username="alice"))
+ assert response == {
+ "success": True,
+ "message": "Download completed",
+ }
+
+ assert not scope["active"]
+ assert scope["entries"] == 2 # claim, then finalise or release
+ assert len(session.queue_query.updates) == 2
+
+
+class TestManualDownloadQueueRetryability:
+ """What the manual route leaves in ``LibraryDownloadQueue`` when its
+ transfer raises.
+
+ The claim flips the row to PROCESSING before the download starts, and
+ nothing in ``src/`` reaps a PROCESSING row. If a raising manual download
+ does not hand the row back on its way out, it is stranded for good: the
+ manual reset guard refuses PROCESSING rows and the bulk pre-pass skips
+ them (issue #4691).
+
+ The release re-enters the DB after the transfer, so it must carry the
+ password captured at request start (a multi-minute transfer can outlive
+ the session password store, and the store-less lookup raises
+ ``DatabaseSessionError`` before the release ever runs), and a failure
+ inside the release must not mask the original transfer error -- the
+ sibling bulk route guards its release the same way.
+ """
+
+ #: Distinct on purpose: the resource that gets downloaded and the queue
+ #: row whose claim is released are different rows, so swapping their ids
+ #: fails the assertions below instead of satisfying them.
+ RESOURCE_ID = 7
+ QUEUE_ITEM_ID = 42
+
+ def test_a_raising_download_returns_the_queue_row_to_pending(self):
+ session = _FakeSession(
+ _resource(resource_id=self.RESOURCE_ID),
+ _queue_entry(queue_id=self.QUEUE_ITEM_ID),
+ )
+ scope_calls = []
+
+ @contextmanager
+ def fake_db_session(*args, **kwargs):
+ scope_calls.append(args)
+ yield session
+
+ context, service = _download_service((True, None))
+ service.download_resource.side_effect = RuntimeError("transfer failed")
+ with (
+ patch.object(
+ library_module,
+ "get_user_db_session",
+ side_effect=fake_db_session,
+ ),
+ patch.object(
+ library_module,
+ "get_authenticated_user_password",
+ return_value="pw",
+ ),
+ patch.object(
+ library_module, "get_document_for_resource", return_value=None
+ ),
+ patch.object(
+ library_module, "DownloadService", return_value=context
+ ),
+ ):
+ request = _post_json_request(
+ {"research_id": "r1", "url": ARXIV_URL}
+ )
+ with pytest.raises(RuntimeError, match="transfer failed"):
+ asyncio.run(download_source(request, username="alice"))
+
+ service.download_resource.assert_called_once_with(self.RESOURCE_ID)
+ # The post-raise re-entry must carry the request's password: after a
+ # multi-minute transfer the session password store can be gone
+ # (logout, password change, idle sweep) and the password-less lookup
+ # raises DatabaseSessionError before the release ever runs (#4691).
+ assert scope_calls == [
+ ("alice",),
+ ("alice", "pw"),
+ ]
+ # reset -> claim -> release: the last update hands the row back to
+ # PENDING, a retryable state, and not a terminal COMPLETED/FAILED
+ # one.
+ updates = session.queue_query.updates
+ assert len(updates) == 3
+ assert updates[-1] == {
+ library_module.LibraryDownloadQueue.status: (
+ library_module.DocumentStatus.PENDING
+ )
+ }, "a raising manual download must leave its queue row PENDING"
+ # It is this stream's own claim (the QUEUE_ITEM_ID row, still
+ # PROCESSING) that is released -- not the downloaded resource.
+ assert session.queue_query.filter_bys[-1] == {
+ "id": self.QUEUE_ITEM_ID,
+ "status": library_module.DocumentStatus.PROCESSING,
+ }
+
+ def test_a_successful_download_leaves_a_terminal_status(self):
+ """Positive control for the case above: the same code path over a
+ successful transfer finalises the row to COMPLETED instead of
+ returning it to the queue."""
+ session = _FakeSession(
+ _resource(resource_id=self.RESOURCE_ID),
+ _queue_entry(queue_id=self.QUEUE_ITEM_ID),
+ )
+ scope_calls = []
+
+ @contextmanager
+ def fake_db_session(*args, **kwargs):
+ scope_calls.append(args)
+ yield session
+
+ context, service = _download_service((True, None))
+ with (
+ patch.object(
+ library_module,
+ "get_user_db_session",
+ side_effect=fake_db_session,
+ ),
+ patch.object(
+ library_module,
+ "get_authenticated_user_password",
+ return_value="pw",
+ ),
+ patch.object(
+ library_module, "get_document_for_resource", return_value=None
+ ),
+ patch.object(
+ library_module, "DownloadService", return_value=context
+ ),
+ ):
+ request = _post_json_request(
+ {"research_id": "r1", "url": ARXIV_URL}
+ )
+ response = asyncio.run(download_source(request, username="alice"))
+
+ assert response == {"success": True, "message": "Download completed"}
+ service.download_resource.assert_called_once_with(self.RESOURCE_ID)
+ assert scope_calls == [
+ ("alice",),
+ ("alice", "pw"),
+ ]
+ updates = session.queue_query.updates
+ assert len(updates) == 3
+ status_column = library_module.LibraryDownloadQueue.status
+ assert (
+ updates[-1][status_column]
+ is library_module.DocumentStatus.COMPLETED
+ )
+ assert (
+ library_module.LibraryDownloadQueue.completed_at in updates[-1]
+ ), "finalise must record a terminal status, not requeue the row"
+
+ def test_a_failing_release_does_not_mask_the_download_error(self):
+ """If the release re-entry itself raises, the caller must still see
+ the original transfer error, not the release failure."""
+ session = _FakeSession(
+ _resource(resource_id=self.RESOURCE_ID),
+ _queue_entry(queue_id=self.QUEUE_ITEM_ID),
+ )
+ scope_calls = []
+
+ @contextmanager
+ def fake_db_session(*args, **kwargs):
+ scope_calls.append(args)
+ if len(scope_calls) == 2:
+ raise RuntimeError("password resolution failed")
+ yield session
+
+ context, service = _download_service((True, None))
+ service.download_resource.side_effect = RuntimeError("transfer failed")
+ with (
+ patch.object(
+ library_module,
+ "get_user_db_session",
+ side_effect=fake_db_session,
+ ),
+ patch.object(
+ library_module,
+ "get_authenticated_user_password",
+ return_value="pw",
+ ),
+ patch.object(
+ library_module, "get_document_for_resource", return_value=None
+ ),
+ patch.object(
+ library_module, "DownloadService", return_value=context
+ ),
+ ):
+ request = _post_json_request(
+ {"research_id": "r1", "url": ARXIV_URL}
+ )
+ with pytest.raises(RuntimeError, match="transfer failed"):
+ asyncio.run(download_source(request, username="alice"))
+
+ assert len(scope_calls) == 2, (
+ "the release re-entry never happened, so this test exercised "
+ "nothing about masking"
+ )
+
+
class TestDownloadTextPositiveControl:
def test_a_successful_text_extraction_reports_no_error(self):
response, service = _call_download_text((True, None))