π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
vector DB for face cluster centroids
laurenspriemb6ba93a01e21
diff --git a/mobile/apps/photos/lib/db/ml/clip_vector_db.dart b/mobile/apps/photos/lib/db/ml/clip_vector_db.dartindex 433b046ddd..904b45ac12 100644--- a/mobile/apps/photos/lib/db/ml/clip_vector_db.dart+++ b/mobile/apps/photos/lib/db/ml/clip_vector_db.dart@@ -63,7 +63,7 @@ class ClipVectorDB {} catch (e, s) {_logger.severe("Could not open VectorDB at path $dbPath", e, s);_logger.severe("Deleting the index file and trying again");- await deleteIndexFile(undoMigration: true);+ await deleteIndexFile();try {vectorDB = VectorDb(filePath: dbPath,@@ -397,7 +397,7 @@ class ClipVectorDB {}}- Future<void> deleteIndexFile({bool undoMigration = false}) async {+ Future<void> deleteIndexFile() async {try {final documentsDirectory = await getApplicationDocumentsDirectory();final String dbPath = join(documentsDirectory.path, _databaseName);@@ -409,11 +409,6 @@ class ClipVectorDB {_logger.info("Deleted index file on disk");_vectorDbFuture = null;_warmupFuture = null;- if (!undoMigration) {- _logger.info(- "Index file was deleted without explicit undo flag; invalidating migration state regardless.",- );- }await invalidateMigrationState();} catch (e, s) {_logger.severe("Error deleting index file on disk", e, s);diff --git a/mobile/apps/photos/lib/db/ml/cluster_centroid_vector_db.dart b/mobile/apps/photos/lib/db/ml/cluster_centroid_vector_db.dartnew file mode 100644index 0000000000..eabe429c09--- /dev/null+++ b/mobile/apps/photos/lib/db/ml/cluster_centroid_vector_db.dart@@ -0,0 +1,344 @@+import "dart:io" show File;+import "dart:typed_data" show Float32List;++import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;+import "package:logging/logging.dart";+import "package:path/path.dart";+import "package:path_provider/path_provider.dart";+import "package:photos/src/rust/api/usearch_api.dart";+import "package:shared_preferences/shared_preferences.dart";++class ClusterCentroidVectorDB {+ static final Logger _logger = Logger("ClusterCentroidVectorDB");++ final String _databaseName;+ final String _migrationKey;++ static const int embeddingDimensions = 192;+ static final BigInt _embeddingDimension = BigInt.from(embeddingDimensions);++ static Logger get logger => _logger;++ ClusterCentroidVectorDB._privateConstructor(+ this._databaseName,+ this._migrationKey,+ );++ static final instance = ClusterCentroidVectorDB._privateConstructor(+ "ente.ml.vectordb.cluster_centroid.usearch",+ "cluster_centroid_vectordb_migration",+ );+ static final offlineInstance = ClusterCentroidVectorDB._privateConstructor(+ "ente.ml.offline.vectordb.cluster_centroid.usearch",+ "cluster_centroid_vectordb_migration_offline",+ );++ factory ClusterCentroidVectorDB() => instance;++ Future<VectorDb>? _vectorDbFuture;+ Future<void>? _warmupFuture;++ Future<VectorDb> get _vectorDB async {+ _vectorDbFuture ??= _initVectorDB();+ return _vectorDbFuture!;+ }++ bool? _migrationDone;++ Future<VectorDb> _initVectorDB() async {+ final documentsDirectory = await getApplicationDocumentsDirectory();+ final String dbPath = join(documentsDirectory.path, _databaseName);+ _logger.info("Opening cluster centroid vector DB access: DB path $dbPath");+ final indexFile = File(dbPath);+ if (!await indexFile.exists() && await checkIfMigrationDone()) {+ _logger.severe(+ "Cluster centroid vector DB file is missing while migration is marked done. Invalidating migration state.",+ );+ await invalidateMigrationState();+ }++ late VectorDb vectorDB;+ try {+ vectorDB = VectorDb(+ filePath: dbPath,+ dimensions: _embeddingDimension,+ );+ } catch (e, s) {+ _logger.severe(+ "Could not open cluster centroid vector DB at path $dbPath",+ e,+ s,+ );+ _logger.severe("Deleting the index file and trying again");+ await deleteIndexFile();+ try {+ vectorDB = VectorDb(+ filePath: dbPath,+ dimensions: _embeddingDimension,+ );+ } catch (e, s) {+ _logger.severe(+ "Still can't open cluster centroid vector DB at path $dbPath",+ e,+ s,+ );+ rethrow;+ }+ }++ final stats = await getIndexStats(vectorDB);+ _logger.info(+ "Cluster centroid vector DB connection opened with stats: ${stats.toString()}",+ );++ return vectorDB;+ }++ Future<bool> checkIfMigrationDone() async {+ if (_migrationDone != null) return _migrationDone!;+ _logger.info("Checking if cluster centroid vector DB migration has run");+ final prefs = await SharedPreferences.getInstance();+ final migrationDone = prefs.getBool(_migrationKey) ?? false;+ if (migrationDone) {+ _logger.info("Cluster centroid vector DB migration already done");+ _migrationDone = true;+ return _migrationDone!;+ } else {+ _logger.info("Cluster centroid vector DB migration not done");+ _migrationDone = false;+ return _migrationDone!;+ }+ }++ Future<void> setMigrationDone() async {+ _logger.info("Setting cluster centroid vector DB migration done");+ final prefs = await SharedPreferences.getInstance();+ await prefs.setBool(_migrationKey, true);+ _migrationDone = true;+ }++ Future<void> invalidateMigrationState() async {+ _logger.info("Invalidating cluster centroid vector DB migration state");+ final prefs = await SharedPreferences.getInstance();+ await prefs.setBool(_migrationKey, false);+ _migrationDone = false;+ }++ Future<void> insertCentroid({+ required int clusterVectorID,+ required List<double> centroid,+ }) async {+ final db = await _vectorDB;+ try {+ await db.addVector(key: BigInt.from(clusterVectorID), vector: centroid);+ } catch (e, s) {+ _logger.severe("Error inserting cluster centroid", e, s);+ rethrow;+ }+ }++ Future<void> bulkInsertCentroids({+ required List<int> clusterVectorIDs,+ required List<Float32List> centroids,+ }) async {+ if (clusterVectorIDs.isEmpty || centroids.isEmpty) {+ return;+ }+ final db = await _vectorDB;+ try {+ await db.bulkAddVectors(+ keys: Uint64List.fromList(clusterVectorIDs),+ vectors: centroids,+ );+ } catch (e, s) {+ _logger.severe("Error bulk inserting cluster centroids", e, s);+ rethrow;+ }+ }++ Future<void> deleteCentroids(List<int> clusterVectorIDs) async {+ if (clusterVectorIDs.isEmpty) {+ return;+ }+ final db = await _vectorDB;+ try {+ final deletedCount = await db.bulkRemoveVectors(+ keys: Uint64List.fromList(clusterVectorIDs),+ );+ _logger.info(+ "Deleted $deletedCount centroids from ${clusterVectorIDs.length} keys",+ );+ } catch (e, s) {+ _logger.severe("Error bulk deleting specific centroids", e, s);+ rethrow;+ }+ }++ Future<void> deleteAllCentroids() async {+ await invalidateMigrationState();+ final db = await _vectorDB;+ try {+ await db.resetIndex();+ } catch (e, s) {+ _logger.severe("Error deleting all cluster centroids", e, s);+ rethrow;+ }+ }++ Future<ClusterCentroidVectorDbStats> getIndexStats([VectorDb? db]) async {+ db ??= await _vectorDB;+ try {+ final stats = await db.getIndexStats();+ return ClusterCentroidVectorDbStats(+ size: stats.$1.toInt(),+ capacity: stats.$2.toInt(),+ dimensions: stats.$3.toInt(),+ fileSize: stats.$4.toInt(),+ memoryUsage: stats.$5.toInt(),+ expansionAdd: stats.$6.toInt(),+ expansionSearch: stats.$7.toInt(),+ );+ } catch (e, s) {+ _logger.severe("Error getting cluster centroid index stats", e, s);+ rethrow;+ }+ }++ Future<List<(int, double)>> searchApproxClosestCentroidsWithinDistance(+ List<double> query,+ Set<int> allowedClusterVectorIDs, {+ required double maxDistance,+ int count = 10,+ }) async {+ if (!await checkIfMigrationDone()) {+ throw StateError(+ "Cluster centroid vector DB migration is not done, cannot run approximate search",+ );+ }+ if (count <= 0 || allowedClusterVectorIDs.isEmpty) {+ return const [];+ }+ final db = await _vectorDB;+ try {+ final allowedKeys = Uint64List.fromList(+ allowedClusterVectorIDs.toList(growable: false),+ );+ final result = await db.approxFilteredSearchVectorsWithinDistance(+ query: query,+ allowedKeys: allowedKeys,+ count: BigInt.from(count),+ maxDistance: maxDistance,+ );+ final keys = result.$1;+ final distances = result.$2;+ final output = <(int, double)>[];+ for (var i = 0; i < keys.length; i++) {+ output.add((keys[i].toInt(), distances[i]));+ }+ return output;+ } catch (e, s) {+ _logger.severe("Error searching filtered centroids", e, s);+ rethrow;+ }+ }++ Future<void> warmupApproxSearch() async {+ _warmupFuture ??= _warmupApproxSearchInternal();+ await _warmupFuture;+ }++ Future<void> _warmupApproxSearchInternal() async {+ final stopwatch = Stopwatch()..start();+ try {+ final db = await _vectorDB;+ final stats = await getIndexStats(db);+ if (stats.size == 0) {+ _logger+ .info("Skipping cluster centroid vector DB warmup: index is empty");+ return;+ }++ final warmupQuery = List<double>.filled(+ stats.dimensions,+ 0.0,+ growable: false,+ );+ await db.searchVectors(+ query: warmupQuery,+ count: BigInt.one,+ exact: false,+ );+ _logger.info(+ "Cluster centroid vector DB warmup finished in ${stopwatch.elapsedMilliseconds} ms",+ );+ } catch (e, s) {+ _logger.warning("Cluster centroid vector DB warmup failed", e, s);+ _warmupFuture = null;+ } finally {+ stopwatch.stop();+ }+ }++ Future<void> deleteIndex() async {+ await invalidateMigrationState();+ final db = await _vectorDB;+ try {+ await db.deleteIndex();+ _vectorDbFuture = null;+ _warmupFuture = null;+ } catch (e, s) {+ _logger.severe("Error deleting cluster centroid index", e, s);+ rethrow;+ }+ }++ Future<void> deleteIndexFile() async {+ try {+ final documentsDirectory = await getApplicationDocumentsDirectory();+ final String dbPath = join(documentsDirectory.path, _databaseName);+ _logger.info("Delete cluster centroid index file: DB path $dbPath");+ final file = File(dbPath);+ if (await file.exists()) {+ await file.delete();+ }+ _logger.info("Deleted cluster centroid index file on disk");+ _vectorDbFuture = null;+ _warmupFuture = null;+ await invalidateMigrationState();+ } catch (e, s) {+ _logger.severe(+ "Error deleting cluster centroid index file on disk",+ e,+ s,+ );+ rethrow;+ }+ }+}++class ClusterCentroidVectorDbStats {+ final int size;+ final int capacity;+ final int dimensions;++ final int fileSize;+ final int memoryUsage;++ final int expansionAdd;+ final int expansionSearch;++ ClusterCentroidVectorDbStats({+ required this.size,+ required this.capacity,+ required this.dimensions,+ required this.fileSize,+ required this.memoryUsage,+ required this.expansionAdd,+ required this.expansionSearch,+ });++ @override+ String toString() {+ return "ClusterCentroidVectorDbStats(size: $size, capacity: $capacity, dimensions: $dimensions, file size on disk (bytes): $fileSize, memory usage (bytes): $memoryUsage, expansionAdd: $expansionAdd, expansionSearch: $expansionSearch)";+ }+}diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dartindex a786518e7a..6c36ab5e93 100644--- a/mobile/apps/photos/lib/db/ml/db.dart+++ b/mobile/apps/photos/lib/db/ml/db.dart@@ -11,9 +11,11 @@ import "package:photos/core/event_bus.dart";import "package:photos/db/common/base.dart";import "package:photos/db/ml/base.dart";import "package:photos/db/ml/clip_vector_db.dart";+import "package:photos/db/ml/cluster_centroid_vector_db.dart";import "package:photos/db/ml/db_model_mappers.dart";import 'package:photos/db/ml/schema.dart';import "package:photos/events/embedding_updated_event.dart";+import "package:photos/generated/protos/ente/common/vector.pb.dart";import "package:photos/models/ml/clip.dart";import "package:photos/models/ml/face/face.dart";import "package:photos/models/ml/face/face_with_embedding.dart";@@ -48,20 +50,25 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final String _databaseName;final ClipVectorDB _clipVectorDB;+ final ClusterCentroidVectorDB _clusterCentroidVectorDB;final List<String> _migrationScripts;MLDataDB._privateConstructor({String databaseName = "ente.ml.db",ClipVectorDB? clipVectorDB,+ ClusterCentroidVectorDB? clusterCentroidVectorDB,List<String>? migrationScripts,}) : _databaseName = databaseName,_clipVectorDB = clipVectorDB ?? ClipVectorDB.instance,+ _clusterCentroidVectorDB =+ clusterCentroidVectorDB ?? ClusterCentroidVectorDB.instance,_migrationScripts = migrationScripts ?? _defaultMigrationScripts;static final MLDataDB instance = MLDataDB._privateConstructor();static final MLDataDB offlineInstance = MLDataDB._privateConstructor(databaseName: "ente.ml.offline.db",clipVectorDB: ClipVectorDB.offlineInstance,+ clusterCentroidVectorDB: ClusterCentroidVectorDB.offlineInstance,migrationScripts: _offlineMigrationScripts,);@@ -76,6 +83,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {createFileDataTable,createFaceCacheTable,createTextEmbeddingsCacheTable,+ createClusterCentroidVectorIdMappingTable,];static const List<String> _offlineMigrationScripts = [..._defaultMigrationScripts,@@ -274,12 +282,12 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {await db.execute(deleteFaceClustersTable);await db.execute(deleteClusterPersonTable);await db.execute(deleteClusterSummaryTable);+ await db.execute(deleteClusterCentroidVectorIdMappingTable);await db.execute(deleteNotPersonFeedbackTable);await db.execute(deleteClipEmbeddingsTable);await db.execute(deleteFileDataTable);- if (await _clipVectorDB.checkIfMigrationDone()) {- await _clipVectorDB.deleteIndexFile(undoMigration: true);- }+ await _clipVectorDB.deleteIndexFile();+ await _clusterCentroidVectorDB.deleteIndexFile();}@override@@ -1058,10 +1066,73 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {});}+ Future<Map<String, int>> getClusterCentroidVectorIdMap(+ Iterable<String> clusterIDs, {+ bool createIfMissing = false,+ }) async {+ final uniqueClusterIDs = clusterIDs.toSet().toList(growable: false);+ if (uniqueClusterIDs.isEmpty) {+ return {};+ }++ final db = await asyncDB;+ if (createIfMissing) {+ const insertSql = '''+ INSERT OR IGNORE INTO $clusterCentroidVectorIdMappingTable ($clusterIDColumn)+ VALUES (?)+ ''';+ final insertParams = <List<Object?>>[];+ for (final clusterID in uniqueClusterIDs) {+ insertParams.add([clusterID]);+ }+ await db.executeBatch(insertSql, insertParams);+ }++ final result = <String, int>{};+ const chunkSize = 800;+ for (int i = 0; i < uniqueClusterIDs.length; i += chunkSize) {+ final chunk = uniqueClusterIDs.sublist(+ i,+ min(i + chunkSize, uniqueClusterIDs.length),+ );+ final rows = await db.getAll(+ '''+ SELECT $clusterIDColumn, $clusterCentroidVectorIdColumn+ FROM $clusterCentroidVectorIdMappingTable+ WHERE $clusterIDColumn IN (${List.filled(chunk.length, '?').join(',')})+ ''',+ chunk,+ );+ for (final row in rows) {+ result[row[clusterIDColumn] as String] =+ row[clusterCentroidVectorIdColumn] as int;+ }+ }+ return result;+ }++ Future<void> deleteClusterCentroidVectorIdMapping(String clusterID) async {+ final db = await asyncDB;+ const deleteSql = '''+ DELETE FROM $clusterCentroidVectorIdMappingTable+ WHERE $clusterIDColumn = ?+ ''';+ await db.execute(deleteSql, [clusterID]);+ }++ Future<void> clearClusterCentroidVectorIdMappings() async {+ final db = await asyncDB;+ await db.execute(deleteClusterCentroidVectorIdMappingTable);+ }+@overrideFuture<void> clusterSummaryUpdate(Map<String, (Uint8List, int)> summary,) async {+ if (summary.isEmpty) {+ return;+ }+final db = await asyncDB;const String sql = '''@@ -1082,6 +1153,62 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {batchCounter++;}await db.executeBatch(sql, parameterSets);++ if (!flagService.enableVectorDb ||+ !await _clusterCentroidVectorDB.checkIfMigrationDone()) {+ return;+ }++ try {+ final clusterIDToVectorID = await getClusterCentroidVectorIdMap(+ summary.keys,+ createIfMissing: true,+ );+ final vectorIDs = <int>[];+ final centroids = <Float32List>[];++ for (final entry in summary.entries) {+ final vectorID = clusterIDToVectorID[entry.key];+ if (vectorID == null) {+ continue;+ }+ final centroidBytes = entry.value.$1;+ Float32List centroid;+ try {+ final centroidValues = EVector.fromBuffer(centroidBytes).values;+ centroid = Float32List.fromList(centroidValues);+ } catch (e, s) {+ _logger.warning(+ "Failed to decode centroid embedding for cluster ${entry.key}, skipping vector update",+ e,+ s,+ );+ continue;+ }+ if (centroid.length != ClusterCentroidVectorDB.embeddingDimensions) {+ _logger.warning(+ "Unexpected centroid embedding size ${centroid.length} for cluster ${entry.key}, skipping vector update",+ );+ continue;+ }+ vectorIDs.add(vectorID);+ centroids.add(centroid);+ }++ if (vectorIDs.isNotEmpty) {+ await _clusterCentroidVectorDB.bulkInsertCentroids(+ clusterVectorIDs: vectorIDs,+ centroids: centroids,+ );+ }+ } catch (e, s) {+ _logger.warning(+ "Failed to sync cluster summaries to cluster centroid vector DB. Invalidating migration state for a safe fallback.",+ e,+ s,+ );+ await _clusterCentroidVectorDB.invalidateMigrationState();+ }}@override@@ -1090,6 +1217,31 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {const String sqlDelete ='DELETE FROM $clusterSummaryTable WHERE $clusterIDColumn = ?';await db.execute(sqlDelete, [clusterID]);++ if (!flagService.enableVectorDb ||+ !await _clusterCentroidVectorDB.checkIfMigrationDone()) {+ await deleteClusterCentroidVectorIdMapping(clusterID);+ return;+ }++ try {+ final clusterIDToVectorID = await getClusterCentroidVectorIdMap(+ [clusterID],+ createIfMissing: false,+ );+ final vectorID = clusterIDToVectorID[clusterID];+ if (vectorID != null) {+ await _clusterCentroidVectorDB.deleteCentroids([vectorID]);+ }+ await deleteClusterCentroidVectorIdMapping(clusterID);+ } catch (e, s) {+ _logger.warning(+ "Failed to remove cluster summary from cluster centroid vector DB. Invalidating migration state for a safe fallback.",+ e,+ s,+ );+ await _clusterCentroidVectorDB.invalidateMigrationState();+ }}/// Returns a map of clusterID to (avg embedding, count)@@ -1161,13 +1313,19 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {await db.execute(deleteClusterPersonTable);await db.execute(deleteNotPersonFeedbackTable);await db.execute(deleteClusterSummaryTable);+ await db.execute(deleteClusterCentroidVectorIdMappingTable);await db.execute(deleteFaceClustersTable);await db.execute(createClusterPersonTable);await db.execute(createNotPersonFeedbackTable);await db.execute(createClusterSummaryTable);+ await db.execute(createClusterCentroidVectorIdMappingTable);await db.execute(createFaceClustersTable);await db.execute(fcClusterIDIndex);++ if (await _clusterCentroidVectorDB.checkIfMigrationDone()) {+ await _clusterCentroidVectorDB.deleteAllCentroids();+ }} catch (e, s) {_logger.severe('Error dropping clusters and person table', e, s);}@@ -1275,6 +1433,167 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {return embeddings;}+ Future<void> checkMigrateFillClusterCentroidVectorDB({+ bool force = false,+ }) async {+ final migrationDone = await _clusterCentroidVectorDB.checkIfMigrationDone();+ if (migrationDone && !force) {+ _logger.info(+ "ClusterCentroidVectorDB migration not needed, already done",+ );+ return;+ }+ _logger.info("Starting ClusterCentroidVectorDB migration");++ final db = await asyncDB;+ final countResult = await db.getAll(+ 'SELECT COUNT($clusterIDColumn) as total FROM $clusterSummaryTable',+ );+ final totalCount = countResult.first['total'] as int;+ if (totalCount == 0) {+ _logger.info("No cluster summaries to migrate");+ await clearClusterCentroidVectorIdMappings();+ await _clusterCentroidVectorDB.deleteAllCentroids();+ await _clusterCentroidVectorDB.setMigrationDone();+ return;+ }+ _logger.info("Total count of cluster summaries: $totalCount");++ final clusterCentroidVectorDB = _clusterCentroidVectorDB;+ await clusterCentroidVectorDB.deleteAllCentroids();+ await clearClusterCentroidVectorIdMappings();+ _logger.info("ClusterCentroidVectorDB cleared before migration");++ const batchSize = 2000;+ int offset = 0;+ int processedCount = 0;+ int weirdCount = 0;+ int whileCount = 0;+ const String migrationKey =+ "cluster_centroid_vector_db_migration_in_progress";+ final stopwatch = Stopwatch()..start();+ try {+ computeController.blockCompute(blocker: migrationKey);+ while (true) {+ whileCount++;+ _logger.info("$whileCount st round of centroid migration while loop");+ await Future.delayed(const Duration(milliseconds: 100));++ final List<Map<String, dynamic>> results = await db.getAll(+ '''+ SELECT $clusterIDColumn, $avgColumn+ FROM $clusterSummaryTable+ ORDER BY $clusterIDColumn DESC+ LIMIT $batchSize OFFSET $offset+ ''',+ );+ if (results.isEmpty) {+ _logger.info("No more centroid rows, breaking out of while loop");+ break;+ }++ final clusterIDs = <String>[];+ final clusterIDToCentroid = <String, Float32List>{};+ for (final result in results) {+ final clusterID = result[clusterIDColumn] as String;+ final centroidBytes = result[avgColumn] as Uint8List;+ Float32List centroid;+ try {+ final centroidValues = EVector.fromBuffer(centroidBytes).values;+ centroid = Float32List.fromList(centroidValues);+ } catch (e, s) {+ weirdCount++;+ _logger.warning(+ "Failed to decode centroid embedding for clusterID $clusterID, skipping",+ e,+ s,+ );+ continue;+ }+ if (centroid.length == ClusterCentroidVectorDB.embeddingDimensions) {+ clusterIDs.add(clusterID);+ clusterIDToCentroid[clusterID] = centroid;+ } else {+ weirdCount++;+ _logger.warning(+ "Weird centroid embedding length ${centroid.length} for clusterID $clusterID, skipping",+ );+ }+ }++ final clusterIDToVectorID = await getClusterCentroidVectorIdMap(+ clusterIDs,+ createIfMissing: true,+ );+ final vectorIDs = <int>[];+ final centroids = <Float32List>[];+ for (final clusterID in clusterIDs) {+ final vectorID = clusterIDToVectorID[clusterID];+ final centroid = clusterIDToCentroid[clusterID];+ if (vectorID == null || centroid == null) {+ continue;+ }+ vectorIDs.add(vectorID);+ centroids.add(centroid);+ }++ if (vectorIDs.isNotEmpty) {+ await clusterCentroidVectorDB.bulkInsertCentroids(+ clusterVectorIDs: vectorIDs,+ centroids: centroids,+ );+ }++ processedCount += vectorIDs.length;+ offset += batchSize;+ _logger.info(+ "migrated $processedCount/$totalCount cluster centroids to ClusterCentroidVectorDB",+ );+ if (processedCount >= totalCount) {+ _logger.info(+ "All cluster centroids migrated, breaking out of while loop",+ );+ break;+ }+ }+ _logger.info(+ "migrated $processedCount cluster centroids to ClusterCentroidVectorDB in ${stopwatch.elapsed.inMilliseconds} ms, with $weirdCount malformed rows skipped",+ );+ await _clusterCentroidVectorDB.setMigrationDone();+ _logger.info("ClusterCentroidVectorDB migration done");+ try {+ final vectorStats = await _clusterCentroidVectorDB.getIndexStats();+ if (vectorStats.size != processedCount) {+ _logger.warning(+ "ClusterCentroidVectorDB size mismatch: vectorDb=${vectorStats.size}, migratedRows=$processedCount",+ );+ } else {+ _logger.info(+ "ClusterCentroidVectorDB size match: vectorDb=${vectorStats.size}, migratedRows=$processedCount",+ );+ }+ } catch (e, s) {+ _logger.warning(+ "Failed to log ClusterCentroidVectorDB size after migration",+ e,+ s,+ );+ }+ } catch (e, s) {+ _logger.severe(+ "Error migrating ClusterCentroidVectorDB after ${stopwatch.elapsed.inMilliseconds} ms, clearing out DB again",+ e,+ s,+ );+ await clusterCentroidVectorDB.deleteAllCentroids();+ await clearClusterCentroidVectorIdMappings();+ rethrow;+ } finally {+ stopwatch.stop();+ computeController.unblockCompute(blocker: migrationKey);+ }+ }+Future<void> checkMigrateFillClipVectorDB({bool force = false}) async {final migrationDone = await _clipVectorDB.checkIfMigrationDone();if (migrationDone && !force) {diff --git a/mobile/apps/photos/lib/db/ml/schema.dart b/mobile/apps/photos/lib/db/ml/schema.dartindex e9575beb75..ff67113477 100644--- a/mobile/apps/photos/lib/db/ml/schema.dart+++ b/mobile/apps/photos/lib/db/ml/schema.dart@@ -84,6 +84,22 @@ const deleteClusterSummaryTable = 'DELETE FROM $clusterSummaryTable';/// End Cluster Summary Table Fields & Schema Queries+/// Cluster Centroid Vector ID Mapping Table Fields & Schema Queries+const clusterCentroidVectorIdMappingTable = 'cluster_centroid_vector_id_map';+const clusterCentroidVectorIdColumn = 'cluster_vector_id';++const createClusterCentroidVectorIdMappingTable = '''+CREATE TABLE IF NOT EXISTS $clusterCentroidVectorIdMappingTable (+ $clusterCentroidVectorIdColumn INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ $clusterIDColumn TEXT NOT NULL UNIQUE+);+''';++const deleteClusterCentroidVectorIdMappingTable =+ 'DELETE FROM $clusterCentroidVectorIdMappingTable';++/// End Cluster Centroid Vector ID Mapping Table Fields & Schema Queries+/// notPersonFeedback Table Fields & Schema Queriesconst notPersonFeedback = 'not_person_feedback';diff --git a/mobile/apps/photos/rust/src/api/usearch_api.rs b/mobile/apps/photos/rust/src/api/usearch_api.rsindex 5970352ccf..b0878cf5db 100644--- a/mobile/apps/photos/rust/src/api/usearch_api.rs+++ b/mobile/apps/photos/rust/src/api/usearch_api.rs@@ -1,6 +1,7 @@use flutter_rust_bridge::frb;use usearch::{Index, IndexOptions, MetricKind, ScalarKind};+use std::collections::HashSet;use std::path::PathBuf;const FAST_SEARCH_STEP_COUNTS: [usize; 5] = [200, 500, 2000, 5000, 10000];@@ -148,6 +149,35 @@ impl VectorDB {self.fast_search_vectors_within_distance(query, max_distance)}+ pub fn approx_filtered_search_vectors_within_distance(+ &self,+ query: &[f32],+ allowed_keys: &Vec<u64>,+ count: usize,+ max_distance: f32,+ ) -> (Vec<u64>, Vec<f32>) {+ let index_size = self.index.size();+ if index_size == 0 || count == 0 || allowed_keys.is_empty() {+ return (Vec::new(), Vec::new());+ }+ if !max_distance.is_finite() || max_distance < 0.0 {+ return (Vec::new(), Vec::new());+ }++ let allowed = allowed_keys.iter().copied().collect::<HashSet<u64>>();+ let search_count = count.min(allowed.len()).min(index_size);+ if search_count == 0 {+ return (Vec::new(), Vec::new());+ }++ let matches = self+ .index+ .filtered_search(query, search_count, |key| allowed.contains(&key))+ .expect("Failed to run filtered vector search");++ Self::truncate_sorted_matches_within_distance(matches.keys, matches.distances, max_distance)+ }+fn fast_search_vectors_within_distance(&self,query: &[f32],