Skip to content

feat(D147): OCR large PDFs in page batches instead of failing at the provider limit - #552

Merged
fazpu merged 6 commits into
mainfrom
feat/pdf-ocr-batches
Nov 7, 2026
Merged

fazpu merged 6 commits into
mainfrom
feat/pdf-ocr-batches

Conversation

@fazpu

@fazpu fazpu commented Nov 7, 2026

Copy link
Copy Markdown
Member

Owner rule: no caps. Before this PR, the PDF route failed any PDF over the OCR provider's per-request ceiling (Mistral: max_document_bytes, 50 MB). Now it splits the PDF into page-range batches, OCRs each one, and stitches the results in page order.

How it works

  • Ceilings: MistralOcrSettings.max_document_bytes (50 MB, unchanged) and a new max_document_pages (1,000). Neither enters version_fingerprint(), so no representation is re-keyed.
  • Splitting: a valid PDF over either ceiling is split with pdfium, which the engine already uses (pdf.pdf_page_batches).
    • Each batch is a new PDF made with import_pages. It is sized from the average page size and shrunk until its saved bytes fit the byte ceiling, and it never exceeds the page ceiling.
    • Only one batch is held at a time.
    • Each pdfium call runs under the existing process lock and converter time limit.
  • Stitching: each batch is one /v1/ocr call.
    • Its pages come back indexed from 0 and are renumbered from the batch's first page, after a per-batch completeness check.
    • The pages are folded into one response, which then goes through the existing _usage (every source page, one ocr usage event) and _normalize. With page-wise identical provider output, the result equals a single call: same document_md, source map, derivation ranges and asset names (asset names carry page numbers).
    • Every page is still OCR'd; there is no text-layer path.
  • Below both ceilings, the request is byte-for-byte the same: one call carrying the original bytes. So is the result.
  • Failure handling:
    • A batch failing after earlier batches were billed raises ConverterLaneError carrying their usage. It is retryable for provider errors and terminal for deterministic 4xx.
    • A single page over the byte ceiling fails with a typed ConversionError.
    • Non-PDF inputs keep the existing byte ceiling.
  • Route limit: the PDF route no longer declares provider_limit_bytes, so the convert stage does not pre-refuse PDFs over 50 MB. The 100 MB PDF reading limit still applies on the in-process bytes path (feat(D147): oversized files reach a URL route; pass 413 from the spend lease #550).

Convert service / URL route

PdfConverter.convert_path(path=, mime=) and MistralOcrConverter.convert_path(path=, mime=) convert a PDF from a local file. pdfium reads it lazily and batches are built one at a time, so a host that downloads the input by pre-signed URL to disk never holds the PDF in memory: one batch (≤ 50 MB) plus its request. Below the ceilings the file is read and sent whole, exactly as by convert.

Tests (test_mistral_ocr.py, with a mock provider that "OCRs" each batch from its text layer)

  • With 10 pages and a page ceiling of 4, the calls are [4, 4, 2], and the reading, source map and derivation ranges equal the single-call result. 10 pages are metered.
  • With the byte ceiling at half the file, the PDF is split and every page appears in order.
  • A single page over the ceiling raises a typed error.
  • A failure on batch 2 raises a retryable ConverterLaneError carrying batch 1's 4 pages.
  • convert_path on a 10-page file with Path.read_bytes forbidden gives batches [3, 3, 3, 1] and all pages located.
  • Below the ceilings there is exactly one request with the original bytes.

Checks

  • ruff, pyright (0), unit lane (3159 passed), docs checks
  • CI
  • Codex review

Coordination: meter-d94 (convert-stage metering, E1) has been told which files this touches.

🤖 Generated with Claude Code

https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm

@fazpu

fazpu commented Nov 7, 2026

Copy link
Copy Markdown
Member Author

Codex review round 1 (gpt-6.1-sol, max effort)

VERDICT: REQUEST_CHANGES

  1. Major — convert_path memory grows with the source PDF. pdf.py:275 keeps the source document open across every batch. A 128 MiB image PDF emitted 4 MiB batches while RSS grew from approximately 96 to 229 MiB, even with forced garbage collection. Reopening the source per batch kept memory roughly flat. Simplest fix: open, import, save and close the source within each batch operation.

  2. Major — trial batches allocate before the size check. pdf.py:288 materializes the estimated range in memory before checking its length. With uneven page sizes, a 100,000-byte ceiling produced a 489,387-byte candidate although each page fitted individually; this can scale to gigabytes. Simplest fix: construct ranges conservatively, using bounded disk-backed trials before reading a fitting batch into bytes.

  3. Major — splitter failures lose earlier billed usage. mistral_ocr.py:269 advances the batch iterator outside the usage-preserving try. A successful first OCR followed by an oversized second page raises plain ConversionError without usage. Later splitting, timeout and cleanup failures have the same gap. Simplest fix: wrap iteration and cleanup, carrying accumulated usage through ConverterLaneError.

  4. Major — a timed-out open can close pdfium outside its lock. pdf.py:350 can abandon an operation returning a native document. When that operation finishes, its unclaimed document is finalized after the lock releases. I reproduced the native close with _PDFIUM_LOCK.locked() == False, permitting concurrent pdfium calls. Simplest fix: keep native document creation, work and cleanup inside one locked worker operation.

  5. Minor — accepted page indexes can produce reversed readings. mistral_ocr.py:308 appends response order after validating sorted indexes. Responses containing [1, 0] pass and produce document order [2, 1, 4, 3]. Simplest fix: sort each batch’s pages by index before appending.

  6. Minor — interchange metadata describes only the first batch. mistral_ocr.py:324 aggregates pages_processed while retaining the first batch’s doc_size_bytes and dropping later top-level metadata. Simplest fix: preserve per-batch response metadata and explicitly aggregate diagnostic totals.

  7. Minor — binding designs still contradict the new limit policy. format_conversion_design.md:76 allows batching, while workspace_formats_design.md:82 still mandates refusal above the lower provider/family ceiling. Simplest fix: reconcile the surviving limit rules and examples.

Validation: 138 passed, 3 skipped; Ruff and diff checks passed. Rich stitching probes matched for ordered responses, and no converter-version or reuse-key change was found. Docker was not used; the worktree remains unchanged.

Disposition (Claude): all accepted, fixed in d701c19

1, 2 and 4 are fixed by one redesign of pdf_page_batches. Each candidate batch is one locked pdfium operation (_save_pages): open the source, import_pages, save into a temporary file on disk, and close both documents. Nothing native outlives the lock, and memory doesn't grow with the source. A candidate is checked by its saved size on disk; only a fitting batch (at most max_bytes) is read into memory. Test test_batching_leaves_pdfium_unlocked.
3. Iteration and the generator's cleanup are now inside the usage-preserving try. Any ConversionError or provider error after billed batches becomes a ConverterLaneError carrying their usage. Test test_a_splitter_failure_after_billed_batches_carries_their_usage.
5. Each batch's pages are sorted by index before stitching. Test test_batch_pages_are_stitched_by_index_not_response_order.
6. Every integer field of usage_info (pages_processed, doc_size_bytes) is now totalled across batches.
7. workspace_formats_design.md §3: page-range batching is explicitly not a replacement of every-page OCR. The size paragraph now matches: no effective pre-OCR provider limit, the reading limits are bytes-path only, and the example is updated.

@fazpu

fazpu commented Nov 7, 2026

Copy link
Copy Markdown
Member Author

Codex review, round 2 (gpt-6.1-sol, max)

VERDICT: REQUEST_CHANGES

  1. Major — Oversized trials still allocate native memory before sizing. pdf.py:327 imports the entire estimated range before checking its saved size. With a 2 MiB ceiling and individually fitting pages, a 64.9 MiB PDF produced a 64 MiB trial; peak RSS rose from approximately 80 to 211 MiB. Disk-backed saving leaves round-1 finding 2 unresolved. Simplest fix: grow ranges conservatively, page by page, stopping at the first overflow; add an uneven-page memory regression.

  2. Major — Splitter I/O failures still lose billed usage. mistral_ocr.py:305 catches only ConversionError and MistralOcrProviderError. Making the second TemporaryFile() fail with OSError(28) after four successfully OCR’d pages propagated plain OSError without usage. Round-1 finding 3 is only partially fixed. Simplest fix: wrap splitter I/O failures in a retryable ConverterLaneError carrying accumulated usage.

  3. Minor — Later batches’ interchange metadata is still discarded. mistral_ocr.py:327 retains the first response’s top-level fields while folding pages and integer usage totals. Distinct document_annotation values from subsequent batches disappear. Simplest fix: retain each batch’s metadata, with its page range, in the interchange asset alongside aggregate totals.

Validation: 184 passed, 3 skipped; Ruff, Pyright and diff checks passed. Below-ceiling payload/artifact equivalence, rich stitching, timeout lock cleanup, page ordering, sizing and URL-route limit behavior verified. No converter-version or reuse-key changes found. Docker/database tests were not run; worktree unchanged.
tokens used
118,463
VERDICT: REQUEST_CHANGES

  1. Major — Oversized trials still allocate native memory before sizing. pdf.py:327 imports the entire estimated range before checking its saved size. With a 2 MiB ceiling and individually fitting pages, a 64.9 MiB PDF produced a 64 MiB trial; peak RSS rose from approximately 80 to 211 MiB. Disk-backed saving leaves round-1 finding 2 unresolved. Simplest fix: grow ranges conservatively, page by page, stopping at the first overflow; add an uneven-page memory regression.

  2. Major — Splitter I/O failures still lose billed usage. mistral_ocr.py:305 catches only ConversionError and MistralOcrProviderError. Making the second TemporaryFile() fail with OSError(28) after four successfully OCR’d pages propagated plain OSError without usage. Round-1 finding 3 is only partially fixed. Simplest fix: wrap splitter I/O failures in a retryable ConverterLaneError carrying accumulated usage.

  3. Minor — Later batches’ interchange metadata is still discarded. mistral_ocr.py:327 retains the first response’s top-level fields while folding pages and integer usage totals. Distinct document_annotation values from subsequent batches disappear. Simplest fix: retain each batch’s metadata, with its page range, in the interchange asset alongside aggregate totals.

Validation: 184 passed, 3 skipped; Ruff, Pyright and diff checks passed. Below-ceiling payload/artifact equivalence, rich stitching, timeout lock cleanup, page ordering, sizing and URL-route limit behavior verified. No converter-version or reuse-key changes found. Docker/database tests were not run; worktree unchanged.

Dispositions (commit 7aec191)

  1. Fixed. Candidates now start from the previous batch's page count (one page at first), grow towards the byte ceiling at most doubling, then binary-search between the last fit and the first overflow. No trial exceeds twice a count known to fit. Regression test: test_byte_split_trials_grow_from_one_page_at_most_doubling. I did not adopt strict page-by-page growth, because it needs O(k²) trial saves per batch; doubling keeps the overshoot bounded at 2x with O(log k) trials.
  2. Fixed. OSError is caught alongside ConversionError and MistralOcrProviderError; after billed batches it becomes a retryable ConverterLaneError carrying their usage. Test: test_a_spool_failure_after_billed_batches_carries_their_usage.
  3. Fixed. Each batch's top-level response (everything but pages) is kept with first_page and page_count under batches in the interchange asset; aggregate usage_info is unchanged. Test: test_every_batch_response_is_kept_in_the_interchange_asset.

D147 item 4 updated. Unit lane: 3165 passed.

@fazpu

fazpu commented Nov 7, 2026

Copy link
Copy Markdown
Member Author

Codex review, round 3 (gpt-6.1-sol, max)

VERDICT: REQUEST_CHANGES

  1. Major — Page-count doubling still permits oversized native allocations. pdf.py:311. Through convert_path, 64 tiny pages followed by 64 image-heavy pages produced a 64 MiB trial under a 2 MiB ceiling, although every page fitted individually. Peak RSS rose from approximately 85 to 236 MiB. Doubling page count does not bound bytes; round-2 finding 1 remains unresolved. Simplest fix: import pages incrementally until the first overflow, and add an uneven-page memory regression.

  2. Major — Spool-write errors can permanently fail valid documents. pdf.py:354. Pdfium’s callback swallows Python write exceptions. Injecting ENOSPC after the first billed batch returned an empty “successful” spool, submitted an empty PDF, and converted the provider’s HTTP 400 into a non-retryable failure. Earlier usage survived, but the transient disk failure became terminal. Simplest fix: capture callback write errors and re-raise OSError before accepting or submitting the spool; test actual write failures.

Validation: 185 passed, 3 skipped; Ruff and Pyright passed. Sixteen settings combinations matched origin/main below ceilings, including request bytes and artifacts. Rich stitching, metadata retention and timeout lock cleanup passed. No converter-version or reuse-key changes found under Rule 4. Docker was not used; worktree unchanged.

Dispositions (commit cd116af)

  1. Fixed, differently. Doubling the page count doesn't bound bytes, agreed. I didn't import page by page with a save after each page, because that writes O(k²) bytes per batch. Instead, each page is measured once on its own (a one-page PDF saved to a counting sink, nothing kept, 64 pages per locked op). A batch then takes pages while those sizes sum to at most the byte ceiling. Shared resources count once per page in that sum, so the real batch is normally smaller, and the first candidate is at most about the limit whatever the page sizes. It's shrunk only if its own save is still over. Regression test: test_no_candidate_batch_runs_past_the_byte_ceiling_on_uneven_pages (8 tiny pages, then 8 incompressible ~30 kB pages, 100 kB limit; asserts every candidate's saved size is at most the limit). The old doubling made a 240 kB candidate in this case.
  2. Fixed. The save target is now a _Sink that counts bytes and records the first OSError from the spool write; _save_copy re-raises it after pdfium returns, so no empty batch is sent. The _batched_pdf handler turns it into a retryable ConverterLaneError carrying billed usage (round 2). Test: test_a_failed_spool_write_raises_instead_of_saving_an_empty_batch.

