Skip to content

armgit / ente

Public Imported from GitHub
0

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

Further write protections for centroid vectorDB

laurensprieme8438409d4c6
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.dart
index ebcc9b6a26..12ded08651 100644
--- a/mobile/apps/photos/lib/db/ml/cluster_centroid_vector_db.dart
+++ b/mobile/apps/photos/lib/db/ml/cluster_centroid_vector_db.dart
@@ -7,6 +7,7 @@ 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";
+import "package:synchronized/synchronized.dart";
class ClusterCentroidVectorDB {
static final Logger _logger = Logger("ClusterCentroidVectorDB");
@@ -37,6 +38,7 @@ class ClusterCentroidVectorDB {
Future<VectorDb>? _vectorDbFuture;
Future<void>? _warmupFuture;
+ final Lock _writeLock = Lock();
Future<VectorDb> get _vectorDB async {
_vectorDbFuture ??= _initVectorDB();
@@ -124,13 +126,23 @@ class ClusterCentroidVectorDB {
_migrationDone = false;
}
+ Future<void> _runWriteOperation(
+ Future<void> Function(VectorDb db) operation,
+ ) async {
+ final db = await _vectorDB;
+ await _writeLock.synchronized(() async {
+ await operation(db);
+ });
+ }
+
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);
+ await _runWriteOperation((db) async {
+ await db.addVector(key: BigInt.from(clusterVectorID), vector: centroid);
+ });
} catch (e, s) {
_logger.severe("Error inserting cluster centroid", e, s);
rethrow;
@@ -144,12 +156,13 @@ class ClusterCentroidVectorDB {
if (clusterVectorIDs.isEmpty || centroids.isEmpty) {
return;
}
- final db = await _vectorDB;
try {
- await db.bulkAddVectors(
- keys: Uint64List.fromList(clusterVectorIDs),
- vectors: centroids,
- );
+ await _runWriteOperation((db) async {
+ await db.bulkAddVectors(
+ keys: Uint64List.fromList(clusterVectorIDs),
+ vectors: centroids,
+ );
+ });
} catch (e, s) {
_logger.severe("Error bulk inserting cluster centroids", e, s);
rethrow;
@@ -160,11 +173,13 @@ class ClusterCentroidVectorDB {
if (clusterVectorIDs.isEmpty) {
return;
}
- final db = await _vectorDB;
try {
- final deletedCount = await db.bulkRemoveVectors(
- keys: Uint64List.fromList(clusterVectorIDs),
- );
+ BigInt deletedCount = BigInt.zero;
+ await _runWriteOperation((db) async {
+ deletedCount = await db.bulkRemoveVectors(
+ keys: Uint64List.fromList(clusterVectorIDs),
+ );
+ });
_logger.info(
"Deleted $deletedCount centroids from ${clusterVectorIDs.length} keys",
);
@@ -176,9 +191,10 @@ class ClusterCentroidVectorDB {
Future<void> deleteAllCentroids() async {
await invalidateMigrationState();
- final db = await _vectorDB;
try {
- await db.resetIndex();
+ await _runWriteOperation((db) async {
+ await db.resetIndex();
+ });
} catch (e, s) {
_logger.severe("Error deleting all cluster centroids", e, s);
rethrow;
@@ -393,9 +409,11 @@ class ClusterCentroidVectorDB {
await invalidateMigrationState();
final db = await _vectorDB;
try {
- await db.deleteIndex();
- _vectorDbFuture = null;
- _warmupFuture = null;
+ await _writeLock.synchronized(() async {
+ await db.deleteIndex();
+ _vectorDbFuture = null;
+ _warmupFuture = null;
+ });
} catch (e, s) {
_logger.severe("Error deleting cluster centroid index", e, s);
rethrow;
@@ -403,26 +421,28 @@ class ClusterCentroidVectorDB {
}
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();
+ await _writeLock.synchronized(() 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;
}
- _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;
- }
+ });
}
}
diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dart
index f78e000bcf..943f177d4e 100644
--- a/mobile/apps/photos/lib/db/ml/db.dart
+++ b/mobile/apps/photos/lib/db/ml/db.dart
@@ -59,6 +59,9 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<void>? _clipVectorDbRecoveryFuture;
final Lock _clipVectorRecoveryLock = Lock();
final Lock _clipVectorMigrationLock = Lock();
+ Future<void>? _clusterCentroidVectorDbRecoveryFuture;
+ final Lock _clusterCentroidVectorRecoveryLock = Lock();
+ final Lock _clusterCentroidVectorMigrationLock = Lock();
MLDataDB._privateConstructor({
String databaseName = "ente.ml.db",
@@ -1251,12 +1254,11 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
);
}
} 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 _handleClusterCentroidVectorWriteFailure(
+ operation: "clusterSummaryUpdate",
+ error: e,
+ stackTrace: s,
);
- await _clusterCentroidVectorDB.invalidateMigrationState();
}
}
@@ -1285,12 +1287,11 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
}
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 _handleClusterCentroidVectorWriteFailure(
+ operation: "deleteClusterSummary",
+ error: e,
+ stackTrace: s,
);
- await _clusterCentroidVectorDB.invalidateMigrationState();
}
}
@@ -1375,7 +1376,12 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
_markClusterSummaryMutated();
if (await _clusterCentroidVectorDB.checkIfMigrationDone()) {
- await _clusterCentroidVectorDB.deleteAllCentroids();
+ await _withClusterCentroidVectorWriteRecovery(
+ operation: "dropClustersAndPersonTable",
+ writeOperation: () async {
+ await _clusterCentroidVectorDB.deleteAllCentroids();
+ },
+ );
}
} catch (e, s) {
_logger.severe('Error dropping clusters and person table', e, s);
@@ -1487,48 +1493,129 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
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");
+ await _clusterCentroidVectorMigrationLock.synchronized(() async {
+ final migrationDone =
+ await _clusterCentroidVectorDB.checkIfMigrationDone();
+ if (migrationDone && !force) {
+ _logger
+ .info("ClusterCentroidVectorDB migration not needed, already done");
+ return;
+ }
+ _logger.info("Starting ClusterCentroidVectorDB migration");
- const maxStableAttempts = 3;
- for (int attempt = 1; attempt <= maxStableAttempts; attempt++) {
- final startMutationVersion = _clusterSummaryMutationSnapshot();
- _logger.info(
- "ClusterCentroidVectorDB migration attempt $attempt/$maxStableAttempts from mutationVersion=$startMutationVersion",
- );
+ const maxStableAttempts = 3;
+ for (int attempt = 1; attempt <= maxStableAttempts; attempt++) {
+ final startMutationVersion = _clusterSummaryMutationSnapshot();
+ _logger.info(
+ "ClusterCentroidVectorDB migration attempt $attempt/$maxStableAttempts from mutationVersion=$startMutationVersion",
+ );
- await _runClusterCentroidMigrationPass();
+ await _runClusterCentroidMigrationPass();
+
+ final endMutationVersion = _clusterSummaryMutationSnapshot();
+ if (endMutationVersion != startMutationVersion) {
+ _logger.info(
+ "Cluster summaries changed during migration attempt $attempt (mutationVersion=$startMutationVersion->$endMutationVersion), retrying full migration",
+ );
+ continue;
+ }
+
+ await _clusterCentroidVectorDB.setMigrationDone();
+ final finalizedMutationVersion = _clusterSummaryMutationSnapshot();
+ if (finalizedMutationVersion == endMutationVersion) {
+ _logger.info("ClusterCentroidVectorDB migration done");
+ return;
+ }
- final endMutationVersion = _clusterSummaryMutationSnapshot();
- if (endMutationVersion != startMutationVersion) {
_logger.info(
- "Cluster summaries changed during migration attempt $attempt (mutationVersion=$startMutationVersion->$endMutationVersion), retrying full migration",
+ "Cluster summaries changed while finalizing migration attempt $attempt (mutationVersion=$endMutationVersion->$finalizedMutationVersion), retrying full migration",
);
- continue;
+ await _clusterCentroidVectorDB.invalidateMigrationState();
}
- await _clusterCentroidVectorDB.setMigrationDone();
- final finalizedMutationVersion = _clusterSummaryMutationSnapshot();
- if (finalizedMutationVersion == endMutationVersion) {
- _logger.info("ClusterCentroidVectorDB migration done");
- return;
- }
-
- _logger.info(
- "Cluster summaries changed while finalizing migration attempt $attempt (mutationVersion=$endMutationVersion->$finalizedMutationVersion), retrying full migration",
+ _logger.severe(
+ "ClusterCentroidVectorDB migration did not reach a stable snapshot after $maxStableAttempts attempts. Leaving migration state invalidated for safe fallback.",
);
await _clusterCentroidVectorDB.invalidateMigrationState();
+ });
+ }
+
+ Future<void> _withClusterCentroidVectorWriteRecovery({
+ required String operation,
+ required Future<void> Function() writeOperation,
+ }) async {
+ try {
+ await writeOperation();
+ } catch (e, s) {
+ await _handleClusterCentroidVectorWriteFailure(
+ operation: operation,
+ error: e,
+ stackTrace: s,
+ );
+ rethrow;
}
+ }
+ Future<void> _handleClusterCentroidVectorWriteFailure({
+ required String operation,
+ required Object error,
+ required StackTrace stackTrace,
+ }) async {
_logger.severe(
- "ClusterCentroidVectorDB migration did not reach a stable snapshot after $maxStableAttempts attempts. Leaving migration state invalidated for safe fallback.",
+ "ClusterCentroidVectorDB write failed during `$operation`. Marking migration stale and scheduling rebuild.",
+ error,
+ stackTrace,
);
- await _clusterCentroidVectorDB.invalidateMigrationState();
+ try {
+ await _clusterCentroidVectorDB.invalidateMigrationState();
+ } catch (invalidateError, invalidateStackTrace) {
+ _logger.severe(
+ "Failed to invalidate ClusterCentroidVectorDB migration state after `$operation` failure",
+ invalidateError,
+ invalidateStackTrace,
+ );
+ }
+ unawaited(_scheduleClusterCentroidVectorDbRecovery());
+ }
+
+ Future<void> _scheduleClusterCentroidVectorDbRecovery() async {
+ await _clusterCentroidVectorRecoveryLock.synchronized(() async {
+ if (_clusterCentroidVectorDbRecoveryFuture != null) {
+ return;
+ }
+ _clusterCentroidVectorDbRecoveryFuture =
+ _recoverClusterCentroidVectorDbFromSqlite();
+ });
+ final recoveryFuture = _clusterCentroidVectorDbRecoveryFuture;
+ if (recoveryFuture != null) {
+ await recoveryFuture;
+ }
+ }
+
+ Future<void> _recoverClusterCentroidVectorDbFromSqlite() async {
+ const idlePollDelay = Duration(seconds: 5);
+ try {
+ _logger.info(
+ "Queued ClusterCentroidVectorDB rebuild from SQLite after index write failure",
+ );
+ while (computeController.computeState != ComputeRunState.idle) {
+ _logger.info(
+ "Waiting for compute to become idle before ClusterCentroidVectorDB rebuild (current state: ${computeController.computeState})",
+ );
+ await Future.delayed(idlePollDelay);
+ }
+ _logger.info("Starting ClusterCentroidVectorDB rebuild from SQLite");
+ await checkMigrateFillClusterCentroidVectorDB(force: true);
+ _logger.info("ClusterCentroidVectorDB rebuild from SQLite completed");
+ } catch (e, s) {
+ _logger.severe(
+ "ClusterCentroidVectorDB rebuild from SQLite failed",
+ e,
+ s,
+ );
+ } finally {
+ _clusterCentroidVectorDbRecoveryFuture = null;
+ }
}
Future<void> _runClusterCentroidMigrationPass() async {