Skip to content

armgit / ente

Public Imported from GitHub
0

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

ml indexing mobile test builders

laurenspriem7b46649804ad
diff --git a/infra/ml/ml-indexing-parity-test-plan.md b/infra/ml/ml-indexing-parity-test-plan.md
index 7feb25de9e..1d19dc8059 100644
--- a/infra/ml/ml-indexing-parity-test-plan.md
+++ b/infra/ml/ml-indexing-parity-test-plan.md
@@ -88,10 +88,10 @@ This section is for implementation agents to keep a running log so handoffs stay
- [x] W2: Implement Python ground truth pipeline (`clip.py`, `face_detection.py`, `face_alignment.py`, `face_embedding.py`, `pipeline.py`)
- [x] W3: Add/define corpus manifest and storage layout under `infra/ml/ground_truth`
- [x] W4: Implement desktop parity runner
-- [ ] W5: Implement Android parity runner
-- [ ] W6: Implement iOS parity runner
+- [x] W5: Implement Android parity runner
+- [x] W6: Implement iOS parity runner
- [x] W7: Implement comparator and report generator
-- [ ] W8: Implement one-command local orchestration (`run_suite.sh`)
+- [x] W8: Implement one-command local orchestration (`run_suite.sh`)
- [ ] W9: Add selective CI workflow for indexing-related path changes
- [ ] W10: Document usage and maintenance (`README`, golden update instructions)
@@ -104,6 +104,8 @@ This section is for implementation agents to keep a running log so handoffs stay
| 2026-02-16 | Codex (GPT-5) | Implemented W2 real ONNX-backed Python ground-truth pipeline with trusted library primitives: Pillow (+HEIF plugin) decode/orientation, OpenCV resize/warp/NMS, ONNX Runtime inference for CLIP + YOLOv5Face + MobileFaceNet, and integrated `generate_goldens.py` to emit schema outputs from live inference. | `infra/ml/ground_truth/_runtime.py`, `infra/ml/ground_truth/clip.py`, `infra/ml/ground_truth/face_detection.py`, `infra/ml/ground_truth/face_alignment.py`, `infra/ml/ground_truth/face_embedding.py`, `infra/ml/ground_truth/pipeline.py`, `infra/ml/tools/generate_goldens.py`, `infra/ml/tools/run_suite.sh`, `infra/ml/ground_truth/README.md`, `infra/ml/pyproject.toml`, `infra/ml/uv.lock`, `infra/ml/ml-indexing-parity-test-plan.md` | `uv run --project infra/ml --no-sync --with pillow-heif python infra/ml/tools/generate_goldens.py --manifest infra/ml/ground_truth/manifest.json --output-dir infra/ml/out/parity/python`; `uv run --project infra/ml --no-sync --with pytest pytest infra/ml/tests/test_schema.py infra/ml/tests/test_comparator.py`; `infra/ml/tools/run_suite.sh --suite smoke --platforms all --allow-empty-comparison --output-dir infra/ml/out/parity` | Implement W4 desktop parity runner next, then wire W5/W6 mobile runners into `run_suite.sh`. |
| 2026-02-16 | Codex (GPT-5) | Implemented W4 desktop parity runner using production desktop ML runtime paths: added Electron host that drives the compiled `ml-worker` utility process for ONNX inference/model downloads, added desktop parity runner that invokes web `indexFaces`/`indexCLIP` logic and emits shared-schema outputs, and wired `run_suite.sh` to compile desktop sources and run desktop parity generation when dependencies are present. | `desktop/scripts/ml_parity_host.js`, `desktop/scripts/ml_parity_runner.ts`, `infra/ml/tools/run_suite.sh`, `infra/ml/ml-indexing-parity-test-plan.md` | `bash -n infra/ml/tools/run_suite.sh`; `node --check desktop/scripts/ml_parity_host.js`; `node --experimental-strip-types --check desktop/scripts/ml_parity_runner.ts`; `uv run --project infra/ml --no-sync --with pytest pytest infra/ml/tests/test_schema.py infra/ml/tests/test_comparator.py`; `infra/ml/tools/run_suite.sh --suite smoke --platforms desktop --allow-empty-comparison --output-dir /tmp/ml_parity_desktop_smoke` | Implement W5/W6 mobile parity runners and then mark W8 complete once all platform runners are fully orchestrated by `run_suite.sh`. |
| 2026-02-16 | Codex (GPT-5) | Hardened desktop decode parity to use the exact production decode helper source: extracted `createImageBitmapAndData` into shared web ML module, reused by production via `blob.ts`, and injected that exact function source into the parity host renderer decode path. | `web/packages/new/photos/services/ml/decode.ts`, `web/packages/new/photos/services/ml/blob.ts`, `desktop/scripts/ml_parity_host.js`, `desktop/scripts/ml_parity_runner.ts`, `infra/ml/tools/run_suite.sh`, `infra/ml/ml-indexing-parity-test-plan.md` | `node --check desktop/scripts/ml_parity_host.js`; `node --experimental-strip-types --check desktop/scripts/ml_parity_runner.ts`; `node --experimental-strip-types --check web/packages/new/photos/services/ml/decode.ts`; `bash -n infra/ml/tools/run_suite.sh`; `uv run --project infra/ml --no-sync --with pytest pytest infra/ml/tests/test_schema.py infra/ml/tests/test_comparator.py`; `infra/ml/tools/run_suite.sh --suite smoke --platforms desktop --allow-empty-comparison --output-dir /tmp/ml_parity_desktop_smoke` | Run full desktop parity locally once `desktop/node_modules` + `web/node_modules` are installed, then proceed with W5/W6. |
+| 2026-02-16 | Codex (GPT-5) | Implemented W5/W6 mobile parity runners with shared harness that executes the production mobile isolate ML pipeline (`IsolateOperation.analyzeImage` -> `analyzeImageStatic`) on Android and iOS, emits shared-schema outputs through an integration-test driver, and wired `run_suite.sh` to launch platform-specific Flutter drive targets and persist `results.json` under `infra/ml/out/parity/<platform>/`. | `mobile/apps/photos/integration_test/ml_parity_shared.dart`, `mobile/apps/photos/integration_test/ml_parity_android_test.dart`, `mobile/apps/photos/integration_test/ml_parity_ios_test.dart`, `mobile/apps/photos/test_driver/ml_parity_driver.dart`, `infra/ml/tools/run_suite.sh`, `infra/ml/ml-indexing-parity-test-plan.md` | `dart format mobile/apps/photos/integration_test/ml_parity_shared.dart mobile/apps/photos/integration_test/ml_parity_android_test.dart mobile/apps/photos/integration_test/ml_parity_ios_test.dart mobile/apps/photos/test_driver/ml_parity_driver.dart`; `flutter analyze mobile/apps/photos/integration_test/ml_parity_shared.dart mobile/apps/photos/integration_test/ml_parity_android_test.dart mobile/apps/photos/integration_test/ml_parity_ios_test.dart mobile/apps/photos/test_driver/ml_parity_driver.dart`; `bash -n infra/ml/tools/run_suite.sh`; `infra/ml/tools/run_suite.sh --suite smoke --platforms android --allow-empty-comparison --output-dir /tmp/ml_parity_android_smoke3`; `infra/ml/tools/run_suite.sh --suite smoke --platforms ios --allow-empty-comparison --output-dir /tmp/ml_parity_ios_smoke2` (fails in this environment with missing iOS module `receive_sharing_intent`) | Implement W9 selective parity CI workflow and W10 maintenance/docs updates. |
+| 2026-02-17 | Codex (GPT-5) | Made Android/iOS parity runners robust to per-file inference/decode failures so runs still emit `results.json` and proceed to comparison; regenerated missing Flutter Rust Bridge artifacts required by Android builds; validated both Android and iOS parity runners now execute end-to-end against real emulator/simulator devices and write outputs. | `mobile/apps/photos/integration_test/ml_parity_shared.dart`, `mobile/apps/photos/ios/Podfile`, `mobile/apps/photos/ios/Podfile.lock`, `mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj`, generated FRB artifacts under gitignored `mobile/apps/photos/lib/src/rust/*` and `mobile/packages/rust/rust/src/frb_generated.rs` | `dart run melos run codegen:rust:photos`; `dart run melos run codegen:rust:packages`; `dart format mobile/apps/photos/integration_test/ml_parity_shared.dart`; `flutter analyze mobile/apps/photos/integration_test/ml_parity_shared.dart`; `ML_PARITY_ANDROID_DEVICE_ID=emulator-5554 infra/ml/tools/run_suite.sh --suite smoke --platforms android --output-dir /tmp/ml_parity_android_live`; `ML_PARITY_IOS_DEVICE_ID=78739D64-4BF5-4A4F-89CA-5F538B5FF68D infra/ml/tools/run_suite.sh --suite smoke --platforms ios --output-dir /tmp/ml_parity_ios_live` | Move to W9 (selective CI workflow) and W10 (maintenance docs), then tune thresholds/known exceptions for currently failing HEIC edge cases surfaced by parity reports. |
### Decisions and Rationale Log
| Date | Decision | Rationale | Impacted Files |
@@ -115,11 +117,13 @@ This section is for implementation agents to keep a running log so handoffs stay
| 2026-02-16 | Implement Python ground truth using trusted library primitives (Pillow/OpenCV/ORT), avoiding handwritten interpolation and NMS logic. | Keeps the reference pipeline easier to audit and maintain while still mirroring the mobile `analyzeImageStatic` flow and model behavior. | `infra/ml/ground_truth/_runtime.py`, `infra/ml/ground_truth/clip.py`, `infra/ml/ground_truth/face_detection.py`, `infra/ml/ground_truth/face_alignment.py`, `infra/ml/ground_truth/face_embedding.py`, `infra/ml/ground_truth/pipeline.py` |
| 2026-02-16 | Desktop runner orchestration is dependency-aware and non-fatal by default when desktop/web node installs are absent. | Preserves one-command suite usability in Python-only environments while still auto-running real desktop parity when prerequisites exist; strict mode can still fail on missing outputs. | `infra/ml/tools/run_suite.sh`, `desktop/scripts/ml_parity_runner.ts`, `desktop/scripts/ml_parity_host.js` |
| 2026-02-16 | Desktop parity decode must use the same conversion+bitmap decode path as production (`renderableImageBlob` then `createImageBitmapAndData` semantics), sourced from one shared implementation. | Decode differences can hide regressions in orientation/format handling; parity coverage is only trustworthy if decode semantics match production and stay coupled as code evolves. | `web/packages/new/photos/services/ml/decode.ts`, `web/packages/new/photos/services/ml/blob.ts`, `desktop/scripts/ml_parity_host.js`, `desktop/scripts/ml_parity_runner.ts`, `infra/ml/tools/run_suite.sh` |
+| 2026-02-17 | Mobile parity runners should not abort the full platform run on single-fixture decode/inference errors; they should continue and emit partial results plus per-file errors. | This preserves runner reliability and enables comparator-based reporting (`missing_files` + drift findings) instead of hard runner failure when platform-specific decode/plugin behavior differs. | `mobile/apps/photos/integration_test/ml_parity_shared.dart` |
### Open Questions / Blockers
| Date | Owner | Blocker | Unblocked By |
|---|---|---|---|
-| 2026-02-16 | Codex (GPT-5) | Mobile platform runners are still missing (`mobile/apps/photos/integration_test/ml_parity_android_test.dart`, `mobile/apps/photos/integration_test/ml_parity_ios_test.dart`), so parity compare can still run with desktop/python only. | Implement W5/W6 and wire both runners into `run_suite.sh` with shared-schema outputs. |
+| 2026-02-16 | Codex (GPT-5) | Running mobile parity still requires an available Android device/emulator and iOS simulator/device in the local environment; `run_suite.sh` skips platform runs when no matching device is detected. | Start/attach platform devices (or provide explicit IDs via `ML_PARITY_ANDROID_DEVICE_ID` / `ML_PARITY_IOS_DEVICE_ID`) before invoking `run_suite.sh`. |
+| 2026-02-17 | Codex (GPT-5) | Comparator currently fails for Android/iOS smoke runs due fixture-level decode/plugin gaps (Android HEIC decode fallback failure on one fixture; iOS `flutter_image_compress` missing plugin implementation in integration-test isolate path affecting HEIC conversion). | Add known-exception/skip policy for specific fixture+platform combinations in manifest/comparator, or fix underlying decode/plugin behavior in the mobile pipeline/runtime so those fixtures index successfully in test context. |
### Handoff Checklist
- [x] Added brief implementation note to `Implementation Log`
diff --git a/infra/ml/tools/run_suite.sh b/infra/ml/tools/run_suite.sh
index bc15897d87..6763a726b6 100755
--- a/infra/ml/tools/run_suite.sh
+++ b/infra/ml/tools/run_suite.sh
@@ -74,6 +74,17 @@ OUTPUT_DIR="$(cd "$OUTPUT_DIR" && pwd -P)"
PYTHON_OUTPUT_DIR="$OUTPUT_DIR/python"
rm -rf "$PYTHON_OUTPUT_DIR"
mkdir -p "$PYTHON_OUTPUT_DIR"
+MANIFEST_B64="$(
+ python3 - "$MANIFEST_PATH" <<'PY'
+import base64
+import pathlib
+import sys
+
+manifest_path = pathlib.Path(sys.argv[1])
+print(base64.b64encode(manifest_path.read_bytes()).decode("ascii"))
+PY
+)"
+CODE_REVISION="$(git -C "$ROOT_DIR" rev-parse --short HEAD 2>/dev/null || echo local)"
echo "Running ML parity suite"
echo " suite: $SUITE"
@@ -212,6 +223,218 @@ run_desktop_runner() {
return 0
}
+platform_device_available() {
+ local platform="$1"
+ python3 - "$platform" <<'PY'
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+
+platform = sys.argv[1]
+
+try:
+ raw = subprocess.check_output(
+ ["flutter", "devices", "--machine"],
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+except Exception:
+ sys.exit(2)
+
+try:
+ devices = json.loads(raw)
+except json.JSONDecodeError:
+ sys.exit(2)
+
+def is_match(device: dict[str, object]) -> bool:
+ target = str(device.get("targetPlatform", "")).lower()
+ name = str(device.get("name", "")).lower()
+ if platform == "android":
+ return "android" in target or "android" in name
+ if platform == "ios":
+ return "ios" in target or "iphone" in name or "ipad" in name
+ return False
+
+sys.exit(0 if any(is_match(device) for device in devices) else 1)
+PY
+}
+
+platform_device_id() {
+ local platform="$1"
+ local selected
+ selected="$(
+ python3 - "$platform" <<'PY'
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+
+platform = sys.argv[1]
+
+try:
+ raw = subprocess.check_output(
+ ["flutter", "devices", "--machine"],
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+except Exception:
+ sys.exit(2)
+
+try:
+ devices = json.loads(raw)
+except json.JSONDecodeError:
+ sys.exit(2)
+
+def is_match(device: dict[str, object]) -> bool:
+ target = str(device.get("targetPlatform", "")).lower()
+ name = str(device.get("name", "")).lower()
+ if platform == "android":
+ return "android" in target or "android" in name
+ if platform == "ios":
+ return "ios" in target or "iphone" in name or "ipad" in name
+ return False
+
+for device in devices:
+ if is_match(device):
+ print(device.get("id", ""))
+ sys.exit(0)
+
+sys.exit(1)
+PY
+ )"
+
+ if [[ -n "$selected" ]]; then
+ echo "$selected"
+ return 0
+ fi
+
+ return 1
+}
+
+run_mobile_runner() {
+ local platform="$1"
+ local target="$2"
+ local device_id="${3:-}"
+
+ local mobile_dir="$ROOT_DIR/mobile/apps/photos"
+ local driver_path="$mobile_dir/test_driver/ml_parity_driver.dart"
+ local target_path="$mobile_dir/$target"
+ local platform_output_dir="$OUTPUT_DIR/$platform"
+ local output_path="$platform_output_dir/results.json"
+
+ if [[ ! -f "$driver_path" ]]; then
+ echo "Mobile parity driver not found at $driver_path; skipping $platform run."
+ return 2
+ fi
+
+ if [[ ! -f "$target_path" ]]; then
+ echo "Mobile parity test target not found at $target_path; skipping $platform run."
+ return 2
+ fi
+
+ if ! command -v flutter >/dev/null 2>&1; then
+ echo "flutter is required to run mobile parity; skipping $platform run."
+ return 2
+ fi
+
+ if [[ -z "$device_id" ]]; then
+ local platform_available_exit=0
+ if platform_device_available "$platform"; then
+ platform_available_exit=0
+ else
+ platform_available_exit=$?
+ fi
+ case "$platform_available_exit" in
+ 0)
+ ;;
+ 1)
+ echo "No connected $platform device/simulator detected; skipping $platform run."
+ return 2
+ ;;
+ *)
+ echo "Could not determine $platform device availability; skipping $platform run."
+ return 2
+ ;;
+ esac
+ fi
+
+ if [[ ! -f "$mobile_dir/.dart_tool/package_config.json" ]]; then
+ echo "Running flutter pub get for mobile app"
+ if ! (cd "$mobile_dir" && flutter pub get); then
+ echo "flutter pub get failed; $platform parity output not generated."
+ return 1
+ fi
+ fi
+
+ local flavor=""
+ case "$platform" in
+ android)
+ flavor="${ML_PARITY_ANDROID_FLAVOR:-independent}"
+ ;;
+ ios)
+ flavor="${ML_PARITY_IOS_FLAVOR:-}"
+ ;;
+ esac
+
+ local -a drive_cmd=(
+ flutter drive
+ --driver=test_driver/ml_parity_driver.dart
+ --target="$target"
+ )
+ if [[ -n "$flavor" ]]; then
+ drive_cmd+=(--flavor "$flavor")
+ fi
+ drive_cmd+=(
+ --no-dds
+ --dart-define=ML_PARITY_MANIFEST_B64="$MANIFEST_B64"
+ --dart-define=ML_PARITY_CODE_REVISION="$CODE_REVISION"
+ --dart-define=ML_PARITY_SUITE="$SUITE"
+ )
+ if [[ -n "$device_id" ]]; then
+ drive_cmd+=(-d "$device_id")
+ else
+ local selected_device_id
+ if ! selected_device_id="$(platform_device_id "$platform")"; then
+ echo "Could not resolve a connected $platform device; skipping $platform run."
+ return 2
+ fi
+ drive_cmd+=(-d "$selected_device_id")
+ fi
+
+ echo "Running $platform parity runner"
+ if ! (
+ cd "$mobile_dir"
+ ML_PARITY_DRIVER_OUTPUT="$output_path" "${drive_cmd[@]}"
+ ); then
+ echo "$platform parity runner failed; $platform parity output not generated."
+ return 1
+ fi
+
+ if [[ ! -f "$output_path" ]]; then
+ echo "$platform parity runner finished without output at $output_path."
+ return 1
+ fi
+
+ return 0
+}
+
+run_android_runner() {
+ run_mobile_runner \
+ "android" \
+ "integration_test/ml_parity_android_test.dart" \
+ "${ML_PARITY_ANDROID_DEVICE_ID:-}"
+}
+
+run_ios_runner() {
+ run_mobile_runner \
+ "ios" \
+ "integration_test/ml_parity_ios_test.dart" \
+ "${ML_PARITY_IOS_DEVICE_ID:-}"
+}
+
run_platform_runner() {
local platform="$1"
case "$platform" in
@@ -219,12 +442,10 @@ run_platform_runner() {
run_desktop_runner
;;
android)
- echo "Android parity runner is not implemented yet; skipping android run."
- return 2
+ run_android_runner
;;
ios)
- echo "iOS parity runner is not implemented yet; skipping ios run."
- return 2
+ run_ios_runner
;;
*)
echo "Unknown platform: $platform" >&2
diff --git a/mobile/apps/photos/integration_test/ml_parity_android_test.dart b/mobile/apps/photos/integration_test/ml_parity_android_test.dart
new file mode 100644
index 0000000000..6ce001149e
--- /dev/null
+++ b/mobile/apps/photos/integration_test/ml_parity_android_test.dart
@@ -0,0 +1,5 @@
+import "ml_parity_shared.dart";
+
+void main() {
+ runMLParityIntegrationTest(expectedPlatform: "android");
+}
diff --git a/mobile/apps/photos/integration_test/ml_parity_ios_test.dart b/mobile/apps/photos/integration_test/ml_parity_ios_test.dart
new file mode 100644
index 0000000000..98314eaeab
--- /dev/null
+++ b/mobile/apps/photos/integration_test/ml_parity_ios_test.dart
@@ -0,0 +1,5 @@
+import "ml_parity_shared.dart";
+
+void main() {
+ runMLParityIntegrationTest(expectedPlatform: "ios");
+}
diff --git a/mobile/apps/photos/integration_test/ml_parity_shared.dart b/mobile/apps/photos/integration_test/ml_parity_shared.dart
new file mode 100644
index 0000000000..705f62f946
--- /dev/null
+++ b/mobile/apps/photos/integration_test/ml_parity_shared.dart
@@ -0,0 +1,445 @@
+import "dart:convert";
+import "dart:io";
+
+import "package:crypto/crypto.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:integration_test/integration_test.dart";
+import "package:package_info_plus/package_info_plus.dart";
+import "package:path_provider/path_provider.dart";
+import "package:photos/core/configuration.dart";
+import "package:photos/core/network/network.dart";
+import "package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart";
+import "package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart";
+import "package:photos/services/machine_learning/ml_indexing_isolate.dart";
+import "package:photos/services/machine_learning/ml_model.dart";
+import "package:photos/services/machine_learning/ml_result.dart";
+import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
+import "package:photos/utils/isolate/isolate_operations.dart";
+
+const _manifestB64 = String.fromEnvironment("ML_PARITY_MANIFEST_B64");
+const _codeRevision =
+ String.fromEnvironment("ML_PARITY_CODE_REVISION", defaultValue: "local");
+
+const _parityReportDataKey = "ml_parity_results_json";
+
+class _ManifestItem {
+ final String fileID;
+ final String sourceURL;
+ final String? sourceSHA256;
+
+ const _ManifestItem({
+ required this.fileID,
+ required this.sourceURL,
+ required this.sourceSHA256,
+ });
+}
+
+class _ModelSpec {
+ final String schemaName;
+ final MlModel model;
+
+ const _ModelSpec({
+ required this.schemaName,
+ required this.model,
+ });
+}
+
+void runMLParityIntegrationTest({required String expectedPlatform}) {
+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+
+ testWidgets(
+ "ML parity runner ($expectedPlatform)",
+ timeout: const Timeout(Duration(minutes: 45)),
+ (tester) async {
+ await tester.runAsync(() async {
+ _validatePlatform(expectedPlatform);
+ final manifestItems = _loadManifestItems();
+ if (manifestItems.isEmpty) {
+ throw StateError("Manifest is empty");
+ }
+
+ final appSupportDir = await getApplicationSupportDirectory();
+ final fixtureRoot =
+ Directory("${appSupportDir.path}/ml_parity/fixtures");
+ await fixtureRoot.create(recursive: true);
+
+ final modelSpecs = _modelSpecs();
+ final loadedModels = await _downloadAndLoadModels(
+ modelSpecs: modelSpecs,
+ );
+
+ final runtime = Platform.isAndroid
+ ? "flutter-mobile-onnx-platform-plugin"
+ : "flutter-mobile-onnx-ffi";
+
+ final results = <Map<String, dynamic>>[];
+ final errors = <Map<String, dynamic>>[];
+ try {
+ for (int i = 0; i < manifestItems.length; i++) {
+ final item = manifestItems[i];
+ final stopwatch = Stopwatch()..start();
+ try {
+ final localFixturePath = await _downloadFixture(
+ item: item,
+ fixtureRoot: fixtureRoot,
+ );
+ final mlResult = await _analyzeImage(
+ fileID: i + 1,
+ filePath: localFixturePath,
+ loadedModels: loadedModels,
+ );
+ stopwatch.stop();
+ results.add(
+ _toParityResult(
+ fileID: item.fileID,
+ mlResult: mlResult,
+ expectedPlatform: expectedPlatform,
+ runtime: runtime,
+ models: loadedModels.modelMetadata,
+ totalMS: stopwatch.elapsedMilliseconds,
+ ),
+ );
+ } catch (error, stackTrace) {
+ stopwatch.stop();
+ final stackLines = stackTrace.toString().split("\n");
+ errors.add({
+ "file_id": item.fileID,
+ "error": error.toString(),
+ "timing_ms": stopwatch.elapsedMilliseconds,
+ "stack": stackLines.isNotEmpty ? stackLines.first : "",
+ });
+ }
+ }
+ } finally {
+ await _releaseModels(loadedModels);
+ }
+
+ final outputPayload = {
+ "platform": expectedPlatform,
+ "results": results,
+ if (errors.isNotEmpty) "errors": errors,
+ };
+
+ binding.reportData = {
+ _parityReportDataKey: jsonEncode(outputPayload),
+ };
+ });
+ },
+ );
+}
+
+void _validatePlatform(String expectedPlatform) {
+ if (expectedPlatform == "android" && !Platform.isAndroid) {
+ throw StateError("Android parity runner launched on non-Android platform");
+ }
+ if (expectedPlatform == "ios" && !Platform.isIOS) {
+ throw StateError("iOS parity runner launched on non-iOS platform");
+ }
+}
+
+List<_ManifestItem> _loadManifestItems() {
+ if (_manifestB64.isEmpty) {
+ throw StateError(
+ "Missing ML_PARITY_MANIFEST_B64 dart define; run via infra/ml/tools/run_suite.sh",
+ );
+ }
+ final manifestBytes = base64Decode(_manifestB64);
+ final manifest =
+ jsonDecode(utf8.decode(manifestBytes)) as Map<String, dynamic>;
+ final items = manifest["items"] as List<dynamic>? ?? const [];
+ return items.map((dynamic rawItem) {
+ final item = rawItem as Map<String, dynamic>;
+ final sourceURL = (item["source_url"] as String?)?.trim() ?? "";
+ if (sourceURL.isEmpty) {
+ throw StateError("Manifest item ${item["file_id"]} missing source_url");
+ }
+ final sourceSHA = (item["source_sha256"] as String?)?.trim();
+ return _ManifestItem(
+ fileID: item["file_id"] as String,
+ sourceURL: sourceURL,
+ sourceSHA256: sourceSHA?.isEmpty == true ? null : sourceSHA,
+ );
+ }).toList(growable: false);
+}
+
+List<_ModelSpec> _modelSpecs() {
+ return [
+ _ModelSpec(
+ schemaName: "face_detection",
+ model: FaceDetectionService.instance,
+ ),
+ _ModelSpec(
+ schemaName: "face_embedding",
+ model: FaceEmbeddingService.instance,
+ ),
+ _ModelSpec(
+ schemaName: "clip",
+ model: ClipImageEncoder.instance,
+ ),
+ ];
+}
+
+class _LoadedModels {
+ final List<String> modelNames;
+ final List<int> modelAddresses;
+ final Map<String, String> modelMetadata;
+
+ const _LoadedModels({
+ required this.modelNames,
+ required this.modelAddresses,
+ required this.modelMetadata,
+ });
+}
+
+Future<_LoadedModels> _downloadAndLoadModels({
+ required List<_ModelSpec> modelSpecs,
+}) async {
+ await _ensureModelNetworkContext();
+
+ final modelNames = <String>[];
+ final modelPaths = <String>[];
+ final modelMetadata = <String, String>{};
+
+ for (final modelSpec in modelSpecs) {
+ final (modelName, modelPath) = await modelSpec.model.getModelNameAndPath();
+ final modelFile = File(modelPath);
+ if (!modelFile.existsSync()) {
+ throw StateError(
+ "Resolved model path does not exist for $modelName: $modelPath",
+ );
+ }
+
+ modelNames.add(modelName);
+ modelPaths.add(modelFile.path);
+ final modelSHA256 = await _sha256HexOfFile(modelFile);
+ modelMetadata[modelSpec.schemaName] =
+ "${modelFile.uri.pathSegments.last}:$modelSHA256";
+ }
+
+ final loadedAddressesRaw = await MLIndexingIsolate.instance.runInIsolate(
+ IsolateOperation.loadIndexingModels,
+ {
+ "modelNames": modelNames,
+ "modelPaths": modelPaths,
+ },
+ ) as List<dynamic>;
+
+ final modelAddresses = loadedAddressesRaw
+ .map((address) => (address as num).toInt())
+ .toList(growable: false);
+ if (modelAddresses.length != modelNames.length) {
+ throw StateError(
+ "Model address count mismatch: expected ${modelNames.length}, got ${modelAddresses.length}",
+ );
+ }
+
+ return _LoadedModels(
+ modelNames: modelNames,
+ modelAddresses: modelAddresses,
+ modelMetadata: modelMetadata,
+ );
+}
+
+bool _modelNetworkContextInitialized = false;
+
+Future<void> _ensureModelNetworkContext() async {
+ if (_modelNetworkContextInitialized) {
+ return;
+ }
+
+ await Configuration.instance.init();
+ final packageInfo = await PackageInfo.fromPlatform();
+ await NetworkClient.instance.init(packageInfo);
+ _modelNetworkContextInitialized = true;
+}
+
+Future<void> _releaseModels(_LoadedModels loadedModels) async {
+ await MLIndexingIsolate.instance.runInIsolate(
+ IsolateOperation.releaseIndexingModels,
+ {
+ "modelNames": loadedModels.modelNames,
+ "modelAddresses": loadedModels.modelAddresses,
+ },
+ );
+}
+
+Future<String> _downloadFixture({
+ required _ManifestItem item,
+ required Directory fixtureRoot,
+}) async {
+ final uri = Uri.parse(item.sourceURL);
+ final outputPath = "${fixtureRoot.path}/${_safeFileName(item.fileID)}";
+ final expectedSHA256 = item.sourceSHA256?.toLowerCase();
+
+ Future<File> ensureFixture() async {
+ final fixtureFile = await _downloadURLToFile(
+ url: item.sourceURL,
+ outputPath: outputPath,
+ );
+ if (expectedSHA256 == null) {
+ return fixtureFile;
+ }
+
+ final actualSHA = (await _sha256HexOfFile(fixtureFile)).toLowerCase();
+ if (actualSHA != expectedSHA256) {
+ throw StateError(
+ "Fixture SHA mismatch for ${item.fileID}: expected $expectedSHA256, got $actualSHA",
+ );
+ }
+ return fixtureFile;
+ }
+
+ File fixtureFile;
+ try {
+ fixtureFile = await ensureFixture();
+ } on StateError {
+ final existingFile = File(outputPath);
+ if (existingFile.existsSync()) {
+ await existingFile.delete();
+ }
+ fixtureFile = await ensureFixture();
+ }
+
+ final fileNameFromURL =
+ uri.pathSegments.isNotEmpty ? uri.pathSegments.last : "";
+ if (fileNameFromURL.isEmpty) {
+ return fixtureFile.path;
+ }
+
+ // Preserve extension semantics from source URL for decoder behavior parity.
+ final extensionHint = fileNameFromURL.split(".").length > 1
+ ? ".${fileNameFromURL.split(".").last}"
+ : "";
+ if (extensionHint.isEmpty || fixtureFile.path.endsWith(extensionHint)) {
+ return fixtureFile.path;
+ }
+
+ final extensionPath = "${fixtureFile.path}$extensionHint";
+ final extensionFile = File(extensionPath);
+ if (!extensionFile.existsSync()) {
+ await fixtureFile.copy(extensionPath);
+ }
+ return extensionPath;
+}
+
+Future<File> _downloadURLToFile({
+ required String url,
+ required String outputPath,
+}) async {
+ final outputFile = File(outputPath);
+ if (outputFile.existsSync()) {
+ return outputFile;
+ }
+
+ await outputFile.parent.create(recursive: true);
+ final tempPath = "$outputPath.tmp";
+ final tempFile = File(tempPath);
+ if (tempFile.existsSync()) {
+ await tempFile.delete();
+ }
+
+ final httpClient = HttpClient();
+ try {
+ final request = await httpClient.getUrl(Uri.parse(url));
+ final response = await request.close();
+ if (response.statusCode < 200 || response.statusCode >= 300) {
+ throw HttpException(
+ "Failed to download $url: HTTP ${response.statusCode}",
+ uri: Uri.parse(url),
+ );
+ }
+ final sink = tempFile.openWrite();
+ await response.pipe(sink);
+ await sink.close();
+ await tempFile.rename(outputPath);
+ } finally {
+ httpClient.close(force: true);
+ }
+
+ return outputFile;
+}
+
+Future<MLResult> _analyzeImage({
+ required int fileID,
+ required String filePath,
+ required _LoadedModels loadedModels,
+}) async {
+ final faceDetectionAddress = loadedModels.modelAddresses[0];
+ final faceEmbeddingAddress = loadedModels.modelAddresses[1];
+ final clipAddress = loadedModels.modelAddresses[2];
+
+ final resultJSONString = await MLIndexingIsolate.instance.runInIsolate(
+ IsolateOperation.analyzeImage,
+ {
+ "enteFileID": fileID,
+ "filePath": filePath,
+ "runFaces": true,
+ "runClip": true,
+ "faceDetectionAddress": faceDetectionAddress,
+ "faceEmbeddingAddress": faceEmbeddingAddress,
+ "clipImageAddress": clipAddress,
+ },
+ ) as String;
+ return MLResult.fromJsonString(resultJSONString);
+}
+
+Map<String, dynamic> _toParityResult({
+ required String fileID,
+ required MLResult mlResult,
+ required String expectedPlatform,
+ required String runtime,
+ required Map<String, String> models,
+ required int totalMS,
+}) {
+ final clip = mlResult.clip;
+ if (clip == null) {
+ throw StateError("Missing CLIP result for $fileID");
+ }
+
+ final faces = (mlResult.faces ?? const <FaceResult>[]).map((face) {
+ final box = face.detection.box;
+ return {
+ "box": [
+ box[0],
+ box[1],
+ box[2] - box[0],
+ box[3] - box[1],
+ ],
+ "landmarks": face.detection.allKeypoints
+ .map((point) => [point[0], point[1]])
+ .toList(growable: false),
+ "score": face.detection.score,
+ "embedding": List<double>.from(face.embedding, growable: false),
+ };
+ }).toList(growable: false);
+
+ return {
+ "file_id": fileID,
+ "clip": {
+ "embedding": List<double>.from(clip.embedding, growable: false),
+ },
+ "faces": faces,
+ "runner_metadata": {
+ "platform": expectedPlatform,
+ "runtime": runtime,
+ "models": models,
+ "code_revision": _codeRevision,
+ "timing_ms": {
+ "total": totalMS.toDouble(),
+ },
+ },
+ };
+}
+
+String _safeFileName(String value) {
+ final sanitized = value.replaceAll(RegExp(r"[^a-zA-Z0-9._-]"), "_");
+ if (sanitized.isNotEmpty) {
+ return sanitized;
+ }
+ return "file";
+}
+
+Future<String> _sha256HexOfFile(File file) async {
+ final digest = await sha256.bind(file.openRead()).first;
+ return digest.toString();
+}
diff --git a/mobile/apps/photos/test_driver/ml_parity_driver.dart b/mobile/apps/photos/test_driver/ml_parity_driver.dart
new file mode 100644
index 0000000000..e355cd91ef
--- /dev/null
+++ b/mobile/apps/photos/test_driver/ml_parity_driver.dart
@@ -0,0 +1,34 @@
+import "dart:io";
+
+import "package:integration_test/integration_test_driver.dart";
+
+const _parityReportDataKey = "ml_parity_results_json";
+const _driverOutputEnvKey = "ML_PARITY_DRIVER_OUTPUT";
+
+Future<void> main() {
+ return integrationDriver(
+ responseDataCallback: (data) async {
+ final outputPath = Platform.environment[_driverOutputEnvKey]?.trim();
+ if (outputPath == null || outputPath.isEmpty) {
+ throw StateError(
+ "Missing $_driverOutputEnvKey environment variable for parity driver output path",
+ );
+ }
+ if (data == null) {
+ throw StateError("Integration test returned null response data");
+ }
+
+ final payload = data[_parityReportDataKey];
+ if (payload is! String || payload.isEmpty) {
+ throw StateError(
+ "Missing parity report data key '$_parityReportDataKey'",
+ );
+ }
+
+ final outputFile = File(outputPath);
+ await outputFile.parent.create(recursive: true);
+ await outputFile.writeAsString("$payload\n");
+ stdout.writeln("ML parity output written to $outputPath");
+ },
+ );
+}