Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.”
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion plan/designs/format_conversion_design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
25 changes: 14 additions & 11 deletions plan/designs/workspace_formats_design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion src/rememberstack/adapters/converters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
172 changes: 166 additions & 6 deletions src/rememberstack/adapters/converters/mistral_ocr.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import base64
from decimal import Decimal
import json
from pathlib import Path
import re
import time
from typing import Any
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]:
Expand Down
Loading
Loading