Unit lane: 3166 passed.

@fazpu

fazpu commented Nov 7, 2026

Copy link
Copy Markdown
Member Author

Codex review, round 4 (gpt-6.1-sol, max)

VERDICT: REQUEST_CHANGES

  1. Major — Page measurement still exceeds the batch memory budget. pdf.py:405 keeps the source open while measuring 64 pages, retaining their native data. With a 64 MiB image PDF and 2 MiB ceiling, convert_path RSS grew from approximately 80 to 154 MiB, although every emitted batch was about 1 MiB. Isolated measurement with source reopening stayed near 86 MiB. At the default ceiling, this can exhaust convert-service memory before OCR. Simplest fix: move source open/close inside the existing measurement loop, keeping one save per page, and add a memory regression covering measurement.

The round-3 spool-write fix is verified, including retryability and billed usage. 207 tests passed, 36 skipped; Ruff, Pyright and CI gate passed. Below-ceiling requests and artifacts matched origin/main across 32 settings combinations. Stitching, sizing, URL-route limits and timeout locking passed. No version or reuse-key changes found. No containers started; worktree unchanged.

Disposition (commit c35ba90)

  1. Fixed as suggested. _measure_pages now opens and closes the source for every page, still with one save per page, so pdfium never holds more than one page's data. Test: test_each_page_is_measured_from_a_freshly_opened_source (at most one document open at a time, and all of them closed).

