π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
remove rust comments in ml code
laurenspriemdd412136216b
diff --git a/rust/crates/photos/src/ml/events.rs b/rust/crates/photos/src/ml/events.rsindex f9fae2fded..d41c523ce7 100644--- a/rust/crates/photos/src/ml/events.rs+++ b/rust/crates/photos/src/ml/events.rs@@ -1,17 +1,9 @@-//! Bounded buffer of notable ML runtime events for the app layer.-//!-//! The Rust runtime degrades gracefully (execution provider fallbacks, golden-//! self-test failures, WebGPU quarantine) without failing the calling-//! operation, so the app would otherwise never learn that a device is running-//! in a degraded or misbehaving configuration. Callers record events here and-//! the app drains them via `take_events` after ML operations, logging them at-//! the appropriate severity.+//! Reports graceful ML fallbacks and quarantines that would otherwise be+//! invisible to the app because the calling operation still succeeds.use std::sync::Mutex;-/// Oldest events are dropped first once the buffer is full; a drop is only-/// possible when the app has not drained for many sessions, in which case the-/// newest events are the actionable ones.+/// Prefer recent, actionable events when the app has not drained the buffer.const MAX_BUFFERED_EVENTS: usize = 64;#[derive(Clone, Debug, PartialEq, Eq)]@@ -39,7 +31,6 @@ pub struct MlRuntimeEvent {static EVENTS: Mutex<Vec<MlRuntimeEvent>> = Mutex::new(Vec::new());-/// Records an event for the app layer and mirrors it to the runtime log.pub(crate) fn record(severity: Severity, message: String) {crate::ml::runtime::rt_log(&format!("[{}] {message}", severity.as_str()));let mut events = EVENTS@@ -57,7 +48,6 @@ pub(crate) fn record(severity: Severity, message: String) {events.push(MlRuntimeEvent { severity, message });}-/// Returns all buffered events, leaving the buffer empty.pub fn take_events() -> Vec<MlRuntimeEvent> {let mut events = EVENTS.lock()diff --git a/rust/crates/photos/src/ml/golden.rs b/rust/crates/photos/src/ml/golden.rsindex ad1845e80e..5a7272b44d 100644--- a/rust/crates/photos/src/ml/golden.rs+++ b/rust/crates/photos/src/ml/golden.rs@@ -1,63 +1,35 @@-//! Golden-output self-tests for accelerated ONNX execution providers.-//!-//! GPU drivers and execution providers can produce numerically wrong output-//! while reporting success (for example, finite garbage from stale pipeline-//! state, or fp16 overflow). Wrong embeddings would be persisted server-side-//! and silently poison search and clustering, so before an accelerated-//! session (WebGPU on Android, CoreML on iOS) is trusted, it must reproduce a-//! committed golden output for a fixed input within a cosine-distance-//! threshold. The golden outputs are generated on the CPU execution provider-//! by `cargo run -p ente-photos --example ml_goldens -- generate`-//! and committed in `golden_data.rs`. A cheap unit test in `golden_tooling`-//! keeps the committed entries pinned (by file name and content hash) to the-//! production models in `infra/ml/test/ml_indexing/assets.json`, so a model-//! update cannot ship without regenerating the goldens.-//!-//! Inputs are deterministic seeded noise (token ids for CLIP text): the-//! models are pure tensor programs without data-dependent control flow, so-//! any fixed input exercises the same kernels as a real photo, and a shared-//! generation function makes device and generator inputs bit-identical.+//! Accelerated ONNX providers must reproduce CPU-generated golden outputs+//! because drivers can return plausible but numerically corrupt results while+//! reporting success. Deterministic inputs exercise the same kernels as real+//! inputs because these models have no data-dependent control flow.use crate::ml::golden_data::GOLDEN_ENTRIES;-// All thresholds are deliberately loose (a false rejection silently degrades-// the device to CPU) and unvalidated against real accelerated hardware;-// tighten them once field measurements exist. Corrupted output measures ~1.0-// on the cosine and coordinate metrics, and orders of magnitude higher on-// the confidence group (its expected norm is tiny).--/// Maximum cosine distance between an accelerated session's embedding output-/// and the CPU golden. Healthy fp16 divergence is around 1e-3.+// False rejections fall back to CPU, so these unvalidated thresholds are+// deliberately loose pending accelerated-hardware measurements. Healthy fp16+// cosine and coordinate divergence is around 1e-3; corrupt output is around+// 1.0 or higher.pub(crate) const COSINE_DISTANCE_THRESHOLD: f64 = 0.025;-/// Maximum relative L2 error for the detector's non-confidence outputs (box-/// coordinates, landmarks), whose absolute values are consumed directly.-/// Well-conditioned: healthy fp16 divergence is around 1e-3.pub(crate) const RELATIVE_L2_THRESHOLD: f64 = 0.1;-/// Maximum relative L2 error for the detector's confidence group. All its-/// values are tiny background sigmoid outputs (samples <= ~2e-3), whose-/// relative error is roughly the absolute drift of the underlying logit, so-/// healthy fp16 pipelines can plausibly measure O(0.1..1) here (a full-/// flush-to-zero is exactly 1.0 and functionally harmless), while defects-/// that inflate confidences measure >= ~45 against the tiny expected norm.-/// Deliberately loose within that gap, pending real-hardware measurements.+// Background confidence samples are <= ~2e-3, making healthy fp16 relative+// error O(0.1..1); full flush-to-zero is 1.0, while inflated confidences are+// >= ~45.pub(crate) const CONFIDENCE_RELATIVE_L2_THRESHOLD: f64 = 2.0;-/// Reference outputs are compared on a deterministic strided sample capped at-/// this many elements, so large detector outputs stay small in the committed-/// golden data. Embedding outputs fit entirely below the cap.const MAX_REFERENCE_SAMPLES: usize = 4096;-/// The fixed input for a golden self-test.pub enum GoldenInput {- /// Uniform [0, 1) noise from [`seeded_noise`], sized to `input_shape`.- SeededF32 { seed: u64 },+ SeededF32 {+ seed: u64,+ },/// Pre-tokenized CLIP text token ids.- I32 { data: &'static [i32] },+ I32 {+ data: &'static [i32],+ },}-/// How a model's output is compared against its golden output.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum GoldenMetric {/// For embedding outputs, which downstream code consumes via cosine@@ -80,8 +52,6 @@ impl GoldenMetric {}}- /// The loosest accepted distance; separation checks must measure beyond- /// this. [`compare_output`] applies the per-group thresholds.pub fn threshold(self) -> f64 {match self {Self::CosineDistance => COSINE_DISTANCE_THRESHOLD,@@ -90,31 +60,18 @@ impl GoldenMetric {}}-/// A committed golden record for one model file.pub struct GoldenEntry {- /// The model's canonical file name; entries are keyed by file name so- /// that a model update (which changes the file name) can never silently- /// reuse a stale golden: the lookup misses and the accelerated provider- /// is denied.+ /// A changed canonical name fails closed instead of reusing a stale golden.pub model_file: &'static str,- /// SHA-256 of the model file's contents, copied from the asset lock- /// (`infra/ml/test/ml_indexing/assets.json`) at generation time. Not- /// checked on device; a cheap unit test in `golden_tooling` compares it- /// against the asset lock so that a model content change β even under an- /// unchanged file name β fails CI until the goldens are regenerated.+ /// Checked against the asset lock in CI, not on device.pub model_sha256: &'static str,pub input: GoldenInput,pub input_shape: &'static [i64],pub metric: GoldenMetric,- /// Length of the model's full first output, used to derive the sample- /// stride and to reject outputs of unexpected shape.pub output_len: usize,- /// Strided sample of the CPU-generated first output.pub expected_sample: &'static [f32],}-/// Finds the golden entry for a model path. `None` means the model must not-/// run on an accelerated execution provider.pub fn lookup(model_path: &str) -> Option<&'static GoldenEntry> {let file_name = std::path::Path::new(model_path).file_name()?.to_str()?;GOLDEN_ENTRIES@@ -122,13 +79,9 @@ pub fn lookup(model_path: &str) -> Option<&'static GoldenEntry> {.find(|entry| matches_model_file(file_name, entry.model_file))}-/// The app stores downloaded models under URL-derived sanitized names (see-/// `RemoteAssetsService._urlToFileName` in the photos app): the protocol is-/// stripped and every character outside `[A-Za-z0-9_]` β including dots β-/// becomes `_`, e.g. `models_ente_com_yolov5s_face_640_640_static_b1_onnx`.-/// An entry therefore matches when the sanitized on-disk name equals the-/// sanitized canonical name, or ends with it at an `_` boundary (the URL host-/// prefix). Exact canonical names (tests, tooling) also match.+/// Downloaded model names include a sanitized URL prefix, so canonical names+/// match at an underscore boundary as well as exactly. This mirrors+/// `RemoteAssetsService._urlToFileName` in the photos app.fn matches_model_file(file_name: &str, model_file: &str) -> bool {if file_name == model_file {return true;@@ -154,15 +107,12 @@ fn sanitize_file_name(value: &str) -> String {.collect()}-/// A golden input materialized for one inference run. Built identically by-/// the on-device self-test and the golden generator.pub enum PreparedGoldenInput {F32(Vec<f32>),I32(Vec<i32>),}impl PreparedGoldenInput {- /// A zero-filled input with the same element type and length.pub fn zeroed(&self) -> Self {match self {Self::F32(data) => Self::F32(vec![0.0; data.len()]),@@ -171,7 +121,6 @@ impl PreparedGoldenInput {}}-/// Materializes the entry's fixed input tensor data.pub fn prepare_input(entry: &GoldenEntry) -> Result<PreparedGoldenInput, String> {let element_count: i64 = entry.input_shape.iter().product();let element_count = usize::try_from(element_count)@@ -210,8 +159,6 @@ pub fn seeded_noise(seed: u64, len: usize) -> Vec<f32> {.collect()}-/// The deterministic sample of a full output that golden entries store and-/// self-tests compare against.pub fn sample_output(output: &[f32]) -> Vec<f32> {let stride = sample_stride(output.len());output.iter().copied().step_by(stride).collect()@@ -221,9 +168,6 @@ fn sample_stride(output_len: usize) -> usize {output_len.div_ceil(MAX_REFERENCE_SAMPLES).max(1)}-/// Compares a session's full first output against a golden entry using the-/// entry's metric. Returns the measured distance, or a description of why the-/// output is rejected.pub fn compare_output(entry: &GoldenEntry, output: &[f32]) -> Result<f64, String> {let distances = measure_output(entry, output)?;match distances {@@ -251,9 +195,6 @@ pub fn compare_output(entry: &GoldenEntry, output: &[f32]) -> Result<f64, String}}-/// Measures an output's distance from the committed golden without applying-/// the acceptance threshold. Useful for checking that a warm-up input's-/// output is well separated from the golden output.pub fn output_distance(entry: &GoldenEntry, output: &[f32]) -> Result<f64, String> {Ok(match measure_output(entry, output)? {OutputDistances::Cosine(distance) => distance,@@ -443,8 +384,6 @@ mod tests {entry_with_metric(GoldenMetric::CosineDistance, expected_sample, output_len)}- /// Downloaded models are stored under URL-derived sanitized names; the- /// canonical name must match both those and its plain form.#[test]fn matches_canonical_and_app_sanitized_model_file_names() {const CANONICAL: &str = "yolov5s_face_640_640_static_b1.onnx";@@ -462,16 +401,12 @@ mod tests {"models_ente_com_mobileclip_s2_image_gelu_opset20_onnx",CANONICAL));- // A different model whose name merely contains the canonical name- // without an underscore boundary must not match.assert!(!matches_model_file("models_ente_com_xyolov5s_face_640_640_static_b1_onnx",CANONICAL));}- /// No committed entry may match another entry's on-device name, otherwise- /// a model could be validated against the wrong golden.#[test]fn committed_entries_are_unambiguous_for_app_sanitized_names() {for entry in GOLDEN_ENTRIES {@@ -494,7 +429,6 @@ mod tests {assert_eq!(first, second);assert!(first.iter().all(|value| (0.0..1.0).contains(value)));assert_ne!(first, seeded_noise(43, 1000));- // Not degenerate: values actually vary.assert!(first.iter().any(|value| *value > 0.9));assert!(first.iter().any(|value| *value < 0.1));}@@ -574,9 +508,6 @@ mod tests {assert!(error.contains("zero vector"), "{error}");}- /// Cosine is scale-invariant by design (embedding consumers normalize),- /// so the detector entries must use relative L2, which rejects- /// magnitude-corrupted output.#[test]fn relative_l2_rejects_scale_corrupted_output_that_cosine_accepts() {static EXPECTED: [f32; 4] = [0.5, -1.0, 2.0, 0.25];@@ -625,11 +556,6 @@ mod tests {)}- /// Background confidences flushed to zero measure exactly 1.0, below the- /// deliberately loose confidence threshold: some fp16 pipelines flush- /// subnormals, and a zeroed background score is functionally identical to- /// a tiny one. An all-zero *output* is still rejected via the coordinate- /// group.#[test]fn detector_metric_tolerates_fully_flushed_confidences() {static EXPECTED: [f32; 32] = [@@ -667,8 +593,6 @@ mod tests {assert!(error.contains("detector confidence"), "{error}");}- /// Coordinate corruption must fail even where the looser confidence- /// threshold would accept it.#[test]fn detector_metric_keeps_the_strict_threshold_for_coordinates() {static EXPECTED: [f32; 32] = [@@ -688,8 +612,6 @@ mod tests {assert!(error.contains("remaining"), "{error}");}- /// A confidence-group deviation beyond the coordinate threshold must- /// still be accepted (fp16 noise floor).#[test]fn detector_metric_tolerates_noise_floor_divergence_on_confidences() {static EXPECTED: [f32; 32] = [diff --git a/rust/crates/photos/src/ml/golden_tooling.rs b/rust/crates/photos/src/ml/golden_tooling.rsindex ec38a4fb84..45b33771ae 100644--- a/rust/crates/photos/src/ml/golden_tooling.rs+++ b/rust/crates/photos/src/ml/golden_tooling.rs@@ -1,11 +1,3 @@-//! Generation and verification of the committed golden self-test data.-//!-//! Regeneration (`render_golden_data`) runs the production models on the CPU-//! execution provider and is invoked manually via the `ml_goldens` developer-//! tool's `generate` command.-//! Verification (`verify_goldens_against_pins`) is metadata-only and runs as-//! a plain unit test in every CI pass.-use std::collections::BTreeMap;use std::path::Path;@@ -15,9 +7,7 @@ use crate::ml::{clip, golden, golden_data::GOLDEN_ENTRIES, onnx};pub use crate::ml::golden::GoldenMetric;-/// One fixed seed for all noise inputs. Inputs need not differ across models-/// (each model's input is shaped and consumed independently), and each entry-/// stores its seed, so the device never depends on this constant.+/// Each generated entry stores this seed, so devices do not depend on it.const GOLDEN_NOISE_SEED: u64 = 0x0060_1DE2_5EED_2026;const GENERATED_FILE_HEADER: &str = "\@@ -35,28 +25,18 @@ use crate::ml::golden::{GoldenEntry, GoldenInput, GoldenMetric};pub(crate) static GOLDEN_ENTRIES: &[GoldenEntry] = &[";-/// A production model to generate a golden entry for.pub struct GoldenModelSpec {pub model_path: String,- /// SHA-256 of the model file as pinned in the asset lock; embedded into- /// the generated entry so that CI can detect a content change without- /// re-running inference.pub sha256: String,pub input: GoldenSpecInput,- /// `CosineDistance` for embedding outputs and a relative-L2 variant for- /// raw tensor outputs.pub metric: GoldenMetric,}pub enum GoldenSpecInput {- /// Deterministic noise seeded from the model file name.SeededNoise,- /// A fixed phrase tokenized with the production CLIP tokenizer.ClipText { phrase: String, vocab_path: String },}-/// Measured separation between a zero-input warm-up and the committed golden-/// when both are run consecutively on one CPU session.pub struct ZeroGoldenSeparation {pub model_file: String,pub metric_label: &'static str,@@ -65,7 +45,6 @@ pub struct ZeroGoldenSeparation {pub threshold: f64,}-/// Renders the complete contents of `golden_data.rs` for the given models.pub fn render_golden_data(models: &[GoldenModelSpec]) -> Result<String, String> {let mut source = String::from(GENERATED_FILE_HEADER);for spec in models {@@ -75,8 +54,6 @@ pub fn render_golden_data(models: &[GoldenModelSpec]) -> Result<String, String>Ok(source)}-/// Runs the production self-test sequence on CPU and measures whether a-/// stale zero-input result would be rejected by the committed golden.pub fn measure_zero_golden_separation(model_path: &str) -> Result<ZeroGoldenSeparation, String> {let model_file = model_file_name(model_path)?;let entry = golden::lookup(model_path)@@ -107,22 +84,12 @@ pub fn measure_zero_golden_separation(model_path: &str) -> Result<ZeroGoldenSepa})}-/// A production model as pinned in the asset lock-/// (`infra/ml/test/ml_indexing/assets.json`).pub struct PinnedModel {pub file_name: String,pub sha256: String,}-/// Cheaply verifies that the committed goldens correspond exactly to the-/// pinned production models, by file name and content hash. Returns-/// human-readable failures; empty means consistent.-///-/// Deliberately metadata-only (no model downloads, no inference) so it runs-/// as a plain unit test in every CI pass. This catches the two realistic-/// ways goldens go stale β a model update (new file name) and a content-/// change under an unchanged name β but not numeric drift of the CPU-/// execution provider itself; the wide on-device thresholds absorb that.+/// Metadata-only CI guard; it does not detect numeric CPU-provider drift.pub fn verify_goldens_against_pins(pins: &[PinnedModel]) -> Vec<String> {let mut failures = Vec::new();@@ -265,9 +232,6 @@ mod tests {use super::{PinnedModel, verify_goldens_against_pins};use crate::ml::golden_data::GOLDEN_ENTRIES;- /// Loads the pinned production models from the asset lock. Restricted to- /// `.onnx` files: other pinned model assets (the CLIP vocabulary) are- /// model inputs, not models, and get no golden entries.fn pinned_production_models() -> Vec<PinnedModel> {let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../infra/ml/test/ml_indexing/assets.json");@@ -286,10 +250,6 @@ mod tests {.collect()}- /// The CI guard against stale goldens: a model update (new file name) or- /// a content change under an unchanged name in the asset lock fails this- /// test until `golden_data.rs` is regenerated with the `ml_goldens`- /// developer tool.#[test]fn committed_goldens_are_pinned_to_the_production_models() {let pins = pinned_production_models();@@ -315,8 +275,6 @@ mod tests {.collect();assert!(verify_goldens_against_pins(&matching).is_empty());- // A pinned model without an entry, a content change under an- // unchanged name, and a dropped pin leaving a stale entry.let mut pins = matching;pins[0].sha256 = "f".repeat(64);let stale = pins.pop().unwrap();diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rsindex e243b91aaf..76fc7ab8bb 100644--- a/rust/crates/photos/src/ml/onnx.rs+++ b/rust/crates/photos/src/ml/onnx.rs@@ -52,8 +52,6 @@ const COREML_PACKAGE_WEIGHT_BLOB: &str = "weight.bin";#[cfg(any(target_os = "ios", target_os = "macos"))]const ENABLE_PERSISTENT_COREML_CACHE: bool = true;-/// An f32 model input that can be borrowed by multiple sessions.-////// The FP16 representation is created lazily and retained so that a shared/// preprocessing result only pays the conversion cost once.pub(crate) struct PreparedF32Input {@@ -116,12 +114,8 @@ pub(crate) enum ExecutionMode {CpuOnly,}-/// The preferred execution provider of the session attempt that succeeded.-///-/// Each accelerated session also registers the policy's fallback providers,-/// but this identifies the provider whose attempt produced the session. The-/// runtime aggregates it across the sessions used for a result so remotely-/// stored embeddings can be attributed to the providers that computed them.+/// Identifies the successful attempt's preferred provider, not its registered+/// fallback providers, for result attribution.#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[allow(dead_code)] // Accelerated variants are constructed only on their target OS.pub(crate) enum ExecutionProvider {@@ -204,12 +198,9 @@ pub(crate) fn build_session()))}-/// Builds a session for one provider attempt and, for CoreML attempts, runs-/// the golden self-test before the session is trusted. A self-test failure is-/// reported as a session-construction failure, so the caller invalidates the-/// CoreML cache (a corrupt compiled model would otherwise persist) and falls-/// through to the next attempt. WebGPU attempts do not take this path; they-/// are validated inside the crash-canary window.+/// A CoreML self-test failure is treated as construction failure so the caller+/// invalidates the possibly corrupt persistent cache. WebGPU validation stays+/// inside its crash-canary window instead.fn build_and_validate_session(model_path: &str, attempt: ProviderAttempt) -> MlResult<Session> {#[cfg(any(target_os = "android",@@ -249,12 +240,8 @@ fn build_and_validate_session(model_path: &str, attempt: ProviderAttempt) -> MlROk(session)}-/// Builds the WebGPU session under the durable crash canary. The canary is-/// armed before session construction and only disarmed after the session has-/// passed the golden self-test, so a driver crash anywhere in between is-/// recorded on disk. Soft failures (including self-test failures) return an-/// error with the canary left armed (the drop keeps the counted attempt), and-/// the caller falls through to the next execution provider.+/// The durable canary remains armed through construction and self-test, so+/// crashes and soft failures both count toward quarantine.#[cfg(any(target_os = "android", target_os = "linux", target_os = "windows"))]fn build_webgpu_session_with_canary(model_path: &str,@@ -359,9 +346,6 @@ fn provider_attempt_failure_message())}-/// Validates a freshly built accelerated session against the model's-/// committed golden output. An error means the session must not be used; the-/// caller falls through to the next execution provider attempt.#[cfg(any(target_os = "android",target_os = "ios",@@ -376,8 +360,6 @@ fn run_session_self_test() -> MlResult<()> {let model_file = model_file_label(model_path);let Some(entry) = golden::lookup(model_path) else {- // Attempts are only constructed for models with a golden entry, so- // this is a defensive fail-closed path.return Err(MlError::Ort(format!("golden self-test entry missing for '{model_file}'")));@@ -468,9 +450,7 @@ fn model_file_label(model_path: &str) -> &str {.unwrap_or(model_path)}-/// Runs one golden input through the session and extracts the first output as-/// f32. Shared with the golden generator so device and generator inference-/// are identical by construction.+/// Shared with the generator so its inference path stays identical to devices.pub(crate) fn run_golden_tensor(session: &mut Session,input_shape: &[i64],@@ -611,9 +591,7 @@ fn coreml_provider((provider.build().error_on_failure(), prepared_cache_dir)}-/// Deletes the entire persistent cache tree while the feature is disabled, so-/// flipping `ENABLE_PERSISTENT_COREML_CACHE` off in a release actually-/// returns the disk space instead of stranding the caches forever.+/// Disabling the feature must also reclaim caches created by earlier releases.#[cfg(any(target_os = "ios", target_os = "macos"))]fn remove_persistent_coreml_cache(model_path: &str) {let Some(coreml_root) = coreml_cache_root(Path::new(model_path))@@ -656,8 +634,6 @@ fn platform_default_attempts(execution_provider: ExecutionProvider::WebGpu,});}- // Clean-session fallbacks for provider or driver failures that prevent- // the primary session from being constructed at all.attempts.push(xnnpack_attempt());attempts.push(ProviderAttempt::cpu_only());attempts@@ -685,9 +661,7 @@ fn platform_default_attempts(attempts}-/// Accelerated execution providers are only allowed for models with a-/// committed golden self-test entry (fail closed). A miss for a production-/// model means a model update shipped without regenerating `golden_data.rs`.+/// Missing goldens fail closed, usually indicating they were not regenerated after an update.#[cfg(any(target_os = "android",target_os = "ios",@@ -741,7 +715,6 @@ fn prepare_coreml_cache_directory(let model_path = Path::new(model_path);let schema_root = coreml_cache_root(model_path);- // Best effort: a prune failure must not cost this load its cache.if let Some(coreml_root) = schema_root.parent() {match prune_stale_coreml_schema_directories(coreml_root, COREML_CACHE_SCHEMA) {Ok(removed) => {@@ -770,9 +743,7 @@ fn prepare_coreml_cache_directory(Ok(cache_dir)}-/// A missing completion marker means the process stopped before ONNX Runtime-/// finished constructing the session. Recreate the directory so ORT cannot-/// mistake a partial model package for a valid cache hit.+/// Rebuild unmarked entries so ORT cannot reuse a package interrupted mid-build.#[cfg(any(target_os = "ios", target_os = "macos", test))]fn prepare_coreml_cache_entry(cache_dir: &Path) -> std::io::Result<()> {if cache_dir.exists() && !coreml_cache_complete_marker(cache_dir).is_file() {@@ -781,11 +752,8 @@ fn prepare_coreml_cache_entry(cache_dir: &Path) -> std::io::Result<()> {std::fs::create_dir_all(cache_dir)}-/// Runs after a session was built successfully from `cache_dir`: trims the-/// redundant generated-package weights, then marks the entry complete. Trim-/// failures are reported but do not fail the load; an untrimmed cache is-/// merely larger. Trimming before marking means a crash mid-trim leaves no-/// completion marker, so the next load rebuilds the entry from scratch.+/// Trim before marking complete so a crash mid-trim forces a clean rebuild.+/// Trim failures only waste disk space and therefore do not fail the load.fn finalize_coreml_cache(cache_dir: &Path, model_path: &str) {match trim_coreml_cache_weights(cache_dir) {Ok(0) => {}@@ -817,25 +785,14 @@ fn finalize_coreml_cache(cache_dir: &Path, model_path: &str) {}}-/// Truncates the weight blobs inside every cached generated package that-/// already contains a compiled model, returning the bytes reclaimed.-////// On a warm cache hit ONNX Runtime 1.27 only checks that the generated-/// MLProgram package directory exists and then loads-/// `compiled_model.mlmodelc` (`model_builder.cc` constructor, `model.mm`-/// `CompileOrReadCachedModel`), so the package's own weight copy is dead-/// bytes β roughly half the cache footprint. Packages without a compiled-/// model are left intact because ONNX Runtime would recompile from them.-/// Should a future runtime read the package weights again, session-/// construction fails, the caller invalidates the entry, and the next load-/// rebuilds it from the ONNX source.+/// package directory and loads `compiled_model.mlmodelc`, making the package's+/// own weights redundant. Uncompiled packages remain intact; incompatible+/// future runtimes will fail construction and trigger cache invalidation.fn trim_coreml_cache_weights(cache_dir: &Path) -> std::io::Result<u64> {let mut reclaimed = 0;- // Layout per ORT 1.27: <cache_dir>/<model_hash>/<partition>/model is the- // generated MLProgram package. `CompileOrReadCachedModel` strips the last- // path component only for the NeuralNetwork format, so for MLProgram the- // compiled model is stored INSIDE the package directory:- // <partition>/model/compiled_model.mlmodelc.+ // ORT 1.27 stores the compiled MLProgram inside+ // <cache_dir>/<model_hash>/<partition>/model/compiled_model.mlmodelc.for model_hash_entry in std::fs::read_dir(cache_dir)? {let model_hash_entry = model_hash_entry?;if !model_hash_entry.file_type()?.is_dir() {@@ -896,9 +853,7 @@ fn coreml_cache_complete_marker(cache_dir: &Path) -> PathBuf {cache_dir.join(COREML_CACHE_COMPLETE_MARKER)}-/// Keep generated CoreML artifacts in Library/Caches so iOS can evict them and-/// exclude them from backups. Model files are stored below Library/Application-/// Support; fall back to the process temporary directory for unusual layouts.+/// Use Library/Caches for eviction and backup exclusion, or temp for unusual layouts.#[cfg(any(target_os = "ios", target_os = "macos", test))]fn coreml_cache_root(model_path: &Path) -> PathBuf {let cache_base = model_path@@ -954,10 +909,7 @@ fn sanitize_cache_component(value: &str) -> String {.collect()}-/// Removes cache trees written under superseded `COREML_CACHE_SCHEMA`-/// versions, returning the names of the removed directories. Without this, a-/// schema bump (ORT upgrade or CoreML policy change) would orphan the-/// previous schema's caches β hundreds of MB β forever.+/// Schema bumps must not orphan the previous version's large cache trees.#[cfg(any(target_os = "ios", target_os = "macos", test))]fn prune_stale_coreml_schema_directories(coreml_root: &Path,@@ -980,8 +932,6 @@ fn prune_stale_coreml_schema_directories(Ok(removed)}-/// Retain exactly one generated cache for each logical model slot. The active-/// directory is identity-specific so ONNX Runtime cannot reuse stale output.#[cfg(any(target_os = "ios", target_os = "macos", test))]fn prune_superseded_coreml_cache_directories(model_cache_root: &Path,@@ -1055,7 +1005,6 @@ fn ensure_finite_f16(data: &[half::f16]) -> MlResult<()> {))}-/// Returns true if the session's first input expects FP16 tensors.fn session_expects_f16(session: &Session) -> bool {session.inputs()@@ -1067,8 +1016,6 @@ fn session_expects_f16(session: &Session) -> bool {.unwrap_or(false)}-/// Run inference accepting f32 data and returning f32 results.-/// Automatically converts inputs/outputs for FP16 models.pub(crate) fn run_f32<const N: usize>(session: &mut Session,input: Vec<f32>,@@ -1088,7 +1035,6 @@ pub(crate) fn run_f32<const N: usize>(}let output = &outputs[0];- // Extract output: try f32 first, fall back to f16 with conversion.if let Ok((tensor_shape, tensor_data)) = output.try_extract_tensor::<f32>() {let shape = tensor_shape.iter().copied().collect::<Vec<_>>();let data = tensor_data.to_vec();@@ -1104,9 +1050,6 @@ pub(crate) fn run_f32<const N: usize>(}}-/// Run inference using a reusable input and process the first output in place.-/// Both f32 and f16 outputs remain borrowed from ONNX Runtime; consumers-/// convert only the values they inspect.pub(crate) fn with_prepared_float_output<const N: usize, T>(session: &mut Session,input: &PreparedF32Input,@@ -1312,12 +1255,6 @@ mod tests {assert!(removed.is_empty());}- /// Mirrors the ORT 1.27 MLProgram cache layout: the generated package at- /// `<cache_dir>/<model_hash>/<partition>/model/` holds its weights under- /// `Data/com.microsoft.OnnxRuntime/weights/weight.bin`, and the compiled- /// model is stored INSIDE the package directory as- /// `model/compiled_model.mlmodelc` (which keeps its own- /// `weights/weight.bin` copy).fn write_cache_partition(cache_dir: &Path,partition: &str,@@ -1352,13 +1289,9 @@ mod tests {assert_eq!(reclaimed, b"weights".len() as u64);assert!(compiled_blob.exists());assert_eq!(std::fs::metadata(&compiled_blob).unwrap().len(), 0);- // The package directory itself must survive: ONNX Runtime checks its- // existence to decide the model is cached.let package_dir = compiled_blob.ancestors().nth(4).unwrap();assert!(package_dir.ends_with("model"));assert!(package_dir.is_dir());- // The compiled model's own weight copy is what warm loads read; the- // trim walk must never descend into the `.mlmodelc` bundle.assert_eq!(std::fs::read(package_dirdiff --git a/rust/crates/photos/src/ml/pet/align.rs b/rust/crates/photos/src/ml/pet/align.rsindex fab60bd089..c54887fec9 100644--- a/rust/crates/photos/src/ml/pet/align.rs+++ b/rust/crates/photos/src/ml/pet/align.rs@@ -10,21 +10,10 @@ use super::{preprocess::{PetFaceEmbeddingInputs, PixelCrop, RgbCropResizer, append_imagenet_tensor},};-/// Minimum eye distance in pixels below which alignment is skipped.const MIN_EYE_DISTANCE: f32 = 5.0;-/// Angle threshold in degrees; below this, skip rotation and just crop.const ANGLE_SKIP_DEG: f32 = 1.0;-/// Expand factor applied to each side of the bounding box when cropping.const CROP_EXPAND: f32 = 0.1;-/// Run pet face alignment using 3-point landmarks (left_eye, right_eye, nose).-///-/// Mirrors `pet_pipeline/detection.py` `_align_face()`:-/// 1. Skip if eye distance < 5 px-/// 2. If angle < 1Β°, crop bounding box directly (no rotation)-/// 3. Otherwise rotate around face center, then crop with 10% expand-/// 4. Resize to 224Γ224-/// 5. Apply ImageNet normalization (CHW)pub(crate) fn run_pet_face_alignment(file_id: i64,decoded: &DecodedImage,@@ -45,7 +34,6 @@ pub(crate) fn run_pet_face_alignment(let mut crop_resizer = RgbCropResizer::new(PET_EMBEDDING_INPUT_SIZE as u32);for detection in detections {- // Convert relative keypoints to absolutelet left_eye = [detection.keypoints[0][0] * img_wf,detection.keypoints[0][1] * img_hf,@@ -59,12 +47,10 @@ pub(crate) fn run_pet_face_alignment(let dy = right_eye[1] - left_eye[1];let eye_dist = (dx * dx + dy * dy).sqrt();- // Skip if eyes are too close togetherif eye_dist < MIN_EYE_DISTANCE {continue;}- // Absolute bounding box (clamped to image bounds on both sides)let max_xf = (img_w as f32 - 1.0).max(0.0);let max_yf = (img_h as f32 - 1.0).max(0.0);let box_x1 = (detection.box_xyxy[0] * img_wf).clamp(0.0, max_xf) as i32;@@ -76,7 +62,6 @@ pub(crate) fn run_pet_face_alignment(let angle_rad = dy.atan2(dx);let aligned_rgb = if angle_deg.abs() < ANGLE_SKIP_DEG {- // No rotation needed β just crop the bounding box directlylet cx1 = box_x1.max(0) as u32;let cy1 = box_y1.max(0) as u32;let cx2 = (box_x2 as u32).min(img_w);@@ -88,7 +73,6 @@ pub(crate) fn run_pet_face_alignment(}crop_and_resize_decoded(&mut crop_resizer, decoded, cx1, cy1, crop_w, crop_h)?} else {- // Rotate only a padded region around the face, not the full image.let bw = (box_x2 - box_x1) as f32;let bh = (box_y2 - box_y1) as f32;let pad = (bw.max(bh) * (CROP_EXPAND + 0.5)).ceil() as i32;@@ -105,11 +89,9 @@ pub(crate) fn run_pet_face_alignment(let region = RgbRegion::new(decoded, region_x1, region_y1, region_w, region_h)?;- // Face center relative to the extracted regionlet local_cx = (box_x1 + box_x2) as f64 / 2.0 - region_x1 as f64;let local_cy = (box_y1 + box_y2) as f64 / 2.0 - region_y1 as f64;- // Crop coordinates relative to the regionlet nx1 = (box_x1 as f32 - bw * CROP_EXPAND - region_x1 as f32).max(0.0) as u32;let ny1 = (box_y1 as f32 - bh * CROP_EXPAND - region_y1 as f32).max(0.0) as u32;let nx2 =@@ -168,8 +150,6 @@ pub(crate) fn run_pet_face_alignment(Ok((aligned_inputs, face_results))}-/// Render a crop of an image rotated around a center point using bilinear-/// interpolation with BORDER_REPLICATE behaviour.fn rotate_crop_around_center(source: &RgbRegion<'_>,angle_rad: f64,@@ -180,10 +160,6 @@ fn rotate_crop_around_center(let cos_a = angle_rad.cos();let sin_a = angle_rad.sin();- // Build forward rotation matrix (output -> input):- // x_in = cos_a * (x_out - cx) + sin_a * (y_out - cy) + cx- // y_in = -sin_a * (x_out - cx) + cos_a * (y_out - cy) + cy-let mut output = RgbImage::new(crop.width, crop.height);let w_f = source.width as f64;let h_f = source.height as f64;@@ -197,11 +173,9 @@ fn rotate_crop_around_center(let src_x = cos_a * dx + sin_a * dy + cx;let src_y = -sin_a * dx + cos_a * dy + cy;- // BORDER_REPLICATE: clamp to valid rangelet sx = src_x.max(0.0).min(w_f - 1.0);let sy = src_y.max(0.0).min(h_f - 1.0);- // Bilinear interpolationlet x0 = sx.floor() as u32;let y0 = sy.floor() as u32;let x1 = (x0 + 1).min(source.width - 1);@@ -229,7 +203,6 @@ fn rotate_crop_around_center(output}-/// Crop a region from an RGB image and resize to 224Γ224 using bilinear interpolation.fn crop_and_resize_rgb<'a>(resizer: &'a mut RgbCropResizer,source: &RgbImage,@@ -240,7 +213,6 @@ fn crop_and_resize_rgb<'a>() -> MlResult<&'a [u8]> {let src_w = source.width();let src_h = source.height();- // Clamp crop region to source bounds to avoid edge-replication artifacts.let clamped_w = w.min(src_w.saturating_sub(x));let clamped_h = h.min(src_h.saturating_sub(y));if clamped_w == 0 || clamped_h == 0 {@@ -296,7 +268,6 @@ fn resize_crop<'a>(resizer.resize(rgb, source_width, source_height, crop)}-/// A row-strided view into a rectangular region of the decoded RGB buffer.struct RgbRegion<'a> {rgb: &'a [u8],image_width: usize,diff --git a/rust/crates/photos/src/ml/pet/detect.rs b/rust/crates/photos/src/ml/pet/detect.rsindex ec5d0511cc..b7ec7c2abf 100644--- a/rust/crates/photos/src/ml/pet/detect.rs+++ b/rust/crates/photos/src/ml/pet/detect.rs@@ -12,7 +12,6 @@ use super::{COCO_CAT, COCO_DOG, PET_SPECIES_CAT, PET_SPECIES_DOG};const PET_FACE_IOU_THRESHOLD: f32 = 0.5;const PET_FACE_MIN_SCORE: f32 = 0.3;-// Body detection thresholdsconst BODY_IOU_THRESHOLD: f32 = 0.5;const BODY_MIN_SCORE: f32 = 0.3;@@ -21,12 +20,8 @@ const BODY_MIN_SCORE: f32 = 0.3;// 1 = cat (face detection class_id=1, COCO_CAT=15)// Dart maps COCO β species via: cocoClass == 15 ? 1 : 0-/// Run pet face detection using YOLOv5-face model with 3 keypoints.-////// Output format per row: [x, y, w, h, obj_conf, lx, ly, rx, ry, nx, ny, ...]/// 3 keypoints: left_eye, right_eye, nose (6 values for coords).-///-/// This mirrors `pet_pipeline/detection.py` `FaceDetector.detect()`.pub(crate) fn run_pet_face_detection(runtime: &MlRuntimeView<'_>,input: &YoloInput,@@ -62,14 +57,9 @@ fn postprocess_pet_face_tensor<T: onnx::FloatTensorData>(output_data: T,input: &YoloInput,) -> MlResult<Vec<PetFaceDetection>> {- // Row format: [x, y, w, h, conf, lm_x1, lm_y1, lm_x2, lm_y2, lm_x3, lm_y3, cls0, cls1]- // row_len = 4 + 1 + 6 + 2 = 13 for 2-class model- // Use the output shape's last dimension to determine row length reliably.let row_len = if output_shape.len() >= 2 {*output_shape.last().unwrap() as usize} else if output_shape.len() == 1 {- // Flat output: total_elements, must infer row_len.- // Prefer 13 (2-class model) as the expected format, then fall back.let total = output_data.len();let inferred = if total.is_multiple_of(13) {13@@ -83,7 +73,6 @@ fn postprocess_pet_face_tensor<T: onnx::FloatTensorData>(total, output_shape)));};- // Warn if the total is ambiguously divisible by multiple candidates.let candidates = [11usize, 12, 13];let valid_count = candidates.iter()@@ -135,7 +124,6 @@ fn postprocess_pet_face_tensor<T: onnx::FloatTensorData>(y_max_abs / YOLO_INPUT_SIZE as f32,];- // 3 keypoints: left_eye, right_eye, noselet mut keypoints = [[output_data.value(start + 5) / YOLO_INPUT_SIZE as f32,@@ -178,12 +166,6 @@ fn postprocess_pet_face_tensor<T: onnx::FloatTensorData>(Ok(naive_nms_pet_face(detections, PET_FACE_IOU_THRESHOLD))}-/// Run pet body detection using YOLOv5n model.-///-/// Filters detections by COCO class 15 (cat) or 16 (dog).-/// Returns all qualifying detections after NMS.-///-/// This mirrors `pet_pipeline/detection.py` `BodyDetector.detect()`.pub(crate) fn run_pet_body_detection(runtime: &MlRuntimeView<'_>,input: &YoloInput,@@ -212,7 +194,6 @@ fn postprocess_pet_body_tensor<T: onnx::FloatTensorData>(input: &YoloInput,) -> MlResult<Vec<PetBodyDetection>> {// YOLOv5 output format: [x, y, w, h, obj_conf, cls0, cls1, ..., cls79]- // Total columns: 4 + 1 + 80 = 85let row_len = 85usize;if output_data.len() < row_len {return Ok(Vec::new());@@ -261,8 +242,6 @@ fn winning_pet_body_class<T: onnx::FloatTensorData>() -> Option<(u8, f32)> {let obj_conf = output_data.value(row_start + 4);- // Most detector rows cannot produce a cat or dog above the score- // threshold. Reject those before scanning all 80 COCO classes.let cat_logit = output_data.value(row_start + 5 + COCO_CAT as usize);let dog_logit = output_data.value(row_start + 5 + COCO_DOG as usize);let best_pet_logit = if dog_logit.total_cmp(&cat_logit).is_ge() {@@ -327,8 +306,6 @@ fn naive_nms_pet_face(if suppressed[j] {continue;}- // Only suppress within the same class so a dog and cat- // occupying the same region are both retained.if detections[i].class_id == detections[j].class_id&& calculate_iou_4(&detections[i].box_xyxy, &detections[j].box_xyxy)>= iou_threshold@@ -359,8 +336,6 @@ fn naive_nms_pet_body(if suppressed[j] {continue;}- // Only suppress within the same COCO class so a dog and cat- // occupying the same region are both retained.if detections[i].coco_class == detections[j].coco_class&& calculate_iou_4(&detections[i].box_xyxy, &detections[j].box_xyxy)>= iou_thresholddiff --git a/rust/crates/photos/src/ml/pet/embed.rs b/rust/crates/photos/src/ml/pet/embed.rsindex 6f43099f8e..967ec836b4 100644--- a/rust/crates/photos/src/ml/pet/embed.rs+++ b/rust/crates/photos/src/ml/pet/embed.rs@@ -11,18 +11,6 @@ use super::{preprocess::{IndexedEmbeddingBatch, PetEmbeddingPreprocessor, PetFaceEmbeddingInputs},};-/// Run pet face embedding on aligned face inputs.-///-/// The species parameter (0=dog, 1=cat) selects the model to use.-///-/// Input per face: CHW float32 of shape [1, 3, 224, 224], ImageNet-normalized.-/// Output: L2-normalized embedding vector (128-d for BYOL).-///-/// This mirrors `pet_pipeline/embedding.py` `Embedder.embed_face()`.-/// Run pet face embedding using each face's own `class_id` to select the model.-///-/// Faces are grouped by species and batched per model to avoid running the-/// wrong embedding model on any detection.pub(crate) fn run_pet_face_embedding(runtime: &MlRuntimeView<'_>,aligned_faces: PetFaceEmbeddingInputs,@@ -88,13 +76,6 @@ pub(crate) fn run_pet_face_embedding(Ok(())}-/// Run pet body embedding on cropped body regions.-///-/// Each body's own `coco_class` (16=dog, 15=cat) selects the embedding model,-/// so mixed-species images get the correct model per detection.-/// Bodies are grouped by species and batched per model.-///-/// This mirrors `pet_pipeline/embedding.py` `Embedder.embed_body()`.pub(crate) fn run_pet_body_embedding(runtime: &MlRuntimeView<'_>,decoded: &DecodedImage,@@ -106,7 +87,6 @@ pub(crate) fn run_pet_body_embedding(let per_body_len = PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_CHANNELS;- // Preprocess all crops and group by species.// Skip detections whose crop is invalid (e.g. zero-area edge boxes)// rather than aborting the whole image.let cat_count = body_resultsdiff --git a/rust/crates/photos/src/ml/pet/preprocess.rs b/rust/crates/photos/src/ml/pet/preprocess.rsindex bff5d5cf51..2f63a87858 100644--- a/rust/crates/photos/src/ml/pet/preprocess.rs+++ b/rust/crates/photos/src/ml/pet/preprocess.rs@@ -64,20 +64,7 @@ pub(super) struct PixelCrop {pub(super) height: u32,}-/// Preprocess a cropped pet face/body image for embedding extraction.-///-/// Steps:-/// 1. Resize to 224x224 using bilinear interpolation-/// 2. Normalize using ImageNet mean/std-/// 3. Output CHW layout as float32-///-/// This mirrors the Python pipeline's preprocessing:-/// ```python-/// img = cv2.resize(crop, (224, 224))-/// img = img / 255.0-/// img = (img - IMAGENET_MEAN) / IMAGENET_STD-/// img = img.transpose(2, 0, 1) # HWC -> CHW-/// ```+/// Mirrors the Python pet pipeline's ImageNet-normalized CHW preprocessing.pub(super) struct PetEmbeddingPreprocessor {crop_resizer: RgbCropResizer,}@@ -141,7 +128,6 @@ fn relative_crop(decoded: &DecodedImage, box_xyxy: &[f32; 4]) -> MlResult<PixelC})}-/// Resizes row-strided crop views while retaining FIR's internal workspace.pub(super) struct RgbCropResizer {resizer: Resizer,resized: FirImage<'static>,diff --git a/rust/crates/photos/src/ml/runtime.rs b/rust/crates/photos/src/ml/runtime.rsindex 6cb5e5ce14..bef629c6ca 100644--- a/rust/crates/photos/src/ml/runtime.rs+++ b/rust/crates/photos/src/ml/runtime.rs@@ -12,7 +12,6 @@ use crate::ml::{onnx,};-/// Log to Android logcat or stderr.pub(crate) fn rt_log(msg: &str) {#[cfg(target_os = "android")]{@@ -736,8 +735,6 @@ mod tests {#[test]fn model_execution_modes_match_platform_policy() {let runtime = MlRuntime::new();- // Pet models stay CPU-only on every platform until they are- // validated on the GPU execution providers.let expected_pet_mode = onnx::ExecutionMode::CpuOnly;assert_eq!(diff --git a/rust/crates/photos/src/ml/types.rs b/rust/crates/photos/src/ml/types.rsindex dc86685d00..194b8803de 100644--- a/rust/crates/photos/src/ml/types.rs+++ b/rust/crates/photos/src/ml/types.rs@@ -46,8 +46,6 @@ pub(crate) fn to_face_id(file_id: i64, box_xyxy: [f32; 4]) -> String {format!("{file_id}_{x_min}_{y_min}_{x_max}_{y_max}")}-// ββ Pet Recognition Types ββββββββββββββββββββββββββββββββββββββββββββββ-#[derive(Clone, Debug)]pub struct PetFaceDetection {pub score: f32,diff --git a/rust/crates/photos/src/ml/vector_db.rs b/rust/crates/photos/src/ml/vector_db.rsindex c322ff3846..6430b21530 100644--- a/rust/crates/photos/src/ml/vector_db.rs+++ b/rust/crates/photos/src/ml/vector_db.rs@@ -45,10 +45,7 @@ impl VectorDB {if file_exists {println!("Loading index from disk.");- // Must use load() instead of view() because:- // - view() creates a read-only memory-mapped view (immutable)- // - load() loads the index into RAM for read/write operations (mutable)- // Using view() causes "Can't add to an immutable index" error+ // `view` is immutable, but the reloaded index must remain writable.db.index.load(file_path).map_err(|e| format!("Failed to load index from {file_path}: {e}"))?;@@ -60,7 +57,6 @@ impl VectorDB {}fn save_index(&self) -> Result<(), String> {- // Ensure directory existsif let Some(parent) = self.path.parent() {std::fs::create_dir_all(parent).map_err(|e| {format!(@@ -70,9 +66,7 @@ impl VectorDB {})?;}- // Use atomic write: save to temp file first, then rename- // Use a unique temp path per save so concurrent saves can never race- // by clobbering the same temporary file.+ // Unique temp paths prevent concurrent saves from clobbering each other.let save_sequence = INDEX_SAVE_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);let temp_path =self.path@@ -81,7 +75,6 @@ impl VectorDB {.to_str().ok_or_else(|| format!("Invalid temp path: {}", temp_path.display()))?;- // Save to temporary fileself.index.save(temp_path_str).map_err(|e| {let _ = std::fs::remove_file(&temp_path);format!(@@ -90,10 +83,7 @@ impl VectorDB {)})?;- // Atomic rename - guaranteed atomic on iOS/Android- // This will atomically replace the existing file- // The rename ensures we never have a partially written file,- // even if the app is suspended or crashes+ // Renaming prevents a suspension or crash from leaving a partial index.if let Err(e) = std::fs::rename(&temp_path, &self.path) {let _ = std::fs::remove_file(&temp_path);return Err(format!(@@ -368,7 +358,6 @@ impl VectorDB {let mut contained_keys = Vec::with_capacity(potential_keys.len());let mut actual_query_count = 0;- // Fill embeddings directly into flat storage using slicesfor key in potential_keys {if self.index.contains(*key) {let start_idx = actual_query_count * dimensions;@@ -388,7 +377,6 @@ impl VectorDB {let mut closeby_keys = vec![Vec::with_capacity(max_result_size); actual_query_count];let mut distances = vec![Vec::with_capacity(max_result_size); actual_query_count];- // Search using slices and fill pre-allocated containersfor i in 0..actual_query_count {let start_idx = i * dimensions;let end_idx = start_idx + dimensions;@@ -401,8 +389,6 @@ impl VectorDB {Ok((contained_keys, closeby_keys, distances))}- /// Check if a vector with the given key exists in the index.- /// `true` if the index contains the vector with the given key, `false` otherwise.pub fn contains_vector(&self, key: u64) -> bool {self.index.contains(key)}diff --git a/rust/crates/photos/src/ml/webgpu.rs b/rust/crates/photos/src/ml/webgpu.rsindex ebf7767390..a164b72154 100644--- a/rust/crates/photos/src/ml/webgpu.rs+++ b/rust/crates/photos/src/ml/webgpu.rs@@ -1,14 +1,7 @@-//! Immediately before a WebGPU session is built, a per-model counter file-//! next to the model is incremented and fsynced ("armed"). After-//! the session has been built *and* has survived one warm-up inference, the-//! file is removed ("disarmed"). A crash, kill, or soft failure in between-//! leaves the incremented counter behind. Once any model's counter reaches-//! [`MAX_CONSECUTIVE_FAILURES`], WebGPU is no longer attempted for models in-//! that directory β durably, across process restarts.-//!-//! Everything here is called from `onnx::build_session` while the caller-//! holds the per-model slot lock, so accesses to one model's counter file are-//! already serialized and no in-memory state is needed beyond the enable flag.+//! Durable WebGPU crash canary: arm before touching the driver and disarm only+//! after session construction and warm-up. Three recorded failures quarantine+//! the model directory across restarts. The caller's model-slot lock serializes+//! access.#[cfg(all(not(target_os = "windows"),@@ -31,8 +24,7 @@ use std::{path::{Path, PathBuf},};-/// Bump the version to discard all previous canary state, e.g. after a major-/// ONNX Runtime or Dawn upgrade that warrants re-trialing quarantined devices.+/// Bump to retry quarantined devices after major ONNX Runtime or Dawn changes.#[cfg(any(target_os = "android",target_os = "linux",@@ -59,21 +51,15 @@ pub(crate) fn set_enabled(enabled: bool) {let _ = enabled;}-/// The GPU adapter allowlist is deliberately not checked here: probing the-/// adapter touches the Vulkan driver, so it must run inside the armed canary-/// window (see `onnx::build_webgpu_session_with_canary`), where a probe crash-/// is recorded like any other WebGPU crash.+/// Adapter probing touches Vulkan and therefore happens after arming, not here.#[cfg(any(target_os = "android", target_os = "linux", target_os = "windows"))]pub(crate) fn attempt_permitted(model_path: &str) -> bool {WEBGPU_ENABLED.load(Ordering::Relaxed)&& model_dir(model_path).is_some_and(|dir| !quarantined(&dir))}-/// Vulkan vendor IDs of GPUs for which Chromium ships WebGPU on Android 12+,-/// mirroring `gpu/config/webgpu_blocklist_impl.cc` (Chromium main, 2026-07).-/// Notably absent, matching Chromium: Imagination/PowerVR (allowed there only-/// on Android 16+), Samsung Xclipse (still work-in-progress), and everything-/// else. Revisit whenever the pinned ONNX Runtime/Dawn build is bumped.+/// Mirrors Chromium's `gpu/config/webgpu_blocklist_impl.cc` Android 12+ policy+/// as of 2026-07; revisit with pinned ONNX Runtime or Dawn upgrades.#[cfg(any(target_os = "android", test))]const ALLOWLISTED_VULKAN_VENDOR_IDS: [u32; 3] = [0x13B5, // ARM (Mali, Immortalis)@@ -81,11 +67,7 @@ const ALLOWLISTED_VULKAN_VENDOR_IDS: [u32; 3] = [0x8086, // Intel];-/// WebGPU requires every enumerated adapter to be allowlisted: Dawn selects-/// its adapter independently of this probe, so a mixed set could otherwise-/// let Dawn pick a denied adapter. Android's Vulkan loader exposes a single-/// vendor driver in practice, so on real devices this is a single-adapter-/// check.+/// Dawn chooses independently, so every enumerated adapter must be allowlisted.#[cfg(any(target_os = "android", test))]fn vendors_allowlisted(vendor_ids: &[u32]) -> bool {!vendor_ids.is_empty()@@ -94,25 +76,16 @@ fn vendors_allowlisted(vendor_ids: &[u32]) -> bool {.all(|vendor_id| ALLOWLISTED_VULKAN_VENDOR_IDS.contains(vendor_id))}-/// `Denied` means the probe completed and the adapter is not allowlisted β a-/// clean policy decision.-/// `Failed` means the probe itself did not complete, which callers must treat-/// as a failed WebGPU attempt (counted by the crash canary) rather than a-/// policy decision: a driver that cannot even create a Vulkan instance must-/// eventually quarantine instead of being re-probed on every launch.#[cfg(target_os = "android")]#[derive(Clone, Copy, PartialEq, Eq, Debug)]pub(crate) enum AdapterCheck {Allowed,Denied,+ /// Probe failures count toward quarantine; policy denials do not.Failed,}-/// Keeping this inside the Rust eligibility path ensures an unsupported-/// adapter cannot be bypassed by any Dart inference entry point.-///-/// Must only be called inside an armed canary window: the probe is the first-/// code in the process to touch the Vulkan driver.+/// Must run inside an armed canary because this is the first Vulkan driver access.#[cfg(target_os = "android")]pub(crate) fn check_adapter() -> AdapterCheck {static VERDICT: OnceLock<AdapterCheck> = OnceLock::new();@@ -139,17 +112,14 @@ pub(crate) fn check_adapter() -> AdapterCheck {fn probe_vulkan_vendor_ids() -> Result<Vec<u32>, String> {use ash::vk;- // SAFETY: loads the system Vulkan loader (`libvulkan.so`, present on all- // Android 7+ devices); `entry` keeps the library loaded until it drops at- // the end of this function, after the instance has been destroyed.+ // SAFETY: loads Android's system Vulkan loader and keeps it alive through+ // instance destruction.let entry = unsafe { ash::Entry::load() }.map_err(|error| format!("loading Vulkan loader failed: {error}"))?;- // SAFETY: a default `InstanceCreateInfo` (Vulkan 1.0, no layers or- // extensions) is a valid instance description.+ // SAFETY: the default Vulkan 1.0 instance description is valid.let instance = unsafe { entry.create_instance(&vk::InstanceCreateInfo::default(), None) }.map_err(|error| format!("creating Vulkan instance failed: {error}"))?;- // SAFETY: `instance` is a live instance; it is destroyed below on every- // path and not used afterwards.+ // SAFETY: `instance` is live and is destroyed below before returning.let vendor_ids = unsafe { instance.enumerate_physical_devices() }.map(|devices| {devices@@ -164,9 +134,7 @@ fn probe_vulkan_vendor_ids() -> Result<Vec<u32>, String> {vendor_ids}-/// A durable record of an in-flight WebGPU attempt for one model. Dropping it-/// without calling [`ArmedCanary::disarm`] leaves the attempt recorded as-/// failed, which is exactly what a crash does implicitly.+/// Dropping without disarming intentionally preserves the failed-attempt record.#[cfg(any(target_os = "android",target_os = "linux",@@ -177,8 +145,6 @@ pub(crate) struct ArmedCanary {path: PathBuf,}-/// On error the caller must skip WebGPU (fail closed): without a durable-/// record, a crash during the attempt would go unnoticed.#[cfg(any(target_os = "android",target_os = "linux",@@ -358,8 +324,6 @@ mod tests {#[test]fn denies_when_any_adapter_is_not_allowlisted() {- // Dawn selects its adapter independently of the probe, so a mixed- // set must fail closed.assert!(!vendors_allowlisted(&[0x5143, 0x1AE0]));assert!(!vendors_allowlisted(&[0x1010, 0x13B5]));}@@ -383,7 +347,6 @@ mod tests {let dir = tempfile::tempdir().unwrap();let model = model_path(dir.path());- // Dropped without disarming, as after a crash or background kill.drop(arm_canary(&model, "clip-image").unwrap());assert!(!quarantined(dir.path()));