π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Organize Rust ML database queries by domain
laurenspriem013ec3684811
diff --git a/rust/crates/photos/src/db.rs b/rust/crates/photos/src/db.rsindex dbb99444eb..29e642bd7e 100644--- a/rust/crates/photos/src/db.rs+++ b/rust/crates/photos/src/db.rs@@ -231,7 +231,7 @@ impl Database {})}- pub fn write_batch<P: Params>(+ pub fn write_batch_atomic<P: Params>(&self,sql: &str,parameter_sets: impl IntoIterator<Item = P>,@@ -245,7 +245,7 @@ impl Database {})}- pub fn write_in_batches<P: Params>(+ pub fn write_batches_committing_each<P: Params>(&self,sql: &str,batch_size: usize,@@ -482,7 +482,7 @@ mod tests {fn failed_batch_rolls_back_and_writer_recovers() {let (_directory, db) = open();assert!(- db.write_batch("INSERT INTO items (id) VALUES (?)", [[1], [2], [1]])+ db.write_batch_atomic("INSERT INTO items (id) VALUES (?)", [[1], [2], [1]]).is_err());assert_eq!(@@ -679,7 +679,7 @@ mod tests {fn chunked_delete_handles_empty_lists_and_rolls_back_on_failure() {let (_directory, db) = open();let ids: Vec<i64> = (0..10_001).collect();- db.write_batch(+ db.write_batch_atomic("INSERT INTO items (id) VALUES (?)",ids.iter().map(|id| [id]),)@@ -717,14 +717,14 @@ mod tests {#[test]fn batched_writes_commit_each_completed_batch() {let (_directory, db) = open();- db.write_in_batches(+ db.write_batches_committing_each("INSERT INTO missing_table VALUES (?)",2,Vec::<[i64; 1]>::new(),).unwrap();assert!(- db.write_in_batches(+ db.write_batches_committing_each("INSERT INTO items (id) VALUES (?)",2,[[1], [2], [3], [4], [1]]@@ -737,7 +737,7 @@ mod tests {[1, 2, 3, 4]);assert!(- db.write_in_batches(+ db.write_batches_committing_each("INSERT INTO items (id) VALUES (?)",2,[[5], [6], [7], [5], [8]]@@ -749,7 +749,7 @@ mod tests {.unwrap(),[1, 2, 3, 4, 5, 6]);- db.write_in_batches("INSERT INTO items (id) VALUES (?)", 2, [[7], [8], [9]])+ db.write_batches_committing_each("INSERT INTO items (id) VALUES (?)", 2, [[7], [8], [9]]).unwrap();assert_eq!(db.read_column::<Vec<i64>, _, _>("SELECT id FROM items ORDER BY id", ())@@ -761,7 +761,7 @@ mod tests {#[test]fn chunked_reads_query_each_chunk_in_order() {let (_directory, db) = open();- db.write_batch("INSERT INTO items (id) VALUES (?)", (1..=7).map(|id| [id]))+ db.write_batch_atomic("INSERT INTO items (id) VALUES (?)", (1..=7).map(|id| [id])).unwrap();let ids: Vec<i64> = (1..=7).collect();let by_chunk: Vec<i64> = db@@ -806,7 +806,7 @@ mod tests {#[test]fn grouped_reads_collect_values_per_key() {let (_directory, db) = open();- db.write_batch("INSERT INTO items (id) VALUES (?)", (1..=5).map(|id| [id]))+ db.write_batch_atomic("INSERT INTO items (id) VALUES (?)", (1..=5).map(|id| [id])).unwrap();let by_parity: HashMap<i64, Vec<i64>> = db.read_grouped("SELECT id % 2, id FROM items ORDER BY id", ())diff --git a/rust/crates/photos/src/ml_db/mod.rs b/rust/crates/photos/src/ml_db/mod.rsindex 113643a113..7a65c67353 100644--- a/rust/crates/photos/src/ml_db/mod.rs+++ b/rust/crates/photos/src/ml_db/mod.rs@@ -1,27 +1,25 @@-mod caches;-mod clusters;-mod faces;-mod filedata;-mod persons;-mod pets;mod queries;mod schema;mod vector_encoding;-use std::collections::{HashMap, HashSet};use std::path::Path;use crate::db::{Database, OpenOptions};-pub use filedata::{FdStatus, PreviewInfo};-pub use persons::PersonToClusterIdToFaceIds;-pub use queries::{+pub use queries::clip::{CLIP_EMBEDDING_BYTES_LENGTH, CLIP_EMBEDDING_DIMENSIONS, CLIP_ML_VERSION, ClipEmbedding,- ClipRow, ClusterCentroidRow, ClusterSummary, EmbeddingVector, FACE_ML_VERSION,- FaceDbInfoForClustering, FaceRow, FaceWithoutEmbedding, LAPLACIAN_HARD_THRESHOLD,- LAPLACIAN_SOFT_THRESHOLD, LAPLACIAN_VERY_SOFT_THRESHOLD, MEDIUM_QUALITY_FACE_SCORE,- MINIMUM_QUALITY_FACE_SCORE, PET_ML_VERSION, PetBodyRow, PetBodyVectorRow, PetFaceRow,- PetFaceVectorRow, PetRowsForFiles, is_bad_face_for_clustering,+ ClipRow, EmbeddingVector,+};+pub use queries::clusters::{ClusterCentroidRow, ClusterSummary};+pub use queries::faces::{+ FACE_ML_VERSION, FaceDbInfoForClustering, FaceRow, FaceWithoutEmbedding,+ LAPLACIAN_HARD_THRESHOLD, LAPLACIAN_SOFT_THRESHOLD, LAPLACIAN_VERY_SOFT_THRESHOLD,+ MEDIUM_QUALITY_FACE_SCORE, MINIMUM_QUALITY_FACE_SCORE, is_bad_face_for_clustering,+};+pub use queries::filedata::{FdStatus, PreviewInfo};+pub use queries::persons::PersonToClusterIdToFaceIds;+pub use queries::pets::{+ PET_ML_VERSION, PetBodyRow, PetBodyVectorRow, PetFaceRow, PetFaceVectorRow, PetRowsForFiles,};pub use vector_encoding::{decode_evector, decode_f32, encode_evector, encode_f32};@@ -55,44 +53,32 @@ impl MlDb {)?,})}-}-fn file_id_to_cluster_ids(- cluster_and_face_ids: Vec<(String, String)>,-) -> Result<HashMap<i64, HashSet<String>>> {- let mut result: HashMap<i64, HashSet<String>> = HashMap::new();- for (cluster_id, face_id) in cluster_and_face_ids {- let file_id = file_id_from_face_id(&face_id)?;- result.entry(file_id).or_default().insert(cluster_id);+ pub fn clear_non_pet_tables(&self) -> Result<()> {+ self.db+ .execute_statements([+ schema::DELETE_FACES,+ schema::DELETE_FACE_CLUSTERS,+ schema::DELETE_CLUSTER_PERSON,+ schema::DELETE_CLUSTER_SUMMARY,+ schema::DELETE_CLUSTER_CENTROID_VECTOR_ID_MAPPING,+ schema::DELETE_NOT_PERSON_FEEDBACK,+ schema::DELETE_CLIP_EMBEDDINGS,+ schema::DELETE_FILE_DATA,+ ])+ .map_err(Into::into)}- Ok(result)-}-fn file_id_from_face_id(face_id: &str) -> Result<i64> {- try_file_id_from_face_id(face_id)- .ok_or_else(|| Error::Codec(format!("Error parsing faceId: {face_id}")))-}--fn try_file_id_from_face_id(face_id: &str) -> Option<i64> {- face_id- .split_once('_')- .and_then(|(file_id, _)| file_id.parse().ok())-}--fn unique_in_order(ids: &[String]) -> Vec<&str> {- let mut seen = HashSet::new();- ids.iter()- .map(String::as_str)- .filter(|id| seen.insert(*id))- .collect()-}--fn limit_clause(limit: Option<i64>) -> &'static str {- if limit.is_some() { " LIMIT ?" } else { "" }-}--fn non_empty<T>(rows: Vec<T>) -> Option<Vec<T>> {- (!rows.is_empty()).then_some(rows)+ pub fn clear_pet_tables(&self) -> Result<()> {+ self.db+ .execute_statements([+ schema::DELETE_PET_FACES,+ schema::DELETE_PET_BODIES,+ schema::DELETE_PET_FACE_VECTOR_ID_MAPPING,+ schema::DELETE_PET_BODY_VECTOR_ID_MAPPING,+ ])+ .map_err(Into::into)+ }}#[cfg(test)]@@ -101,7 +87,8 @@ mod tests {use std::fmt::Debug;use std::path::Path;- use super::queries::tests::full_clip;+ use super::queries::clip::tests::full_clip;+ use super::queries::{caches, clip, clusters, faces, filedata, persons, pets};use super::{Error, MlDb, TARGET_VERSION};use crate::db::Connection;use tempfile::TempDir;@@ -193,6 +180,80 @@ mod tests {values}+ fn seeded_all() -> (TempDir, MlDb) {+ let (directory, db) = open();+ clip::tests::seed(&db);+ filedata::tests::seed(&db);+ caches::tests::seed(&db);+ faces::tests::seed(&db);+ clusters::tests::seed(&db);+ persons::tests::seed(&db);+ pets::tests::seed(&db);+ (directory, db)+ }++ #[test]+ fn clear_non_pet_tables_leaves_pets_and_caches() {+ let (_directory, db) = seeded_all();+ db.clear_non_pet_tables().unwrap();+ assert_eq!(db.get_total_face_count().unwrap(), 0);+ assert!(db.cluster_id_to_face_count().unwrap().is_empty());+ assert!(db.get_person_to_cluster_ids().unwrap().is_empty());+ assert!(db.get_person_to_rejected_suggestions().unwrap().is_empty());+ assert_eq!(db.count_cluster_summaries().unwrap(), 0);+ assert!(+ db.get_cluster_centroid_vector_id_map(&strings(["c1"]), false)+ .unwrap()+ .is_empty()+ );+ assert_eq!(db.count_clip_rows().unwrap(), 0);+ assert!(db.get_file_ids_with_fd_data(None).unwrap().is_empty());+ assert_eq!(db.get_pet_indexed_file_count(1).unwrap(), 2);+ assert_eq!(+ db.get_face_id_used_for_person_or_cluster("p1").unwrap(),+ Some("1_0".to_string())+ );+ assert_eq!(+ db.get_repeated_text_embedding_cache("dog").unwrap(),+ Some(vec![0.5f32, -1.0])+ );+ }++ #[test]+ fn clear_pet_tables_leaves_non_pet_tables() {+ let (directory, db) = seeded_all();+ let connection = Connection::open(directory.path().join("ente.ml.db")).unwrap();+ let row_count = |table: &str| -> i64 {+ connection+ .query_row(&format!("SELECT COUNT(*) FROM {table}"), (), |row| {+ row.get(0)+ })+ .unwrap()+ };+ assert_eq!(row_count("pet_face_vector_id_map"), 2);+ assert_eq!(row_count("pet_body_vector_id_map"), 1);+ db.clear_pet_tables().unwrap();+ assert_eq!(row_count("pet_face_vector_id_map"), 0);+ assert_eq!(row_count("pet_body_vector_id_map"), 0);+ assert_eq!(db.get_pet_indexed_file_count(0).unwrap(), 0);+ assert_eq!(+ db.get_pet_rows_for_files(&[1, 2, 3]).unwrap().faces.len(),+ 0+ );+ assert_eq!(db.get_total_face_count().unwrap(), 9);+ assert_eq!(db.cluster_id_to_face_count().unwrap().len(), 6);+ assert_eq!(db.get_person_cluster_ids("p1").unwrap().len(), 2);+ assert_eq!(db.count_clip_rows().unwrap(), 4);+ assert_eq!(+ db.get_file_ids_with_fd_data(None).unwrap(),+ HashSet::from([1, 2, 3])+ );+ assert_eq!(+ db.get_face_id_used_for_person_or_cluster("p1").unwrap(),+ Some("1_0".to_string())+ );+ }+#[test]fn ml_db_is_send_and_sync() {fn assert_send_sync<T: Send + Sync>() {}diff --git a/rust/crates/photos/src/ml_db/caches.rs b/rust/crates/photos/src/ml_db/queries/caches.rssimilarity index 91%rename from rust/crates/photos/src/ml_db/caches.rsrename to rust/crates/photos/src/ml_db/queries/caches.rsindex dab60f85e7..4e153dba4e 100644--- a/rust/crates/photos/src/ml_db/caches.rs+++ b/rust/crates/photos/src/ml_db/queries/caches.rs@@ -1,8 +1,8 @@use std::time::{SystemTime, UNIX_EPOCH};-use super::queries::CLIP_ML_VERSION;-use super::vector_encoding::{decode_f32, encode_f32};-use super::{MlDb, Result};+use super::clip::CLIP_ML_VERSION;+use crate::ml_db::vector_encoding::{decode_f32, encode_f32};+use crate::ml_db::{MlDb, Result};const THREE_MONTHS_MILLIS: i64 = 90 * 24 * 60 * 60 * 1000;@@ -10,7 +10,10 @@ impl MlDb {pub fn put_repeated_text_embedding_cache(&self, query: &str, embedding: &[f64]) -> Result<()> {let embedding_bytes = encode_f32(embedding.iter().map(|value| *value as f32));self.db.execute(- "INSERT OR REPLACE INTO text_embeddings_cache (text_query, embedding, ml_version, created_at) VALUES (?, ?, ?, ?)",+ r#"+ INSERT OR REPLACE INTO text_embeddings_cache (text_query, embedding, ml_version, created_at)+ VALUES (?, ?, ?, ?)+ "#,(query, embedding_bytes, CLIP_ML_VERSION, now_millis()),)?;Ok(())@@ -18,7 +21,11 @@ impl MlDb {pub fn get_repeated_text_embedding_cache(&self, query: &str) -> Result<Option<Vec<f32>>> {let results: Vec<(Vec<u8>, i64, i64)> = self.db.read_all(- "SELECT embedding, ml_version, created_at FROM text_embeddings_cache WHERE text_query = ?",+ r#"+ SELECT embedding, ml_version, created_at+ FROM text_embeddings_cache+ WHERE text_query = ?+ "#,[query],|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),)?;@@ -82,7 +89,7 @@ fn now_millis() -> i64 {}#[cfg(test)]-pub(super) mod tests {+pub(in crate::ml_db) mod tests {use super::MlDb;use crate::db::Connection;use crate::ml_db::tests::{cases, check, open};diff --git a/rust/crates/photos/src/ml_db/queries.rs b/rust/crates/photos/src/ml_db/queries/clip.rssimilarity index 51%rename from rust/crates/photos/src/ml_db/queries.rsrename to rust/crates/photos/src/ml_db/queries/clip.rsindex 0a527e1063..00aeffc16e 100644--- a/rust/crates/photos/src/ml_db/queries.rs+++ b/rust/crates/photos/src/ml_db/queries/clip.rs@@ -1,24 +1,15 @@use std::collections::HashMap;use crate::db::pair;+use crate::ml_db::schema;+use crate::ml_db::vector_encoding::{decode_f32, encode_f32};+use crate::ml_db::{MlDb, Result};-use super::schema;-use super::vector_encoding::{decode_f32, encode_f32};-use super::{MlDb, Result};--pub const FACE_ML_VERSION: i64 = 1;pub const CLIP_ML_VERSION: i64 = 1;-pub const PET_ML_VERSION: i64 = 1;pub const CLIP_EMBEDDING_DIMENSIONS: usize = 512;pub const CLIP_EMBEDDING_BYTES_LENGTH: i64 = CLIP_EMBEDDING_DIMENSIONS as i64 * 4;-pub const LAPLACIAN_HARD_THRESHOLD: f64 = 10.0;-pub const LAPLACIAN_SOFT_THRESHOLD: f64 = 50.0;-pub const LAPLACIAN_VERY_SOFT_THRESHOLD: f64 = 200.0;-pub const MINIMUM_QUALITY_FACE_SCORE: f64 = 0.80;-pub const MEDIUM_QUALITY_FACE_SCORE: f64 = 0.85;-#[derive(Clone, Debug, PartialEq)]pub struct ClipEmbedding {pub file_id: i64,@@ -38,124 +29,7 @@ pub struct ClipRow {pub embedding: Vec<u8>,}-#[derive(Clone, Debug, PartialEq)]-pub struct FaceRow {- pub file_id: i64,- pub face_id: String,- pub detection_json: String,- pub embedding: Vec<f64>,- pub score: f64,- pub blur: f64,- pub is_sideways: bool,- pub image_height: i64,- pub image_width: i64,- pub ml_version: i64,-}--#[derive(Clone, Debug, PartialEq)]-pub struct FaceWithoutEmbedding {- pub face_id: String,- pub file_id: i64,- pub score: f64,- pub detection_json: String,- pub blur: f64,-}--#[derive(Clone, Debug, PartialEq)]-pub struct FaceDbInfoForClustering {- pub face_id: String,- pub cluster_id: Option<String>,- pub embedding_bytes: Vec<u8>,- pub face_score: f64,- pub blur_value: f64,- pub is_sideways: bool,-}--#[derive(Clone, Debug, PartialEq)]-pub struct PetFaceRow {- pub file_id: i64,- pub pet_face_id: String,- pub detection_json: String,- pub face_vector_id: Option<i64>,- pub species: i64,- pub face_score: f64,- pub image_height: i64,- pub image_width: i64,- pub ml_version: i64,-}--#[derive(Clone, Debug, PartialEq)]-pub struct PetBodyRow {- pub file_id: i64,- pub pet_body_id: String,- pub detection_json: String,- pub body_vector_id: Option<i64>,- pub species: i64,- pub score: f64,- pub image_height: i64,- pub image_width: i64,- pub ml_version: i64,-}--#[derive(Clone, Debug, PartialEq)]-pub struct PetFaceVectorRow {- pub pet_face_id: String,- pub face_vector_id: Option<i64>,- pub species: i64,-}--#[derive(Clone, Debug, PartialEq)]-pub struct PetBodyVectorRow {- pub pet_body_id: String,- pub body_vector_id: Option<i64>,- pub species: i64,-}--#[derive(Clone, Debug, PartialEq)]-pub struct PetRowsForFiles {- pub faces: Vec<PetFaceVectorRow>,- pub bodies: Vec<PetBodyVectorRow>,-}--#[derive(Clone, Debug, PartialEq, Eq)]-pub struct ClusterSummary {- pub avg: Vec<u8>,- pub count: i64,-}--#[derive(Clone, Debug, PartialEq, Eq)]-pub struct ClusterCentroidRow {- pub cluster_id: String,- pub avg: Vec<u8>,-}-impl MlDb {- pub fn clear_non_pet_tables(&self) -> Result<()> {- self.db- .execute_statements([- schema::DELETE_FACES,- schema::DELETE_FACE_CLUSTERS,- schema::DELETE_CLUSTER_PERSON,- schema::DELETE_CLUSTER_SUMMARY,- schema::DELETE_CLUSTER_CENTROID_VECTOR_ID_MAPPING,- schema::DELETE_NOT_PERSON_FEEDBACK,- schema::DELETE_CLIP_EMBEDDINGS,- schema::DELETE_FILE_DATA,- ])- .map_err(Into::into)- }-- pub fn clear_pet_tables(&self) -> Result<()> {- self.db- .execute_statements([- schema::DELETE_PET_FACES,- schema::DELETE_PET_BODIES,- schema::DELETE_PET_FACE_VECTOR_ID_MAPPING,- schema::DELETE_PET_BODY_VECTOR_ID_MAPPING,- ])- .map_err(Into::into)- }-pub fn get_all_clip_vectors(&self) -> Result<Vec<EmbeddingVector>> {let rows: Vec<(i64, Vec<u8>)> =self.db@@ -186,10 +60,17 @@ impl MlDb {}pub fn get_clip_vectorizable_file_count(&self, minimum_ml_version: i64) -> Result<i64> {- self.db.read_value(- "SELECT COUNT(DISTINCT file_id) as count FROM clip WHERE ml_version >= ? AND LENGTH(embedding) = ?",- [minimum_ml_version, CLIP_EMBEDDING_BYTES_LENGTH],- ).map_err(Into::into)+ self.db+ .read_value(+ r#"+ SELECT COUNT(DISTINCT file_id) as count+ FROM clip+ WHERE ml_version >= ?+ AND LENGTH(embedding) = ?+ "#,+ [minimum_ml_version, CLIP_EMBEDDING_BYTES_LENGTH],+ )+ .map_err(Into::into)}pub fn insert_clip_rows(&self, embeddings: &[ClipEmbedding]) -> Result<()> {@@ -201,7 +82,7 @@ impl MlDb {return Ok(());}self.db- .write_batch(+ .write_batch_atomic("INSERT OR REPLACE INTO clip (file_id, embedding, ml_version) values(?, ?, ?)",embeddings.iter().map(clip_row),)@@ -242,13 +123,6 @@ impl MlDb {}}-pub fn is_bad_face_for_clustering(face_score: f64, blur_value: f64, is_sideways: bool) -> bool {- face_score < MINIMUM_QUALITY_FACE_SCORE- || blur_value < LAPLACIAN_SOFT_THRESHOLD- || (blur_value < LAPLACIAN_VERY_SOFT_THRESHOLD && face_score < MEDIUM_QUALITY_FACE_SCORE)- || is_sideways-}-fn clip_row(embedding: &ClipEmbedding) -> (i64, Vec<u8>, i64) {(embedding.file_id,@@ -258,14 +132,12 @@ fn clip_row(embedding: &ClipEmbedding) -> (i64, Vec<u8>, i64) {}#[cfg(test)]-pub(super) mod tests {- use std::collections::{HashMap, HashSet};+pub(in crate::ml_db) mod tests {+ use std::collections::HashMap;use super::{CLIP_EMBEDDING_DIMENSIONS, ClipEmbedding, ClipRow, MlDb};- use crate::db::Connection;- use crate::ml_db::tests::{cases, check, open, strings};+ use crate::ml_db::tests::{cases, check, open};use crate::ml_db::vector_encoding::encode_f32;- use crate::ml_db::{caches, clusters, faces, filedata, persons, pets};use tempfile::TempDir;fn clip(file_id: i64, embedding: Vec<f64>) -> ClipEmbedding {@@ -299,17 +171,6 @@ pub(super) mod tests {(directory, db)}- fn seeded_all() -> (TempDir, MlDb) {- let (directory, db) = seeded();- filedata::tests::seed(&db);- caches::tests::seed(&db);- faces::tests::seed(&db);- clusters::tests::seed(&db);- persons::tests::seed(&db);- pets::tests::seed(&db);- (directory, db)- }-#[test]fn seeded_counts() {let (_directory, db) = seeded();@@ -392,66 +253,4 @@ pub(super) mod tests {db.delete_all_clip_rows().unwrap();assert_eq!(db.count_clip_rows().unwrap(), 0);}-- #[test]- fn clear_non_pet_tables_leaves_pets_and_caches() {- let (_directory, db) = seeded_all();- db.clear_non_pet_tables().unwrap();- assert_eq!(db.get_total_face_count().unwrap(), 0);- assert!(db.cluster_id_to_face_count().unwrap().is_empty());- assert!(db.get_person_to_cluster_ids().unwrap().is_empty());- assert!(db.get_person_to_rejected_suggestions().unwrap().is_empty());- assert_eq!(db.count_cluster_summaries().unwrap(), 0);- assert!(- db.get_cluster_centroid_vector_id_map(&strings(["c1"]), false)- .unwrap()- .is_empty()- );- assert_eq!(db.count_clip_rows().unwrap(), 0);- assert!(db.get_file_ids_with_fd_data(None).unwrap().is_empty());- assert_eq!(db.get_pet_indexed_file_count(1).unwrap(), 2);- assert_eq!(- db.get_face_id_used_for_person_or_cluster("p1").unwrap(),- Some("1_0".to_string())- );- assert_eq!(- db.get_repeated_text_embedding_cache("dog").unwrap(),- Some(vec![0.5f32, -1.0])- );- }-- #[test]- fn clear_pet_tables_leaves_non_pet_tables() {- let (directory, db) = seeded_all();- let connection = Connection::open(directory.path().join("ente.ml.db")).unwrap();- let row_count = |table: &str| -> i64 {- connection- .query_row(&format!("SELECT COUNT(*) FROM {table}"), (), |row| {- row.get(0)- })- .unwrap()- };- assert_eq!(row_count("pet_face_vector_id_map"), 2);- assert_eq!(row_count("pet_body_vector_id_map"), 1);- db.clear_pet_tables().unwrap();- assert_eq!(row_count("pet_face_vector_id_map"), 0);- assert_eq!(row_count("pet_body_vector_id_map"), 0);- assert_eq!(db.get_pet_indexed_file_count(0).unwrap(), 0);- assert_eq!(- db.get_pet_rows_for_files(&[1, 2, 3]).unwrap().faces.len(),- 0- );- assert_eq!(db.get_total_face_count().unwrap(), 9);- assert_eq!(db.cluster_id_to_face_count().unwrap().len(), 6);- assert_eq!(db.get_person_cluster_ids("p1").unwrap().len(), 2);- assert_eq!(db.count_clip_rows().unwrap(), 4);- assert_eq!(- db.get_file_ids_with_fd_data(None).unwrap(),- HashSet::from([1, 2, 3])- );- assert_eq!(- db.get_face_id_used_for_person_or_cluster("p1").unwrap(),- Some("1_0".to_string())- );- }}diff --git a/rust/crates/photos/src/ml_db/clusters.rs b/rust/crates/photos/src/ml_db/queries/clusters.rssimilarity index 86%rename from rust/crates/photos/src/ml_db/clusters.rsrename to rust/crates/photos/src/ml_db/queries/clusters.rsindex ffc7a0de1e..28cc4a6b3b 100644--- a/rust/crates/photos/src/ml_db/clusters.rs+++ b/rust/crates/photos/src/ml_db/queries/clusters.rs@@ -5,18 +5,42 @@ use crate::db::{optional_parameter, pair, params_from_iter,};-use super::queries::{ClusterCentroidRow, ClusterSummary, is_bad_face_for_clustering};-use super::schema::{+use super::faces::{file_id_from_face_id, is_bad_face_for_clustering};+use super::unique_in_order;+use crate::ml_db::schema::{CREATE_CLUSTER_CENTROID_VECTOR_ID_MAPPING_TABLE, CREATE_CLUSTER_PERSON_TABLE,CREATE_CLUSTER_SUMMARY_TABLE, CREATE_FACE_CLUSTERS_TABLE, CREATE_FACES_TABLE,CREATE_NOT_PERSON_FEEDBACK_TABLE, DELETE_CLUSTER_CENTROID_VECTOR_ID_MAPPING,DELETE_CLUSTER_PERSON, DELETE_CLUSTER_SUMMARY, DELETE_FACE_CLUSTERS, DELETE_FACES,DELETE_NOT_PERSON_FEEDBACK, FC_CLUSTER_ID_INDEX,};-use super::{MlDb, Result, file_id_to_cluster_ids, unique_in_order};+use crate::ml_db::{MlDb, Result};-const UPSERT_FACE_CLUSTER: &str = "INSERT INTO face_clusters (face_id, cluster_id) VALUES (?, ?) ON CONFLICT(face_id) DO UPDATE SET cluster_id = excluded.cluster_id";-const UPSERT_CLUSTER_SUMMARY: &str = "INSERT INTO cluster_summary (cluster_id, avg, count) VALUES (?, ?, ?) ON CONFLICT(cluster_id) DO UPDATE SET avg = excluded.avg, count = excluded.count";+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ClusterSummary {+ pub avg: Vec<u8>,+ pub count: i64,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ClusterCentroidRow {+ pub cluster_id: String,+ pub avg: Vec<u8>,+}++const UPSERT_FACE_CLUSTER: &str = r#"+ INSERT INTO face_clusters (face_id, cluster_id)+ VALUES (?, ?)+ ON CONFLICT (face_id) DO UPDATE SET+ cluster_id = excluded.cluster_id+"#;+const UPSERT_CLUSTER_SUMMARY: &str = r#"+ INSERT INTO cluster_summary (cluster_id, avg, count)+ VALUES (?, ?, ?)+ ON CONFLICT (cluster_id) DO UPDATE SET+ avg = excluded.avg,+ count = excluded.count+"#;impl MlDb {pub fn update_face_id_to_cluster_id(@@ -24,14 +48,19 @@ impl MlDb {face_id_to_cluster_id: &HashMap<String, String>,) -> Result<()> {self.db- .write_in_batches(UPSERT_FACE_CLUSTER, 500, face_id_to_cluster_id.iter())+ .write_batches_committing_each(UPSERT_FACE_CLUSTER, 500, face_id_to_cluster_id.iter()).map_err(Into::into)}pub fn cluster_id_to_face_count(&self) -> Result<HashMap<String, i64>> {self.db.read_all(- "SELECT cluster_id, COUNT(*) as count FROM face_clusters where cluster_id IS NOT NULL GROUP BY cluster_id",+ r#"+ SELECT cluster_id, COUNT(*) as count+ FROM face_clusters+ where cluster_id IS NOT NULL+ GROUP BY cluster_id+ "#,(),pair,)@@ -40,7 +69,14 @@ impl MlDb {pub fn get_bad_face_singleton_cluster_ids(&self) -> Result<HashSet<String>> {let rows: Vec<(String, f64, f64, i64)> = self.db.read_all(- "SELECT fc.cluster_id, f.score, f.blur, f.is_sideways FROM face_clusters fc INNER JOIN faces f ON fc.face_id = f.face_id GROUP BY fc.cluster_id HAVING COUNT(*) = 1",+ r#"+ SELECT fc.cluster_id, f.score, f.blur, f.is_sideways+ FROM face_clusters fc+ INNER JOIN faces f+ ON fc.face_id = f.face_id+ GROUP BY fc.cluster_id+ HAVING COUNT(*) = 1+ "#,(),|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),)?;@@ -101,7 +137,15 @@ impl MlDb {) -> Result<Vec<String>> {self.db.read_column(- "SELECT faces.face_id FROM faces JOIN face_clusters ON faces.face_id = face_clusters.face_id WHERE face_clusters.cluster_id = ? ORDER BY faces.score DESC LIMIT ?",+ r#"+ SELECT faces.face_id+ FROM faces+ JOIN face_clusters+ ON faces.face_id = face_clusters.face_id+ WHERE face_clusters.cluster_id = ?+ ORDER BY faces.score DESC+ LIMIT ?+ "#,(cluster_id, limit),).map_err(Into::into)@@ -109,7 +153,13 @@ impl MlDb {pub fn get_blur_values_for_cluster(&self, cluster_id: &str) -> Result<Vec<f64>> {let blur_values: Vec<f64> = self.db.read_column(- "SELECT faces.blur FROM faces JOIN face_clusters ON faces.face_id = face_clusters.face_id WHERE face_clusters.cluster_id = ?",+ r#"+ SELECT faces.blur+ FROM faces+ JOIN face_clusters+ ON faces.face_id = face_clusters.face_id+ WHERE face_clusters.cluster_id = ?+ "#,[cluster_id],)?;let mut seen = HashSet::new();@@ -145,7 +195,7 @@ impl MlDb {face_id_to_cluster_id: &HashMap<String, String>,) -> Result<()> {self.db- .write_batch(UPSERT_FACE_CLUSTER, face_id_to_cluster_id.iter())+ .write_batch_atomic(UPSERT_FACE_CLUSTER, face_id_to_cluster_id.iter()).map_err(Into::into)}@@ -154,7 +204,7 @@ impl MlDb {face_id_to_cluster_id: &HashMap<String, String>,) -> Result<()> {self.db- .write_batch(+ .write_batch_atomic("DELETE FROM face_clusters WHERE face_id = ? AND cluster_id = ?",face_id_to_cluster_id.iter(),)@@ -178,7 +228,13 @@ impl MlDb {pub fn get_file_ids_of_cluster_id(&self, cluster_id: &str) -> Result<Vec<i64>> {self.db.read_column(- "SELECT DISTINCT faces.file_id FROM face_clusters JOIN faces ON face_clusters.face_id = faces.face_id WHERE face_clusters.cluster_id = ?",+ r#"+ SELECT DISTINCT faces.file_id+ FROM face_clusters+ JOIN faces+ ON face_clusters.face_id = faces.face_id+ WHERE face_clusters.cluster_id = ?+ "#,[cluster_id],).map_err(Into::into)@@ -194,14 +250,18 @@ impl MlDb {return Ok(HashMap::new());}if create_if_missing {- self.db.write_batch(+ self.db.write_batch_atomic("INSERT OR IGNORE INTO cluster_centroid_vector_id_map (cluster_id) VALUES (?)",unique_cluster_ids.iter().map(|cluster_id| [cluster_id]),)?;}self.db.read_chunked_in(- "SELECT cluster_id, cluster_vector_id FROM cluster_centroid_vector_id_map WHERE cluster_id IN ({})",+ r#"+ SELECT cluster_id, cluster_vector_id+ FROM cluster_centroid_vector_id_map+ WHERE cluster_id IN ({})+ "#,&unique_cluster_ids,800,pair,@@ -228,7 +288,7 @@ impl MlDb {summary: &HashMap<String, ClusterSummary>,) -> Result<()> {self.db- .write_in_batches(+ .write_batches_committing_each(UPSERT_CLUSTER_SUMMARY,400,summary@@ -298,7 +358,13 @@ impl MlDb {read_cluster_centroid,),Some(before_cluster_id) => self.db.read_all(- "SELECT cluster_id, avg FROM cluster_summary WHERE cluster_id < ? ORDER BY cluster_id DESC LIMIT ?",+ r#"+ SELECT cluster_id, avg+ FROM cluster_summary+ WHERE cluster_id < ?+ ORDER BY cluster_id DESC+ LIMIT ?+ "#,(before_cluster_id, limit),read_cluster_centroid,),@@ -344,7 +410,15 @@ impl MlDb {let mut offset: i64 = 0;while clusters.len() < 20 {let batch: Vec<String> = self.db.read_column(- "SELECT cluster_id, COUNT(*) AS count FROM face_clusters WHERE cluster_id IS NOT NULL GROUP BY cluster_id ORDER BY count DESC, cluster_id LIMIT ? OFFSET ?",+ r#"+ SELECT cluster_id, COUNT(*) AS count+ FROM face_clusters+ WHERE cluster_id IS NOT NULL+ GROUP BY cluster_id+ ORDER BY count DESC, cluster_id+ LIMIT ?+ OFFSET ?+ "#,[batch_size, offset],)?;let batch_len = batch.len() as i64;@@ -365,6 +439,17 @@ impl MlDb {}}+pub(super) fn file_id_to_cluster_ids(+ cluster_and_face_ids: Vec<(String, String)>,+) -> Result<HashMap<i64, HashSet<String>>> {+ let mut result: HashMap<i64, HashSet<String>> = HashMap::new();+ for (cluster_id, face_id) in cluster_and_face_ids {+ let file_id = file_id_from_face_id(&face_id)?;+ result.entry(file_id).or_default().insert(cluster_id);+ }+ Ok(result)+}+fn read_cluster_summary(row: &Row<'_>) -> SqliteResult<(String, ClusterSummary)> {Ok((row.get("cluster_id")?,@@ -383,15 +468,15 @@ fn read_cluster_centroid(row: &Row<'_>) -> SqliteResult<ClusterCentroidRow> {}#[cfg(test)]-pub(super) mod tests {+pub(in crate::ml_db) mod tests {use std::collections::HashMap;use super::{ClusterCentroidRow, ClusterSummary, MlDb};+ 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,};use crate::ml_db::vector_encoding::encode_evector;- use crate::ml_db::{faces, persons};use tempfile::TempDir;fn summary(count: i64) -> ClusterSummary {diff --git a/rust/crates/photos/src/ml_db/faces.rs b/rust/crates/photos/src/ml_db/queries/faces.rssimilarity index 78%rename from rust/crates/photos/src/ml_db/faces.rsrename to rust/crates/photos/src/ml_db/queries/faces.rsindex 732c96ceaf..f34140482a 100644--- a/rust/crates/photos/src/ml_db/faces.rs+++ b/rust/crates/photos/src/ml_db/queries/faces.rs@@ -5,24 +5,77 @@ use crate::db::{optional_parameter, pair, params_from_iter,};-use super::queries::{- CLIP_ML_VERSION, FACE_ML_VERSION, FaceDbInfoForClustering, FaceRow, FaceWithoutEmbedding,- LAPLACIAN_HARD_THRESHOLD, MINIMUM_QUALITY_FACE_SCORE, PET_ML_VERSION,-};-use super::vector_encoding::{decode_evector, encode_evector};-use super::{- Error, MlDb, Result, file_id_from_face_id, limit_clause, non_empty, try_file_id_from_face_id,- unique_in_order,-};+use super::clip::CLIP_ML_VERSION;+use super::pets::PET_ML_VERSION;+use super::{limit_clause, unique_in_order};+use crate::ml_db::vector_encoding::{decode_evector, encode_evector};+use crate::ml_db::{Error, MlDb, Result};++pub const FACE_ML_VERSION: i64 = 1;++pub const LAPLACIAN_HARD_THRESHOLD: f64 = 10.0;+pub const LAPLACIAN_SOFT_THRESHOLD: f64 = 50.0;+pub const LAPLACIAN_VERY_SOFT_THRESHOLD: f64 = 200.0;+pub const MINIMUM_QUALITY_FACE_SCORE: f64 = 0.80;+pub const MEDIUM_QUALITY_FACE_SCORE: f64 = 0.85;++#[derive(Clone, Debug, PartialEq)]+pub struct FaceRow {+ pub file_id: i64,+ pub face_id: String,+ pub detection_json: String,+ pub embedding: Vec<f64>,+ pub score: f64,+ pub blur: f64,+ pub is_sideways: bool,+ pub image_height: i64,+ pub image_width: i64,+ pub ml_version: i64,+}++#[derive(Clone, Debug, PartialEq)]+pub struct FaceWithoutEmbedding {+ pub face_id: String,+ pub file_id: i64,+ pub score: f64,+ pub detection_json: String,+ pub blur: f64,+}++#[derive(Clone, Debug, PartialEq)]+pub struct FaceDbInfoForClustering {+ pub face_id: String,+ pub cluster_id: Option<String>,+ pub embedding_bytes: Vec<u8>,+ pub face_score: f64,+ pub blur_value: f64,+ pub is_sideways: bool,+}const FACE_EMBEDDING_MAX_ROWS: usize = 20000;-const UPSERT_FACE: &str = "INSERT INTO faces (file_id, face_id, detection, embedding, score, blur, is_sideways, height, width, ml_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(file_id, face_id) DO UPDATE SET face_id = excluded.face_id, detection = excluded.detection, embedding = excluded.embedding, score = excluded.score, blur = excluded.blur, is_sideways = excluded.is_sideways, height = excluded.height, width = excluded.width, ml_version = excluded.ml_version";+const UPSERT_FACE: &str = r#"+ INSERT INTO faces (+ file_id, face_id, detection, embedding, score, blur,+ is_sideways, height, width, ml_version+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT (file_id, face_id) DO UPDATE SET+ face_id = excluded.face_id,+ detection = excluded.detection,+ embedding = excluded.embedding,+ score = excluded.score,+ blur = excluded.blur,+ is_sideways = excluded.is_sideways,+ height = excluded.height,+ width = excluded.width,+ ml_version = excluded.ml_version+"#;impl MlDb {pub fn bulk_insert_faces(&self, faces: &[FaceRow]) -> Result<()> {self.db- .write_in_batches(+ .write_batches_committing_each(UPSERT_FACE,500,faces.iter().map(|face| {@@ -68,7 +121,15 @@ impl MlDb {limit: Option<i64>,) -> Result<Vec<Vec<u8>>> {let sql = format!(- "SELECT embedding FROM faces WHERE face_id in (SELECT face_id from face_clusters where cluster_id = ?){}",+ r#"+ SELECT embedding+ FROM faces+ WHERE face_id in (+ SELECT face_id+ from face_clusters+ where cluster_id = ?+ ) {}+ "#,limit_clause(limit));let mut parameters: Vec<&dyn ToSql> = vec![&cluster_id];@@ -99,7 +160,13 @@ impl MlDb {break;}let sql = format!(- "SELECT fc.cluster_id, fe.embedding FROM face_clusters fc INNER JOIN faces fe ON fc.face_id = fe.face_id WHERE fc.cluster_id IN ({}){}",+ r#"+ SELECT fc.cluster_id, fe.embedding+ FROM face_clusters fc+ INNER JOIN faces fe+ ON fc.face_id = fe.face_id+ WHERE fc.cluster_id IN ({}) {}+ "#,bind_placeholders(cluster_chunk.len()),limit_clause(remaining_limit));@@ -136,7 +203,17 @@ impl MlDb {[person_id],)?;let sql = format!(- "SELECT * FROM faces WHERE face_id IN (SELECT face_id FROM face_clusters WHERE cluster_id IN ({})) AND file_id IN ({}) ORDER BY score DESC",+ r#"+ SELECT *+ FROM faces+ WHERE face_id IN (+ SELECT face_id+ FROM face_clusters+ WHERE cluster_id IN ({})+ )+ AND file_id IN ({})+ ORDER BY score DESC+ "#,bind_placeholders(cluster_ids.len()),bind_placeholders(file_ids.len()));@@ -160,11 +237,9 @@ impl MlDb {"SELECT face_id FROM face_clusters WHERE cluster_id = ?",[cluster_id],)?;- if let Some(faces) = self.get_faces_for_given_file_id(recent_file_id)? {- for face in faces {- if face_ids.contains(&face.face_id) {- return Ok(Some(face));- }+ for face in self.get_faces_for_given_file_id(recent_file_id)? {+ if face_ids.contains(&face.face_id) {+ return Ok(Some(face));}}}@@ -176,15 +251,13 @@ impl MlDb {Ok(None)}- pub fn get_faces_for_given_file_id(&self, file_upload_id: i64) -> Result<Option<Vec<FaceRow>>> {+ pub fn get_faces_for_given_file_id(&self, file_upload_id: i64) -> Result<Vec<FaceRow>> {let faces: Vec<StoredFace> = self.db.read_all("SELECT * FROM faces WHERE file_id = ?",[file_upload_id],read_stored_face,)?;- non_empty(faces)- .map(|faces| faces.into_iter().map(StoredFace::decode).collect())- .transpose()+ faces.into_iter().map(StoredFace::decode).collect()}pub fn get_file_ids_to_faces_without_embedding(@@ -218,9 +291,30 @@ impl MlDb {let mut result = Vec::new();loop {let rows: Vec<(String, Vec<u8>, f64, f64, i64)> = self.db.read_all(- "SELECT face_id, embedding, score, blur, is_sideways FROM faces WHERE score > ? AND blur > ? ORDER BY face_id DESC LIMIT ? OFFSET ?",- (MINIMUM_QUALITY_FACE_SCORE, LAPLACIAN_HARD_THRESHOLD, batch_size, offset),- |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)),+ r#"+ SELECT face_id, embedding, score, blur, is_sideways+ FROM faces+ WHERE score > ?+ AND blur > ?+ ORDER BY face_id DESC+ LIMIT ?+ OFFSET ?+ "#,+ (+ MINIMUM_QUALITY_FACE_SCORE,+ LAPLACIAN_HARD_THRESHOLD,+ batch_size,+ offset,+ ),+ |row| {+ Ok((+ row.get(0)?,+ row.get(1)?,+ row.get(2)?,+ row.get(3)?,+ row.get(4)?,+ ))+ },)?;if rows.is_empty() {break;@@ -261,7 +355,13 @@ impl MlDb {break;}let sql = format!(- "SELECT face_id, embedding FROM faces WHERE face_id IN ({}) ORDER BY face_id DESC LIMIT ?",+ r#"+ SELECT face_id, embedding+ FROM faces+ WHERE face_id IN ({})+ ORDER BY face_id DESC+ LIMIT ?+ "#,bind_placeholders(chunk.len()));let mut parameters: Vec<&dyn ToSql> = chunk.iter().map(|id| id as &dyn ToSql).collect();@@ -300,7 +400,18 @@ impl MlDb {}self.db.execute_chunked_in(- "DELETE FROM faces WHERE file_id IN ({}) AND score < 0 AND EXISTS (SELECT 1 FROM faces AS successful WHERE successful.file_id = faces.file_id AND successful.score >= 0 AND successful.ml_version >= faces.ml_version)",+ r#"+ DELETE FROM faces+ WHERE file_id IN ({})+ AND score < 0+ AND EXISTS (+ SELECT 1+ FROM faces AS successful+ WHERE successful.file_id = faces.file_id+ AND successful.score >= 0+ AND successful.ml_version >= faces.ml_version+ )+ "#,file_ids,).map_err(Into::into)@@ -314,7 +425,29 @@ impl MlDb {for chunk in file_ids.chunks(MAX_SQL_BIND_PARAMS_PER_QUERY / 3) {let placeholders = bind_placeholders(chunk.len());let sql = format!(- "SELECT failed.file_id FROM faces AS failed WHERE failed.file_id IN ({placeholders}) AND failed.score < 0 AND NOT EXISTS (SELECT 1 FROM faces AS successful WHERE successful.file_id = failed.file_id AND successful.score >= 0 AND successful.ml_version >= failed.ml_version) UNION SELECT file_id FROM clip WHERE file_id IN ({placeholders}) AND LENGTH(embedding) = 0 UNION SELECT file_id FROM pet_faces WHERE file_id IN ({placeholders}) AND score < 0"+ r#"+ SELECT failed.file_id+ FROM faces AS failed+ WHERE failed.file_id IN ({placeholders})+ AND failed.score < 0+ AND NOT EXISTS (+ SELECT 1+ FROM faces AS successful+ WHERE successful.file_id = failed.file_id+ AND successful.score >= 0+ AND successful.ml_version >= failed.ml_version+ )+ UNION+ SELECT file_id+ FROM clip+ WHERE file_id IN ({placeholders})+ AND LENGTH(embedding) = 0+ UNION+ SELECT file_id+ FROM pet_faces+ WHERE file_id IN ({placeholders})+ AND score < 0+ "#);let matches: Vec<i64> = self.db.read_column(&sql,@@ -337,7 +470,15 @@ impl MlDb {}self.db.execute_chunked_in(- "DELETE FROM faces WHERE file_id IN ({}) AND NOT EXISTS (SELECT 1 FROM face_clusters WHERE face_clusters.face_id = faces.face_id)",+ r#"+ DELETE FROM faces+ WHERE file_id IN ({})+ AND NOT EXISTS (+ SELECT 1+ FROM face_clusters+ WHERE face_clusters.face_id = faces.face_id+ )+ "#,file_ids,).map_err(Into::into)@@ -367,7 +508,15 @@ impl MlDb {pub fn get_unclustered_face_count(&self) -> Result<i64> {self.db.read_value(- "SELECT COUNT(*) as count FROM faces f LEFT JOIN face_clusters fc ON f.face_id = fc.face_id WHERE f.score > ? AND f.blur > ? AND fc.face_id IS NULL",+ r#"+ SELECT COUNT(*) as count+ FROM faces f+ LEFT JOIN face_clusters fc+ ON f.face_id = fc.face_id+ WHERE f.score > ?+ AND f.blur > ?+ AND fc.face_id IS NULL+ "#,(MINIMUM_QUALITY_FACE_SCORE, LAPLACIAN_HARD_THRESHOLD),).map_err(Into::into)@@ -376,7 +525,13 @@ impl MlDb {pub fn get_all_file_ids_of_face_ids_not_in_any_cluster(&self) -> Result<HashSet<i64>> {self.db.read_column(- "SELECT DISTINCT file_id FROM faces LEFT JOIN face_clusters ON faces.face_id = face_clusters.face_id WHERE face_clusters.face_id IS NULL",+ r#"+ SELECT DISTINCT file_id+ FROM faces+ LEFT JOIN face_clusters+ ON faces.face_id = face_clusters.face_id+ WHERE face_clusters.face_id IS NULL+ "#,(),).map_err(Into::into)@@ -388,7 +543,13 @@ impl MlDb {) -> Result<HashSet<i64>> {let except_clusters = except_clusters.unwrap_or_default();let sql = format!(- "SELECT DISTINCT faces.file_id FROM faces JOIN face_clusters on face_clusters.face_id = faces.face_id WHERE face_clusters.cluster_id NOT IN ({})",+ r#"+ SELECT DISTINCT faces.file_id+ FROM faces+ JOIN face_clusters+ on face_clusters.face_id = faces.face_id+ WHERE face_clusters.cluster_id NOT IN ({})+ "#,bind_placeholders(except_clusters.len()));self.db@@ -398,7 +559,15 @@ impl MlDb {pub fn get_fully_indexed_file_ids(&self, include_pets: bool) -> Result<HashSet<i64>> {let mut sql = String::from(- "SELECT file_id FROM faces WHERE ml_version >= ? INTERSECT SELECT file_id FROM clip WHERE ml_version >= ?",+ r#"+ SELECT file_id+ FROM faces+ WHERE ml_version >= ?+ INTERSECT+ SELECT file_id+ FROM clip+ WHERE ml_version >= ?+ "#,);let mut parameters = vec![FACE_ML_VERSION, CLIP_ML_VERSION];if include_pets {@@ -411,6 +580,24 @@ impl MlDb {}}+pub fn is_bad_face_for_clustering(face_score: f64, blur_value: f64, is_sideways: bool) -> bool {+ face_score < MINIMUM_QUALITY_FACE_SCORE+ || blur_value < LAPLACIAN_SOFT_THRESHOLD+ || (blur_value < LAPLACIAN_VERY_SOFT_THRESHOLD && face_score < MEDIUM_QUALITY_FACE_SCORE)+ || is_sideways+}++pub(super) fn file_id_from_face_id(face_id: &str) -> Result<i64> {+ try_file_id_from_face_id(face_id)+ .ok_or_else(|| Error::Codec(format!("Error parsing faceId: {face_id}")))+}++fn try_file_id_from_face_id(face_id: &str) -> Option<i64> {+ face_id+ .split_once('_')+ .and_then(|(file_id, _)| file_id.parse().ok())+}+#[derive(Clone)]struct StoredFace {row: FaceRow,@@ -443,14 +630,15 @@ fn read_stored_face(row: &Row<'_>) -> SqliteResult<StoredFace> {}#[cfg(test)]-pub(super) mod tests {+pub(in crate::ml_db) mod tests {use std::collections::HashMap;use std::ops::RangeInclusive;use super::{FaceRow, MlDb};+ use crate::ml_db::queries::{clip, clusters, persons, pets};use crate::ml_db::tests::{cases, check, ids, open, sorted, strings};use crate::ml_db::vector_encoding::encode_evector;- use crate::ml_db::{Error, PetFaceRow, clusters, persons, pets, queries};+ use crate::ml_db::{Error, PetFaceRow};use tempfile::TempDir;fn face(file_id: i64, index: i64, score: f64, blur: f64, is_sideways: bool) -> FaceRow {@@ -499,7 +687,7 @@ pub(super) mod tests {fn seeded() -> (TempDir, MlDb) {let (directory, db) = open();- queries::tests::seed(&db);+ clip::tests::seed(&db);seed(&db);clusters::tests::seed(&db);persons::tests::seed(&db);@@ -558,10 +746,10 @@ pub(super) mod tests {#[test]fn seeded_rows() {let (_directory, db) = seeded();- let mut faces = db.get_faces_for_given_file_id(1).unwrap().unwrap();+ let mut faces = db.get_faces_for_given_file_id(1).unwrap();faces.sort_by(|left, right| left.face_id.cmp(&right.face_id));assert_eq!(faces, vec![good_face(1, 0), face(1, 1, 0.95, 300.0, false)]);- assert_eq!(db.get_faces_for_given_file_id(99).unwrap(), None);+ assert!(db.get_faces_for_given_file_id(99).unwrap().is_empty());let without_embedding = db.get_file_ids_to_faces_without_embedding().unwrap();assert_eq!(without_embedding.len(), 10);@@ -754,7 +942,7 @@ pub(super) mod tests {};db.bulk_insert_faces(std::slice::from_ref(&updated)).unwrap();- let faces = db.get_faces_for_given_file_id(1).unwrap().unwrap();+ let faces = db.get_faces_for_given_file_id(1).unwrap();assert_eq!(faces.len(), 2);assert_eq!(faces.iter().find(|face| face.face_id == "1_0"),@@ -764,13 +952,13 @@ pub(super) mod tests {db.delete_unclustered_face_index_for_files(&[]).unwrap();db.delete_unclustered_face_index_for_files(&[1, 6]).unwrap();- assert_eq!(db.get_faces_for_given_file_id(1).unwrap().unwrap().len(), 2);- assert_eq!(db.get_faces_for_given_file_id(6).unwrap(), None);+ assert_eq!(db.get_faces_for_given_file_id(1).unwrap().len(), 2);+ assert!(db.get_faces_for_given_file_id(6).unwrap().is_empty());db.delete_face_index_for_files(&[]).unwrap();db.delete_face_index_for_files(&[1, 2]).unwrap();assert_eq!(db.get_face_indexed_file_count(1).unwrap(), 6);- assert_eq!(db.get_faces_for_given_file_id(1).unwrap(), None);+ assert!(db.get_faces_for_given_file_id(1).unwrap().is_empty());}#[test]@@ -808,10 +996,7 @@ pub(super) mod tests {assert_eq!(db.get_errored_file_ids().unwrap(), ids([5, 11, 12]));db.prune_resolved_face_error_results(&[5, 11, 12]).unwrap();assert_eq!(db.get_errored_file_ids().unwrap(), ids([5, 12]));- assert_eq!(- db.get_faces_for_given_file_id(11).unwrap().unwrap().len(),- 1- );+ assert_eq!(db.get_faces_for_given_file_id(11).unwrap().len(), 1);assert_eq!(db.get_file_ids_with_error_results(&file_ids).unwrap(),ids([4, 5, 12, 13])diff --git a/rust/crates/photos/src/ml_db/filedata.rs b/rust/crates/photos/src/ml_db/queries/filedata.rssimilarity index 83%rename from rust/crates/photos/src/ml_db/filedata.rsrename to rust/crates/photos/src/ml_db/queries/filedata.rsindex 9d15618a51..856a226314 100644--- a/rust/crates/photos/src/ml_db/filedata.rs+++ b/rust/crates/photos/src/ml_db/queries/filedata.rs@@ -1,8 +1,7 @@use std::collections::{HashMap, HashSet};use crate::db::optional_parameter;--use super::{MlDb, Result};+use crate::ml_db::{MlDb, Result};#[derive(Clone, Debug, PartialEq, Eq)]pub struct FdStatus {@@ -26,20 +25,27 @@ impl MlDb {if fd_status_list.is_empty() {return Ok(());}- self.db.write_batch(- "INSERT OR REPLACE INTO filedata (file_id, user_id, type, size, obj_id, obj_nonce, updated_at ) values(?, ?, ?, ?, ?, ?, ?)",- fd_status_list.iter().map(|status| {- (- status.file_id,- status.user_id,- &status.data_type,- status.size,- &status.object_id,- &status.object_nonce,- status.updated_at,+ self.db+ .write_batch_atomic(+ r#"+ INSERT OR REPLACE INTO filedata (+ file_id, user_id, type, size, obj_id, obj_nonce, updated_at)- }),- ).map_err(Into::into)+ values (?, ?, ?, ?, ?, ?, ?)+ "#,+ fd_status_list.iter().map(|status| {+ (+ status.file_id,+ status.user_id,+ &status.data_type,+ status.size,+ &status.object_id,+ &status.object_nonce,+ status.updated_at,+ )+ }),+ )+ .map_err(Into::into)}pub fn get_file_ids_vid_preview(&self) -> Result<HashMap<i64, PreviewInfo>> {@@ -72,7 +78,7 @@ impl MlDb {}#[cfg(test)]-pub(super) mod tests {+pub(in crate::ml_db) mod tests {use std::collections::{HashMap, HashSet};use super::{FdStatus, MlDb, PreviewInfo};diff --git a/rust/crates/photos/src/ml_db/queries/mod.rs b/rust/crates/photos/src/ml_db/queries/mod.rsnew file mode 100644index 0000000000..a22b335eee--- /dev/null+++ b/rust/crates/photos/src/ml_db/queries/mod.rs@@ -0,0 +1,21 @@+pub(super) mod caches;+pub(super) mod clip;+pub(super) mod clusters;+pub(super) mod faces;+pub(super) mod filedata;+pub(super) mod persons;+pub(super) mod pets;++use std::collections::HashSet;++fn unique_in_order(ids: &[String]) -> Vec<&str> {+ let mut seen = HashSet::new();+ ids.iter()+ .map(String::as_str)+ .filter(|id| seen.insert(*id))+ .collect()+}++fn limit_clause(limit: Option<i64>) -> &'static str {+ if limit.is_some() { " LIMIT ?" } else { "" }+}diff --git a/rust/crates/photos/src/ml_db/persons.rs b/rust/crates/photos/src/ml_db/queries/persons.rssimilarity index 81%rename from rust/crates/photos/src/ml_db/persons.rsrename to rust/crates/photos/src/ml_db/queries/persons.rsindex fd95fa0ee3..d1b900f0dc 100644--- a/rust/crates/photos/src/ml_db/persons.rs+++ b/rust/crates/photos/src/ml_db/queries/persons.rs@@ -2,23 +2,36 @@ use std::collections::{HashMap, HashSet};use crate::db::{MAX_SQL_BIND_PARAMS_PER_QUERY, pair};-use super::schema::{+use super::clusters::file_id_to_cluster_ids;+use crate::ml_db::schema::{CREATE_CLUSTER_PERSON_TABLE, CREATE_NOT_PERSON_FEEDBACK_TABLE, DELETE_CLUSTER_PERSON,DELETE_NOT_PERSON_FEEDBACK,};-use super::{MlDb, Result, file_id_to_cluster_ids};+use crate::ml_db::{MlDb, Result};pub type PersonToClusterIdToFaceIds = HashMap<String, HashMap<String, HashSet<String>>>;-const INSERT_CLUSTER_PERSON: &str = "INSERT INTO cluster_person (person_id, cluster_id) VALUES (?, ?) ON CONFLICT(person_id, cluster_id) DO NOTHING";-const INSERT_NOT_PERSON_FEEDBACK: &str =- "INSERT INTO not_person_feedback (person_id, cluster_id) VALUES (?, ?) ON CONFLICT DO NOTHING";+const INSERT_CLUSTER_PERSON: &str = r#"+ INSERT INTO cluster_person (person_id, cluster_id)+ VALUES (?, ?)+ ON CONFLICT (person_id, cluster_id) DO NOTHING+"#;+const INSERT_NOT_PERSON_FEEDBACK: &str = r#"+ INSERT INTO not_person_feedback (person_id, cluster_id)+ VALUES (?, ?)+ ON CONFLICT DO NOTHING+"#;impl MlDb {pub fn get_clusters_with_three_or_more_not_person_feedback(&self) -> Result<HashSet<String>> {self.db.read_column(- "SELECT cluster_id FROM not_person_feedback GROUP BY cluster_id HAVING COUNT(*) >= 3",+ r#"+ SELECT cluster_id+ FROM not_person_feedback+ GROUP BY cluster_id+ HAVING COUNT(*) >= 3+ "#,(),).map_err(Into::into)@@ -26,7 +39,12 @@ impl MlDb {pub fn get_person_ignored_clusters(&self, person_id: &str) -> Result<HashSet<String>> {let mut ignored_cluster_ids: HashSet<String> = self.db.read_column(- "SELECT cluster_id FROM cluster_person WHERE person_id != ? AND person_id IS NOT NULL",+ r#"+ SELECT cluster_id+ FROM cluster_person+ WHERE person_id != ?+ AND person_id IS NOT NULL+ "#,[person_id],)?;let reject_cluster_ids: Vec<String> = self.db.read_column(@@ -65,7 +83,12 @@ impl MlDb {pub fn get_person_to_cluster_id_to_face_ids(&self) -> Result<PersonToClusterIdToFaceIds> {let rows: Vec<(String, String, String)> = self.db.read_all(- "SELECT person_id, face_clusters.cluster_id, face_id FROM cluster_person INNER JOIN face_clusters ON cluster_person.cluster_id = face_clusters.cluster_id",+ r#"+ SELECT person_id, face_clusters.cluster_id, face_id+ FROM cluster_person+ INNER JOIN face_clusters+ ON cluster_person.cluster_id = face_clusters.cluster_id+ "#,(),|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),)?;@@ -93,7 +116,13 @@ impl MlDb {) -> Result<HashMap<String, String>> {self.db.read_chunked_in(- "SELECT face_id, person_id FROM cluster_person INNER JOIN face_clusters ON cluster_person.cluster_id = face_clusters.cluster_id WHERE face_id IN ({})",+ r#"+ SELECT face_id, person_id+ FROM cluster_person+ INNER JOIN face_clusters+ ON cluster_person.cluster_id = face_clusters.cluster_id+ WHERE face_id IN ({})+ "#,face_ids,MAX_SQL_BIND_PARAMS_PER_QUERY,pair,@@ -107,7 +136,13 @@ impl MlDb {) -> Result<HashMap<String, HashSet<String>>> {self.db.read_grouped(- "SELECT face_clusters.cluster_id, face_id FROM cluster_person INNER JOIN face_clusters ON cluster_person.cluster_id = face_clusters.cluster_id WHERE person_id = ?",+ r#"+ SELECT face_clusters.cluster_id, face_id+ FROM cluster_person+ INNER JOIN face_clusters+ ON cluster_person.cluster_id = face_clusters.cluster_id+ WHERE person_id = ?+ "#,[person_id],).map_err(Into::into)@@ -116,7 +151,13 @@ impl MlDb {pub fn get_face_ids_for_person(&self, person_id: &str) -> Result<HashSet<String>> {self.db.read_column(- "SELECT face_id FROM face_clusters LEFT JOIN cluster_person ON face_clusters.cluster_id = cluster_person.cluster_id WHERE cluster_person.person_id = ?",+ r#"+ SELECT face_id+ FROM face_clusters+ LEFT JOIN cluster_person+ ON face_clusters.cluster_id = cluster_person.cluster_id+ WHERE cluster_person.person_id = ?+ "#,[person_id],).map_err(Into::into)@@ -129,7 +170,17 @@ impl MlDb {) -> Result<Vec<String>> {self.db.read_column(- "SELECT faces.face_id FROM faces JOIN face_clusters ON faces.face_id = face_clusters.face_id JOIN cluster_person ON face_clusters.cluster_id = cluster_person.cluster_id WHERE cluster_person.person_id = ? ORDER BY faces.score DESC LIMIT ?",+ r#"+ SELECT faces.face_id+ FROM faces+ JOIN face_clusters+ ON faces.face_id = face_clusters.face_id+ JOIN cluster_person+ ON face_clusters.cluster_id = cluster_person.cluster_id+ WHERE cluster_person.person_id = ?+ ORDER BY faces.score DESC+ LIMIT ?+ "#,(person_id, limit),).map_err(Into::into)@@ -162,7 +213,7 @@ impl MlDb {cluster_to_person_id: &HashMap<String, String>,) -> Result<()> {self.db- .write_batch(+ .write_batch_atomic(INSERT_CLUSTER_PERSON,cluster_to_person_id.iter()@@ -182,7 +233,7 @@ impl MlDb {cluster_to_person_id: &HashMap<String, String>,) -> Result<()> {self.db- .write_batch(+ .write_batch_atomic(INSERT_NOT_PERSON_FEEDBACK,cluster_to_person_id.iter()@@ -213,7 +264,13 @@ impl MlDb {) -> Result<HashMap<i64, HashSet<String>>> {self.db.read_all(- "SELECT face_clusters.cluster_id, face_id FROM face_clusters INNER JOIN cluster_person ON face_clusters.cluster_id = cluster_person.cluster_id WHERE cluster_person.person_id = ?",+ r#"+ SELECT face_clusters.cluster_id, face_id+ FROM face_clusters+ INNER JOIN cluster_person+ ON face_clusters.cluster_id = cluster_person.cluster_id+ WHERE cluster_person.person_id = ?+ "#,[person_id],pair,)@@ -245,7 +302,15 @@ impl MlDb {pub fn get_file_ids_of_person_id(&self, person_id: &str) -> Result<Vec<i64>> {self.db.read_column(- "SELECT DISTINCT faces.file_id FROM cluster_person JOIN face_clusters ON cluster_person.cluster_id = face_clusters.cluster_id JOIN faces ON face_clusters.face_id = faces.face_id WHERE cluster_person.person_id = ?",+ r#"+ SELECT DISTINCT faces.file_id+ FROM cluster_person+ JOIN face_clusters+ ON cluster_person.cluster_id = face_clusters.cluster_id+ JOIN faces+ ON face_clusters.face_id = faces.face_id+ WHERE cluster_person.person_id = ?+ "#,[person_id],).map_err(Into::into)@@ -253,14 +318,14 @@ impl MlDb {}#[cfg(test)]-pub(super) mod tests {+pub(in crate::ml_db) mod tests {use std::collections::HashMap;use super::MlDb;+ use crate::ml_db::queries::{clusters, faces};use crate::ml_db::tests::{cases, check, grouped, grouped_by_file, map, open, set, sorted, strings,};- use crate::ml_db::{clusters, faces};use tempfile::TempDir;pub(in crate::ml_db) fn seed(db: &MlDb) {diff --git a/rust/crates/photos/src/ml_db/pets.rs b/rust/crates/photos/src/ml_db/queries/pets.rssimilarity index 76%rename from rust/crates/photos/src/ml_db/pets.rsrename to rust/crates/photos/src/ml_db/queries/pets.rsindex a861f6d489..3f2e0b2150 100644--- a/rust/crates/photos/src/ml_db/pets.rs+++ b/rust/crates/photos/src/ml_db/queries/pets.rs@@ -2,16 +2,92 @@ use std::collections::HashMap;use crate::db::{Row, SqliteResult, bind_placeholders, pair, params_from_iter};-use super::queries::{PetBodyRow, PetBodyVectorRow, PetFaceRow, PetFaceVectorRow, PetRowsForFiles};-use super::{MlDb, Result, non_empty, unique_in_order};+use super::unique_in_order;+use crate::ml_db::{MlDb, Result};++pub const PET_ML_VERSION: i64 = 1;++#[derive(Clone, Debug, PartialEq)]+pub struct PetFaceRow {+ pub file_id: i64,+ pub pet_face_id: String,+ pub detection_json: String,+ pub face_vector_id: Option<i64>,+ pub species: i64,+ pub face_score: f64,+ pub image_height: i64,+ pub image_width: i64,+ pub ml_version: i64,+}++#[derive(Clone, Debug, PartialEq)]+pub struct PetBodyRow {+ pub file_id: i64,+ pub pet_body_id: String,+ pub detection_json: String,+ pub body_vector_id: Option<i64>,+ pub species: i64,+ pub score: f64,+ pub image_height: i64,+ pub image_width: i64,+ pub ml_version: i64,+}++#[derive(Clone, Debug, PartialEq)]+pub struct PetFaceVectorRow {+ pub pet_face_id: String,+ pub face_vector_id: Option<i64>,+ pub species: i64,+}++#[derive(Clone, Debug, PartialEq)]+pub struct PetBodyVectorRow {+ pub pet_body_id: String,+ pub body_vector_id: Option<i64>,+ pub species: i64,+}++#[derive(Clone, Debug, PartialEq)]+pub struct PetRowsForFiles {+ pub faces: Vec<PetFaceVectorRow>,+ pub bodies: Vec<PetBodyVectorRow>,+}-const UPSERT_PET_FACE: &str = "INSERT INTO pet_faces (file_id, pet_face_id, detection, face_vector_id, species, score, height, width, ml_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(file_id, pet_face_id) DO UPDATE SET detection = excluded.detection, face_vector_id = excluded.face_vector_id, species = excluded.species, score = excluded.score, height = excluded.height, width = excluded.width, ml_version = excluded.ml_version";-const UPSERT_PET_BODY: &str = "INSERT INTO pet_bodies (file_id, pet_body_id, detection, body_vector_id, species, score, height, width, ml_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(file_id, pet_body_id) DO UPDATE SET detection = excluded.detection, body_vector_id = excluded.body_vector_id, species = excluded.species, score = excluded.score, height = excluded.height, width = excluded.width, ml_version = excluded.ml_version";+const UPSERT_PET_FACE: &str = r#"+ INSERT INTO pet_faces (+ file_id, pet_face_id, detection, face_vector_id, species,+ score, height, width, ml_version+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT (file_id, pet_face_id) DO UPDATE SET+ detection = excluded.detection,+ face_vector_id = excluded.face_vector_id,+ species = excluded.species,+ score = excluded.score,+ height = excluded.height,+ width = excluded.width,+ ml_version = excluded.ml_version+"#;+const UPSERT_PET_BODY: &str = r#"+ INSERT INTO pet_bodies (+ file_id, pet_body_id, detection, body_vector_id, species,+ score, height, width, ml_version+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT (file_id, pet_body_id) DO UPDATE SET+ detection = excluded.detection,+ body_vector_id = excluded.body_vector_id,+ species = excluded.species,+ score = excluded.score,+ height = excluded.height,+ width = excluded.width,+ ml_version = excluded.ml_version+"#;impl MlDb {pub fn bulk_insert_pet_faces(&self, pet_faces: &[PetFaceRow]) -> Result<()> {self.db- .write_in_batches(+ .write_batches_committing_each(UPSERT_PET_FACE,500,pet_faces.iter().map(|pet_face| {@@ -33,7 +109,7 @@ impl MlDb {pub fn bulk_insert_pet_bodies(&self, pet_bodies: &[PetBodyRow]) -> Result<()> {self.db- .write_in_batches(+ .write_batches_committing_each(UPSERT_PET_BODY,500,pet_bodies.iter().map(|pet_body| {@@ -61,7 +137,7 @@ impl MlDb {return Ok(());}self.db- .write_in_batches(+ .write_batches_committing_each("UPDATE pet_faces SET face_vector_id = ? WHERE pet_face_id = ?",500,pet_face_id_to_vector_id@@ -79,7 +155,7 @@ impl MlDb {return Ok(());}self.db- .write_in_batches(+ .write_batches_committing_each("UPDATE pet_bodies SET body_vector_id = ? WHERE pet_body_id = ?",500,pet_body_id_to_vector_id@@ -89,28 +165,24 @@ impl MlDb {.map_err(Into::into)}- pub fn get_pet_faces_for_file_id(- &self,- file_upload_id: i64,- ) -> Result<Option<Vec<PetFaceRow>>> {- let pet_faces = self.db.read_all(- "SELECT * FROM pet_faces WHERE file_id = ? AND species != -1",- [file_upload_id],- read_pet_face,- )?;- Ok(non_empty(pet_faces))+ pub fn get_pet_faces_for_file_id(&self, file_upload_id: i64) -> Result<Vec<PetFaceRow>> {+ self.db+ .read_all(+ "SELECT * FROM pet_faces WHERE file_id = ? AND species != -1",+ [file_upload_id],+ read_pet_face,+ )+ .map_err(Into::into)}- pub fn get_pet_bodies_for_file_id(- &self,- file_upload_id: i64,- ) -> Result<Option<Vec<PetBodyRow>>> {- let pet_bodies = self.db.read_all(- "SELECT * FROM pet_bodies WHERE file_id = ? AND species != -1",- [file_upload_id],- read_pet_body,- )?;- Ok(non_empty(pet_bodies))+ pub fn get_pet_bodies_for_file_id(&self, file_upload_id: i64) -> Result<Vec<PetBodyRow>> {+ self.db+ .read_all(+ "SELECT * FROM pet_bodies WHERE file_id = ? AND species != -1",+ [file_upload_id],+ read_pet_body,+ )+ .map_err(Into::into)}pub fn pet_indexed_file_ids(&self, minimum_ml_version: i64) -> Result<HashMap<i64, i64>> {@@ -135,10 +207,18 @@ impl MlDb {pub fn get_pet_rows_for_files(&self, file_ids: &[i64]) -> Result<PetRowsForFiles> {let placeholders = bind_placeholders(file_ids.len());let faces_sql = format!(- "SELECT pet_face_id, face_vector_id, species FROM pet_faces WHERE file_id IN ({placeholders})"+ r#"+ SELECT pet_face_id, face_vector_id, species+ FROM pet_faces+ WHERE file_id IN ({placeholders})+ "#);let bodies_sql = format!(- "SELECT pet_body_id, body_vector_id, species FROM pet_bodies WHERE file_id IN ({placeholders})"+ r#"+ SELECT pet_body_id, body_vector_id, species+ FROM pet_bodies+ WHERE file_id IN ({placeholders})+ "#);let faces = self.db@@ -210,7 +290,11 @@ impl MlDb {pet_face_ids,create_if_missing,"INSERT OR IGNORE INTO pet_face_vector_id_map (pet_face_id) VALUES (?)",- "SELECT pet_face_id, pet_face_vector_id FROM pet_face_vector_id_map WHERE pet_face_id IN",+ r#"+ SELECT pet_face_id, pet_face_vector_id+ FROM pet_face_vector_id_map+ WHERE pet_face_id IN+ "#,)}@@ -223,7 +307,11 @@ impl MlDb {pet_body_ids,create_if_missing,"INSERT OR IGNORE INTO pet_body_vector_id_map (pet_body_id) VALUES (?)",- "SELECT pet_body_id, pet_body_vector_id FROM pet_body_vector_id_map WHERE pet_body_id IN",+ r#"+ SELECT pet_body_id, pet_body_vector_id+ FROM pet_body_vector_id_map+ WHERE pet_body_id IN+ "#,)}@@ -240,7 +328,7 @@ impl MlDb {}if create_if_missing {self.db- .write_batch(insert_sql, unique_ids.iter().map(|id| [id]))?;+ .write_batch_atomic(insert_sql, unique_ids.iter().map(|id| [id]))?;}let select_sql = select_prefix.to_owned() + " ({})";self.db@@ -278,7 +366,7 @@ fn read_pet_body(row: &Row<'_>) -> SqliteResult<PetBodyRow> {}#[cfg(test)]-pub(super) mod tests {+pub(in crate::ml_db) mod tests {use std::collections::HashMap;use super::{MlDb, PetBodyRow, PetFaceRow};@@ -383,26 +471,23 @@ pub(super) mod tests {};assert_eq!(db.get_pet_faces_for_file_id(1).unwrap(),- Some(vec![linked_pet_face])+ vec![linked_pet_face]);let new_pet_face = PetFaceRow {ml_version: 2,..pet_face(2, 0, 1)};- assert_eq!(- db.get_pet_faces_for_file_id(2).unwrap(),- Some(vec![new_pet_face])- );- assert_eq!(db.get_pet_faces_for_file_id(9).unwrap(), None);+ assert_eq!(db.get_pet_faces_for_file_id(2).unwrap(), vec![new_pet_face]);+ assert!(db.get_pet_faces_for_file_id(9).unwrap().is_empty());let linked_pet_body = PetBodyRow {body_vector_id: Some(1),..pet_body(1, 0, 0)};assert_eq!(db.get_pet_bodies_for_file_id(1).unwrap(),- Some(vec![linked_pet_body])+ vec![linked_pet_body]);- assert_eq!(db.get_pet_bodies_for_file_id(3).unwrap(), None);+ assert!(db.get_pet_bodies_for_file_id(3).unwrap().is_empty());let rows = db.get_pet_rows_for_files(&[1, 3]).unwrap();let faces: Vec<(&str, Option<i64>, i64)> = rows@@ -434,14 +519,11 @@ pub(super) mod tests {};db.bulk_insert_pet_faces(std::slice::from_ref(&updated)).unwrap();- assert_eq!(- db.get_pet_faces_for_file_id(2).unwrap(),- Some(vec![updated])- );+ assert_eq!(db.get_pet_faces_for_file_id(2).unwrap(), vec![updated]);db.bulk_insert_pet_bodies(&[pet_body(2, 0, 1)]).unwrap();assert_eq!(db.get_pet_bodies_for_file_id(2).unwrap(),- Some(vec![pet_body(2, 0, 1)])+ vec![pet_body(2, 0, 1)]);let face_vector_ids = db@@ -457,7 +539,7 @@ pub(super) mod tests {db.update_pet_body_vector_ids(&HashMap::new()).unwrap();db.update_pet_face_vector_ids(&face_vector_ids).unwrap();assert_eq!(- db.get_pet_faces_for_file_id(2).unwrap().unwrap()[0].face_vector_id,+ db.get_pet_faces_for_file_id(2).unwrap()[0].face_vector_id,Some(3));@@ -467,8 +549,8 @@ pub(super) mod tests {&strings(["1_body_0"]),).unwrap();- assert_eq!(db.get_pet_faces_for_file_id(1).unwrap(), None);- assert_eq!(db.get_pet_bodies_for_file_id(1).unwrap(), None);+ assert!(db.get_pet_faces_for_file_id(1).unwrap().is_empty());+ assert!(db.get_pet_bodies_for_file_id(1).unwrap().is_empty());assert!(db.get_pet_face_vector_id_map(&strings(["1_pet_0", "1_pet_1"]), false).unwrap()@@ -480,8 +562,8 @@ pub(super) mod tests {.is_empty());db.delete_pet_rows_for_files(&[2], &[], &[]).unwrap();- assert_eq!(db.get_pet_faces_for_file_id(2).unwrap(), None);- assert_eq!(db.get_pet_bodies_for_file_id(2).unwrap(), None);+ assert!(db.get_pet_faces_for_file_id(2).unwrap().is_empty());+ assert!(db.get_pet_bodies_for_file_id(2).unwrap().is_empty());assert_eq!(db.get_pet_face_vector_id_map(&strings(["2_pet_0"]), false).unwrap(),