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(library): keep staged download when source-type lookup fails (#8177)

Harshal Joshic04ed4c9b3c8
diff --git a/changelog.d/8176.bugfix.md b/changelog.d/8176.bugfix.md
new file mode 100644
index 0000000000..24c2ed0826
--- /dev/null
+++ b/changelog.d/8176.bugfix.md
@@ -0,0 +1 @@
+A failed source-type lookup during a library download no longer discards the download's tracker update and attempt record while still reporting success.
diff --git a/src/local_deep_research/database/library_init.py b/src/local_deep_research/database/library_init.py
index 8f8dde3364..c9dc6e62ac 100644
--- a/src/local_deep_research/database/library_init.py
+++ b/src/local_deep_research/database/library_init.py
@@ -9,6 +9,7 @@ This module handles:
import threading
import uuid
+from contextlib import nullcontext
from loguru import logger
from sqlalchemy.exc import IntegrityError
@@ -319,7 +320,7 @@ def get_default_library_id(username: str, password: str = None) -> str:
def get_source_type_id(
- username: str, type_name: str, password: str = None
+ username: str, type_name: str, password: str = None, session=None
) -> str:
"""
Get the ID of a source type by name.
@@ -328,6 +329,9 @@ def get_source_type_id(
username: User to query for
type_name: Name of source type (e.g., 'research_download', 'user_upload')
password: User's password (optional, uses session context)
+ session: The caller's open session. Pass it when the caller has
+ uncommitted work: a failure inside a nested get_user_db_session
+ scope rolls back the shared thread-local session, discarding it.
Returns:
UUID of the source type
@@ -336,9 +340,13 @@ def get_source_type_id(
ValueError: If source type not found
"""
try:
- with get_user_db_session(username, password) as session:
+ with (
+ nullcontext(session)
+ if session is not None
+ else get_user_db_session(username, password)
+ ) as db_session:
source_type = (
- session.query(SourceType).filter_by(name=type_name).first()
+ db_session.query(SourceType).filter_by(name=type_name).first()
)
if not source_type:
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 8c1b368a78..f37f60202e 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -695,8 +695,10 @@ def _save_pdf_document_record(
file_path_result = None
else:
try:
+ # Reuse the caller's session: it may hold a staged tracker update
+ # and attempt that a nested scope's rollback would discard.
source_type_id = get_source_type_id(
- username, "research_download", password
+ username, "research_download", password, session
)
except Exception:
source_type = (
diff --git a/tests/database/test_library_init.py b/tests/database/test_library_init.py
index 3c0bcc1360..91379fa2e5 100644
--- a/tests/database/test_library_init.py
+++ b/tests/database/test_library_init.py
@@ -482,3 +482,14 @@ class TestGetSourceTypeId:
assert result == "type-uuid"
mock_get_session.assert_called_once_with("testuser", None)
+
+ @patch("local_deep_research.database.library_init.get_user_db_session")
+ def test_callers_session_opens_no_nested_scope(self, mock_get_session):
+ """A passed session is queried directly, with no nested scope."""
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value.id = "type-uuid"
+
+ result = get_source_type_id("testuser", "manual_entry", None, session)
+
+ assert result == "type-uuid"
+ mock_get_session.assert_not_called()
diff --git a/tests/research_library/services/test_download_source_type_rollback.py b/tests/research_library/services/test_download_source_type_rollback.py
new file mode 100644
index 0000000000..e6084e7547
--- /dev/null
+++ b/tests/research_library/services/test_download_source_type_rollback.py
@@ -0,0 +1,87 @@
+"""A failed source-type lookup must not discard a staged download (#8176)."""
+
+from unittest.mock import Mock
+
+from sqlalchemy import create_engine, event
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database import thread_local_session
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.download_tracker import (
+ DownloadAttempt,
+ DownloadTracker,
+)
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ SourceType,
+)
+from local_deep_research.database.session_context import get_user_db_session
+from local_deep_research.research_library.services import download_service
+
+
+def test_failed_lookup_keeps_staged_attempt(tmp_path, monkeypatch):
+ engine = create_engine(f"sqlite:///{tmp_path / 'downloads.sqlite'}")
+ Base.metadata.create_all(engine)
+ sessions = sessionmaker(bind=engine)
+ url_hash = "a" * 64
+ with sessions() as seed:
+ seed.add_all(
+ [
+ SourceType(
+ id="source",
+ name="research_download",
+ display_name="Research",
+ ),
+ Collection(id="library", name="Library"),
+ DownloadTracker(
+ url="https://example.org/tracked.pdf",
+ url_hash=url_hash,
+ first_resource_id=1,
+ ),
+ ]
+ )
+ seed.commit()
+
+ failures = [RuntimeError("database is locked")]
+
+ @event.listens_for(engine, "before_cursor_execute")
+ def fail_first_lookup(
+ conn, cursor, statement, parameters, context, executemany
+ ):
+ if "FROM source_types" in statement and failures:
+ raise failures.pop()
+
+ with sessions() as shared_session:
+ # Keep the real get_user_db_session and its shared-session rollback;
+ # only replace encrypted connection discovery.
+ monkeypatch.setattr(
+ thread_local_session,
+ "get_metrics_session",
+ lambda username, password: shared_session,
+ )
+ with get_user_db_session("user", "password") as session:
+ session.add(
+ DownloadAttempt(
+ url_hash=url_hash, attempt_number=1, succeeded=True
+ )
+ )
+ download_service._save_pdf_document_record(
+ session=session,
+ pdf_storage_manager=Mock(
+ save_pdf=Mock(return_value=("database", 0))
+ ),
+ pdf_content=b"%PDF-1.4 downloaded bytes",
+ file_hash="b" * 64,
+ url="https://example.org/new.pdf",
+ username="user",
+ password="password",
+ collection_id="library",
+ )
+ session.commit()
+
+ assert not failures, "the injected lookup failure never fired"
+ with sessions() as verification:
+ assert verification.query(Document).count() == 1
+ assert verification.query(DownloadAttempt).count() == 1
+ engine.dispose()