π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Better ML model lifecycle management for rust indexing
laurenspriem55e90a1a5cb7
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 88f8e86033..47e55c9006 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@@ -36,6 +36,7 @@ class MLIndexingIsolate extends SuperIsolate {final _initModelLock = Lock();final _downloadModelLock = Lock();+ final _rustRuntimeLock = Lock();bool areModelsDownloaded = false;@@ -69,19 +70,8 @@ class MLIndexingIsolate extends SuperIsolate {try {final useRustMl = _shouldUseRustMl;- String? faceDetectionModelPath;- String? faceEmbeddingModelPath;- String? clipImageModelPath;- if (useRustMl) {- final faceDetection =- await FaceDetectionService.instance.getModelNameAndPath();- faceDetectionModelPath = faceDetection.$2;- final faceEmbedding =- await FaceEmbeddingService.instance.getModelNameAndPath();- faceEmbeddingModelPath = faceEmbedding.$2;- final clipImage = await ClipImageEncoder.instance.getModelNameAndPath();- clipImageModelPath = clipImage.$2;- }+ final rustRuntimeArgs =+ useRustMl ? await _buildRustRuntimeArgs() : const <String, dynamic>{};_logger.info("Analyzing image ${instruction.fileKey} via rust or legacy: ${useRustMl ? "RUST" : "LEGACY"}",);@@ -93,12 +83,7 @@ class MLIndexingIsolate extends SuperIsolate {"useRustMl": useRustMl,"runFaces": instruction.shouldRunFaces,"runClip": instruction.shouldRunClip,- "faceDetectionModelPath": faceDetectionModelPath,- "faceEmbeddingModelPath": faceEmbeddingModelPath,- "clipImageModelPath": clipImageModelPath,- "preferCoreml": Platform.isIOS,- "preferNnapi": Platform.isAndroid,- "allowCpuFallback": true,+ ...rustRuntimeArgs,"faceDetectionAddress": FaceDetectionService.instance.sessionAddress,"faceEmbeddingAddress": FaceEmbeddingService.instance.sessionAddress,"clipImageAddress": ClipImageEncoder.instance.sessionAddress,@@ -127,6 +112,35 @@ class MLIndexingIsolate extends SuperIsolate {bool get _shouldUseRustMl => flagService.useRustForML;+ Future<void> prepareRustRuntime() async {+ if (!_shouldUseRustMl) {+ return;+ }+ return _rustRuntimeLock.synchronized(() async {+ final rustRuntimeArgs = await _buildRustRuntimeArgs();+ await runInIsolate(+ IsolateOperation.prepareRustMlRuntime,+ rustRuntimeArgs,+ );+ });+ }++ Future<void> releaseRustRuntime() async {+ if (!isIsolateSpawned) {+ return;+ }+ return _rustRuntimeLock.synchronized(() async {+ if (!isIsolateSpawned) {+ return;+ }+ try {+ await runInIsolate(IsolateOperation.releaseRustMlRuntime, {});+ } catch (e, s) {+ _logger.warning("Could not release rust runtime in isolate", e, s);+ }+ });+ }+void triggerModelsDownload() {if (!areModelsDownloaded && !_downloadModelLock.locked) {_logger.info("Models not downloaded, starting download");@@ -257,6 +271,7 @@ class MLIndexingIsolate extends SuperIsolate {}Future<void> cleanupLocalIndexingModels({bool delete = false}) async {+ await releaseRustRuntime();if (!areModelsDownloaded) return;await _releaseModels();@@ -308,4 +323,20 @@ class MLIndexingIsolate extends SuperIsolate {rethrow;}}++ Future<Map<String, dynamic>> _buildRustRuntimeArgs() async {+ final faceDetection =+ await FaceDetectionService.instance.getModelNameAndPath();+ final faceEmbedding =+ await FaceEmbeddingService.instance.getModelNameAndPath();+ final clipImage = await ClipImageEncoder.instance.getModelNameAndPath();+ return {+ "faceDetectionModelPath": faceDetection.$2,+ "faceEmbeddingModelPath": faceEmbedding.$2,+ "clipImageModelPath": clipImage.$2,+ "preferCoreml": Platform.isIOS,+ "preferNnapi": Platform.isAndroid,+ "allowCpuFallback": true,+ };+ }}diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dartindex c308847c89..657d1a1e00 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart@@ -260,6 +260,7 @@ class MLService {Future<void> fetchAndIndexAllImages({required MLMode mode}) async {if (!_canRunMLFunction(function: "Indexing")) return;+ bool rustRuntimePrepared = false;try {_isIndexingOrClusteringRunning = true;_logger.info('starting image indexing');@@ -281,6 +282,10 @@ class MLService {break stream;}if (!localSettings.isMLLocalIndexingEnabled) {+ if (rustRuntimePrepared) {+ await MLIndexingIsolate.instance.releaseRustRuntime();+ rustRuntimePrepared = false;+ }await MLIndexingIsolate.instance.cleanupLocalIndexingModels();continue;} else if (!await canUseHighBandwidth()) {@@ -290,6 +295,10 @@ class MLService {break stream;} else {await MLIndexingIsolate.instance.ensureDownloadedModels();+ if (flagService.useRustForML && !rustRuntimePrepared) {+ await MLIndexingIsolate.instance.prepareRustRuntime();+ rustRuntimePrepared = true;+ }}final futures = <Future<bool>>[];for (final instruction in chunk) {@@ -323,6 +332,7 @@ class MLService {} catch (e, s) {_logger.severe("indexAllImages failed", e, s);} finally {+ await MLIndexingIsolate.instance.releaseRustRuntime();_isIndexingOrClusteringRunning = false;_cancelPauseIndexingAndClustering();}diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dartindex e22415e26f..27cb315257 100644--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart@@ -18,11 +18,19 @@ import "package:photos/utils/image_ml_util.dart";import "package:photos/utils/ml_util.dart";final Map<String, dynamic> _isolateCache = {};+const _rustLibLoadedCacheKey = "rustLibLoaded";+const _rustMlRuntimeConfigCacheKey = "rustMlRuntimeConfig";enum IsolateOperation {/// [MLIndexingIsolate]analyzeImage,+ /// [MLIndexingIsolate]+ prepareRustMlRuntime,++ /// [MLIndexingIsolate]+ releaseRustMlRuntime,+/// [MLIndexingIsolate]loadIndexingModels,@@ -102,6 +110,17 @@ Future<dynamic> isolateFunction(: await analyzeImageStatic(args);return result.toJsonString();+ /// MLIndexingIsolate+ case IsolateOperation.prepareRustMlRuntime:+ await _ensureRustLoaded();+ await _ensureRustRuntimePrepared(args);+ return true;++ /// MLIndexingIsolate+ case IsolateOperation.releaseRustMlRuntime:+ await _releaseRustRuntime();+ return true;+/// MLIndexingIsolatecase IsolateOperation.loadIndexingModels:final modelNames = args['modelNames'] as List<String>;@@ -229,22 +248,88 @@ Future<dynamic> isolateFunction(}Future<void> _ensureRustLoaded() async {- final bool loaded = _isolateCache["rustLibLoaded"] as bool? ?? false;+ final bool loaded = _isolateCache[_rustLibLoadedCacheKey] as bool? ?? false;if (!loaded) {await EntePhotosRust.init();- _isolateCache["rustLibLoaded"] = true;+ _isolateCache[_rustLibLoadedCacheKey] = true;}}Future<void> _ensureRustDisposed() async {- final bool loaded = _isolateCache["rustLibLoaded"] as bool? ?? false;+ final bool loaded = _isolateCache[_rustLibLoadedCacheKey] as bool? ?? false;if (loaded) {- try {- await rust_ml.releaseMlRuntime();- } catch (_) {- // no-op: runtime release is best-effort before process-wide bridge dispose.- }+ await _releaseRustRuntime();EntePhotosRust.dispose();- _isolateCache.remove("rustLibLoaded");+ _isolateCache.remove(_rustLibLoadedCacheKey);+ }+}++Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {+ final modelPaths = rust_ml.RustModelPaths(+ faceDetection: (args["faceDetectionModelPath"] as String?) ?? "",+ faceEmbedding: (args["faceEmbeddingModelPath"] as String?) ?? "",+ clipImage: (args["clipImageModelPath"] as String?) ?? "",+ );+ final providerPolicy = rust_ml.RustExecutionProviderPolicy(+ preferCoreml: args["preferCoreml"] as bool? ?? true,+ preferNnapi: args["preferNnapi"] as bool? ?? true,+ allowCpuFallback: args["allowCpuFallback"] as bool? ?? true,+ );+ final runtimeConfigKey = _runtimeConfigCacheKey(modelPaths, providerPolicy);+ final currentConfigKey =+ _isolateCache[_rustMlRuntimeConfigCacheKey] as String?;+ if (currentConfigKey == runtimeConfigKey) {+ return;}++ final missingModelPaths = <String>[];+ if (modelPaths.faceDetection.trim().isEmpty) {+ missingModelPaths.add("faceDetectionModelPath");+ }+ if (modelPaths.faceEmbedding.trim().isEmpty) {+ missingModelPaths.add("faceEmbeddingModelPath");+ }+ if (modelPaths.clipImage.trim().isEmpty) {+ missingModelPaths.add("clipImageModelPath");+ }+ if (missingModelPaths.isNotEmpty) {+ throw Exception(+ "RustMLMissingModelPath: Missing required model paths: ${missingModelPaths.join(', ')}",+ );+ }++ await rust_ml.initMlRuntime(+ config: rust_ml.RustMlRuntimeConfig(+ modelPaths: modelPaths,+ providerPolicy: providerPolicy,+ ),+ );+ _isolateCache[_rustMlRuntimeConfigCacheKey] = runtimeConfigKey;+}++Future<void> _releaseRustRuntime() async {+ final bool loaded = _isolateCache[_rustLibLoadedCacheKey] as bool? ?? false;+ if (!loaded) {+ return;+ }+ try {+ await rust_ml.releaseMlRuntime();+ } catch (_) {+ // no-op: runtime release is best-effort before process-wide bridge dispose.+ }+ _isolateCache.remove(_rustMlRuntimeConfigCacheKey);+}++String _runtimeConfigCacheKey(+ rust_ml.RustModelPaths modelPaths,+ rust_ml.RustExecutionProviderPolicy providerPolicy,+) {+ return [+ modelPaths.faceDetection,+ modelPaths.faceEmbedding,+ modelPaths.clipImage,+ providerPolicy.preferCoreml,+ providerPolicy.preferNnapi,+ providerPolicy.allowCpuFallback,+ ].join("|");}diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dartindex ef6ad99b23..8201f4f56b 100644--- a/mobile/apps/photos/lib/utils/ml_util.dart+++ b/mobile/apps/photos/lib/utils/ml_util.dart@@ -639,12 +639,6 @@ Future<MLResult> analyzeImageRust(Map args) async {preferNnapi: preferNnapi,allowCpuFallback: allowCpuFallback,);- await rust_ml.initMlRuntime(- config: rust_ml.RustMlRuntimeConfig(- modelPaths: modelPaths,- providerPolicy: providerPolicy,- ),- );final rustResult = await rust_ml.analyzeImageRust(req: rust_ml.AnalyzeImageRequest(