From 9ec8a7fdddb2438ce560d9a009a1e0738f47269e Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 15:33:22 +0100 Subject: [PATCH 1/6] feat(D147): OCR large PDFs in page batches instead of failing at the provider limit Owner rule: no caps. A PDF over the OCR provider's per-request ceilings (about 50 MB, 1,000 pages) is split with pdfium into page-range PDFs that each fit; each batch is OCR'd, its pages renumbered from the batch's first page, and the folded response metered (every source page) and normalized exactly like one call. Below both ceilings the request and result are byte-for-byte unchanged, so no version changes. convert_path reads a PDF on disk one batch at a time, for a host that must not hold it in memory. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- decisions.md | 12 ++ plan/designs/format_conversion_design.md | 2 +- .../adapters/converters/__init__.py | 4 +- .../adapters/converters/mistral_ocr.py | 152 +++++++++++++++- src/rememberstack/adapters/converters/pdf.py | 169 +++++++++++++++++- src/tests/adapters/test_mistral_ocr.py | 136 ++++++++++++++ website/public/llms-full.txt | 2 +- .../src/app/docs/guides/file-types/page.mdx | 2 +- 8 files changed, 467 insertions(+), 12 deletions(-) diff --git a/decisions.md b/decisions.md index 93c9f5d47..c9c21122b 100644 --- a/decisions.md +++ b/decisions.md @@ -7423,6 +7423,18 @@ 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, sized from the average page and shrunk until saved under the byte + ceiling; 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. Below both ceilings + the request and the result are unchanged, so no version changes. Only a single page + over the byte ceiling fails. `PdfConverter.convert_path(path, mime)` and + `MistralOcrConverter.convert_path` do the same from a file on disk, reading one + batch at a time, 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/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..2330aff84 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,109 @@ 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 + processed = 0 + + 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),) + + for first, count, batch in pdf_page_batches( + source=source, + max_bytes=settings.max_document_bytes, + max_pages=settings.max_document_pages, + ): + try: + raw = self._process( + content=batch, mime="application/pdf", allow_empty_pages=True + ) + except (ConversionError, MistralOcrProviderError) as err: + if not billed: + raise + raise ConverterLaneError( + f"PDF OCR batch at page {first + 1} failed: {err}", + usage_events=billed_usage(), + failed_call_keys=("ocr",), + retryable=isinstance(err, MistralOcrProviderError), + ) from err + 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 at " + f"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 batch_pages + ) + info = raw.get("usage_info") + if isinstance(info, dict) and isinstance(info.get("pages_processed"), int): + processed += info["pages_processed"] + 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, + ) + merged = {**merged, "pages": pages} + if isinstance(merged.get("usage_info"), dict): + merged["usage_info"] = { + **merged["usage_info"], + "pages_processed": processed, + } + 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..3d6d0956d 100644 --- a/src/rememberstack/adapters/converters/pdf.py +++ b/src/rememberstack/adapters/converters/pdf.py @@ -1,12 +1,19 @@ """PDF admission and metadata around the mandatory every-page OCR route.""" +from collections.abc import Callable +from collections.abc import Iterator from dataclasses import dataclass from datetime import datetime from datetime import timedelta from datetime import timezone +from functools import partial +import io import logging +import mmap +from pathlib import Path import re import threading +from typing import cast from typing import Final import pypdfium2 @@ -69,6 +76,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 +123,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 +159,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 +225,126 @@ 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 +) -> Iterator[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; only one batch is held at a time. A + batch is sized from the source's average page size, then shrunk until + its saved bytes fit ``max_bytes``; a single page larger than that fails + the conversion, because no split can send it. + """ + document = _with_pdfium( + work=lambda: _open(source=source), what="PDF open for page batches" + ) + try: + page_count = _with_pdfium(work=lambda: len(document), what="PDF page count") + total = pdf_source_size(source=source) + start = 0 + while start < page_count: + remaining = page_count - start + size = max(1, min(remaining, int(page_count * max_bytes * 0.9 / total))) + if max_pages is not None: + size = min(size, max_pages) + while True: + batch = _with_pdfium( + work=partial( + _batch_bytes, document=document, first=start, count=size + ), + what="PDF page batch", + ) + if len(batch) <= max_bytes: + break + if size == 1: + raise ConversionError( + f"PDF page {start + 1} alone is {len(batch)} bytes, over " + f"the OCR provider limit of {max_bytes} bytes" + ) + size = max(1, min(size - 1, int(size * max_bytes * 0.9 / len(batch)))) + yield start, size, batch + start += size + finally: + _with_pdfium(work=document.close, what="PDF close") + + +def _pdfium_input(*, source: PdfSource) -> bytes | str: + return source if isinstance(source, bytes) else str(source) + + +def _open(*, 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 _batch_bytes(*, document: pypdfium2.PdfDocument, first: int, count: int) -> bytes: + """Save pages ``first`` .. ``first + count - 1`` as one new PDF.""" + batch = pypdfium2.PdfDocument.new() + try: + batch.import_pages(document, pages=list(range(first, first + count))) + buffer = io.BytesIO() + batch.save(buffer) + return buffer.getvalue() + except pypdfium2.PdfiumError as err: + raise ConversionError(f"the PDF pages could not be split: {err}") from err + finally: + batch.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..c9fe9e277 100644 --- a/src/tests/adapters/test_mistral_ocr.py +++ b/src/tests/adapters/test_mistral_ocr.py @@ -8,6 +8,7 @@ import base64 from decimal import Decimal import json +from pathlib import Path import httpx import pytest @@ -549,3 +550,138 @@ 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") + ] diff --git a/website/public/llms-full.txt b/website/public/llms-full.txt index 01179dd26..15cf314b3 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. 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. From b91f19efdb4cbadce960b431c73f186ff93a1a1e Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 15:51:38 +0100 Subject: [PATCH 2/6] fix(D147): one locked pdfium operation per batch, disk-backed trials, usage kept Codex round 1: - Each candidate batch opens the source, copies the pages, saves to a temporary file and closes everything inside one locked pdfium operation: memory no longer grows with the source or an oversized candidate, and no native document outlives the lock. Only a fitting batch is read. - Split failures after billed batches carry their usage; batches are stitched by page index; usage_info totals cover every batch. - workspace formats design reconciled with batching and URL routes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- decisions.md | 11 ++- plan/designs/workspace_formats_design.md | 25 ++--- .../adapters/converters/mistral_ocr.py | 93 +++++++++-------- src/rememberstack/adapters/converters/pdf.py | 99 ++++++++++--------- src/tests/adapters/test_mistral_ocr.py | 50 ++++++++++ 5 files changed, 175 insertions(+), 103 deletions(-) diff --git a/decisions.md b/decisions.md index c9c21122b..cafc06ede 100644 --- a/decisions.md +++ b/decisions.md @@ -7431,10 +7431,13 @@ deployment's values into another's work. 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. Below both ceilings the request and the result are unchanged, so no version changes. Only a single page - over the byte ceiling fails. `PdfConverter.convert_path(path, mime)` and - `MistralOcrConverter.convert_path` do the same from a file on disk, reading one - batch at a time, 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. + 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 memory never + grows with the source or an oversized candidate; only a batch that fits is read. + A failure after billed batches 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/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/mistral_ocr.py b/src/rememberstack/adapters/converters/mistral_ocr.py index 2330aff84..81b18d0b3 100644 --- a/src/rememberstack/adapters/converters/mistral_ocr.py +++ b/src/rememberstack/adapters/converters/mistral_ocr.py @@ -255,7 +255,7 @@ def _batched_pdf(self, *, source: PdfSource, source_pages: int) -> ConversionRes merged: dict[str, Any] | None = None pages: list[dict[str, Any]] = [] billed = 0 - processed = 0 + totals: list[object] = [] def billed_usage() -> tuple[ConverterUsageEvent, ...]: usage = _usage( @@ -266,51 +266,55 @@ def billed_usage() -> tuple[ConverterUsageEvent, ...]: ) return (ConverterUsageEvent(call_key="ocr", usage=usage),) - for first, count, batch in pdf_page_batches( + batches = pdf_page_batches( source=source, max_bytes=settings.max_document_bytes, max_pages=settings.max_document_pages, - ): - try: + ) + try: + for first, count, batch in batches: raw = self._process( content=batch, mime="application/pdf", allow_empty_pages=True ) - except (ConversionError, MistralOcrProviderError) as err: - if not billed: - raise - raise ConverterLaneError( - f"PDF OCR batch at page {first + 1} failed: {err}", - usage_events=billed_usage(), - failed_call_keys=("ocr",), - retryable=isinstance(err, MistralOcrProviderError), - ) from err - 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 at " - f"page {first + 1}, received page indexes {indexes}", - usage_events=billed_usage(), - failed_call_keys=("ocr",), - retryable=False, + 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 [] ) - assert isinstance(batch_pages, list) - pages.extend( - {**page, "index": page["index"] + first} for page in batch_pages - ) - info = raw.get("usage_info") - if isinstance(info, dict) and isinstance(info.get("pages_processed"), int): - processed += info["pages_processed"] + 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")) + except (ConversionError, MistralOcrProviderError) as err: + # Splitting 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=isinstance(err, MistralOcrProviderError), + ) from err + finally: + batches.close() assert merged is not None if billed != source_pages: raise ConverterLaneError( @@ -322,9 +326,16 @@ def billed_usage() -> tuple[ConverterUsageEvent, ...]: ) merged = {**merged, "pages": pages} if isinstance(merged.get("usage_info"), dict): + # Diagnostic totals across every batch's response. merged["usage_info"] = { - **merged["usage_info"], - "pages_processed": processed, + 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: diff --git a/src/rememberstack/adapters/converters/pdf.py b/src/rememberstack/adapters/converters/pdf.py index 3d6d0956d..f67d758cc 100644 --- a/src/rememberstack/adapters/converters/pdf.py +++ b/src/rememberstack/adapters/converters/pdf.py @@ -1,18 +1,19 @@ """PDF admission and metadata around the mandatory every-page OCR route.""" from collections.abc import Callable -from collections.abc import Iterator +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 io 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 @@ -263,71 +264,75 @@ def pdf_source_page_count(*, source: PdfSource) -> int: def pdf_page_batches( *, source: PdfSource, max_bytes: int, max_pages: int | None -) -> Iterator[tuple[int, int, bytes]]: +) -> 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; only one batch is held at a time. A - batch is sized from the source's average page size, then shrunk until - its saved bytes fit ``max_bytes``; a single page larger than that fails - the conversion, because no split can send it. + covering every page exactly once. Each candidate 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, so memory never + grows with the source or with an oversized candidate; only a batch that + fits ``max_bytes`` is read into memory. A batch is sized from the + source's average page size and shrunk until it fits; a single page + larger than ``max_bytes`` fails the conversion, because no split can + send it. """ - document = _with_pdfium( - work=lambda: _open(source=source), what="PDF open for page batches" - ) - try: - page_count = _with_pdfium(work=lambda: len(document), what="PDF page count") - total = pdf_source_size(source=source) - start = 0 - while start < page_count: - remaining = page_count - start - size = max(1, min(remaining, int(page_count * max_bytes * 0.9 / total))) - if max_pages is not None: - size = min(size, max_pages) - while True: - batch = _with_pdfium( + page_count = pdf_source_page_count(source=source) + total = pdf_source_size(source=source) + start = 0 + while start < page_count: + remaining = page_count - start + size = max(1, min(remaining, int(page_count * max_bytes * 0.9 / total))) + if max_pages is not None: + size = min(size, max_pages) + while True: + with tempfile.TemporaryFile() as spool: + saved = _with_pdfium( work=partial( - _batch_bytes, document=document, first=start, count=size + _save_pages, source=source, first=start, count=size, out=spool ), what="PDF page batch", ) - if len(batch) <= max_bytes: + if saved <= max_bytes: + spool.seek(0) + batch = spool.read() break - if size == 1: - raise ConversionError( - f"PDF page {start + 1} alone is {len(batch)} bytes, over " - f"the OCR provider limit of {max_bytes} bytes" - ) - size = max(1, min(size - 1, int(size * max_bytes * 0.9 / len(batch)))) - yield start, size, batch - start += size - finally: - _with_pdfium(work=document.close, what="PDF close") + if size == 1: + raise ConversionError( + f"PDF page {start + 1} alone is {saved} bytes, over " + f"the OCR provider limit of {max_bytes} bytes" + ) + size = max(1, min(size - 1, int(size * max_bytes * 0.9 / saved))) + yield start, size, batch + start += size def _pdfium_input(*, source: PdfSource) -> bytes | str: return source if isinstance(source, bytes) else str(source) -def _open(*, source: PdfSource) -> pypdfium2.PdfDocument: +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. + """ try: - return pypdfium2.PdfDocument(_pdfium_input(source=source)) + document = pypdfium2.PdfDocument(_pdfium_input(source=source)) except pypdfium2.PdfiumError as err: raise ConversionError(f"the PDF could not be opened: {err}") from err - - -def _batch_bytes(*, document: pypdfium2.PdfDocument, first: int, count: int) -> bytes: - """Save pages ``first`` .. ``first + count - 1`` as one new PDF.""" - batch = pypdfium2.PdfDocument.new() try: - batch.import_pages(document, pages=list(range(first, first + count))) - buffer = io.BytesIO() - batch.save(buffer) - return buffer.getvalue() - except pypdfium2.PdfiumError as err: - raise ConversionError(f"the PDF pages could not be split: {err}") from err + batch = pypdfium2.PdfDocument.new() + try: + batch.import_pages(document, pages=list(range(first, first + count))) + batch.save(out) + except pypdfium2.PdfiumError as err: + raise ConversionError(f"the PDF pages could not be split: {err}") from err + finally: + batch.close() finally: - batch.close() + document.close() + return out.tell() def _with_pdfium[T](*, work: Callable[[], T], what: str) -> T: diff --git a/src/tests/adapters/test_mistral_ocr.py b/src/tests/adapters/test_mistral_ocr.py index c9fe9e277..77beb9c79 100644 --- a/src/tests/adapters/test_mistral_ocr.py +++ b/src/tests/adapters/test_mistral_ocr.py @@ -685,3 +685,53 @@ def handle(request: httpx.Request) -> httpx.Response: 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 From e0017840d751f5566c24ae549ac318f5e920bb5e Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 16:11:03 +0100 Subject: [PATCH 3/6] Address Codex round-2 review of PDF OCR batching - Grow candidate batches from the previous batch size (one page at first), at most doubling, then binary search, so no trial runs far past what fits. - A disk error while splitting after billed batches keeps their usage (retryable ConverterLaneError). - Keep every batch's response metadata under `batches` in the interchange asset. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- decisions.md | 21 ++--- .../adapters/converters/mistral_ocr.py | 19 +++-- src/rememberstack/adapters/converters/pdf.py | 76 +++++++++++++------ src/tests/adapters/test_mistral_ocr.py | 73 ++++++++++++++++++ 4 files changed, 150 insertions(+), 39 deletions(-) diff --git a/decisions.md b/decisions.md index cafc06ede..8c140c8d0 100644 --- a/decisions.md +++ b/decisions.md @@ -7426,15 +7426,18 @@ deployment's values into another's work. - *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, sized from the average page and shrunk until saved under the byte - ceiling; 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. 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 memory never - grows with the source or an oversized candidate; only a batch that fits is read. - A failure after billed batches carries their usage. `PdfConverter.convert_path(path, + that each fit. A batch starts from the previous batch's page count (one page at + first), grows towards the byte ceiling at most doubling, then binary-searches, so no + candidate runs far past what fits; 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) 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. diff --git a/src/rememberstack/adapters/converters/mistral_ocr.py b/src/rememberstack/adapters/converters/mistral_ocr.py index 81b18d0b3..f8cf1889b 100644 --- a/src/rememberstack/adapters/converters/mistral_ocr.py +++ b/src/rememberstack/adapters/converters/mistral_ocr.py @@ -256,6 +256,7 @@ def _batched_pdf(self, *, source: PdfSource, source_pages: int) -> ConversionRes pages: list[dict[str, Any]] = [] billed = 0 totals: list[object] = [] + described: list[dict[str, Any]] = [] def billed_usage() -> tuple[ConverterUsageEvent, ...]: usage = _usage( @@ -302,16 +303,23 @@ def billed_usage() -> tuple[ConverterUsageEvent, ...]: for page in sorted(batch_pages, key=lambda page: page["index"]) ) totals.append(raw.get("usage_info")) - except (ConversionError, MistralOcrProviderError) as err: - # Splitting or a later call failed after earlier batches were - # billed: their usage must still reach the ledger. + 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=isinstance(err, MistralOcrProviderError), + retryable=not isinstance(err, ConversionError), ) from err finally: batches.close() @@ -324,7 +332,8 @@ def billed_usage() -> tuple[ConverterUsageEvent, ...]: failed_call_keys=("ocr",), retryable=False, ) - merged = {**merged, "pages": pages} + # 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"] = { diff --git a/src/rememberstack/adapters/converters/pdf.py b/src/rememberstack/adapters/converters/pdf.py index f67d758cc..ffdb49c98 100644 --- a/src/rememberstack/adapters/converters/pdf.py +++ b/src/rememberstack/adapters/converters/pdf.py @@ -270,41 +270,67 @@ def pdf_page_batches( Yields ``(first page index, page count, batch PDF bytes)`` in page order, covering every page exactly once. Each candidate 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, so memory never - grows with the source or with an oversized candidate; only a batch that - fits ``max_bytes`` is read into memory. A batch is sized from the - source's average page size and shrunk until it fits; a single page - larger than ``max_bytes`` fails the conversion, because no split can - send it. + them to a temporary file on disk and closes everything, so nothing + native outlives the lock; only a batch that fits ``max_bytes`` is read + into memory. Candidates start from the previous batch's size (one page + at first), grow towards the limit at most doubling, and then binary + search, so no candidate runs far past what fits. A single page larger + than ``max_bytes`` fails the conversion, because no split can send it. """ page_count = pdf_source_page_count(source=source) - total = pdf_source_size(source=source) start = 0 + previous = 1 while start < page_count: - remaining = page_count - start - size = max(1, min(remaining, int(page_count * max_bytes * 0.9 / total))) + cap = page_count - start if max_pages is not None: - size = min(size, max_pages) + cap = min(cap, max_pages) + fitting, batch = 0, b"" # the largest page count known to fit + overflowing: int | None = None # the smallest known not to + count = min(cap, previous) while True: - with tempfile.TemporaryFile() as spool: - saved = _with_pdfium( - work=partial( - _save_pages, source=source, first=start, count=size, out=spool - ), - what="PDF page batch", - ) - if saved <= max_bytes: - spool.seek(0) - batch = spool.read() - break - if size == 1: + saved, data = _trial( + source=source, first=start, count=count, limit=max_bytes + ) + if data is not None: + fitting, batch = count, data + else: + overflowing = count + if overflowing == 1: raise ConversionError( f"PDF page {start + 1} alone is {saved} bytes, over " f"the OCR provider limit of {max_bytes} bytes" ) - size = max(1, min(size - 1, int(size * max_bytes * 0.9 / saved))) - yield start, size, batch - start += size + if fitting == cap or ( + overflowing is not None and overflowing == fitting + 1 + ): + break + if overflowing is None: + # Grow towards the limit from the pages seen, at most doubling, + # so a trial never runs far past what fits. + estimate = int(count * max_bytes * 0.9 / max(saved, 1)) + count = min(cap, max(count + 1, min(2 * count, estimate))) + else: + count = (fitting + overflowing) // 2 + yield start, fitting, batch + start += fitting + previous = fitting + + +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: diff --git a/src/tests/adapters/test_mistral_ocr.py b/src/tests/adapters/test_mistral_ocr.py index 77beb9c79..ef7c795b3 100644 --- a/src/tests/adapters/test_mistral_ocr.py +++ b/src/tests/adapters/test_mistral_ocr.py @@ -9,6 +9,7 @@ from decimal import Decimal import json from pathlib import Path +from typing import cast import httpx import pytest @@ -735,3 +736,75 @@ def test_batching_leaves_pdfium_unlocked() -> None: content=_pdf(pages=_TEN_PAGES), mime="application/pdf" ) assert not pdf_module._PDFIUM_LOCK.locked() # noqa: SLF001 + + +def test_byte_split_trials_grow_from_one_page_at_most_doubling( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """No candidate batch runs far past what is known to fit (D147).""" + from rememberstack.adapters.converters import pdf as pdf_module + + trials: list[tuple[int, int]] = [] + real = pdf_module._save_pages # noqa: SLF001 + + def record(**kwargs: object) -> int: + saved = real(**kwargs) # type: ignore[arg-type] + trials.append((cast(int, kwargs["count"]), saved)) + return saved + + monkeypatch.setattr(pdf_module, "_save_pages", record) + content = _pdf(pages=_TEN_PAGES) + limit = len(content) // 2 + calls: list[int] = [] + _converter(_page_echo_transport(calls), max_document_bytes=limit).convert( + content=content, mime="application/pdf" + ) + assert sum(calls) == 10 + assert trials[0][0] == 1 + largest_fit = 1 + for count, saved in trials: + assert count <= 2 * largest_fit + if saved <= limit: + largest_fit = max(largest_fit, count) + + +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} From d6f9a8c2a27348d845054ff08c5c9a2ca214e9e8 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 16:30:23 +0100 Subject: [PATCH 4/6] Size PDF batches from measured page sizes; surface spool write errors - Measure each page alone (one-page PDF saved to a counter) and take pages while their sizes sum within the byte ceiling, so no candidate batch runs past the limit on uneven pages. - pdfium swallows write-callback exceptions; record them in the save sink and re-raise, so a full disk is a retryable error, not an empty batch sent to the provider. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- decisions.md | 13 +- src/rememberstack/adapters/converters/pdf.py | 166 +++++++++++++------ src/tests/adapters/test_mistral_ocr.py | 56 +++++-- 3 files changed, 166 insertions(+), 69 deletions(-) diff --git a/decisions.md b/decisions.md index 8c140c8d0..b95e8fa1f 100644 --- a/decisions.md +++ b/decisions.md @@ -7426,18 +7426,19 @@ deployment's values into another's work. - *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. A batch starts from the previous batch's page count (one page at - first), grows towards the byte ceiling at most doubling, then binary-searches, so no - candidate runs far past what fits; 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 + that each fit. Each page is first measured alone (a one-page PDF saved to a + counter), 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) carries their - usage. `PdfConverter.convert_path(path, + 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. diff --git a/src/rememberstack/adapters/converters/pdf.py b/src/rememberstack/adapters/converters/pdf.py index ffdb49c98..312ebaf5a 100644 --- a/src/rememberstack/adapters/converters/pdf.py +++ b/src/rememberstack/adapters/converters/pdf.py @@ -268,52 +268,67 @@ def pdf_page_batches( """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 candidate 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, so nothing - native outlives the lock; only a batch that fits ``max_bytes`` is read - into memory. Candidates start from the previous batch's size (one page - at first), grow towards the limit at most doubling, and then binary - search, so no candidate runs far past what fits. A single page larger - than ``max_bytes`` fails the conversion, because no split can send it. + covering every page exactly once. Each page is first measured alone (a + one-page PDF saved to a counter, 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 - previous = 1 while start < page_count: cap = page_count - start if max_pages is not None: cap = min(cap, max_pages) - fitting, batch = 0, b"" # the largest page count known to fit - overflowing: int | None = None # the smallest known not to - count = min(cap, previous) + 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, data = _trial( + saved, batch = _trial( source=source, first=start, count=count, limit=max_bytes ) - if data is not None: - fitting, batch = count, data - else: - overflowing = count - if overflowing == 1: - raise ConversionError( - f"PDF page {start + 1} alone is {saved} bytes, over " - f"the OCR provider limit of {max_bytes} bytes" - ) - if fitting == cap or ( - overflowing is not None and overflowing == fitting + 1 - ): + if batch is not None: break - if overflowing is None: - # Grow towards the limit from the pages seen, at most doubling, - # so a trial never runs far past what fits. - estimate = int(count * max_bytes * 0.9 / max(saved, 1)) - count = min(cap, max(count + 1, min(2 * count, estimate))) - else: - count = (fitting + overflowing) // 2 - yield start, fitting, batch - start += fitting - previous = fitting + 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( @@ -337,28 +352,83 @@ 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``. + + Opens and closes every native document inside the one locked operation. + """ + document = _open_source(source=source) + try: + sizes = [] + for page in range(first, first + count): + sink = _Sink(out=None) + _save_copy(document=document, pages=[page], sink=sink) + sizes.append(sink.size) + return sizes + finally: + document.close() + + 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: - document = pypdfium2.PdfDocument(_pdfium_input(source=source)) - except pypdfium2.PdfiumError as err: - raise ConversionError(f"the PDF could not be opened: {err}") from err - try: - batch = pypdfium2.PdfDocument.new() - try: - batch.import_pages(document, pages=list(range(first, first + count))) - batch.save(out) - except pypdfium2.PdfiumError as err: - raise ConversionError(f"the PDF pages could not be split: {err}") from err - finally: - batch.close() + sink = _Sink(out=out) + _save_copy( + document=document, pages=list(range(first, first + count)), sink=sink + ) + return sink.size finally: document.close() - return out.tell() def _with_pdfium[T](*, work: Callable[[], T], what: str) -> T: diff --git a/src/tests/adapters/test_mistral_ocr.py b/src/tests/adapters/test_mistral_ocr.py index ef7c795b3..78d696527 100644 --- a/src/tests/adapters/test_mistral_ocr.py +++ b/src/tests/adapters/test_mistral_ocr.py @@ -9,6 +9,9 @@ from decimal import Decimal import json from pathlib import Path +import random +import string +from typing import Any from typing import cast import httpx @@ -738,34 +741,57 @@ def test_batching_leaves_pdfium_unlocked() -> None: assert not pdf_module._PDFIUM_LOCK.locked() # noqa: SLF001 -def test_byte_split_trials_grow_from_one_page_at_most_doubling( +def test_no_candidate_batch_runs_past_the_byte_ceiling_on_uneven_pages( monkeypatch: pytest.MonkeyPatch, ) -> None: - """No candidate batch runs far past what is known to fit (D147).""" + """Small pages then heavy ones: candidates stay under the limit (D147).""" from rememberstack.adapters.converters import pdf as pdf_module - trials: list[tuple[int, int]] = [] + trials: list[int] = [] real = pdf_module._save_pages # noqa: SLF001 def record(**kwargs: object) -> int: saved = real(**kwargs) # type: ignore[arg-type] - trials.append((cast(int, kwargs["count"]), saved)) + trials.append(saved) return saved monkeypatch.setattr(pdf_module, "_save_pages", record) - content = _pdf(pages=_TEN_PAGES) - limit = len(content) // 2 + 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] = [] - _converter(_page_echo_transport(calls), max_document_bytes=limit).convert( - content=content, mime="application/pdf" + result = _converter(_page_echo_transport(calls), max_document_bytes=limit).convert( + content=_pdf(pages=texts), mime="application/pdf" ) - assert sum(calls) == 10 - assert trials[0][0] == 1 - largest_fit = 1 - for count, saved in trials: - assert count <= 2 * largest_fit - if saved <= limit: - largest_fit = max(largest_fit, count) + 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_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( From dce869a8c05d64d3c2c0313c9a6e033f09767aba Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 16:44:43 +0100 Subject: [PATCH 5/6] Measure each PDF page from a freshly opened source Reopening the source per measured page keeps pdfium from holding more than one page's data while batches are sized. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- decisions.md | 2 +- src/rememberstack/adapters/converters/pdf.py | 21 +++++++------ src/tests/adapters/test_mistral_ocr.py | 33 ++++++++++++++++++++ 3 files changed, 46 insertions(+), 10 deletions(-) diff --git a/decisions.md b/decisions.md index b95e8fa1f..b87f90fc7 100644 --- a/decisions.md +++ b/decisions.md @@ -7427,7 +7427,7 @@ deployment's values into another's work. 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), and a batch takes pages while those sizes add up to at most the byte + 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 diff --git a/src/rememberstack/adapters/converters/pdf.py b/src/rememberstack/adapters/converters/pdf.py index 312ebaf5a..4e617ebab 100644 --- a/src/rememberstack/adapters/converters/pdf.py +++ b/src/rememberstack/adapters/converters/pdf.py @@ -269,7 +269,8 @@ def pdf_page_batches( 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, nothing kept), and a batch takes pages + 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 @@ -400,18 +401,20 @@ def _open_source(*, source: PdfSource) -> pypdfium2.PdfDocument: 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``. - Opens and closes every native document inside the one locked operation. + 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. """ - document = _open_source(source=source) - try: - sizes = [] - for page in range(first, first + count): + 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) - return sizes - finally: - document.close() + finally: + document.close() + return sizes def _save_pages(*, source: PdfSource, first: int, count: int, out: BinaryIO) -> int: diff --git a/src/tests/adapters/test_mistral_ocr.py b/src/tests/adapters/test_mistral_ocr.py index 78d696527..9bc376ce7 100644 --- a/src/tests/adapters/test_mistral_ocr.py +++ b/src/tests/adapters/test_mistral_ocr.py @@ -777,6 +777,39 @@ def record(**kwargs: object) -> int: 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 From 05e5a967ff5cf0d587f514e4a777ab76d2791895 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 16:57:05 +0100 Subject: [PATCH 6/6] Mark D139's PDF provider limit superseded; add the changelog entry Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- decisions.md | 4 +++- website/public/llms-full.txt | 12 ++++++++++++ website/src/app/docs/project/changelog/page.mdx | 12 ++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/decisions.md b/decisions.md index b87f90fc7..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.” diff --git a/website/public/llms-full.txt b/website/public/llms-full.txt index 15cf314b3..954776a75 100644 --- a/website/public/llms-full.txt +++ b/website/public/llms-full.txt @@ -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/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