diff --git a/decisions.md b/decisions.md index 93c9f5d47..65f36a581 100644 --- a/decisions.md +++ b/decisions.md @@ -6853,7 +6853,9 @@ typed reason and no partial reading. The PDF has one effective pre-OCR size limit: the lower of the family reading limit and the configured provider's input ceiling. Exceeding it leaves the original stored but fails the version with a typed limit reason, without a -card or `document.md` reading. +card or `document.md` reading. *(Superseded 2026-11-07 by D147 item 4: the +provider ceiling no longer limits a PDF, which is OCR'd in page batches; the +family reading limit applies only on the bytes path.)* **Context and alternatives.** The owner restated the explicit requirement on 2026-09-27: “EVERY PDF and every page goes through OCR. No question asked.” @@ -7423,6 +7425,25 @@ deployment's values into another's work. 2026-11-07): a file over its limit whose route fetches it by URL from a presigning store goes to that route instead of being refused (PDF) or carded. A route's own declared `provider_limit_bytes` still applies. + - *PDF OCR in page batches (2026-11-07, owner: no caps).* The OCR provider takes about + 50 MB and 1,000 pages per request (`MistralOcrSettings.max_document_bytes`, + `max_document_pages`). A PDF over either is split with pdfium into page-range PDFs + that each fit. Each page is first measured alone (a one-page PDF saved to a + counter from a freshly opened source), and a batch takes pages while those sizes add up to at most the byte + ceiling, so no candidate runs past what fits whatever the page sizes (it is shrunk + in the rare case its own save is still over); each batch is OCR'd, its pages are + renumbered from the batch's first page, and the folded response is metered (every source page, one + `ocr` usage event) and normalized exactly like one call, so every page is still + OCR'd. Each batch's own response metadata is kept under `batches` in the interchange + asset. Below both ceilings the request and the result are unchanged, so no version + changes. Only a single page over the byte ceiling fails. Each candidate batch is + built in one locked pdfium operation (open, copy pages, save to a temporary file, + close), so nothing native outlives the lock; only a batch that fits is read. A + failure after billed batches (including a disk error while splitting, which pdfium's + save would otherwise swallow) carries their usage. `PdfConverter.convert_path(path, + mime)` and `MistralOcrConverter.convert_path` do the same from a file on disk, for a + host (such as a conversion service fed by URL) that must not hold a large PDF in + memory; the PDF route no longer declares a pre-OCR byte limit. - *Register a stored object (2026-11-07).* `UploadIngestor.ingest_stored(deployment_id, key, size, mime, filename, title=None, source_path=None, ingested_by=None)` ingests a file a client wrote to the raw store itself (direct multipart upload by pre-signed diff --git a/plan/designs/format_conversion_design.md b/plan/designs/format_conversion_design.md index 95f406d9c..43f472f0d 100644 --- a/plan/designs/format_conversion_design.md +++ b/plan/designs/format_conversion_design.md @@ -73,7 +73,7 @@ setting one route never removes the others. Every file is stored. Outcomes: |---|---| | Bytes a declaration contradicts (D132) | Refused with a typed error | | Bytes not recognized as any family | Stored; a `binary` card (D138 §6) | -| Over the family's reading limit | Stored; the head/tail profile for text, otherwise a card stating the reason (D138 §3, §5.2), except PDF: its effective pre-OCR limit is the lower of the family limit and provider input ceiling, and exceeding it fails the version with a typed reason, no card and no `document.md` reading. The reading limit guards the engine process, which would read the file: when the file's route fetches it by URL from a presigning store (D147), the file goes to that route instead, and only the route's own provider ceiling applies | +| Over the family's reading limit | Stored; the head/tail profile for text, otherwise a card stating the reason (D138 §3, §5.2), except PDF: exceeding its family limit fails the version with a typed reason, no card and no `document.md` reading. The OCR provider's per-request ceilings (bytes and pages) are not a limit on the PDF: a larger PDF is split into page-range batches that each fit, every batch is OCR'd, and the pages are renumbered and stitched in order (D147); only a single page over the byte ceiling fails. The reading limit guards the engine process, which would read the file: when the file's route fetches it by URL from a presigning store (D147), the file goes to that route instead, and only the route's own provider ceiling applies | | Family recognized but its converter not built | Stored; conversion parks with `no_route` (D117) until it is | | Family on, converter needs an unconfigured provider | Stored; conversion parks with `no_route` (D117); `resume-no-route` releases it after configuration | | Family on and ready | Stored and converted | diff --git a/plan/designs/workspace_formats_design.md b/plan/designs/workspace_formats_design.md index dabd45cb2..8283d983b 100644 --- a/plan/designs/workspace_formats_design.md +++ b/plan/designs/workspace_formats_design.md @@ -76,19 +76,22 @@ full input. Unknown binary remains stored as a card under D138. conversion-route setting **adds or overrides** entries (for example, routing images to the D115 OCR-and-description converter once provider keys exist); it no longer replaces the table. The PDF invariant survives overlays: a PDF route must OCR every page and cannot -be replaced by text-layer extraction or by a per-page split. +be replaced by text-layer extraction. Sending a large PDF to the OCR provider in +page-range batches is not a replacement: every page of every batch is still OCR'd +(D147). **Size.** Every file is stored. A file larger than its family's reading limit -gets a card that says why, except a PDF. The PDF has one **effective pre-OCR -limit**, the lower of the family reading limit and the configured OCR -provider's input ceiling. Exceeding it leaves the original stored but fails -the version with a typed limit reason, no card and no `document.md` reading; -the check runs before any converter call. If a provider reports a smaller -ceiling only after admission, conversion fails with a typed provider-limit -reason, again without a card. Starting family values: 100 MB for office -documents and PDF, 200 MB for spreadsheets (profiled from sheet dimensions -only above 50 MB). For example, a 100 MB PDF family limit and a 50 MB OCR -provider ceiling give one effective pre-OCR limit of 50 MB. +gets a card that says why, except a PDF: a PDF over its family limit leaves the +original stored but fails the version with a typed limit reason, no card and no +`document.md` reading; the check runs before any converter call. The reading +limits guard the engine process, which would read the file, so they do not +apply when the file's route fetches it by URL (D147). The OCR provider's +per-request ceilings (bytes and pages) are not a limit on the PDF: a larger PDF +is OCR'd in page-range batches that each fit, and only a single page over the +byte ceiling fails. Starting family values: 100 MB for office documents and +PDF, 200 MB for spreadsheets (profiled from sheet dimensions only above 50 MB). +For example, a 70 MB PDF with a 50 MB OCR provider ceiling is OCR'd in two or +more batches. ## 4. The family table diff --git a/src/rememberstack/adapters/converters/__init__.py b/src/rememberstack/adapters/converters/__init__.py index e92833853..c7411c05c 100644 --- a/src/rememberstack/adapters/converters/__init__.py +++ b/src/rememberstack/adapters/converters/__init__.py @@ -66,7 +66,9 @@ def build_conversion_routes(*, route_names: Mapping[str, str]) -> dict[str, Conv if pdf_requested: ocr = built.get("mistral_ocr") or _mistral_ocr() assert settings is not None - built["pdf"] = _pdf(ocr=ocr, provider_limit_bytes=settings.max_document_bytes) + # No pre-OCR byte ceiling: the OCR route sends a larger PDF in page + # batches that each fit the provider (D147). + built["pdf"] = _pdf(ocr=ocr) return { mime: built["pdf"] if mime == "application/pdf" else built[name] for mime, name in route_names.items() diff --git a/src/rememberstack/adapters/converters/mistral_ocr.py b/src/rememberstack/adapters/converters/mistral_ocr.py index 6211c9c9a..f8cf1889b 100644 --- a/src/rememberstack/adapters/converters/mistral_ocr.py +++ b/src/rememberstack/adapters/converters/mistral_ocr.py @@ -17,6 +17,7 @@ import base64 from decimal import Decimal import json +from pathlib import Path import re import time from typing import Any @@ -30,7 +31,12 @@ from pydantic_settings import BaseSettings from pydantic_settings import SettingsConfigDict +from rememberstack.adapters.converters.pdf import pdf_page_batches from rememberstack.adapters.converters.pdf import pdf_page_count +from rememberstack.adapters.converters.pdf import pdf_source_has_body +from rememberstack.adapters.converters.pdf import pdf_source_page_count +from rememberstack.adapters.converters.pdf import pdf_source_size +from rememberstack.adapters.converters.pdf import PdfSource from rememberstack.core.content_detection import has_pdf_body from rememberstack.model import ConversionCoverage from rememberstack.model import ConversionError @@ -72,7 +78,11 @@ class MistralOcrSettings(BaseSettings): model: str = "mistral-ocr-latest" timeout_s: float = Field(default=300.0, gt=0) max_document_bytes: int = Field(default=50_000_000, gt=0) - """Provider request ceiling; larger inputs fail deterministically.""" + """Provider request ceiling. A larger PDF is sent in page batches that + each fit it (D147); any other larger input fails deterministically.""" + max_document_pages: int = Field(default=1_000, gt=0) + """Provider page ceiling per request; a longer PDF is sent in batches. + Neither ceiling changes the output, so neither joins the version.""" include_images: bool = True table_format: Literal["markdown", "html"] = "markdown" extract_headers_and_footers: bool = True @@ -140,18 +150,45 @@ def version(self) -> str: option change creates new representations instead of replaying old ones.""" return f"{MISTRAL_OCR_CONVERTER_VERSION}:{self._settings.version_fingerprint()}" - def convert(self, *, content: bytes, mime: str) -> ConversionResult: - """OCR one document via `/v1/ocr` and normalize the full response.""" - if len(content) > self._settings.max_document_bytes: + def convert_path(self, *, path: Path, mime: str) -> ConversionResult: + """:meth:`convert` for a document on local disk (D147). + + A PDF over the provider's ceilings is sent in page batches read + lazily from the file, so only one batch is in memory; anything that + fits is read and sent whole, exactly as :meth:`convert` sends it. + """ + if mime == "application/pdf" and pdf_source_has_body(source=path): + pages = pdf_source_page_count(source=path) + if self._over_ceiling(size=pdf_source_size(source=path), pages=pages): + return self._batched_pdf(source=path, source_pages=pages) + if pdf_source_size(source=path) > self._settings.max_document_bytes: raise ConversionError( - f"document of {len(content)} bytes exceeds the configured " - f"mistral_ocr ceiling of {self._settings.max_document_bytes}" + f"document of {pdf_source_size(source=path)} bytes exceeds the " + f"configured mistral_ocr ceiling of {self._settings.max_document_bytes}" ) + return self.convert(content=path.read_bytes(), mime=mime) + + def convert(self, *, content: bytes, mime: str) -> ConversionResult: + """OCR one document via `/v1/ocr` and normalize the full response. + + A PDF over the provider's byte or page ceiling is OCR'd in page + batches and stitched in page order (D147); below both ceilings the + request and the result are exactly the single-call ones. + """ source_pages = ( pdf_page_count(content=content) if mime == "application/pdf" and has_pdf_body(content=content) else None ) + if source_pages is not None and self._over_ceiling( + size=len(content), pages=source_pages + ): + return self._batched_pdf(source=content, source_pages=source_pages) + if len(content) > self._settings.max_document_bytes: + raise ConversionError( + f"document of {len(content)} bytes exceeds the configured " + f"mistral_ocr ceiling of {self._settings.max_document_bytes}" + ) started_ns = time.monotonic_ns() raw = self._process( content=content, mime=mime, allow_empty_pages=source_pages is not None @@ -198,6 +235,129 @@ def convert(self, *, content: bytes, mime: str) -> ConversionResult: update={"usage_events": (ConverterUsageEvent(call_key="ocr", usage=usage),)} ) + def _over_ceiling(self, *, size: int, pages: int) -> bool: + """Whether one request could not carry this PDF.""" + return ( + size > self._settings.max_document_bytes + or pages > self._settings.max_document_pages + ) + + def _batched_pdf(self, *, source: PdfSource, source_pages: int) -> ConversionResult: + """OCR a PDF over the provider's ceilings in page batches. + + Each batch is its own call; the pages come back numbered from zero, + are renumbered from the batch's first page, and are folded into one + response that is metered and normalized exactly like a single call. + A failure after billed batches carries their usage. + """ + settings = self._settings + started_ns = time.monotonic_ns() + merged: dict[str, Any] | None = None + pages: list[dict[str, Any]] = [] + billed = 0 + totals: list[object] = [] + described: list[dict[str, Any]] = [] + + def billed_usage() -> tuple[ConverterUsageEvent, ...]: + usage = _usage( + raw=merged or {}, + settings=settings, + latency_ms=(time.monotonic_ns() - started_ns) // 1_000_000, + source_pages=billed, + ) + return (ConverterUsageEvent(call_key="ocr", usage=usage),) + + batches = pdf_page_batches( + source=source, + max_bytes=settings.max_document_bytes, + max_pages=settings.max_document_pages, + ) + try: + for first, count, batch in batches: + raw = self._process( + content=batch, mime="application/pdf", allow_empty_pages=True + ) + billed += count + batch_pages = raw.get("pages") + indexes = ( + [page.get("index") for page in batch_pages] + if isinstance(batch_pages, list) + and all(isinstance(page, dict) for page in batch_pages) + else [] + ) + if merged is None: + merged = raw + if not all(type(index) is int for index in indexes) or sorted( + indexes + ) != list(range(count)): + raise ConverterLaneError( + f"PDF OCR incomplete: expected {count} pages from the batch " + f"at page {first + 1}, received page indexes {indexes}", + usage_events=billed_usage(), + failed_call_keys=("ocr",), + retryable=False, + ) + assert isinstance(batch_pages, list) + pages.extend( + {**page, "index": page["index"] + first} + for page in sorted(batch_pages, key=lambda page: page["index"]) + ) + totals.append(raw.get("usage_info")) + described.append( + { + "first_page": first + 1, + "page_count": count, + **{key: value for key, value in raw.items() if key != "pages"}, + } + ) + except (ConversionError, MistralOcrProviderError, OSError) as err: + # Splitting, its disk spool or a later call failed after earlier + # batches were billed: their usage must still reach the ledger. + if not billed: + raise + raise ConverterLaneError( + f"PDF OCR stopped after {billed} of {source_pages} pages: {err}", + usage_events=billed_usage(), + failed_call_keys=("ocr",), + retryable=not isinstance(err, ConversionError), + ) from err + finally: + batches.close() + assert merged is not None + if billed != source_pages: + raise ConverterLaneError( + f"PDF OCR incomplete: expected {source_pages} source pages, " + f"the batches covered {billed}", + usage_events=billed_usage(), + failed_call_keys=("ocr",), + retryable=False, + ) + # Every batch's own response metadata stays in the interchange asset. + merged = {**merged, "pages": pages, "batches": described} + if isinstance(merged.get("usage_info"), dict): + # Diagnostic totals across every batch's response. + merged["usage_info"] = { + key: sum( + info[key] + for info in totals + if isinstance(info, dict) and type(info.get(key)) is int + ) + if type(value) is int + else value + for key, value in merged["usage_info"].items() + } + usage = billed_usage()[0].usage + try: + result = _normalize(raw=merged, settings=settings, source_is_image=False) + except Exception as err: + raise ProviderCallError( + f"mistral ocr normalization failed after billed calls: {err}", + usage=usage, + ) from err + return result.model_copy( + update={"usage_events": (ConverterUsageEvent(call_key="ocr", usage=usage),)} + ) + def _process( self, *, content: bytes, mime: str, allow_empty_pages: bool = False ) -> dict[str, Any]: diff --git a/src/rememberstack/adapters/converters/pdf.py b/src/rememberstack/adapters/converters/pdf.py index c56f50517..4e617ebab 100644 --- a/src/rememberstack/adapters/converters/pdf.py +++ b/src/rememberstack/adapters/converters/pdf.py @@ -1,12 +1,20 @@ """PDF admission and metadata around the mandatory every-page OCR route.""" +from collections.abc import Callable +from collections.abc import Generator from dataclasses import dataclass from datetime import datetime from datetime import timedelta from datetime import timezone +from functools import partial import logging +import mmap +from pathlib import Path import re +import tempfile import threading +from typing import BinaryIO +from typing import cast from typing import Final import pypdfium2 @@ -69,6 +77,34 @@ def provider_limit_bytes(self) -> int | None: """The configured OCR input ceiling for pre-converter admission.""" return self._provider_limit_bytes + def convert_path(self, *, path: Path, mime: str) -> ConversionResult: + """:meth:`convert` for a PDF on local disk, never holding it whole (D147). + + For a host that downloads the input (for example by a pre-signed URL) + to a file: pdfium reads the file lazily, and an OCR route that offers + ``convert_path`` sends it in provider-sized page batches. + """ + if ( + self._provider_limit_bytes is not None + and pdf_source_size(source=path) > self._provider_limit_bytes + ): + raise ConversionError( + f"PDF exceeds the pre-OCR provider limit of " + f"{self._provider_limit_bytes} bytes" + ) + if not pdf_source_has_body(source=path): + raise ConversionError("the file is not a PDF (invalid PDF body)") + reading = _with_pdfium( + work=lambda: _read_pdf(content=str(path)), what="PDF page count" + ) + convert_path = getattr(self._ocr, "convert_path", None) + result: ConversionResult = ( + cast("ConversionResult", convert_path(path=path, mime=mime)) + if callable(convert_path) + else self._ocr.convert(content=path.read_bytes(), mime=mime) + ) + return self._checked(result=result, reading=reading) + def convert(self, *, content: bytes, mime: str) -> ConversionResult: """OCR every structurally valid page and keep the PDF Info metadata.""" if ( @@ -88,8 +124,15 @@ def convert(self, *, content: bytes, mime: str) -> ConversionResult: reading = time_limit.run_with_time_limit( work=lambda: _read_pdf_and_release(content=content), what="PDF page count" ) + return self._checked( + result=self._ocr.convert(content=content, mime=mime), reading=reading + ) + + def _checked( + self, *, result: ConversionResult, reading: _PdfReading + ) -> ConversionResult: + """Require one OCR result per source page and attach the Info metadata.""" metadata = _info_metadata(info=reading.info) - result = self._ocr.convert(content=content, mime=mime) found = { locator.page for entry in result.source_map or () @@ -117,7 +160,7 @@ def _read_pdf_and_release(*, content: bytes) -> _PdfReading: _PDFIUM_LOCK.release() -def _read_pdf(*, content: bytes) -> _PdfReading: +def _read_pdf(*, content: bytes | str) -> _PdfReading: """Count pages from the page tree and read only the Info dictionary.""" try: document = pypdfium2.PdfDocument(content) @@ -183,3 +226,229 @@ def _pdf_date(*, text: str) -> datetime | None: _logger.warning("PDF date is out of range: %r", text) return None return value.astimezone(timezone.utc) + + +PdfSource = bytes | Path +"""A PDF's content in memory, or the path of a PDF on local disk (D147). + +pdfium reads a path lazily, so a large PDF on disk is never held whole.""" + + +def pdf_source_size(*, source: PdfSource) -> int: + """The source's size in bytes.""" + return len(source) if isinstance(source, bytes) else source.stat().st_size + + +def pdf_source_has_body(*, source: PdfSource) -> bool: + """``has_pdf_body`` on bytes, or on a memory map of the file.""" + if isinstance(source, bytes): + return has_pdf_body(content=source) + if pdf_source_size(source=source) == 0: + return False + with ( + source.open("rb") as handle, + mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as mapped, + ): + return has_pdf_body(content=mapped) # type: ignore[arg-type] + + +def pdf_source_page_count(*, source: PdfSource) -> int: + """``pdf_page_count`` for bytes or a file path.""" + if not pdf_source_has_body(source=source): + raise ConversionError("the file is not a PDF (invalid PDF body)") + return _with_pdfium( + work=lambda: _read_pdf(content=_pdfium_input(source=source)), + what="PDF page count", + ).page_count + + +def pdf_page_batches( + *, source: PdfSource, max_bytes: int, max_pages: int | None +) -> Generator[tuple[int, int, bytes]]: + """Split a PDF into page-range PDFs that each fit a provider's limits. + + Yields ``(first page index, page count, batch PDF bytes)`` in page order, + covering every page exactly once. Each page is first measured alone (a + one-page PDF saved to a counter from a freshly opened source, nothing + kept), and a batch takes pages + while their one-page sizes add up to at most ``max_bytes``; shared + resources are counted once per page there, so the batch itself is + normally smaller and no candidate's native memory runs past the limit + whatever the page sizes. The batch is built in one locked pdfium + operation that opens the source, copies the pages, saves them to a + temporary file on disk and closes everything, and is read into memory + only if it fits; otherwise it is shrunk. A single page larger than + ``max_bytes`` fails the conversion, because no split can send it. + """ + page_count = pdf_source_page_count(source=source) + sizes: list[int] = [] # one-page sizes, measured lazily from ``start`` + start = 0 + while start < page_count: + cap = page_count - start + if max_pages is not None: + cap = min(cap, max_pages) + count, total = 0, 0 + while count < cap: + if count == len(sizes): + sizes.extend( + _with_pdfium( + work=partial( + _measure_pages, + source=source, + first=start + count, + count=min(_MEASURED_PAGES, page_count - start - count), + ), + what="PDF page measurement", + ) + ) + if total + sizes[count] > max_bytes: + break + total += sizes[count] + count += 1 + if count == 0: + raise _single_page_too_large(page=start, size=sizes[0], limit=max_bytes) + while True: + saved, batch = _trial( + source=source, first=start, count=count, limit=max_bytes + ) + if batch is not None: + break + if count == 1: + raise _single_page_too_large(page=start, size=saved, limit=max_bytes) + count = max(1, min(count - 1, int(count * max_bytes * 0.9 / saved))) + yield start, count, batch + del sizes[:count] + start += count + + +_MEASURED_PAGES = 64 +"""Pages measured per locked pdfium operation while sizing batches.""" + + +def _single_page_too_large(*, page: int, size: int, limit: int) -> ConversionError: + return ConversionError( + f"PDF page {page + 1} alone is {size} bytes, over the OCR provider " + f"limit of {limit} bytes" + ) + + +def _trial( + *, source: PdfSource, first: int, count: int, limit: int +) -> tuple[int, bytes | None]: + """Save a candidate batch to disk; return its size, and its bytes if it fits.""" + with tempfile.TemporaryFile() as spool: + saved = _with_pdfium( + work=partial( + _save_pages, source=source, first=first, count=count, out=spool + ), + what="PDF page batch", + ) + if saved > limit: + return saved, None + spool.seek(0) + return saved, spool.read() + + +def _pdfium_input(*, source: PdfSource) -> bytes | str: + return source if isinstance(source, bytes) else str(source) + + +class _Sink: + """pdfium's save target: counts bytes and keeps the first write error. + + pdfium's write callback cannot raise (ctypes reports and drops the + exception), so a failed write is recorded here and raised after saving. + """ + + def __init__(self, out: BinaryIO | None) -> None: + self.out = out + self.size = 0 + self.error: OSError | None = None + + def write(self, data: bytes) -> int: + if self.error is None and self.out is not None: + try: + self.out.write(data) + except OSError as err: + self.error = err + self.size += len(data) + return len(data) + + +def _save_copy( + *, document: pypdfium2.PdfDocument, pages: list[int], sink: _Sink +) -> None: + """Save ``pages`` of ``document`` as a new PDF into ``sink``.""" + batch = pypdfium2.PdfDocument.new() + try: + batch.import_pages(document, pages=pages) + batch.save(sink) + except pypdfium2.PdfiumError as err: + raise ConversionError(f"the PDF pages could not be split: {err}") from err + finally: + batch.close() + if sink.error is not None: + raise sink.error + + +def _open_source(*, source: PdfSource) -> pypdfium2.PdfDocument: + try: + return pypdfium2.PdfDocument(_pdfium_input(source=source)) + except pypdfium2.PdfiumError as err: + raise ConversionError(f"the PDF could not be opened: {err}") from err + + +def _measure_pages(*, source: PdfSource, first: int, count: int) -> list[int]: + """Each page's size saved alone as a PDF, for ``count`` pages from ``first``. + + The source is opened and closed for each page, so pdfium never holds + more than one page's data, and every native document is closed inside + the one locked operation. + """ + sizes = [] + for page in range(first, first + count): + document = _open_source(source=source) + try: + sink = _Sink(out=None) + _save_copy(document=document, pages=[page], sink=sink) + sizes.append(sink.size) + finally: + document.close() + return sizes + + +def _save_pages(*, source: PdfSource, first: int, count: int, out: BinaryIO) -> int: + """Copy pages ``first`` .. ``first + count - 1`` into a new PDF on ``out``. + + Opens and closes every native document inside the one locked operation, + so nothing pdfium owns outlives the lock. Returns the saved size. + """ + document = _open_source(source=source) + try: + sink = _Sink(out=out) + _save_copy( + document=document, pages=list(range(first, first + count)), sink=sink + ) + return sink.size + finally: + document.close() + + +def _with_pdfium[T](*, work: Callable[[], T], what: str) -> T: + """Run one pdfium operation under the process lock and the time limit. + + The lock is released by the thread doing the work, so an operation + abandoned at the time limit keeps pdfium locked until it really ends. + """ + if not _PDFIUM_LOCK.acquire(timeout=time_limit.CONVERTER_TIME_LIMIT_S): + raise ConversionError( + "pdfium is still held by an earlier PDF that overran its time limit" + ) + + def locked() -> T: + try: + return work() + finally: + _PDFIUM_LOCK.release() + + return time_limit.run_with_time_limit(work=locked, what=what) diff --git a/src/tests/adapters/test_mistral_ocr.py b/src/tests/adapters/test_mistral_ocr.py index d4d58274c..9bc376ce7 100644 --- a/src/tests/adapters/test_mistral_ocr.py +++ b/src/tests/adapters/test_mistral_ocr.py @@ -8,6 +8,11 @@ import base64 from decimal import Decimal import json +from pathlib import Path +import random +import string +from typing import Any +from typing import cast import httpx import pytest @@ -549,3 +554,316 @@ def handle(request: httpx.Request) -> httpx.Response: return httpx.Response(200, json=_RAW_RESPONSE) return httpx.MockTransport(handle) + + +def _page_echo_transport(calls: list[int]) -> httpx.MockTransport: + """OCR each request's PDF by reading its pages' text layer (test only).""" + import pypdfium2 + + def handle(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + encoded = body["document"]["document_url"].split(",", 1)[1] + document = pypdfium2.PdfDocument(base64.b64decode(encoded)) + try: + texts = [ + document[index].get_textpage().get_text_range().strip() + for index in range(len(document)) + ] + finally: + document.close() + calls.append(len(texts)) + return httpx.Response( + 200, + json={ + "model": "mistral-ocr-latest", + "pages": [ + {"index": index, "markdown": f"# {text}\n", "dimensions": {}} + for index, text in enumerate(texts) + ], + "usage_info": {"pages_processed": len(texts)}, + }, + ) + + return httpx.MockTransport(handle) + + +_TEN_PAGES: list[str | None] = [f"Section {number}" for number in range(1, 11)] + + +def test_a_pdf_over_the_page_ceiling_is_ocred_in_batches_in_page_order() -> None: + """D147: batches renumber their pages and stitch into one reading.""" + calls: list[int] = [] + content = _pdf(pages=_TEN_PAGES) + batched = _converter(_page_echo_transport(calls), max_document_pages=4).convert( + content=content, mime="application/pdf" + ) + assert calls == [4, 4, 2] + whole_calls: list[int] = [] + whole = _converter(_page_echo_transport(whole_calls)).convert( + content=content, mime="application/pdf" + ) + assert whole_calls == [10] + # Page-wise identical provider output gives the identical reading. + assert batched.document_md == whole.document_md + assert batched.source_map == whole.source_map + assert batched.manifest.derivation_ranges == whole.manifest.derivation_ranges + assert batched.usage_events[0].usage.cost_usd == Decimal("0.010") + + +def test_a_pdf_over_the_byte_ceiling_is_split_and_every_page_is_ocred() -> None: + calls: list[int] = [] + content = _pdf(pages=_TEN_PAGES) + result = _converter( + _page_echo_transport(calls), max_document_bytes=len(content) // 2 + ).convert(content=content, mime="application/pdf") + assert sum(calls) == 10 and len(calls) > 1 + assert [ + line for line in result.document_md.splitlines() if line.startswith("#") + ] == [f"# {text}" for text in _TEN_PAGES] + + +def test_a_single_page_over_the_byte_ceiling_cannot_be_sent() -> None: + content = _pdf(pages=["Only page"]) + with pytest.raises(ConversionError, match="alone"): + _converter(_page_echo_transport([]), max_document_bytes=50).convert( + content=content, mime="application/pdf" + ) + + +def test_a_failed_batch_after_billed_batches_carries_their_usage() -> None: + echo = _page_echo_transport([]) + seen: list[int] = [] + + def handle(request: httpx.Request) -> httpx.Response: + seen.append(1) + if len(seen) == 2: + return httpx.Response(503, text="busy") + return echo.handle_request(request) + + with pytest.raises(ConverterLaneError) as failure: + _converter(httpx.MockTransport(handle), max_document_pages=4).convert( + content=_pdf(pages=_TEN_PAGES), mime="application/pdf" + ) + assert failure.value.retryable + assert failure.value.usage_events[0].usage.cost_usd == Decimal("0.004") + + +def test_a_pdf_on_disk_converts_in_batches_without_reading_it_whole( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """D147: ``convert_path`` reads batches lazily; the file is never read whole.""" + from rememberstack.adapters.converters.pdf import PdfConverter + + calls: list[int] = [] + path = tmp_path / "large.pdf" + path.write_bytes(_pdf(pages=_TEN_PAGES)) + monkeypatch.setattr( + Path, "read_bytes", lambda self: pytest.fail("the PDF was read whole") + ) + result = PdfConverter( + ocr=_converter(_page_echo_transport(calls), max_document_pages=3) + ).convert_path(path=path, mime="application/pdf") + assert calls == [3, 3, 3, 1] + assert result.source_map is not None + pages = { + entry.locators[0].page # pyright: ignore[reportAttributeAccessIssue] + for entry in result.source_map + if entry.locators[0].kind == "page" + } + assert pages == set(range(1, 11)) + + +def test_below_both_ceilings_the_request_is_the_single_whole_document() -> None: + """Unchanged behaviour: one request carrying exactly the original bytes.""" + bodies: list[str] = [] + echo = _page_echo_transport([]) + + def handle(request: httpx.Request) -> httpx.Response: + bodies.append(json.loads(request.content)["document"]["document_url"]) + return echo.handle_request(request) + + content = _pdf(pages=_TEN_PAGES) + _converter(httpx.MockTransport(handle)).convert( + content=content, mime="application/pdf" + ) + assert bodies == [ + "data:application/pdf;base64," + base64.b64encode(content).decode("ascii") + ] + + +def test_a_splitter_failure_after_billed_batches_carries_their_usage( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Usage already billed survives a later split failure (D147).""" + from rememberstack.adapters.converters import mistral_ocr + + real = mistral_ocr.pdf_page_batches + + def one_then_fail(**kwargs: object): # noqa: ANN202 + batches = real(**kwargs) # type: ignore[arg-type] + yield next(batches) + raise ConversionError("PDF page 5 alone is too large") + + monkeypatch.setattr(mistral_ocr, "pdf_page_batches", one_then_fail) + with pytest.raises(ConverterLaneError) as failure: + _converter(_page_echo_transport([]), max_document_pages=4).convert( + content=_pdf(pages=_TEN_PAGES), mime="application/pdf" + ) + assert not failure.value.retryable + assert failure.value.usage_events[0].usage.cost_usd == Decimal("0.004") + + +def test_batch_pages_are_stitched_by_index_not_response_order() -> None: + """A batch answering its pages out of order still reads in page order.""" + echo = _page_echo_transport([]) + + def reversed_pages(request: httpx.Request) -> httpx.Response: + response = echo.handle_request(request) + body = json.loads(response.content) + body["pages"].reverse() + return httpx.Response(200, json=body) + + result = _converter( + httpx.MockTransport(reversed_pages), max_document_pages=2 + ).convert(content=_pdf(pages=_TEN_PAGES), mime="application/pdf") + headings = [ + line for line in result.document_md.splitlines() if line.startswith("#") + ] + assert headings == [f"# {text}" for text in _TEN_PAGES] + + +def test_batching_leaves_pdfium_unlocked() -> None: + from rememberstack.adapters.converters import pdf as pdf_module + + _converter(_page_echo_transport([]), max_document_pages=3).convert( + content=_pdf(pages=_TEN_PAGES), mime="application/pdf" + ) + assert not pdf_module._PDFIUM_LOCK.locked() # noqa: SLF001 + + +def test_no_candidate_batch_runs_past_the_byte_ceiling_on_uneven_pages( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Small pages then heavy ones: candidates stay under the limit (D147).""" + from rememberstack.adapters.converters import pdf as pdf_module + + trials: list[int] = [] + real = pdf_module._save_pages # noqa: SLF001 + + def record(**kwargs: object) -> int: + saved = real(**kwargs) # type: ignore[arg-type] + trials.append(saved) + return saved + + monkeypatch.setattr(pdf_module, "_save_pages", record) + letters = random.Random(7) + texts: list[str | None] = [f"Small {n}" for n in range(8)] + texts += [ # incompressible, so each heavy page saves to about 30 kB + f"Heavy {n} " + "".join(letters.choices(string.ascii_letters, k=40_000)) + for n in range(8) + ] + limit = 100_000 # about three heavy pages + calls: list[int] = [] + result = _converter(_page_echo_transport(calls), max_document_bytes=limit).convert( + content=_pdf(pages=texts), mime="application/pdf" + ) + assert sum(calls) == 16 and len(calls) > 1 + assert max(trials) <= limit + headings = [ + " ".join(line.split()[:3]) + for line in result.document_md.splitlines() + if line.startswith("#") + ] + assert headings == [" ".join(f"# {text}".split()[:3]) for text in texts if text] + + +def test_each_page_is_measured_from_a_freshly_opened_source( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Measuring never holds more than one page's data in pdfium (D147).""" + from rememberstack.adapters.converters import pdf as pdf_module + + open_documents: list[object] = [] + most_open = 0 + real_open = pdf_module._open_source # noqa: SLF001 + + def tracked(**kwargs: Any) -> Any: # noqa: ANN401 + nonlocal most_open + document = real_open(**kwargs) + open_documents.append(document) + most_open = max(most_open, len(open_documents)) + real_close = document.close + + def close() -> None: + open_documents.remove(document) + real_close() + + setattr(document, "close", close) # noqa: B010 + return document + + monkeypatch.setattr(pdf_module, "_open_source", tracked) + sizes = pdf_module._measure_pages( # noqa: SLF001 + source=_pdf(pages=_TEN_PAGES), first=0, count=10 + ) + assert len(sizes) == 10 and all(size > 0 for size in sizes) + assert most_open == 1 + assert open_documents == [] + + +def test_a_failed_spool_write_raises_instead_of_saving_an_empty_batch() -> None: + """pdfium drops write-callback exceptions; the split re-raises them.""" + from rememberstack.adapters.converters import pdf as pdf_module + + class _FullDisk: + def write(self, data: bytes) -> int: + raise OSError(28, "No space left on device") + + with pytest.raises(OSError, match="No space"): + pdf_module._save_pages( # noqa: SLF001 + source=_pdf(pages=_TEN_PAGES), + first=0, + count=2, + out=cast("Any", _FullDisk()), + ) + + +def test_a_spool_failure_after_billed_batches_carries_their_usage( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A disk error while splitting keeps billed usage and is retryable.""" + from rememberstack.adapters.converters import mistral_ocr + + real = mistral_ocr.pdf_page_batches + + def one_then_fail(**kwargs: object): # noqa: ANN202 + batches = real(**kwargs) # type: ignore[arg-type] + yield next(batches) + raise OSError(28, "No space left on device") + + monkeypatch.setattr(mistral_ocr, "pdf_page_batches", one_then_fail) + with pytest.raises(ConverterLaneError) as failure: + _converter(_page_echo_transport([]), max_document_pages=4).convert( + content=_pdf(pages=_TEN_PAGES), mime="application/pdf" + ) + assert failure.value.retryable + assert failure.value.usage_events[0].usage.cost_usd == Decimal("0.004") + + +def test_every_batch_response_is_kept_in_the_interchange_asset() -> None: + result = _converter(_page_echo_transport([]), max_document_pages=4).convert( + content=_pdf(pages=_TEN_PAGES), mime="application/pdf" + ) + (asset,) = [ + asset for asset in result.derived_assets if asset.kind == "provider_response" + ] + decoded = json.loads(asset.content) + assert [page["index"] for page in decoded["pages"]] == list(range(10)) + assert [ + (batch["first_page"], batch["page_count"], batch["usage_info"]) + for batch in decoded["batches"] + ] == [ + (1, 4, {"pages_processed": 4}), + (5, 4, {"pages_processed": 4}), + (9, 2, {"pages_processed": 2}), + ] + assert decoded["usage_info"] == {"pages_processed": 10} diff --git a/website/public/llms-full.txt b/website/public/llms-full.txt index 01179dd26..954776a75 100644 --- a/website/public/llms-full.txt +++ b/website/public/llms-full.txt @@ -3351,7 +3351,7 @@ On a self-hosted deployment: | Web addresses (URLs) | No | No: download the page and send the HTML | A Word or PowerPoint file over 100 MB, or a spreadsheet over 200 MB, -gets a file card instead of a reading. A PDF over the lower of its 100 MB family limit and the OCR provider limit fails conversion without a card; a spreadsheet over 50 MB is profiled +gets a file card instead of a reading. A PDF over its 100 MB family limit fails conversion without a card (a PDF larger than the OCR provider accepts in one request, about 50 MB or 1,000 pages, is OCR'd in page batches); a spreadsheet over 50 MB is profiled from its sheet list and dimensions only. A text file over 1 MB is described by its size, line count, first 50 and last 20 lines instead of read in full. @@ -19941,6 +19941,18 @@ published as `rememberstack`. The engine is pre-1.0. A minor version can change the API; changes that need action from you are marked **Action needed**. +## Unreleased + +**Processing.** + +- A PDF over the OCR provider's per-request limits (about 50 MB or 1,000 + pages) is no longer refused. It is split into page-range batches that each + fit, every batch is OCR'd, and the pages are stitched back in order, so + every page is still OCR'd and metered once. Below both limits the request + and the result are unchanged. Only a single page over the byte limit is + refused. `PdfConverter.convert_path` and `MistralOcrConverter.convert_path` + convert a PDF from a file on disk without reading it whole. + ## 0.18.2 (November 2026) A stock self-hosted deployment needs no action. Its database migrations, its diff --git a/website/src/app/docs/guides/file-types/page.mdx b/website/src/app/docs/guides/file-types/page.mdx index 62326f375..94fc2e91d 100644 --- a/website/src/app/docs/guides/file-types/page.mdx +++ b/website/src/app/docs/guides/file-types/page.mdx @@ -37,7 +37,7 @@ On a self-hosted deployment: | Web addresses (URLs) | No | No: download the page and send the HTML | A Word or PowerPoint file over 100 MB, or a spreadsheet over 200 MB, -gets a file card instead of a reading. A PDF over the lower of its 100 MB family limit and the OCR provider limit fails conversion without a card; a spreadsheet over 50 MB is profiled +gets a file card instead of a reading. A PDF over its 100 MB family limit fails conversion without a card (a PDF larger than the OCR provider accepts in one request, about 50 MB or 1,000 pages, is OCR'd in page batches); a spreadsheet over 50 MB is profiled from its sheet list and dimensions only. A text file over 1 MB is described by its size, line count, first 50 and last 20 lines instead of read in full. diff --git a/website/src/app/docs/project/changelog/page.mdx b/website/src/app/docs/project/changelog/page.mdx index e838b1941..a6783ba9d 100644 --- a/website/src/app/docs/project/changelog/page.mdx +++ b/website/src/app/docs/project/changelog/page.mdx @@ -24,6 +24,18 @@ runs today, and what that means for you, is on +## Unreleased + +**Processing.** + +- A PDF over the OCR provider's per-request limits (about 50 MB or 1,000 + pages) is no longer refused. It is split into page-range batches that each + fit, every batch is OCR'd, and the pages are stitched back in order, so + every page is still OCR'd and metered once. Below both limits the request + and the result are unchanged. Only a single page over the byte limit is + refused. `PdfConverter.convert_path` and `MistralOcrConverter.convert_path` + convert a PDF from a file on disk without reading it whole. + ## 0.18.2 (November 2026) A stock self-hosted deployment needs no action. Its database migrations, its