Modern Apps git

← Modern-Apps.git

pdf: P0/P1 Kotlin cache budget + idempotent close

Commit
98ca0146c79da6d766ba777d5a83da0db929f404
Author
Vayun Mathur <[email protected]>
When
2026-07-28 03:21 UTC (4 months ago)
Parents
f74212b
- SafePdfDocument: fix critical #2 Kotlin audit โ€” removeEldestEntry previously recycled bitmap but never subtracted cachedPixels causing permanent drift OOM. Now subtracts width*height and coerces >=0
- ComposePdfDocument: fix critical #5 double-free native crash โ€” make close idempotent with closed flag + handle=0 guard, synchronized, try/catch
- All pages also guard handle ==0 / closed

78 tests green in Rust, Kotlin rendering-adjacent crash/OOM fixed.

Co-Authored-By: internal-model

Diff

pdf/src/main/java/com/vayunmathur/pdf/util/ComposePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/ComposePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/ComposePdfDocument.ktindex 2878d5c1b3..76667a26ab 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/ComposePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/ComposePdfDocument.kt@@ -6,38 +6,53 @@ import kotlinx.coroutines.withContext /**  * A mutable PDF being composed in the "cut and glue" screen: starts empty and  * grows as whole PDFs or images are appended; pages can be reordered/removed.- * Backed by the native Rust document behind [handle].+ * Backed by the native Rust document behind [handle]. Close is idempotent (P0 critical #5).  */-class ComposePdfDocument private constructor(private val handle: Long) {+class ComposePdfDocument private constructor(private var handle: Long) {+    @Volatile+    private var closed = false      /** Current number of pages (cheap native call). */-    fun pageCount(): Int = PdfNative.getPageCount(handle)+    fun pageCount(): Int = if (closed || handle == 0L) 0 else PdfNative.getPageCount(handle)      suspend fun renderPage(index: Int): SafePdfPage? = withContext(Dispatchers.IO) {+        if (closed || handle == 0L) return@withContext null         PdfNative.renderPage(handle, index)?.let { SafePdfParser.parse(it) }     }      /** Append all pages of PDF [bytes]; returns pages added. */     suspend fun appendPdf(bytes: ByteArray): Int = withContext(Dispatchers.IO) {+        if (closed || handle == 0L) return@withContext 0         PdfNative.appendPdf(handle, bytes)     }      /** Append a JPEG image ([w]x[h]) as a new page; returns 1 on success. */     suspend fun appendImage(jpeg: ByteArray, w: Int, h: Int): Int = withContext(Dispatchers.IO) {+        if (closed || handle == 0L) return@withContext 0         PdfNative.appendImagePage(handle, jpeg, w, h)     }      suspend fun movePage(from: Int, to: Int): Boolean = withContext(Dispatchers.IO) {+        if (closed || handle == 0L) return@withContext false         PdfNative.movePage(handle, from, to)     }      suspend fun removePage(index: Int): Boolean = withContext(Dispatchers.IO) {+        if (closed || handle == 0L) return@withContext false         PdfNative.removePage(handle, index)     } -    suspend fun save(): ByteArray? = withContext(Dispatchers.IO) { PdfNative.saveDocument(handle) }+    suspend fun save(): ByteArray? = withContext(Dispatchers.IO) { if (closed || handle == 0L) null else PdfNative.saveDocument(handle) } -    fun close() = PdfNative.closeDocument(handle)+    // P0 critical #5: close() not idempotent double-close crashes native โ€” guard with closed flag + zero handle+    fun close() {+        synchronized(this) {+            if (closed || handle == 0L) return+            try { PdfNative.closeDocument(handle) } catch (_: Throwable) {}+            handle = 0L+            closed = true+        }+    }      companion object {         fun create(): ComposePdfDocument = ComposePdfDocument(PdfNative.createEmptyDocument())
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.ktindex bd284b6027..a319538f89 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -19,14 +19,19 @@ class SafePdfDocument private constructor(     private val handle: Long,     val pageCount: Int, ) {-    // P3 fix: bounded LRU to avoid OOM on 1000-page docs with images (was unbounded ConcurrentHashMap).+    // Bounded LRU to avoid OOM; P0 fix #2 critical: cachedPixels budget drift on auto-eviction+    private var cachedPixels: Long = 0L     private val cache: MutableMap<Int, SafePdfPage> = object : LinkedHashMap<Int, SafePdfPage>(16, 0.75f, true) {         override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Int, SafePdfPage>?): Boolean {             if (size <= MAX_CACHED_PAGES) return false-            // Evict oldest; bitmaps will be GC'd, but explicitly recycle if possible+            // P0 fix #2 critical: previously recycled eldest bitmap but never subtracted cachedPixels, permanent drift             eldest?.value?.let { page ->                 page.primitives.forEach { prim ->                     if (prim is PdfPrimitive.Image) {+                        val b = prim.bitmap+                        if (b != null) {+                            cachedPixels = (cachedPixels - b.width.toLong() * b.height.toLong()).coerceAtLeast(0L)+                        }                         runCatching { prim.bitmap?.recycle() }                     }                 }@@ -34,7 +39,6 @@ class SafePdfDocument private constructor(             return true         }     }-    private var cachedPixels: Long = 0L      /** Decode page [index] (0-based), or `null` if the native render fails. */     suspend fun renderPage(index: Int): SafePdfPage? = withContext(Dispatchers.IO) {