Modern Apps git

← Modern-Apps.git

pdf: serialise OCR passes natively (#944)

Commit
f29e0662214f42d96b35bade69cb662fb912b693
Author
Vayun Mathur <[email protected]>
When
2026-12-04 18:15 UTC (1 day ago)
Parents
dabe7d6
Issue #944 reports an MTE tag-mismatch SIGSEGV (SEGV_MTESERR)
inside MlNative.recognizeText on Dispatchers.Default after
repeatedly opening documents from WhatsApp in the pdf app.
Interpretation, stated plainly: "Memory tagging" is the Android
MTE crash, and the tombstone frames are in the PP-OCR native pass
(TextRecognizer.recognize via OcrEngine.recognizeDetailed), not
in the Rust PDF renderer; pdf reaches that code through
:library:ocr -> :library:ml.

A prior fix already in this tree deferred the Kotlin/native
destroy until in-flight passes finish. Auditing that guard found
the remaining hole: it was an RwLock, so recognise passes held
only the read side, yet every pass takes &mut OcrHandle in Rust
(resizing its shared pixel Vec and driving its two single-user
Vulkan nets). Two overlapping passes on one handle - possible
whenever a caller bypasses the Kotlin serialisation, which is
exactly the caller behaviour this guard was added to survive -
could therefore race on that Vec and those nets, corrupting the
heap in the way MTE reports inside recognizeText.

Fix: OCR_LIFETIME is now an exclusive Mutex in a new
host-compiled ocr_guard module. Recognise passes (Bitmap and
direct-buffer paths) and destroyOcr all take the same lock, so
passes on one handle never overlap and a handle is never freed
under a live pass, regardless of caller discipline. The guard
moved out of the Android-only bridge so cargo test covers it
on the host. library/ml AGENTS.md updated to match.

Regression tests: two new Rust tests in ocr_guard pin that a
held guard excludes a second holder and can be retaken after
drop. Full modelrunner cargo test passes (873 + 19 + 5), cargo
fmt and clippy are clean, and a fresh
./gradlew :pdf:lint :pdf:lintVitalRelease :pdf:testDevUnitTest
plus :library:ml:testDebugUnitTest and
:library:ocr:testDebugUnitTest is green.

Scope note: no overlap with the #942 work in wt-bug-942, which
touches only pdf/ui viewer files; this change touches only
library/ml native OCR lifetime code.

Diff

library/ml/AGENTS.md
diff --git a/library/ml/AGENTS.md b/library/ml/AGENTS.mdindex c576a1f8e3..96f884cdf9 100644--- a/library/ml/AGENTS.md+++ b/library/ml/AGENTS.md@@ -13,7 +13,7 @@ **Purpose:** All on-device inference — session wrappers for every runtime (ONNX, LiteRT, ExecuTorch, Vulkan compute) plus per-model handles: Whisper (speech), NLLB (translate), Gemma (assistant), Maia (chess), CLIP/faces/segmentation (photos/camera), Supertonic (TTS), OCR post. No vendor SDKs. **How to use:** Pick the runtime session (`OnnxSessions` / `LiteRtSessions` / `ExecutorchSessions` / `VulkanSessions`), then the model handle (`WhisperHandle`, `NllbHandle`, `GemmaTypes`, `MaiaHandle`, `ClipHandle`, `SelfieSegmenter`, …). Pre/post via `OnnxPreprocess`, `OcrPost`, `SegmentationMask`. **Entry points:** The `*Handle` for your model → its `*Sessions` runtime → `VulkanBridge`/`VulkanWire` if GPU.-**Gotchas:** Model files are large and versioned per consumer — never share weights across models without checking compatibility; GPU paths need device-specific testing. `TextRecognizer` is thread-safe without caller locks: passes are serialised internally and `close()` defers the native destroy until any in-flight pass returns; the Rust side enforces the same lifetime with the `OCR_LIFETIME` RwLock in `bridge.rs` (recognise holds the read side, `destroyOcr` the write side), so a handle is never freed under a live `recognizeText` call.+**Gotchas:** Model files are large and versioned per consumer — never share weights across models without checking compatibility; GPU paths need device-specific testing. `TextRecognizer` is thread-safe without caller locks: passes are serialised internally and `close()` defers the native destroy until any in-flight pass returns; the Rust side enforces the same lifetime with the exclusive `OCR_LIFETIME` lock in `ocr_guard.rs` (recognise passes and `destroyOcr` take the same lock), so passes on one handle never overlap and a handle is never freed under a live `recognizeText` call.  ## Key files - com/vayunmathur/library/ml/OnnxSessions.kt
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 9733384576..86cd0eee70 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -42,6 +42,7 @@ use crate::nets::{     nnfp, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler,     supertonic_text, supertonic_vocoder, tinyclip, u2netp, whisper, Plan, };+use crate::ocr_guard::ocr_use_guard; use crate::post::ctc::Dictionary; use crate::post::madlad as madlad_post; use crate::post::nms::{self, Face, Maps};@@ -297,26 +298,6 @@ struct OcrHandle {     pixels: Vec<i32>, } -/// Lifetime guard for every `OcrHandle` (issue #944).-///-/// The JNI contract used to rest entirely on the Kotlin caller serialising-/// `recognizeText`/`recognizeTextBuffer` against `destroyOcr`. That contract-/// was broken in practice (a non-suspend `close()` cannot take the coroutine-/// Mutex the recognise path holds), and `destroyOcr` then freed the handle-/// while a pass on `Dispatchers.Default` was still reading it — a heap-/// use-after-free, reported as an MTE tag-mismatch SIGSEGV inside-/// `recognizeText`. The guard makes the native side enforce the lifetime-/// itself: recognise passes hold the read side for their whole duration, and-/// destruction takes the write side, so a destroy can only ever run between-/// passes, never inside one. Poison-tolerant like the rest of this bridge: a-/// panicking pass must not wedge every later destroy.-pub(crate) static OCR_LIFETIME: std::sync::RwLock<()> = std::sync::RwLock::new(());--/// The read side of [`OCR_LIFETIME`], held for one whole recognise pass.-pub(crate) fn ocr_use_guard() -> std::sync::RwLockReadGuard<'static, ()> {-    OCR_LIFETIME.read().unwrap_or_else(|poisoned| poisoned.into_inner())-}- jni_fn! { /// `TextRecognizer`'s constructor: detection at a fixed square, recognition at a fixed /// width, and the character table. Returns 0 on failure, having logged why. ///
library/ml/src/main/rust/src/bridge_part1.rs
diff --git a/library/ml/src/main/rust/src/bridge_part1.rs b/library/ml/src/main/rust/src/bridge_part1.rsindex 3fdd4dead9..5a41db25c2 100644--- a/library/ml/src/main/rust/src/bridge_part1.rs+++ b/library/ml/src/main/rust/src/bridge_part1.rs@@ -115,12 +115,10 @@ unsafe Java_com_vayunmathur_library_ml_MlNative_destroyOcr; (_class: JClass<'l>,     if handle == 0 {         return;     }-    // The write side of `OCR_LIFETIME`: waits for any in-flight recognise pass-    // to finish before the handle is freed (issue #944). Each `Net`'s Drop-    // waits for the device to go idle.-    let _lifetime = OCR_LIFETIME-        .write()-        .unwrap_or_else(|poisoned| poisoned.into_inner());+    // The same exclusive `OCR_LIFETIME` lock the recognise passes hold:+    // waits for any in-flight pass to finish before the handle is freed+    // (issue #944). Each `Net`'s Drop waits for the device to go idle.+    let _lifetime = ocr_use_guard();     // SAFETY: the caller guarantees this came from `createPpocr` and has not been     // destroyed; the guard guarantees no pass is using it concurrently.     drop(unsafe { Box::from_raw(handle as *mut OcrHandle) });
library/ml/src/main/rust/src/lib.rs
diff --git a/library/ml/src/main/rust/src/lib.rs b/library/ml/src/main/rust/src/lib.rsindex f38d1cb4e0..9c291826f0 100644--- a/library/ml/src/main/rust/src/lib.rs+++ b/library/ml/src/main/rust/src/lib.rs@@ -51,6 +51,7 @@ pub mod logmel; pub mod logmel_extra; pub mod microfrontend; pub mod nets;+pub(crate) mod ocr_guard; pub mod post; pub mod preprocess; // `#[macro_use]` so `timing!` is in scope for the modules declared after this one, which is
library/ml/src/main/rust/src/ocr_guard.rs
diff --git a/library/ml/src/main/rust/src/ocr_guard.rs b/library/ml/src/main/rust/src/ocr_guard.rsnew file mode 100644index 0000000000..327bdd94c5--- /dev/null+++ b/library/ml/src/main/rust/src/ocr_guard.rs@@ -0,0 +1,58 @@+//! Lifetime and exclusion guard for every OCR handle (issue #944).+//!+//! The JNI contract used to rest entirely on the Kotlin caller serialising+//! `recognizeText`/`recognizeTextBuffer` against `destroyOcr`. That contract+//! was broken in practice (a non-suspend `close()` cannot take the coroutine+//! Mutex the recognise path holds), and `destroyOcr` then freed the handle+//! while a pass on `Dispatchers.Default` was still reading it — a heap+//! use-after-free, reported as an MTE tag-mismatch SIGSEGV inside+//! `recognizeText`. The guard makes the native side enforce the lifetime+//! itself, and it is a `Mutex`, not an `RwLock`: a recognise pass takes+//! `&mut OcrHandle` (its pixel `Vec` is resized in place and its two nets+//! are single-user), so two passes on one handle must never overlap either.+//! Passes and destruction all take the same exclusive lock, so a destroy can+//! only ever run between passes, never inside one, and passes are serialised+//! even if a caller bypasses the Kotlin serialisation. Poison-tolerant like+//! the rest of this bridge: a panicking pass must not wedge every later+//! destroy.+//!+//! Host-compiled (unlike the JNI bridge) so the exclusion contract is+//! covered by `cargo test` without a device.++/// The one lock every OCR recognise pass and every OCR destroy takes.+///+/// `allow(dead_code)`: only the Android-only JNI bridge uses this on+/// device builds; host builds compile it for its tests.+#[allow(dead_code)]+pub(crate) static OCR_LIFETIME: std::sync::Mutex<()> = std::sync::Mutex::new(());++/// [`OCR_LIFETIME`] held for one whole recognise pass, or for a destroy.+#[allow(dead_code)]+pub(crate) fn ocr_use_guard() -> std::sync::MutexGuard<'static, ()> {+    OCR_LIFETIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner())+}++#[cfg(test)]+mod tests {+    use super::*;++    /// Regression test for issue #944: the guard a recognise pass holds+    /// must exclude everything else. With the previous `RwLock` read guard+    /// two passes on one handle could overlap and both take+    /// `&mut OcrHandle`, racing on its pixel `Vec` and nets — the same+    /// class of heap corruption MTE reports inside `recognizeText`.+    #[test]+    fn ocr_guard_excludes_a_second_holder() {+        let _guard = ocr_use_guard();+        assert!(+            OCR_LIFETIME.try_lock().is_err(),+            "a held OCR guard must exclude passes and destroys alike"+        );+    }++    #[test]+    fn ocr_guard_can_be_retaken_once_dropped() {+        drop(ocr_use_guard());+        let _guard = ocr_use_guard();+    }+}