ml: name the broken file when gemma4 fails to load (#901)
- Commit
52a2ce816c83f1d763773afdbc69679f2ae5f9a5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-06 05:01 UTC (1 month ago)
- Parents
54abff3
Native createGemma4 returned only 0 on failure, so every cause (missing, truncated, or corrupt weights, absent GPU feature, bad tokenizer) surfaced as one undifferentiated error. The create entry now stores its failure message in a process-wide slot, exposed as MlNative.lastGemma4Error() (consumed on read, so a stale message can never leak into a later load). Gemma4Handle reports it as loadError (plus an explicit note when libmodelrunner.so itself did not load). createGemma4Handle also refuses short files before opening any descriptor, via shortFiles() against a literal size table mirroring ModelUrls.GemmaMaml (kept in sync by hand because :library:ml must not depend on :library:downloadservice); a truncated file used to map fine and die pages-deep in the upload. No load-semantics change: same files required, head still optional, same fallback paths. Kotlin-only callers see a new nullable loadError; the JNI surface gains one function.
Diff
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 5edc0453f7..31e5cb1a75 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@@ -41,6 +41,23 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose internal var handle: Long = if (MlNative.isAvailable) create(directory) else 0L + /**+ * Why the last construction failed, for the error the user sees.+ *+ * The short-file report when a file is truncated, else native's own+ * message (already in logcat under `ModelRunner`), else null when the+ * handle came up. Read by the hosting app's load-error path (#901).+ */+ val loadError: String? = if (handle != 0L) {+ null+ } else if (MlNative.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()+ } else {+ "libmodelrunner.so did not load on this device"+ }+ /** * The token ids the KV cache currently holds, or null when it holds something unmatchable. *
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 97a33c9614..76dfca6c43 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@@ -163,6 +163,14 @@ internal fun createGemma4Handle(directory: File): Long { return 0L } }+ val short = shortFiles(directory)+ if (short.isNotEmpty()) {+ // Fail before native opens anything: a truncated file maps fine and dies+ // pages-deep in the upload, which used to surface as the same bare+ // "failed to load" as a missing GPU feature (#901).+ Log.status(Gemma4Handle.TAG, "short files in $directory: ${short.joinToString()}")+ return 0L+ } // Optional GPU head (third file). Absent on old downloads — native falls // back to the host head, so this stays warning-free by design. val head = File(directory, Gemma4Handle.HEAD)@@ -205,6 +213,36 @@ private class HeadLease(val fd: Int, val length: Long) : AutoCloseable { } } +/**+ * `name to "actual/expected bytes"` for every gemma4 file on disk that is+ * shorter than the mirror serves.+ *+ * Sizes come from the download manifest ([ModelUrls.GemmaMaml.FILES]) rather+ * than native's header because the check runs before any descriptor is+ * opened — and because a maml header describes the data section, not the file,+ * so it cannot catch a tail truncation on its own. [ModelUrls] lives in+ * `:library:downloadservice`, which `:library:ml` must not depend on (consumer+ * direction only), hence the literal table: keep it in sync with the manifest.+ *+ * Public so the hosting app can name the broken file in its load error (#901)+ * instead of surfacing one undifferentiated "failed to load".+ */+fun shortFiles(directory: File): List<String> =+ GEMMA4_EXPECTED_BYTES.mapNotNull { (name, expected) ->+ val file = File(directory, name)+ if (file.isFile && file.length() < expected) "$name ${file.length()}/$expected" else null+ }++/** Expected on-disk bytes per gemma4 file; see [shortFiles] for why it is literal. */+val GEMMA4_EXPECTED_BYTES: Map<String, Long> = mapOf(+ Gemma4Handle.TEXT to 1_101_593_392L,+ Gemma4Handle.EMBED to 1_566_576_256L,+ Gemma4Handle.HEAD to 403_703_360L,+ Gemma4VisionHandle.VISION to 97_815_200L,+ Gemma4AudioHandle.AUDIO to 173_999_072L,+ Gemma4Handle.TOKENIZER to 3_889_167L,+)+ private fun openHeadLease(head: File): HeadLease? { if (!head.isFile) return HeadLease(NO_FD, 0L) val fd = runCatching {
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 1d5912310e..7d5da82592 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -754,6 +754,18 @@ internal object MlNative { /** Release a [createGemma4] handle. */ external fun destroyGemma4(handle: Long) + /**+ * The last [createGemma4] failure message, or null when the last attempt+ * succeeded (or none ran yet). Consumes the stored message.+ *+ * Public so the hosting app can tell a missing or truncated file apart+ * from a device or Vulkan failure instead of surfacing one+ * undifferentiated "failed to load" (#901). The message is already in+ * logcat under `ModelRunner`; this only makes it reachable from the+ * load-error path.+ */+ external fun lastGemma4Error(): String?+ /** * Feed soft tokens - an encoder's output - into the KV cache. Returns how many, or -1. *
library/ml/src/main/rust/src/bridge_part11.rs
diff --git a/library/ml/src/main/rust/src/bridge_part11.rs b/library/ml/src/main/rust/src/bridge_part11.rsindex 3f805662d5..d98f81b02b 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -113,7 +113,9 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4<'l> // that returns without wrapping one leaks it for the life of the process - and there are // three here (the head is optional), so the usual single-`fd` shape is not enough. if text_fd < 0 || embed_fd < 0 {- log(&format!("gemma4 is unavailable: descriptors {text_fd} and {embed_fd}"));+ let message = format!("gemma4 is unavailable: descriptors {text_fd} and {embed_fd}");+ set_gemma4_error(Some(message.clone()));+ log(&message); return Ok(0); } // SAFETY: the caller detached both, so nothing else owns them, and `File` closes them on drop@@ -143,8 +145,12 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4<'l> _ => Err("a graph span that is not a positive offset and length".to_string()), }; Ok(match built {- Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,+ Ok(handle) => {+ set_gemma4_error(None);+ Box::into_raw(Box::new(handle)) as jlong+ } Err(e) => {+ set_gemma4_error(Some(e.clone())); log(&format!("gemma4 is unavailable: {e}")); 0 }@@ -153,6 +159,50 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4<'l> .resolve::<jni::errors::LogErrorAndDefault>() } +/// The last `createGemma4` failure, for Kotlin to tell a missing or truncated file apart from a+/// device or Vulkan failure (#901's undifferentiated "failed to load").+///+/// A process-wide slot rather than a return value because the JNI boundary returns only the+/// handle: 0 already means failure, and the string rides beside it. Written on every create —+/// cleared on success — and read-then-cleared by `lastGemma4Error`, so a stale message can never+/// leak into a later load. `Mutex`, not `OnceLock`, because it is rewritten per attempt.+fn gemma4_error_slot() -> &'static std::sync::Mutex<Option<String>> {+ static SLOT: std::sync::OnceLock<std::sync::Mutex<Option<String>>> = std::sync::OnceLock::new();+ SLOT.get_or_init(|| std::sync::Mutex::new(None))+}++fn set_gemma4_error(message: Option<String>) {+ if let Ok(mut slot) = gemma4_error_slot().lock() {+ *slot = message;+ }+}++/// The last `createGemma4` failure message, or null on success. Consumes the stored message.+///+/// # Safety+///+/// Called only by the JVM.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_lastGemma4Error<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+) -> jstring {+ env.with_env(|env| -> jni::errors::Result<jstring> {+ let message = gemma4_error_slot()+ .lock()+ .map(|mut slot| slot.take())+ .unwrap_or(None);+ Ok(match message {+ Some(text) => match env.new_string(text) {+ Ok(string) => string.into_raw(),+ Err(_) => std::ptr::null_mut(),+ },+ None => std::ptr::null_mut(),+ })+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}+ #[allow(clippy::too_many_arguments)] fn build_gemma4<'l>( env: &Env,