Repository navigation
fix(pdf): reading a PDF larger than 384MB fails instead of returning an answer - #178
Conversation
…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.
|
Claude encountered an error —— View job I'll analyze this and get back to you. |
🔍 Adversarial review (Claude + Codex, independent of the author)Reviewed at 🟠 Posted inline
🟡 File-spanning, no single anchor lineP3 (CONFIRMED) · P3 (CONFIRMED, repo CI defect, not this PR's fault) · Lower notes, no action asked.
✅ Attacked and refuted (recording these so they are not re-litigated)
MethodologyTraced the PDF bytes end to end (tool schema, load loop, Strengths
— 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.
|
Ready for review. ScopeRemoves 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 Linear: ENG-19240 Adversarial review findings addressedAn independent reviewer (not the author) ran the dual pass. Five findings, all CONFIRMED, four fixed in
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 Now a per-provider cap on the summed encoded size, evaluated inside the F2 is deliberately only half done, and the open thread is the reason. The two documentation surfaces now state the 768MB clamp. Verification
Five tests, not four as the PR body originally said. Four fail on unfixed 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 Merging this does not deploy it
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 |
There was a problem hiding this comment.
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).
readLocalFileSafelyconfirmed to acceptmaxBytesand throwtoo-large(src/infra/fs-safe.ts+fs-safe.test.ts:163,458); the newtoo-largecode inLocalMediaAccessErrorroutes it cleanly.- Sandbox
bridge.statis a real interface method (src/agents/sandbox/fs-bridge.ts:198); the pre-readFilesize probe keeps the sandbox path aligned with the host path, both refusing from stat before materializing bytes. - The
NATIVE_INLINE_REQUEST_CAP_BYTESfix 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.mdandschema.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.
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.
…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.
Linear: ENG-19240
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 charactersinstead of an answer, whenever the PDF was larger than 384 MB. The failure was independent of heap size, container size, and the configuredpdfMaxBytesMb— 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
0x1fffffe8chars, 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:
media.buffer.toString("base64").loadedPdfsnow 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.pdfMaxPagesrather than by file size.maxBytesis clamped to a 768 MB engine ceiling. PDFium runs in a 2 GiB WASM heap andFPDF_LoadMemDocumentcopies 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.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).stat, before materialization. The byte cap is now threaded intoreadLocalFileSafely, which already had a pre-readFilesize 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 (
2147483648innode_modules/clawpdf/dist/vendor/pdfium.esm.js), and_FPDF_LoadMemDocumentmallocsbytes.byteLengthandHEAPU8.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: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):
FPDF_LoadCustomDocumentwith a read callback, so PDFium pages bytes in on demand instead of holding a full copy. clawpdf does not currently expose that 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/booncodeVerified by stashing only the production files and re-running.
processes a PDF past the V8 base64 ceiling without encoding itsrc/agents/tools/pdf-tool.test.tsError: Cannot create a string longer than 0x1fffffe8 characters— the ticket's exact errorclamps a configured pdfMaxBytesMb down to the engine ceilingsrc/agents/tools/pdf-tool.test.tsexpected 1073741824 to deeply equal 805306368refuses an oversized local file from its stat, before the bytes are materializedsrc/media/web-media.test.tsMedia exceeds 1MB limit (got 640.00MB)— wrong message, and it materialized 640 MB to get therehands the request buffer to clawpdf without copying itextensions/document-extract/document-extractor.test.tsHow they stay cheap while still proving the thing:
Buffer.allocUnsafe(385 * 1024 * 1024). 385 MiB is the smallest size whose base64 exceeds0x1fffffe8chars, andallocUnsafenever touches the pages, so the fixture costs almost nothing in RSS — but a regression still throws the real V8 error.Buffer.prototype.toStringspy confirms nothing base64-encodes a buffer larger than 64 MB anywhere in the run.process.memoryUsage().externalgrew 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 realloadWebMediaRawand real PDFium, only the LLM call stubbed. Passed on this branch; threw the ticket's error onorigin/boon. RSS 722.7 → 1579.9 MB, growth 857 MB = 2.14x file size.Checks
pnpm tsgo:prod(core + extensions)pnpm tsgo:test(core:test + extensions:test)oxfmt --checkon all 8 changed filesoxlint --type-awareon the 4 changed prod filespdf-tool.test.tsweb-media.test.tsdocument-extractor.test.tslocal-media-access+sandbox-media-paths+pdf-extract+document-extractors.runtime+plugin-sdk-runtime-api-guardrailsimage-tool.test.ts+media-tool-shared.test.ts(the othercreateSandboxBridgeReadFileconsumers)Root-cause check: is this the only unbounded PDF base64?
Yes, for ingest. Every
toString("base64")insrc/andextensions/was checked; the rest are images-only branches (gated ondetectImageMimeType), the already-graceful 5 MBinput-files.tspath with itsrejectOversizedBase64Payloadpre-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.
googleand fall through on error — the existing fallback machinery handles that.FPDF_LoadMemDocumentoutright).createSandboxBridgeReadFilefor 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
pdfMaxBytesMb. It is baked at 1024 inpacker/scripts/06-write-openclaw-json-template.sh(with anassert_fieldbake 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.src/infra/outbound/message-action-params.ts:528doesmedia.buffer.toString("base64")on an outbound message attachment, capped byresolveAttachmentMaxBytes. Boon configuresmediaMaxMb = 1024fleet-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 forgoogle). Oversized PDFs fall through to local extraction, which is bounded bymaxPagesrather than file size.Validation and memory
maxBytesis clamped to 768 MB, matching PDFium's 2 GiB WASM heap limit; a configured 1024 now behaves as 768.statbefore bytes are materialized, with an error naming the file and limit; the sandbox reader got the same gate.Bufferto PDFium instead of re-wrapping it, roughly halving peak RSS.Written for commit 82d7218. Summary will update on new commits.