Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] Decouple remote ML hydration from compute gating

laurenspriem84760e904480
diff --git a/mobile/apps/photos/lib/db/ml/filedata.dart b/mobile/apps/photos/lib/db/ml/filedata.dart
index 5d9c45b088..d8c12e7d81 100644
--- a/mobile/apps/photos/lib/db/ml/filedata.dart
+++ b/mobile/apps/photos/lib/db/ml/filedata.dart
@@ -42,9 +42,14 @@ extension FileDataTable on MLDataDB {
);
}
- Future<Set<int>> getFileIDsWithFDData() async {
+ Future<Set<int>> getFileIDsWithFDData({DataType? type}) async {
final db = await MLDataDB.instance.asyncDB;
- final res = await db.execute('SELECT $fileIDColumn FROM $fileDataTable');
+ final String query = type == null
+ ? 'SELECT $fileIDColumn FROM $fileDataTable'
+ : 'SELECT $fileIDColumn FROM $fileDataTable WHERE type = ?';
+ final List<Object?> args = type == null ? const [] : [type.toJson()];
+ final res =
+ args.isEmpty ? await db.execute(query) : await db.execute(query, args);
return res.map((e) => e[fileIDColumn] as int).toSet();
}
}
diff --git a/mobile/apps/photos/lib/services/filedata/filedata_service.dart b/mobile/apps/photos/lib/services/filedata/filedata_service.dart
index ed2324e7c1..f300e42d7c 100644
--- a/mobile/apps/photos/lib/services/filedata/filedata_service.dart
+++ b/mobile/apps/photos/lib/services/filedata/filedata_service.dart
@@ -22,6 +22,7 @@ class FileDataService {
final SharedPreferences _prefs;
final FileDataGateway _gateway;
late Map<int, PreviewInfo> previewIds;
+ Future<void>? _syncFDStatusFuture;
FileDataService(this._prefs, this._gateway) {
_logger.info("FileDataService constructor called");
@@ -116,7 +117,22 @@ class FileDataService {
);
}
- Future<void> syncFDStatus() async {
+ Future<void> syncFDStatus() {
+ final existing = _syncFDStatusFuture;
+ if (existing != null) {
+ _logger.info("syncFDStatus already running, joining existing run");
+ return existing;
+ }
+ final future = _syncFDStatusInternal();
+ _syncFDStatusFuture = future;
+ return future.whenComplete(() {
+ if (identical(_syncFDStatusFuture, future)) {
+ _syncFDStatusFuture = null;
+ }
+ });
+ }
+
+ Future<void> _syncFDStatusInternal() async {
if (isOfflineMode) {
_logger.fine("Skipping file data sync in offline mode");
return;
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
index 0806fd3486..8af594ec7c 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -19,14 +19,15 @@ import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/ml_versions.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/filedata/model/file_data.dart";
-import 'package:photos/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart';
+import "package:photos/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart";
import "package:photos/services/machine_learning/face_ml/face_clustering/face_db_info_for_clustering.dart";
import "package:photos/services/machine_learning/face_ml/face_detection/detection.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
import "package:photos/services/machine_learning/ml_indexing_isolate.dart";
-import 'package:photos/services/machine_learning/ml_result.dart';
+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/sync/sync_service.dart";
import "package:photos/services/video_preview_service.dart";
import "package:photos/utils/ml_util.dart";
import "package:photos/utils/network_util.dart";
@@ -44,6 +45,8 @@ class MLService {
int? lastRemoteFetch;
static const int _kRemoteFetchCooldownOnLite = 1000 * 60 * 5;
+ Future<void>? _ownedRemoteHydrationFuture;
+ bool _hasScheduledStartupOwnedRemoteHydration = false;
late String client;
@@ -84,6 +87,7 @@ class MLService {
Future<void> init() async {
if (_isInitialized) {
unawaited(_maybePredownloadLocalModels());
+ scheduleStartupOwnedRemoteHydration();
return;
}
_logger.info("init called");
@@ -135,6 +139,7 @@ class MLService {
_isInitialized = true;
unawaited(_maybePredownloadLocalModels());
+ scheduleStartupOwnedRemoteHydration();
_logger.info('init done');
}
@@ -171,6 +176,109 @@ class MLService {
}
}
+ void scheduleStartupOwnedRemoteHydration() {
+ if (_hasScheduledStartupOwnedRemoteHydration ||
+ isProcessBg ||
+ !hasGrantedMLConsent ||
+ isOfflineMode ||
+ !localSettings.remoteFetchEnabled) {
+ return;
+ }
+ _hasScheduledStartupOwnedRemoteHydration = true;
+ unawaited(_runStartupOwnedRemoteHydration());
+ }
+
+ Future<void> _runStartupOwnedRemoteHydration() async {
+ if (!hasGrantedMLConsent || isOfflineMode) {
+ return;
+ }
+ final bool syncSuccessful;
+ try {
+ syncSuccessful = await SyncService.instance.sync();
+ } catch (e, s) {
+ _logger.warning(
+ "Skipping startup-owned remote ML hydration because startup sync failed",
+ e,
+ s,
+ );
+ return;
+ }
+ if (!syncSuccessful) {
+ _logger.info(
+ "Skipping startup-owned remote ML hydration because startup sync did not complete",
+ );
+ return;
+ }
+ try {
+ await fileDataService.syncFDStatus();
+ } catch (e, s) {
+ _logger.warning(
+ "Skipping startup-owned remote ML hydration because FD status refresh failed",
+ e,
+ s,
+ );
+ return;
+ }
+ await hydrateRemoteEmbeddingsForOwnedFiles(reason: "startup");
+ }
+
+ Future<void> hydrateRemoteEmbeddingsForOwnedFiles({
+ required String reason,
+ }) async {
+ if (isProcessBg ||
+ isOfflineMode ||
+ !hasGrantedMLConsent ||
+ !localSettings.remoteFetchEnabled) {
+ return;
+ }
+ final existing = _ownedRemoteHydrationFuture;
+ if (existing != null) {
+ _logger.info(
+ "Owned remote ML hydration already running, joining existing run ($reason)",
+ );
+ return existing;
+ }
+ final future = _hydrateRemoteEmbeddingsForOwnedFilesInternal(
+ reason: reason,
+ );
+ _ownedRemoteHydrationFuture = future;
+ try {
+ await future;
+ } finally {
+ if (identical(_ownedRemoteHydrationFuture, future)) {
+ _ownedRemoteHydrationFuture = null;
+ }
+ }
+ }
+
+ Future<void> _hydrateRemoteEmbeddingsForOwnedFilesInternal({
+ required String reason,
+ }) async {
+ final summary = await hydrateOwnedRemoteMLData(mlDataDB: MLDataDB.instance);
+ if (summary.candidateFiles == 0) {
+ _logger.info(
+ "Skipping owned remote ML hydration ($reason): no owned files need remote hydration",
+ );
+ return;
+ }
+ _logger.info(
+ "Owned remote ML hydration ($reason) finished for ${summary.candidateFiles} files "
+ "(faces hydrated: ${summary.hydratedFaces}, clip hydrated: ${summary.hydratedClips}, "
+ "still pending local ML: ${summary.remainingLocalMl})",
+ );
+ }
+
+ Future<void> _waitForOwnedRemoteHydrationIfRunning() async {
+ final existing = _ownedRemoteHydrationFuture;
+ if (existing == null) {
+ return;
+ }
+ _logger.info(
+ "Waiting for owned remote ML hydration to finish before indexing",
+ );
+ await existing;
+ }
+
bool canFetch() {
if (localSettings.isMLLocalIndexingEnabled) return true;
if (lastRemoteFetch == null) {
@@ -287,6 +395,8 @@ class MLService {
/// with the lastest faceMlVersion and stored on remote or local database. If so, it skips the image.
Future<void> fetchAndIndexAllImages({required MLMode mode}) async {
if (!_canRunMLFunction(function: "Indexing")) return;
+ await _waitForOwnedRemoteHydrationIfRunning();
+ if (!_canRunMLFunction(function: "Indexing")) return;
bool rustRuntimePrepared = false;
try {
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 173a18665f..5d73cb7146 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -67,6 +67,20 @@ class FileMLInstruction {
int get fileKey => isOffline ? offlineFileKey! : file.uploadedFileID!;
}
+class RemoteMLHydrationSummary {
+ final int candidateFiles;
+ final int hydratedFaces;
+ final int hydratedClips;
+ final int remainingLocalMl;
+
+ const RemoteMLHydrationSummary({
+ this.candidateFiles = 0,
+ this.hydratedFaces = 0,
+ this.hydratedClips = 0,
+ this.remainingLocalMl = 0,
+ });
+}
+
Future<IndexStatus> getIndexStatus() async {
try {
final MLMode mode = isOfflineMode ? MLMode.offline : MLMode.online;
@@ -119,7 +133,9 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
petEnabled ? await mlDataDB.petIndexedFileIds() : const {};
final Set<int> queuedFiledIDs = {};
- final Set<int> filesWithFDStatus = await mlDataDB.getFileIDsWithFDData();
+ final Set<int> filesWithFDStatus = await mlDataDB.getFileIDsWithFDData(
+ type: DataType.mlData,
+ );
// Get all regular files and all hidden files
final enteFiles = await SearchService.instance.getAllFilesForSearch();
@@ -213,6 +229,7 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
filesOwnedByOthers.add(instruction);
}
}
+ _lastFetchTimeForOthersIndexed = time;
_logger.info(
'Checking index for ${filesOwnedByOthers.length} owned by others',
);
@@ -331,49 +348,11 @@ Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
}
continue;
}
- final Set<int> ids = {};
- final Map<int, FileMLInstruction> pendingIndex = {};
- for (final instruction in chunk) {
- ids.add(instruction.file.uploadedFileID!);
- pendingIndex[instruction.file.uploadedFileID!] = instruction;
- }
- _logger.info("fetching embeddings for ${ids.length} files");
- final res = await fileDataService.getFilesData(ids);
- _logger.info("embeddingResponse ${res.debugLog()}");
- final List<Face> faces = [];
- final List<ClipEmbedding> clipEmbeddings = [];
- for (FileDataEntity fileMl in res.data.values) {
- final existingInstruction = pendingIndex[fileMl.fileID]!;
- final facesFromRemoteEmbedding = _getFacesFromRemoteEmbedding(fileMl);
- //Note: Always do null check, empty value means no face was found.
- if (facesFromRemoteEmbedding != null) {
- faces.addAll(facesFromRemoteEmbedding);
- existingInstruction.shouldRunFaces = false;
- }
- final remoteClipEmbedding =
- fileMl.getClipEmbeddingIfCompatible(clipMlVersion);
- if (remoteClipEmbedding != null) {
- clipEmbeddings.add(
- ClipEmbedding(
- fileID: fileMl.fileID,
- embedding: remoteClipEmbedding.embedding,
- version: remoteClipEmbedding.version,
- ),
- );
- existingInstruction.shouldRunClip = false;
- }
- if (!existingInstruction.pendingML) {
- pendingIndex.remove(fileMl.fileID);
- } else {
- existingInstruction.existingRemoteFileML = fileMl;
- pendingIndex[fileMl.fileID] = existingInstruction;
- }
- }
-
- await mlDataDB.bulkInsertFaces(faces);
- await mlDataDB.putClip(clipEmbeddings);
- for (final fileID in pendingIndex.keys) {
- final instruction = pendingIndex[fileID]!;
+ final pendingInstructions = await hydrateRemoteMLDataForInstructions(
+ chunk,
+ mlDataDB: mlDataDB,
+ );
+ for (final instruction in pendingInstructions) {
if (instruction.pendingML) {
batchToYield.add(instruction);
if (batchToYield.length == yieldSize) {
@@ -391,6 +370,120 @@ Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
}
}
+Future<RemoteMLHydrationSummary> hydrateOwnedRemoteMLData({
+ required MLDataDB mlDataDB,
+}) async {
+ final filesWithRemoteML = await mlDataDB.getFileIDsWithFDData(
+ type: DataType.mlData,
+ );
+ if (filesWithRemoteML.isEmpty) {
+ return const RemoteMLHydrationSummary();
+ }
+
+ final filesToIndex = await getFilesForMlIndexing();
+ final ownedCandidates = filesToIndex.where((instruction) {
+ final uploadedFileID = instruction.file.uploadedFileID;
+ return uploadedFileID != null &&
+ instruction.file.isOwner &&
+ filesWithRemoteML.contains(uploadedFileID) &&
+ (instruction.shouldRunFaces || instruction.shouldRunClip);
+ }).toList();
+ if (ownedCandidates.isEmpty) {
+ return const RemoteMLHydrationSummary();
+ }
+
+ int hydratedFaces = 0;
+ int hydratedClips = 0;
+ int remainingLocalMl = 0;
+ for (int start = 0;
+ start < ownedCandidates.length;
+ start += embeddingFetchLimit) {
+ final end = math.min(start + embeddingFetchLimit, ownedCandidates.length);
+ final chunk = ownedCandidates.sublist(start, end);
+ final facePendingBefore = chunk.where((i) => i.shouldRunFaces).length;
+ final clipPendingBefore = chunk.where((i) => i.shouldRunClip).length;
+ final pendingAfterHydration = await hydrateRemoteMLDataForInstructions(
+ chunk,
+ mlDataDB: mlDataDB,
+ );
+ hydratedFaces += facePendingBefore -
+ pendingAfterHydration.where((i) => i.shouldRunFaces).length;
+ hydratedClips += clipPendingBefore -
+ pendingAfterHydration.where((i) => i.shouldRunClip).length;
+ remainingLocalMl += pendingAfterHydration.length;
+ }
+
+ return RemoteMLHydrationSummary(
+ candidateFiles: ownedCandidates.length,
+ hydratedFaces: hydratedFaces,
+ hydratedClips: hydratedClips,
+ remainingLocalMl: remainingLocalMl,
+ );
+}
+
+Future<List<FileMLInstruction>> hydrateRemoteMLDataForInstructions(
+ List<FileMLInstruction> instructions, {
+ required MLDataDB mlDataDB,
+}) async {
+ if (instructions.isEmpty) {
+ return <FileMLInstruction>[];
+ }
+ final Set<int> ids = {};
+ final Map<int, FileMLInstruction> pendingIndex = {};
+ for (final instruction in instructions) {
+ if (instruction.isOffline) {
+ continue;
+ }
+ ids.add(instruction.file.uploadedFileID!);
+ pendingIndex[instruction.file.uploadedFileID!] = instruction;
+ }
+ if (ids.isEmpty) {
+ return instructions.where((instruction) => instruction.pendingML).toList();
+ }
+ _logger.info("fetching embeddings for ${ids.length} files");
+ final res = await fileDataService.getFilesData(ids);
+ _logger.info("embeddingResponse ${res.debugLog()}");
+ final List<Face> faces = [];
+ final List<ClipEmbedding> clipEmbeddings = [];
+ for (final fileMl in res.data.values) {
+ final existingInstruction = pendingIndex[fileMl.fileID];
+ if (existingInstruction == null) {
+ continue;
+ }
+ final facesFromRemoteEmbedding = _getFacesFromRemoteEmbedding(fileMl);
+ // Note: always do null check; an empty value means no face was found.
+ if (facesFromRemoteEmbedding != null) {
+ faces.addAll(facesFromRemoteEmbedding);
+ existingInstruction.shouldRunFaces = false;
+ }
+ final remoteClipEmbedding = fileMl.getClipEmbeddingIfCompatible(
+ clipMlVersion,
+ );
+ if (remoteClipEmbedding != null) {
+ clipEmbeddings.add(
+ ClipEmbedding(
+ fileID: fileMl.fileID,
+ embedding: remoteClipEmbedding.embedding,
+ version: remoteClipEmbedding.version,
+ ),
+ );
+ existingInstruction.shouldRunClip = false;
+ }
+ if (!existingInstruction.pendingML) {
+ pendingIndex.remove(fileMl.fileID);
+ } else {
+ existingInstruction.existingRemoteFileML = fileMl;
+ pendingIndex[fileMl.fileID] = existingInstruction;
+ }
+ }
+
+ await mlDataDB.bulkInsertFaces(faces);
+ await mlDataDB.putClip(clipEmbeddings);
+ return pendingIndex.values
+ .where((instruction) => instruction.pendingML)
+ .toList();
+}
+
// Returns a list of faces from the given remote fileML. null if the version is less than the current version
// or if the remote faceEmbedding is null.
List<Face>? _getFacesFromRemoteEmbedding(FileDataEntity fileMl) {