π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add MlStore composing the ML DB with vecdb indexes
laurenspriem93f79f08fd53
diff --git a/mobile/apps/photos/lib/db/ml/dart_db.dart b/mobile/apps/photos/lib/db/ml/dart_db.dartindex 49794d12e6..7fb429367a 100644--- a/mobile/apps/photos/lib/db/ml/dart_db.dart+++ b/mobile/apps/photos/lib/db/ml/dart_db.dart@@ -77,6 +77,7 @@ class DartMLDataDBcreatePetBodiesTable,createPetFaceVectorIdMappingTable,createPetBodyVectorIdMappingTable,+ createMlStoreMetaTable,];static const List<String> _localGalleryMigrationScripts = [..._defaultMigrationScripts,diff --git a/mobile/apps/photos/lib/db/ml/schema.dart b/mobile/apps/photos/lib/db/ml/schema.dartindex e7220042e2..b233423acc 100644--- a/mobile/apps/photos/lib/db/ml/schema.dart+++ b/mobile/apps/photos/lib/db/ml/schema.dart@@ -245,3 +245,13 @@ CREATE TABLE IF NOT EXISTS $petBodyVectorIdMappingTable (const deletePetBodyVectorIdMappingTable ='DELETE FROM $petBodyVectorIdMappingTable';++const mlStoreMetaTable = 'ml_store_meta';++const createMlStoreMetaTable =+ '''+CREATE TABLE IF NOT EXISTS $mlStoreMetaTable (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+);+''';diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 1903e011d8..5b7bc5c631 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2774,7 +2774,9 @@ dependencies = ["ente-core","ente-exif","ente-location",+ "ente-vecdb","futures-util",+ "log","quick-xml","rusqlite","serde",diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.tomlindex 2b9f13c6f5..25ca94302a 100644--- a/rust/crates/photos/Cargo.toml+++ b/rust/crates/photos/Cargo.toml@@ -8,6 +8,8 @@ ente-collections.workspace = trueente-core.workspace = trueente-exif.workspace = trueente-location.workspace = true+ente-vecdb.workspace = true+log.workspace = truequick-xml.workspace = truerusqlite = { workspace = true, default-features = true }serde.workspace = truediff --git a/rust/crates/photos/src/lib.rs b/rust/crates/photos/src/lib.rsindex 279f5b6fcc..08e1912399 100644--- a/rust/crates/photos/src/lib.rs+++ b/rust/crates/photos/src/lib.rs@@ -4,6 +4,7 @@ pub mod files;pub mod location;pub mod metadata;pub mod ml_db;+pub mod ml_store;pub mod motion_photo;pub use motion_photo::{diff --git a/rust/crates/photos/src/ml_db/mod.rs b/rust/crates/photos/src/ml_db/mod.rsindex ea72c2a8be..5714cce87e 100644--- a/rust/crates/photos/src/ml_db/mod.rs+++ b/rust/crates/photos/src/ml_db/mod.rs@@ -1,7 +1,7 @@mod migrations;mod queries;mod schema;-mod vector_encoding;+pub(crate) mod vector_encoding;use std::num::NonZeroUsize;use std::path::Path;@@ -78,7 +78,7 @@ impl MlDb {}#[cfg(test)]-mod tests {+pub(crate) mod tests {use std::collections::{HashMap, HashSet};use std::fmt::Debug;use std::path::Path;@@ -97,6 +97,8 @@ mod tests {};}+ pub(crate) use super::queries::clusters::tests::deny_cluster_summary_inserts_after;+ pub(crate) use super::queries::pets::tests::seed as seed_pet_rows;pub(super) use cases;pub(super) fn open() -> (TempDir, MlDb) {@@ -277,8 +279,8 @@ mod tests {let directory = tempfile::tempdir().unwrap();let path = directory.path().join("ente.ml.db");let _db = MlDb::open(&path).unwrap();- assert_eq!(schema::MIGRATION_SCRIPTS.len(), 15);- assert_eq!(user_version(&path), 15);+ assert_eq!(schema::MIGRATION_SCRIPTS.len(), 16);+ assert_eq!(user_version(&path), 16);let connection = Connection::open(&path).unwrap();for table in ["faces",@@ -295,6 +297,7 @@ mod tests {"pet_bodies","pet_face_vector_id_map","pet_body_vector_id_map",+ "ml_store_meta",] {let count: i64 = connection.query_row(@@ -317,7 +320,7 @@ mod tests {db.insert_clip_rows(&[full_clip(1)]).unwrap();}let db = MlDb::open(&path).unwrap();- assert_eq!(user_version(&path), 15);+ assert_eq!(user_version(&path), 16);assert_eq!(db.count_clip_rows().unwrap(), 1);}@@ -328,12 +331,12 @@ mod tests {drop(MlDb::open(&path).unwrap());Connection::open(&path).unwrap()- .pragma_update("user_version", 16)+ .pragma_update("user_version", 17).unwrap();match MlDb::open(&path) {Err(Error::Downgrade { current, target }) => {- assert_eq!(current, 16);- assert_eq!(target, 15);+ assert_eq!(current, 17);+ assert_eq!(target, 16);}other => panic!("expected downgrade error, got {:?}", other.err()),}@@ -351,7 +354,7 @@ mod tests {connection.pragma_update("user_version", 1).unwrap();}let db = MlDb::open(&path).unwrap();- assert_eq!(user_version(&path), 15);+ assert_eq!(user_version(&path), 16);assert_eq!(db.count_clip_rows().unwrap(), 0);}}diff --git a/rust/crates/photos/src/ml_db/queries/clip.rs b/rust/crates/photos/src/ml_db/queries/clip.rsindex 0001693f0b..00cbcb025f 100644--- a/rust/crates/photos/src/ml_db/queries/clip.rs+++ b/rust/crates/photos/src/ml_db/queries/clip.rs@@ -1,6 +1,8 @@use std::collections::HashMap;+use std::num::NonZeroUsize;use super::helpers::pair;+use crate::db::{self, Row};use crate::ml_db::schema;use crate::ml_db::vector_encoding::{decode_f32, encode_f32};use crate::ml_db::{MlDb, Result};@@ -96,14 +98,42 @@ impl MlDb {self.read_all("SELECT file_id, embedding FROM clip ORDER BY file_id DESC LIMIT ? OFFSET ?",[limit, offset],- |row| {- Ok(ClipRow {- file_id: row.get(0)?,- embedding: row.get(1)?,- })- },+ read_clip_row,)}++ pub fn get_clip_rows_before(+ &self,+ before_file_id: Option<i64>,+ limit: NonZeroUsize,+ ) -> Result<Vec<ClipRow>> {+ let limit = limit.get() as i64;+ match before_file_id {+ None => self.read_all(+ "SELECT file_id, embedding FROM clip ORDER BY file_id DESC LIMIT ?",+ [limit],+ read_clip_row,+ ),+ Some(before_file_id) => self.read_all(+ r#"+ SELECT file_id, embedding+ FROM clip+ WHERE file_id < ?+ ORDER BY file_id DESC+ LIMIT ?+ "#,+ (before_file_id, limit),+ read_clip_row,+ ),+ }+ }+}++fn read_clip_row(row: &Row<'_>) -> db::Result<ClipRow> {+ Ok(ClipRow {+ file_id: row.get(0)?,+ embedding: row.get(1)?,+ })}fn clip_row(embedding: &ClipEmbedding) -> (i64, Vec<u8>, i64) {@@ -117,6 +147,7 @@ fn clip_row(embedding: &ClipEmbedding) -> (i64, Vec<u8>, i64) {#[cfg(test)]pub(in crate::ml_db) mod tests {use std::collections::HashMap;+ use std::num::NonZeroUsize;use super::{CLIP_EMBEDDING_DIMENSIONS, ClipEmbedding, ClipRow, MlDb};use crate::ml_db::tests::{cases, check, open};@@ -213,6 +244,24 @@ pub(in crate::ml_db) mod tests {);}+ #[test]+ fn clip_rows_page_by_keyset() {+ let (_directory, db) = seeded();+ let page_size = NonZeroUsize::new(2).unwrap();+ let file_ids =+ |page: &[ClipRow]| -> Vec<i64> { page.iter().map(|row| row.file_id).collect() };+ let first_page = db.get_clip_rows_before(None, page_size).unwrap();+ assert_eq!(file_ids(&first_page), [4, 3]);+ assert_eq!(first_page[1].embedding, encode_f32([1.0, 2.0]));+ let next_page = db.get_clip_rows_before(Some(3), page_size).unwrap();+ assert_eq!(file_ids(&next_page), [2, 1]);+ assert!(+ db.get_clip_rows_before(Some(1), page_size)+ .unwrap()+ .is_empty()+ );+ }+#[test]fn clip_rows_replace_and_delete() {let (_directory, db) = seeded();diff --git a/rust/crates/photos/src/ml_db/queries/clusters.rs b/rust/crates/photos/src/ml_db/queries/clusters.rsindex d5e2a40632..60544a38f0 100644--- a/rust/crates/photos/src/ml_db/queries/clusters.rs+++ b/rust/crates/photos/src/ml_db/queries/clusters.rs@@ -426,8 +426,10 @@ fn read_cluster_centroid(row: &Row<'_>) -> db::Result<ClusterCentroidRow> {#[cfg(test)]pub(in crate::ml_db) mod tests {use std::collections::HashMap;+ use std::path::Path;use super::{ClusterCentroidRow, ClusterSummary, MlDb};+ use crate::db::Connection;use crate::ml_db::queries::{faces, persons};use crate::ml_db::tests::{cases, check, grouped, grouped_by_file, index_count, map, open, pairs, set, sorted, strings,@@ -476,6 +478,17 @@ pub(in crate::ml_db) mod tests {(directory, db)}+ pub(crate) fn deny_cluster_summary_inserts_after(db_path: &Path, rows: usize) {+ Connection::open(db_path)+ .unwrap()+ .execute_batch(&format!(+ "CREATE TRIGGER deny_cluster_summary_insert BEFORE INSERT ON cluster_summary+ WHEN (SELECT COUNT(*) FROM cluster_summary) >= {rows}+ BEGIN SELECT RAISE(FAIL, 'insert denied'); END;"+ ))+ .unwrap();+ }+#[test]fn seeded_counts() {let (_directory, db) = seeded();@@ -697,6 +710,19 @@ pub(in crate::ml_db) mod tests {);}+ #[test]+ fn cluster_summary_upsert_is_atomic() {+ let (directory, db) = open();+ let mut rows = HashMap::new();+ for index in 0..=400 {+ rows.insert(format!("c{index:04}"), summary(index));+ }+ deny_cluster_summary_inserts_after(&directory.path().join("ente.ml.db"), 400);++ assert!(db.upsert_cluster_summary_rows(&rows).is_err());+ assert_eq!(db.count_cluster_summaries().unwrap(), 0);+ }+#[test]fn cluster_centroid_vector_ids() {let (_directory, db) = seeded();diff --git a/rust/crates/photos/src/ml_db/queries/meta.rs b/rust/crates/photos/src/ml_db/queries/meta.rsnew file mode 100644index 0000000000..cf0d43dbf7--- /dev/null+++ b/rust/crates/photos/src/ml_db/queries/meta.rs@@ -0,0 +1,55 @@+use crate::ml_db::schema;+use crate::ml_db::{MlDb, Result};++impl MlDb {+ pub fn get_meta(&self, key: &str) -> Result<Option<String>> {+ self.read_optional(+ "SELECT value FROM ml_store_meta WHERE key = ?",+ [key],+ |row| Ok(row.get(0)?),+ )+ }++ pub fn set_meta(&self, key: &str, value: &str) -> Result<()> {+ self.execute(+ "INSERT OR REPLACE INTO ml_store_meta (key, value) VALUES (?, ?)",+ (key, value),+ )?;+ Ok(())+ }++ pub fn delete_meta(&self, key: &str) -> Result<()> {+ self.execute("DELETE FROM ml_store_meta WHERE key = ?", [key])?;+ Ok(())+ }++ pub fn clear_meta(&self) -> Result<()> {+ self.execute_statements([schema::DELETE_ML_STORE_META])+ }+}++#[cfg(test)]+mod tests {+ use crate::ml_db::tests::open;++ #[test]+ fn meta_rows_are_set_replaced_deleted_and_cleared() {+ let (_directory, db) = open();+ assert_eq!(db.get_meta("clip.fill").unwrap(), None);+ db.set_meta("clip.fill", "filling").unwrap();+ db.set_meta("clip.cursor", "42").unwrap();+ assert_eq!(+ db.get_meta("clip.fill").unwrap().as_deref(),+ Some("filling")+ );+ assert_eq!(db.get_meta("clip.cursor").unwrap().as_deref(), Some("42"));+ db.set_meta("clip.fill", "filled").unwrap();+ assert_eq!(db.get_meta("clip.fill").unwrap().as_deref(), Some("filled"));+ db.delete_meta("clip.cursor").unwrap();+ db.delete_meta("missing").unwrap();+ assert_eq!(db.get_meta("clip.cursor").unwrap(), None);+ assert_eq!(db.get_meta("clip.fill").unwrap().as_deref(), Some("filled"));+ db.clear_meta().unwrap();+ assert_eq!(db.get_meta("clip.fill").unwrap(), None);+ }+}diff --git a/rust/crates/photos/src/ml_db/queries/mod.rs b/rust/crates/photos/src/ml_db/queries/mod.rsindex f49f7410a5..5fb6ef6d2e 100644--- a/rust/crates/photos/src/ml_db/queries/mod.rs+++ b/rust/crates/photos/src/ml_db/queries/mod.rs@@ -4,6 +4,7 @@ pub(super) mod clusters;pub(super) mod faces;pub(super) mod filedata;mod helpers;+pub(super) mod meta;pub(super) mod persons;pub(super) mod pets;diff --git a/rust/crates/photos/src/ml_db/queries/pets.rs b/rust/crates/photos/src/ml_db/queries/pets.rsindex fb56a29056..628fb9db02 100644--- a/rust/crates/photos/src/ml_db/queries/pets.rs+++ b/rust/crates/photos/src/ml_db/queries/pets.rs@@ -340,7 +340,7 @@ fn read_pet_body(row: &Row<'_>) -> db::Result<PetBodyRow> {}#[cfg(test)]-pub(in crate::ml_db) mod tests {+pub(crate) mod tests {use std::collections::HashMap;use super::{MlDb, PetBodyRow, PetFaceRow};@@ -375,7 +375,7 @@ pub(in crate::ml_db) mod tests {}}- pub(in crate::ml_db) fn seed(db: &MlDb) {+ pub(crate) fn seed(db: &MlDb) {db.bulk_insert_pet_faces(&[pet_face(1, 0, 0),pet_face(1, 1, -1),diff --git a/rust/crates/photos/src/ml_db/schema.rs b/rust/crates/photos/src/ml_db/schema.rsindex a2b27cc2a6..58f4f96738 100644--- a/rust/crates/photos/src/ml_db/schema.rs+++ b/rust/crates/photos/src/ml_db/schema.rs@@ -118,7 +118,12 @@ pub const CREATE_PET_BODY_VECTOR_ID_MAPPING_TABLE: &str =pet_body_id TEXT NOT NULL UNIQUE);";-pub const MIGRATION_SCRIPTS: [&str; 15] = [+pub const CREATE_ML_STORE_META_TABLE: &str = "CREATE TABLE IF NOT EXISTS ml_store_meta (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+);";++pub const MIGRATION_SCRIPTS: [&str; 16] = [CREATE_FACES_TABLE,CREATE_FACE_CLUSTERS_TABLE,CREATE_CLUSTER_PERSON_TABLE,@@ -134,6 +139,7 @@ pub const MIGRATION_SCRIPTS: [&str; 15] = [CREATE_PET_BODIES_TABLE,CREATE_PET_FACE_VECTOR_ID_MAPPING_TABLE,CREATE_PET_BODY_VECTOR_ID_MAPPING_TABLE,+ CREATE_ML_STORE_META_TABLE,];pub const DELETE_FACES: &str = "DELETE FROM faces";@@ -149,3 +155,4 @@ pub const DELETE_PET_FACES: &str = "DELETE FROM pet_faces";pub const DELETE_PET_BODIES: &str = "DELETE FROM pet_bodies";pub const DELETE_PET_FACE_VECTOR_ID_MAPPING: &str = "DELETE FROM pet_face_vector_id_map";pub const DELETE_PET_BODY_VECTOR_ID_MAPPING: &str = "DELETE FROM pet_body_vector_id_map";+pub const DELETE_ML_STORE_META: &str = "DELETE FROM ml_store_meta";diff --git a/rust/crates/photos/src/ml_db/vector_encoding.rs b/rust/crates/photos/src/ml_db/vector_encoding.rsindex 8cb9ddff1b..8bda4a3f0f 100644--- a/rust/crates/photos/src/ml_db/vector_encoding.rs+++ b/rust/crates/photos/src/ml_db/vector_encoding.rs@@ -4,7 +4,7 @@ const EVECTOR_VALUES_PACKED_KEY: u32 = 0x0A;const EVECTOR_VALUES_FIXED64_KEY: u32 = 0x09;const MAX_GROUP_DEPTH: usize = 100;-pub(super) fn encode_evector(values: &[f64]) -> Vec<u8> {+pub(crate) fn encode_evector(values: &[f64]) -> Vec<u8> {if values.is_empty() {return Vec::new();}@@ -17,7 +17,7 @@ pub(super) fn encode_evector(values: &[f64]) -> Vec<u8> {bytes}-pub(super) fn decode_evector(bytes: &[u8]) -> Result<Vec<f64>> {+pub(crate) fn decode_evector(bytes: &[u8]) -> Result<Vec<f64>> {let mut values = Vec::new();let mut offset = 0;while offset < bytes.len() {@@ -44,11 +44,11 @@ pub(super) fn decode_evector(bytes: &[u8]) -> Result<Vec<f64>> {Ok(values)}-pub(super) fn encode_f32(values: impl IntoIterator<Item = f32>) -> Vec<u8> {+pub(crate) fn encode_f32(values: impl IntoIterator<Item = f32>) -> Vec<u8> {values.into_iter().flat_map(f32::to_le_bytes).collect()}-pub(super) fn decode_f32(bytes: &[u8]) -> Vec<f32> {+pub(crate) fn decode_f32(bytes: &[u8]) -> Vec<f32> {bytes.as_chunks::<4>().0diff --git a/rust/crates/photos/src/ml_store/fill.rs b/rust/crates/photos/src/ml_store/fill.rsnew file mode 100644index 0000000000..ca5e1c1aca--- /dev/null+++ b/rust/crates/photos/src/ml_store/fill.rs@@ -0,0 +1,634 @@+use std::num::NonZeroUsize;++use ente_vecdb::VecDb;++use super::{FillState, Index, MlStore, Result, state};+use crate::ml_db::MlDb;+use crate::ml_db::vector_encoding::{decode_evector, decode_f32};++const FILL_PAGE: NonZeroUsize = NonZeroUsize::new(1000).unwrap();++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FillOutcome {+ Completed,+ AlreadyFilled,+ Superseded,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct FillReport {+ pub outcome: FillOutcome,+ pub rows: usize,+ pub indexed: usize,+ pub skipped: usize,+ pub resumed: bool,+}++struct FillRow {+ key: String,+ blob: Vec<u8>,+}++trait FillSource {+ const INDEX: Index;++ fn read_page(db: &MlDb, after: Option<&str>, limit: NonZeroUsize) -> Result<Vec<FillRow>>;++ fn decode(key: &str, blob: &[u8]) -> Option<Vec<f32>>;++ #[cfg(test)]+ fn after_page(_store: &MlStore) {}+}++struct ClipSource;++impl FillSource for ClipSource {+ const INDEX: Index = Index::Clip;++ fn read_page(db: &MlDb, after: Option<&str>, limit: NonZeroUsize) -> Result<Vec<FillRow>> {+ let rows = db.get_clip_rows_before(clip_cursor(after), limit)?;+ Ok(rows+ .into_iter()+ .map(|row| FillRow {+ key: row.file_id.to_string(),+ blob: row.embedding,+ })+ .collect())+ }++ fn decode(key: &str, blob: &[u8]) -> Option<Vec<f32>> {+ let vector = decode_f32(blob);+ Index::Clip.accepts(key, &vector).then_some(vector)+ }+}++fn clip_cursor(after: Option<&str>) -> Option<i64> {+ let cursor = after?;+ let file_id = cursor.parse().ok();+ if file_id.is_none() {+ log::warn!("ignoring malformed clip fill cursor {cursor:?}");+ }+ file_id+}++struct ClusterCentroidSource;++impl FillSource for ClusterCentroidSource {+ const INDEX: Index = Index::ClusterCentroid;++ fn read_page(db: &MlDb, after: Option<&str>, limit: NonZeroUsize) -> Result<Vec<FillRow>> {+ let rows = db.get_cluster_summary_page(after, limit.get() as i64)?;+ Ok(rows+ .into_iter()+ .map(|row| FillRow {+ key: row.cluster_id,+ blob: row.avg,+ })+ .collect())+ }++ fn decode(key: &str, blob: &[u8]) -> Option<Vec<f32>> {+ decode_centroid(key, blob)+ }+}++pub(super) fn decode_centroid(cluster_id: &str, avg: &[u8]) -> Option<Vec<f32>> {+ match decode_evector(avg) {+ Ok(values) => {+ let vector: Vec<f32> = values.into_iter().map(|value| value as f32).collect();+ Index::ClusterCentroid+ .accepts(cluster_id, &vector)+ .then_some(vector)+ }+ Err(error) => {+ log::warn!("skipping cluster summary {cluster_id}: {error}");+ None+ }+ }+}++enum Start {+ Skip,+ Fresh,+ Resume { cursor: Option<String> },+}++impl MlStore {+ pub fn fill_clip_index(&self, force: bool) -> Result<FillReport> {+ self.fill::<ClipSource>(force)+ }++ pub fn fill_cluster_centroid_index(&self, force: bool) -> Result<FillReport> {+ self.fill::<ClusterCentroidSource>(force)+ }++ fn fill<S: FillSource>(&self, force: bool) -> Result<FillReport> {+ let _fill = self.lock_fill(S::INDEX);+ let mut report = FillReport {+ outcome: FillOutcome::AlreadyFilled,+ rows: 0,+ indexed: 0,+ skipped: 0,+ resumed: false,+ };+ let mut cursor = match self.start_fill(S::INDEX, force)? {+ Start::Skip => return Ok(report),+ Start::Fresh => None,+ Start::Resume { cursor } => {+ report.resumed = true;+ cursor+ }+ };+ loop {+ let _mutations = self.lock_mutations();+ if state::read(&self.db, S::INDEX)? != FillState::Filling {+ report.outcome = FillOutcome::Superseded;+ return Ok(report);+ }+ let page = S::read_page(&self.db, cursor.as_deref(), FILL_PAGE)?;+ let Some(last_key) = page.last().map(|row| row.key.clone()) else {+ report.outcome = self.finish_fill(S::INDEX)?;+ return Ok(report);+ };+ self.index_page::<S>(page, &mut report)?;+ state::set_cursor(&self.db, S::INDEX, &last_key)?;+ cursor = Some(last_key);+ drop(_mutations);+ #[cfg(test)]+ S::after_page(self);+ }+ }++ fn start_fill(&self, index: Index, force: bool) -> Result<Start> {+ let _mutations = self.lock_mutations();+ self.with_index(index, |_| Ok(()))?;+ match (force, state::read(&self.db, index)?) {+ (false, FillState::Filled) => Ok(Start::Skip),+ (false, FillState::Filling) => Ok(Start::Resume {+ cursor: state::cursor(&self.db, index)?,+ }),+ (true, _) | (false, FillState::Stale) => {+ state::mark_stale(&self.db, index)?;+ self.with_index(index, VecDb::reset)?;+ state::mark_filling(&self.db, index)?;+ Ok(Start::Fresh)+ }+ }+ }++ fn index_page<S: FillSource>(&self, page: Vec<FillRow>, report: &mut FillReport) -> Result<()> {+ report.rows += page.len();+ let mut keys = Vec::with_capacity(page.len());+ let mut vectors = Vec::with_capacity(page.len());+ for row in page {+ match S::decode(&row.key, &row.blob) {+ Some(vector) => {+ keys.push(row.key);+ vectors.push(vector);+ }+ None => report.skipped += 1,+ }+ }+ self.with_index(S::INDEX, |vecdb| vecdb.bulk_add(&keys, &vectors))?;+ report.indexed += keys.len();+ Ok(())+ }++ fn finish_fill(&self, index: Index) -> Result<FillOutcome> {+ self.with_index(index, VecDb::flush)?;+ if state::read(&self.db, index)? != FillState::Filling {+ return Ok(FillOutcome::Superseded);+ }+ state::mark_filled(&self.db, index)?;+ Ok(FillOutcome::Completed)+ }+}++#[cfg(test)]+mod tests {+ use std::cell::RefCell;+ use std::collections::HashMap;+ use std::num::NonZeroUsize;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::sync::{TryLockError, mpsc};+ use std::thread;++ use tempfile::TempDir;++ 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_index_dir,+ };+ use crate::ml_store::{Error, FillState, Index, MlStore, Result};++ #[test]+ fn fill_spans_pages_reports_skips_and_repeats_as_noop() {+ let (_directory, store) = open();+ let mut rows = clips(1..=2500);+ rows.push(ClipEmbedding {+ file_id: 2501,+ embedding: vec![1.0, 2.0],+ version: 1,+ });+ rows.push(ClipEmbedding {+ file_id: 2502,+ embedding: vec![],+ version: 1,+ });+ store.db().insert_clip_rows(&rows).unwrap();++ let report = store.fill_clip_index(false).unwrap();+ assert_eq!(+ report,+ FillReport {+ outcome: FillOutcome::Completed,+ rows: 2502,+ indexed: 2500,+ skipped: 2,+ resumed: false+ }+ );+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ assert_eq!(meta(&store, "clip.fill").as_deref(), Some("filled"));+ assert_eq!(meta(&store, "clip.cursor"), None);+ assert_eq!(live_count(&store, Index::Clip), 2500);+ assert!(store.contains(Index::Clip, "1").unwrap());+ assert!(store.contains(Index::Clip, "2500").unwrap());+ assert!(!store.contains(Index::Clip, "2501").unwrap());+ assert!(!store.contains(Index::Clip, "2502").unwrap());+ assert_eq!(+ store.fill_clip_index(false).unwrap(),+ empty(FillOutcome::AlreadyFilled)+ );+ assert_eq!(live_count(&store, Index::Clip), 2500);+ }++ #[test]+ fn interrupted_fill_resumes_after_the_cursor() {+ let (_directory, store) = open();+ store.fill_clip_index(false).unwrap();+ store.release().unwrap();+ store.db().insert_clip_rows(&clips(1..=2500)).unwrap();+ store.db().set_meta("clip.fill", "filling").unwrap();+ store.db().set_meta("clip.cursor", "1500").unwrap();+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filling);++ let report = store.fill_clip_index(false).unwrap();+ assert_eq!(+ report,+ FillReport {+ outcome: FillOutcome::Completed,+ rows: 1499,+ indexed: 1499,+ skipped: 0,+ resumed: true+ }+ );+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ assert_eq!(meta(&store, "clip.cursor"), None);+ assert!(store.contains(Index::Clip, "1").unwrap());+ assert!(store.contains(Index::Clip, "1499").unwrap());+ assert!(!store.contains(Index::Clip, "1500").unwrap());+ assert!(!store.contains(Index::Clip, "2500").unwrap());+ assert_eq!(live_count(&store, Index::Clip), 1499);+ }++ #[test]+ fn forced_fill_resets_the_index() {+ let (_directory, store) = open();+ store.fill_clip_index(false).unwrap();+ store.put_clip(&clips([1, 2, 3])).unwrap();+ store.db().delete_clip_rows(&[2]).unwrap();+ assert_eq!(+ store.fill_clip_index(false).unwrap(),+ empty(FillOutcome::AlreadyFilled)+ );+ assert!(store.contains(Index::Clip, "2").unwrap());++ let report = store.fill_clip_index(true).unwrap();+ assert_eq!(+ report,+ FillReport {+ outcome: FillOutcome::Completed,+ rows: 2,+ indexed: 2,+ skipped: 0,+ resumed: false+ }+ );+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ assert!(!store.contains(Index::Clip, "2").unwrap());+ assert!(store.contains(Index::Clip, "3").unwrap());+ assert_eq!(live_count(&store, Index::Clip), 2);+ }++ #[test]+ fn centroid_fill_decodes_evectors_and_skips_malformed_rows() {+ let (_directory, store) = open();+ let mut summaries = HashMap::from([centroid("c1", 1), centroid("c2", 2)]);+ summaries.insert(+ "c3".to_string(),+ ClusterSummary {+ avg: vec![0x0A, 0x10, 0x00],+ count: 1,+ },+ );+ store.db().upsert_cluster_summary_rows(&summaries).unwrap();++ let report = store.fill_cluster_centroid_index(false).unwrap();+ assert_eq!(+ report,+ FillReport {+ outcome: FillOutcome::Completed,+ rows: 3,+ indexed: 2,+ skipped: 1,+ resumed: false+ }+ );+ assert_eq!(+ store.fill_state(Index::ClusterCentroid).unwrap(),+ FillState::Filled+ );+ assert_eq!(+ nearest(+ &store,+ Index::ClusterCentroid,+ &one_hot(Index::ClusterCentroid.dims(), 2)+ ),+ "c2"+ );+ assert!(!store.contains(Index::ClusterCentroid, "c3").unwrap());+ let stored = store+ .get_vector(Index::ClusterCentroid, "c1")+ .unwrap()+ .unwrap();+ assert_eq!(hot_position(&stored), Some(1));+ }++ #[test]+ fn non_finite_clip_rows_are_skipped_by_the_fill() {+ let (_directory, store) = open();+ let mut rows = clips([1, 2]);+ rows[1].embedding[0] = f64::NAN;+ store.db().insert_clip_rows(&rows).unwrap();++ let report = store.fill_clip_index(false).unwrap();+ assert_eq!(+ report,+ FillReport {+ outcome: FillOutcome::Completed,+ rows: 2,+ indexed: 1,+ skipped: 1,+ resumed: false+ }+ );+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ assert!(store.contains(Index::Clip, "1").unwrap());+ assert!(!store.contains(Index::Clip, "2").unwrap());+ assert_eq!(live_count(&store, Index::Clip), 1);+ }++ #[test]+ fn lost_index_files_refill_on_a_non_forced_fill() {+ let (directory, store) = open();+ store.db().insert_clip_rows(&clips(1..=1500)).unwrap();+ store.fill_clip_index(false).unwrap();+ lose_index_files(&store, &index_path(&directory, Index::Clip));++ let report = store.fill_clip_index(false).unwrap();+ assert_eq!(+ report,+ FillReport {+ outcome: FillOutcome::Completed,+ rows: 1500,+ indexed: 1500,+ skipped: 0,+ resumed: false+ }+ );+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ assert_eq!(live_count(&store, Index::Clip), 1500);+ assert!(store.contains(Index::Clip, "1").unwrap());+ assert!(store.contains(Index::Clip, "1500").unwrap());+ }++ #[test]+ fn failed_fill_keeps_the_filling_state_and_cursor() {+ let (_directory, store) = open_with_unusable_index_dir();+ store.db().insert_clip_rows(&clips(1..=5)).unwrap();+ store.db().set_meta("clip.fill", "filling").unwrap();+ store.db().set_meta("clip.cursor", "3").unwrap();+ assert!(matches!(store.fill_clip_index(false), Err(Error::Index(_))));+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filling);+ assert_eq!(meta(&store, "clip.cursor").as_deref(), Some("3"));+ }++ struct SupersedingClipSource;++ impl FillSource for SupersedingClipSource {+ const INDEX: Index = Index::Clip;++ fn read_page(db: &MlDb, after: Option<&str>, limit: NonZeroUsize) -> Result<Vec<FillRow>> {+ if SUPERSEDING_READS.fetch_add(1, Ordering::SeqCst) == 1 {+ db.delete_meta("clip.fill")?;+ }+ ClipSource::read_page(db, after, limit)+ }++ fn decode(key: &str, blob: &[u8]) -> Option<Vec<f32>> {+ ClipSource::decode(key, blob)+ }+ }++ static SUPERSEDING_READS: AtomicUsize = AtomicUsize::new(0);++ #[test]+ fn fill_stops_as_superseded_when_the_state_changes_between_pages() {+ let (_directory, store) = open();+ store.db().insert_clip_rows(&clips(1..=2502)).unwrap();++ let report = store.fill::<SupersedingClipSource>(false).unwrap();+ assert_eq!(+ report,+ FillReport {+ outcome: FillOutcome::Superseded,+ rows: 2000,+ indexed: 2000,+ skipped: 0,+ resumed: false+ }+ );+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ assert_eq!(meta(&store, "clip.fill"), None);+ assert_eq!(meta(&store, "clip.cursor").as_deref(), Some("503"));+ assert_eq!(live_count(&store, Index::Clip), 2000);+ assert!(store.contains(Index::Clip, "2502").unwrap());+ assert!(store.contains(Index::Clip, "503").unwrap());+ assert!(!store.contains(Index::Clip, "502").unwrap());+ assert!(!store.contains(Index::Clip, "1").unwrap());+ }++ #[test]+ fn concurrent_deletes_interleave_with_fill_pages() {+ let (_directory, store) = open();+ store.db().insert_clip_rows(&clips(1..=3000)).unwrap();+ let deleted = [5, 1500, 2999];+ thread::scope(|scope| {+ scope.spawn(|| store.fill_clip_index(false).unwrap());+ scope.spawn(|| store.delete_clip(&deleted).unwrap());+ });+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ assert_eq!(store.db().count_clip_rows().unwrap(), 2997);+ assert_eq!(live_count(&store, Index::Clip), 2997);+ for file_id in deleted {+ assert!(!store.contains(Index::Clip, &file_id.to_string()).unwrap());+ }+ assert!(store.contains(Index::Clip, "1").unwrap());+ assert!(store.contains(Index::Clip, "3000").unwrap());+ }++ type PageHook = Option<Box<dyn FnMut(&MlStore)>>;++ thread_local! {+ static PAGE_HOOK: RefCell<PageHook> = const { RefCell::new(None) };+ }++ struct HookedClipSource;++ impl FillSource for HookedClipSource {+ const INDEX: Index = Index::Clip;++ fn read_page(db: &MlDb, after: Option<&str>, limit: NonZeroUsize) -> Result<Vec<FillRow>> {+ ClipSource::read_page(db, after, limit)+ }++ fn decode(key: &str, blob: &[u8]) -> Option<Vec<f32>> {+ ClipSource::decode(key, blob)+ }++ fn after_page(store: &MlStore) {+ PAGE_HOOK.with_borrow_mut(|hook| hook.as_mut().unwrap()(store));+ }+ }++ fn fill_losing_the_index_after_page(+ store: &MlStore,+ directory: &TempDir,+ page: usize,+ ) -> FillReport {+ let path = index_path(directory, Index::Clip);+ let mut pages = 0;+ PAGE_HOOK.set(Some(Box::new(move |store: &MlStore| {+ pages += 1;+ if pages == page {+ lose_index_files(store, &path);+ }+ })));+ let report = store.fill::<HookedClipSource>(false);+ PAGE_HOOK.take();+ report.unwrap()+ }++ #[test]+ fn fill_stops_when_its_index_is_lost_between_pages() {+ let (directory, store) = open();+ store.db().insert_clip_rows(&clips(1..=3500)).unwrap();++ let report = fill_losing_the_index_after_page(&store, &directory, 2);+ assert_eq!(report.outcome, FillOutcome::Superseded);+ assert_eq!(report.rows, 3000);+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ assert_eq!(meta(&store, "clip.fill"), None);++ let report = store.fill_clip_index(false).unwrap();+ assert_eq!(+ report,+ FillReport {+ outcome: FillOutcome::Completed,+ rows: 3500,+ indexed: 3500,+ skipped: 0,+ resumed: false+ }+ );+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ assert_eq!(live_count(&store, Index::Clip), 3500);+ assert!(store.contains(Index::Clip, "1").unwrap());+ assert!(store.contains(Index::Clip, "3500").unwrap());+ }++ #[test]+ fn fill_stops_when_its_index_is_lost_before_the_finishing_flush() {+ let (directory, store) = open();+ store.db().insert_clip_rows(&clips(1..=2500)).unwrap();++ let report = fill_losing_the_index_after_page(&store, &directory, 3);+ assert_eq!(report.outcome, FillOutcome::Superseded);+ assert_eq!(report.rows, 2500);+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ assert_eq!(meta(&store, "clip.fill"), None);+ assert_eq!(live_count(&store, Index::Clip), 0);+ }++ #[test]+ fn forced_fill_waits_between_pages_while_mutations_continue() {+ let (directory, store) = open();+ let peer = open_in(&directory);+ store.put_clip(&clips(1..=5000)).unwrap();+ let (paused_tx, paused_rx) = mpsc::channel();+ let (resume_tx, resume_rx) = mpsc::channel();+ let (blocked_tx, blocked_rx) = mpsc::channel();++ let (first, forced, centroid, blocked) = thread::scope(|scope| {+ let first = scope.spawn(|| {+ let mut pages = 0;+ PAGE_HOOK.set(Some(Box::new(move |_: &MlStore| {+ pages += 1;+ if pages == 3 {+ paused_tx.send(()).unwrap();+ resume_rx.recv().unwrap();+ }+ })));+ store.fill::<HookedClipSource>(false).unwrap()+ });+ paused_rx.recv().unwrap();+ let forced = scope.spawn(|| {+ let blocked = matches!(+ peer.locks.fills[Index::Clip.position()].try_lock(),+ Err(TryLockError::WouldBlock)+ );+ blocked_tx.send(blocked).unwrap();+ peer.fill_clip_index(true).unwrap()+ });+ let blocked = blocked_rx.recv().unwrap();+ let mutation = peer+ .delete_clip(&[2500])+ .and_then(|()| peer.put_clip(&clips([6000])));+ let centroid = peer.fill_cluster_centroid_index(false);+ resume_tx.send(()).unwrap();+ mutation.unwrap();+ (+ first.join().unwrap(),+ forced.join().unwrap(),+ centroid.unwrap(),+ blocked,+ )+ });++ assert!(blocked);+ assert_eq!(first.outcome, FillOutcome::Completed);+ assert_eq!(first.indexed, 5000);+ assert_eq!(forced.outcome, FillOutcome::Completed);+ assert_eq!(forced.indexed, 5000);+ assert_eq!(centroid.outcome, FillOutcome::Completed);+ assert_eq!(store.db().count_clip_rows().unwrap(), 5000);+ assert_eq!(live_count(&store, Index::Clip), 5000);+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ assert!(store.contains(Index::Clip, "6000").unwrap());+ assert!(!store.contains(Index::Clip, "2500").unwrap());+ }+}diff --git a/rust/crates/photos/src/ml_store/index.rs b/rust/crates/photos/src/ml_store/index.rsnew file mode 100644index 0000000000..8c3c86f76b--- /dev/null+++ b/rust/crates/photos/src/ml_store/index.rs@@ -0,0 +1,323 @@+use std::fs;+use std::io::ErrorKind;+use std::path::{Path, PathBuf};+use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};++use ente_vecdb::{VecDb, VecDbError};++use super::{Error, IndexResult, Result, state};+use crate::ml_db::{CLIP_EMBEDDING_DIMENSIONS, MlDb};++pub const CLUSTER_CENTROID_DIMENSIONS: usize = 192;+pub const PET_FACE_DIMENSIONS: usize = 128;+pub const PET_BODY_DIMENSIONS: usize = 192;++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Species {+ Dog,+ Cat,+}++impl Species {+ pub fn from_sql(species: i64) -> Option<Self> {+ match species {+ 0 => Some(Self::Dog),+ 1 => Some(Self::Cat),+ _ => None,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Index {+ Clip,+ ClusterCentroid,+ PetFace(Species),+ PetBody(Species),+}++impl Index {+ pub const ALL: [Self; 6] = [+ Self::Clip,+ Self::ClusterCentroid,+ Self::PetFace(Species::Dog),+ Self::PetFace(Species::Cat),+ Self::PetBody(Species::Dog),+ Self::PetBody(Species::Cat),+ ];++ pub fn dims(self) -> usize {+ match self {+ Self::Clip => CLIP_EMBEDDING_DIMENSIONS,+ Self::ClusterCentroid => CLUSTER_CENTROID_DIMENSIONS,+ Self::PetFace(_) => PET_FACE_DIMENSIONS,+ Self::PetBody(_) => PET_BODY_DIMENSIONS,+ }+ }++ pub fn name(self) -> &'static str {+ match self {+ Self::Clip => "clip",+ Self::ClusterCentroid => "cluster_centroid",+ Self::PetFace(Species::Dog) => "pet.dog_face",+ Self::PetFace(Species::Cat) => "pet.cat_face",+ Self::PetBody(Species::Dog) => "pet.dog_body",+ Self::PetBody(Species::Cat) => "pet.cat_body",+ }+ }++ pub(super) fn position(self) -> usize {+ match self {+ Self::Clip => 0,+ Self::ClusterCentroid => 1,+ Self::PetFace(Species::Dog) => 2,+ Self::PetFace(Species::Cat) => 3,+ Self::PetBody(Species::Dog) => 4,+ Self::PetBody(Species::Cat) => 5,+ }+ }++ pub(super) fn accepts(self, key: &str, vector: &[f32]) -> bool {+ if vector.is_empty() {+ return false;+ }+ if vector.len() != self.dims() {+ log::warn!(+ "skipping {} vector {key}: {} values, expected {}",+ self.name(),+ vector.len(),+ self.dims()+ );+ return false;+ }+ if let Some(position) = vector.iter().position(|value| !value.is_finite()) {+ log::warn!(+ "skipping {} vector {key}: non-finite value at {position}",+ self.name()+ );+ return false;+ }+ true+ }+}++pub(super) fn db_stem(db_path: &Path) -> Result<String> {+ db_path+ .file_stem()+ .map(|stem| stem.to_string_lossy().into_owned())+ .ok_or_else(|| Error::InvalidArgument(format!("{} has no file name", db_path.display())))+}++pub(super) struct Slot {+ index: Index,+ path: PathBuf,+ handle: RwLock<Option<VecDb>>,+}++impl Slot {+ pub(super) fn new(index: Index, index_dir: &Path, db_stem: &str) -> Self {+ Self {+ index,+ path: index_dir.join(format!("{db_stem}.vecdb.{}", index.name())),+ handle: RwLock::new(None),+ }+ }++ pub(super) fn with_open<T>(+ &self,+ db: &MlDb,+ operation: impl Fn(&VecDb) -> IndexResult<T>,+ ) -> Result<T> {+ if let Some(outcome) = self.with_open_handle(&operation) {+ return outcome;+ }+ let mut handle = self.write_handle();+ *handle = None;+ let vecdb = handle.insert(self.open(db)?);+ operation(vecdb).map_err(Into::into)+ }++ pub(super) fn release(&self) -> Result<()> {+ match self.write_handle().take() {+ Some(vecdb) => vecdb.flush().map_err(Into::into),+ None => Ok(()),+ }+ }++ pub(super) fn purge(&self) -> Result<()> {+ let mut handle = self.write_handle();+ *handle = None;+ VecDb::purge(&self.path).map_err(Into::into)+ }++ pub(super) fn with_open_handle<T>(+ &self,+ operation: &impl Fn(&VecDb) -> IndexResult<T>,+ ) -> Option<Result<T>> {+ self.read_handle()+ .as_ref()+ .and_then(|vecdb| unless_closed(operation(vecdb)))+ }++ fn open(&self, db: &MlDb) -> Result<VecDb> {+ if self.files_are_missing() {+ state::invalidate_lost_index(db, self.index, &self.path)?;+ }+ match VecDb::open(&self.path, self.index.dims(), None) {+ Err(error) if is_header_mismatch(&error) => {+ log::warn!("{}: {error}; purging the index", self.path.display());+ state::mark_stale(db, self.index)?;+ VecDb::purge(&self.path)?;+ VecDb::open(&self.path, self.index.dims(), None).map_err(Into::into)+ }+ opened => opened.map_err(Into::into),+ }+ }++ fn files_are_missing(&self) -> bool {+ matches!(fs::metadata(&self.path), Err(error) if error.kind() == ErrorKind::NotFound)+ }++ fn read_handle(&self) -> RwLockReadGuard<'_, Option<VecDb>> {+ self.handle.read().unwrap_or_else(PoisonError::into_inner)+ }++ fn write_handle(&self) -> RwLockWriteGuard<'_, Option<VecDb>> {+ self.handle.write().unwrap_or_else(PoisonError::into_inner)+ }+}++fn is_header_mismatch(error: &VecDbError) -> bool {+ matches!(+ error,+ VecDbError::DimensionMismatch { .. } | VecDbError::StorageMismatch { .. }+ )+}++fn unless_closed<T>(outcome: IndexResult<T>) -> Option<Result<T>> {+ match outcome {+ Err(VecDbError::Closed) => None,+ outcome => Some(outcome.map_err(Into::into)),+ }+}++#[cfg(test)]+mod tests {+ use ente_vecdb::{OpenCost, StorageKind, VecDb};++ use super::Index;+ use crate::db::Connection;+ use crate::ml_db::CLIP_EMBEDDING_DIMENSIONS;+ use crate::ml_store::tests::{+ DB_FILE, clips, index_path, live_count, lose_index_files, meta, one_hot, open,+ };+ use crate::ml_store::{Error, FillOutcome, FillState, MlStore};++ #[test]+ fn index_positions_follow_the_all_order() {+ for (position, index) in Index::ALL.into_iter().enumerate() {+ assert_eq!(index.position(), position, "{}", index.name());+ }+ }++ #[test]+ fn index_files_are_named_after_the_database_stem() {+ let directory = tempfile::tempdir().unwrap();+ let store = MlStore::open(+ directory.path().join("ente.ml.offline.db"),+ directory.path(),+ )+ .unwrap();+ store.fill_clip_index(false).unwrap();+ assert_eq!(+ VecDb::open_cost(&directory.path().join("ente.ml.offline.vecdb.clip")),+ OpenCost::Ready+ );+ assert!(matches!(+ MlStore::open(directory.path().join(".."), directory.path()),+ Err(Error::InvalidArgument(_))+ ));+ }++ #[test]+ fn mismatched_index_header_is_purged_and_marked_stale() {+ let (directory, store) = open();+ store.fill_clip_index(false).unwrap();+ store.release().unwrap();+ let path = index_path(&directory, Index::Clip);+ VecDb::purge(&path).unwrap();+ let foreign =+ VecDb::open(&path, CLIP_EMBEDDING_DIMENSIONS, Some(StorageKind::F32)).unwrap();+ foreign+ .add("7", &one_hot(CLIP_EMBEDDING_DIMENSIONS, 7))+ .unwrap();+ foreign.flush().unwrap();+ drop(foreign);++ assert!(!store.contains(Index::Clip, "7").unwrap());+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ assert_eq!(store.stats(Index::Clip).unwrap().storage, StorageKind::I8);+ assert_eq!(live_count(&store, Index::Clip), 0);+ }++ #[test]+ fn failed_invalidation_preserves_the_mismatched_index() {+ let (directory, store) = open();+ store.fill_clip_index(false).unwrap();+ store.release().unwrap();+ let path = index_path(&directory, Index::Clip);+ VecDb::purge(&path).unwrap();+ let foreign =+ VecDb::open(&path, CLIP_EMBEDDING_DIMENSIONS, Some(StorageKind::F32)).unwrap();+ foreign+ .add("7", &one_hot(CLIP_EMBEDDING_DIMENSIONS, 7))+ .unwrap();+ let connection = Connection::open(directory.path().join(DB_FILE)).unwrap();+ connection+ .execute_batch(+ "CREATE TRIGGER deny_meta_deletion BEFORE DELETE ON ml_store_meta+ BEGIN SELECT RAISE(FAIL, 'metadata unavailable'); END;",+ )+ .unwrap();++ assert!(matches!(+ store.contains(Index::Clip, "7"),+ Err(Error::Database(_))+ ));+ assert!(foreign.contains("7").unwrap());+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ }++ #[test]+ fn purged_handles_are_reopened_transparently() {+ let (directory, store) = open();+ store.fill_clip_index(false).unwrap();+ store.put_clip(&clips([1])).unwrap();+ VecDb::purge(&index_path(&directory, Index::Clip)).unwrap();+ assert!(!store.contains(Index::Clip, "1").unwrap());+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ store.fill_clip_index(false).unwrap();+ store.put_clip(&clips([2])).unwrap();+ assert!(store.contains(Index::Clip, "1").unwrap());+ assert!(store.contains(Index::Clip, "2").unwrap());+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ }++ #[test]+ fn lost_index_files_are_detected_by_reads() {+ let (directory, store) = open();+ store.db().insert_clip_rows(&clips(1..=3)).unwrap();+ store.fill_clip_index(false).unwrap();+ lose_index_files(&store, &index_path(&directory, Index::Clip));++ assert!(!store.contains(Index::Clip, "1").unwrap());+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ assert_eq!(meta(&store, "clip.fill"), None);+ let report = store.fill_clip_index(false).unwrap();+ assert_eq!(report.outcome, FillOutcome::Completed);+ assert_eq!(report.indexed, 3);+ assert!(store.contains(Index::Clip, "1").unwrap());+ assert_eq!(live_count(&store, Index::Clip), 3);+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ }+}diff --git a/rust/crates/photos/src/ml_store/lock.rs b/rust/crates/photos/src/ml_store/lock.rsnew file mode 100644index 0000000000..6bd83fd24a--- /dev/null+++ b/rust/crates/photos/src/ml_store/lock.rs@@ -0,0 +1,46 @@+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak};++use super::Index;++#[derive(Default)]+pub(super) struct Locks {+ pub mutations: Mutex<()>,+ pub fills: [Mutex<()>; Index::ALL.len()],+}++static REGISTRY: LazyLock<Mutex<HashMap<PathBuf, Weak<Locks>>>> =+ LazyLock::new(|| Mutex::new(HashMap::new()));++pub(super) fn for_database(db_path: &Path) -> Arc<Locks> {+ let key = db_path+ .canonicalize()+ .unwrap_or_else(|_| db_path.to_path_buf());+ let mut registry = REGISTRY.lock().unwrap_or_else(PoisonError::into_inner);+ registry.retain(|_, lock| lock.strong_count() > 0);+ if let Some(lock) = registry.get(&key).and_then(Weak::upgrade) {+ return lock;+ }+ let lock = Arc::new(Locks::default());+ registry.insert(key, Arc::downgrade(&lock));+ lock+}++#[cfg(test)]+mod tests {+ use std::sync::Arc;++ use super::for_database;+ use crate::ml_store::tests::{DB_FILE, open};++ #[test]+ fn mutation_lock_is_shared_per_canonical_database_path() {+ let (directory, _store) = open();+ let first = for_database(&directory.path().join(DB_FILE));+ let second = for_database(&directory.path().join(".").join(DB_FILE));+ assert!(Arc::ptr_eq(&first, &second));+ let other = for_database(&directory.path().join("ente.ml.offline.db"));+ assert!(!Arc::ptr_eq(&first, &other));+ }+}diff --git a/rust/crates/photos/src/ml_store/mod.rs b/rust/crates/photos/src/ml_store/mod.rsnew file mode 100644index 0000000000..f5894d180f--- /dev/null+++ b/rust/crates/photos/src/ml_store/mod.rs@@ -0,0 +1,346 @@+mod fill;+mod index;+mod lock;+mod state;+mod writes;++use std::path::Path;+use std::sync::{Arc, MutexGuard, PoisonError};++use ente_vecdb::{VecDb, VecDbError};++use crate::ml_db::MlDb;++pub use ente_vecdb::{KeyMatches, Match, SearchParams, Stats};+pub use fill::{FillOutcome, FillReport};+pub use index::{+ CLUSTER_CENTROID_DIMENSIONS, Index, PET_BODY_DIMENSIONS, PET_FACE_DIMENSIONS, Species,+};+pub use state::FillState;+pub use writes::PetEmbedding;++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error(transparent)]+ Database(#[from] crate::ml_db::Error),+ #[error(transparent)]+ Index(#[from] VecDbError),+ #[error("{0}")]+ InvalidArgument(String),+}++pub type Result<T> = std::result::Result<T, Error>;++type IndexResult<T> = std::result::Result<T, VecDbError>;++pub struct MlStore {+ db: MlDb,+ locks: Arc<lock::Locks>,+ indexes: [index::Slot; Index::ALL.len()],+}++impl MlStore {+ pub fn open(db_path: impl AsRef<Path>, index_dir: impl AsRef<Path>) -> Result<Self> {+ let db_path = db_path.as_ref();+ let db_stem = index::db_stem(db_path)?;+ let db = MlDb::open(db_path)?;+ Ok(Self {+ db,+ locks: lock::for_database(db_path),+ indexes: Index::ALL.map(|index| index::Slot::new(index, index_dir.as_ref(), &db_stem)),+ })+ }++ pub fn db(&self) -> &MlDb {+ &self.db+ }++ pub fn release(&self) -> Result<()> {+ let mut outcome = Ok(());+ for slot in &self.indexes {+ outcome = outcome.and(slot.release());+ }+ outcome+ }++ pub fn fill_state(&self, index: Index) -> Result<FillState> {+ state::read(&self.db, index)+ }++ pub fn search(&self, index: Index, query: &[f32], params: &SearchParams) -> Result<Vec<Match>> {+ self.read_index(index, |vecdb| vecdb.search(query, params))+ }++ pub fn bulk_search(+ &self,+ index: Index,+ queries: &[Vec<f32>],+ params: &SearchParams,+ ) -> Result<Vec<Vec<Match>>> {+ self.read_index(index, |vecdb| vecdb.bulk_search(queries, params))+ }++ pub fn bulk_search_stored(+ &self,+ index: Index,+ keys: &[String],+ count: usize,+ max_distance: Option<f32>,+ exact: bool,+ restrict_to_input: bool,+ ) -> Result<Vec<KeyMatches>> {+ self.read_index(index, |vecdb| {+ vecdb.bulk_search_stored(keys, count, max_distance, exact, restrict_to_input)+ })+ }++ pub fn get_vector(&self, index: Index, key: &str) -> Result<Option<Vec<f32>>> {+ self.read_index(index, |vecdb| vecdb.get(key))+ }++ pub fn contains(&self, index: Index, key: &str) -> Result<bool> {+ self.read_index(index, |vecdb| vecdb.contains(key))+ }++ pub fn stats(&self, index: Index) -> Result<Stats> {+ self.read_index(index, VecDb::stats)+ }++ fn lock_mutations(&self) -> MutexGuard<'_, ()> {+ self.locks+ .mutations+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ }++ fn lock_fill(&self, index: Index) -> MutexGuard<'_, ()> {+ self.locks.fills[index.position()]+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ }++ fn with_index<T>(+ &self,+ index: Index,+ operation: impl Fn(&VecDb) -> IndexResult<T>,+ ) -> Result<T> {+ self.indexes[index.position()].with_open(&self.db, operation)+ }++ fn read_index<T>(+ &self,+ index: Index,+ operation: impl Fn(&VecDb) -> IndexResult<T>,+ ) -> Result<T> {+ let slot = &self.indexes[index.position()];+ if let Some(outcome) = slot.with_open_handle(&operation) {+ return outcome;+ }+ let _mutations = self.lock_mutations();+ slot.with_open(&self.db, operation)+ }+}++#[cfg(test)]+mod tests {+ use std::fs;+ use std::path::{Path, PathBuf};++ use ente_vecdb::{OpenCost, SearchParams, VecDb};+ use tempfile::TempDir;++ use super::{FillOutcome, FillReport, FillState, Index, MlStore, PetEmbedding, Species};+ use crate::ml_db::vector_encoding::encode_evector;+ use crate::ml_db::{CLIP_EMBEDDING_DIMENSIONS, ClipEmbedding, ClusterSummary};++ pub(super) const DB_FILE: &str = "ente.ml.db";++ pub(super) fn open() -> (TempDir, MlStore) {+ let directory = tempfile::tempdir().unwrap();+ let store = open_in(&directory);+ (directory, store)+ }++ pub(super) fn open_in(directory: &TempDir) -> MlStore {+ MlStore::open(directory.path().join(DB_FILE), directory.path()).unwrap()+ }++ pub(super) fn open_with_unusable_index_dir() -> (TempDir, MlStore) {+ let directory = tempfile::tempdir().unwrap();+ let blocker = directory.path().join("indexes");+ fs::write(&blocker, b"not a directory").unwrap();+ let store = MlStore::open(directory.path().join(DB_FILE), &blocker).unwrap();+ (directory, store)+ }++ pub(super) fn index_path(directory: &TempDir, index: Index) -> PathBuf {+ directory+ .path()+ .join(format!("ente.ml.vecdb.{}", index.name()))+ }++ pub(super) fn one_hot(dims: usize, hot: usize) -> Vec<f32> {+ let mut vector = vec![0.0; dims];+ vector[hot % dims] = 1.0;+ vector+ }++ pub(super) fn clip(file_id: i64) -> ClipEmbedding {+ ClipEmbedding {+ file_id,+ embedding: one_hot(CLIP_EMBEDDING_DIMENSIONS, file_id as usize)+ .into_iter()+ .map(f64::from)+ .collect(),+ version: 1,+ }+ }++ pub(super) fn clips(file_ids: impl IntoIterator<Item = i64>) -> Vec<ClipEmbedding> {+ file_ids.into_iter().map(clip).collect()+ }++ pub(super) fn centroid(cluster_id: &str, hot: usize) -> (String, ClusterSummary) {+ let values: Vec<f64> = one_hot(Index::ClusterCentroid.dims(), hot)+ .into_iter()+ .map(f64::from)+ .collect();+ let summary = ClusterSummary {+ avg: encode_evector(&values),+ count: 1,+ };+ (cluster_id.to_string(), summary)+ }++ pub(super) fn pet(id: &str, species: Species, hot: usize, dims: usize) -> PetEmbedding {+ PetEmbedding {+ id: id.to_string(),+ species,+ embedding: one_hot(dims, hot),+ }+ }++ pub(super) fn nearest(store: &MlStore, index: Index, query: &[f32]) -> String {+ let params = SearchParams {+ limit: Some(1),+ ..SearchParams::default()+ };+ store.search(index, query, ¶ms).unwrap()[0].key.clone()+ }++ pub(super) fn live_count(store: &MlStore, index: Index) -> usize {+ store.stats(index).unwrap().live_count+ }++ pub(super) fn meta(store: &MlStore, key: &str) -> Option<String> {+ store.db().get_meta(key).unwrap()+ }++ pub(super) fn hot_position(vector: &[f32]) -> Option<usize> {+ vector.iter().position(|value| *value > 0.99)+ }++ pub(super) fn empty(outcome: FillOutcome) -> FillReport {+ FillReport {+ outcome,+ rows: 0,+ indexed: 0,+ skipped: 0,+ resumed: false,+ }+ }++ pub(super) fn lose_index_files(store: &MlStore, path: &Path) {+ store.release().unwrap();+ VecDb::purge(path).unwrap();+ }++ #[test]+ fn open_creates_no_index_files_and_fillable_indexes_start_stale() {+ let (directory, store) = open();+ let names: Vec<String> = fs::read_dir(directory.path())+ .unwrap()+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ assert!(+ names.iter().all(|name| name.starts_with(DB_FILE)),+ "{names:?}"+ );+ for index in Index::ALL {+ assert_eq!(+ VecDb::open_cost(&index_path(&directory, index)),+ OpenCost::Absent+ );+ }+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ assert_eq!(+ store.fill_state(Index::ClusterCentroid).unwrap(),+ FillState::Stale+ );+ assert_eq!(+ store.fill_state(Index::PetFace(Species::Dog)).unwrap(),+ FillState::Filled+ );+ assert_eq!(+ store.fill_state(Index::PetBody(Species::Cat)).unwrap(),+ FillState::Filled+ );+ }++ #[test]+ fn release_flushes_and_reopened_stores_keep_data() {+ let (directory, store) = open();+ store.fill_clip_index(false).unwrap();+ store.put_clip(&clips([1, 2])).unwrap();+ store.release().unwrap();+ assert_eq!(+ VecDb::open_cost(&index_path(&directory, Index::Clip)),+ OpenCost::Ready+ );+ assert!(store.contains(Index::Clip, "1").unwrap());+ store.release().unwrap();+ drop(store);++ let reopened = open_in(&directory);+ assert_eq!(reopened.fill_state(Index::Clip).unwrap(), FillState::Filled);+ assert!(reopened.contains(Index::Clip, "2").unwrap());+ assert_eq!(live_count(&reopened, Index::Clip), 2);+ }++ #[test]+ fn getters_reopen_after_another_store_clears_and_repopulates() {+ let (directory, writer) = open();+ let contains_reader = open_in(&directory);+ let vector_reader = open_in(&directory);+ writer.fill_clip_index(false).unwrap();+ writer.put_clip(&clips([1])).unwrap();+ assert!(contains_reader.contains(Index::Clip, "1").unwrap());+ assert!(+ vector_reader+ .get_vector(Index::Clip, "1")+ .unwrap()+ .is_some()+ );++ writer.clear_all().unwrap();+ writer.put_clip(&clips([2])).unwrap();+ writer.fill_clip_index(false).unwrap();++ assert!(contains_reader.contains(Index::Clip, "2").unwrap());+ let vector = vector_reader.get_vector(Index::Clip, "2").unwrap().unwrap();+ assert_eq!(hot_position(&vector), Some(2));+ assert!(!contains_reader.contains(Index::Clip, "1").unwrap());+ assert!(+ vector_reader+ .get_vector(Index::Clip, "1")+ .unwrap()+ .is_none()+ );+ }++ #[test]+ fn ml_store_is_send_and_sync() {+ fn assert_send_sync<T: Send + Sync>() {}+ assert_send_sync::<MlStore>();+ }+}diff --git a/rust/crates/photos/src/ml_store/state.rs b/rust/crates/photos/src/ml_store/state.rsnew file mode 100644index 0000000000..b526e79125--- /dev/null+++ b/rust/crates/photos/src/ml_store/state.rs@@ -0,0 +1,90 @@+use std::path::Path;++use super::{Index, Result};+use crate::ml_db::MlDb;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FillState {+ Filled,+ Filling,+ Stale,+}++const FILLED: &str = "filled";+const FILLING: &str = "filling";++struct Keys {+ fill: &'static str,+ cursor: &'static str,+}++fn keys(index: Index) -> Option<Keys> {+ match index {+ Index::Clip => Some(Keys {+ fill: "clip.fill",+ cursor: "clip.cursor",+ }),+ Index::ClusterCentroid => Some(Keys {+ fill: "cluster_centroid.fill",+ cursor: "cluster_centroid.cursor",+ }),+ Index::PetFace(_) | Index::PetBody(_) => None,+ }+}++pub(super) fn read(db: &MlDb, index: Index) -> Result<FillState> {+ let Some(keys) = keys(index) else {+ return Ok(FillState::Filled);+ };+ Ok(match db.get_meta(keys.fill)?.as_deref() {+ Some(FILLED) => FillState::Filled,+ Some(FILLING) => FillState::Filling,+ _ => FillState::Stale,+ })+}++pub(super) fn cursor(db: &MlDb, index: Index) -> Result<Option<String>> {+ match keys(index) {+ Some(keys) => Ok(db.get_meta(keys.cursor)?),+ None => Ok(None),+ }+}++pub(super) fn set_cursor(db: &MlDb, index: Index, key: &str) -> Result<()> {+ if let Some(keys) = keys(index) {+ db.set_meta(keys.cursor, key)?;+ }+ Ok(())+}++pub(super) fn mark_filling(db: &MlDb, index: Index) -> Result<()> {+ if let Some(keys) = keys(index) {+ db.delete_meta(keys.cursor)?;+ db.set_meta(keys.fill, FILLING)?;+ }+ Ok(())+}++pub(super) fn mark_filled(db: &MlDb, index: Index) -> Result<()> {+ if let Some(keys) = keys(index) {+ db.set_meta(keys.fill, FILLED)?;+ db.delete_meta(keys.cursor)?;+ }+ Ok(())+}++pub(super) fn mark_stale(db: &MlDb, index: Index) -> Result<()> {+ if let Some(keys) = keys(index) {+ db.delete_meta(keys.fill)?;+ db.delete_meta(keys.cursor)?;+ }+ Ok(())+}++pub(super) fn invalidate_lost_index(db: &MlDb, index: Index, path: &Path) -> Result<()> {+ if keys(index).is_none() || read(db, index)? == FillState::Stale {+ return Ok(());+ }+ log::warn!("{}: index files missing, refill required", path.display());+ mark_stale(db, index)+}diff --git a/rust/crates/photos/src/ml_store/writes.rs b/rust/crates/photos/src/ml_store/writes.rsnew file mode 100644index 0000000000..5720c93316--- /dev/null+++ b/rust/crates/photos/src/ml_store/writes.rs@@ -0,0 +1,542 @@+use std::collections::HashMap;++use ente_vecdb::VecDb;++use super::fill::decode_centroid;+use super::{Error, FillState, Index, IndexResult, MlStore, Result, Species, state};+use crate::ml_db::{ClipEmbedding, ClusterSummary, PetRowsForFiles};++#[derive(Clone, Debug, PartialEq)]+pub struct PetEmbedding {+ pub id: String,+ pub species: Species,+ pub embedding: Vec<f32>,+}++type Vectors = (Vec<String>, Vec<Vec<f32>>);++impl MlStore {+ pub fn put_clip(&self, embeddings: &[ClipEmbedding]) -> Result<()> {+ if embeddings.is_empty() {+ return Ok(());+ }+ let _mutations = self.lock_mutations();+ self.db.insert_clip_rows(embeddings)?;+ if self.index_is_stale(Index::Clip)? {+ return Ok(());+ }+ let (keys, vectors) = clip_vectors(embeddings);+ self.index_write(Index::Clip, |vecdb| vecdb.bulk_add(&keys, &vectors))+ }++ pub fn delete_clip(&self, file_ids: &[i64]) -> Result<()> {+ if file_ids.is_empty() {+ return Ok(());+ }+ let _mutations = self.lock_mutations();+ self.db.delete_clip_rows(file_ids)?;+ if self.index_is_stale(Index::Clip)? {+ return Ok(());+ }+ let keys: Vec<String> = file_ids.iter().map(ToString::to_string).collect();+ self.index_write(Index::Clip, |vecdb| vecdb.bulk_remove(&keys))+ }++ pub fn delete_all_clip(&self) -> Result<()> {+ let _mutations = self.lock_mutations();+ self.db.delete_all_clip_rows()?;+ self.reset_index(Index::Clip)+ }++ pub fn cluster_summary_update(&self, summary: &HashMap<String, ClusterSummary>) -> Result<()> {+ if summary.is_empty() {+ return Ok(());+ }+ let _mutations = self.lock_mutations();+ self.db.upsert_cluster_summary_rows(summary)?;+ if self.index_is_stale(Index::ClusterCentroid)? {+ return Ok(());+ }+ let (keys, vectors) = centroid_vectors(summary);+ self.index_write(Index::ClusterCentroid, |vecdb| {+ vecdb.bulk_add(&keys, &vectors)+ })+ }++ pub fn delete_cluster_summary(&self, cluster_id: &str) -> Result<()> {+ let _mutations = self.lock_mutations();+ self.db.delete_cluster_summary_row(cluster_id)?;+ if self.index_is_stale(Index::ClusterCentroid)? {+ return Ok(());+ }+ self.index_write(Index::ClusterCentroid, |vecdb| vecdb.remove(cluster_id))+ }++ pub fn drop_clusters_and_person_table(&self, faces: bool) -> Result<()> {+ let _mutations = self.lock_mutations();+ self.db.reset_cluster_tables(faces)?;+ self.reset_index(Index::ClusterCentroid)+ }++ pub fn store_pet_face_embeddings(&self, embeddings: &[PetEmbedding]) -> Result<()> {+ self.store_pet_embeddings(embeddings, Index::PetFace)+ }++ pub fn store_pet_body_embeddings(&self, embeddings: &[PetEmbedding]) -> Result<()> {+ self.store_pet_embeddings(embeddings, Index::PetBody)+ }++ pub fn delete_pet_data_for_files(&self, file_ids: &[i64]) -> Result<()> {+ if file_ids.is_empty() {+ return Ok(());+ }+ let _mutations = self.lock_mutations();+ let rows = self.db.get_pet_rows_for_files(file_ids)?;+ for (index, keys) in pet_keys(&rows) {+ if let Err(error) = self.with_index(index, |vecdb| vecdb.bulk_remove(&keys)) {+ log::warn!(+ "failed to remove {} vectors from {}: {error}",+ keys.len(),+ index.name()+ );+ }+ }+ let face_ids: Vec<String> = rows.faces.into_iter().map(|row| row.pet_face_id).collect();+ let body_ids: Vec<String> = rows.bodies.into_iter().map(|row| row.pet_body_id).collect();+ self.db+ .delete_pet_rows_for_files(file_ids, &face_ids, &body_ids)?;+ Ok(())+ }++ pub fn clear_all(&self) -> Result<()> {+ let _mutations = self.lock_mutations();+ self.db.clear_non_pet_tables()?;+ self.db.clear_pet_tables()?;+ self.db.clear_meta()?;+ for slot in &self.indexes {+ slot.purge()?;+ }+ Ok(())+ }++ fn store_pet_embeddings(+ &self,+ embeddings: &[PetEmbedding],+ index_of: fn(Species) -> Index,+ ) -> Result<()> {+ if embeddings.is_empty() {+ return Ok(());+ }+ let _mutations = self.lock_mutations();+ for (index, (keys, vectors)) in pet_vectors(embeddings, index_of) {+ self.index_write(index, |vecdb| vecdb.bulk_add(&keys, &vectors))?;+ }+ Ok(())+ }++ fn index_is_stale(&self, index: Index) -> Result<bool> {+ Ok(state::read(&self.db, index)? == FillState::Stale)+ }++ fn index_write<T>(+ &self,+ index: Index,+ operation: impl Fn(&VecDb) -> IndexResult<T>,+ ) -> Result<()> {+ let outcome = self.with_index(index, operation);+ if let Err(Error::Index(_)) = &outcome {+ state::mark_stale(&self.db, index)?;+ }+ outcome.map(drop)+ }++ fn reset_index(&self, index: Index) -> Result<()> {+ self.index_write(index, VecDb::reset)?;+ state::mark_filled(&self.db, index)+ }+}++fn clip_vectors(embeddings: &[ClipEmbedding]) -> Vectors {+ embeddings+ .iter()+ .filter_map(|embedding| {+ let key = embedding.file_id.to_string();+ let vector: Vec<f32> = embedding+ .embedding+ .iter()+ .map(|value| *value as f32)+ .collect();+ Index::Clip.accepts(&key, &vector).then_some((key, vector))+ })+ .unzip()+}++fn centroid_vectors(summary: &HashMap<String, ClusterSummary>) -> Vectors {+ summary+ .iter()+ .filter_map(|(cluster_id, summary)| {+ decode_centroid(cluster_id, &summary.avg).map(|vector| (cluster_id.clone(), vector))+ })+ .unzip()+}++fn pet_vectors(+ embeddings: &[PetEmbedding],+ index_of: fn(Species) -> Index,+) -> HashMap<Index, Vectors> {+ let mut grouped: HashMap<Index, Vectors> = HashMap::new();+ for embedding in embeddings {+ let index = index_of(embedding.species);+ if !index.accepts(&embedding.id, &embedding.embedding) {+ continue;+ }+ let (keys, vectors) = grouped.entry(index).or_default();+ keys.push(embedding.id.clone());+ vectors.push(embedding.embedding.clone());+ }+ grouped+}++fn pet_keys(rows: &PetRowsForFiles) -> HashMap<Index, Vec<String>> {+ let faces = rows.faces.iter().filter_map(|row| {+ Species::from_sql(row.species).map(|species| (Index::PetFace(species), &row.pet_face_id))+ });+ let bodies = rows.bodies.iter().filter_map(|row| {+ Species::from_sql(row.species).map(|species| (Index::PetBody(species), &row.pet_body_id))+ });+ let mut grouped: HashMap<Index, Vec<String>> = HashMap::new();+ for (index, id) in faces.chain(bodies) {+ grouped.entry(index).or_default().push(id.clone());+ }+ grouped+}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use ente_vecdb::{OpenCost, SearchParams, VecDb, VecDbError};++ use crate::ml_db::tests::{deny_cluster_summary_inserts_after, seed_pet_rows};+ use crate::ml_db::vector_encoding::encode_evector;+ use crate::ml_db::{CLIP_EMBEDDING_DIMENSIONS, ClusterSummary};+ use crate::ml_store::tests::{+ DB_FILE, centroid, clips, empty, hot_position, index_path, live_count, meta, nearest,+ one_hot, open, open_with_unusable_index_dir, pet,+ };+ use crate::ml_store::{Error, FillOutcome, FillState, Index, Species};++ #[test]+ fn put_clip_round_trips_through_sql_and_index() {+ let (_directory, store) = open();+ assert_eq!(+ store.fill_clip_index(false).unwrap(),+ empty(FillOutcome::Completed)+ );+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ store.put_clip(&[]).unwrap();+ store.put_clip(&clips([1, 2, 3])).unwrap();+ assert_eq!(store.db().count_clip_rows().unwrap(), 3);+ assert_eq!(live_count(&store, Index::Clip), 3);+ assert!(store.contains(Index::Clip, "2").unwrap());+ assert!(!store.contains(Index::Clip, "4").unwrap());+ let stored = store.get_vector(Index::Clip, "2").unwrap().unwrap();+ assert_eq!(stored.len(), CLIP_EMBEDDING_DIMENSIONS);+ assert_eq!(hot_position(&stored), Some(2));+ assert_eq!(store.get_vector(Index::Clip, "4").unwrap(), None);+ assert_eq!(+ nearest(&store, Index::Clip, &one_hot(CLIP_EMBEDDING_DIMENSIONS, 3)),+ "3"+ );++ let params = SearchParams {+ limit: Some(1),+ ..SearchParams::default()+ };+ let queries = [+ one_hot(CLIP_EMBEDDING_DIMENSIONS, 1),+ one_hot(CLIP_EMBEDDING_DIMENSIONS, 2),+ ];+ let found = store.bulk_search(Index::Clip, &queries, ¶ms).unwrap();+ assert_eq!(found[0][0].key, "1");+ assert_eq!(found[1][0].key, "2");+ let stored_matches = store+ .bulk_search_stored(+ Index::Clip,+ &["1".to_string(), "9".to_string()],+ 2,+ None,+ true,+ false,+ )+ .unwrap();+ assert_eq!(stored_matches.len(), 1);+ assert_eq!(stored_matches[0].key, "1");+ let neighbours: Vec<&str> = stored_matches[0]+ .matches+ .iter()+ .map(|found| found.key.as_str())+ .collect();+ assert_eq!(neighbours.len(), 2);+ assert!(neighbours.contains(&"2") && neighbours.contains(&"3"));+ assert!(matches!(+ store.search(Index::Clip, &[1.0; 3], ¶ms),+ Err(Error::Index(VecDbError::DimensionMismatch { .. }))+ ));+ }++ #[test]+ fn delete_clip_removes_sql_rows_and_vectors() {+ let (_directory, store) = open();+ store.fill_clip_index(false).unwrap();+ store.put_clip(&clips([1, 2, 3])).unwrap();+ store.delete_clip(&[]).unwrap();+ store.delete_clip(&[1, 3, 9]).unwrap();+ assert_eq!(+ store.db().clip_indexed_file_with_version().unwrap(),+ HashMap::from([(2, 1)])+ );+ assert!(!store.contains(Index::Clip, "1").unwrap());+ assert!(store.contains(Index::Clip, "2").unwrap());+ assert_eq!(live_count(&store, Index::Clip), 1);+ }++ #[test]+ fn non_finite_clip_vectors_stay_out_of_the_index() {+ let (_directory, store) = open();+ store.fill_clip_index(false).unwrap();+ let mut rows = clips([1, 2]);+ rows[0].embedding[0] = f64::NAN;+ rows[1].embedding[0] = f64::MAX;+ store.put_clip(&rows).unwrap();+ assert_eq!(store.db().count_clip_rows().unwrap(), 2);+ assert!(!store.contains(Index::Clip, "1").unwrap());+ assert!(!store.contains(Index::Clip, "2").unwrap());+ assert_eq!(live_count(&store, Index::Clip), 0);+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ }++ #[test]+ fn stale_indexes_are_skipped_by_writes() {+ let (_directory, store) = open();+ store.put_clip(&clips([1, 2])).unwrap();+ store.delete_clip(&[2]).unwrap();+ store+ .cluster_summary_update(&HashMap::from([centroid("c1", 1), centroid("c2", 2)]))+ .unwrap();+ store.delete_cluster_summary("c2").unwrap();+ assert_eq!(store.db().count_clip_rows().unwrap(), 1);+ assert_eq!(store.db().count_cluster_summaries().unwrap(), 1);+ assert!(!store.contains(Index::Clip, "1").unwrap());+ assert!(!store.contains(Index::ClusterCentroid, "c1").unwrap());+ assert_eq!(live_count(&store, Index::Clip), 0);+ assert_eq!(live_count(&store, Index::ClusterCentroid), 0);+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ assert_eq!(+ store.fill_state(Index::ClusterCentroid).unwrap(),+ FillState::Stale+ );+ }++ #[test]+ fn cluster_summary_writes_go_through_while_filling() {+ let (_directory, store) = open();+ store.fill_cluster_centroid_index(false).unwrap();+ store+ .db()+ .set_meta("cluster_centroid.fill", "filling")+ .unwrap();+ let mut summaries = HashMap::from([centroid("c1", 1)]);+ summaries.insert(+ "short".to_string(),+ ClusterSummary {+ avg: encode_evector(&[1.0, 2.0]),+ count: 1,+ },+ );+ store.cluster_summary_update(&summaries).unwrap();+ store.cluster_summary_update(&HashMap::new()).unwrap();+ assert_eq!(store.db().count_cluster_summaries().unwrap(), 2);+ assert!(store.contains(Index::ClusterCentroid, "c1").unwrap());+ assert!(!store.contains(Index::ClusterCentroid, "short").unwrap());+ assert_eq!(+ store.fill_state(Index::ClusterCentroid).unwrap(),+ FillState::Filling+ );++ store.delete_cluster_summary("c1").unwrap();+ assert_eq!(store.db().count_cluster_summaries().unwrap(), 1);+ assert!(!store.contains(Index::ClusterCentroid, "c1").unwrap());+ assert_eq!(+ store.fill_state(Index::ClusterCentroid).unwrap(),+ FillState::Filling+ );+ }++ #[test]+ fn failed_cluster_summary_upserts_leave_sql_and_index_untouched() {+ let (directory, store) = open();+ store.fill_cluster_centroid_index(false).unwrap();+ let summaries: HashMap<String, ClusterSummary> = (0..=400)+ .map(|hot| centroid(&format!("c{hot:04}"), hot))+ .collect();+ deny_cluster_summary_inserts_after(&directory.path().join(DB_FILE), 400);++ assert!(matches!(+ store.cluster_summary_update(&summaries),+ Err(Error::Database(_))+ ));+ assert_eq!(store.db().count_cluster_summaries().unwrap(), 0);+ assert_eq!(live_count(&store, Index::ClusterCentroid), 0);+ assert_eq!(+ store.fill_state(Index::ClusterCentroid).unwrap(),+ FillState::Filled+ );+ }++ #[test]+ fn delete_all_clip_and_drop_clusters_leave_filled_empty_indexes() {+ let (_directory, store) = open();+ store.put_clip(&clips([1])).unwrap();+ store+ .db()+ .upsert_cluster_summary_rows(&HashMap::from([centroid("c1", 1)]))+ .unwrap();+ store.delete_all_clip().unwrap();+ store.drop_clusters_and_person_table(false).unwrap();+ for index in [Index::Clip, Index::ClusterCentroid] {+ assert_eq!(store.fill_state(index).unwrap(), FillState::Filled);+ assert_eq!(live_count(&store, index), 0);+ }+ assert_eq!(store.db().count_clip_rows().unwrap(), 0);+ assert_eq!(store.db().count_cluster_summaries().unwrap(), 0);++ store.put_clip(&clips([2])).unwrap();+ store+ .cluster_summary_update(&HashMap::from([centroid("c2", 2)]))+ .unwrap();+ assert_eq!(live_count(&store, Index::Clip), 1);+ assert_eq!(live_count(&store, Index::ClusterCentroid), 1);+ store.delete_all_clip().unwrap();+ store.drop_clusters_and_person_table(true).unwrap();+ for index in [Index::Clip, Index::ClusterCentroid] {+ assert_eq!(store.fill_state(index).unwrap(), FillState::Filled);+ assert_eq!(live_count(&store, index), 0);+ }+ assert_eq!(store.db().count_clip_rows().unwrap(), 0);+ assert_eq!(store.db().count_cluster_summaries().unwrap(), 0);+ }++ #[test]+ fn pet_embeddings_are_stored_searched_and_deleted_per_species() {+ let (_directory, store) = open();+ seed_pet_rows(store.db());+ let face_dims = Index::PetFace(Species::Dog).dims();+ let body_dims = Index::PetBody(Species::Dog).dims();+ store+ .store_pet_face_embeddings(&[+ pet("1_pet_0", Species::Dog, 1, face_dims),+ pet("2_pet_0", Species::Cat, 2, face_dims),+ pet("bad", Species::Dog, 3, face_dims / 2),+ ])+ .unwrap();+ store+ .store_pet_body_embeddings(&[pet("1_body_0", Species::Dog, 1, body_dims)])+ .unwrap();+ store.store_pet_body_embeddings(&[]).unwrap();+ assert_eq!(+ nearest(&store, Index::PetFace(Species::Dog), &one_hot(face_dims, 1)),+ "1_pet_0"+ );+ assert!(+ store+ .contains(Index::PetFace(Species::Cat), "2_pet_0")+ .unwrap()+ );+ assert!(!store.contains(Index::PetFace(Species::Dog), "bad").unwrap());+ assert_eq!(live_count(&store, Index::PetFace(Species::Dog)), 1);+ assert!(+ store+ .contains(Index::PetBody(Species::Dog), "1_body_0")+ .unwrap()+ );++ store.delete_pet_data_for_files(&[]).unwrap();+ store.delete_pet_data_for_files(&[1]).unwrap();+ assert!(+ !store+ .contains(Index::PetFace(Species::Dog), "1_pet_0")+ .unwrap()+ );+ assert!(+ !store+ .contains(Index::PetBody(Species::Dog), "1_body_0")+ .unwrap()+ );+ assert!(+ store+ .contains(Index::PetFace(Species::Cat), "2_pet_0")+ .unwrap()+ );+ assert!(store.db().get_pet_faces_for_file_id(1).unwrap().is_empty());+ assert!(store.db().get_pet_bodies_for_file_id(1).unwrap().is_empty());+ assert_eq!(store.db().get_pet_indexed_file_count(1).unwrap(), 1);+ }++ #[test]+ fn clear_all_removes_rows_meta_and_index_files() {+ let (directory, store) = open();+ store.fill_clip_index(false).unwrap();+ store.fill_cluster_centroid_index(false).unwrap();+ store.put_clip(&clips([1])).unwrap();+ store+ .cluster_summary_update(&HashMap::from([centroid("c1", 1)]))+ .unwrap();+ store+ .store_pet_face_embeddings(&[pet(+ "p",+ Species::Cat,+ 1,+ Index::PetFace(Species::Cat).dims(),+ )])+ .unwrap();++ store.clear_all().unwrap();+ for index in Index::ALL {+ assert_eq!(+ VecDb::open_cost(&index_path(&directory, index)),+ OpenCost::Absent,+ "{}",+ index.name()+ );+ }+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ assert_eq!(+ store.fill_state(Index::ClusterCentroid).unwrap(),+ FillState::Stale+ );+ assert_eq!(meta(&store, "clip.fill"), None);+ assert_eq!(meta(&store, "cluster_centroid.fill"), None);+ assert_eq!(store.db().count_clip_rows().unwrap(), 0);+ assert_eq!(store.db().count_cluster_summaries().unwrap(), 0);+ assert!(!store.contains(Index::Clip, "1").unwrap());+ assert!(!store.contains(Index::PetFace(Species::Cat), "p").unwrap());+ assert_eq!(live_count(&store, Index::Clip), 0);+ assert_eq!(+ store.fill_clip_index(false).unwrap(),+ empty(FillOutcome::Completed)+ );+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Filled);+ }++ #[test]+ fn index_write_failure_marks_the_index_stale() {+ let (_directory, store) = open_with_unusable_index_dir();+ store.db().set_meta("clip.fill", "filled").unwrap();+ assert!(matches!(store.put_clip(&clips([1])), Err(Error::Index(_))));+ assert_eq!(store.db().count_clip_rows().unwrap(), 1);+ assert_eq!(store.fill_state(Index::Clip).unwrap(), FillState::Stale);+ store.put_clip(&clips([2])).unwrap();+ assert_eq!(store.db().count_clip_rows().unwrap(), 2);+ }+}