Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(pdf): bound upload, RAG, and Zotero text extraction (#6472)

LearningCircuita33638e6c562
diff --git a/changelog.d/6472.security.md b/changelog.d/6472.security.md
new file mode 100644
index 0000000000..30ab4f8e14
--- /dev/null
+++ b/changelog.d/6472.security.md
@@ -0,0 +1 @@
+The PDF upload extraction service now walks pages lazily and stops at the shared limits of 500 pages, 10,000,000 extracted characters, and 600 seconds of thread CPU time. It closes and releases each page, reports truncation, and avoids resolving the PDF page tree's declared count, which can loop inside pdfminer on malformed files. Partial uploads retain their truncation flag in the API, show a persistent warning and a lower-bound page count in the research form, and include a partial-extraction notice with the text added to the research query. RAG uploads and Zotero sync now apply the same ceilings and release cached pypdf objects while extracting PDF text from bytes. Both text paths stop before extracting another page when the remaining character budget cannot hold text plus its separator, preserving the retained prefix even if the unread page is malformed. Pypdf still builds the page tree, and a single page parse or extraction call can run until the PDF library returns.
diff --git a/docs/library-and-rag.md b/docs/library-and-rag.md
index 42c2978c7b..46e73f08d5 100644
--- a/docs/library-and-rag.md
+++ b/docs/library-and-rag.md
@@ -51,6 +51,13 @@ The upload dialog's file picker is populated from the live list of formats the
server can actually parse (`GET /library/api/config/supported-formats`), so it
only offers formats whose parser dependencies are installed.
+For PDF text extracted from bytes, including RAG uploads and Zotero sync, the
+server extracts text from at most 500 pages and keeps at most 10,000,000
+characters. It stops starting new pages after 600 seconds of extraction-thread
+CPU time.
+Documents that reach a limit retain the extracted prefix; the current RAG and
+Zotero flows do not display a partial-extraction marker.
+
\* The legacy binary formats `.doc` and `.ppt` are offered **only** when
LibreOffice (`soffice`) is installed: Local Deep Research converts each one to
`.docx`/`.pptx` with `soffice` itself (with a 120-second timeout) and then
diff --git a/src/local_deep_research/document_loaders/bounded_pdf.py b/src/local_deep_research/document_loaders/bounded_pdf.py
new file mode 100644
index 0000000000..f045c050ed
--- /dev/null
+++ b/src/local_deep_research/document_loaders/bounded_pdf.py
@@ -0,0 +1,108 @@
+"""Bound PDF text extraction for byte-backed document loaders.
+
+RAG uploads and Zotero sync both call ``extract_text_from_bytes``. The
+registry's ``PyPDFLoader.load()`` materializes text from every PDF page, so
+those entry points need the same ceilings as the other extraction paths.
+Pypdf still flattens the page tree before the first page is yielded, and one
+``extract_text()`` call cannot be interrupted without process isolation.
+"""
+
+from __future__ import annotations
+
+import io
+import time
+
+from langchain_core.documents import Document
+from loguru import logger
+from pypdf import PdfReader
+
+from ..utilities import pdf_extraction_limits as limits
+from ..utilities.pdf_stream_release import PypdfWalkReleaser
+from ..utilities.resource_utils import safe_close
+
+
+def load_bounded_pdf(content: bytes, source: str) -> list[Document]:
+ """Return page documents, truncating at the shared extraction ceilings."""
+ deadline = time.thread_time() + limits.MAX_PDF_EXTRACTION_CPU_SECONDS
+ documents: list[Document] = []
+ retained_chars = 0
+ text_pages = 0
+ truncated_by: str | None = None
+
+ with io.BytesIO(content) as stream:
+ reader = PdfReader(stream)
+ try:
+ # Pypdf materializes its page tree here; the limit below bounds
+ # text extraction, not the construction of that tree.
+ total_pages = len(reader.pages)
+ releaser = PypdfWalkReleaser(reader)
+ for page_number in range(
+ min(total_pages, limits.MAX_PDF_EXTRACTION_PAGES)
+ ):
+ if time.thread_time() >= deadline:
+ truncated_by = "CPU-time"
+ break
+ separator_chars = 2 if text_pages else 0
+ remaining = (
+ limits.MAX_PDF_EXTRACTED_CHARS
+ - retained_chars
+ - separator_chars
+ )
+ if remaining <= 0:
+ truncated_by = "character"
+ break
+
+ page = reader.pages[page_number]
+ releaser.before_page()
+ try:
+ page_text = (page.extract_text() or "").strip()
+ finally:
+ # The reader otherwise retains decoded streams and parsed
+ # objects after each page has yielded its text.
+ releaser.after_page()
+
+ if page_text:
+ kept_text = page_text[:remaining]
+ retained_chars += separator_chars + len(kept_text)
+ text_pages += 1
+ else:
+ kept_text = ""
+
+ documents.append(
+ Document(
+ page_content=kept_text,
+ metadata={
+ "source": source,
+ "page": page_number,
+ "total_pages": total_pages,
+ },
+ )
+ )
+ if len(kept_text) < len(page_text):
+ truncated_by = "character"
+ break
+ if (
+ retained_chars >= limits.MAX_PDF_EXTRACTED_CHARS
+ and page_number + 1 < total_pages
+ ):
+ truncated_by = "character"
+ break
+ if (
+ truncated_by is None
+ and total_pages > limits.MAX_PDF_EXTRACTION_PAGES
+ ):
+ truncated_by = "page"
+ finally:
+ safe_close(reader, "PDF byte-loader reader")
+
+ if truncated_by:
+ for document in documents:
+ document.metadata["truncated"] = True
+ logger.warning(
+ "PDF document-loader extraction stopped at {} ceiling "
+ "after {} of {} pages",
+ truncated_by,
+ len(documents),
+ total_pages,
+ )
+ return documents
diff --git a/src/local_deep_research/document_loaders/bytes_loader.py b/src/local_deep_research/document_loaders/bytes_loader.py
index f6e8d37771..d3d61ece96 100644
--- a/src/local_deep_research/document_loaders/bytes_loader.py
+++ b/src/local_deep_research/document_loaders/bytes_loader.py
@@ -46,8 +46,9 @@ def load_from_bytes(
"""
Load documents from bytes content.
- This function writes the bytes to a temporary file, uses the appropriate
- LangChain loader, then cleans up the temp file.
+ PDFs are extracted directly from memory with shared page, character,
+ and CPU ceilings. Other formats are written to a temporary file, loaded
+ with the registered LangChain loader, then cleaned up.
Args:
content: File content as bytes
@@ -121,18 +122,23 @@ def load_from_bytes(
loader_class, loader_kwargs = loader_info
- # Create temp file with the content
tmp_path = None
try:
- with tempfile.NamedTemporaryFile(
- suffix=ext, delete=False, prefix="ldr_upload_"
- ) as tmp:
- tmp.write(content)
- tmp_path = tmp.name
-
- # Create loader and load documents
- loader = loader_class(tmp_path, **loader_kwargs)
- documents = loader.load()
+ # PDF text must use the same page/character/CPU ceilings as the
+ # library download and research-upload extractors. Both RAG uploads
+ # and Zotero sync enter through this byte-backed loader.
+ if ext == ".pdf":
+ from .bounded_pdf import load_bounded_pdf
+
+ documents = load_bounded_pdf(content, filename)
+ else:
+ with tempfile.NamedTemporaryFile(
+ suffix=ext, delete=False, prefix="ldr_upload_"
+ ) as tmp:
+ tmp.write(content)
+ tmp_path = tmp.name
+ loader = loader_class(tmp_path, **loader_kwargs)
+ documents = loader.load()
# Add metadata to all documents
for doc in documents:
@@ -143,7 +149,7 @@ def load_from_bytes(
logger.info(
f"Loaded {len(documents)} document(s) from {filename} ({ext})"
)
- return documents # type: ignore[no-any-return]
+ return documents
except (ImportError, ModuleNotFoundError):
# The extension is registered but the loader's runtime parser
diff --git a/src/local_deep_research/utilities/pdf_extraction_limits.py b/src/local_deep_research/utilities/pdf_extraction_limits.py
index 83564e4014..d2b34ff949 100644
--- a/src/local_deep_research/utilities/pdf_extraction_limits.py
+++ b/src/local_deep_research/utilities/pdf_extraction_limits.py
@@ -6,12 +6,19 @@ whose streams decompress into huge text, can still burn unbounded CPU
and memory inside the server process while a page-walking extractor
chews through it.
-At this tree these ceilings bound two extraction paths: the download
-service's ``_extract_text_from_pdf``
-(``research_library/services/download_service.py``, pdfplumber and its
-PyPDF fallback) and the downloader base helper ``extract_text_from_pdf``
-(``research_library/downloaders/base.py``). On those paths they bound
-exactly four things:
+At this tree these ceilings bound four extraction paths:
+
+- the download service's ``_extract_text_from_pdf``
+ (``research_library/services/download_service.py``, pdfplumber and its
+ PyPDF fallback);
+- the downloader base helper ``extract_text_from_pdf``
+ (``research_library/downloaders/base.py``);
+- the upload-path extraction service
+ (``web/services/pdf_extraction_service.py``, pdfplumber).
+- the byte-backed document loader used by RAG uploads and Zotero sync
+ (``document_loaders/bounded_pdf.py``, pypdf).
+
+On all four paths they bound exactly four things:
- pages walked: text is extracted from at most
``MAX_PDF_EXTRACTION_PAGES`` (500) pages per attempt. The download
@@ -43,11 +50,17 @@ exactly four things:
What they do NOT bound:
-- page-tree materialisation. ``pdfplumber`` builds every page object,
- and ``pypdf`` flattens the whole page tree, before the first page is
- yielded -- O(all pages) time and memory for a file with many pages,
- whatever page count the file declares. None of the ceilings above is
- consulted until that has finished.
+- page-tree materialisation, where the walk does not avoid it.
+ ``pypdf`` flattens the whole page tree, and pdfplumber's ``PDF.pages``
+ builds every page object, before the first page is yielded -- O(all
+ pages) time and memory for a file with many pages, whatever page
+ count the file declares -- and none of the ceilings above is
+ consulted until that has finished. That cost is paid by every pypdf
+ walk and by the download service's pdfplumber walk. The upload-path
+ service walks the page tree lazily instead
+ (``utilities/pdf_page_walk``) and never touches
+ ``PDF.pages``, so they build at most the pages they walk (plus the
+ one that shows the ceiling was reached).
- the cost of a single page. One page's ``extract_text()`` runs to
completion inside the library with no check point available to us; a
few kilobytes of compressed content streams can take minutes or
@@ -59,20 +72,18 @@ What they do NOT bound:
the memory held can exceed the threshold by a small multiple: walks
that held ~20 MB (decoded streams) or ~60 MB (parsed ``/Widths``
arrays) more per page peaked ~100-250 MB above their starting RSS.
- Objects cached before the walk began (the page tree) are kept, and a
+ Objects cached before the walk began (the page tree, where it was
+ built before the walk) are kept, and a
released stream that a later page uses again is decoded again, at the
CPU budget's expense.
-Bounding the first two would need a separate process, which these constants
-deliberately do not introduce. The other extraction sites in the tree
-(the upload-path extraction service, the arXiv engine's inline
-extraction, and the ``document_loaders``-based upload and Zotero-sync
-routes) are not bounded by this module at this tree; a companion change
-(#6472) proposes the same page and character ceilings for the first
-two.
-
+Interrupting a parse or a page that is already running would need a
+separate process, which these constants deliberately do not introduce.
Text cut short by any of these ceilings is returned, and stored, like a
-complete extraction; only a logged warning says it is partial.
+complete extraction. The upload-path service also returns a truncation flag
+to its API and research form; the byte-backed loader marks its page documents
+as truncated, but the RAG/Zotero callers only consume joined text, so they
+currently expose the partial result through a logged warning.
"""
from __future__ import annotations
diff --git a/src/local_deep_research/utilities/pdf_page_walk.py b/src/local_deep_research/utilities/pdf_page_walk.py
new file mode 100644
index 0000000000..24a8e28e6b
--- /dev/null
+++ b/src/local_deep_research/utilities/pdf_page_walk.py
@@ -0,0 +1,76 @@
+"""Walk a pdfplumber document's pages lazily.
+
+pdfplumber's ``PDF.pages`` builds a ``Page`` for every page of the
+document on first access, and ``PDF.close()`` -- which leaving a
+``with pdfplumber.open(...)`` block calls -- accesses ``PDF.pages`` too.
+A small upload whose page tree declares 100,000 pages therefore costs
+O(declared pages) time and memory before any page ceiling is consulted
+(#6771). The upload validator (``security/file_upload_validator``)
+avoids that by walking pdfminer's page tree with
+``PDFPage.create_pages``, which yields one page at a time; this module
+does the same for the text-extraction walks, so a walk that stops at
+``MAX_PDF_EXTRACTION_PAGES`` builds at most that many pages (plus the
+one that tells it there are more).
+
+Callers that walk this way must not use ``with pdfplumber.open(...)``
+nor call ``PDF.close()``, which would build every page anyway: they
+open the stream themselves, close it themselves, and close each page
+they were given.
+
+A walk stopped early knows only a lower bound on the page count. The
+page tree's declared ``/Count`` is deliberately not read to fill the
+gap: it is normally an indirect reference, and resolving one can loop
+inside pdfminer with no limit a caller can impose (a self-reference,
+an object-stream entry whose stream is a self-reference, a stream whose
+``/Length`` is one), outside the extraction's CPU budget.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Iterator, Optional
+
+if TYPE_CHECKING:
+ from .pdf_stream_release import PdfplumberWalkReleaser
+
+
+def iter_pdfplumber_pages(
+ pdf: Any, releaser: Optional[PdfplumberWalkReleaser] = None
+) -> Iterator[Any]:
+ """Yield *pdf*'s pages as pdfplumber ``Page`` objects, one at a time.
+
+ The page tree is walked only as far as the caller iterates; each
+ ``Page`` is built exactly as ``PDF.pages`` builds it (same page
+ number and running ``initial_doctop``). An error the page-tree walk
+ raises is re-raised as ``PdfminerException``, as ``PDF.pages`` does.
+
+ Building a page resolves its ``/Resources``, ``/Contents`` and the
+ page-tree nodes above it, which caches those objects on the
+ document. When a *releaser* is given, its ``before_page()`` is
+ called here, just before each page is built, so what building the
+ page caches is inside its window and counted by the ``after_page()``
+ the caller makes once done with the page. The caller then must not
+ call ``before_page()`` itself: that would move the window's start
+ past the page's construction.
+ """
+ from pdfminer.pdfpage import PDFPage
+ from pdfplumber.page import Page
+ from pdfplumber.utils.exceptions import PdfminerException
+
+ generator = PDFPage.create_pages(pdf.doc)
+ doctop = 0
+ page_number = 0
+ while True:
+ if releaser is not None:
+ releaser.before_page()
+ try:
+ page_obj = next(generator)
+ except StopIteration:
+ return
+ except Exception as exc:
+ raise PdfminerException(exc) from exc
+ page_number += 1
+ page = Page(
+ pdf, page_obj, page_number=page_number, initial_doctop=doctop
+ )
+ doctop += page.height
+ yield page
diff --git a/src/local_deep_research/utilities/pdf_stream_release.py b/src/local_deep_research/utilities/pdf_stream_release.py
index 0a9bc6e572..545a6db822 100644
--- a/src/local_deep_research/utilities/pdf_stream_release.py
+++ b/src/local_deep_research/utilities/pdf_stream_release.py
@@ -20,7 +20,9 @@ does not release it:
A walker creates one releaser per document and calls ``before_page()``
just before each page's ``extract_text()`` and ``after_page()`` once the
-page is done. ``after_page()`` estimates what the object cache holds
+page is done. A lazy pdfplumber walk (``utilities/pdf_page_walk``) calls
+``before_page()`` before it builds each page instead, since building a
+page resolves (and caches) its resources and contents. ``after_page()`` estimates what the object cache holds
since the last release -- decoded stream bytes, plus
``_BYTES_PER_PARSED_ELEMENT`` for every element of the objects the walk
has parsed -- and, once that reaches ``MAX_PDF_RETAINED_DECODED_BYTES``,
@@ -28,8 +30,8 @@ releases it: decoded streams go back to their encoded state (the next
access decodes them again from their raw bytes, so a stream a later
page shares still extracts correctly), and every object the walk added
to the cache is dropped, to be parsed again from the file if a later
-page needs it. Objects cached before the walk began (the page tree)
-are kept. Honest documents stay far below the threshold and are left
+page needs it. Objects cached before the first ``before_page()`` (the
+page tree, when the walk materialised it up front) are kept. Honest documents stay far below the threshold and are left
alone.
Each ``after_page()`` scans the document's object cache, so it costs
@@ -115,14 +117,17 @@ class PdfplumberWalkReleaser:
return doc, cache, parsed_objstms, fonts
def before_page(self) -> None:
- """Call just before a page's ``extract_text()``. Never raises."""
+ """Call just before a page's ``extract_text()``, or, in a lazy
+ walk, just before the page is built. Never raises."""
if not self._enabled:
return
try:
_doc, cache, _parsed, _fonts = self._parts()
if self._pre_walk_keys is None:
- # The page tree is materialised by now: what is cached
- # here was not added by the walk and is never dropped.
+ # What is cached here was not added by the walk and is
+ # never dropped. In a lazy walk the page-tree nodes are
+ # parsed as the walk reaches them, so they are counted
+ # and released like any other object the walk added.
self._pre_walk_keys = set(cache)
self._page_mark = len(cache)
except Exception:
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 406f4092b0..effb8e5986 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -3632,6 +3632,7 @@ async def upload_pdf(
"text": result["text"],
"size": result["size"],
"pages": result["pages"],
+ "truncated": result.get("truncated", False),
}
)
processed_files += 1
@@ -3658,7 +3659,14 @@ async def upload_pdf(
"extracted_texts": extracted_texts,
"combined_text": "\n\n".join(
[
- f"--- From {item['filename']} ---\n{item['text']}"
+ f"--- From {item['filename']} ---\n"
+ + (
+ "[Partial PDF extraction: only part of this "
+ "document's text is included.]\n"
+ if item["truncated"]
+ else ""
+ )
+ + item["text"]
for item in extracted_texts
]
),
diff --git a/src/local_deep_research/web/services/pdf_extraction_service.py b/src/local_deep_research/web/services/pdf_extraction_service.py
index 42e6897119..ea82e243f6 100644
--- a/src/local_deep_research/web/services/pdf_extraction_service.py
+++ b/src/local_deep_research/web/services/pdf_extraction_service.py
@@ -6,12 +6,23 @@ Complements pdf_service.py which handles PDF generation.
"""
import io
+import time
from typing import Any, Dict, List
import pdfplumber
from loguru import logger
from local_deep_research.security.filename_sanitizer import sanitize_filename
+from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTED_CHARS,
+ MAX_PDF_EXTRACTION_CPU_SECONDS,
+ MAX_PDF_EXTRACTION_PAGES,
+)
+from local_deep_research.utilities.pdf_page_walk import iter_pdfplumber_pages
+from local_deep_research.utilities.pdf_stream_release import (
+ PdfplumberWalkReleaser,
+)
+from local_deep_research.utilities.resource_utils import safe_close
class PDFExtractionService:
@@ -28,6 +39,28 @@ class PDFExtractionService:
and metadata (page count) in the same operation, avoiding the
performance issue of opening the file multiple times.
+ What is bounded (``utilities/pdf_extraction_limits``): text is
+ extracted from at most ``MAX_PDF_EXTRACTION_PAGES`` pages, at most
+ ``MAX_PDF_EXTRACTED_CHARS`` characters are kept (separators
+ included; the page that crosses the ceiling is truncated to the
+ budget left), and no new page is started once the calling thread
+ has spent ``MAX_PDF_EXTRACTION_CPU_SECONDS`` of its own CPU time
+ (``time.thread_time()``) since entry. The page tree is walked
+ lazily (``utilities/pdf_page_walk``), so a document declaring more
+ pages than the ceiling has at most the ceiling's pages (plus the
+ one that shows there are more) built, not all of them. Every page
+ the walk reaches is closed once done with, which releases its
+ per-page layout caches; what pdfminer decodes and parses for a
+ page stays cached on the document after that, so the walk hands
+ each page to a releaser (``utilities/pdf_stream_release``) that
+ releases those caches once they reach
+ ``MAX_PDF_RETAINED_DECODED_BYTES``.
+
+ What is NOT bounded: the budget is checked between pages only,
+ so neither ``pdfplumber.open`` (the cross-reference parse) nor a
+ single page's ``extract_text()`` can be interrupted, and what one
+ page decodes and parses is held until the release after it.
+
Args:
pdf_content: Raw PDF file bytes
filename: Original filename (for logging)
@@ -35,9 +68,18 @@ class PDFExtractionService:
Returns:
Dictionary with keys:
- 'text': Extracted text content
- - 'pages': Number of pages
+ - 'pages': Number of pages the walk reached. When the walk
+ stops early (a ceiling, or the CPU budget) the pages after
+ it are never built, so this is a lower bound and
+ 'truncated' is True. The page tree's declared ``/Count``
+ is deliberately not read: resolving it can loop inside
+ pdfminer (a self-referencing object, or an object-stream
+ or ``/Length`` reference cycle) after the CPU budget has
+ stopped applying
- 'size': File size in bytes
- 'filename': Original filename
+ - 'truncated': True if a page or character ceiling, or the
+ CPU budget, stopped the extraction early (False otherwise, including failures)
- 'success': Boolean indicating success
- 'error': Error message if failed (None if successful)
@@ -51,48 +93,124 @@ class PDFExtractionService:
except Exception:
filename = "unnamed.pdf"
+ # Started at entry so the budget covers the whole call, the open
+ # included, as in the library download paths. Per-thread CPU time,
+ # not wall time: waiting on other requests is not charged.
+ deadline = time.thread_time() + MAX_PDF_EXTRACTION_CPU_SECONDS
try:
- with pdfplumber.open(io.BytesIO(pdf_content)) as pdf:
- # Get pages list once
- pages = list(pdf.pages)
- page_count = len(pages)
-
- # Extract text from all pages in single pass
- text_parts = []
- for page in pages:
+ # Not a ``with`` block: ``PDF.close()`` accesses ``PDF.pages``,
+ # which builds every page of the document. The stream is an
+ # in-memory buffer, so nothing else needs closing; each page
+ # the walk reaches is closed below.
+ pdf = pdfplumber.open(io.BytesIO(pdf_content))
+ text_parts = []
+ extracted_chars = 0
+ truncated = False
+ pages_seen = 0
+ releaser = PdfplumberWalkReleaser(pdf)
+ # The walk calls releaser.before_page() before building each
+ # page, so what building it resolves and caches (its
+ # /Resources, /Contents, page-tree nodes) is counted too.
+ for page_number, page in enumerate(
+ iter_pdfplumber_pages(pdf, releaser)
+ ):
+ pages_seen = page_number + 1
+ # Close every page this loop reaches, on the break
+ # paths too: pdfplumber keeps a page's parsed layout
+ # objects and text map cached on it until close().
+ try:
+ if page_number >= MAX_PDF_EXTRACTION_PAGES:
+ truncated = True
+ logger.warning(
+ f"PDF extraction stopped at page ceiling "
+ f"({MAX_PDF_EXTRACTION_PAGES}) for {filename}"
+ )
+ break
+ if time.thread_time() >= deadline:
+ truncated = True
+ logger.warning(
+ "PDF extraction stopped at the CPU-time "
+ f"ceiling ({MAX_PDF_EXTRACTION_CPU_SECONDS}s) "
+ f"after {page_number} pages for {filename}"
+ )
+ break
+ separator_chars = 1 if text_parts else 0
+ remaining = (
+ MAX_PDF_EXTRACTED_CHARS
+ - extracted_chars
+ - separator_chars
+ )
+ if remaining <= 0:
+ truncated = True
+ logger.warning(
+ f"PDF extraction stopped at character "
+ f"ceiling ({MAX_PDF_EXTRACTED_CHARS}) "
+ f"for {filename}"
+ )
+ break
page_text = page.extract_text()
if page_text:
+ if len(page_text) > remaining:
+ # Keep the slice that fits rather than
+ # dropping the tripping page whole: a first
+ # page over the ceiling still yields the
+ # budget's text.
+ text_parts.append(page_text[:remaining])
+ extracted_chars += separator_chars + remaining
+ truncated = True
+ logger.warning(
+ f"PDF extraction truncated at character "
+ f"ceiling ({MAX_PDF_EXTRACTED_CHARS}) "
+ f"for {filename}"
+ )
+ break
+ extracted_chars += separator_chars + len(page_text)
text_parts.append(page_text)
+ finally:
+ # safe_close: a failing close() must not mask the
+ # page's own exception.
+ safe_close(page, "pdfplumber page")
+ # close() leaves what pdfminer decoded and parsed
+ # for the page cached on the document; release it
+ # once it reaches MAX_PDF_RETAINED_DECODED_BYTES.
+ releaser.after_page()
+
+ # A lower bound when truncated: the pages after the stop
+ # were never built, and /Count is not consulted (see the
+ # docstring) because no reference is resolved after the walk.
+ page_count = pages_seen
- # Combine all text
- full_text = "\n".join(text_parts)
-
- # Check if any text was extracted
- if not full_text.strip():
- logger.warning(f"No extractable text found in {filename}")
- return {
- "text": "",
- "pages": page_count,
- "size": len(pdf_content),
- "filename": filename,
- "success": False,
- "error": "No extractable text found",
- }
-
- logger.info(
- f"Successfully extracted text from {filename} "
- f"({len(full_text)} chars, {page_count} pages)"
- )
+ # Combine all text
+ full_text = "\n".join(text_parts)
+ # Check if any text was extracted
+ if not full_text.strip():
+ logger.warning(f"No extractable text found in {filename}")
return {
- "text": full_text.strip(),
+ "text": "",
"pages": page_count,
"size": len(pdf_content),
"filename": filename,
- "success": True,
- "error": None,
+ "truncated": truncated,
+ "success": False,
+ "error": "No extractable text found",
}
+ logger.info(
+ f"Successfully extracted text from {filename} "
+ f"({len(full_text)} chars, {page_count} pages)"
+ )
+
+ return {
+ "text": full_text.strip(),
+ "pages": page_count,
+ "size": len(pdf_content),
+ "filename": filename,
+ "truncated": truncated,
+ "success": True,
+ "error": None,
+ }
+
except Exception:
# Log full exception details server-side for debugging
logger.exception(f"Error extracting text from {filename}")
@@ -102,6 +220,7 @@ class PDFExtractionService:
"pages": 0,
"size": len(pdf_content),
"filename": filename,
+ "truncated": False,
"success": False,
"error": "Failed to extract text from PDF",
}
diff --git a/src/local_deep_research/web/static/js/pdf_upload_handler.js b/src/local_deep_research/web/static/js/pdf_upload_handler.js
index 937abd56fa..69a274ea2d 100644
--- a/src/local_deep_research/web/static/js/pdf_upload_handler.js
+++ b/src/local_deep_research/web/static/js/pdf_upload_handler.js
@@ -342,16 +342,14 @@ class PDFUploadHandler {
* Add PDFs to the uploaded list
*/
addPDFsToUploaded(files, extractedTexts) {
- files.forEach((file, index) => {
- const extractedText = extractedTexts[index];
- if (extractedText) {
- this.uploadedPDFs.push({
- filename: file.name,
- size: file.size,
- text: extractedText.text,
- pages: extractedText.pages
- });
- }
+ extractedTexts.forEach((extractedText, index) => {
+ this.uploadedPDFs.push({
+ filename: extractedText.filename ?? files[index]?.name,
+ size: extractedText.size ?? files[index]?.size,
+ text: extractedText.text,
+ pages: extractedText.pages,
+ truncated: extractedText.truncated === true
+ });
});
}
@@ -378,8 +376,12 @@ class PDFUploadHandler {
if (this.uploadedPDFs.length > 0) {
const pdfCount = this.uploadedPDFs.length;
const totalPages = this.uploadedPDFs.reduce((sum, pdf) => sum + pdf.pages, 0);
+ const partial = this.uploadedPDFs.some(pdf => pdf.truncated);
+ const pageSummary = partial
+ ? `at least ${totalPages} pages, partial text`
+ : `${totalPages} pages total`;
this.queryTextarea.placeholder =
- `Enter your research question... (${pdfCount} PDF${pdfCount > 1 ? 's' : ''} loaded, ${totalPages} pages total)`;
+ `Enter your research question... (${pdfCount} PDF${pdfCount > 1 ? 's' : ''} loaded, ${pageSummary})`;
} else {
this.queryTextarea.placeholder = 'Enter your research topic or question\n\nFor example: drop a PDF paper here and ask LDR to search for similar sources';
}
@@ -440,24 +442,32 @@ class PDFUploadHandler {
this.clearStatusTimers();
const statusDiv = this.getOrCreateStatusDiv();
+ const partialPDFs = this.uploadedPDFs.filter(pdf => pdf.truncated);
+ const partial = partialPDFs.length > 0;
// Clear existing content safely
statusDiv.textContent = '';
// Create elements safely (XSS prevention)
const container = document.createElement('div');
- container.style.color = 'var(--success-color)';
+ container.style.color = partial ? 'var(--warning-color)' : 'var(--success-color)';
const icon = document.createElement('i');
- icon.className = 'fas fa-check-circle';
+ icon.className = partial ? 'fas fa-exclamation-triangle' : 'fas fa-check-circle';
const text = document.createTextNode(
- ` Successfully processed ${processedFiles} PDF${processedFiles > 1 ? 's' : ''}`
+ ` ${partial ? 'Processed' : 'Successfully processed'} ${processedFiles} PDF${processedFiles > 1 ? 's' : ''}`
);
container.appendChild(icon);
container.appendChild(text);
+ if (partial) {
+ const warning = document.createElement('p');
+ warning.textContent = `Only part of these PDFs was extracted: ${partialPDFs.map(pdf => pdf.filename).join('; ')}. Some content is missing.`;
+ container.appendChild(warning);
+ }
+
if (errors.length > 0) {
const br = document.createElement('br');
const errorText = document.createElement('small');
@@ -471,6 +481,10 @@ class PDFUploadHandler {
statusDiv.appendChild(container);
statusDiv.style.display = 'block';
+ // Partial extraction affects the research input, so keep its warning
+ // visible until the upload state changes.
+ if (partial) return;
+
// Auto-hide after 5 seconds (store timer ID to prevent leaks)
const timerId = setTimeout(() => {
statusDiv.style.display = 'none';
@@ -560,6 +574,9 @@ class PDFUploadHandler {
*/
clearUploadedPDFs() {
this.uploadedPDFs = [];
+ this.clearStatusTimers();
+ const statusDiv = document.getElementById('pdf-upload-status');
+ if (statusDiv) statusDiv.style.display = 'none';
this.updatePlaceholder();
}
diff --git a/tests/document_loaders/test_bounded_pdf_bytes.py b/tests/document_loaders/test_bounded_pdf_bytes.py
new file mode 100644
index 0000000000..9d4d65f911
--- /dev/null
+++ b/tests/document_loaders/test_bounded_pdf_bytes.py
@@ -0,0 +1,170 @@
+"""PDF byte-loader ceilings shared by RAG uploads and Zotero sync (#6809)."""
+
+from __future__ import annotations
+
+import io
+from unittest.mock import patch
+
+import pytest
+from pypdf._page import PageObject
+
+from local_deep_research.document_loaders.bytes_loader import (
+ extract_text_from_bytes,
+ load_from_bytes,
+)
+from local_deep_research.document_loaders import bounded_pdf
+from local_deep_research.utilities import pdf_extraction_limits as limits
+
+
+def _text_pdf(*pages: str, invalid_page: int | None = None) -> bytes:
+ """Build a small valid PDF with one text stream per page."""
+ kids = " ".join(f"{4 + 2 * i} 0 R" for i in range(len(pages)))
+ objects: dict[int, bytes] = {
+ 1: b"<< /Type /Catalog /Pages 2 0 R >>",
+ 2: f"<< /Type /Pages /Kids [{kids}] /Count {len(pages)} >>".encode(),
+ 3: b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ }
+ for index, text in enumerate(pages):
+ page_id = 4 + 2 * index
+ stream_id = page_id + 1
+ stream = f"BT /F1 24 Tf 72 700 Td ({text}) Tj ET".encode()
+ objects[page_id] = (
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
+ + f"/Contents {stream_id} 0 R ".encode()
+ + b"/Resources << /Font << /F1 3 0 R >> >> >>"
+ )
+ objects[stream_id] = (
+ f"<< /Length {len(stream)} >>\nstream\n".encode()
+ + stream
+ + b"\nendstream"
+ )
+ if index == invalid_page:
+ objects[stream_id] = (
+ b"<< /Filter /NotAFilter /Length 5 >>\nstream\nhello\nendstream"
+ )
+
+ out = io.BytesIO()
+ out.write(b"%PDF-1.4\n")
+ offsets = {}
+ for number, body in sorted(objects.items()):
+ offsets[number] = out.tell()
+ out.write(f"{number} 0 obj\n".encode() + body + b"\nendobj\n")
+ xref = out.tell()
+ out.write(f"xref\n0 {max(objects) + 1}\n0000000000 65535 f \n".encode())
+ for number in range(1, max(objects) + 1):
+ out.write(f"{offsets[number]:010d} 00000 n \n".encode())
+ out.write(
+ f"trailer\n<< /Size {max(objects) + 1} /Root 1 0 R >>\n"
+ f"startxref\n{xref}\n%%EOF\n".encode()
+ )
+ return out.getvalue()
+
+
+def test_pdf_byte_loader_stops_before_third_page(monkeypatch):
+ monkeypatch.setattr(limits, "MAX_PDF_EXTRACTION_PAGES", 2)
+ pdf = _text_pdf("first", "second", "third")
+ extracted_pages = []
+ original_extract_text = PageObject.extract_text
+
+ def record_extract_text(page, *args, **kwargs):
+ extracted_pages.append(page)
+ return original_extract_text(page, *args, **kwargs)
+
+ monkeypatch.setattr(PageObject, "extract_text", record_extract_text)
+
+ documents = load_from_bytes(pdf, ".pdf", "paper.pdf")
+
+ assert [doc.page_content for doc in documents] == ["first", "second"]
+ assert len(extracted_pages) == 2
+ assert all(doc.metadata["truncated"] for doc in documents)
+ assert [doc.metadata["page"] for doc in documents] == [0, 1]
+ assert all(doc.metadata["total_pages"] == 3 for doc in documents)
+ assert (
+ extract_text_from_bytes(pdf, ".pdf", "paper.pdf") == "first\n\nsecond"
+ )
+
+
+def test_pdf_byte_loader_keeps_prefix_of_character_limit_page(monkeypatch):
+ monkeypatch.setattr(limits, "MAX_PDF_EXTRACTED_CHARS", 7)
+ pdf = _text_pdf("ABCD", "EFGH", "IJKL")
+
+ documents = load_from_bytes(pdf, ".pdf", "paper.pdf")
+
+ assert [doc.page_content for doc in documents] == ["ABCD", "E"]
+ assert all(doc.metadata["truncated"] for doc in documents)
+ assert extract_text_from_bytes(pdf, ".pdf", "paper.pdf") == "ABCD\n\nE"
+
+
[email protected]("ceiling", [5, 6, 7])
+def test_pdf_byte_loader_stops_when_separator_leaves_no_text_budget(
+ monkeypatch, ceiling
+):
+ monkeypatch.setattr(limits, "MAX_PDF_EXTRACTED_CHARS", ceiling)
+ pdf = _text_pdf("Hello", "unread", invalid_page=1)
+
+ documents = load_from_bytes(pdf, ".pdf", "paper.pdf")
+
+ assert [doc.page_content for doc in documents] == ["Hello"]
+ assert documents[0].metadata["truncated"] is True
+ assert documents[0].metadata["total_pages"] == 2
+ assert extract_text_from_bytes(pdf, ".pdf", "paper.pdf") == "Hello"
+
+
+def test_pdf_byte_loader_extracts_when_one_character_fits_after_separator(
+ monkeypatch,
+):
+ monkeypatch.setattr(limits, "MAX_PDF_EXTRACTED_CHARS", 8)
+ documents = load_from_bytes(
+ _text_pdf("Hello", "World"), ".pdf", "paper.pdf"
+ )
+
+ assert [doc.page_content for doc in documents] == ["Hello", "W"]
+ assert all(doc.metadata["truncated"] for doc in documents)
+
+
+def test_pdf_byte_loader_stops_starting_pages_at_cpu_budget(monkeypatch):
+ monkeypatch.setattr(limits, "MAX_PDF_EXTRACTION_CPU_SECONDS", 1)
+ pdf = _text_pdf("first", "second", "third")
+ with patch.object(bounded_pdf.time, "thread_time", side_effect=[0, 0, 2]):
+ documents = load_from_bytes(pdf, ".pdf", "paper.pdf")
+
+ assert [doc.page_content for doc in documents] == ["first"]
+ assert documents[0].metadata["truncated"] is True
+
+
+def test_pdf_byte_loader_releases_each_extracted_page(monkeypatch):
+ calls: list[str] = []
+
+ class RecordingReleaser:
+ def __init__(self, _reader):
+ pass
+
+ def before_page(self):
+ calls.append("before")
+
+ def after_page(self):
+ calls.append("after")
+
+ monkeypatch.setattr(bounded_pdf, "PypdfWalkReleaser", RecordingReleaser)
+ documents = load_from_bytes(_text_pdf("one", "two"), ".pdf", "paper.pdf")
+
+ assert len(documents) == 2
+ assert calls == ["before", "after", "before", "after"]
+
+
+def test_zotero_pdf_text_uses_shared_character_ceiling(monkeypatch):
+ from local_deep_research.research_library.zotero.client import ZoteroItem
+ from local_deep_research.research_library.zotero.sync_service import (
+ ZoteroSyncService,
+ )
+
+ monkeypatch.setattr(limits, "MAX_PDF_EXTRACTED_CHARS", 7)
+ item = ZoteroItem("ABCD1234", 1, "attachment", {"title": "paper.pdf"})
+ service = ZoteroSyncService.__new__(ZoteroSyncService)
+
+ text, method = service._safe_extract_text(
+ _text_pdf("ABCD", "EFGH", "IJKL"), item
+ )
+
+ assert method == "pdf_extraction"
+ assert text == "ABCD\n\nE"
diff --git a/tests/js/pdf-upload-handler-migration-contract.test.js b/tests/js/pdf-upload-handler-migration-contract.test.js
index 664562ef70..2068b2a800 100644
--- a/tests/js/pdf-upload-handler-migration-contract.test.js
+++ b/tests/js/pdf-upload-handler-migration-contract.test.js
@@ -149,6 +149,7 @@ it('uploads multipart PDFs with CSRF and consumes the extraction envelope', asyn
size: 4,
text: 'FastAPI contract text',
pages: 2,
+ truncated: false,
}]);
expect(success).toHaveBeenCalledWith(1, []);
});
@@ -189,6 +190,7 @@ it('accepts a dropped PDF while the migrated limits request is still pending', a
size: 4,
text: 'Dropped before limits hydration',
pages: 1,
+ truncated: false,
}]);
});
expect(drop.defaultPrevented).toBe(true);
@@ -339,3 +341,93 @@ it('keeps successful upload feedback visible while updating existing query text'
expect(handler.getUploadedPDFs()).toEqual([]);
expect(query.placeholder).toContain('drop a PDF paper here');
});
+
+it('keeps partial-extraction warnings visible and associates them with the successful file', async () => {
+ const filename = '<img src=x onerror="window.__pdfUploadXss=true">.pdf';
+ const combinedText = '--- From partial.pdf ---\n' +
+ '[Partial PDF extraction: only part of this document\'s text is included.]\n' +
+ 'First 500 pages';
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/api/config/limits') {
+ return Promise.resolve(jsonResponse({ max_file_size: 100, max_files: 2 }));
+ }
+ if (url === '/api/upload/pdf' && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ processed_files: 1,
+ extracted_texts: [{ filename, size: 8, text: 'First 500 pages', pages: 501, truncated: true }],
+ combined_text: combinedText,
+ errors: ['broken.pdf: No extractable text found'],
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ const handler = await loadHandler(fetchMock);
+ vi.useFakeTimers();
+
+ await handler.uploadAndExtractPDFs([
+ new File(['bad'], 'broken.pdf', { type: 'application/pdf' }),
+ new File(['%PDFdata'], filename, { type: 'application/pdf' }),
+ ]);
+
+ expect(handler.getUploadedPDFs()).toEqual([{
+ filename, size: 8, text: 'First 500 pages', pages: 501, truncated: true,
+ }]);
+ const query = document.getElementById('query');
+ expect(query.placeholder).toContain('1 PDF loaded, at least 501 pages, partial text');
+ expect(query.value).toBe(combinedText);
+ const status = document.getElementById('pdf-upload-status');
+ expect(status.textContent).toContain(`Only part of these PDFs was extracted: ${filename}`);
+ expect(status.textContent).toContain('Some content is missing');
+ expect(status.textContent).toContain('broken.pdf: No extractable text found');
+ expect(status.querySelector('.fa-exclamation-triangle')).not.toBeNull();
+ expect(status.querySelector('img')).toBeNull();
+ expect(window.__pdfUploadXss).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(status.style.display).toBe('block');
+
+ handler.clearUploadedPDFs();
+ expect(status.style.display).toBe('none');
+ expect(query.placeholder).toContain('drop a PDF paper here');
+});
+
+it('retains partial-file warnings and lower-bound totals after another complete upload', async () => {
+ let uploads = 0;
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/api/config/limits') {
+ return Promise.resolve(jsonResponse({ max_file_size: 100, max_files: 2 }));
+ }
+ if (url === '/api/upload/pdf' && options.method === 'POST') {
+ const partial = uploads++ === 0;
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ processed_files: 1,
+ extracted_texts: [{
+ filename: partial ? 'partial.pdf' : 'complete.pdf',
+ text: partial ? 'Partial paper' : 'Complete paper',
+ pages: partial ? 501 : 3,
+ truncated: partial,
+ }],
+ combined_text: partial ? 'Partial paper' : 'Complete paper',
+ errors: [],
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ const handler = await loadHandler(fetchMock);
+ vi.useFakeTimers();
+ for (const filename of ['partial.pdf', 'complete.pdf']) {
+ await handler.uploadAndExtractPDFs([
+ new File(['%PDF'], filename, { type: 'application/pdf' }),
+ ]);
+ }
+
+ expect(handler.getUploadedPDFs().map(pdf => pdf.truncated)).toEqual([true, false]);
+ expect(document.getElementById('query').placeholder)
+ .toContain('2 PDFs loaded, at least 504 pages, partial text');
+ const status = document.getElementById('pdf-upload-status');
+ expect(status.textContent).toContain('Only part of these PDFs was extracted: partial.pdf.');
+ expect(status.textContent).not.toContain('Successfully processed');
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(status.style.display).toBe('block');
+});
diff --git a/tests/web/services/test_pdf_extraction_bounds_siblings.py b/tests/web/services/test_pdf_extraction_bounds_siblings.py
new file mode 100644
index 0000000000..3250ac94c6
--- /dev/null
+++ b/tests/web/services/test_pdf_extraction_bounds_siblings.py
@@ -0,0 +1,694 @@
+"""Extraction-bound contracts for the PDF upload service.
+
+The upload service walks pages lazily and stops at the shared page,
+character, and thread-CPU ceilings in ``utilities/pdf_extraction_limits``.
+It closes each page and hands it to ``utilities/pdf_stream_release`` so
+cached decoded objects do not accumulate across a long document. The
+arXiv engine now uses the shared downloader (#6691), whose bounds are
+covered by its own tests.
+
+Most tests hand the walkers MagicMock PDFs carrying a ``.pages`` list;
+the lazy walk needs a real pdfminer document, so those tests patch
+``iter_pdfplumber_pages`` to walk the list. The tests that pin the lazy
+walk itself use small synthetic PDFs built in memory.
+"""
+
+from __future__ import annotations
+
+import io
+from itertools import chain, repeat
+from unittest.mock import MagicMock, Mock
+
+import pytest
+
+TOTAL_PAGES = 600
+
+
+def _pages(n: int, text: str = "page text"):
+ pages = []
+ for _ in range(n):
+ page = MagicMock()
+ page.extract_text.return_value = text
+ pages.append(page)
+ return pages
+
+
+SERVICE_MODULE = "local_deep_research.web.services.pdf_extraction_service"
+
+
+def _walk_mock_pages(mocker, module: str):
+ """Make *module*'s lazy page walk iterate a MagicMock PDF's
+ ``.pages`` list (the real walk needs a pdfminer document)."""
+ mocker.patch(
+ f"{module}.iter_pdfplumber_pages",
+ side_effect=lambda pdf, releaser=None: iter(pdf.pages),
+ )
+
+
+def _text_pdf(
+ n_pages: int,
+ text: str = "Hello",
+ *,
+ count: str | None = None,
+ extra_objects: dict[int, bytes] | None = None,
+ resources_entries: int = 0,
+ compressed: dict[int, tuple[int, int]] | None = None,
+) -> bytes:
+ """A valid PDF of *n_pages* pages that all show *text* (one shared
+ content stream and font), with a flat page tree declaring
+ /Count n_pages.
+
+ *count* replaces the /Count value written into the page-tree root
+ (e.g. an indirect reference into *extra_objects*, which are added
+ as numbered objects). With *resources_entries*, every page gets its
+ own indirect /Resources dictionary carrying a /ProcSet array of that
+ many entries, which pdfminer resolves while building the page.
+
+ With *compressed* (object number -> (object-stream number, index)),
+ the cross-reference is written as an uncompressed xref stream in
+ which those objects are type-2 entries (inside an object stream)
+ rather than as a classic xref table."""
+ content = f"BT /F1 12 Tf 72 700 Td ({text}) Tj ET".encode()
+ objects = {
+ 1: b"<< /Type /Catalog /Pages 2 0 R >>",
+ 3: b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ 4: b"<< /Length %d >>\nstream\n" % len(content)
+ + content
+ + b"\nendstream",
+ }
+ first_page = 5
+ kids = " ".join(f"{first_page + i} 0 R" for i in range(n_pages))
+ count_value = str(n_pages) if count is None else count
+ objects[2] = (
+ f"<< /Type /Pages /Kids [{kids}] /Count {count_value} >>".encode()
+ )
+ first_resources = first_page + n_pages
+ for i in range(n_pages):
+ if resources_entries:
+ procset = b" ".join([b"/PDF"] * resources_entries)
+ objects[first_resources + i] = (
+ b"<< /Font << /F1 3 0 R >> /ProcSet [" + procset + b"] >>"
+ )
+ resources = b"%d 0 R" % (first_resources + i)
+ else:
+ resources = b"<< /Font << /F1 3 0 R >> >>"
+ objects[first_page + i] = (
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
+ b"/Contents 4 0 R /Resources " + resources + b" >>"
+ )
+ objects.update(extra_objects or {})
+ out = io.BytesIO()
+ out.write(b"%PDF-1.4\n")
+ offsets = {}
+ for num in sorted(objects):
+ offsets[num] = out.tell()
+ out.write(b"%d 0 obj\n" % num + objects[num] + b"\nendobj\n")
+ if compressed:
+ xref_id = max([*objects, *compressed]) + 1
+ size = xref_id + 1
+ xref = out.tell()
+ offsets[xref_id] = xref
+ rows = []
+ for num in range(size):
+ if num in compressed:
+ strm, index = compressed[num]
+ rows.append(
+ b"\x02" + strm.to_bytes(4, "big") + index.to_bytes(2, "big")
+ )
+ elif num in offsets:
+ rows.append(
+ b"\x01" + offsets[num].to_bytes(4, "big") + b"\x00\x00"
+ )
+ else:
+ rows.append(b"\x00" * 7)
+ data = b"".join(rows)
+ out.write(
+ b"%d 0 obj\n<< /Type /XRef /Size %d /W [1 4 2] /Root 1 0 R "
+ b"/Length %d >>\nstream\n"
+ % (xref_id, size, len(data))
+ + data
+ + b"\nendstream\nendobj\nstartxref\n%d\n%%%%EOF\n" % xref
+ )
+ return out.getvalue()
+ size = max(objects) + 1
+ xref = out.tell()
+ out.write(b"xref\n0 %d\n0000000000 65535 f \n" % size)
+ for num in range(1, size):
+ if num in offsets:
+ out.write(b"%010d 00000 n \n" % offsets[num])
+ else:
+ out.write(b"0000000000 65535 f \n")
+ out.write(
+ b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n"
+ % (size, xref)
+ )
+ return out.getvalue()
+
+
+def _count_built_pages(mocker):
+ """Count the pdfminer PDFPage objects built from here on (what
+ pdfplumber's eager ``PDF.pages`` builds for every page)."""
+ from pdfminer.pdfpage import PDFPage
+
+ return mocker.spy(PDFPage, "__init__")
+
+
+class TestUploadPathExtractionService:
+ def _service(self):
+ from local_deep_research.web.services.pdf_extraction_service import (
+ PDFExtractionService,
+ )
+
+ return PDFExtractionService()
+
+ def _extract(self, mocker, pages):
+ mock_pdf = MagicMock()
+ mock_pdf.pages = pages
+ mock_pdf.__enter__ = Mock(return_value=mock_pdf)
+ mock_pdf.__exit__ = Mock(return_value=False)
+ mocker.patch(
+ "local_deep_research.web.services.pdf_extraction_service."
+ "pdfplumber.open",
+ return_value=mock_pdf,
+ )
+ _walk_mock_pages(mocker, SERVICE_MODULE)
+ return self._service().extract_text_and_metadata(
+ b"%PDF-fake", "hostile.pdf"
+ )
+
+ @pytest.mark.parametrize("ceiling", [5, 6])
+ def test_no_extraction_when_separator_leaves_no_character_budget(
+ self, monkeypatch, ceiling
+ ):
+ monkeypatch.setattr(
+ f"{SERVICE_MODULE}.MAX_PDF_EXTRACTED_CHARS", ceiling
+ )
+ pdf = _text_pdf(
+ 2,
+ "Hello",
+ extra_objects={
+ 6: (
+ b"<< /Type /Page /Parent 2 0 R "
+ b"/MediaBox [0 0 612 792] /Contents 8 0 R "
+ b"/Resources << /Font << /F1 3 0 R >> >> >>"
+ ),
+ 8: (
+ b"<< /Filter /NotAFilter /Length 5 >>\nstream\n"
+ b"hello\nendstream"
+ ),
+ },
+ )
+
+ result = self._service().extract_text_and_metadata(pdf, "paper.pdf")
+
+ assert result["success"] is True
+ assert result["text"] == "Hello"
+ assert result["truncated"] is True
+ assert result["pages"] == 2
+
+ def test_extracts_when_one_character_fits_after_separator(
+ self, monkeypatch
+ ):
+ monkeypatch.setattr(f"{SERVICE_MODULE}.MAX_PDF_EXTRACTED_CHARS", 7)
+
+ result = self._service().extract_text_and_metadata(
+ _text_pdf(2, "Hello"), "paper.pdf"
+ )
+
+ assert result["success"] is True
+ assert result["text"] == "Hello\nH"
+ assert result["truncated"] is True
+
+ def test_pathological_page_count_is_not_fully_walked(self, mocker):
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTION_PAGES,
+ )
+
+ pages = _pages(TOTAL_PAGES)
+
+ result = self._extract(mocker, pages)
+
+ walked = sum(1 for page in pages if page.extract_text.called)
+ assert 0 < walked < TOTAL_PAGES, (
+ f"extraction walked {walked} of {TOTAL_PAGES} pages — no page "
+ "ceiling is in force on the upload path"
+ )
+ assert result["success"]
+ assert result["truncated"] is True
+ # The pages after the ceiling are never built: the count
+ # reported is the pages the walk reached, a lower bound.
+ assert result["pages"] == MAX_PDF_EXTRACTION_PAGES + 1
+
+ def test_page_ceiling_is_exact(self, mocker):
+ """Exactly MAX_PDF_EXTRACTION_PAGES pages are walked; the next
+ one is not."""
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTION_PAGES,
+ )
+
+ pages = _pages(MAX_PDF_EXTRACTION_PAGES + 1)
+
+ result = self._extract(mocker, pages)
+
+ assert all(
+ page.extract_text.called
+ for page in pages[:MAX_PDF_EXTRACTION_PAGES]
+ )
+ assert not pages[MAX_PDF_EXTRACTION_PAGES].extract_text.called
+ assert result["truncated"] is True
+
+ def test_document_at_page_ceiling_is_not_truncated(self, mocker):
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTION_PAGES,
+ )
+
+ pages = _pages(MAX_PDF_EXTRACTION_PAGES)
+
+ result = self._extract(mocker, pages)
+
+ assert all(page.extract_text.called for page in pages)
+ assert result["truncated"] is False
+ assert result["text"] == "\n".join(["page text"] * len(pages))
+
+ def test_decompression_sized_text_is_capped(self, mocker):
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTED_CHARS,
+ )
+
+ pages = _pages(100, text="x" * 200_000)
+
+ result = self._extract(mocker, pages)
+
+ assert result["success"]
+ assert result["truncated"] is True, (
+ "character-ceiling trip was not reported on the upload path"
+ )
+ assert len(result["text"]) == MAX_PDF_EXTRACTED_CHARS, (
+ "extraction did not return exactly the character ceiling's "
+ "worth of text, separators included"
+ )
+
+ def test_first_page_over_the_ceiling_yields_its_prefix(self, mocker):
+ """A single page larger than the ceiling is truncated, not
+ dropped: the upload succeeds with the budget's worth of text."""
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTED_CHARS,
+ )
+
+ pages = _pages(1, text="x" * (MAX_PDF_EXTRACTED_CHARS + 1)) + _pages(1)
+
+ result = self._extract(mocker, pages)
+
+ assert result["success"] is True, result["error"]
+ assert result["truncated"] is True
+ assert result["text"] == "x" * MAX_PDF_EXTRACTED_CHARS
+ assert not pages[1].extract_text.called
+
+ def test_text_of_exactly_the_ceiling_is_kept_whole(self, mocker):
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTED_CHARS,
+ )
+
+ pages = _pages(1, text="x" * MAX_PDF_EXTRACTED_CHARS)
+
+ result = self._extract(mocker, pages)
+
+ assert result["success"] is True
+ assert result["truncated"] is False
+ assert len(result["text"]) == MAX_PDF_EXTRACTED_CHARS
+
+ def test_join_separators_count_against_the_ceiling(self, mocker):
+ """Two halves of the ceiling fit as text alone, but not with the
+ "\\n" that joins them: the output must still not exceed it."""
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTED_CHARS,
+ )
+
+ half = MAX_PDF_EXTRACTED_CHARS // 2
+ pages = _pages(2, text="x" * half)
+
+ result = self._extract(mocker, pages)
+
+ assert len(result["text"]) == MAX_PDF_EXTRACTED_CHARS
+ assert result["text"] == "x" * half + "\n" + "x" * (half - 1)
+ assert result["truncated"] is True
+
+ def test_each_page_is_closed_after_extraction(self, mocker):
+ pages = _pages(3)
+
+ self._extract(mocker, pages)
+
+ for page in pages:
+ page.close.assert_called_once_with()
+
+ def test_truncated_is_reported_on_every_result(self, mocker):
+ no_text = self._extract(mocker, _pages(2, text=""))
+ assert no_text["success"] is False
+ assert no_text["truncated"] is False
+
+ mocker.patch(
+ "local_deep_research.web.services.pdf_extraction_service."
+ "pdfplumber.open",
+ side_effect=Exception("broken pdf"),
+ )
+ failed = self._service().extract_text_and_metadata(
+ b"%PDF-fake", "hostile.pdf"
+ )
+ assert failed["success"] is False
+ assert failed["truncated"] is False
+
+
+class TestUploadPathLazyWalkAndBudgets:
+ """Behaviour wired in from #6459/#6782: the lazy page walk, the CPU
+ budget and the cache releaser on the upload path."""
+
+ def _service(self):
+ from local_deep_research.web.services.pdf_extraction_service import (
+ PDFExtractionService,
+ )
+
+ return PDFExtractionService()
+
+ @pytest.mark.timeout(60)
+ def test_pages_past_the_ceiling_are_never_built(self, mocker):
+ """A document declaring more pages than the ceiling has only the
+ ceiling's pages (plus the one that shows there are more) built.
+ pdfplumber's ``PDF.pages`` -- also reached through
+ ``PDF.close()`` when leaving a ``with pdfplumber.open(...)``
+ block -- would build all of them."""
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTION_PAGES,
+ )
+
+ declared = MAX_PDF_EXTRACTION_PAGES + 20
+ pdf_bytes = _text_pdf(declared)
+ built = _count_built_pages(mocker)
+
+ result = self._service().extract_text_and_metadata(
+ pdf_bytes, "many-pages.pdf"
+ )
+
+ assert result["success"] is True, result["error"]
+ assert result["truncated"] is True
+ assert built.call_count == MAX_PDF_EXTRACTION_PAGES + 1, (
+ f"{built.call_count} of {declared} pages were built -- the "
+ "upload path materialises the whole page tree"
+ )
+ # The unbuilt rest is not reported: /Count is never read, so
+ # pages is the walk's lower bound (the ceiling plus the page
+ # that showed there are more), flagged by truncated.
+ assert result["pages"] == MAX_PDF_EXTRACTION_PAGES + 1
+ assert result["text"] == "\n".join(["Hello"] * MAX_PDF_EXTRACTION_PAGES)
+
+ def test_short_document_reports_the_pages_walked(self):
+ result = self._service().extract_text_and_metadata(
+ _text_pdf(3), "short.pdf"
+ )
+
+ assert result["success"] is True, result["error"]
+ assert result["truncated"] is False
+ assert result["pages"] == 3
+ assert result["text"] == "Hello\nHello\nHello"
+
+ def test_page_ceiling_reports_the_pages_seen(self, mocker):
+ """A walk stopped by the page ceiling reports the pages seen
+ (the ceiling plus one)."""
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTION_PAGES,
+ )
+
+ mock_pdf = MagicMock()
+ mock_pdf.pages = _pages(MAX_PDF_EXTRACTION_PAGES + 5)
+ mocker.patch(f"{SERVICE_MODULE}.pdfplumber.open", return_value=mock_pdf)
+ _walk_mock_pages(mocker, SERVICE_MODULE)
+
+ result = self._service().extract_text_and_metadata(b"%PDF", "x.pdf")
+
+ assert result["truncated"] is True
+ assert result["pages"] == MAX_PDF_EXTRACTION_PAGES + 1
+
+ def test_cpu_budget_stops_the_walk_between_pages(self, mocker):
+ """Once the thread's CPU budget is spent no new page starts."""
+ from local_deep_research.web.services import pdf_extraction_service
+
+ # Entry (deadline base), first page check, then budget exhausted.
+ clock = Mock(side_effect=chain([0.0, 0.0], repeat(1e12)))
+ mocker.patch.object(
+ pdf_extraction_service, "time", Mock(thread_time=clock)
+ )
+ pages = _pages(5)
+ mock_pdf = MagicMock()
+ mock_pdf.pages = pages
+ mocker.patch(f"{SERVICE_MODULE}.pdfplumber.open", return_value=mock_pdf)
+ _walk_mock_pages(mocker, SERVICE_MODULE)
+
+ result = self._service().extract_text_and_metadata(b"%PDF", "x.pdf")
+
+ walked = [page.extract_text.called for page in pages]
+ assert walked == [True, False, False, False, False]
+ assert result["success"] is True
+ assert result["truncated"] is True
+ assert result["text"] == "page text"
+ # The page that met the spent budget is still closed.
+ pages[1].close.assert_called_once_with()
+
+ def test_every_page_is_handed_to_the_cache_releaser(self, mocker):
+ """With the release threshold at zero the releaser runs after
+ every page, so the decoded streams and parsed objects pdfminer
+ caches on the document cannot pile up across the walk."""
+ from local_deep_research.utilities import (
+ pdf_extraction_limits,
+ pdf_stream_release,
+ )
+
+ mocker.patch.object(
+ pdf_extraction_limits, "MAX_PDF_RETAINED_DECODED_BYTES", 0
+ )
+ after_page = mocker.spy(
+ pdf_stream_release.PdfplumberWalkReleaser, "after_page"
+ )
+
+ result = self._service().extract_text_and_metadata(
+ _text_pdf(3), "three.pdf"
+ )
+
+ assert result["text"] == "Hello\nHello\nHello"
+ assert after_page.call_count == 3
+ assert after_page.spy_return_list == [True, True, True]
+
+ def test_close_failure_does_not_mask_the_text(self, mocker):
+ pages = _pages(2)
+ for page in pages:
+ page.close.side_effect = RuntimeError("close failed")
+ mock_pdf = MagicMock()
+ mock_pdf.pages = pages
+ mocker.patch(f"{SERVICE_MODULE}.pdfplumber.open", return_value=mock_pdf)
+ _walk_mock_pages(mocker, SERVICE_MODULE)
+
+ result = self._service().extract_text_and_metadata(b"%PDF", "x.pdf")
+
+ assert result["success"] is True
+ assert result["text"] == "page text\npage text"
+
+
+class TestPageWalkHelpers:
+ def test_lazy_walk_matches_pdfplumber_pages(self):
+ import pdfplumber
+
+ from local_deep_research.utilities.pdf_page_walk import (
+ iter_pdfplumber_pages,
+ )
+
+ pdf_bytes = _text_pdf(4)
+ with pdfplumber.open(io.BytesIO(pdf_bytes)) as eager:
+ expected = [
+ (p.page_number, p.initial_doctop, p.extract_text())
+ for p in eager.pages
+ ]
+ lazy = pdfplumber.open(io.BytesIO(pdf_bytes))
+ got = [
+ (p.page_number, p.initial_doctop, p.extract_text())
+ for p in iter_pdfplumber_pages(lazy)
+ ]
+
+ assert got == expected
+ assert not hasattr(lazy, "_pages")
+
+ @pytest.mark.parametrize(
+ "pdf_kwargs",
+ [
+ pytest.param(
+ {"extra_objects": {90: b"90 0 R"}}, id="self-reference"
+ ),
+ pytest.param(
+ # /Count is a type-2 xref entry in an object stream whose
+ # own object is a self-reference: getobj -> stream_value
+ # -> resolve1 spins inside pdfminer.
+ {
+ "extra_objects": {91: b"91 0 R"},
+ "compressed": {90: (91, 0)},
+ },
+ id="object-stream-cycle",
+ ),
+ pytest.param(
+ # /Count is a stream whose /Length is a self-reference:
+ # the parser's int_value -> resolve1 spins.
+ {
+ "extra_objects": {
+ 90: b"<< /Length 91 0 R >>\nstream\nxx\nendstream",
+ 91: b"91 0 R",
+ }
+ },
+ id="length-cycle",
+ ),
+ ],
+ )
+ def test_upload_service_survives_a_cyclic_count(self, mocker, pdf_kwargs):
+ """A truncated walk must not resolve the page tree's /Count:
+ each of these makes pdfminer loop forever on the resolve, after
+ the CPU budget has stopped applying. The service never reads
+ /Count, so it returns promptly with the pages it saw."""
+ import threading
+
+ from local_deep_research.web.services import pdf_extraction_service
+
+ mocker.patch.object(
+ pdf_extraction_service, "MAX_PDF_EXTRACTION_PAGES", 1
+ )
+ pdf_bytes = _text_pdf(2, count="90 0 R", **pdf_kwargs)
+ result = []
+ worker = threading.Thread(
+ target=lambda: result.append(
+ pdf_extraction_service.PDFExtractionService.extract_text_and_metadata(
+ pdf_bytes, "cyclic.pdf"
+ )
+ ),
+ daemon=True,
+ )
+ worker.start()
+ worker.join(timeout=10)
+
+ assert not worker.is_alive(), "the upload service looped on /Count"
+ assert result[0]["truncated"] is True
+ assert result[0]["pages"] == 2
+ assert result[0]["text"] == "Hello"
+
+
+class TestReleaseCoversPageConstruction:
+ """Building a page (``next()`` on pdfminer's page generator) resolves
+ its /Resources and /Contents. The lazy walks open the releaser's
+ window before that, so a page whose indirect /Resources carries a
+ large array is counted and released. With the window opened only
+ before ``extract_text()``, those objects were cached outside every
+ window and never counted: ~8M cached array elements at 40 pages."""
+
+ # Each page's /Resources array alone reaches the release threshold
+ # below; nothing else a page caches comes near it.
+ ENTRIES = 200
+ LIMIT = 128 * 150
+
+ def test_upload_service_releases_what_building_a_page_cached(self, mocker):
+ from local_deep_research.utilities import (
+ pdf_extraction_limits,
+ pdf_stream_release,
+ )
+ from local_deep_research.web.services.pdf_extraction_service import (
+ PDFExtractionService,
+ )
+
+ mocker.patch.object(
+ pdf_extraction_limits, "MAX_PDF_RETAINED_DECODED_BYTES", self.LIMIT
+ )
+ after_page = mocker.spy(
+ pdf_stream_release.PdfplumberWalkReleaser, "after_page"
+ )
+
+ result = PDFExtractionService.extract_text_and_metadata(
+ _text_pdf(3, resources_entries=self.ENTRIES), "res.pdf"
+ )
+
+ assert result["text"] == "Hello\nHello\nHello"
+ assert after_page.spy_return_list == [True, True, True]
+
+
+def upload_client(monkeypatch):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from local_deep_research.web.dependencies.rate_limit import limiter
+ from local_deep_research.web.routers import research
+
+ monkeypatch.setattr(limiter, "enabled", False)
+ app = FastAPI()
+ app.include_router(research.router)
+ app.dependency_overrides[research.require_auth] = lambda: "test_pdf_upload"
+ with TestClient(app) as client:
+ yield client
+
+
+ ("pages", "extracted_pages", "reported_pages", "truncated"),
+ [(520, 500, 501, True), (3, 3, 3, False)],
+)
+def test_upload_endpoint_reports_partial_extraction(
+ upload_client, pages, extracted_pages, reported_pages, truncated
+):
+ """Exercise real multipart validation and extraction, not a mock result."""
+ response = upload_client.post(
+ "/api/upload/pdf",
+ files={"files": ("paper.pdf", _text_pdf(pages), "application/pdf")},
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ item = body["extracted_texts"][0]
+ assert item["truncated"] is truncated
+ assert item["pages"] == reported_pages
+ assert item["text"] == "\n".join(["Hello"] * extracted_pages)
+ assert ("[Partial PDF extraction:" in body["combined_text"]) is truncated
+ assert body["errors"] == []
+
+
[email protected]("ceiling", ["characters", "cpu"])
+def test_upload_endpoint_reports_other_extraction_limits(
+ upload_client, monkeypatch, ceiling
+):
+ from local_deep_research.web.services import pdf_extraction_service
+
+ if ceiling == "characters":
+ monkeypatch.setattr(
+ pdf_extraction_service, "MAX_PDF_EXTRACTED_CHARS", 10
+ )
+ expected = "Hello\nHell"
+ else:
+ clock = Mock(side_effect=chain([0.0, 0.0], repeat(1e12)))
+ monkeypatch.setattr(
+ pdf_extraction_service, "time", Mock(thread_time=clock)
+ )
+ expected = "Hello"
+
+ response = upload_client.post(
+ "/api/upload/pdf",
+ files={"files": ("paper.pdf", _text_pdf(3), "application/pdf")},
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ item = body["extracted_texts"][0]
+ assert item["truncated"] is True
+ assert item["pages"] == 2
+ assert item["text"] == expected
+ assert "[Partial PDF extraction:" in body["combined_text"]
+
+
+def test_ceiling_values_are_pinned():
+ """The constants are shared with the download-service bounds (#6459);
+ this pins them across merges."""
+ from local_deep_research.utilities.pdf_extraction_limits import (
+ MAX_PDF_EXTRACTED_CHARS,
+ MAX_PDF_EXTRACTION_PAGES,
+ )
+
+ assert MAX_PDF_EXTRACTION_PAGES == 500
+ assert MAX_PDF_EXTRACTED_CHARS == 10_000_000
diff --git a/tests/web/services/test_pdf_extraction_service.py b/tests/web/services/test_pdf_extraction_service.py
index 542b42a4a7..3e6f9e99dd 100644
--- a/tests/web/services/test_pdf_extraction_service.py
+++ b/tests/web/services/test_pdf_extraction_service.py
@@ -9,6 +9,28 @@ Tests cover:
from unittest.mock import Mock, patch, MagicMock
+import pytest
+
+
[email protected](autouse=True)
+def _walk_mocked_pdfs_through_their_pages_list(monkeypatch):
+ """The service walks the page tree lazily (``iter_pdfplumber_pages``),
+ which needs a real pdfminer document. The mocked tests here hand it a
+ MagicMock PDF with a ``.pages`` list, so walk that list for them; a
+ real ``pdfplumber.PDF`` still goes through the real lazy walk."""
+ import pdfplumber
+
+ from local_deep_research.web.services import pdf_extraction_service
+
+ real_walk = pdf_extraction_service.iter_pdfplumber_pages
+
+ def walk(pdf, releaser=None):
+ if isinstance(pdf, pdfplumber.PDF):
+ return real_walk(pdf, releaser)
+ return iter(pdf.pages)
+
+ monkeypatch.setattr(pdf_extraction_service, "iter_pdfplumber_pages", walk)
+
class TestExtractTextAndMetadata:
"""Tests for extract_text_and_metadata method."""
diff --git a/tests/web_services/test_pdf_extraction_service.py b/tests/web_services/test_pdf_extraction_service.py
index 0476eb5091..569f592faa 100644
--- a/tests/web_services/test_pdf_extraction_service.py
+++ b/tests/web_services/test_pdf_extraction_service.py
@@ -5,6 +5,28 @@ Tests PDF text extraction, metadata extraction, and batch processing.
from unittest.mock import Mock, patch, MagicMock
+import pytest
+
+
[email protected](autouse=True)
+def _walk_mocked_pdfs_through_their_pages_list(monkeypatch):
+ """The service walks the page tree lazily (``iter_pdfplumber_pages``),
+ which needs a real pdfminer document. The mocked tests here hand it a
+ MagicMock PDF with a ``.pages`` list, so walk that list for them; a
+ real ``pdfplumber.PDF`` still goes through the real lazy walk."""
+ import pdfplumber
+
+ from local_deep_research.web.services import pdf_extraction_service
+
+ real_walk = pdf_extraction_service.iter_pdfplumber_pages
+
+ def walk(pdf, releaser=None):
+ if isinstance(pdf, pdfplumber.PDF):
+ return real_walk(pdf, releaser)
+ return iter(pdf.pages)
+
+ monkeypatch.setattr(pdf_extraction_service, "iter_pdfplumber_pages", walk)
+
class TestPDFExtractionServiceExtractTextAndMetadata:
"""Tests for extract_text_and_metadata method."""