Modern Apps git

← Modern-Apps.git

library/ml: add Gemma4 backend seam and device tests (pass 3)

Commit
c156dabd287c23be22c3b06a6846a3d3e7386684
Author
Vayun Mathur <[email protected]>
When
2026-11-07 13:30 UTC (28 days ago)
Parents
245a0ff
Coverage (merged INSTRUCTION, unit + emulator androidTest):
46.0% -> 86.4% (7109/8224).

Testability seams (all behaviour-preserving, defaults are the
previous direct calls):
- Gemma4Backend: new internal interface naming the Gemma 4 JNI
  boundary; NativeGemma4Backend delegates to MlNative one-for-one
  and Gemma4Handle/Gemma4Prefix now call through it. This makes
  the whole prompt/cache/generation pipeline host-testable.
- TextRecognizer.parse: private companion -> internal companion.
- FaceDetector.unpack: private -> internal; FaceDetector.handle
  internal + detectNative/destroyNative replaceable calls.
- TextRecognizer/Gemma4VisionHandle/Gemma4AudioHandle: internal
  handle + replaceable native-call vars (recognizeText, vision
  size/encode/destroy, audio encode/destroy).
- NativeSegmenter: constructor gains readAsset/segmentNative/
  maskWidth/maskHeight/destroyNative params with the current
  behaviour as defaults.
- build.gradle.kts: androidResources.noCompress += maml,bin -
  the FD-based handles (Whisper/Maia/Clip/Nnfp, Supertonic) can
  only open uncompressed assets via openFd; this makes the
  module's own test APK honour that, as a consuming app must.

New tests:
- Gemma4FakeBackendTest: a toy Gemma4Backend (char tokenizer,
  scripted replies) driving Gemma4Handle end to end - greedy and
  sampled generation (topK, logits fallback, consumed fallback),
  cache-prefix reuse, context-full refusal, multimodal soft
  tokens, marker-safe user encoding, loadPrefix magic/positions/
  digest validation + cache growth, backend failure surface.
- Pass3HostTest: OCR/face unpacking, Supertonic Piece fd
  ownership, Gemma4 file-check gauntlet entry points, digest and
  prompt-ceiling arithmetic, tower/segmenter unavailable states.
- Pass3SeamTest: segmenter/detector/OCR/vision/audio lifecycles
  through the seams; shortFiles decisions; sparse full-size
  Gemma4 bundle reaching the hand-off.
- DeviceNativeTest (androidTest, emulator x86_64 with
  -PemulatorAbi=x86_64, garbage .maml assets): the JNI bridge
  actually loads; MusicGate really runs on CPU; every Vulkan
  handle refuses garbage/sparse-zero weights gracefully;
  translation bundles, Supertonic asset/directory bundles, and
  the native backend's documented handle-0 tolerance.

No real model weights, no real network anywhere. 13/13 device
tests pass; lint green; the two detekt errors in the module are
pre-existing (createGemma4Handle ReturnCount, Gemma4Prompt
complexity - neither touched by this change).
Verified: gslot ./gradlew :library:ml:createMergedCoverageReport
with the emulator .ec folded in (86.44% merged instructions).

(cherry picked from commit 61ac63b94c618ebb3e608d3f79a8428e5243eb1d)

Diff

