π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
cargo test ml indexing mvp
laurenspriem838f0f0a1943
diff --git a/.github/workflows/rust-lint.yml b/.github/workflows/rust-lint.ymlindex 13f8e930ff..9acb24b816 100644--- a/.github/workflows/rust-lint.yml+++ b/.github/workflows/rust-lint.yml@@ -43,7 +43,7 @@ jobs:- run: cargo clippy --all-targets --locked- - run: cargo test --locked --workspace+ - run: cargo test --locked --workspace --features ente-photos/ml-assets- run: cargo install cargo-audit --version 0.22.2 --lockeddiff --git a/infra/ml/test/README.md b/infra/ml/test/README.mdindex d20f7f94c9..425bfe1948 100644--- a/infra/ml/test/README.md+++ b/infra/ml/test/README.md@@ -7,6 +7,7 @@ This directory contains the ML indexing parity framework for Android, iOS, deskt- `ground_truth/`: schema, manifest, and ONNX-backed Python pipeline.- `comparator/`: parity comparison engine and threshold checks.- `tools/`: suite orchestration and CLI entrypoints.+- `ml_indexing/`: asset lock for the Cargo-based Rust ML indexing test.- Runtime-only artifacts (gitignored): `test_data/`, `out/`, `.cache/`.## Prerequisites@@ -45,6 +46,34 @@ Optional mobile reuse env vars:- `ML_PARITY_ANDROID_EXISTING_APP_URL`, `ML_PARITY_IOS_EXISTING_APP_URL` (reuse a currently running app via VM service URL)- `ML_PARITY_ANDROID_APPLICATION_BINARY`, `ML_PARITY_IOS_APPLICATION_BINARY` (explicit prebuilt binary path for `flutter drive --use-application-binary`)+## Rust ML Indexing Cargo Test++The Rust-only ML indexing test lives at `rust/crates/photos/tests/ml_indexing.rs`.+It is gated by the `ente-photos/ml-assets` Cargo feature so ordinary local+`cargo test --workspace` runs do not download ML assets or execute indexing.++From `rust/`:++```sh+cargo test -p ente-photos --test ml_indexing --features ml-assets -- --nocapture+```++By default the test downloads the external fixture manifest, fixture images,+Python golden JSON, ONNX Runtime dynamic library, and ONNX models into+`rust/target/ml-assets-cache/`, with SHA-256 verification for every asset. For+local work against a checked-out fixture repo, point the test at the dataset+root:++```sh+ENTE_ML_ASSETS_REPO_DIR=/path/to/test-fixtures/ml/indexing/v1 \+ cargo test -p ente-photos --test ml_indexing --features ml-assets -- --nocapture+```++`infra/ml/test/ml_indexing/assets.json` locks the external manifest, Python+golden, model URLs, expected unsupported decode files, and thresholds. The+current RAW/CR2 fixture is expected to fail Rust decode; the test verifies that+failure path and skips golden comparison for that file until RAW support lands.+## Detection Overlay VisualizerRender face detection overlays (box + score + landmarks) for each platform output:@@ -87,17 +116,28 @@ Outputs:## Golden Update / Maintenance-Goldens are runtime artifacts and are not committed.+Goldens under this monorepo's `out/`, `test_data/`, and cache directories are+runtime artifacts and are not committed. The Rust ML indexing golden JSON is+different: it belongs in the external `test-fixtures` repo next to the image+corpus, because it describes that corpus.Use this process when corpus/threshold/model behavior changes intentionally:-1. Update corpus metadata in `infra/ml/test/ground_truth/manifest.json`; thresholds live in `ThresholdConfig` in `infra/ml/test/comparator/compare.py`.+1. Update corpus metadata in the external fixture repo. Rust ML indexing thresholds live in `infra/ml/test/ml_indexing/assets.json`; shell-suite thresholds live in `ThresholdConfig` in `infra/ml/test/comparator/compare.py`.2. Regenerate and compare with a real run:```shbash infra/ml/test/run_ml_parity_tests.sh --platforms all --output-dir infra/ml/test/out/parity```-3. Review `infra/ml/test/out/parity/parity_report.html`, `comparison_report.json`, and per-platform `results.json` files.-4. If drift is expected, adjust thresholds/known exceptions and rerun until stable.-5. Commit code/config/docs updates only; do not commit generated `out/`, `test_data/`, or cache artifacts.+3. Regenerate the Rust ML indexing golden in the external fixture repo:++```sh+uv run --project infra/ml \+ python infra/ml/test/tools/generate_ml_indexing_golden.py \+ --assets-repo-dir /path/to/test-fixtures/ml/indexing/v1+```++4. Review `infra/ml/test/out/parity/parity_report.html`, `comparison_report.json`, per-platform `results.json` files, and the generated external `goldens/python/results.json`.+5. If drift is expected, update thresholds/known exceptions and the Python golden SHA in `infra/ml/test/ml_indexing/assets.json`, then rerun until stable.+6. Commit code/config/docs updates in this repo; commit the corpus manifest and Python golden JSON in the external fixture repo. Do not commit generated `out/`, `test_data/`, or cache artifacts in this repo.diff --git a/infra/ml/test/ml_indexing/assets.json b/infra/ml/test/ml_indexing/assets.jsonnew file mode 100644index 0000000000..d9dfa44a91--- /dev/null+++ b/infra/ml/test/ml_indexing/assets.json@@ -0,0 +1,75 @@+{+ "schema_version": 1,+ "dataset": "ml-indexing/v1",+ "fixture_base_url": "https://raw.githubusercontent.com/laurenspriem/test-fixtures/ml_more_test_data/ml/indexing/v1/",+ "manifest": {+ "path": "manifest.json",+ "url": "https://raw.githubusercontent.com/laurenspriem/test-fixtures/ml_more_test_data/ml/indexing/v1/manifest.json",+ "sha256": "b9a3b648740b38aa1259a8123fd08f8d1a445ae87549f0406edddc1b7a9025ac"+ },+ "python_golden": {+ "path": "goldens/python/results.json",+ "url": "https://raw.githubusercontent.com/laurenspriem/test-fixtures/ml_more_test_data/ml/indexing/v1/goldens/python/results.json",+ "sha256": "7acb061809e7daea1992d20252ce444d5e15919df7217e7a98adc3a218f76c12"+ },+ "onnx_runtime": {+ "version": "1.18.1",+ "archives": {+ "aarch64-apple-darwin": {+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.18.1/onnxruntime-osx-arm64-1.18.1.tgz",+ "sha256": "f3356203e9b6f5023168a12db74b1060ab397f8f3ce8f5cb2c2bd9e7f1195b01",+ "library_path": "onnxruntime-osx-arm64-1.18.1/lib/libonnxruntime.1.18.1.dylib",+ "library_sha256": "cf0c4da3d0ccae9b71cc854333e716d162869a3c42f9017b142408542fcec9b7"+ },+ "x86_64-apple-darwin": {+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.18.1/onnxruntime-osx-x86_64-1.18.1.tgz",+ "sha256": "938198521ecccd6fca4cadd627a57966de092feb6ea9ecb579437898d04ebad8",+ "library_path": "onnxruntime-osx-x86_64-1.18.1/lib/libonnxruntime.1.18.1.dylib",+ "library_sha256": "b25f77bf7c58ef0fbcdd5fb090301df4e80f82cf0000ceed1042418729b6594d"+ },+ "x86_64-unknown-linux-gnu": {+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.18.1/onnxruntime-linux-x64-1.18.1.tgz",+ "sha256": "a0994512ec1e1debc00c18bfc7a5f16249f6ebd6a6128ff2034464cc380ea211",+ "library_path": "onnxruntime-linux-x64-1.18.1/lib/libonnxruntime.so.1.18.1",+ "library_sha256": "1147caa734d19f7549f90a659aa9ca444366eeb80a596900d19d242145a9f4c9"+ },+ "aarch64-unknown-linux-gnu": {+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.18.1/onnxruntime-linux-aarch64-1.18.1.tgz",+ "sha256": "c1dcd8ab29e8d227d886b6ee415c08aea893956acf98f0758a42a84f27c02851",+ "library_path": "onnxruntime-linux-aarch64-1.18.1/lib/libonnxruntime.so.1.18.1",+ "library_sha256": "006437cc7da2dd9a8a116e3fb0c96fe9c4ec8645fccbb731f3b02082a6fbf70e"+ }+ }+ },+ "models": {+ "face_detection": {+ "file_name": "yolov5s_face_640_640_dynamic.onnx",+ "url": "https://models.ente.io/yolov5s_face_640_640_dynamic.onnx",+ "sha256": "71a008707283b03db4881449a24f4da197f9dbd9ddaca5c91fcdb363fbf7e06f"+ },+ "face_embedding": {+ "file_name": "mobilefacenet_opset15.onnx",+ "url": "https://models.ente.io/mobilefacenet_opset15.onnx",+ "sha256": "472a0f7e24d0b070cbbdc031b085bc2a06c70655b3bdefb87dbd69bc98662f45"+ },+ "clip_image": {+ "file_name": "mobileclip_s2_image.onnx",+ "url": "https://models.ente.io/mobileclip_s2_image.onnx",+ "sha256": "ef54ec66c687603eb4dd303e20d9b67e81069d3133b1c69a70028c76718b7752"+ }+ },+ "expected_unsupported_decode_file_ids": [+ "IMG_8905.CR2"+ ],+ "thresholds": {+ "clip_cosine_distance": 0.015,+ "face_embedding_cosine_distance": 0.015,+ "box_iou": 0.8,+ "face_duplicate_iou": 0.8,+ "face_match_iou_floor": 0.05,+ "landmark_error": 0.03,+ "score_delta": 0.05,+ "min_face_score_for_comparison": 0.8,+ "embedding_norm_tolerance": 0.001+ }+}diff --git a/infra/ml/test/tools/generate_ml_indexing_golden.py b/infra/ml/test/tools/generate_ml_indexing_golden.pynew file mode 100644index 0000000000..90f0341a49--- /dev/null+++ b/infra/ml/test/tools/generate_ml_indexing_golden.py@@ -0,0 +1,197 @@+#!/usr/bin/env python3+from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path+import subprocess+from typing import Any, Mapping++from _paths import repo_root, resolve_repo_relative++from ground_truth.pipeline import GroundTruthPipeline+from ground_truth.schema import dump_results_document+++DEFAULT_ASSET_LOCK = "infra/ml/test/ml_indexing/assets.json"+++def _git_revision(default: str = "local") -> str:+ try:+ completed = subprocess.run(+ ["git", "rev-parse", "--short", "HEAD"],+ capture_output=True,+ text=True,+ check=True,+ )+ except (subprocess.SubprocessError, FileNotFoundError):+ return default+ return completed.stdout.strip() or default+++def _sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as source_file:+ for chunk in iter(lambda: source_file.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _validate_sha256(path: Path, expected_sha256: str, *, label: str) -> None:+ actual_sha256 = _sha256(path)+ if actual_sha256.lower() != expected_sha256.lower():+ raise ValueError(+ f"{label} hash mismatch at {path}: expected {expected_sha256}, got {actual_sha256}"+ )+++def _default_assets_repo_dir(root: Path) -> Path:+ env_path = os.environ.get("ENTE_ML_ASSETS_REPO_DIR")+ if env_path:+ return Path(env_path)+ return root.parent / "test-fixtures" / "ml" / "indexing" / "v1"+++def _file_id(path_value: str) -> str:+ file_name = Path(path_value).name+ if not file_name:+ raise ValueError(f"Could not derive file_id from manifest path: {path_value}")+ return file_name+++def _build_results(+ *,+ assets_repo_dir: Path,+ manifest: Mapping[str, Any],+ model_cache_dir: Path,+ model_base_url: str,+ code_revision: str,+):+ pipeline = GroundTruthPipeline(+ model_cache_dir=model_cache_dir,+ model_base_url=model_base_url,+ )++ results = []+ for item in manifest.get("files", []):+ path_value = str(item["path"])+ source_path = assets_repo_dir / path_value+ file_id = _file_id(path_value)+ if not source_path.exists():+ raise FileNotFoundError(+ f"source file does not exist for '{file_id}': {source_path}"+ )++ expected_sha256 = item.get("sha256")+ if expected_sha256:+ _validate_sha256(+ source_path,+ str(expected_sha256),+ label=f"source fixture {file_id}",+ )++ results.append(+ pipeline.analyze_image(+ file_id=file_id,+ source_path=source_path,+ code_revision=code_revision,+ )+ )++ if not results:+ raise ValueError("Manifest has no files")+ return tuple(results)+++def _dump_deterministic_results(results) -> str:+ payload = json.loads(dump_results_document(results, platform="python"))+ for result in payload["results"]:+ result["runner_metadata"].pop("timing_ms", None)+ return json.dumps(payload, indent=2, sort_keys=True)+++def main() -> int:+ parser = argparse.ArgumentParser(+ description="Generate the Python golden JSON used by the Rust ML indexing Cargo test.",+ )+ parser.add_argument(+ "--asset-lock",+ default=DEFAULT_ASSET_LOCK,+ help="Path to infra/ml/test/ml_indexing/assets.json.",+ )+ parser.add_argument(+ "--assets-repo-dir",+ default=None,+ help=(+ "Path to the external fixture dataset root "+ "(for example test-fixtures/ml/indexing/v1). Defaults to "+ "ENTE_ML_ASSETS_REPO_DIR or ../test-fixtures/ml/indexing/v1."+ ),+ )+ parser.add_argument(+ "--output",+ default=None,+ help="Output JSON path. Defaults to the python_golden.path from the asset lock.",+ )+ parser.add_argument(+ "--model-cache-dir",+ default="infra/ml/test/.cache/onnx_models",+ help="Directory where ONNX models are cached locally.",+ )+ parser.add_argument(+ "--model-base-url",+ default="https://models.ente.io/",+ help="Base URL for downloading ONNX model files.",+ )+ args = parser.parse_args()++ root = repo_root()+ asset_lock_path = resolve_repo_relative(args.asset_lock, repo_root=root)+ asset_lock = json.loads(asset_lock_path.read_text())++ assets_repo_dir = (+ Path(args.assets_repo_dir)+ if args.assets_repo_dir+ else _default_assets_repo_dir(root)+ )+ manifest_path = assets_repo_dir / asset_lock["manifest"]["path"]+ manifest = json.loads(manifest_path.read_text())+ _validate_sha256(+ manifest_path,+ str(asset_lock["manifest"]["sha256"]),+ label="fixture manifest",+ )++ output_path = (+ Path(args.output)+ if args.output+ else assets_repo_dir / asset_lock["python_golden"]["path"]+ )+ model_cache_dir = resolve_repo_relative(args.model_cache_dir, repo_root=root)++ results = _build_results(+ assets_repo_dir=assets_repo_dir,+ manifest=manifest,+ model_cache_dir=model_cache_dir,+ model_base_url=args.model_base_url,+ code_revision=_git_revision(),+ )++ output_path.parent.mkdir(parents=True, exist_ok=True)+ output_path.write_text(_dump_deterministic_results(results))+ sha256 = _sha256(output_path)+ expected_sha256 = str(asset_lock["python_golden"]["sha256"]).lower()+ print(f"Generated {len(results)} Python ML indexing result(s): {output_path}")+ print(f"SHA-256: {sha256}")+ if sha256 != expected_sha256:+ print(+ "NOTE: generated SHA-256 differs from the asset lock. "+ "Update infra/ml/test/ml_indexing/assets.json if this drift is intentional."+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 33a5c40379..a76d0d1b0d 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2420,8 +2420,10 @@ dependencies = [name = "ente-photos"version = "0.0.0"dependencies = [+ "anyhow","ente-image","fast_image_resize",+ "flate2","half","html-escape","image",@@ -2432,6 +2434,11 @@ dependencies = ["plsfix","quick-xml","regex",+ "reqwest 0.12.28",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "tar","tempfile","thiserror 2.0.18","usearch",@@ -6917,6 +6924,7 @@ dependencies = ["base64 0.22.1","bytes","encoding_rs",+ "futures-channel","futures-core","futures-util","h2",diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.tomlindex 9474ec1442..70a2e8a921 100644--- a/rust/crates/photos/Cargo.toml+++ b/rust/crates/photos/Cargo.toml@@ -2,6 +2,10 @@name = "ente-photos"edition = "2024"+[features]+default = []+ml-assets = []+[dependencies]ente-image.workspace = truequick-xml = "0.41"@@ -45,4 +49,16 @@ ort = { git = "https://github.com/pykeio/ort.git", tag = "v2.0.0-rc.4", default-] }[dev-dependencies]+anyhow = "1"+flate2 = "1.1"+reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls-webpki-roots"] }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+sha2 = "0.10"+tar = "0.4"tempfile = "3.12"++[[test]]+name = "ml_indexing"+path = "tests/ml_indexing.rs"+required-features = ["ml-assets"]diff --git a/rust/crates/photos/tests/ml_indexing.rs b/rust/crates/photos/tests/ml_indexing.rsnew file mode 100644index 0000000000..33302acd8c--- /dev/null+++ b/rust/crates/photos/tests/ml_indexing.rs@@ -0,0 +1,20 @@+mod support;++use anyhow::Result;+use support::ml_indexing::{MlIndexingTestContext, fail_if_any, run_with_large_stack};++#[test]+fn rust_ml_matches_python_goldens() {+ run_with_large_stack("rust_ml_matches_python_goldens", run_ml_indexing_test);+}++fn run_ml_indexing_test() -> Result<()> {+ let context = MlIndexingTestContext::load()?;+ let runtime = context.prepare_runtime()?;++ let mut failures = context.validate_manifest_expectations()?;+ let rust_results = context.run_rust_indexing(&runtime, &mut failures)?;+ context.compare_with_python_goldens(&rust_results, &mut failures)?;++ fail_if_any(failures)+}diff --git a/rust/crates/photos/tests/support/ml_indexing.rs b/rust/crates/photos/tests/support/ml_indexing.rsnew file mode 100644index 0000000000..697e8a485b--- /dev/null+++ b/rust/crates/photos/tests/support/ml_indexing.rs@@ -0,0 +1,1249 @@+use std::{+ collections::{BTreeSet, HashMap, HashSet},+ fs,+ io::{Read, Write},+ path::{Path, PathBuf},+};++use anyhow::{Context, Result, anyhow, bail};+use ente_photos::ml::{+ error::MlError,+ indexing::{+ AnalyzeImageRequest, AnalyzeImageResult, analyze_image, init_ml_runtime, release_ml_runtime,+ },+ runtime::{ExecutionProviderPolicy, MlRuntimeConfig, ModelPaths},+ types::FaceResult as RustFaceResult,+};+use flate2::read::GzDecoder;+use reqwest::{Url, blocking::Client};+use serde::Deserialize;+use sha2::{Digest, Sha256};++const ASSET_LOCK_PATH: &str = "infra/ml/test/ml_indexing/assets.json";+const CLIP_EMBEDDING_DIM: usize = 512;+const FACE_EMBEDDING_DIM: usize = 192;+const FLOAT_TOLERANCE: f64 = 1e-8;++pub(crate) fn run_with_large_stack(name: &str, test: fn() -> Result<()>) {+ let result = std::thread::Builder::new()+ .name(name.to_string())+ .stack_size(64 * 1024 * 1024)+ .spawn(test)+ .expect("spawn ML indexing test thread")+ .join();++ match result {+ Ok(Ok(())) => {}+ Ok(Err(error)) => panic!("{error:#}"),+ Err(panic) => std::panic::resume_unwind(panic),+ }+}++pub(crate) fn fail_if_any(mut failures: Vec<String>) -> Result<()> {+ if failures.is_empty() {+ return Ok(());+ }++ failures.sort();+ bail!(+ "Rust ML indexing test failed with {} finding(s):\n{}",+ failures.len(),+ failures.join("\n")+ );+}++pub(crate) struct MlIndexingTestContext {+ asset_lock: AssetLock,+ cache_dir: PathBuf,+ client: Client,+ golden_results: HashMap<String, ComparableResult>,+ local_assets_root: Option<PathBuf>,+ manifest: FixtureManifest,+ runtime_config: MlRuntimeConfig,+}++impl MlIndexingTestContext {+ pub(crate) fn load() -> Result<Self> {+ let repo_root = repo_root()?;+ let asset_lock = load_asset_lock(&repo_root)?;+ let cache_dir = cache_dir(&repo_root);+ let local_assets_root = std::env::var_os("ENTE_ML_ASSETS_REPO_DIR").map(PathBuf::from);+ let client = Client::builder()+ .user_agent("ente-rust-ml-indexing-test")+ .build()+ .context("build HTTP client")?;++ let manifest_path = resolve_document_asset(+ &client,+ local_assets_root.as_deref(),+ &cache_dir,+ "manifest",+ &asset_lock.manifest,+ )?;+ let golden_path = resolve_document_asset(+ &client,+ local_assets_root.as_deref(),+ &cache_dir,+ "python-golden",+ &asset_lock.python_golden,+ )?;+ let manifest = load_manifest(&manifest_path)?;+ let golden_results = load_golden_results(&golden_path)?;++ let onnx_runtime_library =+ resolve_onnx_runtime_library(&client, &cache_dir, &asset_lock.onnx_runtime)?;+ ort::init_from(onnx_runtime_library.to_string_lossy())+ .commit()+ .context("initialize ONNX Runtime dynamic library")?;++ let runtime_config = MlRuntimeConfig {+ model_paths: resolve_model_paths(&client, &cache_dir, &asset_lock.models)?,+ provider_policy: ExecutionProviderPolicy {+ prefer_coreml: false,+ prefer_nnapi: false,+ prefer_xnnpack: false,+ allow_cpu_fallback: true,+ },+ };++ Ok(Self {+ asset_lock,+ cache_dir,+ client,+ golden_results,+ local_assets_root,+ manifest,+ runtime_config,+ })+ }++ pub(crate) fn prepare_runtime(&self) -> Result<PreparedMlRuntime> {+ init_ml_runtime(self.runtime_config.clone()).context("prepare ML runtime")?;+ Ok(PreparedMlRuntime {+ config: self.runtime_config.clone(),+ })+ }++ pub(crate) fn validate_manifest_expectations(&self) -> Result<Vec<String>> {+ let mut failures = Vec::new();+ let manifest_ids = self.manifest_file_ids()?;+ for file_id in self.unsupported_decode_file_ids() {+ if !manifest_ids.contains(&file_id) {+ failures.push(format!(+ "{file_id}: expected unsupported decode entry is not present in manifest"+ ));+ }+ }+ Ok(failures)+ }++ pub(crate) fn run_rust_indexing(+ &self,+ runtime: &PreparedMlRuntime,+ failures: &mut Vec<String>,+ ) -> Result<HashMap<String, ComparableResult>> {+ let expected_unsupported = self.unsupported_decode_file_ids();+ let mut rust_results = HashMap::new();++ for (index, fixture) in self.manifest.files.iter().enumerate() {+ let file_id = file_id_for_manifest_path(&fixture.path)?;+ let image_path = match self.resolve_fixture(fixture) {+ Ok(path) => path,+ Err(error) => {+ failures.push(format!("{file_id}: failed to resolve fixture: {error:#}"));+ continue;+ }+ };+ let req = AnalyzeImageRequest {+ file_id: (index + 1) as i64,+ image_path: image_path.to_string_lossy().into_owned(),+ run_faces: true,+ run_clip: true,+ run_pets: false,+ runtime_config: runtime.config().clone(),+ };++ if expected_unsupported.contains(&file_id) {+ expect_decode_error(&file_id, req, failures);+ continue;+ }++ match analyze_image(req) {+ Ok(result) => match comparable_from_rust(&file_id, &result) {+ Ok(comparable) => {+ if rust_results.insert(file_id.clone(), comparable).is_some() {+ failures.push(format!("{file_id}: duplicate Rust result"));+ }+ }+ Err(error) => {+ failures.push(format!("{file_id}: invalid Rust result: {error:#}"))+ }+ },+ Err(error) => failures.push(format!("{file_id}: Rust ML indexing failed: {error}")),+ }+ }++ Ok(rust_results)+ }++ pub(crate) fn compare_with_python_goldens(+ &self,+ rust_results: &HashMap<String, ComparableResult>,+ failures: &mut Vec<String>,+ ) -> Result<()> {+ let expected_unsupported = self.unsupported_decode_file_ids();+ let supported_manifest_ids = self+ .manifest_file_ids()?+ .into_iter()+ .filter(|file_id| !expected_unsupported.contains(file_id))+ .collect::<BTreeSet<_>>();++ for file_id in &supported_manifest_ids {+ if !self.golden_results.contains_key(file_id) {+ failures.push(format!("{file_id}: missing from Python golden"));+ }+ if !rust_results.contains_key(file_id) {+ failures.push(format!("{file_id}: missing from Rust results"));+ }+ }++ for file_id in self.golden_results.keys() {+ if !supported_manifest_ids.contains(file_id) && !expected_unsupported.contains(file_id)+ {+ failures.push(format!(+ "{file_id}: Python golden is not present in manifest"+ ));+ }+ }++ for file_id in &supported_manifest_ids {+ let Some(golden) = self.golden_results.get(file_id) else {+ continue;+ };+ let Some(rust) = rust_results.get(file_id) else {+ continue;+ };+ compare_results(file_id, golden, rust, &self.asset_lock.thresholds, failures);+ }++ Ok(())+ }++ fn manifest_file_ids(&self) -> Result<BTreeSet<String>> {+ let mut ids = BTreeSet::new();+ for file in &self.manifest.files {+ let file_id = file_id_for_manifest_path(&file.path)?;+ if !ids.insert(file_id.clone()) {+ bail!("manifest has duplicate file id: {file_id}");+ }+ }+ Ok(ids)+ }++ fn resolve_fixture(&self, fixture: &FixtureFile) -> Result<PathBuf> {+ resolve_fixture_asset(+ &self.client,+ self.local_assets_root.as_deref(),+ &self.cache_dir,+ &self.asset_lock.fixture_base_url,+ fixture,+ )+ }++ fn unsupported_decode_file_ids(&self) -> HashSet<String> {+ self.asset_lock+ .expected_unsupported_decode_file_ids+ .iter()+ .cloned()+ .collect()+ }+}++pub(crate) struct PreparedMlRuntime {+ config: MlRuntimeConfig,+}++impl PreparedMlRuntime {+ fn config(&self) -> &MlRuntimeConfig {+ &self.config+ }+}++impl Drop for PreparedMlRuntime {+ fn drop(&mut self) {+ let _ = release_ml_runtime();+ }+}++#[derive(Debug, Deserialize)]+struct AssetLock {+ fixture_base_url: String,+ manifest: DocumentAsset,+ python_golden: DocumentAsset,+ onnx_runtime: OnnxRuntimeAssets,+ models: ModelAssets,+ expected_unsupported_decode_file_ids: Vec<String>,+ thresholds: Thresholds,+}++#[derive(Debug, Deserialize)]+struct DocumentAsset {+ path: String,+ url: String,+ sha256: String,+}++#[derive(Debug, Deserialize)]+struct OnnxRuntimeAssets {+ archives: HashMap<String, OnnxRuntimeArchive>,+}++#[derive(Debug, Deserialize)]+struct OnnxRuntimeArchive {+ url: String,+ sha256: String,+ library_path: String,+ library_sha256: String,+}++#[derive(Debug, Deserialize)]+struct ModelAssets {+ face_detection: ModelAsset,+ face_embedding: ModelAsset,+ clip_image: ModelAsset,+}++#[derive(Debug, Deserialize)]+struct ModelAsset {+ file_name: String,+ url: String,+ sha256: String,+}++#[derive(Clone, Copy, Debug, Deserialize)]+struct Thresholds {+ clip_cosine_distance: f64,+ face_embedding_cosine_distance: f64,+ box_iou: f64,+ face_duplicate_iou: f64,+ face_match_iou_floor: f64,+ landmark_error: f64,+ score_delta: f64,+ min_face_score_for_comparison: f64,+ embedding_norm_tolerance: f64,+}++#[derive(Debug, Deserialize)]+struct FixtureManifest {+ files: Vec<FixtureFile>,+}++#[derive(Debug, Deserialize)]+struct FixtureFile {+ path: String,+ sha256: String,+}++#[derive(Clone, Debug, Deserialize)]+pub(crate) struct ComparableResult {+ file_id: String,+ clip: ComparableClip,+ faces: Vec<ComparableFace>,+}++#[derive(Clone, Debug, Deserialize)]+struct ComparableClip {+ embedding: Vec<f64>,+}++#[derive(Clone, Debug, Deserialize)]+struct ComparableFace {+ #[serde(rename = "box")]+ box_xywh: [f64; 4],+ landmarks: Vec<[f64; 2]>,+ score: f64,+ embedding: Vec<f64>,+}++fn repo_root() -> Result<PathBuf> {+ let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ manifest_dir+ .parent()+ .and_then(Path::parent)+ .and_then(Path::parent)+ .map(Path::to_path_buf)+ .context("resolve repository root from CARGO_MANIFEST_DIR")+}++fn cache_dir(repo_root: &Path) -> PathBuf {+ std::env::var_os("ENTE_ML_ASSETS_CACHE_DIR")+ .map(PathBuf::from)+ .unwrap_or_else(|| repo_root.join("rust/target/ml-assets-cache"))+}++fn load_asset_lock(repo_root: &Path) -> Result<AssetLock> {+ let path = repo_root.join(ASSET_LOCK_PATH);+ let payload =+ fs::read_to_string(&path).with_context(|| format!("read asset lock {}", path.display()))?;+ serde_json::from_str(&payload).with_context(|| format!("parse asset lock {}", path.display()))+}++fn load_manifest(path: &Path) -> Result<FixtureManifest> {+ let payload =+ fs::read_to_string(path).with_context(|| format!("read manifest {}", path.display()))?;+ let manifest: FixtureManifest = serde_json::from_str(&payload)+ .with_context(|| format!("parse manifest {}", path.display()))?;+ if manifest.files.is_empty() {+ bail!("manifest has no files: {}", path.display());+ }+ Ok(manifest)+}++fn load_golden_results(path: &Path) -> Result<HashMap<String, ComparableResult>> {+ let payload =+ fs::read_to_string(path).with_context(|| format!("read golden {}", path.display()))?;+ let document: ResultsDocument = serde_json::from_str(&payload)+ .with_context(|| format!("parse golden {}", path.display()))?;+ if document.results.is_empty() {+ bail!("golden has no results: {}", path.display());+ }++ let mut results = HashMap::new();+ for result in document.results {+ if results.insert(result.file_id.clone(), result).is_some() {+ bail!("Python golden has duplicate file_id");+ }+ }+ Ok(results)+}++#[derive(Clone, Debug, Deserialize)]+struct ResultsDocument {+ results: Vec<ComparableResult>,+}++fn file_id_for_manifest_path(path: &str) -> Result<String> {+ Path::new(path)+ .file_name()+ .and_then(|file_name| file_name.to_str())+ .map(ToOwned::to_owned)+ .with_context(|| format!("derive file_id from manifest path '{path}'"))+}++fn resolve_document_asset(+ client: &Client,+ local_assets_root: Option<&Path>,+ cache_dir: &Path,+ label: &str,+ asset: &DocumentAsset,+) -> Result<PathBuf> {+ if let Some(root) = local_assets_root {+ return require_local_asset(root, &asset.path, &asset.sha256, label);+ }++ let target = cache_path_for(cache_dir, "documents", &asset.path, &asset.sha256)?;+ ensure_remote_asset(client, &asset.url, &asset.sha256, &target, label)+}++fn resolve_fixture_asset(+ client: &Client,+ local_assets_root: Option<&Path>,+ cache_dir: &Path,+ fixture_base_url: &str,+ fixture: &FixtureFile,+) -> Result<PathBuf> {+ let file_id = file_id_for_manifest_path(&fixture.path)?;+ if let Some(root) = local_assets_root {+ return require_local_asset(root, &fixture.path, &fixture.sha256, &file_id);+ }++ let url = Url::parse(fixture_base_url)+ .with_context(|| format!("parse fixture base URL '{fixture_base_url}'"))?+ .join(&fixture.path)+ .with_context(|| format!("join fixture URL for {}", fixture.path))?+ .to_string();+ let target = cache_path_for(cache_dir, "fixtures", &fixture.path, &fixture.sha256)?;+ ensure_remote_asset(client, &url, &fixture.sha256, &target, &file_id)+}++fn resolve_onnx_runtime_library(+ client: &Client,+ cache_dir: &Path,+ assets: &OnnxRuntimeAssets,+) -> Result<PathBuf> {+ let target_key = onnx_runtime_target_key()?;+ let archive = assets.archives.get(&target_key).with_context(|| {+ let supported = assets+ .archives+ .keys()+ .map(String::as_str)+ .collect::<Vec<_>>()+ .join(", ");+ format!(+ "no ONNX Runtime asset for target '{target_key}' in {ASSET_LOCK_PATH}; supported: {supported}"+ )+ })?;++ let archive_name = url_file_name(&archive.url)?;+ let archive_path = cache_path_for(+ cache_dir,+ "onnx-runtime-archives",+ &archive_name,+ &archive.sha256,+ )?;+ let archive_path = ensure_remote_asset(+ client,+ &archive.url,+ &archive.sha256,+ &archive_path,+ "onnx-runtime-archive",+ )?;++ let library_name = file_id_for_manifest_path(&archive.library_path)?;+ let library_cache_path = format!("{target_key}/{library_name}");+ let library_target = cache_path_for(+ cache_dir,+ "onnx-runtime-libraries",+ &library_cache_path,+ &archive.library_sha256,+ )?;+ if library_target.is_file() {+ verify_file_sha256(+ &library_target,+ &archive.library_sha256,+ "onnx-runtime-library",+ )?;+ return Ok(library_target);+ }++ extract_tgz_member(&archive_path, &archive.library_path, &library_target)+ .with_context(|| format!("extract ONNX Runtime library for {target_key}"))?;+ verify_file_sha256(+ &library_target,+ &archive.library_sha256,+ "onnx-runtime-library",+ )?;+ Ok(library_target)+}++fn onnx_runtime_target_key() -> Result<String> {+ match (std::env::consts::OS, std::env::consts::ARCH) {+ ("linux", "x86_64") => Ok("x86_64-unknown-linux-gnu".to_string()),+ ("linux", "aarch64") => Ok("aarch64-unknown-linux-gnu".to_string()),+ ("macos", "x86_64") => Ok("x86_64-apple-darwin".to_string()),+ ("macos", "aarch64") => Ok("aarch64-apple-darwin".to_string()),+ (os, arch) => bail!("unsupported ONNX Runtime target for ML indexing test: {arch}-{os}"),+ }+}++fn url_file_name(url: &str) -> Result<String> {+ Url::parse(url)+ .with_context(|| format!("parse asset URL '{url}'"))?+ .path_segments()+ .and_then(Iterator::last)+ .filter(|segment| !segment.is_empty())+ .map(ToOwned::to_owned)+ .with_context(|| format!("derive file name from URL '{url}'"))+}++fn extract_tgz_member(archive_path: &Path, member_path: &str, target: &Path) -> Result<()> {+ let expected_member = Path::new(member_path);+ if expected_member.is_absolute() {+ bail!("archive member path must be relative: {member_path}");+ }++ let parent = target+ .parent()+ .with_context(|| format!("resolve parent for {}", target.display()))?;+ fs::create_dir_all(parent)+ .with_context(|| format!("create cache directory {}", parent.display()))?;++ let archive_file = fs::File::open(archive_path)+ .with_context(|| format!("open archive {}", archive_path.display()))?;+ let decoder = GzDecoder::new(archive_file);+ let mut archive = tar::Archive::new(decoder);+ for entry in archive.entries().context("read tgz entries")? {+ let mut entry = entry.context("read tgz entry")?;+ let entry_path = entry.path().context("read tgz entry path")?;+ if entry_path.as_ref() != expected_member {+ continue;+ }+ entry+ .unpack(target)+ .with_context(|| format!("unpack {member_path} to {}", target.display()))?;+ return Ok(());+ }++ bail!(+ "archive {} did not contain expected member {member_path}",+ archive_path.display()+ );+}++fn resolve_model_paths(+ client: &Client,+ cache_dir: &Path,+ models: &ModelAssets,+) -> Result<ModelPaths> {+ let face_detection =+ resolve_model_asset(client, cache_dir, "face-detection", &models.face_detection)?;+ let face_embedding =+ resolve_model_asset(client, cache_dir, "face-embedding", &models.face_embedding)?;+ let clip_image = resolve_model_asset(client, cache_dir, "clip-image", &models.clip_image)?;++ Ok(ModelPaths {+ face_detection: face_detection.to_string_lossy().into_owned(),+ face_embedding: face_embedding.to_string_lossy().into_owned(),+ clip_image: clip_image.to_string_lossy().into_owned(),+ clip_text: String::new(),+ pet_face_detection: String::new(),+ pet_face_embedding_dog: String::new(),+ pet_face_embedding_cat: String::new(),+ pet_body_detection: String::new(),+ pet_body_embedding_dog: String::new(),+ pet_body_embedding_cat: String::new(),+ })+}++fn resolve_model_asset(+ client: &Client,+ cache_dir: &Path,+ label: &str,+ asset: &ModelAsset,+) -> Result<PathBuf> {+ let target = cache_path_for(cache_dir, "models", &asset.file_name, &asset.sha256)?;+ ensure_remote_asset(client, &asset.url, &asset.sha256, &target, label)+}++fn require_local_asset(+ local_assets_root: &Path,+ relative_path: &str,+ expected_sha256: &str,+ label: &str,+) -> Result<PathBuf> {+ let path = local_assets_root.join(relative_path);+ if !path.is_file() {+ bail!(+ "{label} is missing from local asset repo at {}",+ path.display()+ );+ }+ verify_file_sha256(&path, expected_sha256, label)?;+ Ok(path)+}++fn ensure_remote_asset(+ client: &Client,+ url: &str,+ expected_sha256: &str,+ target: &Path,+ label: &str,+) -> Result<PathBuf> {+ if target.is_file() {+ verify_file_sha256(target, expected_sha256, label)?;+ return Ok(target.to_path_buf());+ }++ let parent = target+ .parent()+ .with_context(|| format!("resolve parent for {}", target.display()))?;+ fs::create_dir_all(parent)+ .with_context(|| format!("create cache directory {}", parent.display()))?;++ let mut response = client+ .get(url)+ .send()+ .with_context(|| format!("download {label} from {url}"))?+ .error_for_status()+ .with_context(|| format!("download {label} from {url}"))?;++ let mut temp_file = tempfile::NamedTempFile::new_in(parent)+ .with_context(|| format!("create temp file in {}", parent.display()))?;+ let mut hasher = Sha256::new();+ let mut buffer = [0_u8; 1024 * 1024];+ loop {+ let read = response+ .read(&mut buffer)+ .with_context(|| format!("read {label} response body"))?;+ if read == 0 {+ break;+ }+ hasher.update(&buffer[..read]);+ temp_file+ .write_all(&buffer[..read])+ .with_context(|| format!("write cached {label}"))?;+ }++ let digest = hasher.finalize();+ let actual_sha256 = hex_digest(&digest);+ if actual_sha256 != normalize_sha256(expected_sha256) {+ bail!(+ "{label} SHA-256 mismatch after download: expected {}, got {}",+ normalize_sha256(expected_sha256),+ actual_sha256+ );+ }++ temp_file+ .flush()+ .with_context(|| format!("flush cached {label}"))?;+ temp_file.persist(target).map_err(|error| {+ anyhow!(+ "persist cached {label} to {}: {}",+ target.display(),+ error.error+ )+ })?;+ Ok(target.to_path_buf())+}++fn cache_path_for(+ cache_dir: &Path,+ namespace: &str,+ relative_path: &str,+ expected_sha256: &str,+) -> Result<PathBuf> {+ let relative = Path::new(relative_path);+ if relative.is_absolute() {+ bail!("asset path must be relative: {relative_path}");+ }+ let sha = normalize_sha256(expected_sha256);+ let prefix = sha+ .get(..16)+ .with_context(|| format!("SHA-256 is too short for {relative_path}"))?;+ Ok(cache_dir.join(namespace).join(prefix).join(relative))+}++fn verify_file_sha256(path: &Path, expected_sha256: &str, label: &str) -> Result<()> {+ let actual_sha256 = sha256_file(path)?;+ let expected_sha256 = normalize_sha256(expected_sha256);+ if actual_sha256 != expected_sha256 {+ bail!(+ "{label} SHA-256 mismatch at {}: expected {}, got {}",+ path.display(),+ expected_sha256,+ actual_sha256+ );+ }+ Ok(())+}++fn sha256_file(path: &Path) -> Result<String> {+ let mut file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;+ let mut hasher = Sha256::new();+ let mut buffer = [0_u8; 1024 * 1024];+ loop {+ let read = file+ .read(&mut buffer)+ .with_context(|| format!("read {}", path.display()))?;+ if read == 0 {+ break;+ }+ hasher.update(&buffer[..read]);+ }+ let digest = hasher.finalize();+ Ok(hex_digest(&digest))+}++fn normalize_sha256(value: &str) -> String {+ value.trim().to_ascii_lowercase()+}++fn hex_digest(bytes: &[u8]) -> String {+ let mut hex = String::with_capacity(bytes.len() * 2);+ for byte in bytes {+ hex.push_str(&format!("{byte:02x}"));+ }+ hex+}++fn expect_decode_error(file_id: &str, req: AnalyzeImageRequest, failures: &mut Vec<String>) {+ match analyze_image(req) {+ Err(MlError::Decode(_)) => {}+ Err(error) => failures.push(format!(+ "{file_id}: expected decode error, got different ML error: {error}"+ )),+ Ok(_) => failures.push(format!(+ "{file_id}: expected decode error, but Rust ML indexing succeeded"+ )),+ }+}++fn comparable_from_rust(file_id: &str, result: &AnalyzeImageResult) -> Result<ComparableResult> {+ let clip = result+ .clip+ .as_ref()+ .context("missing CLIP result")?+ .embedding+ .iter()+ .map(|value| *value as f64)+ .collect();+ let faces = result+ .faces+ .as_ref()+ .context("missing face results")?+ .iter()+ .map(comparable_face_from_rust)+ .collect();++ Ok(ComparableResult {+ file_id: file_id.to_owned(),+ clip: ComparableClip { embedding: clip },+ faces,+ })+}++fn comparable_face_from_rust(face: &RustFaceResult) -> ComparableFace {+ let [x_min, y_min, x_max, y_max] = face.detection.box_xyxy;+ ComparableFace {+ box_xywh: [+ x_min as f64,+ y_min as f64,+ (x_max - x_min).max(0.0) as f64,+ (y_max - y_min).max(0.0) as f64,+ ],+ landmarks: face+ .detection+ .keypoints+ .iter()+ .map(|point| [point[0] as f64, point[1] as f64])+ .collect(),+ score: face.detection.score as f64,+ embedding: face.embedding.iter().map(|value| *value as f64).collect(),+ }+}++fn compare_results(+ file_id: &str,+ reference: &ComparableResult,+ candidate: &ComparableResult,+ thresholds: &Thresholds,+ failures: &mut Vec<String>,+) {+ validate_result(file_id, "python golden", reference, thresholds, failures);+ validate_result(file_id, "rust", candidate, thresholds, failures);++ match cosine_distance(&reference.clip.embedding, &candidate.clip.embedding) {+ Ok(distance) if distance > thresholds.clip_cosine_distance => failures.push(format!(+ "{file_id}: CLIP cosine distance {distance:.6} exceeded threshold {:.6}",+ thresholds.clip_cosine_distance+ )),+ Ok(_) => {}+ Err(error) => failures.push(format!("{file_id}: CLIP cosine distance failed: {error:#}")),+ }++ let reference_faces = dedupe_faces(&reference.faces, thresholds.face_duplicate_iou);+ let candidate_faces = dedupe_faces(&candidate.faces, thresholds.face_duplicate_iou);+ let all_matches = match_faces(+ &reference_faces,+ &candidate_faces,+ thresholds.face_match_iou_floor,+ );++ let matched_reference_indices: BTreeSet<usize> = all_matches+ .iter()+ .map(|face_match| face_match.reference_index)+ .collect();+ let matched_candidate_indices: BTreeSet<usize> = all_matches+ .iter()+ .map(|face_match| face_match.candidate_index)+ .collect();+ let relevant_matches: Vec<FaceMatch> = all_matches+ .iter()+ .copied()+ .filter(|face_match| {+ reference_faces[face_match.reference_index].score+ >= thresholds.min_face_score_for_comparison+ || candidate_faces[face_match.candidate_index].score+ >= thresholds.min_face_score_for_comparison+ })+ .collect();++ let unmatched_reference_indices: Vec<usize> = reference_faces+ .iter()+ .enumerate()+ .filter_map(|(index, face)| {+ (face.score >= thresholds.min_face_score_for_comparison+ && !matched_reference_indices.contains(&index))+ .then_some(index)+ })+ .collect();+ let unmatched_candidate_indices: Vec<usize> = candidate_faces+ .iter()+ .enumerate()+ .filter_map(|(index, face)| {+ (face.score >= thresholds.min_face_score_for_comparison+ && !matched_candidate_indices.contains(&index))+ .then_some(index)+ })+ .collect();++ let comparable_reference_indices: BTreeSet<usize> = relevant_matches+ .iter()+ .map(|face_match| face_match.reference_index)+ .chain(unmatched_reference_indices.iter().copied())+ .collect();+ let comparable_candidate_indices: BTreeSet<usize> = relevant_matches+ .iter()+ .map(|face_match| face_match.candidate_index)+ .chain(unmatched_candidate_indices.iter().copied())+ .collect();++ if comparable_reference_indices.len() != comparable_candidate_indices.len() {+ failures.push(format!(+ "{file_id}: comparable face count mismatch: python={} rust={}",+ comparable_reference_indices.len(),+ comparable_candidate_indices.len()+ ));+ }++ let expected_match_count = comparable_reference_indices+ .len()+ .min(comparable_candidate_indices.len());+ if relevant_matches.len() != expected_match_count {+ failures.push(format!(+ "{file_id}: matched comparable face count mismatch: matched={} expected={}",+ relevant_matches.len(),+ expected_match_count+ ));+ }++ for index in unmatched_reference_indices {+ failures.push(format!(+ "{file_id}: unmatched high-score python face {}",+ describe_face(&reference_faces[index])+ ));+ }+ for index in unmatched_candidate_indices {+ failures.push(format!(+ "{file_id}: unmatched high-score Rust face {}",+ describe_face(&candidate_faces[index])+ ));+ }++ for face_match in relevant_matches {+ let reference_face = &reference_faces[face_match.reference_index];+ let candidate_face = &candidate_faces[face_match.candidate_index];++ if face_match.iou < thresholds.box_iou {+ failures.push(format!(+ "{file_id}: face box IoU {iou:.6} below threshold {threshold:.6}; python={python} rust={rust}",+ iou = face_match.iou,+ threshold = thresholds.box_iou,+ python = describe_face(reference_face),+ rust = describe_face(candidate_face)+ ));+ }++ match landmark_error(&reference_face.landmarks, &candidate_face.landmarks) {+ Ok(error) if error > thresholds.landmark_error => failures.push(format!(+ "{file_id}: landmark error {error:.6} exceeded threshold {:.6}",+ thresholds.landmark_error+ )),+ Ok(_) => {}+ Err(error) => {+ failures.push(format!("{file_id}: landmark comparison failed: {error:#}"))+ }+ }++ let score_delta = (reference_face.score - candidate_face.score).abs();+ if score_delta > thresholds.score_delta {+ failures.push(format!(+ "{file_id}: face score delta {score_delta:.6} exceeded threshold {:.6}",+ thresholds.score_delta+ ));+ }++ match cosine_distance(&reference_face.embedding, &candidate_face.embedding) {+ Ok(distance) if distance > thresholds.face_embedding_cosine_distance => failures.push(+ format!(+ "{file_id}: face embedding cosine distance {distance:.6} exceeded threshold {:.6}",+ thresholds.face_embedding_cosine_distance+ ),+ ),+ Ok(_) => {}+ Err(error) => failures.push(format!(+ "{file_id}: face embedding cosine distance failed: {error:#}"+ )),+ }+ }+}++fn validate_result(+ file_id: &str,+ label: &str,+ result: &ComparableResult,+ thresholds: &Thresholds,+ failures: &mut Vec<String>,+) {+ validate_embedding(+ file_id,+ label,+ "clip.embedding",+ &result.clip.embedding,+ CLIP_EMBEDDING_DIM,+ thresholds.embedding_norm_tolerance,+ failures,+ );++ for (index, face) in result.faces.iter().enumerate() {+ validate_box(file_id, label, index, &face.box_xywh, failures);+ if !face.score.is_finite() {+ failures.push(format!(+ "{file_id}: {label} faces[{index}].score is not finite"+ ));+ }+ if face.landmarks.len() != 5 {+ failures.push(format!(+ "{file_id}: {label} faces[{index}].landmarks has len {}, expected 5",+ face.landmarks.len()+ ));+ }+ for (landmark_index, landmark) in face.landmarks.iter().enumerate() {+ for (axis, value) in landmark.iter().enumerate() {+ if !value.is_finite() || *value < 0.0 || *value > 1.0 {+ failures.push(format!(+ "{file_id}: {label} faces[{index}].landmarks[{landmark_index}][{axis}] is outside [0, 1]: {value}"+ ));+ }+ }+ }+ validate_embedding(+ file_id,+ label,+ &format!("faces[{index}].embedding"),+ &face.embedding,+ FACE_EMBEDDING_DIM,+ thresholds.embedding_norm_tolerance,+ failures,+ );+ }+}++fn validate_box(+ file_id: &str,+ label: &str,+ index: usize,+ box_xywh: &[f64; 4],+ failures: &mut Vec<String>,+) {+ let [x, y, width, height] = *box_xywh;+ if !box_xywh.iter().all(|value| value.is_finite()) {+ failures.push(format!(+ "{file_id}: {label} faces[{index}].box has non-finite values: {box_xywh:?}"+ ));+ return;+ }+ if width < 0.0 || height < 0.0 {+ failures.push(format!(+ "{file_id}: {label} faces[{index}].box has negative size: {box_xywh:?}"+ ));+ }+ if x < 0.0 || y < 0.0 || x + width > 1.0 + FLOAT_TOLERANCE || y + height > 1.0 + FLOAT_TOLERANCE+ {+ failures.push(format!(+ "{file_id}: {label} faces[{index}].box is outside [0, 1]: {box_xywh:?}"+ ));+ }+}++fn validate_embedding(+ file_id: &str,+ label: &str,+ field: &str,+ values: &[f64],+ expected_len: usize,+ norm_tolerance: f64,+ failures: &mut Vec<String>,+) {+ if values.len() != expected_len {+ failures.push(format!(+ "{file_id}: {label} {field} has len {}, expected {expected_len}",+ values.len()+ ));+ return;+ }+ if let Some((index, value)) = values+ .iter()+ .enumerate()+ .find(|(_, value)| !value.is_finite())+ {+ failures.push(format!(+ "{file_id}: {label} {field}[{index}] is not finite: {value}"+ ));+ return;+ }++ let norm = l2_norm(values);+ if norm <= FLOAT_TOLERANCE {+ failures.push(format!("{file_id}: {label} {field} is a zero vector"));+ } else if (norm - 1.0).abs() > norm_tolerance {+ failures.push(format!(+ "{file_id}: {label} {field} is not L2-normalized: norm={norm:.6}"+ ));+ }+}++#[derive(Clone, Copy, Debug)]+struct FaceMatch {+ reference_index: usize,+ candidate_index: usize,+ iou: f64,+}++fn dedupe_faces(faces: &[ComparableFace], min_iou_for_duplicate: f64) -> Vec<ComparableFace> {+ let mut sorted_faces: Vec<(usize, &ComparableFace)> = faces.iter().enumerate().collect();+ sorted_faces.sort_by(|left, right| {+ right+ .1+ .score+ .total_cmp(&left.1.score)+ .then_with(|| left.0.cmp(&right.0))+ });++ let mut kept: Vec<(usize, &ComparableFace)> = Vec::new();+ for (index, face) in sorted_faces {+ if kept.iter().any(|(_, kept_face)| {+ box_iou(&face.box_xywh, &kept_face.box_xywh) >= min_iou_for_duplicate+ }) {+ continue;+ }+ kept.push((index, face));+ }++ kept.sort_by_key(|(index, _)| *index);+ kept.into_iter().map(|(_, face)| face.clone()).collect()+}++fn match_faces(+ reference_faces: &[ComparableFace],+ candidate_faces: &[ComparableFace],+ min_iou_for_match: f64,+) -> Vec<FaceMatch> {+ let mut pairs = Vec::new();+ for (reference_index, reference_face) in reference_faces.iter().enumerate() {+ for (candidate_index, candidate_face) in candidate_faces.iter().enumerate() {+ pairs.push((+ box_iou(&reference_face.box_xywh, &candidate_face.box_xywh),+ reference_index,+ candidate_index,+ ));+ }+ }+ pairs.sort_by(|left, right| {+ right+ .0+ .total_cmp(&left.0)+ .then_with(|| left.1.cmp(&right.1))+ .then_with(|| left.2.cmp(&right.2))+ });++ let mut used_reference = HashSet::new();+ let mut used_candidate = HashSet::new();+ let mut matches = Vec::new();+ for (iou, reference_index, candidate_index) in pairs {+ if iou < min_iou_for_match {+ break;+ }+ if used_reference.contains(&reference_index) || used_candidate.contains(&candidate_index) {+ continue;+ }+ used_reference.insert(reference_index);+ used_candidate.insert(candidate_index);+ matches.push(FaceMatch {+ reference_index,+ candidate_index,+ iou,+ });+ }++ matches.sort_by(|left, right| {+ left.reference_index+ .cmp(&right.reference_index)+ .then_with(|| left.candidate_index.cmp(&right.candidate_index))+ });+ matches+}++fn box_iou(left: &[f64; 4], right: &[f64; 4]) -> f64 {+ let [left_x, left_y, left_width, left_height] = *left;+ let [right_x, right_y, right_width, right_height] = *right;++ let left_x2 = left_x + left_width;+ let left_y2 = left_y + left_height;+ let right_x2 = right_x + right_width;+ let right_y2 = right_y + right_height;++ let inter_x1 = left_x.max(right_x);+ let inter_y1 = left_y.max(right_y);+ let inter_x2 = left_x2.min(right_x2);+ let inter_y2 = left_y2.min(right_y2);++ let inter_width = (inter_x2 - inter_x1).max(0.0);+ let inter_height = (inter_y2 - inter_y1).max(0.0);+ let inter_area = inter_width * inter_height;+ let left_area = (left_width * left_height).max(0.0);+ let right_area = (right_width * right_height).max(0.0);+ let denominator = left_area + right_area - inter_area;+ if denominator <= 0.0 {+ return 0.0;+ }+ inter_area / denominator+}++fn landmark_error(left: &[[f64; 2]], right: &[[f64; 2]]) -> Result<f64> {+ if left.len() != right.len() {+ bail!(+ "landmark count mismatch: python={} rust={}",+ left.len(),+ right.len()+ );+ }+ if left.is_empty() {+ return Ok(0.0);+ }++ let total = left+ .iter()+ .zip(right.iter())+ .map(|(left_point, right_point)| {+ let dx = left_point[0] - right_point[0];+ let dy = left_point[1] - right_point[1];+ (dx * dx + dy * dy).sqrt()+ })+ .sum::<f64>();+ Ok(total / left.len() as f64)+}++fn cosine_distance(left: &[f64], right: &[f64]) -> Result<f64> {+ if left.len() != right.len() {+ bail!(+ "cosine distance vector dimension mismatch: left={} right={}",+ left.len(),+ right.len()+ );+ }++ let dot = left+ .iter()+ .zip(right.iter())+ .map(|(left_value, right_value)| left_value * right_value)+ .sum::<f64>();+ let denominator = l2_norm(left) * l2_norm(right);+ if denominator <= FLOAT_TOLERANCE {+ bail!("cosine distance cannot be computed for zero vectors");+ }+ let similarity = (dot / denominator).clamp(-1.0, 1.0);+ Ok(1.0 - similarity)+}++fn l2_norm(values: &[f64]) -> f64 {+ values.iter().map(|value| value * value).sum::<f64>().sqrt()+}++fn describe_face(face: &ComparableFace) -> String {+ format!(+ "score={:.4} box=[{:.4}, {:.4}, {:.4}, {:.4}]",+ face.score, face.box_xywh[0], face.box_xywh[1], face.box_xywh[2], face.box_xywh[3]+ )+}diff --git a/rust/crates/photos/tests/support/mod.rs b/rust/crates/photos/tests/support/mod.rsnew file mode 100644index 0000000000..637991df86--- /dev/null+++ b/rust/crates/photos/tests/support/mod.rs@@ -0,0 +1 @@+pub(crate) mod ml_indexing;