π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Expose MlStore to Flutter
laurenspriem974ad08e5175
diff --git a/mobile/apps/photos/lib/db/ml/rust_db.dart b/mobile/apps/photos/lib/db/ml/rust_db.dartindex 0256521322..bda5465e67 100644--- a/mobile/apps/photos/lib/db/ml/rust_db.dart+++ b/mobile/apps/photos/lib/db/ml/rust_db.dart@@ -62,9 +62,9 @@ class RustMLDataDB with MLDataDBOrchestration implements IMLDataDB<int> {@overrideLogger get logger => _logger;- Future<rust.MlDb>? _dbFuture;+ Future<rust.MlStore>? _dbFuture;- Future<rust.MlDb> get _db async {+ Future<rust.MlStore> get _db async {final future = _dbFuture ??= _openDatabase();try {return await future;@@ -76,12 +76,12 @@ class RustMLDataDB with MLDataDBOrchestration implements IMLDataDB<int> {}}- Future<rust.MlDb> _openDatabase() async {+ Future<rust.MlStore> _openDatabase() async {final documentsDirectory = await getApplicationDocumentsDirectory();final String path = join(documentsDirectory.path, _databaseName);_logger.info("Opening rust ML DB access: DB path $path");try {- return await rust.MlDb.open(path: path);+ return await rust.MlStore.open(path: path);} on rust.MlDbError_Downgrade catch (e) {throw DatabaseDowngradeError(e.message);}diff --git a/rust/bindings/frb/photos/src/api/ml_db_api.rs b/rust/bindings/frb/photos/src/api/ml_db_api.rsindex 3e430f47d9..04a983a0f7 100644--- a/rust/bindings/frb/photos/src/api/ml_db_api.rs+++ b/rust/bindings/frb/photos/src/api/ml_db_api.rs@@ -7,8 +7,14 @@ pub use ente_photos::ml_db::{FaceDbInfoForClustering, FaceRow, FaceWithoutEmbedding, FdStatus, PetBodyRow, PetBodyVectorRow,PetFaceRow, PetFaceVectorRow, PetRowsForFiles, PreviewInfo,};+use ente_photos::ml_store;+pub use ente_photos::ml_store::{FillOutcome, FillState, Index};use flutter_rust_bridge::frb;+use super::vecdb_api::{+ VecDbKeyMatches, VecDbMatch, VecDbStats, to_api_key_matches, to_api_matches, to_api_stats,+};+static BACKEND: OnceLock<bool> = OnceLock::new();#[frb(sync)]@@ -32,6 +38,17 @@ impl From<ml_db::Error> for MlDbError {}}+impl From<ml_store::Error> for MlDbError {+ fn from(error: ml_store::Error) -> Self {+ match error {+ ml_store::Error::Database(error) => Self::from(error),+ other => Self::Other {+ message: ente_core::error::chain(&other),+ },+ }+ }+}+#[frb(mirror(FaceRow))]pub struct _FaceRow {pub file_id: i64,@@ -159,39 +176,210 @@ pub struct _PreviewInfo {pub object_size: i64,}+#[frb(mirror(Index))]+pub enum _Index {+ Clip,+ ClusterCentroid,+}++#[frb(mirror(FillState))]+pub enum _FillState {+ Filled,+ Filling,+ Stale,+}++#[frb(mirror(FillOutcome))]+pub enum _FillOutcome {+ Completed,+ AlreadyFilled,+ Superseded,+}++pub struct FillReport {+ pub outcome: FillOutcome,+ pub rows: u32,+ pub indexed: u32,+ pub skipped: u32,+ pub resumed: bool,+}++impl From<ml_store::FillReport> for FillReport {+ fn from(report: ml_store::FillReport) -> Self {+ Self {+ outcome: report.outcome,+ rows: report.rows as u32,+ indexed: report.indexed as u32,+ skipped: report.skipped as u32,+ resumed: report.resumed,+ }+ }+}++fn search_params(+ limit: Option<u32>,+ max_distance: Option<f32>,+ exact: bool,+ allowed_keys: Option<Vec<String>>,+) -> ml_store::SearchParams {+ ml_store::SearchParams {+ limit: limit.map(|value| value as usize),+ max_distance,+ exact,+ allowed_keys,+ }+}+#[frb(opaque)]-pub struct MlDb {- inner: ml_db::MlDb,+pub struct MlStore {+ inner: ml_store::MlStore,}-impl MlDb {- pub fn open(path: String) -> Result<MlDb, MlDbError> {+impl MlStore {+ pub fn open(path: String) -> Result<MlStore, MlDbError> {Ok(Self {- inner: ml_db::MlDb::open(path)?,+ inner: ml_store::MlStore::open(path)?,})}+ pub fn release(&self) -> Result<(), MlDbError> {+ Ok(self.inner.release()?)+ }++ pub fn fill_state(&self, index: Index) -> Result<FillState, MlDbError> {+ Ok(self.inner.fill_state(index)?)+ }++ pub fn fill_clip_index(&self, force: bool) -> Result<FillReport, MlDbError> {+ Ok(self.inner.fill_clip_index(force)?.into())+ }++ pub fn fill_cluster_centroid_index(&self, force: bool) -> Result<FillReport, MlDbError> {+ Ok(self.inner.fill_cluster_centroid_index(force)?.into())+ }++ pub fn put_clip(&self, embeddings: Vec<ClipEmbedding>) -> Result<(), MlDbError> {+ Ok(self.inner.put_clip(&embeddings)?)+ }++ pub fn delete_clip(&self, file_ids: Vec<i64>) -> Result<(), MlDbError> {+ Ok(self.inner.delete_clip(&file_ids)?)+ }++ pub fn delete_all_clip(&self) -> Result<(), MlDbError> {+ Ok(self.inner.delete_all_clip()?)+ }++ pub fn cluster_summary_update(+ &self,+ summary: HashMap<String, ClusterSummary>,+ ) -> Result<(), MlDbError> {+ Ok(self.inner.cluster_summary_update(&summary)?)+ }++ pub fn delete_cluster_summary(&self, cluster_id: String) -> Result<(), MlDbError> {+ Ok(self.inner.delete_cluster_summary(&cluster_id)?)+ }++ pub fn drop_clusters_and_person_table(&self, faces: bool) -> Result<(), MlDbError> {+ Ok(self.inner.drop_clusters_and_person_table(faces)?)+ }++ pub fn clear_all(&self) -> Result<(), MlDbError> {+ Ok(self.inner.clear_all()?)+ }++ pub fn search(+ &self,+ index: Index,+ query: Vec<f32>,+ limit: Option<u32>,+ max_distance: Option<f32>,+ exact: bool,+ allowed_keys: Option<Vec<String>>,+ ) -> Result<Vec<VecDbMatch>, MlDbError> {+ let params = search_params(limit, max_distance, exact, allowed_keys);+ Ok(to_api_matches(self.inner.search(index, &query, ¶ms)?))+ }++ pub fn bulk_search(+ &self,+ index: Index,+ queries: Vec<Vec<f32>>,+ limit: Option<u32>,+ max_distance: Option<f32>,+ exact: bool,+ allowed_keys: Option<Vec<String>>,+ ) -> Result<Vec<Vec<VecDbMatch>>, MlDbError> {+ let params = search_params(limit, max_distance, exact, allowed_keys);+ Ok(self+ .inner+ .bulk_search(index, &queries, ¶ms)?+ .into_iter()+ .map(to_api_matches)+ .collect())+ }++ pub fn bulk_search_stored(+ &self,+ index: Index,+ keys: Vec<String>,+ count: u32,+ max_distance: Option<f32>,+ exact: bool,+ restrict_to_input: bool,+ ) -> Result<Vec<VecDbKeyMatches>, MlDbError> {+ Ok(self+ .inner+ .bulk_search_stored(+ index,+ &keys,+ count as usize,+ max_distance,+ exact,+ restrict_to_input,+ )?+ .into_iter()+ .map(to_api_key_matches)+ .collect())+ }++ pub fn get_vector(&self, index: Index, key: String) -> Result<Option<Vec<f32>>, MlDbError> {+ Ok(self.inner.get_vector(index, &key)?)+ }++ pub fn contains(&self, index: Index, key: String) -> Result<bool, MlDbError> {+ Ok(self.inner.contains(index, &key)?)+ }++ pub fn stats(&self, index: Index) -> Result<VecDbStats, MlDbError> {+ Ok(to_api_stats(self.inner.stats(index)?))+ }+pub fn clear_non_pet_tables(&self) -> Result<(), MlDbError> {- Ok(self.inner.clear_non_pet_tables()?)+ Ok(self.inner.db().clear_non_pet_tables()?)}pub fn clear_pet_tables(&self) -> Result<(), MlDbError> {- Ok(self.inner.clear_pet_tables()?)+ Ok(self.inner.db().clear_pet_tables()?)}pub fn bulk_insert_faces(&self, faces: Vec<FaceRow>) -> Result<(), MlDbError> {- Ok(self.inner.bulk_insert_faces(&faces)?)+ Ok(self.inner.db().bulk_insert_faces(&faces)?)}pub fn face_indexed_file_ids(&self,minimum_ml_version: i64,) -> Result<HashMap<i64, i64>, MlDbError> {- Ok(self.inner.face_indexed_file_ids(minimum_ml_version)?)+ Ok(self.inner.db().face_indexed_file_ids(minimum_ml_version)?)}pub fn get_face_indexed_file_count(&self, minimum_ml_version: i64) -> Result<i64, MlDbError> {- Ok(self.inner.get_face_indexed_file_count(minimum_ml_version)?)+ Ok(self+ .inner+ .db()+ .get_face_indexed_file_count(minimum_ml_version)?)}pub fn get_face_embeddings_for_cluster(@@ -201,6 +389,7 @@ impl MlDb {) -> Result<Vec<Vec<u8>>, MlDbError> {Ok(self.inner+ .db().get_face_embeddings_for_cluster(&cluster_id, limit)?)}@@ -211,6 +400,7 @@ impl MlDb {) -> Result<HashMap<String, Vec<Vec<u8>>>, MlDbError> {Ok(self.inner+ .db().get_face_embeddings_for_clusters(&cluster_ids, limit)?)}@@ -221,7 +411,7 @@ impl MlDb {avatar_face_id: Option<String>,cluster_id: Option<String>,) -> Result<Option<FaceRow>, MlDbError> {- Ok(self.inner.get_cover_face_for_person(+ Ok(self.inner.db().get_cover_face_for_person(recent_file_id,person_id.as_deref(),avatar_face_id.as_deref(),@@ -233,13 +423,16 @@ impl MlDb {&self,file_upload_id: i64,) -> Result<Vec<FaceRow>, MlDbError> {- Ok(self.inner.get_faces_for_given_file_id(file_upload_id)?)+ Ok(self+ .inner+ .db()+ .get_faces_for_given_file_id(file_upload_id)?)}pub fn get_file_ids_to_faces_without_embedding(&self,) -> Result<HashMap<i64, Vec<FaceWithoutEmbedding>>, MlDbError> {- Ok(self.inner.get_file_ids_to_faces_without_embedding()?)+ Ok(self.inner.db().get_file_ids_to_faces_without_embedding()?)}pub fn get_face_info_for_clustering(@@ -250,6 +443,7 @@ impl MlDb {) -> Result<Vec<FaceDbInfoForClustering>, MlDbError> {Ok(self.inner+ .db().get_face_info_for_clustering(max_faces, offset, batch_size)?)}@@ -257,23 +451,34 @@ impl MlDb {&self,face_ids: Vec<String>,) -> Result<Vec<(String, Vec<u8>)>, MlDbError> {- Ok(self.inner.get_face_embedding_rows_for_faces(&face_ids)?)+ Ok(self+ .inner+ .db()+ .get_face_embedding_rows_for_faces(&face_ids)?)}pub fn get_total_face_count(&self) -> Result<i64, MlDbError> {- Ok(self.inner.get_total_face_count()?)+ Ok(self.inner.db().get_total_face_count()?)}pub fn get_errored_face_count(&self) -> Result<i64, MlDbError> {- Ok(self.inner.get_errored_face_count()?)+ Ok(self.inner.db().get_errored_face_count()?)}pub fn get_errored_file_ids(&self) -> Result<Vec<i64>, MlDbError> {- Ok(self.inner.get_errored_file_ids()?.into_iter().collect())+ Ok(self+ .inner+ .db()+ .get_errored_file_ids()?+ .into_iter()+ .collect())}pub fn prune_resolved_face_error_results(&self, file_ids: Vec<i64>) -> Result<(), MlDbError> {- Ok(self.inner.prune_resolved_face_error_results(&file_ids)?)+ Ok(self+ .inner+ .db()+ .prune_resolved_face_error_results(&file_ids)?)}pub fn get_file_ids_with_error_results(@@ -282,13 +487,14 @@ impl MlDb {) -> Result<Vec<i64>, MlDbError> {Ok(self.inner+ .db().get_file_ids_with_error_results(&file_ids)?.into_iter().collect())}pub fn delete_face_index_for_files(&self, file_ids: Vec<i64>) -> Result<(), MlDbError> {- Ok(self.inner.delete_face_index_for_files(&file_ids)?)+ Ok(self.inner.db().delete_face_index_for_files(&file_ids)?)}pub fn delete_unclustered_face_index_for_files(@@ -297,20 +503,22 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().delete_unclustered_face_index_for_files(&file_ids)?)}pub fn get_clustered_or_faceless_file_count(&self) -> Result<i64, MlDbError> {- Ok(self.inner.get_clustered_or_faceless_file_count()?)+ Ok(self.inner.db().get_clustered_or_faceless_file_count()?)}pub fn get_unclustered_face_count(&self) -> Result<i64, MlDbError> {- Ok(self.inner.get_unclustered_face_count()?)+ Ok(self.inner.db().get_unclustered_face_count()?)}pub fn get_all_file_ids_of_face_ids_not_in_any_cluster(&self) -> Result<Vec<i64>, MlDbError> {Ok(self.inner+ .db().get_all_file_ids_of_face_ids_not_in_any_cluster()?.into_iter().collect())@@ -322,6 +530,7 @@ impl MlDb {) -> Result<Vec<i64>, MlDbError> {Ok(self.inner+ .db().get_all_files_associated_with_all_clusters(except_clusters.as_deref())?.into_iter().collect())@@ -330,6 +539,7 @@ impl MlDb {pub fn get_fully_indexed_file_ids(&self, include_pets: bool) -> Result<Vec<i64>, MlDbError> {Ok(self.inner+ .db().get_fully_indexed_file_ids(include_pets)?.into_iter().collect())@@ -341,36 +551,37 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().update_face_id_to_cluster_id(&face_id_to_cluster_id)?)}pub fn cluster_id_to_face_count(&self) -> Result<HashMap<String, i64>, MlDbError> {- Ok(self.inner.cluster_id_to_face_count()?)+ Ok(self.inner.db().cluster_id_to_face_count()?)}pub fn get_bad_face_singleton_cluster_ids(&self) -> Result<HashSet<String>, MlDbError> {- Ok(self.inner.get_bad_face_singleton_cluster_ids()?)+ Ok(self.inner.db().get_bad_face_singleton_cluster_ids()?)}pub fn get_cluster_to_face_ids(&self,cluster_ids: HashSet<String>,) -> Result<HashMap<String, Vec<String>>, MlDbError> {- Ok(self.inner.get_cluster_to_face_ids(&cluster_ids)?)+ Ok(self.inner.db().get_cluster_to_face_ids(&cluster_ids)?)}pub fn get_cluster_id_for_face_id(&self, face_id: String) -> Result<Option<String>, MlDbError> {- Ok(self.inner.get_cluster_id_for_face_id(&face_id)?)+ Ok(self.inner.db().get_cluster_id_for_face_id(&face_id)?)}pub fn get_all_cluster_id_to_face_ids(&self,) -> Result<HashMap<String, Vec<String>>, MlDbError> {- Ok(self.inner.get_all_cluster_id_to_face_ids()?)+ Ok(self.inner.db().get_all_cluster_id_to_face_ids()?)}pub fn get_face_ids_for_cluster(&self, cluster_id: String) -> Result<Vec<String>, MlDbError> {- Ok(self.inner.get_face_ids_for_cluster(&cluster_id)?)+ Ok(self.inner.db().get_face_ids_for_cluster(&cluster_id)?)}pub fn get_face_ids_for_cluster_ordered_by_score(@@ -380,22 +591,23 @@ impl MlDb {) -> Result<Vec<String>, MlDbError> {Ok(self.inner+ .db().get_face_ids_for_cluster_ordered_by_score(&cluster_id, limit)?)}pub fn get_blur_values_for_cluster(&self, cluster_id: String) -> Result<Vec<f64>, MlDbError> {- Ok(self.inner.get_blur_values_for_cluster(&cluster_id)?)+ Ok(self.inner.db().get_blur_values_for_cluster(&cluster_id)?)}pub fn get_face_ids_to_cluster_ids(&self,face_ids: Vec<String>,) -> Result<HashMap<String, Option<String>>, MlDbError> {- Ok(self.inner.get_face_ids_to_cluster_ids(&face_ids)?)+ Ok(self.inner.db().get_face_ids_to_cluster_ids(&face_ids)?)}pub fn get_file_id_to_cluster_ids(&self) -> Result<HashMap<i64, HashSet<String>>, MlDbError> {- Ok(self.inner.get_file_id_to_cluster_ids()?)+ Ok(self.inner.db().get_file_id_to_cluster_ids()?)}pub fn force_update_cluster_ids(@@ -404,6 +616,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().force_update_cluster_ids(&face_id_to_cluster_id)?)}@@ -413,6 +626,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().remove_face_id_to_cluster_id(&face_id_to_cluster_id)?)}@@ -422,11 +636,12 @@ impl MlDb {) -> Result<HashMap<i64, HashSet<String>>, MlDbError> {Ok(self.inner+ .db().get_file_id_to_cluster_id_set_for_cluster(&cluster_ids)?)}pub fn get_file_ids_of_cluster_id(&self, cluster_id: String) -> Result<Vec<i64>, MlDbError> {- Ok(self.inner.get_file_ids_of_cluster_id(&cluster_id)?)+ Ok(self.inner.db().get_file_ids_of_cluster_id(&cluster_id)?)}pub fn get_cluster_centroid_vector_id_map(@@ -436,6 +651,7 @@ impl MlDb {) -> Result<HashMap<String, i64>, MlDbError> {Ok(self.inner+ .db().get_cluster_centroid_vector_id_map(&cluster_ids, create_if_missing)?)}@@ -445,40 +661,47 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().delete_cluster_centroid_vector_id_mapping(&cluster_id)?)}pub fn clear_cluster_centroid_vector_id_mappings(&self) -> Result<(), MlDbError> {- Ok(self.inner.clear_cluster_centroid_vector_id_mappings()?)+ Ok(self+ .inner+ .db()+ .clear_cluster_centroid_vector_id_mappings()?)}pub fn upsert_cluster_summary_rows(&self,summary: HashMap<String, ClusterSummary>,) -> Result<(), MlDbError> {- Ok(self.inner.upsert_cluster_summary_rows(&summary)?)+ Ok(self.inner.db().upsert_cluster_summary_rows(&summary)?)}pub fn delete_cluster_summary_row(&self, cluster_id: String) -> Result<(), MlDbError> {- Ok(self.inner.delete_cluster_summary_row(&cluster_id)?)+ Ok(self.inner.db().delete_cluster_summary_row(&cluster_id)?)}pub fn get_all_cluster_summary(&self,min_cluster_size: Option<i64>,) -> Result<HashMap<String, ClusterSummary>, MlDbError> {- Ok(self.inner.get_all_cluster_summary(min_cluster_size)?)+ Ok(self.inner.db().get_all_cluster_summary(min_cluster_size)?)}pub fn get_cluster_to_cluster_summary(&self,cluster_ids: Vec<String>,) -> Result<HashMap<String, ClusterSummary>, MlDbError> {- Ok(self.inner.get_cluster_to_cluster_summary(&cluster_ids)?)+ Ok(self+ .inner+ .db()+ .get_cluster_to_cluster_summary(&cluster_ids)?)}pub fn count_cluster_summaries(&self) -> Result<i64, MlDbError> {- Ok(self.inner.count_cluster_summaries()?)+ Ok(self.inner.db().count_cluster_summaries()?)}pub fn get_cluster_summary_page(@@ -488,18 +711,19 @@ impl MlDb {) -> Result<Vec<ClusterCentroidRow>, MlDbError> {Ok(self.inner+ .db().get_cluster_summary_page(before_cluster_id.as_deref(), limit)?)}pub fn reset_cluster_tables(&self, faces: bool) -> Result<(), MlDbError> {- Ok(self.inner.reset_cluster_tables(faces)?)+ Ok(self.inner.db().reset_cluster_tables(faces)?)}pub fn get_clusters_for_memory_lane(&self,assigned: HashSet<String>,) -> Result<HashSet<String>, MlDbError> {- Ok(self.inner.get_clusters_for_memory_lane(&assigned)?)+ Ok(self.inner.db().get_clusters_for_memory_lane(&assigned)?)}pub fn get_clusters_with_three_or_more_not_person_feedback(@@ -507,6 +731,7 @@ impl MlDb {) -> Result<HashSet<String>, MlDbError> {Ok(self.inner+ .db().get_clusters_with_three_or_more_not_person_feedback()?)}@@ -514,41 +739,44 @@ impl MlDb {&self,person_id: String,) -> Result<HashSet<String>, MlDbError> {- Ok(self.inner.get_person_ignored_clusters(&person_id)?)+ Ok(self.inner.db().get_person_ignored_clusters(&person_id)?)}pub fn get_person_to_rejected_suggestions(&self,) -> Result<HashMap<String, HashSet<String>>, MlDbError> {- Ok(self.inner.get_person_to_rejected_suggestions()?)+ Ok(self.inner.db().get_person_to_rejected_suggestions()?)}pub fn get_person_cluster_ids(&self, person_id: String) -> Result<HashSet<String>, MlDbError> {- Ok(self.inner.get_person_cluster_ids(&person_id)?)+ Ok(self.inner.db().get_person_cluster_ids(&person_id)?)}pub fn get_persons_cluster_ids(&self,person_ids: Vec<String>,) -> Result<HashSet<String>, MlDbError> {- Ok(self.inner.get_persons_cluster_ids(&person_ids)?)+ Ok(self.inner.db().get_persons_cluster_ids(&person_ids)?)}pub fn get_person_to_cluster_id_to_face_ids(&self,) -> Result<HashMap<String, HashMap<String, HashSet<String>>>, MlDbError> {- Ok(self.inner.get_person_to_cluster_id_to_face_ids()?)+ Ok(self.inner.db().get_person_to_cluster_id_to_face_ids()?)}pub fn get_person_to_cluster_ids(&self) -> Result<HashMap<String, HashSet<String>>, MlDbError> {- Ok(self.inner.get_person_to_cluster_ids()?)+ Ok(self.inner.db().get_person_to_cluster_ids()?)}pub fn get_face_id_to_person_id_for_faces(&self,face_ids: Vec<String>,) -> Result<HashMap<String, String>, MlDbError> {- Ok(self.inner.get_face_id_to_person_id_for_faces(&face_ids)?)+ Ok(self+ .inner+ .db()+ .get_face_id_to_person_id_for_faces(&face_ids)?)}pub fn get_cluster_id_to_face_ids_for_person(@@ -557,11 +785,12 @@ impl MlDb {) -> Result<HashMap<String, HashSet<String>>, MlDbError> {Ok(self.inner+ .db().get_cluster_id_to_face_ids_for_person(&person_id)?)}pub fn get_face_ids_for_person(&self, person_id: String) -> Result<HashSet<String>, MlDbError> {- Ok(self.inner.get_face_ids_for_person(&person_id)?)+ Ok(self.inner.db().get_face_ids_for_person(&person_id)?)}pub fn get_face_ids_for_person_ordered_by_score(@@ -571,11 +800,12 @@ impl MlDb {) -> Result<Vec<String>, MlDbError> {Ok(self.inner+ .db().get_face_ids_for_person_ordered_by_score(&person_id, limit)?)}pub fn remove_person(&self, person_id: String) -> Result<(), MlDbError> {- Ok(self.inner.remove_person(&person_id)?)+ Ok(self.inner.db().remove_person(&person_id)?)}pub fn assign_cluster_to_person(@@ -585,6 +815,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().assign_cluster_to_person(&person_id, &cluster_id)?)}@@ -594,6 +825,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().bulk_assign_cluster_to_person_id(&cluster_to_person_id)?)}@@ -604,6 +836,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().capture_not_person_feedback(&person_id, &cluster_id)?)}@@ -613,6 +846,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().bulk_capture_not_person_feedback(&cluster_to_person_id)?)}@@ -623,6 +857,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().remove_not_person_feedback(&person_id, &cluster_id)?)}@@ -633,6 +868,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().remove_cluster_to_person(&person_id, &cluster_id)?)}@@ -640,31 +876,34 @@ impl MlDb {&self,person_id: String,) -> Result<HashMap<i64, HashSet<String>>, MlDbError> {- Ok(self.inner.get_file_id_to_cluster_id_set(&person_id)?)+ Ok(self.inner.db().get_file_id_to_cluster_id_set(&person_id)?)}pub fn get_cluster_id_to_person_id(&self) -> Result<HashMap<String, String>, MlDbError> {- Ok(self.inner.get_cluster_id_to_person_id()?)+ Ok(self.inner.db().get_cluster_id_to_person_id()?)}pub fn drop_faces_feedback_tables(&self) -> Result<(), MlDbError> {- Ok(self.inner.drop_faces_feedback_tables()?)+ Ok(self.inner.db().drop_faces_feedback_tables()?)}pub fn get_file_ids_of_person_id(&self, person_id: String) -> Result<Vec<i64>, MlDbError> {- Ok(self.inner.get_file_ids_of_person_id(&person_id)?)+ Ok(self.inner.db().get_file_ids_of_person_id(&person_id)?)}pub fn get_all_clip_vectors(&self) -> Result<Vec<EmbeddingVector>, MlDbError> {- Ok(self.inner.get_all_clip_vectors()?)+ Ok(self.inner.db().get_all_clip_vectors()?)}pub fn clip_indexed_file_with_version(&self) -> Result<HashMap<i64, i64>, MlDbError> {- Ok(self.inner.clip_indexed_file_with_version()?)+ Ok(self.inner.db().clip_indexed_file_with_version()?)}pub fn get_clip_indexed_file_count(&self, minimum_ml_version: i64) -> Result<i64, MlDbError> {- Ok(self.inner.get_clip_indexed_file_count(minimum_ml_version)?)+ Ok(self+ .inner+ .db()+ .get_clip_indexed_file_count(minimum_ml_version)?)}pub fn get_clip_vectorizable_file_count(@@ -673,35 +912,36 @@ impl MlDb {) -> Result<i64, MlDbError> {Ok(self.inner+ .db().get_clip_vectorizable_file_count(minimum_ml_version)?)}pub fn insert_clip_rows(&self, embeddings: Vec<ClipEmbedding>) -> Result<(), MlDbError> {- Ok(self.inner.insert_clip_rows(&embeddings)?)+ Ok(self.inner.db().insert_clip_rows(&embeddings)?)}pub fn delete_clip_rows(&self, file_ids: Vec<i64>) -> Result<(), MlDbError> {- Ok(self.inner.delete_clip_rows(&file_ids)?)+ Ok(self.inner.db().delete_clip_rows(&file_ids)?)}pub fn delete_all_clip_rows(&self) -> Result<(), MlDbError> {- Ok(self.inner.delete_all_clip_rows()?)+ Ok(self.inner.db().delete_all_clip_rows()?)}pub fn count_clip_rows(&self) -> Result<i64, MlDbError> {- Ok(self.inner.count_clip_rows()?)+ Ok(self.inner.db().count_clip_rows()?)}pub fn get_clip_rows_page(&self, limit: i64, offset: i64) -> Result<Vec<ClipRow>, MlDbError> {- Ok(self.inner.get_clip_rows_page(limit, offset)?)+ Ok(self.inner.db().get_clip_rows_page(limit, offset)?)}pub fn bulk_insert_pet_faces(&self, pet_faces: Vec<PetFaceRow>) -> Result<(), MlDbError> {- Ok(self.inner.bulk_insert_pet_faces(&pet_faces)?)+ Ok(self.inner.db().bulk_insert_pet_faces(&pet_faces)?)}pub fn bulk_insert_pet_bodies(&self, pet_bodies: Vec<PetBodyRow>) -> Result<(), MlDbError> {- Ok(self.inner.bulk_insert_pet_bodies(&pet_bodies)?)+ Ok(self.inner.db().bulk_insert_pet_bodies(&pet_bodies)?)}pub fn update_pet_face_vector_ids(@@ -710,6 +950,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().update_pet_face_vector_ids(&pet_face_id_to_vector_id)?)}@@ -719,6 +960,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().update_pet_body_vector_ids(&pet_body_id_to_vector_id)?)}@@ -726,29 +968,32 @@ impl MlDb {&self,file_upload_id: i64,) -> Result<Vec<PetFaceRow>, MlDbError> {- Ok(self.inner.get_pet_faces_for_file_id(file_upload_id)?)+ Ok(self.inner.db().get_pet_faces_for_file_id(file_upload_id)?)}pub fn get_pet_bodies_for_file_id(&self,file_upload_id: i64,) -> Result<Vec<PetBodyRow>, MlDbError> {- Ok(self.inner.get_pet_bodies_for_file_id(file_upload_id)?)+ Ok(self.inner.db().get_pet_bodies_for_file_id(file_upload_id)?)}pub fn pet_indexed_file_ids(&self,minimum_ml_version: i64,) -> Result<HashMap<i64, i64>, MlDbError> {- Ok(self.inner.pet_indexed_file_ids(minimum_ml_version)?)+ Ok(self.inner.db().pet_indexed_file_ids(minimum_ml_version)?)}pub fn get_pet_indexed_file_count(&self, minimum_ml_version: i64) -> Result<i64, MlDbError> {- Ok(self.inner.get_pet_indexed_file_count(minimum_ml_version)?)+ Ok(self+ .inner+ .db()+ .get_pet_indexed_file_count(minimum_ml_version)?)}pub fn get_pet_rows_for_files(&self, file_ids: Vec<i64>) -> Result<PetRowsForFiles, MlDbError> {- Ok(self.inner.get_pet_rows_for_files(&file_ids)?)+ Ok(self.inner.db().get_pet_rows_for_files(&file_ids)?)}pub fn delete_pet_rows_for_files(@@ -759,6 +1004,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().delete_pet_rows_for_files(&file_ids, &pet_face_ids, &pet_body_ids)?)}@@ -769,6 +1015,7 @@ impl MlDb {) -> Result<HashMap<String, i64>, MlDbError> {Ok(self.inner+ .db().get_pet_face_vector_id_map(&pet_face_ids, create_if_missing)?)}@@ -779,6 +1026,7 @@ impl MlDb {) -> Result<HashMap<String, i64>, MlDbError> {Ok(self.inner+ .db().get_pet_body_vector_id_map(&pet_body_ids, create_if_missing)?)}@@ -789,6 +1037,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().put_repeated_text_embedding_cache(&query, &embedding)?)}@@ -796,7 +1045,7 @@ impl MlDb {&self,query: String,) -> Result<Option<Vec<f32>>, MlDbError> {- Ok(self.inner.get_repeated_text_embedding_cache(&query)?)+ Ok(self.inner.db().get_repeated_text_embedding_cache(&query)?)}pub fn put_face_id_cached_for_person_or_cluster(@@ -806,6 +1055,7 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().put_face_id_cached_for_person_or_cluster(&person_or_cluster_id, &face_id)?)}@@ -815,6 +1065,7 @@ impl MlDb {) -> Result<Option<String>, MlDbError> {Ok(self.inner+ .db().get_face_id_used_for_person_or_cluster(&person_or_cluster_id)?)}@@ -824,15 +1075,16 @@ impl MlDb {) -> Result<(), MlDbError> {Ok(self.inner+ .db().remove_face_id_cached_for_person_or_cluster(&person_or_cluster_id)?)}pub fn put_fd_status(&self, fd_status_list: Vec<FdStatus>) -> Result<(), MlDbError> {- Ok(self.inner.put_fd_status(&fd_status_list)?)+ Ok(self.inner.db().put_fd_status(&fd_status_list)?)}pub fn get_file_ids_vid_preview(&self) -> Result<HashMap<i64, PreviewInfo>, MlDbError> {- Ok(self.inner.get_file_ids_vid_preview()?)+ Ok(self.inner.db().get_file_ids_vid_preview()?)}pub fn get_file_ids_with_fd_data(@@ -841,6 +1093,7 @@ impl MlDb {) -> Result<Vec<i64>, MlDbError> {Ok(self.inner+ .db().get_file_ids_with_fd_data(data_type.as_deref())?.into_iter().collect())@@ -849,7 +1102,7 @@ impl MlDb {#[cfg(test)]mod tests {- use super::{MlDbError, ml_db};+ use super::{FillOutcome, FillReport, MlDbError, ml_db, ml_store};#[test]fn downgrade_errors_keep_the_bridge_variant_and_message() {@@ -872,4 +1125,40 @@ mod tests {MlDbError::Other { message } if message == "invalid value"));}++ #[test]+ fn store_errors_wrapping_a_downgrade_keep_the_downgrade_variant() {+ let error = MlDbError::from(ml_store::Error::Database(ml_db::Error::Downgrade {+ current: 16,+ target: 15,+ }));+ assert!(matches!(+ error,+ MlDbError::Downgrade { message }+ if message == "currentVersion(16) cannot be greater than toVersion(15)"+ ));+ }++ #[test]+ fn other_store_errors_map_to_the_other_variant() {+ let error = MlDbError::from(ml_store::Error::InvalidArgument("bad path".into()));+ assert!(matches!(+ error,+ MlDbError::Other { message } if message == "bad path"+ ));+ }++ #[test]+ fn fill_reports_keep_their_outcome_and_counts() {+ let report = FillReport::from(ml_store::FillReport {+ outcome: FillOutcome::Superseded,+ rows: 3,+ indexed: 2,+ skipped: 1,+ resumed: true,+ });+ assert_eq!(report.outcome, FillOutcome::Superseded);+ assert_eq!((report.rows, report.indexed, report.skipped), (3, 2, 1));+ assert!(report.resumed);+ }}diff --git a/rust/bindings/frb/photos/src/api/vecdb_api.rs b/rust/bindings/frb/photos/src/api/vecdb_api.rsindex 4555f25139..a1e18959ff 100644--- a/rust/bindings/frb/photos/src/api/vecdb_api.rs+++ b/rust/bindings/frb/photos/src/api/vecdb_api.rs@@ -54,7 +54,7 @@ fn to_engine_storage(storage: VecDbStorage) -> vecdb::StorageKind {}}-fn to_api_storage(storage: vecdb::StorageKind) -> VecDbStorage {+pub(crate) fn to_api_storage(storage: vecdb::StorageKind) -> VecDbStorage {match storage {vecdb::StorageKind::F32 => VecDbStorage::F32,vecdb::StorageKind::I8 => VecDbStorage::I8,@@ -136,10 +136,29 @@ fn to_api_match(entry: vecdb::Match) -> VecDbMatch {}}-fn to_api_matches(matches: Vec<vecdb::Match>) -> Vec<VecDbMatch> {+pub(crate) fn to_api_matches(matches: Vec<vecdb::Match>) -> Vec<VecDbMatch> {matches.into_iter().map(to_api_match).collect()}+pub(crate) fn to_api_key_matches(entry: vecdb::KeyMatches) -> VecDbKeyMatches {+ VecDbKeyMatches {+ key: entry.key,+ matches: to_api_matches(entry.matches),+ }+}++pub(crate) fn to_api_stats(stats: vecdb::Stats) -> VecDbStats {+ VecDbStats {+ live_count: stats.live_count as u32,+ dead_count: stats.dead_count as u32,+ dims: stats.dims as u32,+ storage: to_api_storage(stats.storage),+ log_bytes: stats.log_bytes,+ records_since_snapshot: stats.records_since_snapshot as u32,+ approximate_memory_bytes: stats.approximate_memory_bytes as u64,+ }+}+pub fn delete_vec_db_files(file_path: String) -> Result<(), RustVecDbError> {Ok(vecdb::VecDb::purge(Path::new(&file_path))?)}@@ -328,13 +347,7 @@ impl VecDb {exact,restrict_to_input,)?;- Ok(results- .into_iter()- .map(|entry| VecDbKeyMatches {- key: entry.key,- matches: to_api_matches(entry.matches),- })- .collect())+ Ok(results.into_iter().map(to_api_key_matches).collect())}pub fn bulk_get_vectors(@@ -364,16 +377,7 @@ impl VecDb {}pub fn get_index_stats(&self) -> Result<VecDbStats, RustVecDbError> {- let stats = self.inner.stats()?;- Ok(VecDbStats {- live_count: stats.live_count as u32,- dead_count: stats.dead_count as u32,- dims: stats.dims as u32,- storage: to_api_storage(stats.storage),- log_bytes: stats.log_bytes,- records_since_snapshot: stats.records_since_snapshot as u32,- approximate_memory_bytes: stats.approximate_memory_bytes as u64,- })+ Ok(to_api_stats(self.inner.stats()?))}}diff --git a/rust/crates/photos/src/ml_store/fill.rs b/rust/crates/photos/src/ml_store/fill.rsindex 82adceff1f..5153380501 100644--- a/rust/crates/photos/src/ml_store/fill.rs+++ b/rust/crates/photos/src/ml_store/fill.rs@@ -200,6 +200,7 @@ impl MlStore {return Ok(FillOutcome::Superseded);}state::mark_filled(&self.db, index)?;+ self.indexes[index.position()].remove_legacy_files();Ok(FillOutcome::Completed)}}@@ -218,8 +219,9 @@ mod tests {use super::{ClipSource, FillOutcome, FillReport, FillRow, FillSource};use crate::ml_db::{ClipEmbedding, ClusterSummary, MlDb};use crate::ml_store::tests::{- centroid, clips, empty, hot_position, index_path, live_count, lose_index_files, meta,- nearest, one_hot, open, open_in, open_with_unusable_clip_index,+ all_exist, centroid, clips, create_usearch_files, empty, hot_position, index_path,+ live_count, lose_index_files, meta, nearest, one_hot, open, open_in,+ open_with_unusable_clip_index,};use crate::ml_store::{Error, FillState, Index, MlStore, Result};@@ -561,6 +563,22 @@ mod tests {assert!(store.contains(Index::Clip, "3500").unwrap());}+ #[test]+ fn superseded_fills_leave_legacy_usearch_files_in_place() {+ let (directory, store) = open();+ store.db().insert_clip_rows(&clips(1..=1500)).unwrap();+ let clip = create_usearch_files(&directory, "ente.ml.vectordb.clip.usearch");+ PAGE_HOOK.set(Some(Box::new(|store: &MlStore| {+ store.db().delete_meta("clip.fill").unwrap();+ })));+ let report = store.fill::<HookedClipSource>(false);+ PAGE_HOOK.take();++ assert_eq!(report.unwrap().outcome, FillOutcome::Superseded);+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ assert!(all_exist(&clip));+ }+#[test]fn fill_stops_when_its_index_is_lost_before_the_finishing_flush() {let (directory, store) = open();diff --git a/rust/crates/photos/src/ml_store/index.rs b/rust/crates/photos/src/ml_store/index.rsindex 0ca18c14c8..0d33c2603b 100644--- a/rust/crates/photos/src/ml_store/index.rs+++ b/rust/crates/photos/src/ml_store/index.rs@@ -1,5 +1,6 @@+use std::ffi::OsStr;use std::fs;-use std::io::ErrorKind;+use std::io::{self, ErrorKind};use std::path::{Path, PathBuf};use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};@@ -78,6 +79,7 @@ pub(super) fn db_stem(db_path: &Path) -> Result<String> {pub(super) struct Slot {index: Index,path: PathBuf,+ legacy_prefix: PathBuf,handle: RwLock<Option<VecDb>>,}@@ -86,6 +88,7 @@ impl Slot {Self {index,path: db_path.with_file_name(format!("{db_stem}.vecdb.{}", index.name())),+ legacy_prefix: db_path.with_file_name(format!("{db_stem}.vectordb.{}.", index.name())),handle: RwLock::new(None),}}@@ -117,6 +120,10 @@ impl Slot {VecDb::purge(&self.path).map_err(Into::into)}+ pub(super) fn remove_legacy_files(&self) {+ remove_files_starting_with(&self.legacy_prefix);+ }+pub(super) fn with_open_handle<T>(&self,operation: &impl Fn(&VecDb) -> IndexResult<T>,@@ -170,6 +177,60 @@ fn unless_closed<T>(outcome: IndexResult<T>) -> Option<Result<T>> {}}+fn remove_files_starting_with(prefix_path: &Path) {+ let Some(prefix) = prefix_path.file_name() else {+ return;+ };+ let directory = scan_directory(prefix_path);+ match fs::read_dir(directory) {+ Ok(entries) => {+ for entry in entries {+ remove_entry_starting_with(directory, prefix, entry);+ }+ }+ Err(error) => warn_unless_not_found(directory, &error),+ }+}++fn scan_directory(prefix_path: &Path) -> &Path {+ match prefix_path.parent() {+ Some(parent) if !parent.as_os_str().is_empty() => parent,+ _ => Path::new("."),+ }+}++fn remove_entry_starting_with(directory: &Path, prefix: &OsStr, entry: io::Result<fs::DirEntry>) {+ let path = match entry {+ Ok(entry) => entry.path(),+ Err(error) => {+ warn_unless_not_found(directory, &error);+ return;+ }+ };+ if !file_name_starts_with(&path, prefix) {+ return;+ }+ if let Err(error) = fs::remove_file(&path) {+ warn_unless_not_found(&path, &error);+ }+}++fn file_name_starts_with(path: &Path, prefix: &OsStr) -> bool {+ path.file_name().is_some_and(|name| {+ name.as_encoded_bytes()+ .starts_with(prefix.as_encoded_bytes())+ })+}++fn warn_unless_not_found(path: &Path, error: &io::Error) {+ if error.kind() != ErrorKind::NotFound {+ log::warn!(+ "{}: could not remove legacy usearch files: {error}",+ path.display()+ );+ }+}+#[cfg(test)]mod tests {use std::collections::HashMap;@@ -178,11 +239,12 @@ mod tests {use ente_vecdb::{OpenCost, StorageKind, VecDb};- use super::Index;+ use super::{Index, scan_directory};use crate::db::Connection;use crate::ml_db::CLIP_EMBEDDING_DIMENSIONS;use crate::ml_store::tests::{- DB_FILE, centroid, clips, index_path, live_count, lose_index_files, meta, one_hot, open,+ DB_FILE, all_exist, centroid, clips, create_usearch_files, index_path, live_count,+ lose_index_files, meta, one_hot, open, open_with_unusable_clip_index,};use crate::ml_store::{Error, FillOutcome, FillReport, FillState, MlStore};@@ -335,6 +397,76 @@ mod tests {assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);}+ #[test]+ fn completed_fills_remove_their_legacy_usearch_files() {+ let (directory, store) = open();+ let clip = create_usearch_files(&directory, "ente.ml.vectordb.clip.usearch");+ let centroid =+ create_usearch_files(&directory, "ente.ml.vectordb.cluster_centroid.usearch");+ let pet = create_usearch_files(&directory, "ente.ml.vectordb.pet.dog_face.usearch");+ let offline = create_usearch_files(&directory, "ente.ml.offline.vectordb.clip.usearch");++ assert_eq!(+ store.fill_clip_index(false).unwrap().outcome,+ FillOutcome::Completed+ );+ assert!(clip.iter().all(|path| !path.exists()));+ assert!(all_exist(¢roid));++ assert_eq!(+ store.fill_cluster_centroid_index(false).unwrap().outcome,+ FillOutcome::Completed+ );+ assert!(centroid.iter().all(|path| !path.exists()));+ assert!(all_exist(&pet));+ assert!(all_exist(&offline));+ }++ #[test]+ fn fills_that_do_not_complete_leave_legacy_usearch_files_in_place() {+ let (directory, store) = open_with_unusable_clip_index();+ let clip = create_usearch_files(&directory, "ente.ml.vectordb.clip.usearch");+ assert!(matches!(store.fill_clip_index(false), Err(Error::Index(_))));+ assert!(all_exist(&clip));++ store.fill_cluster_centroid_index(false).unwrap();+ let centroid =+ create_usearch_files(&directory, "ente.ml.vectordb.cluster_centroid.usearch");+ assert_eq!(+ store.fill_cluster_centroid_index(false).unwrap().outcome,+ FillOutcome::AlreadyFilled+ );+ assert!(all_exist(¢roid));+ }++ #[test]+ fn legacy_usearch_removal_failures_do_not_fail_the_fill() {+ let (directory, store) = open();+ let blocker = directory.path().join("ente.ml.vectordb.clip.usearch");+ fs::create_dir(&blocker).unwrap();+ let sibling = directory.path().join("ente.ml.vectordb.clip.tmp.1.2");+ fs::write(&sibling, b"usearch").unwrap();+ assert_eq!(+ store.fill_clip_index(false).unwrap().outcome,+ FillOutcome::Completed+ );+ assert!(blocker.is_dir());+ assert!(!sibling.exists());+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ }++ #[test]+ fn legacy_files_are_scanned_beside_the_prefix() {+ assert_eq!(+ scan_directory(Path::new("ente.ml.vectordb.clip.")),+ Path::new(".")+ );+ assert_eq!(+ scan_directory(Path::new("/data/ente.ml.vectordb.clip.")),+ Path::new("/data")+ );+ }+#[test]fn lost_index_files_are_detected_by_reads() {let (directory, store) = open();diff --git a/rust/crates/photos/src/ml_store/mod.rs b/rust/crates/photos/src/ml_store/mod.rsindex 6c73fc359d..73243005f6 100644--- a/rust/crates/photos/src/ml_store/mod.rs+++ b/rust/crates/photos/src/ml_store/mod.rs@@ -242,6 +242,19 @@ mod tests {VecDb::purge(path).unwrap();}+ pub(super) fn create_usearch_files(directory: &TempDir, name: &str) -> [PathBuf; 2] {+ let index_file = directory.path().join(name);+ let save_temp_file = index_file.with_extension("tmp.1.2");+ [index_file, save_temp_file].map(|path| {+ fs::write(&path, b"usearch").unwrap();+ path+ })+ }++ pub(super) fn all_exist(paths: &[PathBuf]) -> bool {+ paths.iter().all(|path| path.exists())+ }+#[test]fn open_creates_no_index_files_and_fillable_indexes_start_stale() {let (directory, store) = open();