I measured peak RSS with a 69 MB, 64-page image PDF on disk and a 2 MiB ceiling (64 one-page batches of about 1 MiB), running each stage in its own process:

stage peak RSS
baseline 80 MiB
page measurement (8 or 1 page per locked op) 81 MiB
all 64 batch trials 83 MiB
pdfium page count 80 MiB
pdf_source_has_body (mmap scan of the file) 146 MiB

So the remaining peak comes from the PDF body check, which scans a memory map of the file for the end marker. Those are clean, file-backed pages: the kernel reclaims them under pressure and they go away when the map closes. It isn't anonymous memory. On Cloud Run, /tmp is itself in memory, so the downloaded file already costs its size whether or not it's mapped. I'm leaving the body check as it is, so a file on disk and the same bytes in memory get the same answer.

Unit lane: 3167 passed.

fazpu and others added 6 commits November 7, 2026 16:57
…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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
… 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm
@fazpu

fazpu commented Nov 7, 2026

Copy link
Copy Markdown
Member Author

Codex review, round 5 (gpt-6.1-sol, max)

VERDICT: APPROVE

  1. Minor, non-blocking — stale limit rule. decisions.md:6853 still requires rejecting PDFs above the provider ceiling. Simplest fix: mark that D139 clause superseded by D147 item 4.

Round-4 fix verified; no code regressions found. Below-ceiling requests and artifacts matched origin/main across 32 settings combinations. Stitching, sizing, timeout locking, billed usage, and URL-route limits passed. No version or reuse-key changes.

335 tests passed, 21 skipped. Ruff, Pyright, and CI gate passed. Database tests left to CI; no containers started or files modified.

Disposition (commit 05e5a96, rebased on main)

  1. Fixed. D139's pre-OCR provider-ceiling clause is marked superseded by D147 item 4. I also added an "Unreleased" changelog entry (0.18.2 is already released).

@fazpu
fazpu force-pushed the feat/pdf-ocr-batches branch from c35ba90 to 05e5a96 Compare November 7, 2026 15:57
@fazpu
fazpu merged commit 1fa204c into main Nov 7, 2026
21 checks passed
@fazpu fazpu mentioned this pull request Nov 7, 2026
6 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant