Skip to content

fix(pdf): reading a PDF larger than 384MB fails instead of returning an answer - #178

Merged
ikhsanuddin merged 2 commits into
boonfrom
eng-19240-pdf-chunking
Sep 2, 2026
Merged

ikhsanuddin merged 2 commits into
boonfrom
eng-19240-pdf-chunking

Conversation

@ikhsanuddin

@ikhsanuddin ikhsanuddin commented Sep 2, 2026 •

Copy link
Copy Markdown

Linear: ENG-19240

Read the "Why not page-range chunking" section before the diff. The ticket's first proposed option was page-range chunking. I measured it three different ways and it does not lift the residual ceiling. That is why this PR does not contain any chunking.

What Problem This Solves

Fixes an issue where an agent asked to read a large PDF bid set would get Error: Cannot create a string longer than 0x1fffffe8 characters instead of an answer, whenever the PDF was larger than 384 MB. The failure was independent of heap size, container size, and the configured pdfMaxBytesMb — a 1 GB fleet cap advertised a size the tool could never actually process. Two related operational problems shipped with it: an oversized local PDF was read fully into memory before being refused, and peak memory ran roughly 4x file size, so a large set could OOM a trial container before it failed on the string limit.

Why This Change Was Made

The pdf tool base64-encoded every loaded PDF up front, in the load loop, even though only the native-provider branch ever consumes that string. Base64 inflates 4/3 and V8 caps a single string at 0x1fffffe8 chars, so 384 MB of PDF was a hard wall. Deleting that eager encode is the fix; everything else is the memory and honesty work around it.

The complete shipped change:

  • Deleted the eager media.buffer.toString("base64"). loadedPdfs now carries only the Buffer, and base64 is built lazily inside the native branch, so it only ever exists for a file small enough to send.
  • Native inline is size-gated at 32 MB. Above that the native branch is skipped and the same run falls through to local extraction, which is bounded by pdfMaxPages rather than by file size.
  • maxBytes is clamped to a 768 MB engine ceiling. PDFium runs in a 2 GiB WASM heap and FPDF_LoadMemDocument copies the whole file into it, so the file and its per-page working set share those 2 GiB. A fleet config of 1024 could not be honoured.
  • Removed a gratuitous full-file copy in the document extractor. new Uint8Array(request.buffer) re-wrapped a Buffer that already is a Uint8Array. Removing it dropped peak RSS on a 1.34 GB set from 4080 MB to 2790 MB (−1.29 GB, about one whole file).
  • Local reads are refused from stat, before materialization. The byte cap is now threaded into readLocalFileSafely, which already had a pre-readFile size check that nothing was feeding. Same pre-stat gate added to the sandbox bridge reader. No second gate was introduced.

Why not page-range chunking (measured, refuted)

The ticket proposed batching pages so memory would be O(chunk). It isn't, because the file copy alone eats 70% of the WASM heap before any page renders. PDFium's 2 GiB heap is a compiled-in constant (2147483648 in node_modules/clawpdf/dist/vendor/pdfium.esm.js), and _FPDF_LoadMemDocument mallocs bytes.byteLength and HEAPU8.sets the entire file into it (engine.js:openInternal). Three independent strategies on the same 1.34 GB set, all aborting on the same page 13:

Strategy Result
One document, 20 pages heap 1437 → 1759 → 1951 MB, abort at page 13
One engine, fresh document per 5-page batch heap 1437 → 1768 MB, abort at page 13
Fresh engine (fresh WASM module) per 5-page batch batch 2 alone reached heap 1725 MB, abort at page 13; peak RSS 6.2 GB

Page 13 needs >611 MB of PDFium working memory by itself. With 1437 MB permanently spent on the file copy, no slicing of the page list creates that headroom. The binding constraint is fileBytes + singlePageWorkingSet <= 2 GiB, and the page list is not a term in it.

