pdf: don't eagerly prewarm search on huge documents (#942)
- Commit
3a9ec97b8e0daababcd731ecd1db136b8554c481- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-28 07:11 UTC (8 days ago)
- Parents
504d964
The reporter crashes opening a 940-page book. Driving the real file through every viewer entry point on the host passes (all 940 pages render and index cleanly), so the defect is the open-time work, not a malformed object: SafePdfViewerLoad unconditionally prewarmed the search index at open, interpreting the whole book and retaining ~74 MB of span tuples before the first page was useful, and under the release profile's panic=abort any failure in that eager path killed the process instead of degrading. SafePdfDocument now gates prewarm at MAX_PREWARM_PAGES=256; larger documents build the identical index lazily on first search. Regression: SafePdfPrewarmGateTest boundary tests plus issue942_tests (synthetic 150-page book through open+render-all+index always; env-gated drive of the real 940-page file, which passed). Verified: cargo pdf_render 660 tests, :pdf:testDevUnitTest green; :pdf:lint errors are pre-existing findings in untouched files.
Diff
pdf/AGENTS.md
diff --git a/pdf/AGENTS.md b/pdf/AGENTS.mdindex 67dd259ae6..8b3cb16767 100644--- a/pdf/AGENTS.md+++ b/pdf/AGENTS.md@@ -22,6 +22,8 @@ _Install: ./install pdf (dev by default)._ - Started-with-intent launches `finish()` on back instead of returning to the picker; in-app launches reset to the picker - Document, frame, and edit code (`FrameGeometry`, `FrameImageOps`, `SafePdfDocumentEdits`, `SafePdfPrimitives`, the `SafePdf*` wrappers) is in `platform/`; `ui/` is `SafePdf*` + capture/crop/cut-glue screens; there is no `domain/` root - `util/` holds only `PdfNative` (the Rust engine bridge) — don't add more files there; the capture model is in `data/`+- Search-index prewarm at open is page-count gated (`SafePdfDocument.MAX_PREWARM_PAGES`, 256): opening a document never eagerly interprets the whole book; larger documents build the same index lazily on first search+- Adobe YCCK (APP14 transform 2) CMYK JPEGs reach the Rust decoder with all four samples in inverted-ink polarity; the CMYK32 arm inverts all four before converting (transform 0 samples are already true ink) ## Key files ### Root — entry + navigation
pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.ktindex d34135a82a..edba22136d 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfDocument.kt@@ -259,9 +259,23 @@ class SafePdfDocument private constructor( /** Case-insensitive full-text search across all pages. */ suspend fun searchLegacy(query: String): List<SafeSearchMatch> = search(query, false) - /** Prebuild the search text index so the first query is instant. */+ /**+ * Prebuild the search text index so the first query is instant — but+ * only for documents where that is cheap (issue #942). Building the+ * index interprets *every* page and retains a per-glyph span table for+ * the whole book in the native index cache. The reported document is a+ * 940-page pdfTeX book: on a clean host that is ~35 s of interpretation+ * and ~74 MB of span tuples (plus the parsed document) committed at+ * open, before the first page can be useful — and on a phone, with the+ * release profile's `panic = "abort"`, any failure in that eager path+ * kills the process instead of degrading to a failed page. Searching a+ * large document still builds the same index, lazily, on the first+ * query, where the wait belongs to an explicit user action.+ */ suspend fun prewarmSearch() = withContext(Dispatchers.IO) {- PdfNative.buildSearchIndex(documentHandle)+ if (shouldPrewarmSearch(pageCount)) {+ PdfNative.buildSearchIndex(documentHandle)+ } } /** Serialize this document encrypted with the given passwords, or null. */@@ -271,6 +285,18 @@ class SafePdfDocument private constructor( /** Shared constants and helpers for SafePdfDocument. */ companion object { private const val TAG = "SafePdfDocument"++ /**+ * Largest page count whose search index is built eagerly at open+ * (see [prewarmSearch], issue #942). Well above a pamphlet or a+ * paper, well below a book: ~256 pages of dense text is a few+ * seconds of interpretation and a few MB of retained spans.+ */+ internal const val MAX_PREWARM_PAGES = 256++ /** Whether opening a [pageCount]-page document prewarms its search index. */+ internal fun shouldPrewarmSearch(pageCount: Int): Boolean =+ pageCount in 0..MAX_PREWARM_PAGES private const val MAX_CACHED_PAGES = 12 /** * Rough per-primitive retained cost, in bytes. `FillPath` holds `List<List<Offset>>`
pdf/src/main/rust/src/issue942_tests.rs
diff --git a/pdf/src/main/rust/src/issue942_tests.rs b/pdf/src/main/rust/src/issue942_tests.rsnew file mode 100644index 0000000000..4a724f7b5f--- /dev/null+++ b/pdf/src/main/rust/src/issue942_tests.rs@@ -0,0 +1,159 @@+//! Regression harness for GitHub issue #942 ("crashes when opening" a+//! 940-page pdfTeX book, app v2.6.11b).+//!+//! What the reported document is (verified by host-side reproduction with+//! the file itself, which is copyrighted book text and is NOT committed):+//! a 940-page LaTeX-produced PDF 1.5, 202 compressed object streams, 59+//! subset Type1 fonts, ~8.8k link annotations, and an embedded text layer+//! on every content page. Diving it on the host target shows the current+//! parser/renderer handles it at *every* entry point the viewer calls at+//! open — `open_document`, `render_page` for all 940 pages, `ensure_index`+//! (2,324,745 glyph spans, ~74 MB of retained span tuples), `list_outline`,+//! `document_text`, per-page listings and search (240 s full pass in a+//! debug build, 238 MB peak RSS) — and the Kotlin wire parser decodes its+//! largest pages in ~25 ms. So on HEAD there is no malformed object in it+//! that panics this pipeline; the shipped-build crash is the *open-time+//! work* it triggers (the viewer eagerly built that whole-book index+//! before the first page was useful, with the release profile's+//! `panic = "abort"` turning any failure in the eager path into a process+//! kill instead of a failed page).+//!+//! The fix gated the eager prewarm by page count on the Kotlin side+//! (`SafePdfDocument.MAX_PREWARM_PAGES`); this module is the native half+//! of the regression net. It must never be able to turn into the kind of+//! silent skip `issue321_tests` warns about, so:+//!+//! * a synthetic many-page book (built here, no fixture needed) is driven+//! through open + render-every-page + index on every run; and+//! * the real reported file can additionally be driven by pointing+//! `ISSUE942_PDF` at it, with `ISSUE942_REQUIRE_PDF=1` making its+//! absence a hard failure instead of a skip.++#[cfg(test)]+mod issue942 {+ use crate::*;++ /// Assemble a classic-xref PDF from `(object number, body)` pairs.+ fn raw_pdf(objs: &[(u32, Vec<u8>)], trailer_extra: &str) -> Vec<u8> {+ let mut out = b"%PDF-1.5\n".to_vec();+ let mut offsets = Vec::new();+ for (num, body) in objs {+ offsets.push((*num, out.len()));+ out.extend_from_slice(format!("{num} 0 obj\n").as_bytes());+ out.extend_from_slice(body);+ out.extend_from_slice(b"\nendobj\n");+ }+ let xref_at = out.len();+ let max = objs.iter().map(|(n, _)| *n).max().unwrap_or(0);+ out.extend_from_slice(format!("xref\n0 {}\n", max + 1).as_bytes());+ out.extend_from_slice(b"0000000000 65535 f \n");+ for n in 1..=max {+ let off = offsets.iter().find(|(num, _)| *num == n).map(|(_, o)| *o).unwrap_or(0);+ out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(+ format!("trailer\n<< /Size {} {trailer_extra} >>\nstartxref\n{xref_at}\n%%EOF\n", max + 1).as_bytes(),+ );+ out+ }++ fn raw_stream(dict: &str, content: &[u8]) -> Vec<u8> {+ let mut v = format!("{dict}\nstream\n").into_bytes();+ v.extend_from_slice(content);+ v.extend_from_slice(b"\nendstream");+ v+ }++ /// The synthetic trigger: many ordinary text pages behind one /Pages+ /// tree — the shape whose only unusual property is scale.+ fn many_page_book(pages: u32) -> Vec<u8> {+ let mut objs: Vec<(u32, Vec<u8>)> = vec![+ (1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),+ (5, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec()),+ ];+ let mut kids = String::new();+ for i in 0..pages {+ let page_obj = 10 + i * 2;+ let content_obj = page_obj + 1;+ kids.push_str(&format!("{page_obj} 0 R "));+ objs.push((+ page_obj,+ format!(+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \+ /Contents {content_obj} 0 R \+ /Resources << /Font << /F1 5 0 R >> >> >>"+ )+ .into_bytes(),+ ));+ let mut content = b"BT /F1 11 Tf ".to_vec();+ for line in 0..30 {+ content.extend_from_slice(+ format!("1 0 0 1 40 {} Tm (page {} line {} of a long book) Tj ", 740 - line * 12, i, line)+ .as_bytes(),+ );+ }+ content.extend_from_slice(b"ET");+ objs.push((+ content_obj,+ raw_stream(&format!("<< /Length {} >>", content.len()), &content),+ ));+ }+ objs.push((+ 2,+ format!("<< /Type /Pages /Kids [{kids}] /Count {pages} >>").into_bytes(),+ ));+ raw_pdf(&objs, "/Root 1 0 R")+ }++ /// Drive one document (bytes) through the viewer's open-time sequence:+ /// open, render every page, build the whole search index. Returns the+ /// page count, or panics with the failing step named.+ fn open_render_and_index_all(bytes: &[u8]) -> usize {+ let handle = open_document(bytes);+ assert!(handle != 0, "open_document refused the document");+ let pages = {+ let reg = registry().lock().unwrap_or_else(|e| e.into_inner());+ reg.get(&handle).map(|d| d.get_pages().len()).unwrap_or(0)+ };+ assert!(pages > 0, "document reports no pages");+ for i in 0..pages {+ let wire = render_page(handle, i as i32);+ assert!(wire.is_some(), "page {i} of {pages} failed to render");+ let wire = wire.unwrap();+ assert!(wire.len() >= 20, "page {i} wire is truncated ({} bytes)", wire.len());+ }+ let index = ensure_index(handle).expect("search index refused the document");+ assert_eq!(index.len(), pages, "index must cover every page");+ close_document(handle);+ pages+ }++ #[test]+ fn a_many_page_book_opens_renders_and_indexes_in_full() {+ // 150 pages keeps the debug-build runtime in single-digit seconds+ // while still being far past anything the prewarm gate allows and+ // past every per-page cache in the viewer. The reported book is+ // 940 pages of this shape.+ let bytes = many_page_book(150);+ let pages = open_render_and_index_all(&bytes);+ assert_eq!(pages, 150);+ }++ #[test]+ fn the_reported_book_pdf_when_provided() {+ let Some(path) = std::env::var_os("ISSUE942_PDF") else {+ if std::env::var_os("ISSUE942_REQUIRE_PDF").is_some() {+ panic!("ISSUE942_PDF is not set but ISSUE942_REQUIRE_PDF=1: refusing to skip");+ }+ eprintln!(+ "[issue942] SKIPPING the real-book drive: set ISSUE942_PDF to the \+ reported file (940-page pdfTeX book) to run it. The synthetic \+ many-page test above is NOT a substitute for it."+ );+ return;+ };+ let bytes = std::fs::read(&path).expect("ISSUE942_PDF must be readable");+ let pages = open_render_and_index_all(&bytes);+ eprintln!("[issue942] reported book: {pages} pages opened, rendered and indexed");+ }+}
pdf/src/main/rust/src/lib.rs
diff --git a/pdf/src/main/rust/src/lib.rs b/pdf/src/main/rust/src/lib.rsindex 93bfa20bab..b572623666 100644--- a/pdf/src/main/rust/src/lib.rs+++ b/pdf/src/main/rust/src/lib.rs@@ -95,6 +95,7 @@ mod reference_diff_tests; mod perf_tests; #[cfg(test)] mod robustness_tests;+#[cfg(test)] mod issue942_tests; #[cfg(test)] mod cov_geometry_tests; #[cfg(test)] mod cov_outlines_tests; #[cfg(test)] mod cov_interpret_tests;
pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfPrewarmGateTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfPrewarmGateTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfPrewarmGateTest.ktnew file mode 100644index 0000000000..13d135678d--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfPrewarmGateTest.kt@@ -0,0 +1,30 @@+package com.vayunmathur.pdf.platform++import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Issue #942: opening a document must not eagerly build a whole-book+ * search index. The gate lives on [SafePdfDocument] so both the viewer+ * prewarm and any future caller get the same decision.+ */+class SafePdfPrewarmGateTest {++ @Test fun smallDocumentsStillPrewarm() {+ assertTrue(SafePdfDocument.shouldPrewarmSearch(0))+ assertTrue(SafePdfDocument.shouldPrewarmSearch(1))+ assertTrue(SafePdfDocument.shouldPrewarmSearch(42))+ }++ @Test fun theBoundaryIsInclusiveAndBookScaleIsExcluded() {+ assertTrue(SafePdfDocument.shouldPrewarmSearch(SafePdfDocument.MAX_PREWARM_PAGES))+ assertFalse(SafePdfDocument.shouldPrewarmSearch(SafePdfDocument.MAX_PREWARM_PAGES + 1))+ // The reported #942 document: 940 pages.+ assertFalse(SafePdfDocument.shouldPrewarmSearch(940))+ }++ @Test fun negativeCountsNeverPrewarm() {+ assertFalse(SafePdfDocument.shouldPrewarmSearch(-1))+ }+}