π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Delete model and pause indexing on corrupted ML model
laurenspriem41fd087cb3c1
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dartindex 0d64a2c72c..e9fe1fd3e9 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart@@ -81,8 +81,7 @@ class MLIndexingIsolate extends SuperIsolate {"Analyzing image ${instruction.fileKey} via rust or legacy: ${useRustMl ? "RUST" : "LEGACY"}",);- final resultJsonString =- await runInIsolate(IsolateOperation.analyzeImage, {+ final isolateResult = await runInIsolate(IsolateOperation.analyzeImage, {"enteFileID": instruction.fileKey,"filePath": filePath,"useRustMl": useRustMl,@@ -93,7 +92,17 @@ class MLIndexingIsolate extends SuperIsolate {"faceDetectionAddress": FaceDetectionService.instance.sessionAddress,"faceEmbeddingAddress": FaceEmbeddingService.instance.sessionAddress,"clipImageAddress": ClipImageEncoder.instance.sessionAddress,- }) as String?;+ });+ if (isolateResult is RustCorruptModelCacheDeletedException) {+ _logger.warning(+ "Deleted corrupt Rust ONNX model cache at ${isolateResult.modelPath}; "+ "stopping ML indexing for fileID ${instruction.fileKey}",+ );+ _cachedRustRuntimeArgs = null;+ shouldPauseIndexingAndClustering = true;+ throw isolateResult;+ }+ final resultJsonString = isolateResult as String?;if (resultJsonString == null) {if (!shouldPauseIndexingAndClustering) {_logger.severe('Analyzing image in isolate is giving back null');@@ -103,7 +112,8 @@ class MLIndexingIsolate extends SuperIsolate {result = MLResult.fromJsonString(resultJsonString);result.usedRustMl = useRustMl;} catch (e, s) {- if (isExpectedMlSkipError(e)) {+ if (e is RustCorruptModelCacheDeletedException ||+ isExpectedMlSkipError(e)) {rethrow;}_logger.severe(diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dartindex 8bae9fdbf1..d8640a7a2b 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart@@ -29,6 +29,7 @@ import "package:photos/services/machine_learning/ml_result.dart";import "package:photos/services/machine_learning/semantic_search/semantic_search_service.dart";import "package:photos/services/search_service.dart";import "package:photos/services/video_preview_service.dart";+import "package:photos/utils/isolate/isolate_operations.dart";import "package:photos/utils/ml_util.dart";import "package:photos/utils/network_util.dart";import "package:photos/utils/ram_check_util.dart";@@ -530,6 +531,10 @@ class MLService {"`indexAllImages()` finished. Analyzed $fileAnalyzedCount images, in ${stopwatch.elapsed.inSeconds} seconds (avg of ${stopwatch.elapsed.inSeconds / fileAnalyzedCount} seconds per image)",);_logStatus();+ } on RustCorruptModelCacheDeletedException catch (e) {+ _logger.warning(+ "Stopping image indexing because corrupt Rust ONNX model cache was deleted at ${e.modelPath}",+ );} catch (e, s) {_logger.severe("indexAllImages failed", e, s);} finally {@@ -752,7 +757,8 @@ class MLService {);// Check if there's no result simply because MLController paused indexingif (result == null) {- if (!_shouldPauseIndexingAndClustering) {+ if (!_shouldPauseIndexingAndClustering &&+ !MLIndexingIsolate.instance.shouldPauseIndexingAndClustering) {_logger.severe("Failed to analyze image with fileID: ${instruction.fileKey}",);@@ -901,6 +907,15 @@ class MLService {final String format = instruction.file.displayName.split('.').last;final int? size = instruction.file.fileSize;final fileType = instruction.file.fileType;+ if (e is RustCorruptModelCacheDeletedException) {+ pauseIndexingAndClustering();+ _logger.warning(+ "Stopping ML indexing for fileID ${instruction.fileKey} "+ "(format $format, type $fileType, size $size) because corrupt Rust "+ "ONNX model cache was deleted at ${e.modelPath}",+ );+ rethrow;+ }final bool acceptedIssue = isExpectedMlSkipError(e);if (acceptedIssue) {_logger.warning(diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dartindex 69ae162163..a3702e64e9 100644--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart@@ -1,3 +1,4 @@+import 'dart:io' show File;import 'dart:typed_data' show Float32List, Uint8List;import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;@@ -26,6 +27,15 @@ final Map<String, dynamic> _isolateCache = {};const _rustLibLoadedCacheKey = "rustLibLoaded";const _rustMlRuntimeConfigCacheKey = "rustMlRuntimeConfig";+class RustCorruptModelCacheDeletedException implements Exception {+ const RustCorruptModelCacheDeletedException(this.modelPath);++ final String modelPath;++ @override+ String toString() => "RustCorruptModelCacheDeletedException: $modelPath";+}+enum IsolateOperation {/// [MLIndexingIsolate]analyzeImage,@@ -123,9 +133,18 @@ Future<dynamic> isolateFunction(if (useRustMl) {await _ensureRustLoaded();}- final MLResult result = useRustMl- ? await analyzeImageRust(args)- : await analyzeImageStatic(args);+ final MLResult result;+ try {+ result = useRustMl+ ? await analyzeImageRust(args)+ : await analyzeImageStatic(args);+ } on rust_ml.RustMlError_CorruptModel catch (e) {+ final file = File(e.field0);+ if (await file.exists()) {+ await file.delete();+ }+ return RustCorruptModelCacheDeletedException(e.field0);+ }return result.toJsonString();/// MLIndexingIsolatediff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dartindex a32a789fbf..20597531c5 100644--- a/mobile/apps/photos/lib/utils/ml_util.dart+++ b/mobile/apps/photos/lib/utils/ml_util.dart@@ -946,6 +946,9 @@ Future<MLResult> analyzeImageRust(Map args) async {rustResult = await runRustAnalyzeForPath(imagePath);} catch (e, s) {if (!_isRustDecodeIssue(e)) {+ if (_isRustCorruptModelIssue(e)) {+ rethrow;+ }_logger.severe("Rust pipeline failed (non-decode) for fileID $enteFileID (format: $fileFormat)",e,@@ -1131,6 +1134,10 @@ bool _isRustDecodeIssue(Object error) {return error is rust_ml.RustMlError_Decode;}+bool _isRustCorruptModelIssue(Object error) {+ return error is rust_ml.RustMlError_CorruptModel;+}+String _normalizedErrorMessage(Object error) {if (error is PlatformException) {return <String>[diff --git a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs b/mobile/apps/photos/rust/src/api/ml_indexing_api.rsindex 761802e61c..9424695c58 100644--- a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs+++ b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs@@ -61,6 +61,7 @@ pub enum RustMlError {Decode(String),Preprocess(String),Ort(String),+ CorruptModel(String),Postprocess(String),Runtime(String),}@@ -245,6 +246,7 @@ impl From<SharedMlError> for RustMlError {SharedMlError::Decode(message) => RustMlError::Decode(message),SharedMlError::Preprocess(message) => RustMlError::Preprocess(message),SharedMlError::Ort(message) => RustMlError::Ort(message),+ SharedMlError::CorruptModel(message) => RustMlError::CorruptModel(message),SharedMlError::Postprocess(message) => RustMlError::Postprocess(message),SharedMlError::Runtime(message) => RustMlError::Runtime(message),}diff --git a/rust/photos/src/ml/error.rs b/rust/photos/src/ml/error.rsindex bf76b4be7a..f988ef0234 100644--- a/rust/photos/src/ml/error.rs+++ b/rust/photos/src/ml/error.rs@@ -12,6 +12,8 @@ pub enum MlError {Preprocess(String),#[error("onnx runtime error: {0}")]Ort(String),+ #[error("corrupt model: {0}")]+ CorruptModel(String),#[error("postprocess error: {0}")]Postprocess(String),#[error("runtime error: {0}")]diff --git a/rust/photos/src/ml/onnx.rs b/rust/photos/src/ml/onnx.rsindex d0d7e6f6f4..75cbd324a3 100644--- a/rust/photos/src/ml/onnx.rs+++ b/rust/photos/src/ml/onnx.rs@@ -55,12 +55,24 @@ pub fn build_session(model_path: &str, policy: &ExecutionProviderPolicy) -> MlRe));}+ if has_protobuf_parse_failure(&errors) {+ return Err(MlError::CorruptModel(model_path.to_string()));+ }+Err(MlError::Ort(format!("failed to create ONNX session for model '{model_path}' across EP fallbacks: {}",errors.join(" | "))))}+fn has_protobuf_parse_failure(errors: &[String]) -> bool {+ errors.iter().any(|error| {+ error+ .to_ascii_lowercase()+ .contains("protobuf parsing failed")+ })+}+fn providers_for_policy(policy: &ExecutionProviderPolicy,include_xnnpack: bool,@@ -201,3 +213,22 @@ pub fn run_i32_f32<const N: usize>(let data = tensor.iter().copied().collect::<Vec<_>>();Ok((shape, data))}++#[cfg(test)]+mod tests {+ use super::has_protobuf_parse_failure;++ #[test]+ fn detects_protobuf_parse_failure() {+ assert!(has_protobuf_parse_failure(&[String::from(+ "Load model failed:Protobuf parsing failed.",+ )]));+ }++ #[test]+ fn ignores_other_onnx_errors() {+ assert!(!has_protobuf_parse_failure(&[String::from(+ "Load model failed: missing initializer",+ )]));+ }+}