~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): auto-persist research sources to library and prevent double-fetch (#6781) (#7416)
Sb3703cc3394d
diff --git a/changelog.d/7416.feature.md b/changelog.d/7416.feature.mdnew file mode 100644index 0000000000..47cb592d14--- /dev/null+++ b/changelog.d/7416.feature.md@@ -0,0 +1,5 @@+---+type: feature+---++Add opt-in auto-persist of research sources to the Library (`research_library.auto_persist_research_sources`, default off). When enabled, completed runs link already-fetched PDFs without re-downloading; PDF downloads honor `document_scheduler.download_pdfs` and `research_library.pdf_storage_mode`. Plain web pages are still fetched at completion by design. Note: a PDF fetched before its run is cancelled may already be persisted in the Library.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 329324102e..5b571fa03d 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -220,6 +220,7 @@ They are not available in the Web UI because they are needed to start the applic| `report.searches_per_section` | `LDR_REPORT_SEARCHES_PER_SECTION` | `2` | Number of web searches to perform per report section. Higher values increase research depth for each section but also increase search engine queries and processing time. Default is 2. | REPORT || `report.uncited_sources_mode` | `LDR_REPORT_UNCITED_SOURCES_MODE` | `fallback` | Which sources appear in the final report bibliography. Cited only with fallback keeps sources cited in the report body and falls back to all sources when no citations are detected; strict keeps only cited sources; legacy lists every accumulated search hit. | REPORT || `research_library.auto_index_enabled` | `LDR_RESEARCH_LIBRARY_AUTO_INDEX_ENABLED` | `false` | Automatically index documents for RAG search when they are added to collections (via upload or download). Indexing runs in the background without blocking uploads. Disable to defer indexing and improve upload speed for large batches. | APP |+| `research_library.auto_persist_research_sources` | `LDR_RESEARCH_LIBRARY_AUTO_PERSIST_RESEARCH_SOURCES` | `false` | Automatically persist research sources (PDFs and extracted text) into the Library when a research run completes. Default off. When enabled, PDF downloads still honor the scheduler preference document_scheduler.download_pdfs and the PDF storage mode. | APP || `research_library.confirm_deletions` | `LDR_RESEARCH_LIBRARY_CONFIRM_DELETIONS` | `true` | Show confirmation dialogs before delete operations. Recommended to keep enabled to prevent accidental data loss. | APP || `research_library.max_pdf_size_mb` | `LDR_RESEARCH_LIBRARY_MAX_PDF_SIZE_MB` | `3072` | Maximum allowed PDF file size in megabytes for the research library. PDFs larger than this will not be stored. Uploads are also gated by the per-file upload cap (LDR_SECURITY_UPLOAD_MAX_FILE_SIZE_MB, default 3072 MB / 3 GB) — raising this value above that cap has no effect because uploads are rejected before they reach storage. | APP || `research_library.pdf_storage_mode` | `RESEARCH_LIBRARY_PDF_STORAGE_MODE` | `database` | Choose how PDFs are stored. Each user has their own encrypted database. Database mode stores PDFs encrypted within it (secure, portable, isolated per-user). Filesystem mode stores unencrypted files on disk (faster for large files). None stores only extracted text (smallest footprint). | APP |diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.pyindex be82c7743f..17f180e7a7 100644--- a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py@@ -1023,12 +1023,29 @@ def _fetch_raw_content(except Exception: # pragma: no cover - defensive_hit = None+ username = getattr(egress_context, "username", None)+ password = getattr(egress_context, "password", None)+ try:+ from ....utilities.thread_context import resolve_fetch_identity++ username, password, settings_snapshot = resolve_fetch_identity(+ egress_context=egress_context,+ settings_snapshot=settings_snapshot,+ username=username,+ password=password,+ )+ except Exception: # allow: silent-exception+ pass+enable_js = _read_js_rendering_setting(settings_snapshot)fetcher_options = {"timeout": CONTENT_FETCH_TIMEOUT,"enable_js_rendering": enable_js,"egress_context": egress_context,"content_cache": _cache,+ "username": username,+ "password": password,+ "settings_snapshot": settings_snapshot,}if url_guard is not None:fetcher_options["url_guard"] = url_guarddiff --git a/src/local_deep_research/content_fetcher/fetcher.py b/src/local_deep_research/content_fetcher/fetcher.pyindex 4b8d508e90..c8063c15d9 100644--- a/src/local_deep_research/content_fetcher/fetcher.py+++ b/src/local_deep_research/content_fetcher/fetcher.py@@ -56,6 +56,9 @@ class ContentFetcher:egress_context: Any = None,content_cache: Any = None,url_guard: Any = None,+ username: Optional[str] = None,+ password: Optional[str] = None,+ settings_snapshot: Optional[dict] = None,):"""Initialize the content fetcher.@@ -91,6 +94,9 @@ class ContentFetcher:static extraction without browser or source enrichment.They never read or store page content in the shared cache;only its per-run SSRF validation memo is shared.+ username: Optional username for user context and library persistence.+ password: Optional database encryption password.+ settings_snapshot: Optional settings dictionary snapshot."""self.timeout = timeoutself.language = language@@ -98,6 +104,21 @@ class ContentFetcher:self.egress_context = egress_contextself.content_cache = content_cacheself.url_guard = url_guard+ try:+ from ..utilities.thread_context import resolve_fetch_identity++ username, password, settings_snapshot = resolve_fetch_identity(+ egress_context=egress_context,+ settings_snapshot=settings_snapshot,+ username=username,+ password=password,+ )+ except Exception:+ username = username or getattr(egress_context, "username", None)+ password = password or getattr(egress_context, "password", None)+ self.username = username+ self.password = password+ self.settings_snapshot = settings_snapshotself._downloaders: Dict[URLType, Any] = {}def _resolve_cache(self) -> Any:@@ -122,13 +143,24 @@ class ContentFetcher:if url_type in self._downloaders:return self._downloaders[url_type]+ downloader_kwargs: Dict[str, Any] = {}+ if self.username is not None:+ downloader_kwargs["username"] = self.username+ if self.password is not None:+ downloader_kwargs["password"] = self.password+ if self.settings_snapshot is not None:+ downloader_kwargs["settings_snapshot"] = self.settings_snapshot+downloader: Any = Noneif url_type == URLType.ARXIV:try:from ..research_library.downloaders.arxiv import ArxivDownloader- downloader = ArxivDownloader(timeout=self.timeout)+ downloader = ArxivDownloader(+ timeout=self.timeout,+ **downloader_kwargs,+ )except ImportError:logger.warning("content_fetcher.arxiv_downloader_unavailable")@@ -138,7 +170,10 @@ class ContentFetcher:PubMedDownloader,)- downloader = PubMedDownloader(timeout=self.timeout)+ downloader = PubMedDownloader(+ timeout=self.timeout,+ **downloader_kwargs,+ )except ImportError:logger.warning("content_fetcher.pubmed_downloader_unavailable")@@ -148,7 +183,10 @@ class ContentFetcher:SemanticScholarDownloader,)- downloader = SemanticScholarDownloader(timeout=self.timeout)+ downloader = SemanticScholarDownloader(+ timeout=self.timeout,+ **downloader_kwargs,+ )except ImportError:logger.warning("content_fetcher.semantic_scholar_downloader_unavailable"@@ -160,7 +198,10 @@ class ContentFetcher:BioRxivDownloader,)- downloader = BioRxivDownloader(timeout=self.timeout)+ downloader = BioRxivDownloader(+ timeout=self.timeout,+ **downloader_kwargs,+ )except ImportError:logger.warning("content_fetcher.biorxiv_downloader_unavailable")@@ -170,7 +211,10 @@ class ContentFetcher:DirectPDFDownloader,)- downloader = DirectPDFDownloader(timeout=self.timeout)+ downloader = DirectPDFDownloader(+ timeout=self.timeout,+ **downloader_kwargs,+ )except ImportError:logger.warning("content_fetcher.direct_pdf_downloader_unavailable"@@ -186,7 +230,9 @@ class ContentFetcher:)downloader = StaticHTMLDownloader(- timeout=self.timeout, language=self.language+ timeout=self.timeout,+ language=self.language,+ **downloader_kwargs,)else:from ..research_library.downloaders.playwright_html import (@@ -197,6 +243,7 @@ class ContentFetcher:timeout=self.timeout,language=self.language,enable_js_rendering=self.enable_js_rendering,+ **downloader_kwargs,)except ImportError:logger.warning("content_fetcher.html_downloader_unavailable")@@ -459,21 +506,127 @@ class ContentFetcher:)downloader = html_downloaderif result.is_success and result.content:- if result.content[:4] == b"%PDF":+ # Decode content — check PDF magic first (allowing+ # leading bytes within the first 1024 per spec), then+ # UTF-8. This runs only on the cache-miss path+ # (_download_once), so cache hits never re-persist.+ from ..research_library.services.download_service import (+ _is_pdf_bytes,+ )++ metadata: Dict[str, Any] = {}+ metadata_fetched = False+ raw_pdf_bytes: Optional[bytes] = None+ candidate_pdf = getattr(result, "pdf_content", None)+ if isinstance(candidate_pdf, (bytes, bytearray)):+ raw_pdf_bytes = bytes(candidate_pdf)+ if raw_pdf_bytes is None:+ candidate_dl_pdf = getattr(+ downloader, "_last_pdf_content", None+ )+ if isinstance(candidate_dl_pdf, (bytes, bytearray)):+ raw_pdf_bytes = bytes(candidate_dl_pdf)+ if (+ raw_pdf_bytes is None+ and isinstance(result.content, (bytes, bytearray))+ and _is_pdf_bytes(result.content)+ ):+ raw_pdf_bytes = bytes(result.content)++ if raw_pdf_bytes is not None and _is_pdf_bytes(+ raw_pdf_bytes+ ):from ..research_library.downloaders.base import (BaseDownloader,)- content = BaseDownloader.extract_text_from_pdf(- result.content- )- if not content:- return {- "status": "error",- "url": url,- "source_type": source_name,- "error": "Could not extract text from PDF",- }+ if raw_pdf_bytes is not result.content:+ try:+ content = result.content.decode("utf-8")+ except UnicodeDecodeError:+ content = BaseDownloader.extract_text_from_pdf(+ raw_pdf_bytes+ )+ else:+ content = BaseDownloader.extract_text_from_pdf(+ raw_pdf_bytes+ )+ if not content or not content.strip():+ if (+ raw_pdf_bytes.lstrip(+ b"\xef\xbb\xbf\x00 \t\r\n"+ )[:4]+ == b"%PDF"+ ):+ return {+ "status": "error",+ "url": url,+ "source_type": source_name,+ "error": "Could not extract text from PDF",+ }+ try:+ content = raw_pdf_bytes.decode("utf-8")+ except UnicodeDecodeError:+ return {+ "status": "error",+ "url": url,+ "source_type": source_name,+ "error": "Could not extract text from PDF",+ }+ else:+ # Single fetch-time writer (downloaders do not+ # persist; library downloads persist+ # synchronously in DownloadService). Fetch+ # metadata once and reuse it below so HTML+ # get_metadata does not re-fetch the page.+ if hasattr(downloader, "get_metadata"):+ try:+ fetched_meta = downloader.get_metadata(url)+ if isinstance(fetched_meta, dict):+ metadata = fetched_meta+ metadata_fetched = True+ except Exception:+ logger.opt(exception=False).debug(+ "content_fetcher.metadata_failed url={url}",+ url=redact_url_for_log(url),+ )+ # Persist when PDF extraction produced valid text+ # and the payload matches PDF detection (aligning with+ # _is_pdf_bytes to cover spec-legal PDFs with leading junk).+ if _is_pdf_bytes(raw_pdf_bytes):+ try:+ from ..research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ pdf_title = (+ metadata.get("title")+ if metadata+ else None+ )+ extra_urls = None+ final_url = getattr(+ downloader, "_last_final_url", None+ )+ if final_url and final_url != url:+ extra_urls = [final_url]+ persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=raw_pdf_bytes,+ text=content,+ title=pdf_title,+ username=self.username,+ password=self.password,+ settings_snapshot=self.settings_snapshot,+ extra_urls=extra_urls,+ run_in_background=True,+ check_setting=True,+ )+ except Exception:+ logger.opt(exception=False).debug(+ "content_fetcher.persist_skipped url={url}",+ url=redact_url_for_log(url),+ )else:try:content = result.content.decode("utf-8")@@ -486,8 +639,9 @@ class ContentFetcher:"Content is not valid UTF-8 and not a PDF"),}- metadata: Dict[str, Any] = {}- if hasattr(downloader, "get_metadata"):+ if not metadata_fetched and hasattr(+ downloader, "get_metadata"+ ):try:metadata = downloader.get_metadata(url)except Exception:diff --git a/src/local_deep_research/defaults/research_library/library_settings.json b/src/local_deep_research/defaults/research_library/library_settings.jsonindex 6547794c80..eec07618c3 100644--- a/src/local_deep_research/defaults/research_library/library_settings.json+++ b/src/local_deep_research/defaults/research_library/library_settings.json@@ -136,5 +136,20 @@"ui_element": "checkbox","value": true,"visible": true+ },+ "research_library.auto_persist_research_sources": {+ "category": "research_library",+ "description": "Automatically persist research sources (PDFs and extracted text) into the Library when a research run completes. Default off. When enabled, PDF downloads still honor the scheduler preference document_scheduler.download_pdfs and the PDF storage mode.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Auto-Persist Research Sources",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true,+ "env_var": "LDR_RESEARCH_LIBRARY_AUTO_PERSIST_RESEARCH_SOURCES"}}diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.pyindex 5773657b9c..4967b115f2 100644--- a/src/local_deep_research/research_library/downloaders/arxiv.py+++ b/src/local_deep_research/research_library/downloaders/arxiv.py@@ -166,6 +166,7 @@ class ArxivDownloader(HTMLDownloader):language: str = "English",*,fetch_host: str = "arxiv.org",+ **kwargs,):"""``fetch_host`` is the host the HTML and PDF legs request from.@@ -178,7 +179,7 @@ class ArxivDownloader(HTMLDownloader):if fetch_host not in ("arxiv.org", ARXIV_EXPORT_HOST):raise ValueError("fetch_host must be arxiv.org or export.arxiv.org")self._fetch_host = fetch_host- super().__init__(timeout=timeout, language=language)+ super().__init__(timeout=timeout, language=language, **kwargs)session = self.sessionif session is not None:session.headers.update({"User-Agent": USER_AGENT})diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.pyindex e9bf43dce1..dd77366a3f 100644--- a/src/local_deep_research/research_library/downloaders/base.py+++ b/src/local_deep_research/research_library/downloaders/base.py@@ -107,6 +107,7 @@ class DownloadResult(NamedTuple):# Abstract/metadata fallbacks are useful display text, but cannot# satisfy a later request for the complete source from a shared cache.content_is_complete: bool = True+ pdf_content: Optional[bytes] = Noneclass _ResponseBodyTooLarge(Exception):@@ -131,14 +132,62 @@ _DOCUMENT_ABSENT_STATUSES: frozenset[int] = frozenset({404, 410})class BaseDownloader(ABC):"""Abstract base class for academic content downloaders."""- def __init__(self, timeout: int = 30):+ def __init__(+ self,+ timeout: int = 30,+ username: Optional[str] = None,+ password: Optional[str] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ enable_fetch_persistence: bool = True,+ **kwargs,+ ):"""Initialize the downloader.Args:timeout: Request timeout in seconds+ username: Optional username for identity propagation+ password: Optional database password+ settings_snapshot: Optional settings dictionary+ enable_fetch_persistence: When True, research-fetch paths may+ persist PDFs on-the-spot. DownloadService constructs its+ downloaders with False because it saves synchronously —+ otherwise each sweep download would persist twice."""+ if kwargs:+ # ``language`` is forwarded by several subclasses and consumed+ # by them, not here. Anything else is a caller typo: warn+ # instead of silently dropping it.+ unknown = sorted(set(kwargs) - {"language"})+ if unknown:+ logger.warning(+ f"BaseDownloader ignoring unknown arguments: {unknown}"+ )self.timeout = timeout+ self.username = username+ self.password = password+ self.settings_snapshot = settings_snapshot+ self.enable_fetch_persistence = enable_fetch_persistence+ # Last redirect final URL and raw PDF bytes seen by _download_pdf, exposed+ # so the single fetch-time writer (ContentFetcher) can track and persist them.+ self._last_final_url: Optional[str] = None+ self._last_pdf_content: Optional[bytes] = None+ if not self.username or not self.password:+ try:+ from ...utilities.thread_context import resolve_fetch_identity++ (+ self.username,+ self.password,+ self.settings_snapshot,+ ) = resolve_fetch_identity(+ username=self.username,+ password=self.password,+ settings_snapshot=self.settings_snapshot,+ )+ except Exception: # allow: silent-exception+ pass+self.session = SafeSession(block_https_downgrade=True)self.session.headers.update({"User-Agent": USER_AGENT})@@ -416,6 +465,8 @@ class BaseDownloader(ABC):f"Downloading PDF from {redact_url_for_log(url)} with adaptive "f"rate limiting (max {max_attempts} attempts)")+ self._last_pdf_content = None+ self._last_final_url = Nonefor attempt in range(1, max_attempts + 1):# Apply adaptive rate limiting before the request@@ -467,6 +518,23 @@ class BaseDownloader(ABC):retry_count=attempt,search_result_count=1, # We got the PDF)+ self._last_pdf_content = body+ # Single fetch-time writer lives in ContentFetcher;+ # downloaders only record the redirect final URL.+ # Library downloads persist synchronously in+ # DownloadService._download_pdf.+ try:+ resp_url = getattr(response, "url", None)+ if resp_url and resp_url != url:+ self._last_final_url = resp_url+ else:+ self._last_final_url = None+ except Exception as exc:+ logger.opt(exception=False).debug(+ "pdf.final_url_track_failed url={url} exc_class={exc_class}",+ url=redact_url_for_log(url),+ exc_class=type(exc).__name__,+ )return bodylogger.warning(f"Response is not a PDF: {response.headers.get('content-type', 'unknown')}"diff --git a/src/local_deep_research/research_library/downloaders/biorxiv.py b/src/local_deep_research/research_library/downloaders/biorxiv.pyindex f85309e3ec..b4396c2a42 100644--- a/src/local_deep_research/research_library/downloaders/biorxiv.py+++ b/src/local_deep_research/research_library/downloaders/biorxiv.py@@ -60,7 +60,9 @@ class BioRxivDownloader(BaseDownloader):extracted_text = self.extract_text_from_pdf(pdf_content)if extracted_text:return DownloadResult(- content=extracted_text.encode("utf-8"), is_success=True+ content=extracted_text.encode("utf-8"),+ is_success=True,+ pdf_content=pdf_content,)return DownloadResult(@@ -79,7 +81,9 @@ class BioRxivDownloader(BaseDownloader):pdf_content = super()._download_pdf(pdf_url)if pdf_content:- return DownloadResult(content=pdf_content, is_success=True)+ return DownloadResult(+ content=pdf_content, is_success=True, pdf_content=pdf_content+ )# Check if it's a server issue or article doesn't existtry:response = self.session.head(url, timeout=5)diff --git a/src/local_deep_research/research_library/downloaders/direct_pdf.py b/src/local_deep_research/research_library/downloaders/direct_pdf.pyindex 011ff2f009..52d0f32a88 100644--- a/src/local_deep_research/research_library/downloaders/direct_pdf.py+++ b/src/local_deep_research/research_library/downloaders/direct_pdf.py@@ -68,7 +68,9 @@ class DirectPDFDownloader(BaseDownloader):text = self.extract_text_from_pdf(pdf_content)if text:return DownloadResult(- content=text.encode("utf-8"), is_success=True+ content=text.encode("utf-8"),+ is_success=True,+ pdf_content=pdf_content,)return DownloadResult(skip_reason="PDF downloaded but text extraction failed"@@ -80,14 +82,16 @@ class DirectPDFDownloader(BaseDownloader):logger.info(f"Attempting direct PDF download from {redact_url_for_log(url)}")- pdf_content = super()._download_pdf(url)+ pdf_content = self._download_pdf(url)if pdf_content:logger.info(f"Successfully downloaded PDF directly from "f"{redact_url_for_log(url)}")- return DownloadResult(content=pdf_content, is_success=True)+ return DownloadResult(+ content=pdf_content, is_success=True, pdf_content=pdf_content+ )# Try to determine specific reason for failuretry:response = self.session.head(url, timeout=5, allow_redirects=True)diff --git a/src/local_deep_research/research_library/downloaders/generic.py b/src/local_deep_research/research_library/downloaders/generic.pyindex 7c6dd31386..093a3655b4 100644--- a/src/local_deep_research/research_library/downloaders/generic.py+++ b/src/local_deep_research/research_library/downloaders/generic.py@@ -92,7 +92,9 @@ class GenericDownloader(BaseDownloader):text = self.extract_text_from_pdf(pdf_content)if text:return DownloadResult(- content=text.encode("utf-8"), is_success=True+ content=text.encode("utf-8"),+ is_success=True,+ pdf_content=pdf_content,)return DownloadResult(skip_reason="PDF downloaded but text extraction failed"@@ -110,7 +112,9 @@ class GenericDownloader(BaseDownloader):logger.info(f"Successfully downloaded PDF from {redact_url_for_log(url)}")- return DownloadResult(content=pdf_content, is_success=True)+ return DownloadResult(+ content=pdf_content, is_success=True, pdf_content=pdf_content+ )# If the URL doesn't end with .pdf, try adding itpdf_url = _with_pdf_suffix(url)@@ -126,7 +130,9 @@ class GenericDownloader(BaseDownloader):logger.info(f"Successfully downloaded PDF from {redact_url_for_log(pdf_url)}")- return DownloadResult(content=pdf_content, is_success=True)+ return DownloadResult(+ content=pdf_content, is_success=True, pdf_content=pdf_content+ )# Diagnostic request: determine WHY the download failed.#diff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.pyindex bd936747a4..3fdf1141bd 100644--- a/src/local_deep_research/research_library/downloaders/html.py+++ b/src/local_deep_research/research_library/downloaders/html.py@@ -126,9 +126,18 @@ class HTMLDownloader(BaseDownloader):self,timeout: int = 30,language: str = "English",+ username: Optional[str] = None,+ password: Optional[str] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,**kwargs,):- super().__init__(timeout)+ super().__init__(+ timeout=timeout,+ username=username,+ password=password,+ settings_snapshot=settings_snapshot,+ **kwargs,+ )self.session.headers.update({"User-Agent": BROWSER_USER_AGENT})self.language = language@@ -157,6 +166,8 @@ class HTMLDownloader(BaseDownloader):Returns:Extracted text as UTF-8 bytes, or None if failed"""+ self._last_pdf_content = None+ self._last_final_url = Noneif content_type == ContentType.PDF:logger.warning("html.download_pdf_unsupported url={url}",@@ -179,6 +190,18 @@ class HTMLDownloader(BaseDownloader):payload, final_url or url, url)if pdf_text:+ try:+ self._last_final_url = (+ final_url+ if final_url and final_url != url+ else None+ )+ except Exception: # allow: silent-exception+ pass+ try:+ self._last_pdf_content = payload+ except Exception: # allow: silent-exception+ passreturn pdf_text.encode("utf-8")elif kind == "text" and isinstance(payload, str):if payload.strip():@@ -220,6 +243,8 @@ class HTMLDownloader(BaseDownloader):are reduced to a client-safe skip reason. Extraction failures andmissing documents (404/410) remain per-document results."""+ self._last_pdf_content = None+ self._last_final_url = Noneif content_type == ContentType.PDF:return DownloadResult(skip_reason="HTML downloader does not support PDF downloads"@@ -247,9 +272,22 @@ class HTMLDownloader(BaseDownloader):payload, final_url or url, url)if pdf_text:+ try:+ self._last_final_url = (+ final_url+ if final_url and final_url != url+ else None+ )+ except Exception: # allow: silent-exception+ pass+ try:+ self._last_pdf_content = payload+ except Exception: # allow: silent-exception+ passreturn DownloadResult(content=pdf_text.encode("utf-8"),is_success=True,+ pdf_content=payload,)return DownloadResult(skip_reason=(diff --git a/src/local_deep_research/research_library/downloaders/openalex.py b/src/local_deep_research/research_library/downloaders/openalex.pyindex 451e6f9e26..9a7512cb3e 100644--- a/src/local_deep_research/research_library/downloaders/openalex.py+++ b/src/local_deep_research/research_library/downloaders/openalex.py@@ -29,6 +29,7 @@ class OpenAlexDownloader(BaseDownloader):timeout: int = 30,polite_pool_email: Optional[str] = None,api_key: Optional[str] = None,+ **kwargs,):"""Initialize OpenAlex downloader.@@ -45,7 +46,7 @@ class OpenAlexDownloader(BaseDownloader):later lookup goes out keyless, so a bad key never turnsan available PDF into "no PDF available"."""- super().__init__(timeout)+ super().__init__(timeout, **kwargs)self.polite_pool_email = polite_pool_emailself.api_key: Optional[str] = normalize_openalex_api_key(api_key)# Set only once OpenAlex refuses the key; kept so ``_scrub``diff --git a/src/local_deep_research/research_library/downloaders/playwright_html.py b/src/local_deep_research/research_library/downloaders/playwright_html.pyindex 7efa95a287..b250ffedf3 100644--- a/src/local_deep_research/research_library/downloaders/playwright_html.py+++ b/src/local_deep_research/research_library/downloaders/playwright_html.py@@ -284,7 +284,7 @@ class PlaywrightHTMLDownloader(HTMLDownloader):block_link_local: bool = False,**kwargs,):- super().__init__(timeout=timeout, language=language)+ super().__init__(timeout=timeout, language=language, **kwargs)self.wait_until = wait_untilself.block_resources = block_resources# SSRF policy for the browser route guards (initial navigation +@@ -1332,7 +1332,7 @@ class AutoHTMLDownloader(HTMLDownloader):block_link_local: bool = False,**kwargs,):- super().__init__(timeout=timeout, language=language)+ super().__init__(timeout=timeout, language=language, **kwargs)self.min_content_length = min_content_lengthself.enable_js_rendering = enable_js_rendering# SSRF policy threaded to the lazily-built Playwright child so thediff --git a/src/local_deep_research/research_library/downloaders/pubmed.py b/src/local_deep_research/research_library/downloaders/pubmed.pyindex 66e63be060..32d94eaca9 100644--- a/src/local_deep_research/research_library/downloaders/pubmed.py+++ b/src/local_deep_research/research_library/downloaders/pubmed.py@@ -16,7 +16,9 @@ from ...security.egress.policy import PolicyDeniedErrorclass PubMedDownloader(BaseDownloader):"""Downloader for PubMed and PubMed Central articles with PDF and text support."""- def __init__(self, timeout: int = 30, rate_limit_delay: float = 1.0):+ def __init__(+ self, timeout: int = 30, rate_limit_delay: float = 1.0, **kwargs+ ):"""Initialize PubMed downloader.@@ -24,7 +26,7 @@ class PubMedDownloader(BaseDownloader):timeout: Request timeout in secondsrate_limit_delay: Delay between requests to avoid rate limiting"""- super().__init__(timeout)+ super().__init__(timeout, **kwargs)self.rate_limit_delay = rate_limit_delayself.last_request_time: float = 0.0diff --git a/src/local_deep_research/research_library/downloaders/semantic_scholar.py b/src/local_deep_research/research_library/downloaders/semantic_scholar.pyindex 7dda6ce721..4ec7c36c82 100644--- a/src/local_deep_research/research_library/downloaders/semantic_scholar.py+++ b/src/local_deep_research/research_library/downloaders/semantic_scholar.py@@ -19,7 +19,9 @@ from .base import BaseDownloader, ContentType, DownloadResultclass SemanticScholarDownloader(BaseDownloader):"""Downloader for Semantic Scholar papers with open access PDF support."""- def __init__(self, timeout: int = 30, api_key: Optional[str] = None):+ def __init__(+ self, timeout: int = 30, api_key: Optional[str] = None, **kwargs+ ):"""Initialize Semantic Scholar downloader.@@ -27,7 +29,7 @@ class SemanticScholarDownloader(BaseDownloader):timeout: Request timeout in secondsapi_key: Optional Semantic Scholar API key for higher rate limits"""- super().__init__(timeout)+ super().__init__(timeout, **kwargs)self.api_key = api_keyself.base_api_url = "https://api.semanticscholar.org/graph/v1"diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex b9a86b0fd2..fb9568f9fd 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -8,7 +8,10 @@ Handles downloading PDFs from various academic sources with:- File organization and storage"""+from concurrent.futures import ThreadPoolExecutorfrom contextlib import nullcontext+import atexit+import threadingimport hashlibimport osimport re@@ -17,7 +20,16 @@ import uuidfrom datetime import datetime, UTCfrom pathlib import Pathfrom collections.abc import Set as AbstractSet-from typing import Any, Dict, NamedTuple, Optional, Tuple, assert_never+from typing import (+ Any,+ Dict,+ List,+ NamedTuple,+ Optional,+ Tuple,+ Union,+ assert_never,+)from urllib.parse import urlparseimport requests@@ -32,6 +44,7 @@ from ...utilities.arxiv import extract_arxiv_id, is_arxiv_paper_urlfrom ...constants import DEFAULT_SEARCH_TOOLfrom ...utilities.url_utils import canonical_url_keyfrom ...constants import FILE_PATH_SENTINELS, FILE_PATH_TEXT_ONLY+from ...utilities.type_utils import to_bool, unwrap_settingfrom ...database.models.download_tracker import (DownloadAttempt,DownloadTracker,@@ -46,6 +59,7 @@ from ...database.models.download_tracker import (# filter, not a security control.from ...security import (failure_reason_for_log,+ redact_secrets,safe_get,sanitize_error_for_client,)@@ -63,6 +77,7 @@ from ...database.models.library import (DownloadQueue as LibraryDownloadQueue,RAGIndex,RagDocumentStatus,+ SourceType,)from .pdf_storage_manager import (DEFAULT_MAX_PDF_SIZE_MB,@@ -241,6 +256,599 @@ def _client_safe_download_message(exc: BaseException) -> str:return client_safe_download_message(exc)+_PDF_PERSIST_EXECUTOR: Optional[ThreadPoolExecutor] = None+_EXECUTOR_LOCK = threading.Lock()+# Bound the background persistence queue: full PDF payloads park in RAM+# until two workers drain, so cap pending work and bytes. When full the+# fetch path skips background persistence and the completion sweep handles+# it synchronously — never silently retaining unbounded PDFs.+_PDF_PERSIST_SEMAPHORE = threading.Semaphore(4)+_PDF_PERSIST_BYTES = 0+_PDF_PERSIST_BYTES_LOCK = threading.Lock()+_PDF_PERSIST_MAX_PENDING_BYTES = 20 * 1024 * 1024+++def _is_pdf_bytes(payload: Optional[bytes]) -> bool:+ """Return True when ``payload`` looks like a PDF.++ Direct ``%PDF`` magic prefix (allowing leading whitespace, NULs, or UTF-8 BOM+ within the first 1024 bytes) is accepted. The PDF spec allows leading bytes+ within the first 1024 bytes for streams with wrappers or leading headers.+ Structural text documents (HTML/XML/JSON) that happen to mention ``%PDF``+ are excluded.+ """+ if not payload or len(payload) < 4:+ return False+ if payload[:4] == b"%PDF":+ return True+ try:+ head = payload[:1024]+ idx = head.find(b"%PDF")+ if idx == -1:+ return False+ # Fast path: HTML, XML, or JSON text payloads are never PDFs+ head_stripped = head.lstrip(b"\xef\xbb\xbf \t\r\n\x00")+ if head_stripped.startswith(+ (+ b"<!DOCTYPE",+ b"<!doctype",+ b"<html",+ b"<HTML",+ b"<?xml",+ b'{"',+ b"[{",+ b"<head",+ b"<body",+ )+ ):+ return False+ return True+ except Exception: # allow: silent-exception+ return False+++def _get_pdf_persistence_executor() -> ThreadPoolExecutor:+ global _PDF_PERSIST_EXECUTOR+ if _PDF_PERSIST_EXECUTOR is None:+ with _EXECUTOR_LOCK:+ if _PDF_PERSIST_EXECUTOR is None:+ _PDF_PERSIST_EXECUTOR = ThreadPoolExecutor(+ max_workers=2,+ thread_name_prefix="pdf_persistence_worker",+ )+ return _PDF_PERSIST_EXECUTOR+++def _shutdown_pdf_persistence_executor() -> None:+ global _PDF_PERSIST_EXECUTOR+ executor = _PDF_PERSIST_EXECUTOR+ _PDF_PERSIST_EXECUTOR = None+ if executor is not None:+ try:+ executor.shutdown(wait=False, cancel_futures=True)+ except Exception: # allow: silent-exception+ pass+++atexit.register(_shutdown_pdf_persistence_executor)+++def _resolve_persist_identity(+ username: Optional[str] = None,+ password: Optional[str] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+) -> tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]:+ """Resolve on-the-spot persistence identity via the central helper."""+ try:+ from ...utilities.thread_context import resolve_fetch_identity++ return resolve_fetch_identity(+ egress_context=None,+ settings_snapshot=settings_snapshot,+ username=username,+ password=password,+ )+ except Exception:+ return username, password, settings_snapshot+++def _is_auto_persist_enabled(+ settings_snapshot: Optional[Dict[str, Any]] = None,+ username: Optional[str] = None,+) -> bool:+ """Return whether research source auto-persistence is enabled.++ Default-off. Strictly requires boolean True. String values (e.g.+ ``"false"``, ``"off"``), numbers, and any other non-bool+ types are treated as disabled/unset so a default-off gate never fails open.+ Settings snapshots with wrapped envelopes (``{"value": True}``) are+ unwrapped before evaluating the boolean gate.+ """+ if isinstance(settings_snapshot, dict) and (+ "research_library.auto_persist_research_sources" in settings_snapshot+ ):+ val = unwrap_setting(+ settings_snapshot.get(+ "research_library.auto_persist_research_sources"+ )+ )+ return val is True++ if username:+ try:+ settings = get_settings_manager(username=username)+ val = unwrap_setting(+ settings.get_setting(+ "research_library.auto_persist_research_sources", False+ )+ )+ return val is True+ except Exception: # allow: silent-exception+ pass+ return False+++def _resolve_pdf_storage_mode(+ settings_snapshot: Optional[Dict[str, Any]],+ username: Optional[str] = None,+) -> str:+ """Resolve ``pdf_storage_mode`` preferring an explicit snapshot key.++ A snapshot that lacks the key (e.g. ``{"_username": ...}`` built for+ snapshot-less runs) must fall back to live settings instead of+ defaulting to ``"database"`` and writing blobs against a live+ ``"none"`` preference.+ Also honors ``document_scheduler.download_pdfs``: when explicitly+ disabled (default False), PDF bytes are not stored and the mode is+ treated as ``"none"`` (text only).+ """+ scheduler_allows_pdfs = None+ if isinstance(settings_snapshot, dict) and (+ "document_scheduler.download_pdfs" in settings_snapshot+ ):+ raw_sched = unwrap_setting(+ settings_snapshot.get("document_scheduler.download_pdfs")+ )+ scheduler_allows_pdfs = (+ to_bool(raw_sched) if raw_sched is not None else False+ )+ elif username:+ try:+ settings = get_settings_manager(username=username)+ raw_sched = unwrap_setting(+ settings.get_setting("document_scheduler.download_pdfs", False)+ )+ scheduler_allows_pdfs = (+ to_bool(raw_sched) if raw_sched is not None else False+ )+ except Exception: # allow: silent-exception+ pass++ if scheduler_allows_pdfs is False:+ return "none"++ if isinstance(settings_snapshot, dict) and (+ "research_library.pdf_storage_mode" in settings_snapshot+ ):+ return resolve_pdf_storage_mode(+ unwrap_setting(+ settings_snapshot.get("research_library.pdf_storage_mode")+ )+ )+ try:+ settings = get_settings_manager(username=username)+ return resolve_pdf_storage_mode(+ unwrap_setting(+ settings.get_setting(+ "research_library.pdf_storage_mode", "database"+ )+ )+ )+ except Exception:+ if isinstance(settings_snapshot, dict):+ return resolve_pdf_storage_mode(+ unwrap_setting(+ settings_snapshot.get(+ "research_library.pdf_storage_mode", "database"+ )+ )+ )+ return resolve_pdf_storage_mode("database")+++def _save_pdf_document_record(+ session: Session,+ pdf_storage_manager: Any,+ pdf_content: bytes,+ file_hash: str,+ url: str,+ text: Optional[str] = None,+ title: Optional[str] = None,+ username: Optional[str] = None,+ password: Optional[str] = None,+ collection_id: Optional[str] = None,+ resource_id: Optional[int] = None,+ research_id: Optional[str] = None,+ extra_urls: Optional[List[str]] = None,+ pdf_storage_mode: str = "database",+ require_text: bool = False,+) -> Tuple[Optional[Document], Optional[str]]:+ """Save or update Document, PDF storage, trackers, and collection membership.++ Unified helper shared between DownloadService._download_pdf and+ persist_downloaded_pdf_on_the_spot to prevent logic drift.++ Versioning: content hash wins. Identical bytes reuse the existing+ document; new bytes at a known URL mint a new document (matching main)+ so Document and DownloadTracker hashes never diverge.+ When ``require_text`` is True (fetch-time on-the-spot), garbage+ ``%PDF``-magic payloads without extractable text are rejected+ (return ``(None, None)``) instead of persisting empty COMPLETED rows.+ Library downloads pass False to preserve placeholder/retry behavior.+ """+ # Extraction is fetch-time only: library downloads (require_text=False)+ # leave text production to their own canonical step, as on main.+ if (+ require_text+ and (not text or not text.strip())+ and _is_pdf_bytes(pdf_content)+ ):+ from ..downloaders.base import BaseDownloader++ try:+ extracted = BaseDownloader.extract_text_from_pdf(pdf_content)+ if extracted and extracted.strip():+ text = extracted+ except Exception: # allow: silent-exception+ pass++ if not text or not text.strip():+ if require_text:+ logger.debug(+ f"pdf_persist skipped no text for {redact_url_for_log(url)}"+ )+ return None, None+ # Keep None (not "") so the RAG sweep's IS NOT NULL check skips+ # documents that have no text yet.+ text = None++ # Resolve the default collection early so callers that fail later on+ # mocked storage still exercise the default-library path (matches main's+ # order where collection defaulting precedes the blob write).+ if not collection_id:+ try:+ collection_id = get_default_library_id(username, password)+ except Exception: # allow: silent-exception+ pass++ is_pdf_storage_enabled = pdf_storage_mode in ("database", "filesystem")+ char_count = len(text) if text else None+ w_count = len(text.split()) if text else None++ # Hash-first reuse: identical bytes across mirrors share one document.+ existing_by_hash = (+ session.query(Document).filter_by(document_hash=file_hash).first()+ )+ if existing_by_hash is not None:+ target_doc = existing_by_hash+ if text and not target_doc.text_content:+ target_doc.text_content = text+ target_doc.character_count = char_count+ target_doc.word_count = w_count+ if title and target_doc.title in (None, "", "Untitled"):+ target_doc.title = title+ if target_doc.status != DocumentStatus.COMPLETED:+ target_doc.status = DocumentStatus.COMPLETED+ target_doc.error_message = None+ if resource_id is not None and not target_doc.resource_id:+ target_doc.resource_id = resource_id+ if research_id is not None and not target_doc.research_id:+ target_doc.research_id = research_id++ file_path_result: Optional[str] = target_doc.file_path+ has_retrievable_pdf = False+ try:+ if target_doc.file_type == "pdf":+ from sqlalchemy import func+ from ...database.models.library import DocumentBlob++ blob_len = (+ session.query(func.length(DocumentBlob.pdf_binary))+ .filter_by(document_id=target_doc.id)+ .scalar()+ )+ if blob_len is not None and blob_len > 0:+ has_retrievable_pdf = True+ elif target_doc.file_path:+ safe_path = None+ if hasattr(pdf_storage_manager, "_get_safe_file_path"):+ safe_path = pdf_storage_manager._get_safe_file_path(+ target_doc.file_path+ )+ elif (+ target_doc.file_path != "database"+ and target_doc.file_path not in FILE_PATH_SENTINELS+ ):+ safe_path = Path(target_doc.file_path)+ if safe_path and safe_path.is_file():+ try:+ if safe_path.stat().st_size > 0:+ has_retrievable_pdf = True+ except OSError:+ pass+ except Exception: # allow: silent-exception+ has_retrievable_pdf = False+ needs_storage = (+ target_doc.storage_mode in (None, "none") or not has_retrievable_pdf+ ) and is_pdf_storage_enabled++ if needs_storage:+ saved_path, _ = pdf_storage_manager.save_pdf(+ pdf_content=pdf_content,+ document=target_doc,+ session=session,+ filename=f"{resource_id}.pdf"+ if resource_id is not None+ else f"{target_doc.id}.pdf",+ url=url,+ resource_id=resource_id,+ )+ if saved_path:+ file_path_result = saved_path+ target_doc.file_type = "pdf"+ target_doc.mime_type = "application/pdf"+ else:+ file_path_result = None+ target_doc.file_type = "pdf"+ target_doc.mime_type = "application/pdf"+ target_doc.storage_mode = "none"+ if require_text:+ target_doc.file_path = FILE_PATH_TEXT_ONLY+ else:+ target_doc.file_path = None+ elif not is_pdf_storage_enabled:+ # None-mode PDF downloads keep the pdf label (awaiting refill+ # shape) as main did; do not flip to text. A document that+ # already stores its PDF (blob or file) keeps its storage+ # metadata: this fetch declined to store new bytes, it did+ # not remove the stored ones, and relabelling would make+ # document_awaits_pdf report a present PDF as missing.+ target_doc.file_type = "pdf"+ target_doc.mime_type = "application/pdf"+ if not has_retrievable_pdf:+ target_doc.storage_mode = "none"+ if require_text:+ target_doc.file_path = FILE_PATH_TEXT_ONLY+ elif not target_doc.file_path or target_doc.file_path in (+ "database",+ FILE_PATH_TEXT_ONLY,+ ):+ target_doc.file_path = None+ file_path_result = None+ else:+ try:+ source_type_id = get_source_type_id(+ username, "research_download", password+ )+ except Exception:+ source_type = (+ session.query(SourceType)+ .filter_by(name="research_download")+ .first()+ )+ if source_type:+ source_type_id = source_type.id+ else:+ raise++ doc_id = str(uuid.uuid4())+ target_doc = Document(+ id=doc_id,+ source_type_id=source_type_id,+ resource_id=resource_id,+ research_id=research_id,+ document_hash=file_hash,+ original_url=url,+ # Fetch-time rows keep the awaiting-refill sentinel in+ # none mode; library downloads match main's None shape.+ file_path=FILE_PATH_TEXT_ONLY+ if (require_text and not is_pdf_storage_enabled)+ else None,+ file_size=len(pdf_content),+ file_type="pdf",+ mime_type="application/pdf",+ title=title or "Untitled",+ status=DocumentStatus.COMPLETED,+ text_content=text,+ character_count=char_count,+ word_count=w_count,+ processed_at=datetime.now(UTC),+ created_at=datetime.now(UTC),+ storage_mode=pdf_storage_mode,+ )+ session.add(target_doc)+ winner = None+ if require_text:+ try:+ with session.begin_nested():+ session.flush()+ except Exception as exc:+ # Concurrent writers racing SELECT-then-INSERT on the unique+ # hash: reuse the winner instead of dying. Nested savepoint+ # scopes the rollback so outer pending work survives.+ from sqlalchemy.exc import IntegrityError++ if isinstance(exc, IntegrityError):+ # pysqlite invalidates the whole transaction on a+ # failed statement (SAVEPOINT cannot scope recovery),+ # so a full rollback is mandatory before any further+ # use of this session. Tracker and collection writes+ # below are re-executed afterwards, so nothing is+ # lost except already-staged caller state that the+ # caller re-applies from the returned winner.+ try:+ session.rollback()+ except Exception: # allow: silent-exception+ pass+ winner = (+ session.query(Document)+ .filter_by(document_hash=file_hash)+ .first()+ )+ if winner is not None:+ target_doc = winner+ if text and not target_doc.text_content:+ target_doc.text_content = text+ target_doc.character_count = char_count+ target_doc.word_count = w_count+ else:+ raise+ else:+ raise+ else:+ session.flush()++ file_path_result = None+ if winner is None:+ saved_path, _ = pdf_storage_manager.save_pdf(+ pdf_content=pdf_content,+ document=target_doc,+ session=session,+ filename=f"{resource_id}.pdf"+ if resource_id is not None+ else f"{doc_id}.pdf",+ url=url,+ resource_id=resource_id,+ )+ if saved_path:+ file_path_result = saved_path+ target_doc.file_type = "pdf"+ target_doc.mime_type = "application/pdf"+ else:+ file_path_result = None+ target_doc.file_type = "pdf"+ target_doc.mime_type = "application/pdf"+ target_doc.storage_mode = "none"+ if require_text:+ target_doc.file_path = FILE_PATH_TEXT_ONLY+ else:+ target_doc.file_path = None+ else:+ file_path_result = target_doc.file_path++ if resource_id is None:+ candidate_urls = [url]+ if extra_urls:+ for eu in extra_urls:+ if eu and eu not in candidate_urls:+ candidate_urls.append(eu)+ res_match = (+ session.query(ResearchResource)+ .filter(ResearchResource.url.in_(candidate_urls))+ .first()+ )+ if res_match is not None:+ resource_id = res_match.id+ if not research_id:+ research_id = res_match.research_id+ if resource_id is not None and not target_doc.resource_id:+ target_doc.resource_id = resource_id+ if research_id is not None and not target_doc.research_id:+ target_doc.research_id = research_id+ all_urls = [url]+ if extra_urls:+ for eu in extra_urls:+ if eu and eu not in all_urls:+ all_urls.append(eu)++ for u in all_urls:+ tracker = find_tracker_by_url(session, u)+ recorded_size = len(pdf_content)+ recorded_path = (+ file_path_result+ if (is_pdf_storage_enabled and file_path_result)+ else None+ )+ recorded_name = (+ Path(file_path_result).name+ if (+ is_pdf_storage_enabled+ and file_path_result+ and file_path_result != "database"+ )+ else None+ )+ if tracker:+ tracker.file_hash = file_hash+ tracker.file_size = recorded_size+ tracker.file_path = recorded_path+ tracker.file_name = recorded_name+ tracker.is_downloaded = True+ if not tracker.downloaded_at:+ tracker.downloaded_at = datetime.now(UTC)+ if not tracker.first_resource_id and resource_id is not None:+ tracker.first_resource_id = resource_id+ else:+ # Tracker rows require a resource (first_resource_id NOT NULL),+ # so fetch-time persistence without a resource cannot create+ # them. Redirect final URLs are still passed via extra_urls and+ # recorded here whenever a resource is known; cross-URL redirect+ # reuse beyond that still re-downloads once (storage deduped by+ # hash) — documented limitation, same-URL never double-fetches.+ if resource_id is None:+ continue+ try:+ with session.begin_nested():+ try:+ from ...utilities.download_url import get_url_hash+ except Exception:+ get_url_hash = None # type: ignore[assignment]+ try:+ u_hash = (+ get_url_hash(canonical_url_key(u))+ if get_url_hash+ else hashlib.sha256(u.strip().encode()).hexdigest()+ )+ except Exception:+ u_hash = hashlib.sha256(u.strip().encode()).hexdigest()+ tracker = DownloadTracker(+ url=u,+ url_hash=u_hash,+ first_resource_id=resource_id,+ file_hash=file_hash,+ file_size=recorded_size,+ file_path=recorded_path,+ file_name=recorded_name,+ is_downloaded=True,+ downloaded_at=datetime.now(UTC),+ )+ session.add(tracker)+ except Exception as exc:+ from sqlalchemy.exc import IntegrityError++ if not isinstance(exc, IntegrityError):+ raise+ # begin_nested already rolled back to the savepoint; do not+ # full-rollback the outer transaction (would wipe the doc).++ try:+ target_collection = collection_id+ if not target_collection:+ default_coll = (+ session.query(Collection).filter_by(is_default=True).first()+ )+ if default_coll:+ target_collection = default_coll.id+ else:+ target_collection = get_default_library_id(username, password)+ if target_collection:+ ensure_in_collection(session, target_doc.id, target_collection)+ except Exception:+ logger.debug("pdf_persist collection link failed", exc_info=True)++ return target_doc, file_path_result++class DownloadService:"""Service for downloading and managing research PDFs."""@@ -364,20 +972,62 @@ class DownloadService:# which yields no identifier -- still reaches DirectPDFDownloader# instead of being claimed and skipped.self.downloaders = [- ArxivDownloader(timeout=30),- DirectPDFDownloader(timeout=30),+ ArxivDownloader(+ timeout=30,+ username=username,+ password=password,+ settings_snapshot=self._settings_snapshot,+ enable_fetch_persistence=False,+ ),+ DirectPDFDownloader(+ timeout=30,+ username=username,+ password=password,+ settings_snapshot=self._settings_snapshot,+ enable_fetch_persistence=False,+ ),SemanticScholarDownloader(timeout=30,api_key=semantic_scholar_api_keyif semantic_scholar_api_keyelse None,+ username=username,+ password=password,+ settings_snapshot=self._settings_snapshot,+ enable_fetch_persistence=False,),# OpenAlex work lookup; the key is optional (it raises the# daily budget 10x) and None means the keyless free tier.- OpenAlexDownloader(timeout=30, api_key=openalex_api_key),- PubMedDownloader(timeout=30, rate_limit_delay=1.0),- BioRxivDownloader(timeout=30),- GenericDownloader(timeout=30), # Generic should be last (fallback)+ OpenAlexDownloader(+ timeout=30,+ api_key=openalex_api_key,+ username=username,+ password=password,+ settings_snapshot=self._settings_snapshot,+ enable_fetch_persistence=False,+ ),+ PubMedDownloader(+ timeout=30,+ rate_limit_delay=1.0,+ username=username,+ password=password,+ settings_snapshot=self._settings_snapshot,+ enable_fetch_persistence=False,+ ),+ BioRxivDownloader(+ timeout=30,+ username=username,+ password=password,+ settings_snapshot=self._settings_snapshot,+ enable_fetch_persistence=False,+ ),+ GenericDownloader(+ timeout=30,+ username=username,+ password=password,+ settings_snapshot=self._settings_snapshot,+ enable_fetch_persistence=False,+ ), # Generic should be last (fallback)]# Initialize retry manager for smart failure tracking@@ -1102,13 +1752,198 @@ class DownloadService:return Truereturn False- def download_resource(self, resource_id: int) -> Tuple[bool, Optional[str]]:+ def persist_research_sources(+ self,+ research_id: str,+ collection_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ """+ Persist all sources from a research session into the Library.++ Eliminates the PDF double-fetch: PDFs already persisted on-the-spot+ during the run are linked without network I/O. Plain web-page text+ has no fetch-time persistence and is still fetched here by design.+ For each research resource:+ - If PDF storage is enabled (pdf_storage_mode is 'database' or 'filesystem'),+ the scheduler allows PDFs (document_scheduler.download_pdfs), and the+ URL is downloadable, download the PDF (and extract its text).+ If PDF download fails, fall back to extracting and saving text.+ - Otherwise extract and persist text content directly.+ - Resources that are already completed and do not await a PDF are skipped.+ - Deduplication: URL-based via DownloadTracker (including redirect+ final URLs), content-hash-based via Document.document_hash.++ Args:+ research_id: The UUID of the research session.+ collection_id: Optional collection ID to add the documents to (defaults to Library).++ Returns:+ Dict summarizing the persistence run:+ {'total': int, 'persisted': int, 'failed': int, 'skipped': int}+ """+ start_time = time.perf_counter()+ persisted_count = 0+ failed_count = 0++ with get_user_db_session(self.username, self.password) as session:+ resources = (+ session.query(ResearchResource)+ .filter_by(research_id=research_id)+ .order_by(ResearchResource.id.asc())+ .all()+ )+ if not resources:+ logger.info(+ f"No research resources to persist for research {research_id}"+ )+ return {"total": 0, "persisted": 0, "failed": 0, "skipped": 0}++ pdf_storage_mode = resolve_pdf_storage_mode(+ self.settings.get_setting(+ "research_library.pdf_storage_mode", "database"+ )+ )+ try:+ scheduler_allows_pdfs = bool(+ self.settings.get_setting(+ "document_scheduler.download_pdfs", False+ )+ )+ except Exception:+ scheduler_allows_pdfs = False+ enable_pdf_storage = (+ pdf_storage_mode != "none" and scheduler_allows_pdfs+ )++ items_to_process = []+ skipped_count = 0+ for r in resources:+ doc = get_document_for_resource(session, r)+ if doc is None and r.url:+ tracker = find_tracker_by_url(session, r.url)+ if (+ tracker+ and getattr(tracker, "is_downloaded", False) is True+ and getattr(tracker, "file_hash", None)+ ):+ existing_by_hash = (+ session.query(Document)+ .filter_by(+ document_hash=tracker.file_hash,+ status=DocumentStatus.COMPLETED,+ )+ .first()+ )+ if existing_by_hash and not document_awaits_pdf(+ existing_by_hash+ ):+ r.document_id = existing_by_hash.id+ doc = existing_by_hash+ session.commit()+ persisted_count += 1+ continue++ existing_by_url = (+ session.query(Document)+ .filter_by(+ original_url=r.url,+ status=DocumentStatus.COMPLETED,+ )+ .order_by(Document.created_at.desc())+ .first()+ )+ if existing_by_url and not document_awaits_pdf(+ existing_by_url+ ):+ r.document_id = existing_by_url.id+ doc = existing_by_url+ session.commit()+ persisted_count += 1+ continue+ is_dl = self._is_downloadable(r) or (+ doc is not None and getattr(doc, "file_type", None) == "pdf"+ )+ if doc is not None and doc.status == DocumentStatus.COMPLETED:+ if (+ enable_pdf_storage+ and is_dl+ and document_awaits_pdf(doc)+ ):+ items_to_process.append((r.id, r.url, is_dl))+ else:+ skipped_count += 1+ else:+ items_to_process.append((r.id, r.url, is_dl))++ for resource_id, url, is_dl in items_to_process:+ try:+ if enable_pdf_storage and is_dl:+ success, error = self.download_resource(+ resource_id, collection_id=collection_id+ )+ if success:+ persisted_count += 1+ logger.info(+ f"Auto-persisted PDF for resource {resource_id} ({redact_url_for_log(url)})"+ )+ else:+ logger.info(+ f"PDF download failed for resource {resource_id} ({failure_reason_for_log(error)}), attempting text fallback"+ )+ text_success, text_error = self.download_as_text(+ resource_id+ )+ if text_success:+ persisted_count += 1+ logger.info(+ f"Auto-persisted fallback text for resource {resource_id}"+ )+ else:+ failed_count += 1+ logger.warning(+ f"Failed to persist resource {resource_id}: {failure_reason_for_log(text_error)}"+ )+ else:+ success, error = self.download_as_text(resource_id)+ if success:+ persisted_count += 1+ logger.info(+ f"Auto-persisted text for resource {resource_id} ({redact_url_for_log(url)})"+ )+ else:+ failed_count += 1+ logger.warning(+ f"Failed to persist text for resource {resource_id}: {failure_reason_for_log(error)}"+ )+ except Exception as exc:+ failed_count += 1+ log_exception_type(+ f"Error persisting resource {resource_id}", exc+ )++ elapsed = time.perf_counter() - start_time+ summary = {+ "total": len(resources),+ "persisted": persisted_count,+ "failed": failed_count,+ "skipped": skipped_count,+ }+ logger.info(+ f"Auto-persisted research sources for {research_id} in {elapsed:.2f}s: "+ f"{persisted_count} persisted, {failed_count} failed, {skipped_count} skipped (total {len(resources)})"+ )+ return summary++ def download_resource(+ self, resource_id: int, collection_id: Optional[str] = None+ ) -> Tuple[bool, Optional[str]]:"""Download a specific resource.Returns:Tuple of (success: bool, skip_reason: str or None)"""+ linked_doc_id: Optional[str] = Nonewith get_user_db_session(self.username, self.password) as session:resource = session.get(ResearchResource, resource_id)if not resource:@@ -1142,11 +1977,12 @@ class DownloadService:.filter_by(resource_id=resource_id).first())- collection_id = (- queue_entry.collection_id- if queue_entry and queue_entry.collection_id- else None- )+ if not collection_id:+ collection_id = (+ queue_entry.collection_id+ if queue_entry and queue_entry.collection_id+ else None+ )# Create download tracker entry. B2 compat (#6758): reuse a# pre-upgrade legacy-hash row when present instead of inserting@@ -1154,6 +1990,88 @@ class DownloadService:url_hash = self._get_url_hash(resource.url)tracker = find_tracker_by_url(session, resource.url)+ # Check if another resource with the same URL is already+ # downloaded (tracker dedup). Auto-persist only: with the+ # setting off, library downloads keep main's flow (including+ # its collection, tracker and retry bookkeeping) exactly.+ if (+ _is_auto_persist_enabled(+ getattr(self, "_settings_snapshot", None),+ getattr(self, "username", None),+ )+ and tracker+ and getattr(tracker, "is_downloaded", False) is True+ and isinstance(getattr(tracker, "first_resource_id", None), int)+ and tracker.first_resource_id != resource.id+ ):+ first_resource = session.get(+ ResearchResource, tracker.first_resource_id+ )+ first_doc = (+ get_document_for_resource(session, first_resource)+ if first_resource+ else None+ )+ if not first_doc and tracker.file_hash:+ first_doc = (+ session.query(Document)+ .filter_by(document_hash=tracker.file_hash)+ .first()+ )+ if not first_doc:+ first_doc = (+ session.query(Document)+ .filter_by(original_url=resource.url)+ .first()+ )+ if (+ first_doc+ and first_doc.status == DocumentStatus.COMPLETED+ and not document_awaits_pdf(first_doc)+ ):+ # Link without skipping bookkeeping: the caller may+ # have queued this resource into a specific collection,+ # and the post-download block below still owns queue,+ # retry and auto-index handling for that collection.+ resource.document_id = first_doc.id+ try:+ target_collection = collection_id+ if not target_collection:+ from ...database.library_init import (+ get_default_library_id as _get_default_lib,+ )++ target_collection = _get_default_lib(+ self.username, self.password+ )+ if target_collection:+ from ...database.models.library import Collection++ coll_exists = (+ session.query(Collection.id)+ .filter_by(id=target_collection)+ .first()+ is not None+ )+ if coll_exists:+ with session.begin_nested():+ ensure_in_collection(+ session, first_doc.id, target_collection+ )+ session.flush()+ else:+ logger.warning(+ f"Collection {target_collection} not found, skipping dedup link"+ )+ except Exception as exc:+ log_exception_type(+ "Failed to link deduped document to collection",+ exc,+ )+ session.commit()+ linked_doc_id = first_doc.id+ logger.info("Resource already downloaded via tracker link")+if not tracker:# Wrap the new-tracker INSERT in a SAVEPOINT so it is# structurally separated from the shared thread-local@@ -1217,10 +2135,14 @@ class DownloadService:# transaction and does not promote any caller-staged row.session.commit()- # Attempt download outside database session (#6560)- success, skip_reason, status_code = self._download_pdf(- resource, tracker, None, collection_id- )+ # Attempt download outside database session (#6560), unless the+ # tracker dedup above already linked a completed document.+ if linked_doc_id is not None:+ success, skip_reason, status_code = True, None, None+ else:+ success, skip_reason, status_code = self._download_pdf(+ resource, tracker, None, collection_id+ )# Open short transaction for post-download queue and retry updateswith get_user_db_session(self.username, self.password) as session:@@ -1413,6 +2335,9 @@ class DownloadService:f"No downloader found for {redact_url_for_log(url)}")skip_reason = "No compatible downloader available"+ # When pdf_content came from the local cache, selected_downloader+ # stays None (as on main) so text production stays local and+ # never sends arXiv duplicates through a network path.# Produce the canonical text BEFORE the persistence block.# download_text_with_source may issue a network (HTML) request,@@ -1503,14 +2428,25 @@ class DownloadService:staging_resource_title = target_resource.title# Helper for attempt number calculation- if hasattr(target_tracker, "download_attempts") and hasattr(- target_tracker.download_attempts, "count"+ attempts = getattr(target_tracker, "download_attempts", None)+ if (+ attempts is not None+ and not isinstance(attempts, (list, tuple))+ and hasattr(attempts, "count")):- attempt_num = target_tracker.download_attempts.count() + 1- elif hasattr(tracker, "download_attempts") and hasattr(- tracker.download_attempts, "count"+ attempt_num = attempts.count() + 1+ elif isinstance(attempts, (list, tuple)):+ attempt_num = len(attempts) + 1+ elif (+ hasattr(tracker, "download_attempts")+ and not isinstance(tracker.download_attempts, (list, tuple))+ and hasattr(tracker.download_attempts, "count")):attempt_num = tracker.download_attempts.count() + 1+ elif isinstance(+ getattr(tracker, "download_attempts", None), (list, tuple)+ ):+ attempt_num = len(tracker.download_attempts) + 1else:attempt_num = 1if not pdf_content:@@ -1956,59 +2892,22 @@ class DownloadService:f"{existing_by_hash.id} (matched on content hash)")else:- # Get source type ID for research downloads- try:- source_type_id = get_source_type_id(- self.username,- "research_download",- self.password,- )- # Use provided collection_id or default to Library- library_collection_id = (- collection_id- or get_default_library_id(- self.username, self.password- )- )- except Exception as exc:- log_exception_type(- "Failed to get source type or library collection",- exc,- )- raise-- # Create new unified document entry- doc_id = str(uuid.uuid4())- pdf_document_id = doc_id- doc = Document(- id=doc_id,- source_type_id=source_type_id,- resource_id=target_resource.id,- research_id=target_resource.research_id,- document_hash=target_tracker.file_hash,- original_url=url,- file_size=len(pdf_content),- file_type="pdf",- mime_type="application/pdf",- title=target_resource.title,- status=DocumentStatus.COMPLETED,- processed_at=datetime.now(UTC),- storage_mode=pdf_storage_mode,- )- sess.add(doc)- sess.flush() # Ensure doc.id is available for blob storage- target_resource.document_id = doc.id- # Save PDF using storage manager (updates storage_mode and file_path)- file_path_result, _ = pdf_storage_manager.save_pdf(- pdf_content=pdf_content,- document=doc,+ doc, file_path_result = _save_pdf_document_record(session=sess,- filename=f"{target_resource.id}.pdf",+ pdf_storage_manager=pdf_storage_manager,+ pdf_content=pdf_content,+ file_hash=target_tracker.file_hash,url=url,+ title=target_resource.title,+ username=self.username,+ password=self.password,+ collection_id=collection_id,resource_id=target_resource.id,+ research_id=target_resource.research_id,+ pdf_storage_mode=pdf_storage_mode,)-- # Update tracker+ pdf_document_id = doc.id+ target_resource.document_id = doc.idtarget_tracker.file_path = (file_path_result if file_path_result else None)@@ -2022,11 +2921,6 @@ class DownloadService:tracker.file_path = target_tracker.file_pathtracker.file_name = target_tracker.file_name- # Link document to default Library collection- ensure_in_collection(- sess, doc_id, library_collection_id- )-if pdf_storage_mode == "database":logger.info(f"Successfully stored PDF in database: {redact_url_for_log(resource.url)}"@@ -2584,6 +3478,74 @@ class DownloadService:.first())+ # URL/tracker reuse is an auto-persist behaviour: with the setting+ # off, main's flow (linked document only, then canonical steps)+ # is preserved exactly.+ auto_persist_on = _is_auto_persist_enabled(+ getattr(self, "_settings_snapshot", None),+ getattr(self, "username", None),+ )+ if auto_persist_on and not existing_doc and resource and resource.url:+ tracker = find_tracker_by_url(session, resource.url)+ if tracker and getattr(tracker, "is_downloaded", False) is True:+ tracked_doc = None+ if tracker.file_hash:+ tracked_doc = (+ session.query(Document)+ .filter_by(+ document_hash=tracker.file_hash,+ status=DocumentStatus.COMPLETED,+ )+ .first()+ )+ if not tracked_doc and (+ isinstance(getattr(tracker, "first_resource_id", None), int)+ and tracker.first_resource_id != resource.id+ ):+ first_resource = session.get(+ ResearchResource, tracker.first_resource_id+ )+ tracked_doc = (+ get_document_for_resource(session, first_resource)+ if first_resource+ else None+ )+ if not tracked_doc:+ tracked_doc = (+ session.query(Document)+ .filter_by(+ original_url=resource.url,+ status=DocumentStatus.COMPLETED,+ )+ .order_by(Document.created_at.desc())+ .first()+ )+ if tracked_doc and _has_reusable_text(tracked_doc):+ resource.document_id = tracked_doc.id+ if not tracker.first_resource_id:+ tracker.first_resource_id = resource.id+ session.commit()+ logger.info(+ f"Reused existing text via tracker for resource_id={resource_id}"+ )+ return True, None++ existing_by_url = (+ session.query(Document)+ .filter_by(+ original_url=resource.url,+ status=DocumentStatus.COMPLETED,+ )+ .order_by(Document.created_at.desc())+ .first()+ )+ if existing_by_url and _has_reusable_text(existing_by_url):+ resource.document_id = existing_by_url.id+ session.commit()+ logger.info(+ f"Reused existing text via on-the-spot document for resource_id={resource_id}"+ )+ return True, Noneif not existing_doc:return None@@ -3075,6 +4037,33 @@ class DownloadService:safe_error = _client_safe_download_message(e)return False, safe_error+ def persist_pdf_on_the_spot(+ self,+ url: str,+ pdf_content: bytes,+ text: Optional[str] = None,+ title: Optional[str] = None,+ extra_urls: Optional[List[str]] = None,+ collection_id: Optional[str] = None,+ resource_id: Optional[int] = None,+ check_setting: bool = True,+ ) -> Optional[str]:+ """Persist a downloaded PDF directly into the Library database and storage."""+ return persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=pdf_content,+ text=text,+ title=title,+ username=self.username,+ password=self.password,+ settings_snapshot=self._settings_snapshot,+ library_root=self.library_root,+ extra_urls=extra_urls,+ collection_id=collection_id,+ resource_id=resource_id,+ check_setting=check_setting,+ )+def _get_downloader(self, url: str):"""Get the appropriate downloader for a URL.@@ -3861,3 +4850,354 @@ class DownloadService:except Exception as exc:log_exception_type("Error recording failed text extraction", exc)+++def _do_persist_downloaded_pdf_on_the_spot(+ url: str,+ pdf_content: bytes,+ text: Optional[str] = None,+ title: Optional[str] = None,+ username: Optional[str] = None,+ password: Optional[str] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ library_root: Optional[Union[str, Path]] = None,+ extra_urls: Optional[List[str]] = None,+ collection_id: Optional[str] = None,+ resource_id: Optional[int] = None,+ check_setting: bool = False,+) -> Optional[str]:+ """Inner synchronous implementation of on-the-spot PDF persistence."""+ if not _is_pdf_bytes(pdf_content):+ return None++ if isinstance(settings_snapshot, dict) and (+ settings_snapshot.get("research_library.auto_persist_research_sources")+ is False+ ):+ return None++ if check_setting and not _is_auto_persist_enabled(+ settings_snapshot, username+ ):+ return None++ username, password, settings_snapshot = _resolve_persist_identity(+ username, password, settings_snapshot+ )++ if not username:+ logger.debug(+ f"pdf_persist skipped no user for {redact_url_for_log(url)}"+ )+ return None++ try:+ import hashlib++ file_hash_val = hashlib.sha256(pdf_content).hexdigest()++ if text is None or not text.strip():+ try:+ from ..downloaders.base import BaseDownloader++ extracted = BaseDownloader.extract_text_from_pdf(pdf_content)+ if extracted and extracted.strip():+ text = extracted+ except Exception: # allow: silent-exception+ pass++ if not text or not text.strip():+ # Garbage magic without extractable text: do not mint an empty+ # COMPLETED row the sweep would trust forever.+ logger.debug(+ "pdf_persist_skipped_no_text url={url}",+ url=redact_url_for_log(url),+ )+ return None++ pdf_storage_mode = _resolve_pdf_storage_mode(+ settings_snapshot, username+ )+ max_pdf_size_mb = DEFAULT_MAX_PDF_SIZE_MB+ custom_library_path = None+ if isinstance(settings_snapshot, dict):+ try:+ max_pdf_size_mb = int(+ unwrap_setting(+ settings_snapshot.get(+ "research_library.max_pdf_size_mb",+ DEFAULT_MAX_PDF_SIZE_MB,+ )+ )+ )+ except Exception: # allow: silent-exception+ pass+ custom_library_path = unwrap_setting(+ settings_snapshot.get("research_library.storage_path")+ )+ else:+ try:+ settings = get_settings_manager(username=username)+ max_pdf_size_mb = int(+ unwrap_setting(+ settings.get_setting(+ "research_library.max_pdf_size_mb",+ DEFAULT_MAX_PDF_SIZE_MB,+ )+ )+ )+ custom_library_path = unwrap_setting(+ settings.get_setting("research_library.storage_path")+ )+ except Exception: # allow: silent-exception+ pass++ if library_root is None:+ if custom_library_path:+ from ..utils import apply_user_subdir++ library_root = apply_user_subdir(+ Path(custom_library_path), username, False+ )+ else:+ from ..utils import get_library_storage_path++ try:+ library_root = get_library_storage_path(username)+ except Exception:+ library_root = Path("library")+ else:+ library_root = Path(library_root)++ with get_user_db_session(username, password) as session:+ pdf_storage_manager = PDFStorageManager(+ library_root=library_root,+ storage_mode=pdf_storage_mode,+ max_pdf_size_mb=max_pdf_size_mb,+ username=username,+ )++ target_doc, _ = _save_pdf_document_record(+ session=session,+ pdf_storage_manager=pdf_storage_manager,+ pdf_content=pdf_content,+ file_hash=file_hash_val,+ url=url,+ text=text,+ title=title,+ username=username,+ password=password,+ collection_id=collection_id,+ resource_id=resource_id,+ extra_urls=extra_urls,+ pdf_storage_mode=pdf_storage_mode,+ require_text=True,+ )+ if target_doc is None:+ try:+ session.rollback()+ except Exception: # allow: silent-exception+ pass+ return None+ session.commit()+ return target_doc.id++ except Exception as exc:+ safe_msg = redact_secrets(str(exc), password)+ logger.warning(+ f"Failed on-the-spot persistence for {redact_url_for_log(url)}: {safe_msg}"+ )+ return None+++def persist_downloaded_pdf_on_the_spot(+ url: str,+ pdf_content: bytes,+ text: Optional[str] = None,+ title: Optional[str] = None,+ username: Optional[str] = None,+ password: Optional[str] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ library_root: Optional[Union[str, Path]] = None,+ extra_urls: Optional[List[str]] = None,+ collection_id: Optional[str] = None,+ resource_id: Optional[int] = None,+ run_in_background: bool = False,+ check_setting: bool = False,+) -> Optional[str]:+ """Persist a downloaded PDF directly into Library DB and storage on the spot.++ Single fetch-time writer for research PDF fetches. Library downloads use+ the synchronous ``DownloadService._download_pdf`` path instead, so each+ PDF is persisted once. When ``run_in_background=True`` the write runs in+ a bounded (4 pending / 20 MB) worker pool; when full it is skipped and+ the completion sweep handles it — payloads are never retained unbounded.+ Only eliminates the PDF double-fetch; plain web-page text is still+ fetched at completion by design.+ """+ if isinstance(settings_snapshot, dict) and (+ unwrap_setting(+ settings_snapshot.get(+ "research_library.auto_persist_research_sources"+ )+ )+ is False+ ):+ return None++ if check_setting and not _is_auto_persist_enabled(+ settings_snapshot, username+ ):+ return None+ if run_in_background:+ payload_len = len(pdf_content) if pdf_content else 0+ acquired = _PDF_PERSIST_SEMAPHORE.acquire(blocking=False)+ if not acquired:+ logger.debug(+ f"pdf_persist skipped backpressure for {redact_url_for_log(url)}"+ )+ return None+ bytes_reserved = False+ submitted = False+ try:+ with _PDF_PERSIST_BYTES_LOCK:+ global _PDF_PERSIST_BYTES+ if (+ _PDF_PERSIST_BYTES + payload_len+ > _PDF_PERSIST_MAX_PENDING_BYTES+ ):+ logger.debug(+ f"pdf_persist skipped byte cap for {redact_url_for_log(url)}"+ )+ return None+ _PDF_PERSIST_BYTES += payload_len+ bytes_reserved = True++ def _bounded_persist() -> None:+ global _PDF_PERSIST_BYTES+ try:+ _do_persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=pdf_content,+ text=text,+ title=title,+ username=username,+ password=password,+ settings_snapshot=settings_snapshot,+ library_root=library_root,+ extra_urls=extra_urls,+ collection_id=collection_id,+ resource_id=resource_id,+ check_setting=check_setting,+ )+ finally:+ with _PDF_PERSIST_BYTES_LOCK:+ _PDF_PERSIST_BYTES = max(+ 0, _PDF_PERSIST_BYTES - payload_len+ )+ _PDF_PERSIST_SEMAPHORE.release()+ try:+ from ...database.thread_local_session import (+ cleanup_current_thread,+ )++ cleanup_current_thread()+ except Exception: # allow: silent-exception+ pass++ executor = _get_pdf_persistence_executor()+ executor.submit(_bounded_persist)+ submitted = True+ # Slot and bytes released in _bounded_persist finally.+ return None+ except Exception as exc:+ safe_msg = redact_secrets(str(exc), password)+ logger.warning(+ f"Failed to submit background PDF persistence for {redact_url_for_log(url)}: {safe_msg}"+ )+ return None+ finally:+ if not submitted:+ if bytes_reserved:+ with _PDF_PERSIST_BYTES_LOCK:+ _PDF_PERSIST_BYTES = max(+ 0, _PDF_PERSIST_BYTES - payload_len+ )+ _PDF_PERSIST_SEMAPHORE.release()++ return _do_persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=pdf_content,+ text=text,+ title=title,+ username=username,+ password=password,+ settings_snapshot=settings_snapshot,+ library_root=library_root,+ extra_urls=extra_urls,+ collection_id=collection_id,+ resource_id=resource_id,+ check_setting=check_setting,+ )+++def auto_persist_research_sources(+ username: str,+ research_id: str,+ db_password: Optional[str] = None,+ collection_id: Optional[str] = None,+) -> Dict[str, Any]:+ """Auto-persist research sources (PDFs and text) to the Library.++ Default-off behind ``research_library.auto_persist_research_sources``.+ PDF downloads additionally honor ``document_scheduler.download_pdfs``+ so users who disabled PDF downloads are not overridden.+ Safe to call from any context — exceptions are caught and logged.+ """+ try:+ settings = get_settings_manager(username=username)+ try:+ auto_enabled = unwrap_setting(+ settings.get_setting(+ "research_library.auto_persist_research_sources", False+ )+ )+ except Exception:+ auto_enabled = False+ if auto_enabled is not True:+ logger.debug(+ f"auto_persist skipped disabled for research {research_id}"+ )+ return {+ "total": 0,+ "persisted": 0,+ "failed": 0,+ "skipped": 0,+ "skipped_reason": "disabled",+ }+ settings_snapshot = None+ try:+ settings_snapshot = settings.get_settings_snapshot()+ except Exception: # allow: silent-exception+ pass++ with DownloadService(+ username,+ password=db_password,+ settings_snapshot=settings_snapshot,+ ) as download_service:+ return download_service.persist_research_sources(+ research_id, collection_id=collection_id+ )+ except Exception as exc:+ safe_msg = redact_secrets(str(exc), db_password)+ logger.warning(+ f"Failed to auto-persist sources for research {research_id} (user {username}): {safe_msg}"+ )+ return {+ "total": 0,+ "persisted": 0,+ "failed": 0,+ "skipped": 0,+ "error": safe_msg,+ }diff --git a/src/local_deep_research/research_library/services/pdf_storage_manager.py b/src/local_deep_research/research_library/services/pdf_storage_manager.pyindex aadb75d5b2..80e6b79e74 100644--- a/src/local_deep_research/research_library/services/pdf_storage_manager.py+++ b/src/local_deep_research/research_library/services/pdf_storage_manager.py@@ -21,6 +21,7 @@ from ...constants import FILE_PATH_SENTINELSfrom ...utilities.arxiv import extract_arxiv_idfrom ...database.models.library import Document, DocumentBlobfrom ...security.path_validator import PathValidator, resolve_allow_missing+from ...utilities.type_utils import unwrap_setting# Default storage cap for individual PDFs (megabytes). Mirrors the@@ -71,6 +72,7 @@ def resolve_pdf_storage_mode(mode):previously-written plaintext files stay readable after coercion."""global _COERCION_WARNED+ mode = unwrap_setting(mode)if isinstance(mode, str) and mode.strip().lower() == "filesystem":if not filesystem_pdf_storage_allowed():if not _COERCION_WARNED:diff --git a/src/local_deep_research/utilities/thread_context.py b/src/local_deep_research/utilities/thread_context.pyindex 9a4267b941..77fb94efb7 100644--- a/src/local_deep_research/utilities/thread_context.py+++ b/src/local_deep_research/utilities/thread_context.py@@ -60,6 +60,48 @@ def get_search_context() -> Dict[str, Any] | None:return context+def resolve_fetch_identity(+ egress_context: Any = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ username: Optional[str] = None,+ password: Optional[str] = None,+) -> tuple[Optional[str], Optional[str], Optional[Dict[str, Any]]]:+ """Centralize fetch-time identity resolution in one helper.++ Precedence: explicit args > egress_context > thread search context >+ settings snapshot ``_username``. Never raises; missing identity yields+ ``None`` so callers can skip persistence gracefully.+ """+ if username is None and egress_context is not None:+ username = getattr(egress_context, "username", None)+ if password is None and egress_context is not None:+ password = getattr(egress_context, "password", None)+ if (not username or not password or not settings_snapshot) and True:+ try:+ ctx = get_search_context()+ if ctx and isinstance(ctx, dict):+ if not username:+ username = ctx.get("username")+ if not password:+ password = ctx.get("user_password")+ if not settings_snapshot:+ snap = ctx.get("settings_snapshot")+ if isinstance(snap, dict):+ settings_snapshot = snap+ except Exception: # allow: silent-exception+ pass+ if not username and isinstance(settings_snapshot, dict):+ try:+ from ..search_system import username_from_snapshot++ snap_user = username_from_snapshot(settings_snapshot)+ if snap_user:+ username = snap_user+ except Exception: # allow: silent-exception+ pass+ return username, password, settings_snapshot++@contextmanagerdef search_context(context: Dict[str, Any]) -> Generator[None, None, None]:"""Context manager that sets and clears search context automatically.diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex 5b821b206d..2aecd612c3 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -3,9 +3,11 @@ Queue processor v2 - uses encrypted user databases instead of service.dbSupports both direct execution and queue modes."""+import atexitimport threadingimport timeimport uuid+from concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclassfrom enum import Enum, autofrom typing import Any, Dict, Optional@@ -51,6 +53,58 @@ from ..services.research_service import (start_research_process,)++_AUTO_PERSIST_EXECUTOR: Optional[ThreadPoolExecutor] = None+_AUTO_PERSIST_LOCK = threading.Lock()+# Admission bound for completion sweeps: 2 workers run at once, and at+# most this many sweeps may be pending in total. Beyond it a sweep is+# skipped with an explicit log instead of queueing unbounded work.+_AUTO_PERSIST_MAX_PENDING = 8+_AUTO_PERSIST_PENDING = threading.Semaphore(_AUTO_PERSIST_MAX_PENDING)+++def _auto_persist_enabled_for(username: str) -> bool:+ """Best-effort opt-in check used before enqueueing a sweep."""+ try:+ from ...research_library.services.download_service import (+ _is_auto_persist_enabled,+ )++ return _is_auto_persist_enabled(None, username)+ except Exception: # allow: silent-exception+ return False+++def _get_auto_persist_executor() -> ThreadPoolExecutor:+ global _AUTO_PERSIST_EXECUTOR+ if _AUTO_PERSIST_EXECUTOR is None:+ with _AUTO_PERSIST_LOCK:+ if _AUTO_PERSIST_EXECUTOR is None:+ _AUTO_PERSIST_EXECUTOR = ThreadPoolExecutor(+ max_workers=2,+ thread_name_prefix="auto_persist_sweep",+ )+ return _AUTO_PERSIST_EXECUTOR+++def _shutdown_auto_persist_executor() -> None:+ global _AUTO_PERSIST_EXECUTOR+ executor = _AUTO_PERSIST_EXECUTOR+ _AUTO_PERSIST_EXECUTOR = None+ if executor is not None:+ try:+ executor.shutdown(wait=False, cancel_futures=True)+ except Exception: # allow: silent-exception+ pass+++def _reset_auto_persist_pending() -> None:+ """Reset the admission semaphore for testing."""+ global _AUTO_PERSIST_PENDING+ _AUTO_PERSIST_PENDING = threading.Semaphore(_AUTO_PERSIST_MAX_PENDING)+++atexit.register(_shutdown_auto_persist_executor)# Retry configuration constants for notification database queriesMAX_RESEARCH_LOOKUP_RETRIES = 3INITIAL_RESEARCH_LOOKUP_DELAY = 0.5 # seconds@@ -850,6 +904,59 @@ class QueueProcessorV2:auto_convert_research(username, research_id, db_password=user_password)+ # Auto-persist research sources (PDFs and text) into the Library.+ # Default-off behind research_library.auto_persist_research_sources;+ # runs in a daemon thread so source-heavy completions do not hold+ # the active-research slot for sequential downloads.+ def _auto_persist_async() -> None:+ try:+ from ...research_library.services.download_service import (+ auto_persist_research_sources,+ )++ auto_persist_research_sources(+ username, research_id, db_password=user_password+ )+ except Exception as exc:+ safe_msg = redact_secrets(str(exc), user_password)+ logger.debug(+ f"auto-persist background failed for {research_id}: {safe_msg}"+ )+ finally:+ _AUTO_PERSIST_PENDING.release()+ try:+ from ...database.thread_local_session import (+ cleanup_current_thread,+ )++ cleanup_current_thread()+ except Exception: # allow: silent-exception+ pass++ # Check the opt-out before enqueueing so disabled users (the+ # default) never occupy a bounded sweep slot.+ if not _auto_persist_enabled_for(username):+ logger.debug(+ f"auto-persist sweep not queued (disabled) for {research_id}"+ )+ elif not _AUTO_PERSIST_PENDING.acquire(blocking=False):+ logger.warning(+ f"auto-persist sweep skipped for {research_id}: "+ f"{_AUTO_PERSIST_MAX_PENDING} sweeps already pending; "+ "already-fetched PDFs remain persisted, and the text "+ "sweep can be retriggered by a later library download"+ )+ else:+ try:+ executor = _get_auto_persist_executor()+ executor.submit(_auto_persist_async)+ except Exception as exc:+ _AUTO_PERSIST_PENDING.release()+ safe_msg = redact_secrets(str(exc), user_password)+ logger.debug(+ f"auto-persist submission failed for {research_id}: {safe_msg}"+ )+def notify_research_failed(self,username: str,diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 75c0c3e327..ce5c1f6074 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -3414,12 +3414,55 @@ def cleanup_research_resources(from ..queue.processor_v2 import queue_processorif username:- queue_processor.notify_research_completed(- username, research_id, user_password=user_password- )- logger.info(- f"Notified queue processor of completion for research {research_id} (user: {username})"- )+ if current_status == ResearchStatus.COMPLETED:+ queue_processor.notify_research_completed(+ username, research_id, user_password=user_password+ )+ logger.info(+ f"Notified queue processor of completion for research {research_id} (user: {username})"+ )+ elif current_status == ResearchStatus.FAILED:+ queue_processor.notify_research_failed(+ username,+ research_id,+ error_message="Research failed",+ user_password=user_password,+ )+ logger.info(+ f"Notified queue processor of failure for research {research_id} (user: {username})"+ )+ else:+ # SUSPENDED/cancelled: update status without triggering the+ # auto-persist sweep — a cancelled run must not download.+ try:+ from datetime import datetime, UTC++ queue_processor.queue_error_update(+ username=username,+ research_id=research_id,+ status=current_status,+ error_message=f"Research was {current_status}",+ metadata={},+ completed_at=datetime.now(UTC).isoformat(),+ report_path=None,+ )+ try:+ with get_user_db_session(+ username, user_password+ ) as session:+ from ...database.queue_service import UserQueueService++ queue_service = UserQueueService(session)+ queue_service.update_task_status(+ research_id, current_status+ )+ queue_processor._drop_active_research_row(+ session, username, research_id+ )+ except Exception: # allow: silent-exception+ pass+ except Exception: # allow: silent-exception+ logger.debug(f"suspend status update failed for {research_id}")else:logger.warning(f"Cannot notify completion for research {research_id} - no username provided"diff --git a/tests/research_library/services/test_auto_persist_exhaustive.py b/tests/research_library/services/test_auto_persist_exhaustive.pynew file mode 100644index 0000000000..348975bfd7--- /dev/null+++ b/tests/research_library/services/test_auto_persist_exhaustive.py@@ -0,0 +1,1905 @@+"""Exhaustive tests for on-the-spot PDF persistence and auto-persist gating.++Covers helpers, versioning, gating matrix, executor bounds, sweep paths,+and regression pins that the feature test file does not exercise.+"""++import hashlib+from datetime import UTC, datetime+from types import SimpleNamespace+from unittest.mock import MagicMock, Mock++import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from local_deep_research.constants import FILE_PATH_TEXT_ONLY, ResearchStatus+from local_deep_research.database.models import Base+from local_deep_research.database.models.download_tracker import DownloadTracker+from local_deep_research.database.models.library import (+ Collection,+ Document,+ DocumentCollection,+ DocumentStatus,+ SourceType,+)+from local_deep_research.database.models.research import (+ ResearchHistory,+ ResearchResource,+)+from local_deep_research.research_library.services import (+ download_service as ds,+)+from local_deep_research.research_library.services.download_service import (+ DownloadService,+ auto_persist_research_sources,+)+++def db():+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ session.add(Collection(id="default-library", name="Library"))+ session.add(+ SourceType(+ id="st-research",+ name="research_download",+ display_name="Research Download",+ )+ )+ session.add(+ ResearchHistory(+ id="res-123",+ query="Quantum Computing",+ mode="quick",+ status=ResearchStatus.COMPLETED,+ created_at=datetime.now(UTC).isoformat(),+ )+ )+ session.commit()+ yield session+ session.close()+++def _mock_db_session(monkeypatch, session):+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: session, __exit__=lambda *a: None+ ),+ )+++def _settings_mock(monkeypatch, values):+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: values.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_default_library_id",+ lambda *a, **k: "default-library",+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_source_type_id",+ lambda *a, **k: "st-research",+ )+ return mock_settings+++def _live_settings(monkeypatch, auto=True, mode="database"):+ return _settings_mock(+ monkeypatch,+ {+ "research_library.auto_persist_research_sources": auto,+ "research_library.pdf_storage_mode": mode,+ "research_library.max_pdf_size_mb": 50,+ },+ )+++def _make_resource(db, rid, url, research_id="res-123", document_id=None):+ r = ResearchResource(+ id=rid,+ research_id=research_id,+ url=url,+ title=f"Resource {rid}",+ document_id=document_id,+ created_at=datetime.now(UTC).isoformat(),+ )+ db.add(r)+ db.commit()+ return r+++def _stub_service(settings_values):+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: (+ settings_values.get(k, d)+ )+ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service.library_root = "/fake/root"+ return service+++# ---------------------------------------------------------------------------+# _is_pdf_bytes+# ---------------------------------------------------------------------------+++def test_is_pdf_bytes_direct_magic():+ assert ds._is_pdf_bytes(b"%PDF-1.4 hello") is True+++def test_is_pdf_bytes_leading_whitespace():+ assert ds._is_pdf_bytes(b"\n\n%PDF-1.4 hello") is True+++def test_is_pdf_bytes_leading_bytes_within_1024():+ assert ds._is_pdf_bytes(b" " * 1000 + b"%PDF-1.4") is True+++def test_is_pdf_bytes_header_beyond_1024_rejected():+ assert ds._is_pdf_bytes(b" " * 1025 + b"%PDF-1.4") is False+++def test_is_pdf_bytes_empty_and_none():+ assert ds._is_pdf_bytes(b"") is False+ assert ds._is_pdf_bytes(None) is False+ assert ds._is_pdf_bytes(b"%P") is False+++def test_is_pdf_bytes_non_pdf():+ assert ds._is_pdf_bytes(b"<html>not a pdf</html>") is False+++def test_is_pdf_bytes_html_mentioning_pdf_magic():+ html_doc = b"<!DOCTYPE html><html><body>Document describing %PDF-1.7 format</body></html>"+ assert ds._is_pdf_bytes(html_doc) is False+ assert (+ ds._is_pdf_bytes(b"<html><head><title>%PDF spec</title></head></html>")+ is False+ )+ assert ds._is_pdf_bytes(b'{"magic": "%PDF-1.4", "type": "doc"}') is False+ assert ds._is_pdf_bytes(b"<body><h1>%PDF Reference</h1></body>") is False+ assert ds._is_pdf_bytes(b"<head><title>%PDF</title></head>") is False+++def test_is_pdf_bytes_binary_stream_with_leading_junk():+ binary_pdf = b"\x00\xff\xfe\x80junk%PDF-1.4 binary data\x00\x01"+ assert ds._is_pdf_bytes(binary_pdf) is True+++def test_bom_prefixed_pdf_stays_a_pdf():+ assert ds._is_pdf_bytes(b"\xef\xbb\xbf%PDF-1.4 hello") is True+ assert ds._is_pdf_bytes(b"\x00\x00\x00\x00%PDF-1.4 nul padded") is True+ assert ds._is_pdf_bytes(b"Copyright 17 byte\n%PDF-1.4 ascii prefix") is True+++# ---------------------------------------------------------------------------+# _is_auto_persist_enabled+# ---------------------------------------------------------------------------+++def test_auto_enabled_snapshot_true():+ assert (+ ds._is_auto_persist_enabled(+ {"research_library.auto_persist_research_sources": True},+ "u",+ )+ is True+ )+++def test_auto_enabled_snapshot_false():+ assert (+ ds._is_auto_persist_enabled(+ {"research_library.auto_persist_research_sources": False},+ "u",+ )+ is False+ )+++def test_auto_enabled_non_boolean_snapshot_values_disabled():+ for non_bool in (+ "false",+ "off",+ "true",+ 1,+ 0,+ {"value": False},+ {"value": "true"},+ {"value": 1},+ [True],+ ):+ assert (+ ds._is_auto_persist_enabled(+ {"research_library.auto_persist_research_sources": non_bool},+ "u",+ )+ is False+ )+++def test_auto_enabled_wrapped_dict_snapshot():+ assert (+ ds._is_auto_persist_enabled(+ {"research_library.auto_persist_research_sources": {"value": True}},+ "u",+ )+ is True+ )+ assert (+ ds._is_auto_persist_enabled(+ {+ "research_library.auto_persist_research_sources": {+ "value": True,+ "ui_element": "checkbox",+ }+ },+ "u",+ )+ is True+ )+ assert (+ ds._is_auto_persist_enabled(+ {+ "research_library.auto_persist_research_sources": {+ "value": False+ }+ },+ "u",+ )+ is False+ )+++def test_auto_enabled_missing_key_falls_back_to_live(monkeypatch):+ _live_settings(monkeypatch, auto=True)+ assert ds._is_auto_persist_enabled({"_username": "u"}, "u") is True+++def test_auto_enabled_missing_key_live_false(monkeypatch):+ _live_settings(monkeypatch, auto=False)+ assert ds._is_auto_persist_enabled({"_username": "u"}, "u") is False+++def test_auto_enabled_no_snapshot_live_true(monkeypatch):+ _live_settings(monkeypatch, auto=True)+ assert ds._is_auto_persist_enabled(None, "u") is True+++def test_auto_enabled_no_username_no_snapshot():+ assert ds._is_auto_persist_enabled(None, None) is False+ assert ds._is_auto_persist_enabled({}, None) is False+++def test_auto_enabled_live_lookup_failure_returns_false(monkeypatch):+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ Mock(side_effect=RuntimeError("db down")),+ )+ assert ds._is_auto_persist_enabled({"other": 1}, "u") is False+++# ---------------------------------------------------------------------------+# _resolve_pdf_storage_mode+# ---------------------------------------------------------------------------+++def test_storage_mode_filesystem_gated_to_database_by_default():+ # Operator gate closed in test env: filesystem coerces to database.+ assert (+ ds._resolve_pdf_storage_mode(+ {+ "research_library.pdf_storage_mode": "filesystem",+ "document_scheduler.download_pdfs": True,+ },+ "u",+ )+ == "database"+ )+++def test_storage_mode_filesystem_allowed_with_gate_open(monkeypatch):+ monkeypatch.setattr(+ "local_deep_research.research_library.services.pdf_storage_manager.filesystem_pdf_storage_allowed",+ lambda: True,+ )+ assert (+ ds._resolve_pdf_storage_mode(+ {+ "research_library.pdf_storage_mode": "filesystem",+ "document_scheduler.download_pdfs": True,+ },+ "u",+ )+ == "filesystem"+ )+++def test_storage_mode_scheduler_false_forces_none():+ assert (+ ds._resolve_pdf_storage_mode(+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": False,+ },+ "u",+ )+ == "none"+ )+++def test_storage_mode_wrapped_dict_handling(monkeypatch):+ from local_deep_research.research_library.services.pdf_storage_manager import (+ resolve_pdf_storage_mode,+ )++ # download_pdfs wrapped as {"value": False} forces "none"+ assert (+ ds._resolve_pdf_storage_mode(+ {+ "research_library.pdf_storage_mode": {"value": "database"},+ "document_scheduler.download_pdfs": {"value": False},+ },+ "u",+ )+ == "none"+ )++ # filesystem wrapped in dict coerces to database when operator gate closed+ assert (+ ds._resolve_pdf_storage_mode(+ {+ "research_library.pdf_storage_mode": {"value": "filesystem"},+ "document_scheduler.download_pdfs": {"value": True},+ },+ "u",+ )+ == "database"+ )++ # download_pdfs present-but-None forces "none"+ assert (+ ds._resolve_pdf_storage_mode(+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": None,+ },+ "u",+ )+ == "none"+ )+ assert (+ ds._resolve_pdf_storage_mode(+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": {"value": None},+ },+ "u",+ )+ == "none"+ )++ # direct resolve_pdf_storage_mode with wrapped dict coerces to database+ assert resolve_pdf_storage_mode({"value": "filesystem"}) == "database"+++def test_storage_mode_keyless_snapshot_uses_live_none(monkeypatch):+ _settings_mock(+ monkeypatch,+ {+ "research_library.pdf_storage_mode": "none",+ "document_scheduler.download_pdfs": True,+ },+ )+ assert ds._resolve_pdf_storage_mode({"_username": "u"}, "u") == "none"+++def test_storage_mode_snapshot_key_beats_live(monkeypatch):+ _settings_mock(+ monkeypatch,+ {+ "research_library.pdf_storage_mode": "none",+ "document_scheduler.download_pdfs": True,+ },+ )+ assert (+ ds._resolve_pdf_storage_mode(+ {"research_library.pdf_storage_mode": "database"}, "u"+ )+ == "database"+ )+++def test_storage_mode_no_snapshot_uses_live(monkeypatch):+ _settings_mock(+ monkeypatch,+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ },+ )+ assert ds._resolve_pdf_storage_mode(None, "u") == "database"+++def test_storage_mode_invalid_value_passes_through_unvalidated():+ # No validation at this layer: unknown values pass through unchanged.+ assert (+ ds._resolve_pdf_storage_mode(+ {+ "research_library.pdf_storage_mode": "bogus",+ "document_scheduler.download_pdfs": True,+ },+ "u",+ )+ == "bogus"+ )+++# ---------------------------------------------------------------------------+# resolve_fetch_identity+# ---------------------------------------------------------------------------+++def test_identity_explicit_wins():+ from local_deep_research.utilities.thread_context import (+ resolve_fetch_identity,+ )++ u, p, s = resolve_fetch_identity(+ username="exp", password="pw", settings_snapshot={"a": 1}+ )+ assert (u, p, s) == ("exp", "pw", {"a": 1})+++def test_identity_egress_used_when_no_explicit():+ from local_deep_research.utilities.thread_context import (+ resolve_fetch_identity,+ )++ egress = SimpleNamespace(username="eg", password="egpw")+ u, p, _ = resolve_fetch_identity(egress_context=egress)+ assert (u, p) == ("eg", "egpw")+++def test_identity_egress_without_username_falls_through():+ from local_deep_research.utilities.thread_context import (+ resolve_fetch_identity,+ )++ egress = SimpleNamespace(username=None, password=None)+ u, p, _ = resolve_fetch_identity(+ egress_context=egress,+ settings_snapshot={"_username": "snap"},+ )+ assert u == "snap"+++def test_identity_thread_context_used():+ from local_deep_research.utilities.thread_context import (+ clear_search_context,+ resolve_fetch_identity,+ set_search_context,+ )++ set_search_context(+ {+ "username": "thr",+ "user_password": "thrpw",+ "settings_snapshot": {"k": "v"},+ }+ )+ try:+ u, p, s = resolve_fetch_identity()+ assert (u, p, s) == ("thr", "thrpw", {"k": "v"})+ finally:+ clear_search_context()+++def test_identity_explicit_beats_thread_context():+ from local_deep_research.utilities.thread_context import (+ clear_search_context,+ resolve_fetch_identity,+ set_search_context,+ )++ set_search_context({"username": "thr", "user_password": "thrpw"})+ try:+ u, p, _ = resolve_fetch_identity(username="exp", password="exppw")+ assert (u, p) == ("exp", "exppw")+ finally:+ clear_search_context()+++def test_identity_non_dict_snapshot():+ from local_deep_research.utilities.thread_context import (+ resolve_fetch_identity,+ )++ u, p, s = resolve_fetch_identity(settings_snapshot="nope")+ assert u is None and s == "nope"+++# ---------------------------------------------------------------------------+# Executor bounds and lifecycle+# ---------------------------------------------------------------------------+++def test_pdf_executor_is_singleton():+ assert (+ ds._get_pdf_persistence_executor() is ds._get_pdf_persistence_executor()+ )+++def test_pdf_executor_shutdown_is_idempotent_and_renewable():+ first = ds._get_pdf_persistence_executor()+ ds._shutdown_pdf_persistence_executor()+ ds._shutdown_pdf_persistence_executor()+ second = ds._get_pdf_persistence_executor()+ assert second is not first+++def test_auto_persist_executor_singleton_and_shutdown():+ from local_deep_research.web.queue.processor_v2 import (+ _get_auto_persist_executor,+ _shutdown_auto_persist_executor,+ )++ assert _get_auto_persist_executor() is _get_auto_persist_executor()+ _shutdown_auto_persist_executor()+ _shutdown_auto_persist_executor()+ assert _get_auto_persist_executor() is not None+++def test_background_submit_skipped_when_slots_exhausted(monkeypatch):+ import threading++ mock_executor = Mock()+ monkeypatch.setattr(+ ds, "_get_pdf_persistence_executor", lambda: mock_executor+ )+ # Isolate from slots held by background submits in earlier tests of+ # a combined run (mock executors there never run the closure).+ monkeypatch.setattr(ds, "_PDF_PERSIST_SEMAPHORE", threading.Semaphore(4))+ with ds._PDF_PERSIST_BYTES_LOCK:+ ds._PDF_PERSIST_BYTES = 0+ acquired = []+ try:+ for _ in range(4):+ assert ds._PDF_PERSIST_SEMAPHORE.acquire(blocking=False)+ acquired.append(True)+ res = ds.persist_downloaded_pdf_on_the_spot(+ url="https://example.com/full.pdf",+ pdf_content=b"%PDF-1.4 x",+ text="t",+ username="u",+ run_in_background=True,+ )+ assert res is None+ mock_executor.submit.assert_not_called()+ finally:+ for _ in acquired:+ ds._PDF_PERSIST_SEMAPHORE.release()+++def test_background_submit_skipped_when_byte_cap_hit(monkeypatch):+ mock_executor = Mock()+ monkeypatch.setattr(+ ds, "_get_pdf_persistence_executor", lambda: mock_executor+ )+ with ds._PDF_PERSIST_BYTES_LOCK:+ ds._PDF_PERSIST_BYTES = ds._PDF_PERSIST_MAX_PENDING_BYTES+ try:+ res = ds.persist_downloaded_pdf_on_the_spot(+ url="https://example.com/big.pdf",+ pdf_content=b"%PDF-1.4 x" * 100,+ text="t",+ username="u",+ run_in_background=True,+ )+ assert res is None+ mock_executor.submit.assert_not_called()+ finally:+ with ds._PDF_PERSIST_BYTES_LOCK:+ ds._PDF_PERSIST_BYTES = 0+++def test_background_closure_releases_slot_and_bytes(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ captured = []+ mock_executor = Mock()+ mock_executor.submit.side_effect = lambda fn: captured.append(fn)+ monkeypatch.setattr(+ ds, "_get_pdf_persistence_executor", lambda: mock_executor+ )+ res = ds.persist_downloaded_pdf_on_the_spot(+ url="https://example.com/acct.pdf",+ pdf_content=b"%PDF-1.4 accounting",+ text="accounting text",+ username="testuser",+ settings_snapshot={"research_library.pdf_storage_mode": "database"},+ run_in_background=True,+ )+ assert res is None+ assert len(captured) == 1+ captured[0]()+ with ds._PDF_PERSIST_BYTES_LOCK:+ assert ds._PDF_PERSIST_BYTES == 0+ assert ds._PDF_PERSIST_SEMAPHORE.acquire(blocking=False)+ ds._PDF_PERSIST_SEMAPHORE.release()+ assert (+ db.query(Document)+ .filter_by(original_url="https://example.com/acct.pdf")+ .count()+ == 1+ )+++# ---------------------------------------------------------------------------+# _save_pdf_document_record: versioning and field hygiene+# ---------------------------------------------------------------------------+++def _storage_manager(tmp_path):+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ return PDFStorageManager(+ library_root=tmp_path,+ storage_mode="database",+ max_pdf_size_mb=50,+ username="testuser",+ )+++def test_save_changed_bytes_mint_new_doc_and_advance_tracker(+ db, monkeypatch, tmp_path+):+ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ _make_resource(db, 11, "https://example.com/evolving.pdf")+ old_bytes = b"%PDF-1.4 version one"+ new_bytes = b"%PDF-1.4 version two updated"+ old_hash = hashlib.sha256(old_bytes).hexdigest()+ new_hash = hashlib.sha256(new_bytes).hexdigest()++ doc_old, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=old_bytes,+ file_hash=old_hash,+ url="https://example.com/evolving.pdf",+ text="OLD TEXT",+ username="testuser",+ resource_id=11,+ pdf_storage_mode="database",+ )+ db.commit()+ doc_new, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=new_bytes,+ file_hash=new_hash,+ url="https://example.com/evolving.pdf",+ text="NEW TEXT",+ username="testuser",+ resource_id=11,+ pdf_storage_mode="database",+ )+ db.commit()++ assert doc_new.id != doc_old.id+ assert db.query(Document).count() == 2+ assert (+ db.query(Document).filter_by(id=doc_old.id).first().text_content+ == "OLD TEXT"+ )+ tracker = ds.find_tracker_by_url(db, "https://example.com/evolving.pdf")+ assert tracker is not None+ assert tracker.file_hash == new_hash+++def test_save_identical_bytes_across_urls_share_one_doc(+ db, monkeypatch, tmp_path+):+ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ _make_resource(db, 21, "https://mirror1.example.com/paper.pdf")+ _make_resource(db, 22, "https://mirror2.example.com/paper.pdf")+ payload = b"%PDF-1.4 identical bytes"+ file_hash = hashlib.sha256(payload).hexdigest()++ doc_a, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=payload,+ file_hash=file_hash,+ url="https://mirror1.example.com/paper.pdf",+ text="SAME TEXT",+ username="testuser",+ resource_id=21,+ pdf_storage_mode="database",+ )+ db.commit()+ doc_b, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=payload,+ file_hash=file_hash,+ url="https://mirror2.example.com/paper.pdf",+ text="SAME TEXT",+ username="testuser",+ resource_id=22,+ pdf_storage_mode="database",+ )+ db.commit()++ assert doc_a.id == doc_b.id+ assert db.query(Document).count() == 1+++def test_save_require_text_rejects_garbage(db, monkeypatch, tmp_path):+ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: None,+ )+ doc, path = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=b"%PDF-garbage-no-text",+ file_hash=hashlib.sha256(b"%PDF-garbage-no-text").hexdigest(),+ url="https://example.com/garbage.pdf",+ text=None,+ username="testuser",+ pdf_storage_mode="database",+ require_text=True,+ )+ assert doc is None and path is None+ assert db.query(Document).count() == 0+++def test_save_library_path_tolerates_empty_text(db, monkeypatch, tmp_path):+ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "SHOULD NOT BE EXTRACTED ON LIBRARY PATH",+ )+ payload = b"%PDF-1.4 synthetic no text"+ doc, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=payload,+ file_hash=hashlib.sha256(payload).hexdigest(),+ url="https://example.com/synth.pdf",+ text=None,+ username="testuser",+ pdf_storage_mode="database",+ require_text=False,+ )+ db.commit()+ assert doc is not None+ assert doc.file_type == "pdf"+ # Library path leaves text to its canonical step and stores None,+ # never "", so the RAG sweep's IS NOT NULL check skips it.+ assert doc.text_content is None++[email protected]("stored_mode", ["database", "filesystem"])+def test_save_text_only_reuse_preserves_stored_pdf_metadata(+ db, monkeypatch, tmp_path, stored_mode+):+ """Text-only reuse must not relabel a document that stores its PDF."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )+ from local_deep_research.research_library.utils import (+ document_awaits_pdf,+ )++ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ _make_resource(db, 31, "https://example.com/stored.pdf")+ payload = b"%PDF-1.4 stored bytes"+ file_hash = hashlib.sha256(payload).hexdigest()+ url = "https://example.com/stored.pdf"++ stored_manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode=stored_mode,+ max_pdf_size_mb=50,+ username="testuser",+ )+ doc, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=stored_manager,+ pdf_content=payload,+ file_hash=file_hash,+ url=url,+ text="STORED TEXT",+ username="testuser",+ resource_id=31,+ pdf_storage_mode=stored_mode,+ require_text=True,+ )+ db.commit()+ assert doc is not None+ assert stored_manager.has_pdf(doc, db) is True+ stored_shape = (doc.storage_mode, doc.file_path)++ none_manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="none",+ max_pdf_size_mb=50,+ username="testuser",+ )+ reused, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=none_manager,+ pdf_content=payload,+ file_hash=file_hash,+ url=url,+ text="STORED TEXT",+ username="testuser",+ resource_id=31,+ pdf_storage_mode="none",+ require_text=True,+ )+ db.commit()+ assert reused is not None and reused.id == doc.id+ assert (reused.storage_mode, reused.file_path) == stored_shape+ assert reused.storage_mode == stored_mode+ assert document_awaits_pdf(reused) is False+++def test_save_text_only_reuse_empty_blob_relabels_and_awaits_pdf(+ db, monkeypatch, tmp_path+):+ """Empty or unretrievable blob row must be treated as not stored and await PDF."""+ from local_deep_research.database.models.library import DocumentBlob+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )+ from local_deep_research.research_library.utils import (+ document_awaits_pdf,+ )++ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ _make_resource(db, 32, "https://example.com/empty_blob.pdf")+ payload = b"%PDF-1.4 empty blob test"+ file_hash = hashlib.sha256(payload).hexdigest()+ url = "https://example.com/empty_blob.pdf"++ doc = Document(+ id="doc-empty-blob",+ source_type_id="st-research",+ resource_id=32,+ research_id="res-123",+ document_hash=file_hash,+ original_url=url,+ file_size=len(payload),+ file_type="pdf",+ mime_type="application/pdf",+ title="Empty Blob PDF",+ status=DocumentStatus.COMPLETED,+ text_content="EXTRACTED TEXT",+ storage_mode="database",+ file_path=None,+ )+ db.add(doc)+ empty_blob = DocumentBlob(+ document_id=doc.id,+ pdf_binary=b"",+ blob_hash=hashlib.sha256(b"").hexdigest(),+ stored_at=datetime.now(UTC),+ )+ db.add(empty_blob)+ db.commit()++ none_manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="none",+ max_pdf_size_mb=50,+ username="testuser",+ )+ reused, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=none_manager,+ pdf_content=payload,+ file_hash=file_hash,+ url=url,+ text="EXTRACTED TEXT",+ username="testuser",+ resource_id=32,+ pdf_storage_mode="none",+ require_text=True,+ )+ db.commit()+ assert reused is not None and reused.id == doc.id+ assert reused.storage_mode == "none"+ assert reused.file_path == FILE_PATH_TEXT_ONLY+ assert document_awaits_pdf(reused) is True+++def test_save_dedup_check_probes_metadata_without_calling_load_pdf_or_dirtying_session(+ db, monkeypatch, tmp_path+):+ """Dedup check must probe metadata via func.length without materializing PDF bytes via load_pdf+ and without marking the DocumentBlob dirty in the session.+ """+ from local_deep_research.database.models.library import DocumentBlob+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )+ from local_deep_research.research_library.utils import document_awaits_pdf++ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ _make_resource(db, 77, "https://example.com/no_load_pdf.pdf")+ payload = b"%PDF-1.4 metadata probe only"+ file_hash = hashlib.sha256(payload).hexdigest()+ url = "https://example.com/no_load_pdf.pdf"++ doc = Document(+ id="doc-no-load-pdf",+ source_type_id="st-research",+ resource_id=77,+ research_id="res-123",+ document_hash=file_hash,+ original_url=url,+ file_size=len(payload),+ file_type="pdf",+ mime_type="application/pdf",+ title="Probe PDF",+ status=DocumentStatus.COMPLETED,+ text_content="EXTRACTED TEXT",+ storage_mode="database",+ file_path="database",+ )+ db.add(doc)+ init_time = datetime.now(UTC)+ blob = DocumentBlob(+ document_id=doc.id,+ pdf_binary=payload,+ blob_hash=file_hash,+ stored_at=init_time,+ last_accessed=init_time,+ )+ db.add(blob)+ db.commit()++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="database",+ max_pdf_size_mb=50,+ username="testuser",+ )+ load_pdf_called = False+ original_load = manager.load_pdf++ def spy_load_pdf(*args, **kwargs):+ nonlocal load_pdf_called+ load_pdf_called = True+ return original_load(*args, **kwargs)++ manager.load_pdf = spy_load_pdf++ reused, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=manager,+ pdf_content=payload,+ file_hash=file_hash,+ url=url,+ text="EXTRACTED TEXT",+ username="testuser",+ resource_id=77,+ pdf_storage_mode="database",+ require_text=True,+ )++ assert load_pdf_called is False+ assert blob not in db.dirty+ assert reused.id == doc.id+ assert reused.storage_mode == "database"+ assert document_awaits_pdf(reused) is False+ db.commit()+++def test_save_pdf_document_record_over_cap_reuse_legacy_row_resets_file_path(+ db, monkeypatch, tmp_path+):+ """When a legacy document with a truthy file_path (e.g. 'database') is reused+ and PDF storage cannot save due to size cap, file_path must be reset to FILE_PATH_TEXT_ONLY+ under require_text=True so document_awaits_pdf reports True.+ """+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )+ from local_deep_research.research_library.utils import document_awaits_pdf++ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ _make_resource(db, 88, "https://example.com/overcap_legacy.pdf")+ payload = b"%PDF-1.4 legacy overcap"+ file_hash = hashlib.sha256(payload).hexdigest()+ url = "https://example.com/overcap_legacy.pdf"++ doc = Document(+ id="doc-legacy-overcap",+ source_type_id="st-research",+ resource_id=88,+ research_id="res-123",+ document_hash=file_hash,+ original_url=url,+ file_size=len(payload),+ file_type="pdf",+ mime_type="application/pdf",+ title="Legacy Overcap PDF",+ status=DocumentStatus.COMPLETED,+ text_content="EXTRACTED TEXT",+ storage_mode="none",+ file_path="database",+ )+ db.add(doc)+ db.commit()++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="database",+ max_pdf_size_mb=0,+ username="testuser",+ )+ manager.max_pdf_size_bytes = 1++ reused, file_path_result = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=manager,+ pdf_content=payload,+ file_hash=file_hash,+ url=url,+ text="EXTRACTED TEXT",+ username="testuser",+ resource_id=88,+ pdf_storage_mode="database",+ require_text=True,+ )+ db.commit()++ assert reused.id == doc.id+ assert reused.storage_mode == "none"+ assert reused.file_path == FILE_PATH_TEXT_ONLY+ assert document_awaits_pdf(reused) is True++[email protected]("stored_mode", ["database", "filesystem"])[email protected]("require_text", [True, False])+def test_save_pdf_document_record_over_cap_storage_enabled(+ db, monkeypatch, tmp_path, stored_mode, require_text+):+ """When PDF exceeds max_pdf_size_mb with storage enabled, no UnboundLocalError occurs+ and document is handled consistently as text-only/not-stored.+ """+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )+ from local_deep_research.research_library.utils import (+ document_awaits_pdf,+ )++ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ res_id = 45 if require_text else 46+ _make_resource(+ db,+ res_id,+ f"https://example.com/overcap_{stored_mode}_{require_text}.pdf",+ )+ payload = b"%PDF-1.4 " + b"X" * 2000+ file_hash = hashlib.sha256(payload).hexdigest()+ url = f"https://example.com/overcap_{stored_mode}_{require_text}.pdf"++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode=stored_mode,+ max_pdf_size_mb=0,+ username="testuser",+ )+ manager.max_pdf_size_bytes = 100++ doc, file_path_result = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=manager,+ pdf_content=payload,+ file_hash=file_hash,+ url=url,+ text="OVERCAP TEXT",+ username="testuser",+ resource_id=res_id,+ pdf_storage_mode=stored_mode,+ require_text=require_text,+ )+ db.commit()++ assert doc is not None+ assert file_path_result is None+ assert doc.file_type == "pdf"+ assert doc.storage_mode == "none"++ tracker = ds.find_tracker_by_url(db, url)+ assert tracker is not None+ assert tracker.file_path is None++ if require_text:+ assert doc.file_path == FILE_PATH_TEXT_ONLY+ assert document_awaits_pdf(doc) is True+ else:+ assert doc.file_path is None+++def test_save_backfills_missing_text_title_status_and_ids(+ db, monkeypatch, tmp_path+):+ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ payload = b"%PDF-1.4 backfill"+ file_hash = hashlib.sha256(payload).hexdigest()+ thin = Document(+ id="doc-thin",+ source_type_id="st-research",+ document_hash=file_hash,+ original_url="https://example.com/thin.pdf",+ file_size=len(payload),+ file_type="pdf",+ mime_type="application/pdf",+ title="Untitled",+ status=DocumentStatus.FAILED,+ error_message="boom",+ text_content="",+ storage_mode="database",+ file_path="database",+ )+ db.add(thin)+ db.commit()++ doc, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=payload,+ file_hash=file_hash,+ url="https://example.com/thin.pdf",+ text="BACKFILLED TEXT",+ title="Real Title",+ username="testuser",+ resource_id=31,+ research_id="res-123",+ pdf_storage_mode="database",+ )+ db.commit()+ assert doc.id == "doc-thin"+ assert doc.text_content == "BACKFILLED TEXT"+ assert doc.title == "Real Title"+ assert doc.status == DocumentStatus.COMPLETED+ assert doc.error_message is None+ assert doc.resource_id == 31+ assert doc.research_id == "res-123"+++def test_save_does_not_clobber_existing_text_title_or_ids(+ db, monkeypatch, tmp_path+):+ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ payload = b"%PDF-1.4 keep me"+ file_hash = hashlib.sha256(payload).hexdigest()+ _make_resource(db, 32, "https://example.com/keep.pdf")+ _make_resource(db, 33, "https://example.com/keep.pdf")+ first, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=payload,+ file_hash=file_hash,+ url="https://example.com/keep.pdf",+ text="ORIGINAL",+ title="Original Title",+ username="testuser",+ resource_id=32,+ research_id="res-123",+ pdf_storage_mode="database",+ )+ db.commit()+ second, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=payload,+ file_hash=file_hash,+ url="https://example.com/keep.pdf",+ text="NEWTEXT",+ title="New Title",+ username="testuser",+ resource_id=33,+ research_id="res-999",+ pdf_storage_mode="database",+ )+ db.commit()+ assert second.id == first.id+ assert second.text_content == "ORIGINAL"+ assert second.title == "Original Title"+ assert second.resource_id == 32+ assert second.research_id == "res-123"+++def test_save_collection_failure_still_returns_doc(db, monkeypatch, tmp_path):+ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds,+ "get_default_library_id",+ Mock(side_effect=RuntimeError("no library")),+ )+ db.query(Collection).delete()+ db.commit()+ payload = b"%PDF-1.4 lonely doc"+ doc, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=payload,+ file_hash=hashlib.sha256(payload).hexdigest(),+ url="https://example.com/lonely.pdf",+ text="lonely text",+ username="testuser",+ pdf_storage_mode="database",+ )+ db.commit()+ assert doc is not None+ assert db.query(Document).filter_by(id=doc.id).count() == 1+++def test_save_uses_canonical_url_hash_for_trackers(db, monkeypatch, tmp_path):+ from local_deep_research.utilities.download_url import get_url_hash+ from local_deep_research.utilities.url_utils import canonical_url_key++ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ _make_resource(db, 41, "https://example.com/paper?utm_source=x")+ payload = b"%PDF-1.4 canonical hash"+ doc, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=payload,+ file_hash=hashlib.sha256(payload).hexdigest(),+ url="https://example.com/paper?utm_source=x",+ text="canonical text",+ username="testuser",+ resource_id=41,+ extra_urls=["https://cdn.example.com/final.pdf"],+ pdf_storage_mode="database",+ )+ db.commit()+ assert doc is not None+ for u in (+ "https://example.com/paper?utm_source=x",+ "https://cdn.example.com/final.pdf",+ ):+ tracker = ds.find_tracker_by_url(db, u)+ assert tracker is not None+ assert tracker.url_hash == get_url_hash(canonical_url_key(u))+ assert tracker.file_size == len(payload)+++def test_save_race_winner_still_writes_trackers_and_collection(+ db, monkeypatch, tmp_path+):+ # True concurrency shape: the hash lookup misses (winner not yet+ # committed) but the flush collides. Hide the winner from the first+ # Document-hash lookup only; the loser's real flush then raises a real+ # IntegrityError against the committed winner.+ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )+ _make_resource(db, 51, "https://mirror-b.example.com/p.pdf")+ payload = b"%PDF-1.4 racy bytes"+ file_hash = hashlib.sha256(payload).hexdigest()+ winner = Document(+ id="doc-winner",+ source_type_id="st-research",+ document_hash=file_hash,+ original_url="https://mirror-a.example.com/p.pdf",+ file_size=len(payload),+ file_type="pdf",+ mime_type="application/pdf",+ title="Winner",+ status=DocumentStatus.COMPLETED,+ text_content="winner text",+ storage_mode="database",+ file_path="database",+ )+ db.add(winner)+ db.commit()++ real_query = db.query+ skipped = {"once": False}++ def hiding_query(*entities, **kwargs):+ if not skipped["once"] and entities and entities[0] is Document:+ skipped["once"] = True++ class _Miss:+ def filter_by(self, **kw):+ return self++ def first(self):+ return None++ return _Miss()+ return real_query(*entities, **kwargs)++ monkeypatch.setattr(db, "query", hiding_query)+ doc, _ = ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=payload,+ file_hash=file_hash,+ url="https://mirror-b.example.com/p.pdf",+ text="loser text",+ username="testuser",+ resource_id=51,+ extra_urls=["https://mirror-b.example.com/p.pdf"],+ collection_id="default-library",+ pdf_storage_mode="database",+ require_text=True,+ )+ db.commit()++ assert doc.id == "doc-winner"+ assert db.query(Document).count() == 1+ tracker = ds.find_tracker_by_url(db, "https://mirror-b.example.com/p.pdf")+ assert tracker is not None+ assert tracker.file_hash == file_hash+ assert (+ db.query(DocumentCollection)+ .filter_by(document_id="doc-winner", collection_id="default-library")+ .count()+ == 1+ )+++def test_save_non_integrity_flush_error_propagates(db, monkeypatch, tmp_path):+ monkeypatch.setattr(ds, "get_source_type_id", lambda *a, **k: "st-research")+ monkeypatch.setattr(+ ds, "get_default_library_id", lambda *a, **k: "default-library"+ )++ def bad_flush():+ raise ValueError("disk on fire")++ monkeypatch.setattr(db, "flush", bad_flush)+ with pytest.raises(ValueError, match="disk on fire"):+ ds._save_pdf_document_record(+ session=db,+ pdf_storage_manager=_storage_manager(tmp_path),+ pdf_content=b"%PDF-1.4 x",+ file_hash=hashlib.sha256(b"%PDF-1.4 x").hexdigest(),+ url="https://example.com/err.pdf",+ text="t",+ username="testuser",+ pdf_storage_mode="database",+ require_text=True,+ )+++# ---------------------------------------------------------------------------+# _do_persist gating matrix+# ---------------------------------------------------------------------------+++def _do_kwargs(**overrides):+ base = {+ "url": "https://example.com/gate.pdf",+ "pdf_content": b"%PDF-1.4 gated",+ "text": "gated text",+ "title": "Gated",+ "username": "testuser",+ }+ base.update(overrides)+ return base+++def test_do_persist_sync_baseline(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ doc_id = ds._do_persist_downloaded_pdf_on_the_spot(**_do_kwargs())+ assert doc_id is not None+ doc = db.query(Document).filter_by(id=doc_id).first()+ assert doc.text_content == "gated text"+ assert doc.file_type == "pdf"+++def test_do_persist_explicit_opt_out_honored_without_flag(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ doc_id = ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(+ settings_snapshot={+ "research_library.auto_persist_research_sources": False+ }+ )+ )+ assert doc_id is None+ assert db.query(Document).count() == 0+++def test_do_persist_gated_on_with_snapshot_key(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=False)+ doc_id = ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(+ settings_snapshot={+ "research_library.auto_persist_research_sources": True+ }+ ),+ check_setting=True,+ )+ assert doc_id is not None+++def test_do_persist_wrapped_dict_snapshot_enabled(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=False)+ doc_id = ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(+ settings_snapshot={+ "research_library.auto_persist_research_sources": {+ "value": True,+ "ui_element": "checkbox",+ },+ "research_library.max_pdf_size_mb": {"value": 50},+ }+ ),+ check_setting=True,+ )+ assert doc_id is not None+++def test_do_persist_gated_off_with_snapshot_key(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ doc_id = ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(+ settings_snapshot={+ "research_library.auto_persist_research_sources": False+ }+ ),+ check_setting=True,+ )+ assert doc_id is None+ assert db.query(Document).count() == 0+++def test_do_persist_non_boolean_snapshot_values_disabled(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ for non_bool in ("false", "off", "true", 1, 0, {"value": False}):+ doc_id = ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(+ settings_snapshot={+ "research_library.auto_persist_research_sources": non_bool+ }+ ),+ check_setting=True,+ )+ assert doc_id is None+ assert db.query(Document).count() == 0+++def test_do_persist_gated_missing_key_uses_live_true(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ mock_settings = _live_settings(monkeypatch, auto=True)+ doc_id = ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(settings_snapshot={"_username": "testuser"}),+ check_setting=True,+ )+ assert doc_id is not None+ assert mock_settings.get_setting.called+++def test_do_persist_gated_missing_key_uses_live_false(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=False)+ doc_id = ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(settings_snapshot={"_username": "testuser"}),+ check_setting=True,+ )+ assert doc_id is None+ assert db.query(Document).count() == 0+++def test_do_persist_gated_no_snapshot_live_true(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ doc_id = ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(), check_setting=True+ )+ assert doc_id is not None+++def test_do_persist_rejects_non_pdf(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ assert (+ ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(pdf_content=b"<html>nope</html>")+ )+ is None+ )+++def test_do_persist_no_identity_returns_none(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ assert (+ ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(username=None, settings_snapshot=None)+ )+ is None+ )+++def test_do_persist_empty_text_with_flag_rejected(db, monkeypatch):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: " ",+ )+ assert (+ ds._do_persist_downloaded_pdf_on_the_spot(+ **_do_kwargs(text=" "), check_setting=True+ )+ is None+ )+ assert db.query(Document).count() == 0+++# ---------------------------------------------------------------------------+# persist_research_sources: scheduler, tracker link, failures+# ---------------------------------------------------------------------------+++def test_sweep_scheduler_off_forces_text_path(db, monkeypatch):+ _make_resource(db, 61, "https://arxiv.org/pdf/2301.00001.pdf")+ _mock_db_session(monkeypatch, db)+ service = _stub_service(+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": False,+ }+ )+ service.download_resource = Mock()+ service.download_as_text = Mock(return_value=(True, None))++ summary = service.persist_research_sources("res-123")+ assert summary["persisted"] == 1+ service.download_resource.assert_not_called()+ service.download_as_text.assert_called_once_with(61)+++def test_sweep_tracker_redirect_links_without_network(db, monkeypatch):+ payload = b"%PDF-1.4 redirect target"+ file_hash = hashlib.sha256(payload).hexdigest()+ doc = Document(+ id="doc-redirect",+ source_type_id="st-research",+ document_hash=file_hash,+ original_url="https://doi.org/10.9/orig",+ file_size=len(payload),+ file_type="pdf",+ mime_type="application/pdf",+ title="Redirect Target",+ status=DocumentStatus.COMPLETED,+ text_content="redirect text",+ storage_mode="database",+ file_path="database",+ )+ first = ResearchResource(+ id=70,+ research_id="res-123",+ url="https://doi.org/10.9/orig",+ title="Orig",+ created_at=datetime.now(UTC).isoformat(),+ )+ r = ResearchResource(+ id=71,+ research_id="res-123",+ url="https://publisher.example.com/final.pdf",+ title="Final",+ created_at=datetime.now(UTC).isoformat(),+ )+ from local_deep_research.utilities.download_url import get_url_hash+ from local_deep_research.utilities.url_utils import canonical_url_key++ tracker = DownloadTracker(+ url="https://publisher.example.com/final.pdf",+ url_hash=get_url_hash(+ canonical_url_key("https://publisher.example.com/final.pdf")+ ),+ first_resource_id=70,+ file_hash=file_hash,+ file_size=len(payload),+ is_downloaded=True,+ )+ db.add_all([doc, first, r, tracker])+ db.commit()+ _mock_db_session(monkeypatch, db)+ service = _stub_service(+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ }+ )+ service.download_resource = Mock(return_value=(True, None))+ service.download_as_text = Mock(return_value=(True, None))++ summary = service.persist_research_sources("res-123")+ assert summary == {+ "total": 2,+ "persisted": 2,+ "failed": 0,+ "skipped": 0,+ }+ called_ids = [+ c.args[0] for c in service.download_resource.call_args_list+ ] + [c.args[0] for c in service.download_as_text.call_args_list]+ assert 71 not in called_ids+ assert (+ db.query(ResearchResource).filter_by(id=71).first().document_id+ == "doc-redirect"+ )+++def test_sweep_both_pdf_and_text_fail_counts_failed(db, monkeypatch):+ _make_resource(db, 72, "https://example.com/broken-page")+ _mock_db_session(monkeypatch, db)+ service = _stub_service(+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ }+ )+ service.download_resource = Mock(return_value=(False, "conn reset"))+ service.download_as_text = Mock(return_value=(False, "404"))++ summary = service.persist_research_sources("res-123")+ assert summary == {"total": 1, "persisted": 0, "failed": 1, "skipped": 0}+++def test_sweep_awaiting_pdf_refills_via_download_resource(db, monkeypatch):+ doc = Document(+ id="doc-await",+ source_type_id="st-research",+ resource_id=73,+ document_hash="hash-await",+ original_url="https://arxiv.org/pdf/2301.00002.pdf",+ file_size=10,+ file_type="pdf",+ mime_type="application/pdf",+ title="Awaiting",+ status=DocumentStatus.COMPLETED,+ text_content="some text",+ storage_mode="none",+ file_path=FILE_PATH_TEXT_ONLY,+ )+ r = ResearchResource(+ id=73,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00002.pdf",+ title="Awaiting",+ document_id="doc-await",+ created_at=datetime.now(UTC).isoformat(),+ )+ db.add_all([doc, r])+ db.commit()+ _mock_db_session(monkeypatch, db)+ service = _stub_service(+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ }+ )+ service.download_resource = Mock(return_value=(True, None))+ service.download_as_text = Mock()++ summary = service.persist_research_sources("res-123")+ assert summary["persisted"] == 1+ service.download_resource.assert_called_once_with(73, collection_id=None)+ service.download_as_text.assert_not_called()+++def test_sweep_completed_non_awaiting_is_skipped(db, monkeypatch):+ doc = Document(+ id="doc-done",+ source_type_id="st-research",+ resource_id=74,+ document_hash="hash-done",+ original_url="https://example.com/done",+ file_size=10,+ file_type="text",+ status=DocumentStatus.COMPLETED,+ text_content="done",+ )+ r = ResearchResource(+ id=74,+ research_id="res-123",+ url="https://example.com/done",+ title="Done",+ document_id="doc-done",+ created_at=datetime.now(UTC).isoformat(),+ )+ db.add_all([doc, r])+ db.commit()+ _mock_db_session(monkeypatch, db)+ service = _stub_service(+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ }+ )+ service.download_resource = Mock()+ service.download_as_text = Mock()++ summary = service.persist_research_sources("res-123")+ assert summary == {"total": 1, "persisted": 0, "failed": 0, "skipped": 1}+ service.download_resource.assert_not_called()+ service.download_as_text.assert_not_called()+++def test_sweep_unexpected_exception_in_one_resource_continues(db, monkeypatch):+ _make_resource(db, 75, "https://arxiv.org/pdf/2301.00003.pdf")+ _make_resource(db, 76, "https://example.com/ok-page")+ _mock_db_session(monkeypatch, db)+ service = _stub_service(+ {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ }+ )+ service.download_resource = Mock(side_effect=RuntimeError("disk gone"))+ service.download_as_text = Mock(return_value=(True, None))++ summary = service.persist_research_sources("res-123")+ assert summary == {"total": 2, "persisted": 1, "failed": 1, "skipped": 0}+++# ---------------------------------------------------------------------------+# auto_persist wrapper+# ---------------------------------------------------------------------------+++def test_auto_persist_enabled_path_delegates(monkeypatch):+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: (+ True if k == "research_library.auto_persist_research_sources" else d+ )+ mock_settings.get_settings_snapshot.return_value = {"snapshot": True}+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ summary = {"total": 2, "persisted": 2, "failed": 0, "skipped": 0}+ svc_cls = MagicMock()+ svc_cls.return_value.__enter__.return_value.persist_research_sources.return_value = summary+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.DownloadService",+ svc_cls,+ )+ assert (+ auto_persist_research_sources("alice", "r1", db_password="pw")+ == summary+ )+ svc_cls.assert_called_once_with(+ "alice", password="pw", settings_snapshot={"snapshot": True}+ )+++def test_auto_persist_exception_redacts_password(monkeypatch):+ secret = "SuperSecretPassword99"+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ Mock(side_effect=RuntimeError(f"boom {secret}")),+ )+ res = auto_persist_research_sources("alice", "r1", db_password=secret)+ assert res["persisted"] == 0+ assert secret not in res.get("error", "")+ assert "***REDACTED***" in res.get("error", "")+++def test_auto_persist_stringly_false_is_disabled(monkeypatch):+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: (+ "false" if k == "research_library.auto_persist_research_sources" else d+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ svc_cls = MagicMock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.DownloadService",+ svc_cls,+ )+ res = auto_persist_research_sources("alice", "r1", db_password="pw")+ assert res["persisted"] == 0+ assert res["skipped_reason"] == "disabled"+ svc_cls.assert_not_called()+++# ---------------------------------------------------------------------------+# Repo-level pins: setting default and changelog+# ---------------------------------------------------------------------------+++def test_auto_persist_setting_defaults_off():+ import json++ import local_deep_research++ root = list(local_deep_research.__path__)[0]+ from pathlib import Path++ defaults = json.loads(+ Path(+ root, "defaults", "research_library", "library_settings.json"+ ).read_text()+ )+ entry = defaults["research_library.auto_persist_research_sources"]+ assert entry["value"] is False+ assert entry["editable"] is True+++def test_changelog_fragment_exists():+ import local_deep_research++ from pathlib import Path++ root = Path(list(local_deep_research.__path__)[0]).parents[1]+ fragment = root / "changelog.d" / "7416.feature.md"+ assert fragment.exists()+ text = fragment.read_text()+ assert "auto" in text.lower() and "persist" in text.lower()diff --git a/tests/research_library/services/test_auto_persist_research_sources.py b/tests/research_library/services/test_auto_persist_research_sources.pynew file mode 100644index 0000000000..2f98342c4f--- /dev/null+++ b/tests/research_library/services/test_auto_persist_research_sources.py@@ -0,0 +1,2051 @@+"""Tests for auto_persist_research_sources and DownloadService.persist_research_sources."""++from datetime import UTC, datetime+from unittest.mock import MagicMock, Mock++import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from local_deep_research.constants import FILE_PATH_TEXT_ONLY, ResearchStatus+from local_deep_research.database.models import Base+from local_deep_research.database.models.download_tracker import DownloadTracker+from local_deep_research.database.models.library import (+ Collection,+ Document,+ DocumentStatus,+ SourceType,+)+from local_deep_research.database.models.research import (+ ResearchHistory,+ ResearchResource,+)+from local_deep_research.research_library.services.download_service import (+ DownloadService,+ auto_persist_research_sources,+)++[email protected](autouse=True)+def _isolate_auto_persist_semaphore():+ from local_deep_research.web.queue.processor_v2 import (+ _reset_auto_persist_pending,+ )++ _reset_auto_persist_pending()+ yield+ _reset_auto_persist_pending()+++def in_memory_db():+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ Session = sessionmaker(bind=engine)+ session = Session()++ # Create default Library collection and source type+ library = Collection(id="default-library", name="Library")+ session.add(library)++ st = SourceType(+ id="st-research",+ name="research_download",+ display_name="Research Download",+ )+ session.add(st)++ # Create sample research+ research = ResearchHistory(+ id="res-123",+ query="Quantum Computing",+ mode="quick",+ status=ResearchStatus.COMPLETED,+ created_at=datetime.now(UTC).isoformat(),+ )+ session.add(research)+ session.commit()++ yield session+ session.close()+++def fk_enforced_db(tmp_path):+ """SQLite session with PRAGMA foreign_keys = ON enforced."""+ from sqlalchemy import event, text++ db_path = tmp_path / "fk_enforced.db"+ engine = create_engine(f"sqlite:///{db_path}")++ @event.listens_for(engine, "connect")+ def _enable_fk(dbapi_connection, _):+ dbapi_connection.execute("PRAGMA foreign_keys = ON")++ Base.metadata.create_all(engine)+ Session = sessionmaker(bind=engine)+ session = Session()++ assert session.execute(text("PRAGMA foreign_keys")).scalar() == 1++ library = Collection(id="default-library", name="Library")+ session.add(library)++ st = SourceType(+ id="st-research",+ name="research_download",+ display_name="Research Download",+ )+ session.add(st)++ research = ResearchHistory(+ id="res-123",+ query="Quantum Computing",+ mode="quick",+ status=ResearchStatus.COMPLETED,+ created_at=datetime.now(UTC).isoformat(),+ )+ session.add(research)+ session.commit()++ yield session+ session.close()+ engine.dispose()+++def test_auto_persist_no_resources(in_memory_db, monkeypatch):+ """When research has no resources, persist_research_sources returns zeros."""+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "database"+ mock_settings.get_settings_snapshot.return_value = {}++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service.library_root = "/fake/root"++ res = service.persist_research_sources("res-123")+ assert res == {"total": 0, "persisted": 0, "failed": 0, "skipped": 0}+++def test_auto_persist_pdf_storage_enabled_downloads_pdf(+ in_memory_db, monkeypatch+):+ """Downloadable resource calls download_resource when PDF storage is enabled."""+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Quantum Paper",+ created_at=datetime.now(UTC).isoformat(),+ )+ r2 = ResearchResource(+ id=2,+ research_id="res-123",+ url="https://example.com/news",+ title="Web Article",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add_all([r1, r2])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "database"+ mock_settings.get_settings_snapshot.return_value = {}++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service.library_root = "/fake/root"+ service._is_downloadable = lambda res: "arxiv" in res.url+ service.download_resource = Mock(return_value=(True, None))+ service.download_as_text = Mock(return_value=(True, None))++ res = service.persist_research_sources("res-123")+ assert res == {"total": 2, "persisted": 2, "failed": 0, "skipped": 0}+ service.download_resource.assert_called_once_with(1, collection_id=None)+ service.download_as_text.assert_called_once_with(2)+++def test_auto_persist_pdf_storage_none_extracts_text_for_all(+ in_memory_db, monkeypatch+):+ """When PDF storage mode is 'none', all resources use download_as_text."""+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Quantum Paper",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add(r1)+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "none"+ mock_settings.get_settings_snapshot.return_value = {}++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service.library_root = "/fake/root"+ service._is_downloadable = lambda res: True+ service.download_resource = Mock()+ service.download_as_text = Mock(return_value=(True, None))++ res = service.persist_research_sources("res-123")+ assert res == {"total": 1, "persisted": 1, "failed": 0, "skipped": 0}+ service.download_resource.assert_not_called()+ service.download_as_text.assert_called_once_with(1)+++def test_auto_persist_skips_already_completed_resource(+ in_memory_db, monkeypatch+):+ """Resources with a completed document are skipped."""+ doc = Document(+ id="doc-1",+ source_type_id="st-research",+ resource_id=1,+ research_id="res-123",+ document_hash="hash-1",+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="database",+ file_path="database",+ text_content="Some content",+ )+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Quantum Paper",+ document_id="doc-1",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add_all([doc, r1])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "database"++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service._is_downloadable = lambda res: True+ service.download_resource = Mock()+ service.download_as_text = Mock()++ res = service.persist_research_sources("res-123")+ assert res == {"total": 1, "persisted": 0, "failed": 0, "skipped": 1}+ service.download_resource.assert_not_called()+ service.download_as_text.assert_not_called()+++def test_auto_persist_refills_document_awaiting_pdf(in_memory_db, monkeypatch):+ """A document that awaits its PDF is downloaded to refill the PDF."""+ doc = Document(+ id="doc-1",+ source_type_id="st-research",+ resource_id=1,+ research_id="res-123",+ document_hash="hash-1",+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="none",+ file_path=FILE_PATH_TEXT_ONLY,+ text_content="Some extracted text",+ )+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Quantum Paper",+ document_id="doc-1",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add_all([doc, r1])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "database"++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service._is_downloadable = lambda res: True+ service.download_resource = Mock(return_value=(True, None))+ service.download_as_text = Mock()++ res = service.persist_research_sources("res-123")+ assert res == {"total": 1, "persisted": 1, "failed": 0, "skipped": 0}+ service.download_resource.assert_called_once_with(1, collection_id=None)+++def test_auto_persist_pdf_fails_falls_back_to_text(in_memory_db, monkeypatch):+ """When PDF download fails, it falls back to text extraction."""+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Quantum Paper",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add(r1)+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "database"++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service._is_downloadable = lambda res: True+ service.download_resource = Mock(return_value=(False, "Connection reset"))+ service.download_as_text = Mock(return_value=(True, None))++ res = service.persist_research_sources("res-123")+ assert res == {"total": 1, "persisted": 1, "failed": 0, "skipped": 0}+ service.download_resource.assert_called_once_with(1, collection_id=None)+ service.download_as_text.assert_called_once_with(1)+++def test_auto_persist_both_pdf_and_text_fail(in_memory_db, monkeypatch):+ """When both PDF and fallback text fail, counts as failed."""+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Quantum Paper",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add(r1)+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "database"++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service._is_downloadable = lambda res: True+ service.download_resource = Mock(return_value=(False, "Connection reset"))+ service.download_as_text = Mock(return_value=(False, "404 Not Found"))++ res = service.persist_research_sources("res-123")+ assert res == {"total": 1, "persisted": 0, "failed": 1, "skipped": 0}+++def test_auto_persist_exception_in_one_resource_continues(+ in_memory_db, monkeypatch+):+ """An unexpected exception processing one resource does not abort others."""+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Bad Resource",+ created_at=datetime.now(UTC).isoformat(),+ )+ r2 = ResearchResource(+ id=2,+ research_id="res-123",+ url="https://example.com/good",+ title="Good Resource",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add_all([r1, r2])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "database"++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service._is_downloadable = lambda res: res.id == 1+ service.download_resource = Mock(side_effect=RuntimeError("disk error"))+ service.download_as_text = Mock(return_value=(True, None))++ res = service.persist_research_sources("res-123")+ assert res == {"total": 2, "persisted": 1, "failed": 1, "skipped": 0}+++def test_auto_persist_top_level_catches_all_exceptions(monkeypatch):+ """auto_persist_research_sources swallows any top-level error and redacts password."""+ secret_pw = "SuperSecretMasterKey123"+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ Mock(side_effect=RuntimeError(f"Fatal crash with {secret_pw}")),+ )++ res = auto_persist_research_sources("alice", "r1", db_password=secret_pw)+ assert res["total"] == 0+ assert res["persisted"] == 0+ assert secret_pw not in res.get("error", "")+ assert "***REDACTED***" in res.get("error", "")+++def test_notify_research_completed_calls_auto_persist(monkeypatch):+ """QueueProcessorV2.notify_research_completed calls auto_persist_research_sources."""+ from local_deep_research.web.queue.processor_v2 import QueueProcessorV2++ mock_persist = Mock()+ mock_convert = Mock()++ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: Mock(), __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.send_research_completed_notification_from_session",+ Mock(),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.search.services.research_history_indexer.auto_convert_research",+ mock_convert,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.auto_persist_research_sources",+ mock_persist,+ )+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2._auto_persist_enabled_for",+ lambda u: True,+ )++ proc = QueueProcessorV2()+ proc.notify_research_completed("alice", "res-456", user_password="pwd")++ mock_convert.assert_called_once_with("alice", "res-456", db_password="pwd")+ # Auto-persist runs in an executor worker; wait briefly for the call.+ import time as _time++ deadline = _time.time() + 5+ while _time.time() < deadline and mock_persist.call_count == 0:+ _time.sleep(0.05)+ mock_persist.assert_called_once_with("alice", "res-456", db_password="pwd")+++def test_tracker_url_deduplication_in_download_resource(+ in_memory_db, monkeypatch+):+ """Stage 1 tracker dedup reuses an existing document for the same URL."""+ doc1 = Document(+ id="doc-1",+ source_type_id="st-research",+ resource_id=1,+ research_id="res-123",+ document_hash="hash-1",+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="database",+ file_path="database",+ text_content="Doc 1 text",+ )+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Paper 1",+ document_id="doc-1",+ created_at=datetime.now(UTC).isoformat(),+ )+ r2 = ResearchResource(+ id=2,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Paper 2",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ tracker = DownloadTracker(+ url="https://arxiv.org/pdf/2301.00001.pdf",+ url_hash="some-hash",+ first_resource_id=1,+ is_downloaded=True,+ )+ in_memory_db.add_all([doc1, r1, r2, tracker])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.find_tracker_by_url",+ lambda sess, url: tracker,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = "database"++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service._settings_snapshot = {+ "research_library.auto_persist_research_sources": True+ }+ service.retry_manager = Mock()+ service._download_pdf = Mock()++ success, error = service.download_resource(2)+ assert success is True+ assert error is None+ # Verify r2 was linked to doc-1 and network download was skipped+ service._download_pdf.assert_not_called()+ assert r2.document_id == "doc-1"+++def test_download_resource_dedup_adds_requested_collection(+ in_memory_db, monkeypatch+):+ """Tracker dedup must not skip the requested collection membership."""+ from local_deep_research.database.models.library import (+ DocumentCollection,+ )++ selected = Collection(id="selected-col", name="Selected")+ in_memory_db.add(selected)+ doc1 = Document(+ id="doc-1",+ source_type_id="st-research",+ resource_id=1,+ research_id="res-123",+ document_hash="hash-1",+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="database",+ file_path="database",+ text_content="Doc 1 text",+ )+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Paper 1",+ document_id="doc-1",+ created_at=datetime.now(UTC).isoformat(),+ )+ r2 = ResearchResource(+ id=2,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Paper 2",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ tracker = DownloadTracker(+ url="https://arxiv.org/pdf/2301.00001.pdf",+ url_hash="some-hash",+ first_resource_id=1,+ is_downloaded=True,+ )+ in_memory_db.add_all([doc1, r1, r2, tracker])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.find_tracker_by_url",+ lambda sess, url: tracker,+ )++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = Mock()+ service._settings_snapshot = {+ "research_library.auto_persist_research_sources": True+ }+ service.retry_manager = Mock()+ service._download_pdf = Mock()++ success, error = service.download_resource(2, collection_id="selected-col")+ assert (success, error) == (True, None)+ service._download_pdf.assert_not_called()+ assert r2.document_id == "doc-1"+ link = (+ in_memory_db.query(DocumentCollection)+ .filter_by(document_id="doc-1", collection_id="selected-col")+ .first()+ )+ assert link is not None+++def test_download_resource_dedup_deleted_collection_does_not_break_bookkeeping(+ fk_enforced_db, monkeypatch+):+ """When the requested collection does not exist or was deleted, tracker dedup still+ links the resource and completes queue/retry bookkeeping without IntegrityError.+ """+ from local_deep_research.database.models.library import DocumentCollection++ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Paper 1",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ r2 = ResearchResource(+ id=2,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00001.pdf",+ title="Paper 2",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ fk_enforced_db.add_all([r1, r2])+ fk_enforced_db.commit()++ doc1 = Document(+ id="doc-1",+ source_type_id="st-research",+ resource_id=1,+ research_id="res-123",+ document_hash="hash-1",+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="database",+ file_path="database",+ text_content="Doc 1 text",+ )+ fk_enforced_db.add(doc1)+ fk_enforced_db.commit()++ r1.document_id = "doc-1"+ tracker = DownloadTracker(+ url="https://arxiv.org/pdf/2301.00001.pdf",+ url_hash="some-hash",+ first_resource_id=1,+ is_downloaded=True,+ )+ fk_enforced_db.add(tracker)+ fk_enforced_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: fk_enforced_db, __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.find_tracker_by_url",+ lambda sess, url: tracker,+ )++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = Mock()+ service._settings_snapshot = {+ "research_library.auto_persist_research_sources": True+ }+ service.retry_manager = Mock()+ service._download_pdf = Mock()++ success, error = service.download_resource(+ 2, collection_id="non-existent-collection"+ )+ assert (success, error) == (True, None)+ service._download_pdf.assert_not_called()+ assert r2.document_id == "doc-1"+ service.retry_manager.record_attempt.assert_called_once()++ # Assert skip path: non-existent collection link was never created/orphaned+ orphan = (+ fk_enforced_db.query(DocumentCollection)+ .filter_by(document_id="doc-1", collection_id="non-existent-collection")+ .first()+ )+ assert orphan is None+++def test_download_resource_dedup_savepoint_rollback_on_collection_fk_error(+ fk_enforced_db, monkeypatch+):+ """When a collection is deleted mid-flight during link insertion, the nested savepoint+ rolls back on FK violation without aborting the outer transaction or dropping resource.document_id.+ """+ from sqlalchemy import text+ from local_deep_research.database.models.library import DocumentCollection+ import local_deep_research.research_library.services.download_service as ds_mod++ r1 = ResearchResource(+ id=10,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00010.pdf",+ title="Paper 10",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ r2 = ResearchResource(+ id=20,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.00010.pdf",+ title="Paper 20",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ fk_enforced_db.add_all([r1, r2])+ fk_enforced_db.commit()++ doc1 = Document(+ id="doc-10",+ source_type_id="st-research",+ resource_id=10,+ research_id="res-123",+ document_hash="hash-10",+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="database",+ file_path="database",+ text_content="Doc 10 text",+ )+ fk_enforced_db.add(doc1)+ fk_enforced_db.commit()++ r1.document_id = "doc-10"+ tracker = DownloadTracker(+ url="https://arxiv.org/pdf/2301.00010.pdf",+ url_hash="some-hash-10",+ first_resource_id=10,+ is_downloaded=True,+ )+ temp_col = Collection(id="temp-col", name="Temp")+ fk_enforced_db.add_all([tracker, temp_col])+ fk_enforced_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: fk_enforced_db, __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.find_tracker_by_url",+ lambda sess, url: tracker,+ )++ # Simulate mid-flight deletion: coll_exists passed, but collection is deleted+ # before the insert flush inside the savepoint, triggering SQLite FOREIGN KEY failure+ real_ensure = ds_mod.ensure_in_collection++ def racing_ensure(sess, doc_id, col_id):+ sess.execute(+ text("DELETE FROM collections WHERE id = :cid"), {"cid": col_id}+ )+ return real_ensure(sess, doc_id, col_id)++ monkeypatch.setattr(ds_mod, "ensure_in_collection", racing_ensure)++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = Mock()+ service._settings_snapshot = {+ "research_library.auto_persist_research_sources": True+ }+ service.retry_manager = Mock()+ service._download_pdf = Mock()++ success, error = service.download_resource(20, collection_id="temp-col")+ assert (success, error) == (True, None)+ service._download_pdf.assert_not_called()+ assert r2.document_id == "doc-10"+ service.retry_manager.record_attempt.assert_called_once()++ # The savepoint rolled back cleanly; no orphaned link exists+ orphan = (+ fk_enforced_db.query(DocumentCollection)+ .filter_by(document_id="doc-10", collection_id="temp-col")+ .first()+ )+ assert orphan is None+++def test_tracker_url_deduplication_in_try_existing_text(+ in_memory_db, monkeypatch+):+ """Stage 1 tracker dedup in _try_existing_text reuses text from the same URL."""+ doc1 = Document(+ id="doc-1",+ source_type_id="st-research",+ resource_id=1,+ research_id="res-123",+ document_hash="hash-1",+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="text",+ text_content="Existing text from earlier download",+ extraction_method="direct",+ )+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://example.com/article",+ title="Article 1",+ document_id="doc-1",+ created_at=datetime.now(UTC).isoformat(),+ )+ r2 = ResearchResource(+ id=2,+ research_id="res-123",+ url="https://example.com/article",+ title="Article 2",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ tracker = DownloadTracker(+ url="https://example.com/article",+ url_hash="article-hash",+ first_resource_id=1,+ is_downloaded=True,+ )+ in_memory_db.add_all([doc1, r1, r2, tracker])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.find_tracker_by_url",+ lambda sess, url: tracker,+ )++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service._settings_snapshot = {+ "research_library.auto_persist_research_sources": True+ }++ result = service._try_existing_text(in_memory_db, 2)+ assert result == (True, None)+ assert r2.document_id == "doc-1"+++def test_try_existing_text_url_reuse_disabled_when_setting_off(+ in_memory_db, monkeypatch+):+ """With auto-persist off, URL reuse must not link another document."""+ doc1 = Document(+ id="doc-1",+ source_type_id="st-research",+ resource_id=1,+ research_id="res-123",+ document_hash="hash-1",+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="text",+ text_content="Existing text from earlier download",+ extraction_method="direct",+ )+ r1 = ResearchResource(+ id=1,+ research_id="res-123",+ url="https://example.com/article",+ title="Article 1",+ document_id="doc-1",+ created_at=datetime.now(UTC).isoformat(),+ )+ r2 = ResearchResource(+ id=2,+ research_id="res-123",+ url="https://example.com/article",+ title="Article 2",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ tracker = DownloadTracker(+ url="https://example.com/article",+ url_hash="article-hash",+ first_resource_id=1,+ is_downloaded=True,+ )+ in_memory_db.add_all([doc1, r1, r2, tracker])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.find_tracker_by_url",+ lambda sess, url: tracker,+ )++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service._settings_snapshot = {+ "research_library.auto_persist_research_sources": False+ }++ result = service._try_existing_text(in_memory_db, 2)+ assert result is None+ assert r2.document_id is None+++def test_persist_pdf_on_the_spot_creates_document_without_resource(+ in_memory_db, monkeypatch+):+ """persist_downloaded_pdf_on_the_spot creates Document and stores PDF even before research completes."""+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "research_library.max_pdf_size_mb": 50,+ }.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )++ pdf_bytes = b"%PDF-1.4 test content for on-the-spot persistence"+ url = "https://arxiv.org/pdf/2301.99999.pdf"++ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ doc_id = persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=pdf_bytes,+ text="Extracted on the spot text",+ title="On The Spot Paper",+ username="testuser",+ )++ assert doc_id is not None+ doc = in_memory_db.query(Document).filter_by(id=doc_id).first()+ assert doc is not None+ assert doc.status == DocumentStatus.COMPLETED+ assert doc.text_content == "Extracted on the spot text"+ assert doc.title == "On The Spot Paper"+ assert doc.file_type == "pdf"+ assert doc.original_url == url+++def test_persist_pdf_on_the_spot_creates_tracker_when_resource_provided(+ in_memory_db, monkeypatch+):+ """When resource_id is provided, DownloadTracker is also created."""+ r = ResearchResource(+ id=99,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.99999.pdf",+ title="Paper 99",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add(r)+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "research_library.max_pdf_size_mb": 50,+ }.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )++ pdf_bytes = b"%PDF-1.4 test content with tracker"+ url = "https://arxiv.org/pdf/2301.99999.pdf"++ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ doc_id = persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=pdf_bytes,+ text="Text with tracker",+ title="Paper 99",+ username="testuser",+ resource_id=99,+ )++ assert doc_id is not None+ tracker = in_memory_db.query(DownloadTracker).filter_by(url=url).first()+ assert tracker is not None+ assert tracker.is_downloaded is True+ assert tracker.first_resource_id == 99+++def test_persist_pdf_on_the_spot_deduplicates_by_hash(+ in_memory_db, monkeypatch+):+ """When the same PDF bytes are downloaded from two URLs, reuse the Document."""+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "research_library.max_pdf_size_mb": 50,+ }.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )++ pdf_bytes = b"%PDF-1.4 identical bytes across two mirrors"+ url1 = "https://mirror1.example.com/paper.pdf"+ url2 = "https://mirror2.example.com/paper.pdf"++ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ doc_id_1 = persist_downloaded_pdf_on_the_spot(+ url=url1,+ pdf_content=pdf_bytes,+ text="Sample text",+ title="Mirror 1",+ username="testuser",+ )+ doc_id_2 = persist_downloaded_pdf_on_the_spot(+ url=url2,+ pdf_content=pdf_bytes,+ text="Sample text",+ title="Mirror 2",+ username="testuser",+ )++ # Document should be the same+ assert doc_id_1 == doc_id_2+ docs = in_memory_db.query(Document).all()+ assert len(docs) == 1+++def test_persist_pdf_on_the_spot_with_extra_urls(in_memory_db, monkeypatch):+ """extra_urls (e.g. redirected URLs) are also tracked when resource exists."""+ r = ResearchResource(+ id=101,+ research_id="res-123",+ url="https://doi.org/10.1234/5678",+ title="Redirected Paper",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add(r)+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "research_library.max_pdf_size_mb": 50,+ }.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )++ pdf_bytes = b"%PDF-1.4 redirected paper"+ orig_url = "https://doi.org/10.1234/5678"+ final_url = "https://publisher.com/fulltext.pdf"++ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ doc_id = persist_downloaded_pdf_on_the_spot(+ url=orig_url,+ pdf_content=pdf_bytes,+ text="Redirected text",+ extra_urls=[final_url],+ username="testuser",+ resource_id=101,+ )+ assert doc_id is not None+ t_orig = in_memory_db.query(DownloadTracker).filter_by(url=orig_url).first()+ t_final = (+ in_memory_db.query(DownloadTracker).filter_by(url=final_url).first()+ )+ assert t_orig is not None and t_orig.is_downloaded is True+ assert t_final is not None and t_final.is_downloaded is True+++def test_auto_persist_links_on_the_spot_downloaded_pdf_without_network(+ in_memory_db, monkeypatch+):+ """auto_persist_research_sources links to on-the-spot document with 0 network calls."""+ # Pre-populate Document on the spot (before research completes)+ pdf_bytes = b"%PDF-1.4 pre-persisted paper"+ url = "https://arxiv.org/pdf/2301.12345.pdf"++ import hashlib++ f_hash = hashlib.sha256(pdf_bytes).hexdigest()++ doc = Document(+ id="doc-pre-persisted",+ source_type_id="st-research",+ document_hash=f_hash,+ original_url=url,+ file_size=len(pdf_bytes),+ file_type="pdf",+ status=DocumentStatus.COMPLETED,+ text_content="Pre-persisted text",+ title="Pre-persisted Paper",+ )+ r = ResearchResource(+ id=10,+ research_id="res-123",+ url=url,+ title="Pre-persisted Paper",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add_all([doc, r])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "database"+ mock_settings.get_settings_snapshot.return_value = {}++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service.library_root = "/fake/root"+ service._download_pdf = Mock() # Must not be called!++ summary = service.persist_research_sources("res-123")+ assert summary["persisted"] == 1+ assert summary["failed"] == 0++ # Ensure network download was skipped and resource linked to on-the-spot document+ service._download_pdf.assert_not_called()+ assert r.document_id == "doc-pre-persisted"+++def test_persist_pdf_on_the_spot_rejects_non_pdf():+ """Non-PDF bytes return None and do not write to DB."""+ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ res = persist_downloaded_pdf_on_the_spot(+ url="https://example.com/notpdf",+ pdf_content=b"<html>Not a PDF</html>",+ username="testuser",+ )+ assert res is None+++def test_persist_pdf_on_the_spot_no_username():+ """Missing username context returns None gracefully."""+ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ res = persist_downloaded_pdf_on_the_spot(+ url="https://example.com/paper.pdf",+ pdf_content=b"%PDF-1.4 test",+ username=None,+ )+ assert res is None+++def test_persist_pdf_on_the_spot_run_in_background(monkeypatch):+ """When run_in_background=True, returns None immediately and submits task to executor."""+ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ mock_executor = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service._get_pdf_persistence_executor",+ lambda: mock_executor,+ )++ pdf_bytes = b"%PDF-1.4 async background test"+ res = persist_downloaded_pdf_on_the_spot(+ url="https://example.com/async_paper.pdf",+ pdf_content=pdf_bytes,+ username="testuser",+ password="secret_password",+ settings_snapshot={"research_library.pdf_storage_mode": "database"},+ run_in_background=True,+ )+ assert res is None # Async returns immediately++ # Bounded pool submits a zero-arg closure holding explicit identity.+ mock_executor.submit.assert_called_once()+ args, kwargs = mock_executor.submit.call_args+ assert len(args) == 1 and not kwargs+ assert callable(args[0])+++def test_identity_propagation_through_content_fetcher():+ """ContentFetcher explicitly propagates username, password, and settings_snapshot to downloaders."""+ from local_deep_research.content_fetcher.fetcher import ContentFetcher+ from local_deep_research.content_fetcher.url_classifier import URLType++ fetcher = ContentFetcher(+ username="carol",+ password="carol_password",+ settings_snapshot={"test_key": "test_val"},+ )+ assert fetcher.username == "carol"+ assert fetcher.password == "carol_password"+ assert fetcher.settings_snapshot == {"test_key": "test_val"}++ for u_type in (URLType.PDF, URLType.HTML, URLType.ARXIV):+ dl = fetcher._get_downloader(u_type)+ if dl:+ assert dl.username == "carol"+ assert dl.password == "carol_password"+ assert dl.settings_snapshot == {"test_key": "test_val"}+++def test_is_downloadable_is_pure_url_check(in_memory_db, monkeypatch):+ """DownloadService._is_downloadable is a pure URL check without DB queries."""+ from local_deep_research.research_library.services.download_service import (+ DownloadService,+ )+ from local_deep_research.database.models.research import ResearchResource++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.RetryManager",+ Mock(),+ )+ service = DownloadService("testuser", password="test_password")+ res_pdf = ResearchResource(+ id=1,+ research_id="r1",+ url="https://example.com/paper.pdf",+ title="PDF Paper",+ )+ res_html = ResearchResource(+ id=2,+ research_id="r1",+ url="https://example.com/page.html",+ title="HTML Page",+ )++ assert service._is_downloadable(res_pdf) is True+ assert service._is_downloadable(res_html) is False+++def test_persist_pdf_on_the_spot_honors_none_storage_mode(+ in_memory_db, monkeypatch+):+ """When pdf_storage_mode is 'none', PDF bytes are not saved but text is persisted."""+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.pdf_storage_mode": "none",+ "research_library.max_pdf_size_mb": 50,+ }.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )++ pdf_bytes = b"%PDF-1.4 text only test paper"+ url = "https://example.com/text_only_paper.pdf"+ text_content = (+ "This is text that must be persisted regardless of PDF storage mode."+ )++ from local_deep_research.constants import FILE_PATH_TEXT_ONLY+ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ doc_id = persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=pdf_bytes,+ text=text_content,+ title="Text Only Paper",+ username="testuser",+ settings_snapshot={"research_library.pdf_storage_mode": "none"},+ )++ assert doc_id is not None+ doc = in_memory_db.query(Document).filter_by(id=doc_id).first()+ assert doc is not None+ assert doc.status == DocumentStatus.COMPLETED+ assert doc.text_content == text_content+ # None-mode PDF downloads keep the pdf label (awaiting-refill shape) as+ # main did; only extracted-text rows are file_type text.+ assert doc.file_type == "pdf"+ assert doc.mime_type == "application/pdf"+ assert doc.file_path == FILE_PATH_TEXT_ONLY+ assert doc.storage_mode == "none"+ assert doc.file_size == len(pdf_bytes)+++def test_persist_pdf_on_the_spot_extracts_text_if_missing_under_none_mode(+ in_memory_db, monkeypatch+):+ """When text is not provided under none mode, text is extracted from PDF bytes."""+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "Extracted fallback text content",+ )++ pdf_bytes = b"%PDF-1.4 paper without text"+ url = "https://example.com/no_text_paper.pdf"++ from local_deep_research.constants import FILE_PATH_TEXT_ONLY+ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ doc_id = persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=pdf_bytes,+ text=None,+ title="Fallback Extracted Paper",+ username="testuser",+ settings_snapshot={"research_library.pdf_storage_mode": "none"},+ )++ assert doc_id is not None+ doc = in_memory_db.query(Document).filter_by(id=doc_id).first()+ assert doc is not None+ assert doc.text_content == "Extracted fallback text content"+ assert doc.file_type == "pdf"+ assert doc.file_path == FILE_PATH_TEXT_ONLY+++def test_fetch_path_persists_single_write_with_redirect(+ in_memory_db, monkeypatch+):+ """ContentFetcher PDF fetch persists once with both original+final URLs tracked."""+ from local_deep_research.content_fetcher.fetcher import ContentFetcher++ orig_url = "https://doi.org/10.1234/5678"+ final_url = "https://cdn.example.com/final.pdf"+ pdf_bytes = b"%PDF-1.4 redirect test payload"++ r = ResearchResource(+ id=101,+ research_id="res-123",+ url=orig_url,+ title="Redirect Paper",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add(r)+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "research_library.max_pdf_size_mb": 50,+ }.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_default_library_id",+ lambda *a, **k: "default-library",+ )++ class FakeDownloader:+ _last_final_url = final_url++ def can_handle(self, url):+ return True++ def download_with_result(self, url, content_type=None):+ return Mock(+ is_success=True,+ content=pdf_bytes,+ status_code=200,+ skip_reason=None,+ )++ def get_metadata(self, url):+ return {"title": "Redirect Paper"}++ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "Redirect extracted text",+ )++ from local_deep_research.research_library.services import (+ download_service as ds_mod,+ )++ monkeypatch.setattr(+ ds_mod,+ "_get_pdf_persistence_executor",+ lambda: Mock(submit=lambda fn: fn()),+ )++ fetcher = ContentFetcher(+ username="testuser",+ password="pw",+ settings_snapshot={+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ },+ )+ monkeypatch.setattr(fetcher, "_get_downloader", lambda ut: FakeDownloader())++ result = fetcher.fetch(orig_url)+ assert result["status"] == "success"+ assert result["content"] == "Redirect extracted text"++ doc = in_memory_db.query(Document).filter_by(original_url=orig_url).first()+ assert doc is not None+ assert doc.text_content == "Redirect extracted text"++ t_orig = in_memory_db.query(DownloadTracker).filter_by(url=orig_url).first()+ t_final = (+ in_memory_db.query(DownloadTracker).filter_by(url=final_url).first()+ )+ assert t_orig is not None and t_orig.is_downloaded is True+ assert t_final is not None and t_final.is_downloaded is True+++def test_redirect_extra_urls_tracked_with_resource(in_memory_db, monkeypatch):+ """extra_urls create tracker rows for both original and final URLs."""+ r = ResearchResource(+ id=201,+ research_id="res-123",+ url="https://doi.org/10.9/redirect",+ title="Redirect",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add(r)+ in_memory_db.commit()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "research_library.max_pdf_size_mb": 50,+ }.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_default_library_id",+ lambda *a, **k: "default-library",+ )++ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ doc_id = persist_downloaded_pdf_on_the_spot(+ url="https://doi.org/10.9/redirect",+ pdf_content=b"%PDF-1.4 redirect bytes",+ text="redirect text",+ username="testuser",+ settings_snapshot={+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ },+ extra_urls=["https://pub.example.com/final.pdf"],+ resource_id=201,+ )+ assert doc_id is not None+ t_orig = (+ in_memory_db.query(DownloadTracker)+ .filter_by(url="https://doi.org/10.9/redirect")+ .first()+ )+ t_final = (+ in_memory_db.query(DownloadTracker)+ .filter_by(url="https://pub.example.com/final.pdf")+ .first()+ )+ assert t_orig is not None and t_orig.is_downloaded is True+ assert t_final is not None and t_final.is_downloaded is True+++def test_background_executor_end_to_end(in_memory_db, monkeypatch):+ """Background persist closure executes and writes the document."""+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "research_library.max_pdf_size_mb": 50,+ }.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_default_library_id",+ lambda *a, **k: "default-library",+ )++ from local_deep_research.research_library.services import (+ download_service as ds_mod,+ )++ captured = []+ mock_executor = Mock()++ def _capture(fn):+ captured.append(fn)+ return Mock()++ mock_executor.submit.side_effect = _capture+ monkeypatch.setattr(+ ds_mod, "_get_pdf_persistence_executor", lambda: mock_executor+ )+ res = ds_mod.persist_downloaded_pdf_on_the_spot(+ url="https://example.com/bg.pdf",+ pdf_content=b"%PDF-1.4 background e2e",+ text="background text",+ username="testuser",+ settings_snapshot={+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ },+ run_in_background=True,+ )+ assert res is None+ assert len(captured) == 1+ captured[0]() # run closure on main thread+ doc = (+ in_memory_db.query(Document)+ .filter_by(original_url="https://example.com/bg.pdf")+ .first()+ )+ assert doc is not None+ assert doc.text_content == "background text"+++def test_credential_fallback_chain(monkeypatch):+ """Central identity helper resolves explicit > egress > thread > snapshot."""+ from local_deep_research.utilities.thread_context import (+ clear_search_context,+ resolve_fetch_identity,+ set_search_context,+ )++ # Explicit wins.+ u, p, s = resolve_fetch_identity(+ username="exp", password="exppw", settings_snapshot={"a": 1}+ )+ assert (u, p) == ("exp", "exppw")++ # Egress context next.+ egress = Mock()+ egress.username = "eg"+ egress.password = "egpw"+ u, p, _ = resolve_fetch_identity(egress_context=egress)+ assert (u, p) == ("eg", "egpw")++ # Thread context next.+ set_search_context({"username": "thr", "user_password": "thrpw"})+ try:+ u, p, _ = resolve_fetch_identity()+ assert (u, p) == ("thr", "thrpw")+ finally:+ clear_search_context()++ # Snapshot _username last.+ u, p, _ = resolve_fetch_identity(settings_snapshot={"_username": "snap"})+ assert u == "snap"+++def test_executor_singleton():+ """Executor is a process-wide singleton."""+ from local_deep_research.research_library.services.download_service import (+ _get_pdf_persistence_executor,+ )++ assert _get_pdf_persistence_executor() is _get_pdf_persistence_executor()+++def test_garbage_pdf_rejected_on_the_spot(in_memory_db, monkeypatch):+ """%PDF-magic garbage without extractable text persists nothing."""+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: None,+ )+ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ res = persist_downloaded_pdf_on_the_spot(+ url="https://example.com/garbage.pdf",+ pdf_content=b"%PDF-garbage-no-text",+ text=None,+ username="testuser",+ settings_snapshot={"research_library.pdf_storage_mode": "database"},+ )+ assert res is None+ assert in_memory_db.query(Document).count() == 0+++def test_auto_persist_disabled_by_default(monkeypatch):+ """auto_persist wrapper is default-off without the explicit setting."""+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: (+ False if k == "research_library.auto_persist_research_sources" else d+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ res = auto_persist_research_sources("alice", "r1", db_password="pw")+ assert res["persisted"] == 0+ assert res.get("skipped_reason") == "disabled"+++def test_persist_pdf_on_the_spot_disabled_when_setting_off(+ in_memory_db, monkeypatch+):+ """When auto_persist is disabled and check_setting=True, nothing is persisted."""+ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ doc_id = persist_downloaded_pdf_on_the_spot(+ url="https://example.com/opt_out.pdf",+ pdf_content=b"%PDF-1.4 test payload",+ text="Sample text",+ username="testuser",+ settings_snapshot={+ "research_library.auto_persist_research_sources": False+ },+ check_setting=True,+ )+ assert doc_id is None+ assert in_memory_db.query(Document).count() == 0+++def test_download_service_persist_pdf_on_the_spot_method(+ in_memory_db, monkeypatch, tmp_path+):+ """DownloadService.persist_pdf_on_the_spot method functions on real service construction."""+ lib_dir = tmp_path / "library"+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "research_library.max_pdf_size_mb": 50,+ "research_library.storage_path": str(lib_dir),+ }.get(k, d)+ mock_settings.get_settings_snapshot.return_value = {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ }+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_default_library_id",+ lambda *a, **k: "default-library",+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.RetryManager",+ Mock(),+ )++ service = DownloadService(+ username="testuser",+ password="secret_password",+ settings_snapshot={+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ },+ )+ doc_id = service.persist_pdf_on_the_spot(+ url="https://example.com/service_method.pdf",+ pdf_content=b"%PDF-1.4 test payload",+ text="Extracted via service method",+ title="Service Paper",+ )+ assert doc_id is not None+ doc = in_memory_db.query(Document).filter_by(id=doc_id).first()+ assert doc is not None+ assert doc.text_content == "Extracted via service method"+++def test_redirect_sweep_dedup_without_resource(in_memory_db, monkeypatch):+ """Fetch with redirect URL dedupes sweep when resource uses the final redirect URL."""+ from local_deep_research.research_library.services.download_service import (+ persist_downloaded_pdf_on_the_spot,+ )++ orig_url = "https://doi.org/10.1000/182"+ final_url = "https://publisher.example.com/article.pdf"++ # A real resource created for the original URL+ res_orig = ResearchResource(+ id=554,+ research_id="res-123",+ url=orig_url,+ title="Redirected Paper",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add(res_orig)+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ "research_library.max_pdf_size_mb": 50,+ "research_library.storage_path": "/fake/library",+ }.get(k, d)+ mock_settings.get_settings_snapshot.return_value = {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ }+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_default_library_id",+ lambda *a, **k: "default-library",+ )++ # 1. Fetch persists on the spot with resource_id=None (matches res_orig via candidate_urls)+ doc_id = persist_downloaded_pdf_on_the_spot(+ url=orig_url,+ pdf_content=b"%PDF-1.4 redirect paper bytes",+ text="Redirect paper content",+ title="Redirected Paper",+ username="testuser",+ settings_snapshot={+ "research_library.auto_persist_research_sources": True+ },+ extra_urls=[final_url],+ resource_id=None,+ )+ assert doc_id is not None++ # 2. Research completed with resource recording the final redirect URL+ res = ResearchResource(+ id=555,+ research_id="res-123",+ url=final_url,+ title="Redirected Paper",+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add(res)+ in_memory_db.commit()++ # 3. Sweep runs for research: must link to existing document via tracker without calling download_resource+ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service.library_root = "/fake/root"+ service.download_resource = Mock()+ service.download_as_text = Mock()++ summary = service.persist_research_sources("res-123")+ assert summary["persisted"] >= 1+ service.download_resource.assert_not_called()+ service.download_as_text.assert_not_called()+ assert res.document_id == doc_id+++def test_persist_research_sources_prefers_tracked_hash_over_stale_url_document(+ in_memory_db, monkeypatch+):+ """When v1 and v2 documents exist for the same URL and the tracker points to v2,+ persist_research_sources must link to v2, not an arbitrary v1 document by URL.+ """+ url = "https://example.com/versioned_paper.pdf"+ doc_v1 = Document(+ id="doc-v1-sweep",+ source_type_id="st-research",+ document_hash="hash-v1",+ original_url=url,+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="database",+ file_path="database",+ text_content="V1 text",+ created_at=datetime(2026, 1, 1, tzinfo=UTC),+ )+ doc_v2 = Document(+ id="doc-v2-sweep",+ source_type_id="st-research",+ document_hash="hash-v2",+ original_url=url,+ file_size=200,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="database",+ file_path="database",+ text_content="V2 text",+ created_at=datetime(2026, 1, 2, tzinfo=UTC),+ )+ tracker = DownloadTracker(+ url=url,+ url_hash="versioned-tracker-hash",+ file_hash="hash-v2",+ first_resource_id=1,+ is_downloaded=True,+ )+ res = ResearchResource(+ id=789,+ research_id="res-123",+ url=url,+ title="Versioned Paper",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add_all([doc_v1, doc_v2, tracker, res])+ in_memory_db.commit()++ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": False,+ }.get(k, d)++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service.download_resource = Mock()+ service.download_as_text = Mock()++ summary = service.persist_research_sources("res-123")+ assert summary["persisted"] >= 1+ service.download_resource.assert_not_called()+ service.download_as_text.assert_not_called()+ assert res.document_id == "doc-v2-sweep"+++def test_try_existing_text_prefers_tracked_hash_over_stale_url_document(+ in_memory_db, monkeypatch+):+ """When v1 and v2 documents exist for the same URL and the tracker points to v2,+ _try_existing_text must link to v2, not an arbitrary v1 document by URL.+ """+ url = "https://example.com/versioned_text.pdf"+ doc_v1 = Document(+ id="doc-v1-text",+ source_type_id="st-research",+ document_hash="hash-text-v1",+ original_url=url,+ file_size=100,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="database",+ file_path="database",+ text_content="V1 text",+ extraction_method="pypdf",+ created_at=datetime(2026, 1, 1, tzinfo=UTC),+ )+ doc_v2 = Document(+ id="doc-v2-text",+ source_type_id="st-research",+ document_hash="hash-text-v2",+ original_url=url,+ file_size=200,+ status=DocumentStatus.COMPLETED,+ file_type="pdf",+ storage_mode="database",+ file_path="database",+ text_content="V2 text",+ extraction_method="pypdf",+ created_at=datetime(2026, 1, 2, tzinfo=UTC),+ )+ tracker = DownloadTracker(+ url=url,+ url_hash="versioned-text-tracker-hash",+ file_hash="hash-text-v2",+ first_resource_id=1,+ is_downloaded=True,+ )+ res = ResearchResource(+ id=790,+ research_id="res-123",+ url=url,+ title="Versioned Text Paper",+ document_id=None,+ created_at=datetime.now(UTC).isoformat(),+ )+ in_memory_db.add_all([doc_v1, doc_v2, tracker, res])+ in_memory_db.commit()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: in_memory_db, __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.find_tracker_by_url",+ lambda sess, u: tracker,+ )++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = Mock()+ service._settings_snapshot = {+ "research_library.auto_persist_research_sources": True+ }++ result = service._try_existing_text(in_memory_db, 790)+ assert result == (True, None)+ assert res.document_id == "doc-v2-text"diff --git a/tests/research_library/services/test_fetch_time_persist_exhaustive.py b/tests/research_library/services/test_fetch_time_persist_exhaustive.pynew file mode 100644index 0000000000..2ddf61a4f3--- /dev/null+++ b/tests/research_library/services/test_fetch_time_persist_exhaustive.py@@ -0,0 +1,1056 @@+"""Exhaustive tests for fetch-time persistence hooks and queue integration.++Covers ContentFetcher single-write behavior, downloader gating flags,+completion-sweep offloading, and cleanup routing by terminal status.+"""++from datetime import UTC, datetime+from unittest.mock import MagicMock, Mock++import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from local_deep_research.constants import ResearchStatus+from local_deep_research.database.models import Base+from local_deep_research.database.models.library import (+ Collection,+ Document,+ DocumentStatus,+ SourceType,+)+from local_deep_research.database.models.research import (+ ResearchHistory,+ ResearchResource,+)++[email protected](autouse=True)+def _isolate_auto_persist_semaphore():+ from local_deep_research.web.queue.processor_v2 import (+ _reset_auto_persist_pending,+ )++ _reset_auto_persist_pending()+ yield+ _reset_auto_persist_pending()+++def db():+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ session.add(Collection(id="default-library", name="Library"))+ session.add(+ SourceType(+ id="st-research",+ name="research_download",+ display_name="Research Download",+ )+ )+ session.add(+ ResearchHistory(+ id="res-123",+ query="Quantum Computing",+ mode="quick",+ status=ResearchStatus.COMPLETED,+ created_at=datetime.now(UTC).isoformat(),+ )+ )+ session.commit()+ yield session+ session.close()+++def _mock_db_session(monkeypatch, session):+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: session, __exit__=lambda *a: None+ ),+ )+++def _live_settings(monkeypatch, auto=True, mode="database"):+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": auto,+ "research_library.pdf_storage_mode": mode,+ "research_library.max_pdf_size_mb": 50,+ }.get(k, d)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_default_library_id",+ lambda *a, **k: "default-library",+ )+ return mock_settings+++def _fake_pdf_downloader(pdf_bytes, final_url=None, meta=None):+ calls = {"meta": 0}++ class FakeDownloader:+ _last_final_url = final_url++ def download_with_result(self, url, content_type=None):+ return Mock(+ is_success=True,+ content=pdf_bytes,+ status_code=200,+ skip_reason=None,+ )++ def get_metadata(self, url):+ calls["meta"] += 1+ return dict(meta or {})++ return FakeDownloader(), calls+++def _fetcher(username="testuser", password="pw", snapshot=None):+ from local_deep_research.content_fetcher.fetcher import ContentFetcher++ return ContentFetcher(+ username=username,+ password=password,+ settings_snapshot=snapshot+ or {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ },+ )+++# ---------------------------------------------------------------------------+# ContentFetcher.fetch: single write, metadata-once, extras+# ---------------------------------------------------------------------------+++def test_fetch_pdf_persists_once_with_final_url_and_metadata_once(+ db, monkeypatch+):+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "FETCHED PDF TEXT",+ )+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )+ pdf_bytes = b"%PDF-1.4 fetcher single write"+ final_url = "https://cdn.example.com/final.pdf"+ downloader, calls = _fake_pdf_downloader(+ pdf_bytes, final_url=final_url, meta={"title": "Fetched Paper"}+ )+ fetcher = _fetcher()+ monkeypatch.setattr(fetcher, "_get_downloader", lambda ut: downloader)++ result = fetcher.fetch("https://arxiv.org/pdf/2301.00001.pdf")++ assert result["status"] == "success"+ assert result["content"] == "FETCHED PDF TEXT"+ assert result["title"] == "Fetched Paper"+ assert calls["meta"] == 1+ persist.assert_called_once()+ kwargs = persist.call_args.kwargs+ assert kwargs["url"] == "https://arxiv.org/pdf/2301.00001.pdf"+ assert kwargs["pdf_content"] == pdf_bytes+ assert kwargs["text"] == "FETCHED PDF TEXT"+ assert kwargs["title"] == "Fetched Paper"+ assert kwargs["extra_urls"] == [final_url]+ assert kwargs["run_in_background"] is True+++def test_fetch_pdf_with_get_all_settings_snapshot_unmocked_gate(+ db, monkeypatch+):+ """ContentFetcher.fetch with real get_all_settings()-shaped snapshot leaves the gate unmocked."""+ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "FETCHED PDF TEXT",+ )+ pdf_bytes = b"%PDF-1.4 unmocked gate body"+ final_url = "https://cdn.example.com/final.pdf"+ downloader, calls = _fake_pdf_downloader(+ pdf_bytes, final_url=final_url, meta={"title": "Wrapped Settings Paper"}+ )++ wrapped_snapshot = {+ "research_library.auto_persist_research_sources": {+ "value": True,+ "ui_element": "checkbox",+ "category": "library",+ },+ "research_library.pdf_storage_mode": {+ "value": "database",+ "ui_element": "select",+ },+ "document_scheduler.download_pdfs": {+ "value": True,+ "ui_element": "checkbox",+ },+ "research_library.max_pdf_size_mb": {+ "value": 50,+ "ui_element": "number",+ },+ }++ fetcher = _fetcher(snapshot=wrapped_snapshot)+ monkeypatch.setattr(fetcher, "_get_downloader", lambda ut: downloader)++ submitted_fns = []++ class InlineExecutor:+ def submit(self, fn, *args, **kwargs):+ submitted_fns.append(fn)+ fn()+ return Mock()++ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service._get_pdf_persistence_executor",+ lambda: InlineExecutor(),+ )++ result = fetcher.fetch("https://arxiv.org/pdf/2301.00001.pdf")++ assert result["status"] == "success"+ assert result["content"] == "FETCHED PDF TEXT"+ assert len(submitted_fns) == 1+ doc = (+ db.query(Document)+ .filter_by(original_url="https://arxiv.org/pdf/2301.00001.pdf")+ .first()+ )+ assert doc is not None+ assert doc.text_content == "FETCHED PDF TEXT"+ assert doc.file_type == "pdf"++ # Verify that the unmocked gate blocks when wrapped value is False+ submitted_fns.clear()+ disabled_snapshot = dict(wrapped_snapshot)+ disabled_snapshot["research_library.auto_persist_research_sources"] = {+ "value": False,+ "ui_element": "checkbox",+ }+ fetcher_disabled = _fetcher(snapshot=disabled_snapshot)+ monkeypatch.setattr(+ fetcher_disabled, "_get_downloader", lambda ut: downloader+ )+ result_disabled = fetcher_disabled.fetch(+ "https://arxiv.org/pdf/2301.00002.pdf"+ )+ assert result_disabled["status"] == "success"+ assert len(submitted_fns) == 0+++def test_fetch_junk_prefixed_pdf_persists(monkeypatch):+ """Spec-legal PDF with short non-strippable ASCII/junk prefix before %PDF must persist."""+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "JUNK PREFIXED PDF TEXT",+ )+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )+ # 17-byte ASCII prefix before %PDF+ pdf_bytes = b"WRAPPER_PREFIX_17\r\n%PDF-1.4 extractable body"++ class JunkPrefixDownloader:+ def download_with_result(self, url, content_type=None):+ return Mock(is_success=True, content=pdf_bytes)++ def get_metadata(self, url):+ return {"title": "Prefixed Paper"}++ fetcher = _fetcher()+ monkeypatch.setattr(+ fetcher, "_get_downloader", lambda ut: JunkPrefixDownloader()+ )++ result = fetcher.fetch("https://example.com/prefixed.pdf")++ assert result["status"] == "success"+ assert result["content"] == "JUNK PREFIXED PDF TEXT"+ persist.assert_called_once()+ kwargs = persist.call_args.kwargs+ assert kwargs["url"] == "https://example.com/prefixed.pdf"+ assert kwargs["pdf_content"] == pdf_bytes+ assert kwargs["text"] == "JUNK PREFIXED PDF TEXT"+++def test_fetch_direct_pdf_downloader_prefer_text_invokes_persistence(+ monkeypatch,+):+ """Real DirectPDFDownloader returning extracted UTF-8 text under prefer_text=True+ must preserve raw PDF bytes and invoke on-the-spot persistence.+ """+ from local_deep_research.research_library.downloaders.direct_pdf import (+ DirectPDFDownloader,+ )++ pdf_bytes = b"%PDF-1.4 real direct pdf payload"+ extracted_text = "Real extracted direct PDF text"++ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: extracted_text,+ )++ downloader = DirectPDFDownloader()+ downloader._download_pdf = Mock(return_value=pdf_bytes)+ downloader.extract_text_from_pdf = Mock(return_value=extracted_text)++ fetcher = _fetcher()+ monkeypatch.setattr(fetcher, "_get_downloader", lambda ut: downloader)++ # 1. Default fetch with prefer_text=True+ res_text = fetcher.fetch(+ "https://example.com/direct_paper.pdf", prefer_text=True+ )+ assert res_text["status"] == "success"+ assert res_text["content"] == extracted_text+ persist.assert_called_once()+ kwargs = persist.call_args.kwargs+ assert kwargs["url"] == "https://example.com/direct_paper.pdf"+ assert kwargs["pdf_content"] == pdf_bytes+ assert kwargs["text"] == extracted_text++ persist.reset_mock()++ # 2. Fetch with prefer_text=False+ res_pdf = fetcher.fetch(+ "https://example.com/direct_paper.pdf", prefer_text=False+ )+ assert res_pdf["status"] == "success"+ assert res_pdf["content"] == extracted_text+ persist.assert_called_once()+ kwargs = persist.call_args.kwargs+ assert kwargs["url"] == "https://example.com/direct_paper.pdf"+ assert kwargs["pdf_content"] == pdf_bytes+ assert kwargs["text"] == extracted_text+++def test_fetch_pdf_without_final_url_passes_no_extras(monkeypatch):+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "TEXT",+ )+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )++ class NoRedirect:+ def download_with_result(self, url, content_type=None):+ return Mock(is_success=True, content=b"%PDF-1.4 x")++ def get_metadata(self, url):+ return {}++ fetcher = _fetcher()+ monkeypatch.setattr(fetcher, "_get_downloader", lambda ut: NoRedirect())+ result = fetcher.fetch("https://arxiv.org/pdf/2301.00002.pdf")+ assert result["status"] == "success"+ assert persist.call_args.kwargs["extra_urls"] is None+++def test_fetch_non_pdf_never_persists(monkeypatch):+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )++ class HtmlDownloader:+ def download_with_result(self, url, content_type=None):+ return Mock(is_success=True, content=b"<html>hello</html>")++ def get_metadata(self, url):+ return {"title": "Page"}++ fetcher = _fetcher()+ monkeypatch.setattr(fetcher, "_get_downloader", lambda ut: HtmlDownloader())+ result = fetcher.fetch("https://example.com/page")+ assert result["status"] == "success"+ assert result["content"] == "<html>hello</html>"+ persist.assert_not_called()+++def test_fetch_html_mentioning_pdf_magic_succeeds_as_html(monkeypatch):+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )++ class HtmlPdfMentionDownloader:+ def download_with_result(self, url, content_type=None):+ return Mock(+ is_success=True,+ content=b"<!DOCTYPE html><html><body>About %PDF-1.7 format</body></html>",+ )++ def get_metadata(self, url):+ return {}++ fetcher = _fetcher()+ monkeypatch.setattr(+ fetcher, "_get_downloader", lambda ut: HtmlPdfMentionDownloader()+ )+ result = fetcher.fetch("https://example.com/pdf-spec.html")+ assert result["status"] == "success"+ assert "About %PDF-1.7 format" in result["content"]+ persist.assert_not_called()+++def test_fetch_plain_text_mentioning_pdf_magic_returns_original_text(+ monkeypatch,+):+ """Rescue pin: plain UTF-8 mentioning %PDF early stays text."""+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "",+ )+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )++ class PlainTextDownloader:+ def download_with_result(self, url, content_type=None):+ return Mock(+ is_success=True,+ content=b"The %PDF-1.7 format is documented here in plain text.",+ )++ def get_metadata(self, url):+ return {}++ fetcher = _fetcher()+ monkeypatch.setattr(+ fetcher, "_get_downloader", lambda ut: PlainTextDownloader()+ )+ result = fetcher.fetch("https://example.com/pdf-notes.txt")+ assert result["status"] == "success"+ assert (+ result["content"]+ == "The %PDF-1.7 format is documented here in plain text."+ )+ persist.assert_not_called()+++def test_fetch_garbage_pdf_errors_without_persist(monkeypatch):+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "",+ )+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )++ class GarbageDownloader:+ def download_with_result(self, url, content_type=None):+ return Mock(is_success=True, content=b"%PDF-garbage-bytes")++ def get_metadata(self, url):+ return {}++ fetcher = _fetcher()+ monkeypatch.setattr(+ fetcher, "_get_downloader", lambda ut: GarbageDownloader()+ )+ result = fetcher.fetch("https://example.com/garbage.pdf")+ assert result["status"] == "error"+ assert "Could not extract text from PDF" in result["error"]+ persist.assert_not_called()+++def test_fetch_pdf_persist_skipped_when_opted_out(monkeypatch):+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.base.BaseDownloader.extract_text_from_pdf",+ lambda b: "TEXT",+ )+ persist = Mock(return_value=None)+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )+ downloader, _ = _fake_pdf_downloader(b"%PDF-1.4 x")+ fetcher = _fetcher(+ snapshot={"research_library.auto_persist_research_sources": False}+ )+ monkeypatch.setattr(fetcher, "_get_downloader", lambda ut: downloader)+ result = fetcher.fetch("https://arxiv.org/pdf/2301.00003.pdf")+ assert result["status"] == "success"+ persist.assert_called_once()+ assert persist.call_args.kwargs["check_setting"] is True+++# ---------------------------------------------------------------------------+# HTMLDownloader recovery hooks+# ---------------------------------------------------------------------------+++def _html_downloader(enable=True):+ from local_deep_research.research_library.downloaders.html import (+ HTMLDownloader,+ )++ return HTMLDownloader(timeout=30, enable_fetch_persistence=enable)+++def _patch_html_recovery(monkeypatch, downloader, pdf_bytes, final_url):+ monkeypatch.setattr(downloader, "_fetch_html", lambda url: None)+ monkeypatch.setattr(+ downloader,+ "_consume_recovery",+ lambda url: ("pdf", pdf_bytes, final_url),+ )+ monkeypatch.setattr(+ downloader, "_extract_stashed_pdf_text", lambda *a: "RECOVERED TEXT"+ )+++def test_html_download_does_not_persist_directly(monkeypatch):+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )+ dl = _html_downloader(enable=True)+ pdf_bytes = b"%PDF-1.4 served as html"+ final_url = "https://cdn.example.com/real.pdf"+ _patch_html_recovery(monkeypatch, dl, pdf_bytes, final_url)++ out = dl.download("https://example.com/paper")+ assert out == "RECOVERED TEXT".encode("utf-8")+ persist.assert_not_called()+ assert dl._last_final_url == final_url+ assert dl._last_pdf_content == pdf_bytes+++def test_html_download_skips_persist_when_disabled(monkeypatch):+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )+ dl = _html_downloader(enable=False)+ _patch_html_recovery(+ monkeypatch, dl, b"%PDF-1.4 x", "https://cdn.example.com/r.pdf"+ )+ out = dl.download("https://example.com/paper")+ assert out == "RECOVERED TEXT".encode("utf-8")+ persist.assert_not_called()+ assert dl._last_final_url == "https://cdn.example.com/r.pdf"+++def test_html_download_with_result_does_not_persist_directly(monkeypatch):+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )+ dl = _html_downloader(enable=True)+ pdf_bytes = b"%PDF-1.4 y"+ final_url = "https://cdn.example.com/r2.pdf"+ _patch_html_recovery(monkeypatch, dl, pdf_bytes, final_url)+ result = dl.download_with_result("https://example.com/paper2")+ assert result.is_success is True+ assert result.content == "RECOVERED TEXT".encode("utf-8")+ assert result.pdf_content == pdf_bytes+ assert dl._last_final_url == final_url+ assert dl._last_pdf_content == pdf_bytes+ persist.assert_not_called()+++def test_fetch_html_recovering_pdf_persists_once_via_content_fetcher(+ monkeypatch,+):+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )+ dl = _html_downloader(enable=True)+ pdf_bytes = b"%PDF-1.4 html recovered"+ final_url = "https://cdn.example.com/real.pdf"+ _patch_html_recovery(monkeypatch, dl, pdf_bytes, final_url)++ fetcher = _fetcher()+ monkeypatch.setattr(fetcher, "_get_downloader", lambda ut: dl)++ result = fetcher.fetch("https://example.com/paper")+ assert result["status"] == "success"+ assert result["content"] == "RECOVERED TEXT"+ persist.assert_called_once()+ kwargs = persist.call_args.kwargs+ assert kwargs["url"] == "https://example.com/paper"+ assert kwargs["pdf_content"] == pdf_bytes+ assert kwargs["text"] == "RECOVERED TEXT"+ assert kwargs["extra_urls"] == [final_url]+ assert kwargs["run_in_background"] is True+++def test_recovered_pdf_bytes_do_not_leak_into_next_page_persist(monkeypatch):+ persist = Mock()+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.persist_downloaded_pdf_on_the_spot",+ persist,+ )+ dl = _html_downloader(enable=True)+ pdf_bytes = b"%PDF-1.4 first doc pdf"+ final_url = "https://cdn.example.com/doc1.pdf"++ def fake_consume(url):+ if url == "https://example.com/doc1":+ return ("pdf", pdf_bytes, final_url)+ return (None, None, None)++ monkeypatch.setattr(dl, "_consume_recovery", fake_consume)+ monkeypatch.setattr(+ dl,+ "_fetch_html",+ lambda url, **k: (+ None+ if url == "https://example.com/doc1"+ else "<html><body><p>Article 2</p></body></html>"+ ),+ )+ monkeypatch.setattr(+ dl,+ "_extract_stashed_pdf_text",+ lambda *a: "RECOVERED DOC1 TEXT",+ )+ monkeypatch.setattr(+ dl,+ "_extract_content",+ lambda html, url: (+ {"content": "PLAIN ARTICLE 2 TEXT"}+ if url == "https://example.com/page2"+ else None+ ),+ )+ monkeypatch.setattr(+ dl,+ "_format_extracted_content",+ lambda extracted: extracted["content"],+ )++ fetcher = _fetcher()+ monkeypatch.setattr(fetcher, "_get_downloader", lambda ut: dl)++ # Fetch 1: recovered PDF+ r1 = fetcher.fetch("https://example.com/doc1")+ assert r1["status"] == "success"+ assert r1["content"] == "RECOVERED DOC1 TEXT"+ assert persist.call_count == 1+ assert persist.call_args.kwargs["url"] == "https://example.com/doc1"+ assert persist.call_args.kwargs["pdf_content"] == pdf_bytes++ # Fetch 2: plain HTML on same fetcher instance+ r2 = fetcher.fetch("https://example.com/page2")+ assert r2["status"] == "success"+ assert r2["content"] == "PLAIN ARTICLE 2 TEXT"+ # Second fetch must NOT trigger persist_downloaded_pdf_on_the_spot with doc1's PDF bytes+ assert persist.call_count == 1+ assert dl._last_pdf_content is None+ assert dl._last_final_url is None+++def test_html_same_url_final_url_records_no_extra():+ dl = _html_downloader(enable=True)+ dl._last_final_url = None+ assert getattr(dl, "_last_final_url", None) is None+ assert dl.enable_fetch_persistence is True+++# ---------------------------------------------------------------------------+# Downloader identity flags+# ---------------------------------------------------------------------------+++def test_base_downloader_defaults_enable_persistence():+ from local_deep_research.research_library.downloaders.direct_pdf import (+ DirectPDFDownloader,+ )++ dl = DirectPDFDownloader(timeout=30)+ assert dl.enable_fetch_persistence is True+ assert dl._last_final_url is None+++def test_download_service_constructs_downloaders_without_fetch_persistence(+ monkeypatch, tmp_path+):+ from local_deep_research.research_library.services.download_service import (+ DownloadService,+ )++ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.storage_path": str(tmp_path),+ "research_library.shared_library": False,+ "search.engine.web.semantic_scholar.api_key": "",+ "search.engine.web.openalex.api_key": "",+ }.get(k, d)+ mock_settings.get_settings_snapshot.return_value = {}+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ lambda *a, **k: mock_settings,+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.services.download_service.RetryManager",+ Mock(),+ )+ svc = DownloadService(username="u", password="p")+ assert len(svc.downloaders) >= 5+ for dl in svc.downloaders:+ assert dl.enable_fetch_persistence is False+ assert dl.username == "u"+ assert dl.password == "p"+++def test_content_fetcher_propagates_identity_to_downloaders():+ from local_deep_research.content_fetcher.fetcher import ContentFetcher+ from local_deep_research.content_fetcher.url_classifier import URLType++ fetcher = ContentFetcher(+ username="carol",+ password="carolpw",+ settings_snapshot={"k": "v"},+ )+ for url_type in (URLType.PDF, URLType.HTML, URLType.ARXIV):+ dl = fetcher._get_downloader(url_type)+ if dl is not None:+ assert dl.username == "carol"+ assert dl.password == "carolpw"+ assert dl.enable_fetch_persistence is True+++# ---------------------------------------------------------------------------+# Queue processor offloading+# ---------------------------------------------------------------------------+++def test_notify_completed_offloads_to_bounded_executor(monkeypatch):+ from local_deep_research.web.queue import processor_v2 as proc_mod+ from local_deep_research.web.queue.processor_v2 import QueueProcessorV2++ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: Mock(), __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.send_research_completed_notification_from_session",+ Mock(),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.search.services.research_history_indexer.auto_convert_research",+ Mock(),+ )+ submitted = []+ mock_executor = Mock()+ mock_executor.submit.side_effect = lambda fn: submitted.append(fn)+ monkeypatch.setattr(+ proc_mod, "_get_auto_persist_executor", lambda: mock_executor+ )+ monkeypatch.setattr(proc_mod, "_auto_persist_enabled_for", lambda u: True)++ QueueProcessorV2().notify_research_completed(+ "alice", "res-456", user_password="pwd"+ )+ assert len(submitted) == 1+++def test_notify_completed_executor_failure_swallowed(monkeypatch):+ from local_deep_research.web.queue.processor_v2 import QueueProcessorV2++ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: Mock(), __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.send_research_completed_notification_from_session",+ Mock(),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.search.services.research_history_indexer.auto_convert_research",+ Mock(),+ )+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2._get_auto_persist_executor",+ Mock(side_effect=RuntimeError("pool gone")),+ )+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2._auto_persist_enabled_for",+ lambda u: True,+ )+ QueueProcessorV2().notify_research_completed(+ "alice", "res-456", user_password="pwd"+ )+++def test_notify_completed_mock_executor_does_not_poison_semaphore(monkeypatch):+ """Mock executors that do not run submitted closures saturate at 8 permits+ and do not leak permits across tests (verified via isolation fixture).+ """+ proc_mod, cls, submitted = _patch_notify_sweep(monkeypatch, enabled=True)+ # Submit more than _AUTO_PERSIST_MAX_PENDING (8) non-run tasks+ for i in range(10):+ cls().notify_research_completed(+ "alice", f"res-leak-{i}", user_password="pwd"+ )+ # Exactly 8 are admitted into the bounded pending queue; 9th and 10th are skipped+ assert len(submitted) == proc_mod._AUTO_PERSIST_MAX_PENDING+++def _patch_notify_sweep(monkeypatch, enabled):+ from local_deep_research.web.queue import processor_v2 as proc_mod+ from local_deep_research.web.queue.processor_v2 import QueueProcessorV2++ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.get_user_db_session",+ lambda *a, **k: MagicMock(+ __enter__=lambda s: Mock(), __exit__=lambda *a: None+ ),+ )+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.send_research_completed_notification_from_session",+ Mock(),+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.search.services.research_history_indexer.auto_convert_research",+ Mock(),+ )+ submitted = []+ mock_executor = Mock()+ mock_executor.submit.side_effect = lambda fn: submitted.append(fn)+ monkeypatch.setattr(+ proc_mod, "_get_auto_persist_executor", lambda: mock_executor+ )+ monkeypatch.setattr(+ proc_mod, "_auto_persist_enabled_for", lambda u: enabled+ )+ return proc_mod, QueueProcessorV2, submitted+++def test_notify_completed_disabled_does_not_enqueue(monkeypatch):+ _, cls, submitted = _patch_notify_sweep(monkeypatch, enabled=False)+ cls().notify_research_completed("alice", "res-456", user_password="pwd")+ assert submitted == []+++def test_notify_completed_saturated_queue_skips_enqueue(monkeypatch):+ proc_mod, cls, submitted = _patch_notify_sweep(monkeypatch, enabled=True)+ acquired = 0+ try:+ while proc_mod._AUTO_PERSIST_PENDING.acquire(blocking=False):+ acquired += 1+ cls().notify_research_completed("alice", "res-456", user_password="pwd")+ assert submitted == []+ finally:+ for _ in range(acquired):+ proc_mod._AUTO_PERSIST_PENDING.release()+++# ---------------------------------------------------------------------------+# cleanup_research_resources routing by terminal status+# ---------------------------------------------------------------------------+++def _patch_cleanup(monkeypatch):+ import local_deep_research.web.services.research_service as rs++ qp = Mock()+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.queue_processor", qp+ )+ monkeypatch.setattr(+ "local_deep_research.web.research_state.cleanup_research", Mock()+ )+ monkeypatch.setattr(rs, "_sio_emit", Mock())+ monkeypatch.setattr(rs, "_sio_remove", Mock())+ monkeypatch.setattr(+ "local_deep_research.settings.env_registry.is_test_mode",+ lambda: False,+ )+ return rs, qp+++def test_cleanup_completed_notifies_completion(monkeypatch):+ rs, qp = _patch_cleanup(monkeypatch)+ rs.cleanup_research_resources(+ "res-1",+ username="u",+ user_password="pw",+ final_status=ResearchStatus.COMPLETED,+ )+ qp.notify_research_completed.assert_called_once_with(+ "u", "res-1", user_password="pw"+ )+ qp.notify_research_failed.assert_not_called()+ qp.queue_error_update.assert_not_called()+++def test_cleanup_failed_notifies_failure_without_sweep(monkeypatch):+ rs, qp = _patch_cleanup(monkeypatch)+ rs.cleanup_research_resources(+ "res-1",+ username="u",+ user_password="pw",+ final_status=ResearchStatus.FAILED,+ )+ qp.notify_research_failed.assert_called_once()+ qp.notify_research_completed.assert_not_called()+ qp.queue_error_update.assert_not_called()+++def test_cleanup_suspended_skips_persist_sweep(monkeypatch):+ rs, qp = _patch_cleanup(monkeypatch)+ rs.cleanup_research_resources(+ "res-1",+ username="u",+ user_password="pw",+ final_status=ResearchStatus.SUSPENDED,+ )+ qp.notify_research_completed.assert_not_called()+ qp.notify_research_failed.assert_not_called()+ qp.queue_error_update.assert_called_once()+++def test_cleanup_without_username_notifies_nothing(monkeypatch):+ rs, qp = _patch_cleanup(monkeypatch)+ rs.cleanup_research_resources("res-1", username=None)+ qp.notify_research_completed.assert_not_called()+ qp.notify_research_failed.assert_not_called()+ qp.queue_error_update.assert_not_called()+++# ---------------------------------------------------------------------------+# Tracker and sweep consistency pins+# ---------------------------------------------------------------------------+++def test_sweep_links_same_url_doc_without_network(db, monkeypatch):+ from local_deep_research.research_library.services.download_service import (+ DownloadService,+ )++ doc = Document(+ id="doc-spot",+ source_type_id="st-research",+ document_hash="hash-spot",+ original_url="https://arxiv.org/pdf/2301.77777.pdf",+ file_size=100,+ file_type="pdf",+ status=DocumentStatus.COMPLETED,+ text_content="spot text",+ storage_mode="database",+ file_path="database",+ )+ r = ResearchResource(+ id=81,+ research_id="res-123",+ url="https://arxiv.org/pdf/2301.77777.pdf",+ title="Spot",+ created_at=datetime.now(UTC).isoformat(),+ )+ db.add_all([doc, r])+ db.commit()+ _mock_db_session(monkeypatch, db)+ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None+ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ }.get(k, d)+ service.settings = mock_settings+ service.download_resource = Mock()+ service.download_as_text = Mock()++ summary = service.persist_research_sources("res-123")+ assert summary["persisted"] == 1+ service.download_resource.assert_not_called()+ service.download_as_text.assert_not_called()+ assert (+ db.query(ResearchResource).filter_by(id=81).first().document_id+ == "doc-spot"+ )+++def test_on_the_spot_then_sweep_needs_no_download(db, monkeypatch, tmp_path):+ from local_deep_research.research_library.services import (+ download_service as ds_mod,+ )++ _mock_db_session(monkeypatch, db)+ _live_settings(monkeypatch, auto=True)+ url = "https://arxiv.org/pdf/2301.88888.pdf"+ pdf_bytes = b"%PDF-1.4 end to end"+ doc_id = ds_mod.persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=pdf_bytes,+ text="e2e text",+ username="testuser",+ settings_snapshot={"research_library.pdf_storage_mode": "database"},+ )+ assert doc_id is not None+ r = ResearchResource(+ id=82,+ research_id="res-123",+ url=url,+ title="E2E",+ created_at=datetime.now(UTC).isoformat(),+ )+ db.add(r)+ db.commit()++ mock_settings = Mock()+ mock_settings.get_setting.side_effect = lambda k, d=None: {+ "research_library.auto_persist_research_sources": True,+ "research_library.pdf_storage_mode": "database",+ "document_scheduler.download_pdfs": True,+ }.get(k, d)+ service = ds_mod.DownloadService.__new__(ds_mod.DownloadService)+ service.username = "testuser"+ service.password = None+ service.settings = mock_settings+ service.library_root = "/fake/root"+ service.download_resource = Mock()+ service.download_as_text = Mock()++ summary = service.persist_research_sources("res-123")+ assert summary["persisted"] >= 1+ service.download_resource.assert_not_called()+ service.download_as_text.assert_not_called()+ assert (+ db.query(ResearchResource).filter_by(id=82).first().document_id+ == doc_id+ )diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 1109ddb215..567a7f31c5 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -2775,6 +2775,21 @@"value": false,"visible": true},+ "research_library.auto_persist_research_sources": {+ "category": "research_library",+ "description": "Automatically persist research sources (PDFs and extracted text) into the Library when a research run completes. Default off. When enabled, PDF downloads still honor the scheduler preference document_scheduler.download_pdfs and the PDF storage mode.",+ "editable": true,+ "env_var": "LDR_RESEARCH_LIBRARY_AUTO_PERSIST_RESEARCH_SOURCES",+ "max_value": null,+ "min_value": null,+ "name": "Auto-Persist Research Sources",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },"research_library.confirm_deletions": {"category": "research_library","description": "Show confirmation dialogs before delete operations. Recommended to keep enabled to prevent accidental data loss.",