library/ml/build.gradle.kts
diff --git a/library/ml/build.gradle.kts b/library/ml/build.gradle.ktsindex 5b0ce81a94..bd5c0b30ae 100644--- a/library/ml/build.gradle.kts+++ b/library/ml/build.gradle.kts@@ -2,6 +2,16 @@ plugins {     id("common-conventions-library") } +android {+    // The FD-based handles (Whisper/Maia/Clip/Nnfp, Supertonic) can only open+    // assets that AAPT stored uncompressed - their create() calls openFd.+    // Declaring it here makes the library's own (test) APK honour that, which+    // is also what a consuming app must do for these models to load at all.+    androidResources {+        noCompress += listOf("maml", "bin")+    }+}+ androidComponents {     onVariants { variant ->         variant.sources.jniLibs?.addStaticSourceDirectory(
library/ml/src/androidTest/assets/clip/tinyclip.maml
diff --git a/library/ml/src/androidTest/assets/clip/tinyclip.maml b/library/ml/src/androidTest/assets/clip/tinyclip.mamlnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/clip/tinyclip.maml@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/madlad400.maml
diff --git a/library/ml/src/androidTest/assets/madlad400.maml b/library/ml/src/androidTest/assets/madlad400.mamlnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/madlad400.maml@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/maia3-5m.maml
diff --git a/library/ml/src/androidTest/assets/maia3-5m.maml b/library/ml/src/androidTest/assets/maia3-5m.mamlnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/maia3-5m.maml@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/modnet.maml
diff --git a/library/ml/src/androidTest/assets/modnet.maml b/library/ml/src/androidTest/assets/modnet.mamlnew file mode 100644index 0000000000..fd4fdb19ee--- /dev/null+++ b/library/ml/src/androidTest/assets/modnet.maml@@ -0,0 +1 @@+not a real model\ No newline at end of file
library/ml/src/androidTest/assets/nnfp.maml
diff --git a/library/ml/src/androidTest/assets/nnfp.maml b/library/ml/src/androidTest/assets/nnfp.mamlnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/nnfp.maml@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/ppocr_det.maml
diff --git a/library/ml/src/androidTest/assets/ppocr_det.maml b/library/ml/src/androidTest/assets/ppocr_det.mamlnew file mode 100644index 0000000000..fd4fdb19ee--- /dev/null+++ b/library/ml/src/androidTest/assets/ppocr_det.maml@@ -0,0 +1 @@+not a real model\ No newline at end of file
library/ml/src/androidTest/assets/ppocr_keys.txt
diff --git a/library/ml/src/androidTest/assets/ppocr_keys.txt b/library/ml/src/androidTest/assets/ppocr_keys.txtnew file mode 100644index 0000000000..ed2c580a02--- /dev/null+++ b/library/ml/src/androidTest/assets/ppocr_keys.txt@@ -0,0 +1 @@+a b c\ No newline at end of file
library/ml/src/androidTest/assets/ppocr_rec.maml
diff --git a/library/ml/src/androidTest/assets/ppocr_rec.maml b/library/ml/src/androidTest/assets/ppocr_rec.mamlnew file mode 100644index 0000000000..fd4fdb19ee--- /dev/null+++ b/library/ml/src/androidTest/assets/ppocr_rec.maml@@ -0,0 +1 @@+not a real model\ No newline at end of file
library/ml/src/androidTest/assets/scrfd_500m.maml
diff --git a/library/ml/src/androidTest/assets/scrfd_500m.maml b/library/ml/src/androidTest/assets/scrfd_500m.mamlnew file mode 100644index 0000000000..fd4fdb19ee--- /dev/null+++ b/library/ml/src/androidTest/assets/scrfd_500m.maml@@ -0,0 +1 @@+not a real model\ No newline at end of file
library/ml/src/androidTest/assets/selfie_segmentation.maml
diff --git a/library/ml/src/androidTest/assets/selfie_segmentation.maml b/library/ml/src/androidTest/assets/selfie_segmentation.mamlnew file mode 100644index 0000000000..fd4fdb19ee--- /dev/null+++ b/library/ml/src/androidTest/assets/selfie_segmentation.maml@@ -0,0 +1 @@+not a real model\ No newline at end of file
library/ml/src/androidTest/assets/supertonic/style_F1.bin
diff --git a/library/ml/src/androidTest/assets/supertonic/style_F1.bin b/library/ml/src/androidTest/assets/supertonic/style_F1.binnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/supertonic/style_F1.bin@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/supertonic/supertonic_dp.maml
diff --git a/library/ml/src/androidTest/assets/supertonic/supertonic_dp.maml b/library/ml/src/androidTest/assets/supertonic/supertonic_dp.mamlnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/supertonic/supertonic_dp.maml@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/supertonic/supertonic_ttl.maml
diff --git a/library/ml/src/androidTest/assets/supertonic/supertonic_ttl.maml b/library/ml/src/androidTest/assets/supertonic/supertonic_ttl.mamlnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/supertonic/supertonic_ttl.maml@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/supertonic/supertonic_ve.maml
diff --git a/library/ml/src/androidTest/assets/supertonic/supertonic_ve.maml b/library/ml/src/androidTest/assets/supertonic/supertonic_ve.mamlnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/supertonic/supertonic_ve.maml@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/supertonic/supertonic_voc.maml
diff --git a/library/ml/src/androidTest/assets/supertonic/supertonic_voc.maml b/library/ml/src/androidTest/assets/supertonic/supertonic_voc.mamlnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/supertonic/supertonic_voc.maml@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/supertonic/unicode_indexer.bin
diff --git a/library/ml/src/androidTest/assets/supertonic/unicode_indexer.bin b/library/ml/src/androidTest/assets/supertonic/unicode_indexer.binnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/supertonic/unicode_indexer.bin@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/assets/u2netp.maml
diff --git a/library/ml/src/androidTest/assets/u2netp.maml b/library/ml/src/androidTest/assets/u2netp.mamlnew file mode 100644index 0000000000..fd4fdb19ee--- /dev/null+++ b/library/ml/src/androidTest/assets/u2netp.maml@@ -0,0 +1 @@+not a real model\ No newline at end of file
library/ml/src/androidTest/assets/w600k_mbf.maml
diff --git a/library/ml/src/androidTest/assets/w600k_mbf.maml b/library/ml/src/androidTest/assets/w600k_mbf.mamlnew file mode 100644index 0000000000..fd4fdb19ee--- /dev/null+++ b/library/ml/src/androidTest/assets/w600k_mbf.maml@@ -0,0 +1 @@+not a real model\ No newline at end of file
library/ml/src/androidTest/assets/whisper-base/whisper_base.maml
diff --git a/library/ml/src/androidTest/assets/whisper-base/whisper_base.maml b/library/ml/src/androidTest/assets/whisper-base/whisper_base.mamlnew file mode 100644index 0000000000..d58adb0f78--- /dev/null+++ b/library/ml/src/androidTest/assets/whisper-base/whisper_base.maml@@ -0,0 +1 @@+garbage\ No newline at end of file
library/ml/src/androidTest/java/com/vayunmathur/library/ml/DeviceNativeTest.kt
diff --git a/library/ml/src/androidTest/java/com/vayunmathur/library/ml/DeviceNativeTest.kt b/library/ml/src/androidTest/java/com/vayunmathur/library/ml/DeviceNativeTest.ktnew file mode 100644index 0000000000..a8577a5055--- /dev/null+++ b/library/ml/src/androidTest/java/com/vayunmathur/library/ml/DeviceNativeTest.kt@@ -0,0 +1,269 @@+package com.vayunmathur.library.ml++import android.graphics.Bitmap+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue++/**+ * Pass 3 (library/ml): the JNI bridge on a real (emulator) device, where+ * `libmodelrunner.so` actually loads and the android-only symbols exist.+ *+ * No real model weights are used: the `.maml` files in androidTest/assets+ * are garbage, so every Vulkan-backed create must refuse gracefully (handle+ * 0, feature off) — except [MusicGate], which is CPU-only with no weights+ * and genuinely runs.+ */+@RunWith(AndroidJUnit4::class)+class DeviceNativeTest {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    /**+     * The instrumentation (test APK) context: the garbage `.maml` assets live+     * in the test APK, not in the library's own empty app APK, so asset-based+     * handles must be built from here to reach their create paths at all.+     */+    private val testContext: android.content.Context+        get() = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().context++    @Test+    fun nativeLibraryLoadsOnDevice() {+        assertTrue(MlNative.isAvailable)+    }++    @Test+    fun musicGateActuallyRunsOnDevice() {+        val gate = MusicGate.inProcess()+        assertTrue(gate.isAvailable)+        // two seconds of silence: warm-up completes and hops report+        val scores = gate.push(ShortArray(16_000 * 2))+        assertNotNull(scores)+        assertTrue(scores!!.isNotEmpty())+        assertTrue(scores.all { it in 0f..1f })+        // count must fit the buffer+        assertNull(gate.push(ShortArray(4), count = 99))+        gate.reset()+        val afterReset = gate.push(ShortArray(16_000 * 2))+        assertNotNull(afterReset)+        gate.close()+        gate.close()+        assertEquals("Now Playing music gate (CPU)", gate.toString())+    }++    @Test+    fun gemmaHandleWithMissingAndShortFilesIsUnavailableOnDevice() {+        val empty = File(context.cacheDir, "gemma-device-empty").apply { mkdirs() }+        val handle = Gemma4Handle.inDirectory(empty)+        assertFalse(handle.isAvailable)+        // on device the native error read works (no UnsatisfiedLinkError):+        // loadError is the native/short-file message or null, never a throw+        handle.loadError+        assertEquals(0, handle.position)+        assertNull(handle.generate(listOf(Gemma4Handle.Turn(Gemma4Handle.Role.USER, "hi")), null))+        assertEquals("", handle.decode(intArrayOf(1)))+        handle.close()++        val short = File(context.cacheDir, "gemma-device-short").apply { mkdirs() }+        File(short, Gemma4Handle.TEXT).writeBytes(byteArrayOf(1))+        File(short, Gemma4Handle.EMBED).writeBytes(byteArrayOf(1))+        File(short, Gemma4Handle.TOKENIZER).writeBytes(byteArrayOf(1))+        val shortHandle = Gemma4Handle.inDirectory(short)+        assertFalse(shortHandle.isAvailable)+        val error = shortHandle.loadError+        assertTrue(error == null || error.isNotBlank())+        shortHandle.close()+    }++    @Test+    fun gemmaCreateWithFullSizeSparseFilesRefusesGracefullyOnDevice() {+        // Sparse files at the manifest sizes pass the Kotlin file checks and+        // reach the native create, which must refuse zero-filled weights+        // with a handle of 0 rather than crashing.+        val dir = File(context.cacheDir, "gemma-device-sparse").apply { mkdirs() }+        for (name in listOf(Gemma4Handle.TEXT, Gemma4Handle.EMBED, Gemma4Handle.TOKENIZER)) {+            val f = File(dir, name)+            java.io.RandomAccessFile(f, "rw").use {+                it.setLength(GEMMA4_EXPECTED_BYTES.getValue(name))+            }+        }+        val handle = Gemma4Handle.inDirectory(dir)+        assertFalse(handle.isAvailable)+        handle.close()+        dir.deleteRecursively()+    }++    @Test+    fun gemmaCreateWithHeadLeaseAlsoRefusesGracefullyOnDevice() {+        // As the sparse test, plus the vision HEAD span: the head lease is+        // opened and handed to native, which still refuses zero weights.+        val dir = File(context.cacheDir, "gemma-device-head").apply { mkdirs() }+        for (name in Gemma4Handle.FILES_WITH_HEAD) {+            val f = File(dir, name)+            java.io.RandomAccessFile(f, "rw").use {+                it.setLength(GEMMA4_EXPECTED_BYTES.getValue(name))+            }+        }+        val handle = Gemma4Handle.inDirectory(dir)+        assertFalse(handle.isAvailable)+        handle.close()+        dir.deleteRecursively()+    }++    @Test+    fun supertonicFromGarbageAssetsIsUnavailableOnDevice() {+        val synth = SupertonicSynthesizer.inAssets(testContext.assets, "supertonic")+        assertFalse(synth.isAvailable)+        synth.close()+    }++    @Test+    fun translationHandlesWithGarbageFilesAreUnavailableOnDevice() {+        val dir = File(context.cacheDir, "translate-device").apply { mkdirs() }+        File(dir, MadladHandle.GRAPH).writeBytes(byteArrayOf(1, 2, 3))+        File(dir, MadladHandle.TOKENIZER).writeBytes("not json".toByteArray())+        val madlad = MadladHandle.inDirectory(dir)+        assertFalse(madlad.isAvailable)+        madlad.close()++        File(dir, NllbHandle.GRAPH).writeBytes(byteArrayOf(1, 2, 3))+        File(dir, NllbHandle.TOKENIZER).writeBytes("not json".toByteArray())+        val nllb = NllbHandle.inDirectory(dir)+        assertFalse(nllb.isAvailable)+        nllb.close()+        dir.deleteRecursively()+    }++    @Test+    fun nativeBackendToleratesAZeroHandleOnDevice() {+        // Every bridge method documents handle 0 as safe; prove it for the+        // ones that do not need a model behind them.+        val backend = NativeGemma4Backend+        assertTrue(backend.isAvailable)+        assertEquals(-1, backend.position(0L)) // native no-handle answer+        backend.reset(0L)+        assertEquals(0, backend.decode(0L, intArrayOf(1, 2))?.length ?: 0)+        backend.destroy(0L)+        backend.loadPrefix(0L, 0, ByteArray(0))+    }++    @Test+    fun visionAndAudioTowersRefuseSparseZeroWeightsOnDevice() {+        val dir = File(context.cacheDir, "towers-device").apply { mkdirs() }+        val visionFile = File(dir, Gemma4VisionHandle.VISION)+        java.io.RandomAccessFile(visionFile, "rw").use {+            it.setLength(GEMMA4_EXPECTED_BYTES.getValue(Gemma4VisionHandle.VISION))+        }+        val vision = Gemma4VisionHandle.inDirectory(dir)+        assertFalse(vision.isAvailable)+        vision.close()++        val audioFile = File(dir, Gemma4AudioHandle.AUDIO)+        java.io.RandomAccessFile(audioFile, "rw").use {+            it.setLength(GEMMA4_EXPECTED_BYTES.getValue(Gemma4AudioHandle.AUDIO))+        }+        val audio = Gemma4AudioHandle.inDirectory(dir)+        assertFalse(audio.isAvailable)+        audio.close()+        dir.deleteRecursively()+    }++    @Test+    fun faceAndSegmenterCreatesRefuseGarbageWeightsOnDevice() {+        val bmp = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)++        val detector = FaceDetector(testContext)+        assertFalse(detector.isAvailable)+        assertTrue(detector.detect(bmp).isEmpty())+        detector.close()++        val embedder = FaceEmbedder(testContext)+        assertFalse(embedder.isAvailable)+        assertNull(embedder.embed(bmp))+        embedder.close()++        val selfie = SelfieSegmenter(testContext)+        assertFalse(selfie.isAvailable)+        assertNull(selfie.segment(bmp))+        selfie.close()++        val subject = SubjectSegmenter(testContext)+        assertFalse(subject.isAvailable)+        assertNull(subject.segment(bmp))+        subject.close()++        val modnet = ModnetSegmenter(testContext)+        assertFalse(modnet.isAvailable)+        assertNull(modnet.segment(bmp))+        modnet.close()+    }++    @Test+    fun textRecognizerRefusesGarbageAssetsOnDevice() {+        val recognizer = TextRecognizer(testContext)+        assertFalse(recognizer.isAvailable)+        val bmp = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)+        assertTrue(recognizer.recognize(bmp).isEmpty())+        recognizer.close()+        recognizer.close()+    }++    @Test+    fun supertonicWithAnEmptyDirectoryIsUnavailableOnDevice() {+        val dir = File(context.cacheDir, "supertonic-device-empty").apply { mkdirs() }+        val synth = SupertonicSynthesizer.inDirectory(dir)+        assertFalse(synth.isAvailable)+        assertEquals(0, synth.synthesize("hello", "en").size)+        synth.close()+    }++    @Test+    fun assetHandlesWithoutModelsAreUnavailableOnDevice() {+        val whisper = WhisperHandle.inAssets(+            testContext.assets,+            special = intArrayOf(1, 2, 3, 4, 5),+            languages = intArrayOf(10),+            suppress = intArrayOf(),+            suppressAtBegin = intArrayOf(),+        )+        assertFalse(whisper.isAvailable)+        whisper.close()++        val maia = MaiaHandle.inAssets(testContext.assets)+        assertFalse(maia.isAvailable)+        maia.close()++        val clip = ClipHandle.inAssets(testContext.assets)+        assertFalse(clip.isAvailable)+        clip.close()++        val nnfp = NnfpHandle.inAssets(testContext.assets)+        assertFalse(nnfp.isAvailable)+        nnfp.close()++        val dir = File(context.cacheDir, "handles-device-empty").apply { mkdirs() }+        val nllb = NllbHandle.inDirectory(dir)+        assertFalse(nllb.isAvailable)+        nllb.close()++        val madlad = MadladHandle.inDirectory(dir)+        assertFalse(madlad.isAvailable)+        madlad.close()++        val vision = Gemma4VisionHandle.inDirectory(dir)+        assertFalse(vision.isAvailable)+        vision.close()++        val audio = Gemma4AudioHandle.inDirectory(dir)+        assertFalse(audio.isAvailable)+        audio.close()+    }+}
library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.ktindex 5dd695d47c..cd39867684 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt@@ -68,7 +68,9 @@ data class DetectedFaceBox(  */ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable { -    @Volatile private var handle: Long = if (!MlNative.isAvailable) {+    // Internal (pass-3 test seam): tests drive [detect] with a fake handle+    // and [detectNative] instead of the JNI bridge, which has no host symbols.+    @Volatile internal var handle: Long = if (!MlNative.isAvailable) {         0L     } else {         try {@@ -82,6 +84,13 @@ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCl     /** Whether the detector came up. False means people clustering is off. */     val isAvailable: Boolean get() = handle != 0L +    /** Test seam (pass 3): the [MlNative.detectFaces] call, replaceable on the host. */+    internal var detectNative: (Long, IntArray, Int, Int) -> FloatArray? =+        { h, pixels, w, hh -> MlNative.detectFaces(h, pixels, w, hh) }++    /** Test seam (pass 3): the [MlNative.destroy] call, replaceable on the host. */+    internal var destroyNative: (Long) -> Unit = { MlNative.destroy(it) }+     /** Reused across photos, so an indexing pass does not allocate one array per image. */     private var pixels: IntArray? = null @@ -110,7 +119,7 @@ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCl                 pixels = buffer             }             readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)-            val flat = MlNative.detectFaces(live, buffer, readable.width, readable.height)+            val flat = detectNative(live, buffer, readable.width, readable.height)                 ?: return emptyList()             unpack(flat)         } finally {@@ -119,7 +128,7 @@ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCl     }      /** Fifteen floats per face; see `MlNative.detectFaces` for the order. */-    private fun unpack(flat: FloatArray): List<DetectedFaceBox> {+    internal fun unpack(flat: FloatArray): List<DetectedFaceBox> {         if (flat.size % FLOATS_PER_FACE != 0) {             Log.error(TAG, "${flat.size} floats is not a whole number of faces")             return emptyList()@@ -153,7 +162,7 @@ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCl         val toDestroy = handle         handle = 0L         pixels = null-        if (toDestroy != 0L) MlNative.destroy(toDestroy)+        if (toDestroy != 0L) destroyNative(toDestroy)     }      companion object {
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.ktindex 1074e07905..fbcd5e839e 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.kt@@ -42,7 +42,16 @@ import java.io.File  */ class Gemma4AudioHandle private constructor(private val file: File) : AutoCloseable { -    private var handle: Long = if (MlNative.isAvailable) create(file) else 0L+    // Internal (pass-3 test seam): tests drive [encode] with a fake handle+    // and a fake native call instead of the JNI bridge (no host symbols).+    internal var handle: Long = if (MlNative.isAvailable) create(file) else 0L++    /** Test seam (pass 3): the [MlNative.encodeAudioGemma4] call. */+    internal var encodeNative: (Long, FloatArray) -> FloatArray? =+        { h, samples -> MlNative.encodeAudioGemma4(h, samples) }++    /** Test seam (pass 3): the [MlNative.destroyGemma4Audio] call. */+    internal var destroyNative: (Long) -> Unit = { MlNative.destroyGemma4Audio(it) }      /** Whether the tower came up. False leaves the assistant without audio rather than crashing. */     val isAvailable: Boolean@@ -65,13 +74,13 @@ class Gemma4AudioHandle private constructor(private val file: File) : AutoClosea             Log.status(TAG, "${samples.size} samples is under the $MIN_SAMPLES the band needs")             return null         }-        return MlNative.encodeAudioGemma4(handle, samples)+        return encodeNative(handle, samples)     }      override fun close() {         val live = handle         handle = 0L-        if (live != 0L) MlNative.destroyGemma4Audio(live)+        if (live != 0L) destroyNative(live)     }      override fun toString(): String = "Gemma 4 audio tower at $file"
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Backend.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Backend.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Backend.ktnew file mode 100644index 0000000000..eaf11a0812--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Backend.kt@@ -0,0 +1,77 @@+package com.vayunmathur.library.ml++import java.io.File++/**+ * The native boundary [Gemma4Handle] talks to: every Gemma 4 JNI entry point+ * it uses, behind an interface so the prompt/cache/generation pipeline (which+ * is ordinary Kotlin) can be exercised on the host JVM with a fake.+ *+ * Production always uses [NativeGemma4Backend], which forwards to [MlNative]+ * one-for-one — this seam changes no behaviour, it only names the boundary+ * that was previously a direct `MlNative.` call at each site. Tests inject a+ * fake through [Gemma4Handle]'s internal constructor.+ */+internal interface Gemma4Backend {+    /** Whether the native library loaded at all (says nothing about Vulkan). */+    val isAvailable: Boolean++    /** Open the model in [directory]; 0 on any failure. */+    fun create(directory: File): Long++    /** Native's own message for the last failed [create], or null. */+    fun lastError(): String?++    fun encode(handle: Long, text: String, specials: Array<String>): IntArray?+    fun decode(handle: Long, tokens: IntArray): String?+    fun push(handle: Long, tokens: IntArray): Int+    fun pushSoft(handle: Long, embeddings: FloatArray): Int+    fun step(handle: Long, token: Int): Int+    fun logits(handle: Long, token: Int): FloatArray?+    fun topK(handle: Long, token: Int, k: Int): FloatArray?+    fun position(handle: Long): Int+    fun reset(handle: Long)+    fun seek(handle: Long, position: Int): Int+    fun capacity(handle: Long): Int+    fun grow(handle: Long, needed: Int): Int+    fun loadPrefix(handle: Long, positions: Int, cache: ByteArray): Int+    fun destroy(handle: Long)+    fun capabilities()+    fun imageProbe()+    fun benchmark(handle: Long)+}++/** The production backend: a straight delegation to [MlNative]. */+internal object NativeGemma4Backend : Gemma4Backend {+    override val isAvailable: Boolean get() = MlNative.isAvailable+    override fun create(directory: File): Long = createGemma4Handle(directory)+    override fun lastError(): String? = MlNative.lastGemma4Error()+    override fun encode(handle: Long, text: String, specials: Array<String>): IntArray? =+        MlNative.encodeGemma4(handle, text, specials)+    override fun decode(handle: Long, tokens: IntArray): String? =+        MlNative.decodeGemma4(handle, tokens)+    override fun push(handle: Long, tokens: IntArray): Int = MlNative.pushGemma4(handle, tokens)+    override fun pushSoft(handle: Long, embeddings: FloatArray): Int =+        MlNative.pushSoftGemma4(handle, embeddings)+    override fun step(handle: Long, token: Int): Int = MlNative.stepGemma4(handle, token)+    override fun logits(handle: Long, token: Int): FloatArray? = MlNative.logitsGemma4(handle, token)+    override fun topK(handle: Long, token: Int, k: Int): FloatArray? =+        MlNative.topKGemma4(handle, token, k)+    override fun position(handle: Long): Int = MlNative.positionGemma4(handle)+    override fun reset(handle: Long) = MlNative.resetGemma4(handle)+    override fun seek(handle: Long, position: Int): Int = MlNative.seekGemma4(handle, position)+    override fun capacity(handle: Long): Int = MlNative.capacityGemma4(handle)+    override fun grow(handle: Long, needed: Int): Int = MlNative.growGemma4(handle, needed)+    override fun loadPrefix(handle: Long, positions: Int, cache: ByteArray): Int =+        MlNative.loadPrefixGemma4(handle, positions, cache)+    override fun destroy(handle: Long) = MlNative.destroyGemma4(handle)+    override fun capabilities() {+        MlNative.capabilitiesGemma4()+    }+    override fun imageProbe() {+        MlNative.imageProbeGemma4()+    }+    override fun benchmark(handle: Long) {+        MlNative.benchmarkGemma4(handle)+    }+}
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.ktindex 31e5cb1a75..65578a7666 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt@@ -37,9 +37,12 @@ import java.text.Normalizer  * position, so two concurrent turns would interleave their tokens into the same conversation.  * The caller must hold a lock across a whole turn, not merely across a call.  */-class Gemma4Handle private constructor(internal val directory: File) : AutoCloseable {+class Gemma4Handle internal constructor(+    internal val directory: File,+    internal val backend: Gemma4Backend = NativeGemma4Backend,+) : AutoCloseable { -    internal var handle: Long = if (MlNative.isAvailable) create(directory) else 0L+    internal var handle: Long = if (backend.isAvailable) backend.create(directory) else 0L      /**      * Why the last construction failed, for the error the user sees.@@ -50,10 +53,10 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose      */     val loadError: String? = if (handle != 0L) {         null-    } else if (MlNative.isAvailable) {+    } else if (backend.isAvailable) {         // Native ran and refused: prefer its message, which names the header,         // graph id, or span that failed rather than just the file.-        MlNative.lastGemma4Error()+        backend.lastError()     } else {         "libmodelrunner.so did not load on this device"     }@@ -90,7 +93,7 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose      /** Positions in the KV cache, which is where the next token goes. */     val position: Int-        get() = if (handle == 0L) 0 else MlNative.positionGemma4(handle)+        get() = if (handle == 0L) 0 else backend.position(handle)      /** Positions left before [MAX_CONTEXT] is reached. */     val remaining: Int@@ -104,7 +107,7 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose      */     fun reset() {         cachedIds = null-        if (handle != 0L) MlNative.resetGemma4(handle)+        if (handle != 0L) backend.reset(handle)     }      /**@@ -116,7 +119,7 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose     fun encodeText(text: String): IntArray {         if (handle == 0L) return IntArray(0)         val normalised = Normalizer.normalize(text, Normalizer.Form.NFKC)-        return MlNative.encodeGemma4(handle, normalised, emptyArray()) ?: IntArray(0)+        return backend.encode(handle, normalised, emptyArray()) ?: IntArray(0)     }      /**@@ -126,12 +129,12 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose      */     internal fun encodePrompt(text: String): IntArray {         if (handle == 0L) return IntArray(0)-        return MlNative.encodeGemma4(handle, text, MARKERS) ?: IntArray(0)+        return backend.encode(handle, text, MARKERS) ?: IntArray(0)     }      /** Text for token ids, with byte pieces fused back into characters. */     fun decode(tokens: IntArray): String =-        if (handle == 0L) "" else MlNative.decodeGemma4(handle, tokens).orEmpty()+        if (handle == 0L) "" else backend.decode(handle, tokens).orEmpty()      /**      * Run one turn, calling [onToken] with the reply so far after each token.@@ -193,9 +196,9 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose         // Grow the cache if this turn has outgrown it. Conversations start at the smallest         // tier, so most never allocate more than 19 MB; the ones that keep going climb.         val wantedPositions = length + limit + PromptConstants.PROMPT_SLACK_POSITIONS-        var capacity = MlNative.capacityGemma4(handle)+        var capacity = backend.capacity(handle)         if (capacity in 1 until wantedPositions) {-            val grown = MlNative.growGemma4(handle, wantedPositions)+            val grown = backend.grow(handle, wantedPositions)             if (grown > capacity) {                 // `cachedIds` deliberately survives. Growing used to empty the cache, so this                 // cleared the record to match; it now copies the contents into the new arena and@@ -289,7 +292,7 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose             val ceiling = minOf(prior.size, flat.size - 1)             while (reused < ceiling && prior[reused] == flat[reused]) reused++         }-        if (reused > 0 && MlNative.seekGemma4(handle, reused) == reused) {+        if (reused > 0 && backend.seek(handle, reused) == reused) {             Log.status(TAG, "reused $reused of $length positions, feeding ${length - reused}")         } else {             reused = 0@@ -308,7 +311,7 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose         // Everything but the very last token only fills the cache; its logits would be discarded.         if (flat != null) {             val feed = flat.copyOfRange(reused, flat.size - 1)-            if (feed.isNotEmpty() && MlNative.pushGemma4(handle, feed) < 0) return false+            if (feed.isNotEmpty() && backend.push(handle, feed) < 0) return false             // What the cache holds now. The reply's own tokens are appended as they are             // generated, so the next turn matches against the whole exchange.             cachedIds = flat.copyOfRange(0, flat.size - 1)@@ -316,12 +319,12 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose         }         for ((index, part) in parts.withIndex()) {             val fed = when (part) {-                is Part.Image -> MlNative.pushSoftGemma4(handle, part.soft)-                is Part.Audio -> MlNative.pushSoftGemma4(handle, part.soft)+                is Part.Image -> backend.pushSoft(handle, part.soft)+                is Part.Audio -> backend.pushSoft(handle, part.soft)                 is Part.Tokens -> {                     val ids = if (index == parts.lastIndex) part.ids.dropLast(1).toIntArray()                     else part.ids-                    if (ids.isEmpty()) 0 else MlNative.pushGemma4(handle, ids)+                    if (ids.isEmpty()) 0 else backend.push(handle, ids)                 }                 is Part.Text -> -1             }@@ -360,23 +363,23 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose     /** One generation step: greedy native step, or a sampled draw from native candidates. */     private fun nextToken(next: Int, sampling: Sampling?, step: Int): Int? {         val token = when {-            sampling == null -> MlNative.stepGemma4(handle, next)+            sampling == null -> backend.step(handle, next)             sampling.topK in 1..GEMMA4_TOP_K_CANDIDATES -> {-                val before = MlNative.positionGemma4(handle)-                val candidates = MlNative.topKGemma4(handle, next, GEMMA4_TOP_K_CANDIDATES)+                val before = backend.position(handle)+                val candidates = backend.topK(handle, next, GEMMA4_TOP_K_CANDIDATES)                 when {                     candidates != null -> sampleGemma4Candidates(candidates, sampling, step)                     // Only when the failed call did not consume the token: feeding it again                     // after it reached the cache would put it there twice.-                    MlNative.positionGemma4(handle) == before -> {-                        val logits = MlNative.logitsGemma4(handle, next) ?: return null+                    backend.position(handle) == before -> {+                        val logits = backend.logits(handle, next) ?: return null                         sampleGemma4Logits(logits, sampling, step)                     }                     else -> return null                 }             }             else -> {-                val logits = MlNative.logitsGemma4(handle, next) ?: return null+                val logits = backend.logits(handle, next) ?: return null                 sampleGemma4Logits(logits, sampling, step)             }         }@@ -524,7 +527,7 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose     override fun close() {         val live = handle         handle = 0L-        if (live != 0L) MlNative.destroyGemma4(live)+        if (live != 0L) backend.destroy(live)     }      override fun toString(): String = "Gemma 4 E2B in $directory"@@ -812,9 +815,6 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose          */         fun inDirectory(directory: File): Gemma4Handle = Gemma4Handle(directory) -        // Native handle construction (create, fd close, cache budget) lives in Gemma4Prefix.kt.-        private fun create(directory: File): Long = createGemma4Handle(directory)-         /** The baked prefix cache, beside the weights. Optional. */         const val PREFIX_CACHE = "gemma4_prefix.kv" 
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.ktindex 76dfca6c43..aab28d190b 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt@@ -18,9 +18,9 @@ import java.io.File  */ internal fun Gemma4Handle.runBenchmark() {     if (handle != 0L) {-        MlNative.capabilitiesGemma4()-        MlNative.imageProbeGemma4()-        MlNative.benchmarkGemma4(handle)+        backend.capabilities()+        backend.imageProbe()+        backend.benchmark(handle)     } } @@ -110,8 +110,8 @@ private fun Gemma4Handle.ensurePrefixCapacity(positions: Int): Boolean {     // The cache starts at the smallest tier and this prefix is larger than it. Growing first     // is not optional: `loadPrefixGemma4` refuses a prefix bigger than the cache rather than     // truncating it, because half a prefix is keys for a prompt nobody sent.-    if (MlNative.capacityGemma4(handle) < positions) {-        val grown = MlNative.growGemma4(handle, positions + PREFIX_SLACK_POSITIONS)+    if (backend.capacity(handle) < positions) {+        val grown = backend.grow(handle, positions + PREFIX_SLACK_POSITIONS)         if (grown < positions) {             Log.status(                 Gemma4Handle.TAG,@@ -129,7 +129,7 @@ private fun Gemma4Handle.installPrefix(     positions: Int ): Boolean {     val payload = blob.copyOfRange(Gemma4Handle.HEADER, blob.size)-    val loaded = MlNative.loadPrefixGemma4(handle, positions, payload)+    val loaded = backend.loadPrefix(handle, positions, payload)     if (loaded != positions) return false     // The cache now holds exactly these tokens, so the next turn matches against them and     // feeds only what follows.
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.ktindex 8b1dc0498c..75a780a512 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.kt@@ -33,7 +33,20 @@ import java.io.File  */ class Gemma4VisionHandle private constructor(private val file: File) : AutoCloseable { -    private var handle: Long = if (MlNative.isAvailable) create(file) else 0L+    // Internal (pass-3 test seam): tests drive [encode] with a fake handle+    // and fake native calls instead of the JNI bridge (no host symbols).+    internal var handle: Long = if (MlNative.isAvailable) create(file) else 0L++    /** Test seam (pass 3): the [MlNative.gemma4VisionSize] call. */+    internal var sizeNative: (Int, Int, Int) -> IntArray? =+        { w, h, tokens -> MlNative.gemma4VisionSize(w, h, tokens) }++    /** Test seam (pass 3): the [MlNative.encodeImageGemma4] call. */+    internal var encodeNative: (Long, IntArray, Int, Int) -> FloatArray? =+        { h, pixels, w, hh -> MlNative.encodeImageGemma4(h, pixels, w, hh) }++    /** Test seam (pass 3): the [MlNative.destroyGemma4Vision] call. */+    internal var destroyNative: (Long) -> Unit = { MlNative.destroyGemma4Vision(it) }      /** Whether the tower came up. False leaves the assistant text-only rather than crashing. */     val isAvailable: Boolean@@ -51,7 +64,7 @@ class Gemma4VisionHandle private constructor(private val file: File) : AutoClose      */     fun encode(image: Bitmap, softTokens: Int = SOFT_TOKENS_DEFAULT): FloatArray? {         if (handle == 0L) return null-        val size = MlNative.gemma4VisionSize(image.width, image.height, softTokens)+        val size = sizeNative(image.width, image.height, softTokens)         if (size == null || size.size != 2) {             Log.status(TAG, "no vision grid for ${image.width}x${image.height} at $softTokens")             return null@@ -67,13 +80,13 @@ class Gemma4VisionHandle private constructor(private val file: File) : AutoClose         val pixels = IntArray(width * height)         scaled.getPixels(pixels, 0, width, 0, 0, width, height)         if (scaled !== image) scaled.recycle()-        return MlNative.encodeImageGemma4(handle, pixels, width, height)+        return encodeNative(handle, pixels, width, height)     }      override fun close() {         val live = handle         handle = 0L-        if (live != 0L) MlNative.destroyGemma4Vision(live)+        if (live != 0L) destroyNative(live)     }      override fun toString(): String = "Gemma 4 vision tower at $file"
library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.ktindex 2aeb276cc7..fd4466dd11 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt@@ -48,6 +48,16 @@ internal class NativeSegmenter(     assetName: String,     tag: String,     create: (ByteArray) -> Long,+    // Test seams (pass 3): the asset read and the three native calls, each+    // defaulting to exactly what production did before they were named.+    private val readAsset: (String) -> ByteArray = { name ->+        context.assets.open(name).use { it.readBytes() }+    },+    private val segmentNative: (Long, IntArray, Int, Int) -> FloatArray? =+        { h, pixels, w, hh -> MlNative.segment(h, pixels, w, hh) },+    private val maskWidthNative: (Long) -> Int = { MlNative.maskWidth(it) },+    private val maskHeightNative: (Long) -> Int = { MlNative.maskHeight(it) },+    private val destroyNative: (Long) -> Unit = { MlNative.destroy(it) }, ) : AutoCloseable {      /**@@ -62,7 +72,7 @@ internal class NativeSegmenter(         try {             // `.maml` is `noCompress` in both apps, so this is a straight copy out of the             // mapped APK rather than an inflate into a second buffer.-            create(context.assets.open(assetName).use { it.readBytes() })+            create(readAsset(assetName))         } catch (expected: Exception) {             Log.error(tag, "cannot load $assetName", expected)             0L@@ -98,9 +108,9 @@ internal class NativeSegmenter(                 pixels = buffer             }             readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)-            val values = MlNative.segment(handle, buffer, readable.width, readable.height)+            val values = segmentNative(handle, buffer, readable.width, readable.height)                 ?: return null-            SegmentationMask(MlNative.maskWidth(handle), MlNative.maskHeight(handle), values)+            SegmentationMask(maskWidthNative(handle), maskHeightNative(handle), values)         } finally {             if (readable !== bitmap) readable.recycle()         }@@ -117,6 +127,6 @@ internal class NativeSegmenter(         val toDestroy = handle         handle = 0L         pixels = null-        if (toDestroy != 0L) MlNative.destroy(toDestroy)+        if (toDestroy != 0L) destroyNative(toDestroy)     } }
library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.ktindex 538c1c74ac..096d7c2e5e 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt@@ -61,9 +61,18 @@ class TextRecognizer(     recognitionAsset: String = RECOGNITION_ASSET,     dictionaryAsset: String = DICTIONARY_ASSET, ) : AutoCloseable {-    private var handle: Long = 0L+    // Internal (pass-3 test seam): tests drive [recognize] with a fake handle+    // and [ocrNative] instead of the JNI bridge, which has no host symbols.+    internal var handle: Long = 0L     private var pixels: IntArray? = null +    /** Test seam (pass 3): the [MlNative.recognizeText] call, replaceable on the host. */+    internal var ocrNative: (Long, IntArray, Int, Int) -> String? =+        { h, buf, w, hh -> MlNative.recognizeText(h, buf, w, hh) }++    /** Test seam (pass 3): the [MlNative.destroyOcr] call, replaceable on the host. */+    internal var destroyNative: (Long) -> Unit = { MlNative.destroyOcr(it) }+     init {         handle = if (!MlNative.isAvailable) {             0L@@ -104,7 +113,7 @@ class TextRecognizer(             val count = readable.width * readable.height             val buffer = pixels?.takeIf { it.size == count } ?: IntArray(count).also { pixels = it }             readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)-            val packed = MlNative.recognizeText(handle, buffer, readable.width, readable.height)+            val packed = ocrNative(handle, buffer, readable.width, readable.height)                 ?: return emptyList()             return parse(packed)         } finally {@@ -117,10 +126,10 @@ class TextRecognizer(         val live = handle         handle = 0L         pixels = null-        if (live != 0L) MlNative.destroyOcr(live)+        if (live != 0L) destroyNative(live)     } -    private companion object {+    internal companion object {         private const val TAG = "TextRecognizer"         const val DETECTION_ASSET = "ppocr_det.maml"         const val RECOGNITION_ASSET = "ppocr_rec.maml"
library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4FakeBackendTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4FakeBackendTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4FakeBackendTest.ktnew file mode 100644index 0000000000..3ec07199c8--- /dev/null+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4FakeBackendTest.kt@@ -0,0 +1,401 @@+package com.vayunmathur.library.ml++import java.io.File+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * A toy [Gemma4Backend]: a character tokenizer, a position counter, and a+ * scripted generation loop. It implements the boundary's *contract* (ids in,+ * positions tracked, stop tokens honoured) without any model, so the whole+ * Kotlin pipeline in [Gemma4Handle] — prompt rendering, cache reuse, feeding,+ * sampled/greedy stepping, prefix installation — runs on the host JVM.+ */+class FakeGemma4Backend(+    var capacityValue: Int = 100_000,+    var createResult: Long = 42L,+    var errorMessage: String? = null,+) : Gemma4Backend {+    override val isAvailable: Boolean = true++    var positionValue = 0+    val pushed = mutableListOf<IntArray>()+    val pushedSoft = mutableListOf<FloatArray>()+    val seeks = mutableListOf<Int>()+    var stepScript = ArrayDeque<Int>()+    var logitsResult: FloatArray? = null+    var topKResult: FloatArray? = null+    var topKConsumes = false+    var growResult: Int? = null+    var loadPrefixResult: Int? = null+    var destroyed = 0+    var resets = 0+    var benchmarkCalls = 0+    var createCalls = 0++    private val markerIds = HashMap<String, Int>()+    private val idText = HashMap<Int, String>()++    fun tokenFor(text: String): Int = 100 + text.single().code++    fun scriptReply(text: String) {+        stepScript = ArrayDeque(text.map { tokenFor(it.toString()) } + Gemma4Handle.STOP[1])+    }++    override fun create(directory: File): Long {+        createCalls+++        return createResult+    }++    override fun lastError(): String? = errorMessage++    override fun encode(handle: Long, text: String, specials: Array<String>): IntArray {+        val out = ArrayList<Int>()+        var i = 0+        while (i < text.length) {+            val marker = specials.firstOrNull { text.startsWith(it, i) }+            if (marker != null) {+                val id = markerIds.getOrPut(marker) { 3_000 + markerIds.size }+                idText[id] = marker+                out += id+                i += marker.length+            } else {+                out += tokenFor(text[i].toString())+                i+++            }+        }+        return out.toIntArray()+    }++    override fun decode(handle: Long, tokens: IntArray): String =+        tokens.joinToString("") { id ->+            idText[id] ?: if (id in 100..(100 + 0xFFFF)) (id - 100).toChar().toString() else "?"+        }++    override fun push(handle: Long, tokens: IntArray): Int {+        pushed += tokens.copyOf()+        positionValue += tokens.size+        return positionValue+    }++    override fun pushSoft(handle: Long, embeddings: FloatArray): Int {+        pushedSoft += embeddings.copyOf()+        positionValue += embeddings.size / Gemma4Handle.SOFT_TOKEN_WIDTH+        return positionValue+    }++    override fun step(handle: Long, token: Int): Int {+        positionValue+++        return if (stepScript.isEmpty()) Gemma4Handle.STOP[1] else stepScript.removeFirst()+    }++    private var logitsCalls = 0++    override fun logits(handle: Long, token: Int): FloatArray? {+        positionValue+++        // after the first sampled token, offer the stop token as argmax so+        // scripted replies terminate the way a real model's would+        if (++logitsCalls > 1) {+            return FloatArray(200) { if (it == Gemma4Handle.STOP[1]) 9f else 0f }+        }+        return logitsResult+    }++    private var topKCalls = 0++    override fun topK(handle: Long, token: Int, k: Int): FloatArray? {+        if (topKConsumes) positionValue+++        if (++topKCalls > 1 && topKResult != null) {+            return floatArrayOf(9f, Gemma4Handle.STOP[1].toFloat())+        }+        return topKResult+    }++    override fun position(handle: Long): Int = positionValue++    override fun reset(handle: Long) {+        resets+++        positionValue = 0+    }++    override fun seek(handle: Long, position: Int): Int {+        seeks += position+        positionValue = position+        return position+    }++    override fun capacity(handle: Long): Int = capacityValue++    override fun grow(handle: Long, needed: Int): Int {+        val grown = growResult ?: capacityValue+        capacityValue = grown+        return grown+    }++    override fun loadPrefix(handle: Long, positions: Int, cache: ByteArray): Int =+        loadPrefixResult ?: positions++    override fun destroy(handle: Long) {+        destroyed+++    }++    override fun capabilities() {}+    override fun imageProbe() {}+    override fun benchmark(handle: Long) {+        benchmarkCalls+++    }+}++/**+ * Pass 3 (library/ml): [Gemma4Handle]'s generation pipeline driven through+ * the [Gemma4Backend] seam with [FakeGemma4Backend] — no native library, no+ * model weights, every Kotlin decision asserted.+ */+@RunWith(RobolectricTestRunner::class)+class Gemma4FakeBackendTest {++    private fun tempDir(): File = java.nio.file.Files.createTempDirectory("gemma-fake").toFile()++    private fun handleWith(+        backend: FakeGemma4Backend,+        dir: File = tempDir(),+    ): Gemma4Handle = Gemma4Handle(dir, backend)++    private fun userTurn(text: String) = Gemma4Handle.Turn(Gemma4Handle.Role.USER, text)++    @Test+    fun `greedy generation feeds all but the last token and streams the reply`() {+        val backend = FakeGemma4Backend()+        backend.scriptReply("Hi")+        val handle = handleWith(backend)+        assertTrue(handle.isAvailable)+        assertNull(handle.loadError)+        val seen = mutableListOf<String>()+        val reply = handle.generate(listOf(userTurn("hello")), system = "Be nice") { text ->+            seen += text+            true+        }+        assertEquals("Hi", reply)+        assertEquals(listOf("H", "Hi"), seen)+        // the prompt was pushed once, without its final token+        assertEquals(1, backend.pushed.size)+        assertTrue(backend.pushed.first().isNotEmpty())+        assertTrue(handle.position > 0)+        handle.close()+        assertEquals(1, backend.destroyed)+        handle.close() // idempotent: no second destroy+        assertEquals(1, backend.destroyed)+    }++    @Test+    fun `onToken returning false stops generation early`() {+        val backend = FakeGemma4Backend()+        backend.scriptReply("Hello")+        val handle = handleWith(backend)+        val reply = handle.generate(listOf(userTurn("hi")), null) { false }+        assertEquals("H", reply)+    }++    @Test+    fun `stop token and step failure end the reply without throwing`() {+        val backend = FakeGemma4Backend()+        backend.stepScript = ArrayDeque(listOf(Gemma4Handle.STOP[0]))+        val handle = handleWith(backend)+        assertEquals("", handle.generate(listOf(userTurn("hi")), null))++        val failing = FakeGemma4Backend()+        failing.stepScript = ArrayDeque(listOf(-1))+        val handle2 = handleWith(failing)+        assertEquals("", handle2.generate(listOf(userTurn("hi")), null))+    }++    @Test+    fun `second turn reuses the shared cache prefix`() {+        val backend = FakeGemma4Backend()+        val handle = handleWith(backend)+        backend.scriptReply("ok")+        val conversation = mutableListOf(userTurn("hello"))+        handle.generate(conversation, system = "Be nice")+        assertTrue(backend.seeks.isEmpty())++        conversation += Gemma4Handle.Turn(Gemma4Handle.Role.MODEL, "ok")+        conversation += userTurn("again")+        backend.scriptReply("yo")+        val pushesBefore = backend.pushed.size+        val reply = handle.generate(conversation, system = "Be nice")+        assertEquals("yo", reply)+        // the shared prefix was sought, and only the differing tail was fed+        assertTrue(backend.seeks.isNotEmpty())+        assertTrue(backend.seeks.first() > 0)+        assertTrue(backend.pushed.size > pushesBefore)+    }++    @Test+    fun `sampled generation uses topK candidates then logits fallbacks`() {+        // topK path with a greedy (temperature 0) config picks the best candidate+        val backend = FakeGemma4Backend()+        backend.topKResult = floatArrayOf(9f, backend.tokenFor("A").toFloat(), 1f, 55f)+        val handle = handleWith(backend)+        val reply = handle.generate(+            listOf(userTurn("hi")), null,+            sampling = Sampling(topK = 64, topP = 1f, temperature = 0f),+        )+        assertEquals("A", reply)++        // topK unavailable but the token was not consumed: logits are sampled+        val backend2 = FakeGemma4Backend()+        backend2.topKResult = null+        backend2.logitsResult = FloatArray(300) { if (it == backend2.tokenFor("B")) 5f else 0f }+        val handle2 = handleWith(backend2)+        val reply2 = handle2.generate(+            listOf(userTurn("hi")), null,+            sampling = Sampling(topK = 64, topP = 1f, temperature = 0f),+        )+        assertEquals("B", reply2)++        // topK outside the candidate window goes straight to logits+        val backend3 = FakeGemma4Backend()+        backend3.logitsResult = FloatArray(300) { if (it == backend3.tokenFor("C")) 5f else 0f }+        val handle3 = handleWith(backend3)+        val reply3 = handle3.generate(+            listOf(userTurn("hi")), null,+            sampling = Sampling(topK = 0, topP = 1f, temperature = 0f),+        )+        assertEquals("C", reply3)++        // topK consumed the token and produced nothing: generation aborts+        val backend4 = FakeGemma4Backend()+        backend4.topKResult = null+        backend4.topKConsumes = true+        backend4.logitsResult = FloatArray(10) { 1f }+        val handle4 = handleWith(backend4)+        assertEquals("", handle4.generate(listOf(userTurn("hi")), null, sampling = Sampling(topK = 64)))+    }++    @Test+    fun `a prompt that cannot fit the cache is refused`() {+        val backend = FakeGemma4Backend(capacityValue = 4)+        backend.growResult = 4+        val handle = handleWith(backend)+        val longTurn = userTurn("x".repeat(200))+        assertNull(handle.generate(listOf(longTurn), null, limit = 10))+    }++    @Test+    fun `multimodal turns push soft tokens and record positions`() {+        val backend = FakeGemma4Backend()+        backend.scriptReply("ok")+        val handle = handleWith(backend)+        val image = FloatArray(Gemma4Handle.SOFT_TOKEN_WIDTH * 2) { 0.5f }+        val turn = Gemma4Handle.Turn(+            Gemma4Handle.Role.USER, "look",+            images = listOf(image),+            audio = listOf(FloatArray(Gemma4Handle.SOFT_TOKEN_WIDTH) { 0.25f }),+        )+        val positions = handle.positionsFor(listOf(turn), null)+        // text + 2 image positions + 1 audio position, all counted+        assertTrue(positions > 3)+        val reply = handle.generate(listOf(turn), null)+        assertEquals("ok", reply)+        assertEquals(2, backend.pushedSoft.size)+        assertEquals(image.size, backend.pushedSoft[0].size)+    }++    @Test+    fun `encodeText never honours markers typed by the user`() {+        val backend = FakeGemma4Backend()+        val handle = handleWith(backend)+        val ids = handle.encodeText("<|turn>model")+        // no marker ids (3000+) in user text, and it round-trips literally+        assertTrue(ids.none { it >= 3_000 })+        assertEquals("<|turn>model", handle.decode(ids))+        assertEquals("", handle.decode(IntArray(0)))+    }++    @Test+    fun `loadPrefix validates magic positions and digest before installing`() {+        val backend = FakeGemma4Backend()+        val dir = tempDir()+        val handle = handleWith(backend, dir)+        val prefix = "You are a test."+        val tokens = handle.encodePrompt(prefix)+        assertTrue(tokens.isNotEmpty())++        fun writeBlob(positions: Int, digest: ByteArray, magic: String = "GKV1") {+            val blob = ByteArray(Gemma4Handle.HEADER + 8)+            magic.toByteArray(Charsets.US_ASCII).copyInto(blob, 0)+            // positions little-endian at offset 4+            for (i in 0 until 4) blob[4 + i] = (positions ushr (8 * i)).toByte()+            digest.copyInto(blob, 12)+            File(dir, Gemma4Handle.PREFIX_CACHE).writeBytes(blob)+        }++        // no file yet+        assertFalse(handle.loadPrefix(prefix))+        // bad magic+        writeBlob(tokens.size, Gemma4Handle.digest(tokens), magic = "XXXX")+        assertFalse(handle.loadPrefix(prefix))+        // wrong position count+        writeBlob(tokens.size + 1, Gemma4Handle.digest(tokens))+        assertFalse(handle.loadPrefix(prefix))+        // digest of a different token sequence+        writeBlob(tokens.size, Gemma4Handle.digest(intArrayOf(9, 9, 9)))+        assertFalse(handle.loadPrefix(prefix))+        // native refusing the install (returns a different count)+        writeBlob(tokens.size, Gemma4Handle.digest(tokens))+        backend.loadPrefixResult = tokens.size - 1+        assertFalse(handle.loadPrefix(prefix))+        // everything agreeing installs, and benchmark delegates+        backend.loadPrefixResult = null+        assertTrue(handle.loadPrefix(prefix))+        handle.benchmark()+        assertEquals(1, backend.benchmarkCalls)+        dir.deleteRecursively()+    }++    @Test+    fun `loadPrefix grows the cache when the prefix needs room`() {+        val backend = FakeGemma4Backend(capacityValue = 1)+        backend.growResult = 100_000+        val dir = tempDir()+        val handle = handleWith(backend, dir)+        val prefix = "prefix"+        val tokens = handle.encodePrompt(prefix)+        val blob = ByteArray(Gemma4Handle.HEADER + 4)+        "GKV1".toByteArray(Charsets.US_ASCII).copyInto(blob, 0)+        for (i in 0 until 4) blob[4 + i] = (tokens.size ushr (8 * i)).toByte()+        Gemma4Handle.digest(tokens).copyInto(blob, 12)+        File(dir, Gemma4Handle.PREFIX_CACHE).writeBytes(blob)+        assertTrue(handle.loadPrefix(prefix))+        dir.deleteRecursively()+    }++    @Test+    fun `failed creation surfaces the backend error and stays inert`() {+        val backend = FakeGemma4Backend(createResult = 0L, errorMessage = "bad header")+        val handle = handleWith(backend)+        assertFalse(handle.isAvailable)+        assertEquals("bad header", handle.loadError)+        assertEquals(0, handle.position)+        assertEquals("", handle.decode(intArrayOf(1)))+        assertNull(handle.generate(listOf(userTurn("hi")), null))+        handle.reset() // must not call the backend with no handle+        assertEquals(0, backend.resets)+        handle.close()+        assertEquals(0, backend.destroyed)+    }++    @Test+    fun `native backend delegates and throws where the JNI bridge is absent`() {+        assertEquals(MlNative.isAvailable, NativeGemma4Backend.isAvailable)+        // the host library loads but exports no Gemma4 symbols (android-only JNI)+        assertFailsWith<UnsatisfiedLinkError> { NativeGemma4Backend.lastError() }+        assertFailsWith<UnsatisfiedLinkError> { NativeGemma4Backend.encode(1L, "x", emptyArray()) }+    }+}
library/ml/src/test/java/com/vayunmathur/library/ml/Pass3HostTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/Pass3HostTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/Pass3HostTest.ktnew file mode 100644index 0000000000..067a96a7e1--- /dev/null+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/Pass3HostTest.kt@@ -0,0 +1,257 @@+package com.vayunmathur.library.ml++import android.content.Context+import android.graphics.Bitmap+import android.os.ParcelFileDescriptor+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3 (library/ml): the pure-Kotlin surfaces behind the native handles —+ * OCR result unpacking, face-box unpacking, the music gate's inert state,+ * and Gemma4Handle's unavailable-state contract — on the host JVM, where+ * `libmodelrunner.so` exports no symbols.+ */+@RunWith(RobolectricTestRunner::class)+class Pass3HostTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun tempDir(prefix: String): File =+        java.nio.file.Files.createTempDirectory(prefix).toFile()++    // --- TextRecognizer.parse (internal seam) --------------------------------++    @Test+    fun `ocr parse unpacks lines with corners confidence and orientation`() {+        val packed = listOf(+            "Hello world\t0\t0\t100\t0\t100\t20\t0\t20\t0.95\t0",+            "Vertical\t5\t6\t7\t8\t9\t10\t11\t12\t0.5\t1",+        ).joinToString("\n")+        val lines = TextRecognizer.parse(packed)+        assertEquals(2, lines.size)+        val first = lines[0]+        assertEquals("Hello world", first.text)+        assertEquals(0.95f, first.confidence)+        assertFalse(first.vertical)+        assertEquals(0f, first.left)+        assertEquals(0f, first.top)+        assertEquals(100f, first.right)+        assertEquals(20f, first.bottom)+        assertTrue(lines[1].vertical)+        assertEquals(5f, lines[1].left)+        assertEquals(12f, lines[1].bottom)+    }++    @Test+    fun `ocr parse drops malformed rows and empty input`() {+        assertEquals(emptyList(), TextRecognizer.parse(""))+        val packed = listOf(+            "too\tfew\tfields",+            "bad numbers\tx\t0\t100\t0\t100\t20\t0\t20\t0.9\t0",+            "good\t1\t2\t3\t4\t5\t6\t7\t8\t0.25\t0",+            "",+        ).joinToString("\n")+        val lines = TextRecognizer.parse(packed)+        assertEquals(1, lines.size)+        assertEquals("good", lines.first().text)+        assertEquals(0.25f, lines.first().confidence)+    }++    // --- FaceDetector.unpack (internal seam) ---------------------------------++    @Test+    fun `face unpack maps fifteen floats per face`() {+        val detector = FaceDetector(context)+        assertFalse(detector.isAvailable)+        val flat = floatArrayOf(+            0.1f, 0.2f, 0.5f, 0.6f, 0.2f, 0.3f, 0.4f, 0.3f, 0.9f, 0.3f, 0.4f, 0.25f, 0.5f, 0.45f, 0.5f,+            0.6f, 0.1f, 0.9f, 0.4f, 0.7f, 0.2f, 0.85f, 0.2f, 0.8f, 0.75f, 0.25f, 0.7f, 0.35f, 0.9f, 0.35f,+        )+        val faces = detector.unpack(flat)+        assertEquals(2, faces.size)+        assertEquals(0.1f, faces[0].left)+        assertEquals(0.6f, faces[0].bottom)+        assertEquals(0.9f, faces[0].score)+        assertEquals(0.45f, faces[0].mouthRightX)+        assertEquals(0.85f, faces[1].rightEyeX)+        // a trailing partial face is refused wholesale, not part-unpacked+        assertEquals(emptyList(), detector.unpack(floatArrayOf(1f, 2f, 3f)))+        assertEquals(emptyList(), detector.unpack(FloatArray(0)))+        // detect on an unavailable detector is empty, and close is idempotent+        val bmp = Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888)+        assertEquals(emptyList(), detector.detect(bmp))+        detector.close()+        detector.close()+    }++    @Test+    fun `face embedder on an unavailable segmenter returns null`() {+        val embedder = FaceEmbedder(context)+        assertFalse(embedder.isAvailable)+        val bmp = Bitmap.createBitmap(112, 112, Bitmap.Config.ARGB_8888)+        assertNull(embedder.embed(bmp))+        embedder.close()+        assertEquals(512, FaceEmbedder.EMBEDDING_LENGTH)+    }++    // --- MusicGate ------------------------------------------------------------++    @Test+    fun `music gate constants describe the streaming contract`() {+        assertEquals(16_000, MusicGate.SAMPLE_RATE)+        assertEquals(160, MusicGate.HOP_SAMPLES)+        // warm-up arithmetic the streaming contract documents+        assertEquals(+            MusicGate.FRAME_SAMPLES + MusicGate.HOP_SAMPLES * (MusicGate.RECEPTIVE_FIELD_HOPS - 1),+            MusicGate.WARMUP_SAMPLES,+        )+        assertEquals(3_920, MusicGate.WARMUP_SAMPLES)+        // construction itself is a native call (CPU gate, no asset): on the+        // host the android-only JNI bridge throws, on a device it builds the+        // gate - the emulator suite covers the live path+        assertFailsWith<UnsatisfiedLinkError> { MusicGate.inProcess() }+    }++    // --- Gemma4Handle unavailable surface ------------------------------------++    @Test+    fun `gemma handle construction checks files before native on the host`() {+        // On the host the library loads but the android-only Gemma4 JNI+        // symbols are absent, so construction gets as far as the file checks+        // in createGemma4Handle and then dies reading the native error -+        // the emulator suite covers the graceful device path. Both the+        // missing-file and truncated-file rejections must fire first.+        val empty = tempDir("gemma-empty")+        assertFailsWith<UnsatisfiedLinkError> { Gemma4Handle.inDirectory(empty) }+        val short = tempDir("gemma-short")+        File(short, Gemma4Handle.TEXT).writeBytes(byteArrayOf(1))+        File(short, Gemma4Handle.EMBED).writeBytes(byteArrayOf(1))+        File(short, Gemma4Handle.TOKENIZER).writeBytes(byteArrayOf(1))+        assertFailsWith<UnsatisfiedLinkError> { Gemma4Handle.inDirectory(short) }+        assertEquals(+            listOf(Gemma4Handle.TEXT, Gemma4Handle.EMBED, Gemma4Handle.TOKENIZER),+            Gemma4Handle.FILES,+        )+        assertEquals(4, Gemma4Handle.FILES_WITH_HEAD.size)+        empty.deleteRecursively()+        short.deleteRecursively()+    }++    @Test+    fun `gemma prompt ceiling and digest arithmetic`() {+        assertEquals(+            Gemma4Handle.MAX_CONTEXT - Gemma4Handle.DEFAULT_REPLY,+            Gemma4Handle.promptCeiling(),+        )+        // a tiny reply still reserves the minimum, not the reply size+        assertEquals(Gemma4Handle.MAX_CONTEXT - 3, Gemma4Handle.promptCeiling(1))+        assertEquals(Gemma4Handle.MAX_CONTEXT - 100, Gemma4Handle.promptCeiling(100))++        val bytes = byteArrayOf(0x78, 0x56, 0x34, 0x12)+        assertEquals(0x12345678, Gemma4Handle.readInt(bytes, 0))+        val digest = Gemma4Handle.digest(intArrayOf(1, 2, 3))+        assertEquals(32, digest.size)+        assertTrue(digest.contentEquals(Gemma4Handle.digest(intArrayOf(1, 2, 3))))+        assertFalse(digest.contentEquals(Gemma4Handle.digest(intArrayOf(1, 2, 4))))+        assertFalse(digest.contentEquals(Gemma4Handle.digest(IntArray(0))))+    }++    @Test+    fun `gemma vision and audio handles degrade without the library`() {+        val dir = tempDir("gemma-media")+        val vision = Gemma4VisionHandle.inDirectory(dir)+        assertFalse(vision.isAvailable)+        val bmp = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)+        assertNull(vision.encode(bmp))+        vision.close()+        vision.close()++        val audio = Gemma4AudioHandle.inDirectory(dir)+        assertFalse(audio.isAvailable)+        assertNull(audio.encode(FloatArray(1600)))+        audio.close()+        dir.deleteRecursively()+    }++    // --- Supertonic pieces -----------------------------------------------------++    @Test+    fun `supertonic is unavailable and its descriptor piece honors ownership`() {+        val synth = SupertonicSynthesizer.inDirectory(tempDir("supertonic-empty"))+        assertFalse(synth.isAvailable)+        assertEquals(SupertonicSynthesizer.SAMPLE_RATE, synth.sampleRate)+        assertEquals(FloatArray(0).toList(), synth.synthesize("hello", "en").toList())+        assertEquals(FloatArray(0).toList(), synth.synthesize("  ", "en").toList())+        assertFalse(synth.voice("F2"))+        synth.close()+        synth.close()+        assertEquals("style_F2.bin", SupertonicSynthesizer.styleName("F2"))++        // Piece: release hands the fd to native (close becomes a no-op);+        // without release, close closes it exactly once. Raw fds come from a+        // FileInputStream reflectively - ParcelFileDescriptor.detachFd is+        // not faithfully shadowed in the sandbox.+        val file = File(tempDir("piece"), "x.bin").apply {+            parentFile?.mkdirs()+            writeBytes(byteArrayOf(1, 2, 3))+        }+        val keepAlive = mutableListOf<ParcelFileDescriptor>()+        fun rawFd(): Int {+            val pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)+            keepAlive += pfd+            return pfd.fd+        }+        val piece = SupertonicSynthesizer.Piece(rawFd(), at = 0L, length = 3L)+        assertEquals(3L, piece.length)+        piece.close()+        piece.close() // second close must not double-close a recycled fd number++        val fd2 = rawFd()+        val released = SupertonicSynthesizer.Piece(fd2, at = 5L, length = 7L)+        assertEquals(fd2, released.release())+        released.close() // no-op after release; the caller owns fd2 now+        // (prod's own closeFd swallows sandbox fd quirks via runCatching;+        // here the owning PFD from rawFd is closed by the sandbox at teardown)+    }++    @Test+    fun `segmenters are unavailable and inert on the host`() {+        val bmp = Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888)+        val selfie = SelfieSegmenter(context)+        assertFalse(selfie.isAvailable)+        assertNull(selfie.segment(bmp))+        selfie.close()+        val subject = SubjectSegmenter(context)+        assertFalse(subject.isAvailable)+        assertNull(subject.segment(bmp))+        subject.close()+        val modnet = ModnetSegmenter(context)+        assertFalse(modnet.isAvailable)+        assertNull(modnet.segment(bmp))+        modnet.close()+        val recognizer = TextRecognizer(context)+        assertFalse(recognizer.isAvailable)+        assertEquals(emptyList(), recognizer.recognize(bmp))+        recognizer.close()+        recognizer.close()+    }++    @Test+    fun `ml native library loads on the host but exports no gemma symbols`() {+        // The host .so exists (rustHostLibs), so the library loads; the JNI+        // bridge is cfg(target_os = "android"), so the Gemma4 externals are+        // absent - which is exactly why the pipeline needs the backend seam+        // and the emulator suite.+        assertTrue(MlNative.isAvailable)+        assertFailsWith<UnsatisfiedLinkError> { MlNative.lastGemma4Error() }+    }+}
library/ml/src/test/java/com/vayunmathur/library/ml/Pass3SeamTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/Pass3SeamTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/Pass3SeamTest.ktnew file mode 100644index 0000000000..52402bc1c4--- /dev/null+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/Pass3SeamTest.kt@@ -0,0 +1,211 @@+package com.vayunmathur.library.ml++import android.content.Context+import android.graphics.Bitmap+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import java.io.RandomAccessFile+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3 (library/ml): the segmenter/detector native-call seams and the+ * Gemma4 file-check gauntlet, driven on the host with fakes — the JNI+ * bridge itself has no host symbols, so everything past these seams is+ * asserted through their contracts.+ */+@RunWith(RobolectricTestRunner::class)+class Pass3SeamTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `segmenter runs its full lifecycle through the seams`() {+        var destroyedWith: Long? = null+        var createdWith: ByteArray? = null+        val segmenter = NativeSegmenter(+            context = context,+            assetName = "fake.maml",+            tag = "test",+            create = { bytes -> createdWith = bytes; 7L },+            readAsset = { byteArrayOf(4, 5, 6) },+            segmentNative = { _, pixels, w, h ->+                // a 2x2 mask over whatever pixels arrived+                assertEquals(w * h, pixels.size)+                floatArrayOf(0.1f, 0.2f, 0.3f, 0.4f)+            },+            maskWidthNative = { 2 },+            maskHeightNative = { 2 },+            destroyNative = { destroyedWith = it },+        )+        assertTrue(segmenter.isAvailable)+        assertEquals(byteArrayOf(4, 5, 6).toList(), createdWith?.toList())+        val bmp = Bitmap.createBitmap(4, 3, Bitmap.Config.ARGB_8888)+        val mask = segmenter.segment(bmp)+        assertNotNull(mask)+        assertEquals(2, mask.width)+        assertEquals(2, mask.height)+        assertEquals(listOf(0.1f, 0.2f, 0.3f, 0.4f), mask.mask.toList())+        // second call at a different size reallocates the pixel buffer+        val bigger = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)+        assertNotNull(segmenter.segment(bigger))+        segmenter.close()+        assertEquals(7L, destroyedWith)+        segmenter.close() // idempotent: no second destroy+        assertEquals(7L, destroyedWith)+        // after close the segmenter is inert again+        assertNull(segmenter.segment(bmp))+    }++    @Test+    fun `segmenter whose creator fails stays unavailable`() {+        val segmenter = NativeSegmenter(+            context = context,+            assetName = "fake.maml",+            tag = "test",+            create = { 0L },+            readAsset = { byteArrayOf(1) },+        )+        assertFalse(segmenter.isAvailable)+        val bmp = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888)+        assertNull(segmenter.segment(bmp))+        segmenter.close()++        val unreadable = NativeSegmenter(+            context = context,+            assetName = "fake.maml",+            tag = "test",+            create = { 9L },+            readAsset = { throw java.io.IOException("no asset") },+        )+        assertFalse(unreadable.isAvailable)+    }++    @Test+    fun `detector drives detect through its seam including hardware bitmaps`() {+        val detector = FaceDetector(context)+        var destroyed = false+        detector.destroyNative = { destroyed = true }+        detector.handle = 7L+        assertTrue(detector.isAvailable)+        detector.detectNative = { _, pixels, w, h ->+            assertEquals(w * h, pixels.size)+            floatArrayOf(+                0.1f, 0.2f, 0.5f, 0.6f,+                0.2f, 0.3f, 0.4f, 0.3f, 0.9f,+                0.3f, 0.4f, 0.25f, 0.5f, 0.45f, 0.5f,+            )+        }+        val bmp = Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888)+        val faces = detector.detect(bmp)+        assertEquals(1, faces.size)+        assertEquals(0.9f, faces[0].score)+        // native returning null is "no faces", not an error+        detector.detectNative = { _, _, _, _ -> null }+        assertEquals(emptyList(), detector.detect(bmp))+        detector.close()+        assertTrue(destroyed)+        assertFalse(detector.isAvailable)+    }++    @Test+    fun `recognizer runs recognition through its seam`() {+        val recognizer = TextRecognizer(context)+        var destroyed = false+        recognizer.destroyNative = { destroyed = true }+        recognizer.handle = 7L+        assertTrue(recognizer.isAvailable)+        recognizer.ocrNative = { _, pixels, w, h ->+            assertEquals(w * h, pixels.size)+            "Line one\t0\t0\t10\t0\t10\t5\t0\t5\t0.9\t0"+        }+        val bmp = Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888)+        val lines = recognizer.recognize(bmp)+        assertEquals(1, lines.size)+        assertEquals("Line one", lines.first().text)+        // a second, larger bitmap reallocates the shared pixel buffer+        val bigger = Bitmap.createBitmap(9, 9, Bitmap.Config.ARGB_8888)+        assertEquals(1, recognizer.recognize(bigger).size)+        // native returning null is "no text", not an error+        recognizer.ocrNative = { _, _, _, _ -> null }+        assertEquals(emptyList(), recognizer.recognize(bmp))+        recognizer.close()+        assertTrue(destroyed)+        assertFalse(recognizer.isAvailable)+    }++    @Test+    fun `vision and audio towers encode through their seams`() {+        val dir = java.nio.file.Files.createTempDirectory("towers").toFile()+        val vision = Gemma4VisionHandle.inDirectory(dir)+        var visionDestroyed = false+        vision.destroyNative = { visionDestroyed = true }+        vision.handle = 7L+        assertTrue(vision.isAvailable)+        vision.sizeNative = { w, h, _ -> intArrayOf(w * 2, h * 2) }+        vision.encodeNative = { _, pixels, w, h ->+            assertEquals(w * h, pixels.size)+            FloatArray(Gemma4VisionHandle.OUT_DIM * 3) { 0.5f }+        }+        val image = Bitmap.createBitmap(4, 3, Bitmap.Config.ARGB_8888)+        val soft = vision.encode(image)+        assertNotNull(soft)+        assertEquals(Gemma4VisionHandle.OUT_DIM * 3, soft.size)+        // a malformed grid answer is a refusal, not a crash+        vision.sizeNative = { _, _, _ -> intArrayOf(1) }+        assertNull(vision.encode(image))+        vision.sizeNative = { _, _, _ -> null }+        assertNull(vision.encode(image))+        vision.close()+        assertTrue(visionDestroyed)++        val audio = Gemma4AudioHandle.inDirectory(dir)+        var audioDestroyed = false+        audio.destroyNative = { audioDestroyed = true }+        audio.handle = 7L+        // too-short clips are refused before the native call+        assertNull(audio.encode(FloatArray(10)))+        audio.encodeNative = { _, samples -> FloatArray(samples.size) { 0.25f } }+        val encoded = audio.encode(FloatArray(Gemma4AudioHandle.MIN_SAMPLES))+        assertNotNull(encoded)+        assertEquals(Gemma4AudioHandle.MIN_SAMPLES, encoded.size)+        audio.close()+        assertTrue(audioDestroyed)+        dir.deleteRecursively()+    }++    @Test+    fun `gemma create gauntlet rejects short files and opens full ones`() {+        // shortFiles is the public half of the check (#901): every present+        // file under its manifest size is named, missing ones are not+        val dir = java.nio.file.Files.createTempDirectory("gemma-gauntlet").toFile()+        assertEquals(emptyList(), shortFiles(dir))+        File(dir, Gemma4Handle.TEXT).writeBytes(byteArrayOf(1, 2))+        File(dir, Gemma4Handle.TOKENIZER).writeBytes(byteArrayOf(1))+        val short = shortFiles(dir)+        assertEquals(2, short.size)+        assertTrue(short.any { it.startsWith(Gemma4Handle.TEXT) })+        assertTrue(short.any { it.startsWith(Gemma4Handle.TOKENIZER) })++        // with every required file present at full (sparse) size the gauntlet+        // reaches the descriptor hand-off; in the sandbox the fd detach is+        // not faithfully shadowed and on the host the JNI create has no+        // symbols - either way construction cannot produce a handle here,+        // and the emulator suite covers the graceful device refusal+        for (name in listOf(Gemma4Handle.TEXT, Gemma4Handle.EMBED, Gemma4Handle.TOKENIZER)) {+            RandomAccessFile(File(dir, name), "rw").use {+                it.setLength(GEMMA4_EXPECTED_BYTES.getValue(name))+            }+        }+        assertEquals(emptyList(), shortFiles(dir))+        assertFailsWith<Throwable> { Gemma4Handle.inDirectory(dir) }+        dir.deleteRecursively()+    }+}