What would actually lift the residual ceiling (not in this PR, the ticket's options 2/3):

  1. FPDF_LoadCustomDocument with a read callback, so PDFium pages bytes in on demand instead of holding a full copy. clawpdf does not currently expose that loader.
  2. Extraction out of tenant — a provider Files API upload, or a service with real memory and a random-access loader.

User Impact

An agent can now read a PDF past the old 384 MB wall. Proven end to end on a real 400 MB / 30-page set with real PDFium: it returns an answer instead of throwing. Peak memory for that run is ~2.1x file size, down from ~4x. A file too large for the engine is now refused immediately with a message naming the file and the limit, instead of being read into memory first and then rejected with a wrong message.

Behaviour change worth flagging: PDFs between 32 MB and 384 MB no longer attempt native provider inlining and go straight to local extraction. See the assumptions below.

Evidence

Tests — 4 new, each verified to FAIL on unfixed origin/boon code

Verified by stashing only the production files and re-running.

Test File Fails without the fix with
processes a PDF past the V8 base64 ceiling without encoding it src/agents/tools/pdf-tool.test.ts Error: Cannot create a string longer than 0x1fffffe8 characters — the ticket's exact error
clamps a configured pdfMaxBytesMb down to the engine ceiling src/agents/tools/pdf-tool.test.ts expected 1073741824 to deeply equal 805306368
refuses an oversized local file from its stat, before the bytes are materialized src/media/web-media.test.ts Media exceeds 1MB limit (got 640.00MB) — wrong message, and it materialized 640 MB to get there
hands the request buffer to clawpdf without copying it extensions/document-extract/document-extractor.test.ts identity assertion fails (a copy was passed)

How they stay cheap while still proving the thing:

  • The ceiling test uses Buffer.allocUnsafe(385 * 1024 * 1024). 385 MiB is the smallest size whose base64 exceeds 0x1fffffe8 chars, and allocUnsafe never touches the pages, so the fixture costs almost nothing in RSS — but a regression still throws the real V8 error.
  • "No allocation scales with file size" is asserted structurally: a Buffer.prototype.toString spy confirms nothing base64-encodes a buffer larger than 64 MB anywhere in the run.
  • The refusal test uses a 640 MB sparse file and asserts process.memoryUsage().external grew by less than half the file before checking the message, so "before materialization" is what fails on regression, not just the wording. Skipped on win32, where sparse truncate is a no-op.

Live end-to-end run (not committed — needs a 400 MB fixture)

Drove the real createPdfTool().execute() against a valid 400 MB / 30-page PDF with real loadWebMediaRaw and real PDFium, only the LLM call stubbed. Passed on this branch; threw the ticket's error on origin/boon. RSS 722.7 → 1579.9 MB, growth 857 MB = 2.14x file size.

Checks

Check Result
pnpm tsgo:prod (core + extensions) exit 0
pnpm tsgo:test (core:test + extensions:test) exit 0
oxfmt --check on all 8 changed files clean
oxlint --type-aware on the 4 changed prod files exit 0
pdf-tool.test.ts 27 passed
web-media.test.ts 75 passed
document-extractor.test.ts 8 passed
local-media-access + sandbox-media-paths + pdf-extract + document-extractors.runtime + plugin-sdk-runtime-api-guardrails 21 passed
image-tool.test.ts + media-tool-shared.test.ts (the other createSandboxBridgeReadFile consumers) 105 passed

Root-cause check: is this the only unbounded PDF base64?

Yes, for ingest. Every toString("base64") in src/ and extensions/ was checked; the rest are images-only branches (gated on detectImageMimeType), the already-graceful 5 MB input-files.ts path with its rejectOversizedBase64Payload pre-check, or fixed-size inputs (hashes, tokens, auth headers). No sibling PDF-ingest path is still broken.

Assumptions — stated as assumptions, not measurements

Three things in this diff are judgement calls I did not measure. Reviewers should push back on any of them.

  1. The 32 MB native-inline threshold comes from Anthropic's documented request cap, not from a live 413. Files between 32 MB and 384 MB previously attempted native inline and now don't. I believe those requests were already failing upstream, but I did not confirm with a live provider call. Note Gemini's inline limit is lower (~20 MB), so a 25 MB file will still attempt native for google and fall through on error — the existing fallback machinery handles that.
  2. The 768 MB ceiling is judgement, not a measured cliff. Derived from 2 GiB heap − worst observed working set (~700 MB) ≈ 1.3 GB theoretical, halved for margin because one pathological page can spike. I proved 400 MB works and 1.34 GB does not; I did not bisect between them (no valid PDF of intermediate size was available — a 529 MB candidate was truncated and failed FPDF_LoadMemDocument outright).
  3. The sandbox path gate is unverified as to whether it is ever exercised. I added the same pre-stat gate to createSandboxBridgeReadFile for parity with the host path, but I did not verify whether boon's trial/paid agents actually run the PDF tool sandboxed. It is harmless either way.

Follow-ups, not in this PR

  • boon-infra should lower pdfMaxBytesMb. It is baked at 1024 in packer/scripts/06-write-openclaw-json-template.sh (with an assert_field bake guard, so it must change there, not on hosts). The clamp here means 1024 now silently behaves as 768, which is safe but misleading. The two tiers want different numbers: peak RSS is ~2.1x file, so a 1 GB trial container tops out around 300–350 MB, well under the 768 MB engine ceiling. 768 is the paid-EC2 number.
  • The residual ceiling needs option 1 or 2 from the refutation section above, not chunking.
  • One adjacent latent defect, reported not fixed. src/infra/outbound/message-action-params.ts:528 does media.buffer.toString("base64") on an outbound message attachment, capped by resolveAttachmentMaxBytes. Boon configures mediaMaxMb = 1024 fleet-wide, so attaching a >384 MB file to an outbound message hits the identical V8 ceiling. Different feature (sending, not ingesting) and out of scope here; worth its own ticket.

Summary by cubic

Fixes PDF ingest failures above the 384 MB V8 base64 string limit. The tool no longer base64-encodes every loaded PDF up front; the encode is built lazily only inside the native-provider branch, which is skipped whenever the summed encoded size of all PDFs in the call exceeds the provider's request cap (32 MB for anthropic, 20 MB for google). Oversized PDFs fall through to local extraction, which is bounded by maxPages rather than file size.

Validation and memory

  • maxBytes is clamped to 768 MB, matching PDFium's 2 GiB WASM heap limit; a configured 1024 now behaves as 768.
  • Oversized local files are refused from stat before bytes are materialized, with an error naming the file and limit; the sandbox reader got the same gate.
  • The document extractor passes the existing Buffer to PDFium instead of re-wrapping it, roughly halving peak RSS.
  • Adds regression tests for the V8 limit, encoded-size budgeting, pre-read rejection, engine ceiling, and buffer reuse.

Written for commit 82d7218. Summary will update on new commits.

Review in cubic

…pre-read

The pdf tool encoded every loaded PDF into one base64 string up front, even
though only the native-provider path consumes it. V8 caps a string at
0x1fffffe8 chars and base64 inflates 4/3, so any PDF over 384MB threw
"Cannot create a string longer than" regardless of heap or container size.

- Drop the eager encode; build base64 lazily inside the native branch only,
  and skip that branch entirely above 32MB (Anthropic Messages caps a request
  there anyway), so the run falls through to local extraction, which is
  bounded by pdfMaxPages rather than file size.
- Clamp the configured pdfMaxBytesMb to 768MB. PDFium runs in a 2GiB WASM heap
  and FPDF_LoadMemDocument copies the whole file into it, so the file and its
  per-page working set share those 2GiB; a 1.34GB set loads and then aborts
  mid-extraction.
- Pass the byte cap into readLocalFileSafely so an oversized local file is
  refused from its stat instead of being read first, and name the file plus the
  limit in the error. Same pre-stat gate added to the sandbox bridge reader.
- Stop re-wrapping the request Buffer in the document extractor; Buffer already
  is a Uint8Array and the copy doubled peak memory (-1.3GB on a 1.34GB set).

Peak RSS for a 400MB set drops from impossible to ~2.1x file size.
@ikhsanuddin ikhsanuddin self-assigned this Sep 2, 2026
@claude

claude Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

Comment thread src/agents/tools/pdf-tool.ts Resolved
Comment thread src/agents/tools/pdf-tool.ts Resolved
Comment thread src/agents/tools/pdf-tool.test.ts Resolved
@ikhsanuddin

Copy link
Copy Markdown
Author

🔍 Adversarial review (Claude + Codex, independent of the author)

Reviewed at c201f4fa against boon. I was pointed at this PR to try to break its claims, not confirm them. The core claim holds: the eager media.buffer.toString("base64") was the 384MB wall, deleting it is the right fix, and the "why not page-range chunking" refutation is sound (I re-read clawpdf/dist/vendor/pdfium.esm.js and engine.js:83-90; fileBytes + singlePageWorkingSet <= 2GiB is the real constraint and the page list is genuinely not a term in it). What did not survive is a set of edges around the new gate and the new ceiling.

🟠 Posted inline

  • P2 · The 32MB native-inline gate measures the wrong quantity (pdf-tool.ts:204) - three defects in one expression: raw bytes compared against a cap on encoded request bytes (off by 4/3, so a single 32MiB PDF is already 42.7MiB of base64 and 33% over the cited cap); every() is per-file where the cap is per-request, so 10 x 32MiB all pass and produce a ~1.17GB transient peak on a request 13x the cap; and it is hoisted out of the per-attempt callback where provider is already in scope, so it cannot be the per-provider limit it needs to be. One edit fixes all three.
  • P2 · The 768MB clamp contradicts the public config contract (pdf-tool.ts:398) - the zod schema (positive(), no .max()), schema.help.ts:1463, and docs/tools/pdf.md:64 all still advertise an unbounded value. Root AGENTS.md requires those aligned. The operator-facing tail is an error naming 805306368 bytes under a config that says 1024.
  • P3 · mock.instances is outside its documented contract (pdf-tool.test.ts:395) - not the tautology I went looking for (proved load-bearing by mutation), but it reads the new-keyword array to get plain-call receivers. mock.contexts is the documented one. One-word fix; the failure mode if vitest ever aligns instances with its docs is a silently vacuous assertion.

🟡 File-spanning, no single anchor line

P3 (CONFIRMED) · docs/tools/pdf.md "Native mode limits" is now incomplete, and two documented errors became size-dependent.
The list at docs/tools/pdf.md:96-103 has exactly two entries, pages and password. This PR adds a third native-mode limit (32MB) and does not document it; AGENTS.md says docs change with behavior. The non-obvious knock-on: because canInlineNative === false skips the whole native branch, the pages is not supported with native PDF providers and password is not supported ... throws at pdf-tool.ts:222-228 (documented at docs/tools/pdf.md:166) now only fire for PDFs at or under 32MB. The same call with a 35MB PDF succeeds through extraction. The outcome is strictly better, but a documented error is now silently conditional on file size.

P3 (CONFIRMED, repo CI defect, not this PR's fault) · Critical Quality (web-media-runtime-boundary) never runs on any PR in this repo.
src/media/web-media.ts is in this diff and the check reported skipped. This is not a shard selector missing a path. .github/workflows/codeql-critical-quality.yml:675 reads if: ${{ github.event_name != 'pull_request' && ... }}, so the job is hard-excluded from every pull_request event. The detect step (:180-193) declares 13 shard outputs and there is no web_media output at all, which is presumably why the author of that job reached for the event-name exclusion instead. Every other boundary job uses needs: quality-shards plus a shard output (agent-runtime-boundary at :513-516 is the pattern, and it ran and passed here). ui-control-plane (:653) has the identical defect. The check is not broken, just unreachable from PRs: it reported success on origin/boon's head. Net effect is that the guard on web-media.ts only fires after a change lands on boon. Worth its own ticket (add a web_media shard and switch to needs: quality-shards); not a merge block here.

Lower notes, no action asked.

  • localReadCap is computed but not applied on the readFileOverride branch (web-media.ts:1036-1048), which is why the sandbox needed its own gate. Of the 6 createSandboxBridgeReadFile call sites only pdf-tool.ts:487 passes maxBytes; the image/video/music/embedded-runner ones do not. Asymmetric, not a regression, and clampAndFinalize still caps post-read.
  • The sandbox gate is a separate stat then readFile (two container round-trips, TOCTOU-able), whereas the host path fstats an already-open handle (@openclaw/fs-safe/dist/read-opened-file.js:3) and is race-free. The sandbox gate also fails open when parseSandboxStatSize cannot parse (returns 0, fs-bridge-stat-parse.ts:11-18). Best-effort by design; the post-read cap is the real backstop.
  • localReadCap mirrors fetchCap (:967-972) except when maxBytes === undefined, where remote falls back to maxBytesForKind("document") and local stays uncapped pre-read. Looks deliberate and is safe, but it means the pre-read refusal does not apply to callers that omit maxBytes.

✅ Attacked and refuted (recording these so they are not re-litigated)

  • Buffer aliasing from dropping new Uint8Array(request.buffer) - safe, and the wrap really was gratuitous. normalizePdfInput returns a Uint8Array untouched (clawpdf/dist/input.js:3-4), bytes.byteLength is the view length, and HEAPU8.set(bytes, ptr) honours byteOffset (engine.js:85-90). Nothing in clawpdf/dist reads input.buffer or writes into the input (grepped bytes[..]=, .set, .fill, copyWithin: zero hits). Proved end to end against real PDFium with a pooled Buffer at byteOffset: 632 and the surrounding pool bytes poisoned to 0x41/0x42: correct text out. Worth noting the brief's assumption was wrong in the other direction: non-zero byteOffset is real traffic here (read-response-with-limit.ts:118-122 returns Buffer.concat output, pooled for sub-4096-byte PDFs). It is simply not a bug. request.buffer is typed Buffer at its only construction site (document-extractors.runtime.ts:25) and at every caller above it.
  • bridge.stat cannot be undefined. Non-optional on SandboxFsBridge (fs-bridge.types.ts:41-45), returns SandboxFsStat | null, and the if (stat && ...) guard handles the null-for-missing-file case. The signature change is additive (maxBytes?), so all 5 other consumers compile and behave unchanged.
  • All the tests earn their place, and there are 5 of them, not 4. Verified in an isolated detached worktree at origin/boon with head test files over unfixed prod: the V8 test fails with ERR_STRING_TOO_LONG at the deleted pdf-tool.ts:471, the clamp test with expected 1073741824 to deeply equal 805306368, the sparse test on both its assertions independently (expected 671311778 to be less than 335544320 and the message regex), the zero-copy test on Object.is. The 5th (keeps optimized image reads above maxBytes) passes on baseline because it guards the PR's own new localReadCap from being over-tightened, proved by mutating Math.max(maxBytes, maxBytesForKind("document")) to plain maxBytes, which kills it. The .external assertion is not vacuous (readFile puts the full 640MB in .external, heapUsed grows 880 bytes). The 385MiB allocUnsafe fixture costs ~151MB marginal RSS, not 385MB, so the cheap-fixture comment is substantially right, though note the file runs under two vitest projects so it is allocated twice. Sparse truncate is really sparse here (blocks: 0, ext4). Nothing silently skipped on Linux or macOS.
  • Losing native inline for 32MB-384MB PDFs is not a capability regression. Those requests were already failing upstream on both providers' caps, so nothing that worked stops working. The PR flags this as an unverified assumption; the arithmetic supports it.
  • Aggregate memory across 10 PDFs is a standing issue, not a regression. Post-PR worst-case peak (10 x 768MB of buffers) is lower than pre-PR (which held buffer plus base64 for every file). The trial-container sizing consequence is already in the PR body's Follow-ups, so I am not re-raising it.
  • A provider size rejection does recover. runWithImageModelFallback has no retryability predicate (model-fallback.ts:1998-2020), any throw advances the chain, and the chain is native-first then non-native (pdf-tool.model-config.ts:332-334). Covered in the inline comment; the only residual is the native-only-chain case, which is pre-existing.
  • packages/plugin-sdk/dist drift from the LocalMediaAccessErrorCode change: gitignored (.gitignore:45). The too-large FsSafeError code genuinely exists (@openclaw/fs-safe/dist/errors.d.ts:1), so the new branch at web-media.ts:1069 is live, not dead.

Methodology

Traced the PDF bytes end to end (tool schema, load loop, runWithImageModelFallback candidate chain, both native providers, readLocalFileSafely down to readOpenedFileSafely's pre-read fstat, and the sandbox bridge's stat shell plan), plus the config surfaces and docs that describe the two new constants, and read clawpdf/pdfium source for the removed-copy claim. Codex ran the same diff independently at high reasoning effort and converged on the gate defect and the config-contract drift, and added the readFileOverride bypass; it could not execute vitest in its read-only sandbox, so the test verification here is mine, run in a separate worktree with the production files at origin/boon. Dedupe set was empty: the only pre-existing comment is claude[bot]'s credential-less workflow error, and cubic posted no findings.

Strengths

  • The refutation section is the most useful part of the PR. Measuring three chunking strategies and showing all three abort on the same page 13 is what turns "chunking did not work" into "chunking cannot work", and it saves the next person the same week.
  • Feeding maxBytes into a pre-read size check that already existed and was receiving nothing (read-opened-file.js:3) is the right shape: no second gate, no new abstraction.
  • Every test fails on unfixed code, which is rarer than it should be, and the 640MB sparse fixture asserting on .external growth before the message is a genuinely better test than asserting the wording alone.

— Generated with Claude Code

…raw bytes

The 32MB native-inline gate measured the wrong quantity three ways. It compared
raw byteLength against a cap on the base64-encoded request, so a 32MiB PDF was
already 42.7MiB encoded and 33% over the cited cap. It used every() per file
while the cap is per request, and all PDFs share one request body, so ten 12MiB
files passed the check and built a 48MiB string. And it was hoisted out of the
per-attempt callback, so one constant served both Anthropic (32MB request) and
Gemini (20MB inline).

Replace it with a per-provider cap on the summed encoded size, evaluated inside
the fallback callback where the provider is known. Over the cap the native
branch is skipped and the run falls through to extraction, unchanged.

Also: document the 768MB clamp on the three surfaces that still advertised an
unbounded value (schema help, tool docs), note that the native-only pages and
password errors are reachable only below the size cap, and read mock.contexts
rather than mock.instances in the no-large-encode assertion, since vitest
documents instances as receivers from new.
@ikhsanuddin

Copy link
Copy Markdown
Author

Ready for review.

Scope

Removes the 384MB hard ceiling on PDF ingest. The tool base64-encoded every loaded PDF in the load loop, but only the native-provider branch consumes that string, and V8 caps a string at 0x1fffffe8 chars — so any PDF over 384MB threw regardless of heap or container size. Deleting that eager encode is the fix; the rest is bounding what remains.

Linear: ENG-19240

Adversarial review findings addressed

An independent reviewer (not the author) ran the dual pass. Five findings, all CONFIRMED, four fixed in 82d72181.

# Sev Finding State
F1 P2 32MB native gate measured the wrong quantity, three ways fixed
F2 P2 768MB clamp contradicted three config surfaces partly fixed, thread open
F3 P3 test read mock.instances where it meant mock.contexts fixed
F4 P3 docs/tools/pdf.md native-mode limits incomplete fixed
F5 P3 web-media boundary check never runs on PRs not this PR — ENG-19310

F1 was the one that mattered, and it was wrong in the opposite direction to what the PR body originally guessed. The body flagged "one big file disables native for the small ones" as the risk. The real defect was that .every() was far too permissive: it compared raw byteLength against a cap on the encoded request (off by 4/3), and checked per file when all PDFs share a single request body. With DEFAULT_MAX_PDFS = 10, ten 12MiB files passed and built a 48MiB string — which violates this ticket's own AC2. It was also hoisted out of the per-attempt callback, so one constant served both Anthropic (32MB request) and Gemini (20MB inline).

Now a per-provider cap on the summed encoded size, evaluated inside the run callback where the provider is known. New test skips native inline when several PDFs each fit the cap but their one request does not is mutation-proved: reverting the helper to the old per-file check fails it.

F2 is deliberately only half done, and the open thread is the reason. The two documentation surfaces now state the 768MB clamp. .max(768) on the zod schema is the better fix and would make the infra follow-up self-enforcing, but pdfMaxBytesMb: 1024 is currently baked into the paid AMI behind an assert_field guard — adding .max() would turn that into a startup validation failure on every paid host before the infra change lands. That sequencing is a deploy decision, not a PR-scope one. Would appreciate a call on it.

Verification

Check Result
pnpm tsgo:prod, pnpm tsgo:test exit 0
oxlint --type-aware on changed prod files exit 0
oxfmt --check on all changed files clean
pdf-tool + web-media + document-extractor + local-media-access + sandbox-media-paths + image-tool 215 passed, 0 failed
CI on 82d72181 118 success, 22 skipped, 2 neutral, 0 failures

Five tests, not four as the PR body originally said. Four fail on unfixed origin/boon (verified in an isolated detached worktree, head test files over unfixed prod); the fifth, keeps optimized image reads above maxBytes, passes on baseline by design — it guards the new localReadCap from over-tightening, and was mutation-proved load-bearing.

Also corrected from the body: the pre-read refusal I added covers the local/sandbox path. Production dispatches attachments as presigned S3 URLs, so the real Boon Agent flow takes the HTTP branch, which is governed by the pre-existing fetchCap (streams and aborts at the cap) — tightened by the 768MB clamp, but not by the new gate.

Merging this does not deploy it

openclaw is upstream. Reaching a host needs a release cut plus the boon-infra change to pdfMaxBytesMb (baked at 1024 in packer/scripts/06-write-openclaw-json-template.sh). Until then the clamp means 1024 behaves as 768, which is safe but silent. Note the two tiers want different numbers: peak RSS runs ~2.1x file size, so a 1GB trial container tops out nearer 300-350MB, well under the 768MB engine ceiling. 768 is the paid-EC2 number.

Residual ceiling, and why chunking is not the answer

~768MB, and page-range chunking cannot lift it. PDFium's WASM heap is a compiled-in 2GiB constant and _FPDF_LoadMemDocument copies the whole file into it, so fileBytes + singlePageWorkingSet <= 2GiB binds and the page list is not a term in it. Three strategies were measured, all aborting on the same page 13. Lifting it needs FPDF_LoadCustomDocument with a read callback (clawpdf does not expose it) or out-of-tenant extraction.

@gandalfboon gandalfboon Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved. Verified end-to-end:

  • 139/139 tests green on this branch locally (all four new tests hit real behavior: 1024→768 clamp, 385MiB PDF processes without base64, per-provider aggregate cap on 3×12MiB catches what the per-file check missed, sandbox stat-gates oversized reads).
  • readLocalFileSafely confirmed to accept maxBytes and throw too-large (src/infra/fs-safe.ts + fs-safe.test.ts:163,458); the new too-large code in LocalMediaAccessError routes it cleanly.
  • Sandbox bridge.stat is a real interface method (src/agents/sandbox/fs-bridge.ts:198); the pre-readFile size probe keeps the sandbox path aligned with the host path, both refusing from stat before materializing bytes.
  • The NATIVE_INLINE_REQUEST_CAP_BYTES fix is the one that mattered: comparing raw bytes to an encoded-request cap, per-file when one request carries all PDFs, would ship a 48MiB base64 string under a 32MB Anthropic cap. Now: Math.ceil(rawBytes/3)*4 ≤ cap, summed across the call, provider-scoped, evaluated per fallback attempt so the base64 is never built when the branch is skipped.
  • Documented ceiling behavior is honest — the 768MB clamp is applied at load time and surfaced in both docs/tools/pdf.md and schema.help.ts. Deferring the schema .max(768) until paid AMIs bake ≤768 is the right sequencing call; forcing it now would fail startup on every host still at 1024.

Releasing this needs the openclaw release cut + the boon-infra pdfMaxBytesMb change (as noted in the PR body). Ship it.

@ikhsanuddin
ikhsanuddin merged commit 66a5356 into boon Sep 2, 2026
148 checks passed
@ikhsanuddin
ikhsanuddin deleted the eng-19240-pdf-chunking branch September 2, 2026 11:47
@orswn orswn mentioned this pull request Sep 2, 2026
orswn added a commit that referenced this pull request Sep 2, 2026
Version-bump-only release cutting the three commits merged to boon since
v2026.6.11-boon.32: #177 (ENG-19233), #178, and #179 (ENG-19305).

#179 is customer-blocking: a macro-enabled Office file the agent produced or
downloaded was dropped by the host media allowlist, so the chat showed
"Media failed." while the assistant text claimed the file was attached. The
estimating templates are macro-enabled, so their workbook output always took
the failing path. The fix is on boon but no fleet host can run it until a
tagged release exists.

Bumps the gateway plus @openclaw/slack, @openclaw/msteams, and
@openclaw/diagnostics-prometheus to 2026.6.11-boon.33 in lockstep across all 8
manifests, and adds the CHANGELOG entry. No code changes.

The security-fast failure is unrelated to this release: four HIGH fast-uri
advisories were published upstream about an hour before the run, and the same
audit passes on every earlier PR in this stack. No dependency changed here.
convyusboy added a commit that referenced this pull request Sep 3, 2026
…nflicts)

5 feature/fix commits (boon.32, boon.33): confirm-before-act on ambiguous
requests (#175), unclosed content-block detection at stream finalization
(ENG-19233, #177), >384MB PDF handling (#178), macro-enabled Office document
delivery (#179), cron failure-destination recipient validation (#181).

All conflicts were the established package.json/npm-shrinkwrap.json
version-string pattern (kept 2026.6.34-boon.1), plus a new one this round:
origin/boon still pins fast-uri at 3.1.6 across pnpm-workspace.yaml,
pnpm-lock.yaml, and four npm-shrinkwrap.json files (root, acpx, lobster).
This integration branch already carries a deliberate 4.1.2 override from the
original 2026.6.34 sync (documented in the PR description's "Dependency /
security pins" section: the bump was needed because upstream's 6.34-era code
targets fast-uri's 4.x API, not because it's numerically newer) -- the same
"boon hasn't caught up to a pin this branch already needed" situation as the
`tar` override in that same section. Kept 4.1.2 everywhere.

Verified: pnpm tsgo:core:test + tsgo:extensions:test both clean. Targeted
tests across every touched surface (pdf-tool, web-media, mime, cron
delivery-target-validation + cron.validation, anthropic-transport-stream,
concise-interaction-overlay, embedded-agent-helpers, amazon-bedrock stream
runtime, anthropic prompt-overlay, document-extract) -- 303 passing, 0
failures. One unrelated pre-existing failure noted and left alone:
src/gateway/mcp-http.test.ts's "withdraws a closing runtime before drain
without fencing its successor" fails deterministically in this sandboxed
environment with a raw ECONNRESET on a real loopback TCP socket -- neither
mcp-http.ts nor its test file were touched by this merge, so this is an
environment/network-sandboxing artifact, not a regression from this change.
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