Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Fix pet ML isolation, Rust gating, and runtime race condition

Amrithesh Kakkoth Ente0dfbef7e8b1e
diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dart
index a788b92b5a..dea9b25325 100644
--- a/mobile/apps/photos/lib/db/ml/db.dart
+++ b/mobile/apps/photos/lib/db/ml/db.dart
@@ -56,6 +56,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
final String _databaseName;
final ClipVectorDB _clipVectorDB;
final ClusterCentroidVectorDB _clusterCentroidVectorDB;
+ final bool _isOffline;
final List<String> _migrationScripts;
int _clusterSummaryMutationVersion = 0;
Future<void>? _clipVectorDbRecoveryFuture;
@@ -71,11 +72,13 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
String databaseName = "ente.ml.db",
ClipVectorDB? clipVectorDB,
ClusterCentroidVectorDB? clusterCentroidVectorDB,
+ bool isOffline = false,
List<String>? migrationScripts,
}) : _databaseName = databaseName,
_clipVectorDB = clipVectorDB ?? ClipVectorDB.instance,
_clusterCentroidVectorDB =
clusterCentroidVectorDB ?? ClusterCentroidVectorDB.instance,
+ _isOffline = isOffline,
_migrationScripts = migrationScripts ?? _defaultMigrationScripts;
static final MLDataDB instance = MLDataDB._privateConstructor();
@@ -83,6 +86,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
databaseName: "ente.ml.offline.db",
clipVectorDB: ClipVectorDB.offlineInstance,
clusterCentroidVectorDB: ClusterCentroidVectorDB.offlineInstance,
+ isOffline: true,
migrationScripts: _offlineMigrationScripts,
);
@@ -327,6 +331,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
final vdb = PetVectorDB.forModel(
species: entry.key,
isFace: true,
+ offline: _isOffline,
);
final petFaceIds = entry.value.map((e) => e.$1.petFaceId).toList();
final idMap = await vdb.getPetFaceVectorIdMap(
@@ -387,6 +392,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
final vdb = PetVectorDB.forModel(
species: entry.key,
isFace: false,
+ offline: _isOffline,
);
final bodyIds = entry.value.map((e) => e.$1.petBodyId).toList();
final idMap = await vdb.getObjectVectorIdMap(
@@ -571,7 +577,9 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
await db.execute(deletePetBodiesTable);
await db.execute(deletePetFaceVectorIdMappingTable);
await db.execute(deletePetBodyVectorIdMappingTable);
- for (final vdb in PetVectorDB.allInstances) {
+ final petVdbs =
+ _isOffline ? PetVectorDB.allOfflineInstances : PetVectorDB.allInstances;
+ for (final vdb in petVdbs) {
await vdb.deleteIndexFile();
}
_markClusterSummaryMutated();
diff --git a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart b/mobile/apps/photos/lib/db/ml/pet_vector_db.dart
index 6384a0f61f..c346968d2b 100644
--- a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart
+++ b/mobile/apps/photos/lib/db/ml/pet_vector_db.dart
@@ -38,7 +38,7 @@ class PetVectorDB {
this._embeddingDimension,
);
- // ── 4 separate vector spaces, one per model ──
+ // ── Online vector spaces ──
static final dogFace = PetVectorDB._named(
"ente.ml.vectordb.pet.dog_face.usearch",
@@ -60,7 +60,29 @@ class PetVectorDB {
BigInt.from(bodyDimension),
);
- /// All 4 vector DB instances for iteration.
+ // ── Offline vector spaces ──
+
+ static final offlineDogFace = PetVectorDB._named(
+ "ente.ml.offline.vectordb.pet.dog_face.usearch",
+ BigInt.from(faceDimension),
+ );
+
+ static final offlineCatFace = PetVectorDB._named(
+ "ente.ml.offline.vectordb.pet.cat_face.usearch",
+ BigInt.from(faceDimension),
+ );
+
+ static final offlineDogBody = PetVectorDB._named(
+ "ente.ml.offline.vectordb.pet.dog_body.usearch",
+ BigInt.from(bodyDimension),
+ );
+
+ static final offlineCatBody = PetVectorDB._named(
+ "ente.ml.offline.vectordb.pet.cat_body.usearch",
+ BigInt.from(bodyDimension),
+ );
+
+ /// All online vector DB instances for iteration.
static final List<PetVectorDB> allInstances = [
dogFace,
catFace,
@@ -68,10 +90,29 @@ class PetVectorDB {
catBody,
];
+ /// All offline vector DB instances for iteration.
+ static final List<PetVectorDB> allOfflineInstances = [
+ offlineDogFace,
+ offlineCatFace,
+ offlineDogBody,
+ offlineCatBody,
+ ];
+
/// Get the correct vector DB for a species + embedding type.
/// [species]: 0 = dog, 1 = cat
/// [isFace]: true = face embedding, false = body embedding
- static PetVectorDB forModel({required int species, required bool isFace}) {
+ static PetVectorDB forModel({
+ required int species,
+ required bool isFace,
+ bool offline = false,
+ }) {
+ if (offline) {
+ if (species == 0) {
+ return isFace ? offlineDogFace : offlineDogBody;
+ } else {
+ return isFace ? offlineCatFace : offlineCatBody;
+ }
+ }
if (species == 0) {
return isFace ? dogFace : dogBody;
} else {
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 1a483e8000..469b1032ad 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -77,7 +77,9 @@ Future<IndexStatus> getIndexStatus() async {
final int facesIndexedFiles = await mlDataDB.getFaceIndexedFileCount();
final int clipIndexedFiles = await mlDataDB.getClipIndexedFileCount();
int indexedFiles = math.min(facesIndexedFiles, clipIndexedFiles);
- if (flagService.internalUser && localSettings.petRecognitionEnabled) {
+ if (flagService.internalUser &&
+ localSettings.petRecognitionEnabled &&
+ (flagService.useRustForML || isOfflineMode)) {
final int petIndexedFiles = await mlDataDB.getPetIndexedFileCount();
indexedFiles = math.min(indexedFiles, petIndexedFiles);
}
@@ -109,8 +111,9 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
final Map<int, int> faceIndexedFileIDs = await mlDataDB.faceIndexedFileIds();
final Map<int, int> clipIndexedFileIDs =
await mlDataDB.clipIndexedFileWithVersion();
- final bool petEnabled =
- flagService.internalUser && localSettings.petRecognitionEnabled;
+ final bool petEnabled = flagService.internalUser &&
+ localSettings.petRecognitionEnabled &&
+ (flagService.useRustForML || isOfflineMode);
final Map<int, int> petIndexedFileIDs =
petEnabled ? await mlDataDB.petIndexedFileIds() : const {};
final Set<int> queuedFiledIDs = {};
@@ -225,8 +228,9 @@ Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing() async {
final Map<int, int> faceIndexedFileIDs = await mlDataDB.faceIndexedFileIds();
final Map<int, int> clipIndexedFileIDs =
await mlDataDB.clipIndexedFileWithVersion();
- final bool petEnabled =
- flagService.internalUser && localSettings.petRecognitionEnabled;
+ final bool petEnabled = flagService.internalUser &&
+ localSettings.petRecognitionEnabled &&
+ (flagService.useRustForML || isOfflineMode);
final Map<int, int> petIndexedFileIDs =
petEnabled ? await mlDataDB.petIndexedFileIds() : const {};
final Set<int> queuedFileIDs = {};
diff --git a/mobile/apps/photos/rust/src/ml/runtime.rs b/mobile/apps/photos/rust/src/ml/runtime.rs
index 8e5a38b222..055ecd472e 100644
--- a/mobile/apps/photos/rust/src/ml/runtime.rs
+++ b/mobile/apps/photos/rust/src/ml/runtime.rs
@@ -269,34 +269,43 @@ fn write_runtime() -> std::sync::RwLockWriteGuard<'static, Option<RuntimeState>>
}
pub fn ensure_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
- let rebuild_config = {
+ // Fast path: check under read lock whether the current runtime can serve.
+ {
let guard = read_runtime();
- match guard.as_ref() {
- Some(existing) => {
- if existing.config.provider_policy == config.provider_policy
- && existing.config.model_paths.can_serve(&config.model_paths)
- {
- None // existing runtime can handle this request
- } else {
- // Merge: keep already-known paths, add/update from request
- Some(MlRuntimeConfig {
- model_paths: existing.config.model_paths.merge(&config.model_paths),
- provider_policy: config.provider_policy.clone(),
- })
- }
+ if let Some(existing) = guard.as_ref() {
+ if existing.config.provider_policy == config.provider_policy
+ && existing.config.model_paths.can_serve(&config.model_paths)
+ {
+ return Ok(()); // existing runtime handles this request
}
- None => Some(config.clone()),
}
+ }
+
+ // Slow path: acquire write lock, re-check (another thread may have
+ // already merged), compute the merged config, build, and install.
+ let mut guard = write_runtime();
+ let merged = match guard.as_ref() {
+ Some(existing) => {
+ // Re-check: a concurrent caller may have updated since the
+ // read-lock check above.
+ if existing.config.provider_policy == config.provider_policy
+ && existing.config.model_paths.can_serve(&config.model_paths)
+ {
+ return Ok(());
+ }
+ MlRuntimeConfig {
+ model_paths: existing.config.model_paths.merge(&config.model_paths),
+ provider_policy: config.provider_policy.clone(),
+ }
+ }
+ None => config.clone(),
};
- if let Some(merged) = rebuild_config {
- let runtime = create_runtime(&merged);
- let mut guard = write_runtime();
- *guard = Some(RuntimeState {
- config: merged,
- runtime,
- });
- }
+ let runtime = create_runtime(&merged);
+ *guard = Some(RuntimeState {
+ config: merged,
+ runtime,
+ });
Ok(())
}