Skip to content

armgit / ente

Public Imported from GitHub
0

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

Fix background ML consent/init flow and preserve partial reindex results

Prateek Sunal9566438c8be4
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 79269b03e0..aad591033e 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -224,9 +224,10 @@ Future<void> _runMinimally(String taskId, TimeLogger tlog) async {
_logger.info("[BG TASK] home widget sync");
await _homeWidgetSync(true);
- if (flagService.enableMLInBackground) {
+ if (flagService.enableMLInBackground && hasGrantedMLConsent) {
await MLService.instance.init();
await PersonService.init(entityService, MLDataDB.instance, prefs);
+ await controller.init();
final canRunML = controller.requestCompute(ml: true);
if (!canRunML) {
_logger.info(
diff --git a/mobile/apps/photos/lib/services/machine_learning/compute_controller.dart b/mobile/apps/photos/lib/services/machine_learning/compute_controller.dart
index c78a463f0f..f59549ed20 100644
--- a/mobile/apps/photos/lib/services/machine_learning/compute_controller.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/compute_controller.dart
@@ -39,6 +39,7 @@ class ComputeController {
bool _hasCompletedInitialHealthChecks = false;
bool _temporaryInteractionOverride = false;
bool _debugInteractionOverride = false;
+ Future<void>? _initFuture;
/// If true, user interaction is ignored and compute tasks can run regardless of user activity.
bool get interactionOverride =>
@@ -63,12 +64,16 @@ class ComputeController {
ComputeController(this._localSettings) {
_logger.info('ComputeController constructor');
- init();
+ unawaited(init());
_logger.info('init done ');
}
// Directly assign the values + Attach listener for compute controller
- Future<void> init() async {
+ Future<void> init() {
+ return _initFuture ??= _initInternal();
+ }
+
+ Future<void> _initInternal() async {
if (!isProcessBg) {
// Initialize interaction tracking before any await to avoid first-tap races.
_startInteractionTimer(kDefaultInteractionTimeout);
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 04d102083a..6855ae274a 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -3,7 +3,7 @@ import "dart:io" show Platform;
import "dart:math" show min;
import "dart:typed_data" show Uint8List;
-import "package:flutter/foundation.dart" show kDebugMode;
+import "package:flutter/foundation.dart" show kDebugMode, visibleForTesting;
import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/db/files_db.dart";
@@ -12,6 +12,7 @@ import "package:photos/db/offline_files_db.dart";
import "package:photos/events/compute_control_event.dart";
import "package:photos/events/people_changed_event.dart";
import "package:photos/main.dart";
+import "package:photos/models/file/file.dart";
import "package:photos/models/ml/clip.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/ml_versions.dart";
@@ -177,6 +178,10 @@ class MLService {
}
Future<void> runAllML({bool force = false}) async {
+ if (!hasGrantedMLConsent) {
+ _logger.info("runAllML called without ML consent, skipping");
+ return;
+ }
if (_isRunningML) {
_logger.info("runAllML called while already running, skipping");
return;
@@ -662,16 +667,10 @@ class MLService {
e,
s,
);
- await mlDataDB.bulkInsertFaces(
- [Face.empty(instruction.fileKey, error: true)],
+ await storeAcceptedIssuePlaceholders(
+ instruction: instruction,
+ mlDataDB: mlDataDB,
);
- if (instruction.isOffline) {
- await mlDataDB.putClip([ClipEmbedding.empty(instruction.fileKey)]);
- } else {
- await SemanticSearchService.instance.storeEmptyClipImageResult(
- instruction.file,
- );
- }
return true;
}
_logger.severe(
@@ -683,6 +682,30 @@ class MLService {
}
}
+ @visibleForTesting
+ Future<void> storeAcceptedIssuePlaceholders({
+ required FileMLInstruction instruction,
+ required MLDataDB mlDataDB,
+ Future<void> Function(EnteFile file)? storeEmptyClipImageResult,
+ }) async {
+ if (instruction.shouldRunFaces) {
+ await mlDataDB.bulkInsertFaces(
+ [Face.empty(instruction.fileKey, error: true)],
+ );
+ }
+ if (!instruction.shouldRunClip) {
+ return;
+ }
+ if (instruction.isOffline) {
+ await mlDataDB.putClip([ClipEmbedding.empty(instruction.fileKey)]);
+ return;
+ }
+ await (storeEmptyClipImageResult ??
+ SemanticSearchService.instance.storeEmptyClipImageResult)(
+ instruction.file,
+ );
+ }
+
bool _canRunMLFunction({required String function}) {
if (kDebugMode && Platform.isIOS && !_isIndexingOrClusteringRunning) {
return true;
diff --git a/mobile/apps/photos/test/services/machine_learning/ml_service_test.dart b/mobile/apps/photos/test/services/machine_learning/ml_service_test.dart
new file mode 100644
index 0000000000..5100e7be00
--- /dev/null
+++ b/mobile/apps/photos/test/services/machine_learning/ml_service_test.dart
@@ -0,0 +1,144 @@
+import "dart:convert";
+
+import "package:dio/dio.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:mockito/mockito.dart";
+import "package:photos/db/ml/db.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/file/file_type.dart";
+import "package:photos/models/ml/clip.dart";
+import "package:photos/models/ml/face/face.dart";
+import "package:package_info_plus/package_info_plus.dart";
+import "package:photos/service_locator.dart";
+import "package:photos/services/machine_learning/ml_service.dart";
+import "package:photos/utils/ml_util.dart";
+import "package:shared_preferences/shared_preferences.dart";
+
+class RecordingMLDataDB extends Mock implements MLDataDB {
+ final List<List<Face>> insertedFaces = [];
+ final List<List<ClipEmbedding>> insertedClips = [];
+
+ @override
+ Future<void> bulkInsertFaces(List<Face> faces) async {
+ insertedFaces.add(faces);
+ }
+
+ @override
+ Future<void> putClip(List<ClipEmbedding> embeddings) async {
+ insertedClips.add(embeddings);
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test("runAllML(force: true) skips when ML consent is disabled", () async {
+ SharedPreferences.setMockInitialValues({
+ "remote_flags": jsonEncode({
+ "faceSearchEnabled": false,
+ "internalUser": true,
+ }),
+ });
+ final prefs = await SharedPreferences.getInstance();
+ ServiceLocator.instance.init(
+ prefs,
+ Dio(),
+ Dio(),
+ PackageInfo(
+ appName: "photos",
+ packageName: "io.ente.photos",
+ version: "1.0.0",
+ buildNumber: "1",
+ ),
+ );
+
+ expect(hasGrantedMLConsent, isFalse);
+
+ await expectLater(MLService.instance.runAllML(force: true), completes);
+ expect(MLService.instance.isRunningML, isFalse);
+ });
+
+ group("storeAcceptedIssuePlaceholders", () {
+ late RecordingMLDataDB mlDataDB;
+
+ setUp(() {
+ mlDataDB = RecordingMLDataDB();
+ });
+
+ test("faces-only reindex stores empty face placeholder only", () async {
+ final instruction = FileMLInstruction(
+ file: _makeFile(1),
+ mode: MLMode.offline,
+ offlineFileKey: 101,
+ shouldRunFaces: true,
+ shouldRunClip: false,
+ );
+
+ await MLService.instance.storeAcceptedIssuePlaceholders(
+ instruction: instruction,
+ mlDataDB: mlDataDB,
+ );
+
+ expect(mlDataDB.insertedFaces, hasLength(1));
+ expect(mlDataDB.insertedFaces.single, hasLength(1));
+ expect(mlDataDB.insertedFaces.single.single.fileID, 101);
+ expect(mlDataDB.insertedFaces.single.single.embedding, isEmpty);
+ expect(mlDataDB.insertedFaces.single.single.score, -1.0);
+ expect(mlDataDB.insertedClips, isEmpty);
+ });
+
+ test("clip-only offline reindex stores empty clip placeholder only",
+ () async {
+ final instruction = FileMLInstruction(
+ file: _makeFile(2),
+ mode: MLMode.offline,
+ offlineFileKey: 202,
+ shouldRunFaces: false,
+ shouldRunClip: true,
+ );
+
+ await MLService.instance.storeAcceptedIssuePlaceholders(
+ instruction: instruction,
+ mlDataDB: mlDataDB,
+ );
+
+ expect(mlDataDB.insertedClips, hasLength(1));
+ expect(mlDataDB.insertedClips.single, hasLength(1));
+ expect(mlDataDB.insertedClips.single.single.fileID, 202);
+ expect(mlDataDB.insertedClips.single.single.isEmpty, isTrue);
+ expect(mlDataDB.insertedFaces, isEmpty);
+ });
+
+ test("clip-only online reindex does not write empty faces", () async {
+ final file = _makeFile(3);
+ int emptyClipStoreCalls = 0;
+
+ final instruction = FileMLInstruction(
+ file: file,
+ mode: MLMode.online,
+ shouldRunFaces: false,
+ shouldRunClip: true,
+ );
+
+ await MLService.instance.storeAcceptedIssuePlaceholders(
+ instruction: instruction,
+ mlDataDB: mlDataDB,
+ storeEmptyClipImageResult: (enteFile) async {
+ expect(enteFile, same(file));
+ emptyClipStoreCalls++;
+ },
+ );
+
+ expect(emptyClipStoreCalls, 1);
+ expect(mlDataDB.insertedFaces, isEmpty);
+ expect(mlDataDB.insertedClips, isEmpty);
+ });
+ });
+}
+
+EnteFile _makeFile(int uploadedFileID) {
+ return EnteFile()
+ ..uploadedFileID = uploadedFileID
+ ..title = "test.jpg"
+ ..fileType = FileType.image;
+}