π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Organize ML database types and fixtures by feature
laurenspriem139ce8bda5a0
diff --git a/rust/crates/photos/src/ml_db/caches.rs b/rust/crates/photos/src/ml_db/caches.rsindex 16876d4b5e..dead632342 100644--- a/rust/crates/photos/src/ml_db/caches.rs+++ b/rust/crates/photos/src/ml_db/caches.rs@@ -1,9 +1,8 @@use std::time::{SystemTime, UNIX_EPOCH};-use super::MlDb;+use super::clip::CLIP_ML_VERSION;use super::codec::{decode_f32, encode_f32};-use super::constants::CLIP_ML_VERSION;-use super::error::Result;+use super::{MlDb, Result};const THREE_MONTHS_MILLIS: i64 = 90 * 24 * 60 * 60 * 1000;@@ -84,21 +83,43 @@ fn now_millis() -> i64 {}#[cfg(test)]-mod tests {+pub(super) mod tests {+ use super::MlDb;use crate::db::Connection;- use crate::ml_db::tests::{cases, check_seeded, seeded};+ use crate::ml_db::tests::{cases, check, open};+ use tempfile::TempDir;++ pub(in crate::ml_db) fn seed(db: &MlDb) {+ db.put_repeated_text_embedding_cache("dog", &[0.5, -1.0])+ .unwrap();+ db.put_face_id_cached_for_person_or_cluster("p1", "1_0")+ .unwrap();+ }++ fn seeded() -> (TempDir, MlDb) {+ let (directory, db) = open();+ seed(&db);+ (directory, db)+ }#[test]fn seeded_optional_values() {- check_seeded(&cases![- "cached face p1": Some("1_0".to_string()) =>- |db| db.get_face_id_used_for_person_or_cluster("p1"),- "cached face p2": None => |db| db.get_face_id_used_for_person_or_cluster("p2"),- ]);- check_seeded(&cases![- "cached dog": Some(vec![0.5, -1.0]) => |db| db.get_repeated_text_embedding_cache("dog"),- "uncached cat": None => |db| db.get_repeated_text_embedding_cache("cat"),- ]);+ let (_directory, db) = seeded();+ check(+ &db,+ &cases![+ "cached face p1": Some("1_0".to_string()) =>+ |db| db.get_face_id_used_for_person_or_cluster("p1"),+ "cached face p2": None => |db| db.get_face_id_used_for_person_or_cluster("p2"),+ ],+ );+ check(+ &db,+ &cases![+ "cached dog": Some(vec![0.5, -1.0]) => |db| db.get_repeated_text_embedding_cache("dog"),+ "uncached cat": None => |db| db.get_repeated_text_embedding_cache("cat"),+ ],+ );}#[test]diff --git a/rust/crates/photos/src/ml_db/clip.rs b/rust/crates/photos/src/ml_db/clip.rsindex fb96473ac3..f742fc35c1 100644--- a/rust/crates/photos/src/ml_db/clip.rs+++ b/rust/crates/photos/src/ml_db/clip.rs@@ -2,12 +2,32 @@ use std::collections::HashMap;use crate::db::pair;-use super::MlDb;use super::codec::{decode_f32, encode_f32};-use super::constants::CLIP_EMBEDDING_BYTES_LENGTH;-use super::error::Result;use super::schema::DELETE_CLIP_EMBEDDINGS;-use super::types::{ClipEmbedding, ClipRow, EmbeddingVector};+use super::{MlDb, Result};++pub const CLIP_ML_VERSION: i64 = 1;+pub const CLIP_EMBEDDING_DIMENSIONS: usize = 512;+pub const CLIP_EMBEDDING_BYTES_LENGTH: i64 = CLIP_EMBEDDING_DIMENSIONS as i64 * 4;++#[derive(Clone, Debug, PartialEq)]+pub struct ClipEmbedding {+ pub file_id: i64,+ pub embedding: Vec<f64>,+ pub version: i64,+}++#[derive(Clone, Debug, PartialEq)]+pub struct EmbeddingVector {+ pub file_id: i64,+ pub embedding: Vec<f32>,+}++#[derive(Clone, Debug, PartialEq)]+pub struct ClipRow {+ pub file_id: i64,+ pub embedding: Vec<u8>,+}impl MlDb {pub fn get_all_clip_vectors(&self) -> Result<Vec<EmbeddingVector>> {@@ -107,31 +127,70 @@ fn clip_row(embedding: &ClipEmbedding) -> (i64, Vec<u8>, i64) {}#[cfg(test)]-mod tests {+pub(super) mod tests {use std::collections::HashMap;- use super::ClipRow;+ use super::{CLIP_EMBEDDING_DIMENSIONS, ClipEmbedding, ClipRow, MlDb};use crate::ml_db::codec::encode_f32;- use crate::ml_db::constants::CLIP_EMBEDDING_DIMENSIONS;- use crate::ml_db::tests::{cases, check_seeded, clip, full_clip, seeded};+ use crate::ml_db::tests::{cases, check, open};+ use tempfile::TempDir;++ fn clip(file_id: i64, embedding: Vec<f64>) -> ClipEmbedding {+ ClipEmbedding {+ file_id,+ embedding,+ version: 1,+ }+ }++ pub(in crate::ml_db) fn full_clip(file_id: i64) -> ClipEmbedding {+ clip(file_id, vec![0.25; CLIP_EMBEDDING_DIMENSIONS])+ }++ pub(in crate::ml_db) fn seed(db: &MlDb) {+ db.insert_clip_rows(&[+ full_clip(1),+ ClipEmbedding {+ version: 2,+ ..full_clip(2)+ },+ clip(3, vec![1.0, 2.0]),+ clip(4, vec![]),+ ])+ .unwrap();+ }++ fn seeded() -> (TempDir, MlDb) {+ let (directory, db) = open();+ seed(&db);+ (directory, db)+ }#[test]fn seeded_counts() {- check_seeded(&cases![- "clip files": 4 => |db| db.get_clip_indexed_file_count(1),- "clip files v2": 1 => |db| db.get_clip_indexed_file_count(2),- "clip vectorizable": 2 => |db| db.get_clip_vectorizable_file_count(1),- "clip vectorizable v2": 1 => |db| db.get_clip_vectorizable_file_count(2),- "clip rows": 4 => |db| db.count_clip_rows(),- ]);+ let (_directory, db) = seeded();+ check(+ &db,+ &cases![+ "clip files": 4 => |db| db.get_clip_indexed_file_count(1),+ "clip files v2": 1 => |db| db.get_clip_indexed_file_count(2),+ "clip vectorizable": 2 => |db| db.get_clip_vectorizable_file_count(1),+ "clip vectorizable v2": 1 => |db| db.get_clip_vectorizable_file_count(2),+ "clip rows": 4 => |db| db.count_clip_rows(),+ ],+ );}#[test]fn seeded_versions() {- check_seeded(&cases![- "clip versions": HashMap::from([(1, 1), (2, 2), (3, 1), (4, 1)]) =>- |db| db.clip_indexed_file_with_version(),- ]);+ let (_directory, db) = seeded();+ check(+ &db,+ &cases![+ "clip versions": HashMap::from([(1, 1), (2, 2), (3, 1), (4, 1)]) =>+ |db| db.clip_indexed_file_with_version(),+ ],+ );}#[test]diff --git a/rust/crates/photos/src/ml_db/codec.rs b/rust/crates/photos/src/ml_db/codec.rsindex 205b110984..b6811a6586 100644--- a/rust/crates/photos/src/ml_db/codec.rs+++ b/rust/crates/photos/src/ml_db/codec.rs@@ -1,4 +1,4 @@-use super::error::{Error, Result};+use super::{Error, Result};const EVECTOR_VALUES_PACKED_TAG: u64 = 0x0A;const EVECTOR_VALUES_FIXED64_TAG: u64 = 0x09;diff --git a/rust/crates/photos/src/ml_db/constants.rs b/rust/crates/photos/src/ml_db/constants.rsindex 320bd50a63..00e646f591 100644--- a/rust/crates/photos/src/ml_db/constants.rs+++ b/rust/crates/photos/src/ml_db/constants.rs@@ -1,10 +1,6 @@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;diff --git a/rust/crates/photos/src/ml_db/error.rs b/rust/crates/photos/src/ml_db/error.rsdeleted file mode 100644index 9efb76a0d4..0000000000--- a/rust/crates/photos/src/ml_db/error.rs+++ /dev/null@@ -1,13 +0,0 @@-#[derive(Debug, thiserror::Error)]-pub enum Error {- #[error(transparent)]- Database(#[from] crate::db::Error),- #[error("{0}")]- Codec(String),- #[error(transparent)]- Io(#[from] std::io::Error),- #[error("{0}")]- InvalidArgument(String),-}--pub type Result<T> = std::result::Result<T, Error>;diff --git a/rust/crates/photos/src/ml_db/filedata.rs b/rust/crates/photos/src/ml_db/filedata.rsindex a6cc193e27..9d15618a51 100644--- a/rust/crates/photos/src/ml_db/filedata.rs+++ b/rust/crates/photos/src/ml_db/filedata.rs@@ -2,9 +2,24 @@ use std::collections::{HashMap, HashSet};use crate::db::optional_parameter;-use super::MlDb;-use super::error::Result;-use super::types::{FdStatus, PreviewInfo};+use super::{MlDb, Result};++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct FdStatus {+ pub file_id: i64,+ pub user_id: i64,+ pub data_type: String,+ pub size: i64,+ pub object_id: Option<String>,+ pub object_nonce: Option<String>,+ pub updated_at: i64,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct PreviewInfo {+ pub object_id: String,+ pub object_size: i64,+}impl MlDb {pub fn put_fd_status(&self, fd_status_list: &[FdStatus]) -> Result<()> {@@ -57,25 +72,73 @@ impl MlDb {}#[cfg(test)]-mod tests {- use std::collections::HashMap;+pub(super) mod tests {+ use std::collections::{HashMap, HashSet};++ use super::{FdStatus, MlDb, PreviewInfo};+ use crate::ml_db::tests::{cases, check, open};+ use tempfile::TempDir;++ fn status(file_id: i64, data_type: &str, object_id: Option<&str>) -> FdStatus {+ FdStatus {+ file_id,+ user_id: 42,+ data_type: data_type.to_string(),+ size: file_id * 10,+ object_id: object_id.map(str::to_string),+ object_nonce: None,+ updated_at: 1000,+ }+ }++ fn preview(object_id: &str, object_size: i64) -> PreviewInfo {+ PreviewInfo {+ object_id: object_id.to_string(),+ object_size,+ }+ }++ fn ids<const N: usize>(values: [i64; N]) -> HashSet<i64> {+ HashSet::from(values)+ }++ pub(in crate::ml_db) fn seed(db: &MlDb) {+ db.put_fd_status(&[+ status(1, "vid_preview", Some("obj1")),+ status(2, "mldata", None),+ status(3, "vid_preview", Some("obj3")),+ ])+ .unwrap();+ }- use crate::ml_db::tests::{cases, check_seeded, ids, preview, seeded, status};+ fn seeded() -> (TempDir, MlDb) {+ let (directory, db) = open();+ seed(&db);+ (directory, db)+ }#[test]fn seeded_file_id_sets() {- check_seeded(&cases![- "fd data": ids([1, 2, 3]) => |db| db.get_file_ids_with_fd_data(None),- "fd mldata": ids([2]) => |db| db.get_file_ids_with_fd_data(Some("mldata")),- ]);+ let (_directory, db) = seeded();+ check(+ &db,+ &cases![+ "fd data": ids([1, 2, 3]) => |db| db.get_file_ids_with_fd_data(None),+ "fd mldata": ids([2]) => |db| db.get_file_ids_with_fd_data(Some("mldata")),+ ],+ );}#[test]fn seeded_video_previews() {- check_seeded(&cases![- "video previews": HashMap::from([(1, preview("obj1", 10)), (3, preview("obj3", 30))]) =>- |db| db.get_file_ids_vid_preview(),- ]);+ let (_directory, db) = seeded();+ check(+ &db,+ &cases![+ "video previews": HashMap::from([(1, preview("obj1", 10)), (3, preview("obj3", 30))]) =>+ |db| db.get_file_ids_vid_preview(),+ ],+ );}#[test]diff --git a/rust/crates/photos/src/ml_db/mod.rs b/rust/crates/photos/src/ml_db/mod.rsindex fed60fac15..da0932ec43 100644--- a/rust/crates/photos/src/ml_db/mod.rs+++ b/rust/crates/photos/src/ml_db/mod.rs@@ -1,18 +1,44 @@mod caches;mod clip;-pub mod codec;-pub mod constants;-mod error;+mod codec;+mod constants;mod filedata;-pub mod schema;-pub mod types;+mod schema;+mod types;use std::path::Path;use crate::db::Database;-pub use error::{Error, Result};-pub use types::*;+pub use clip::{+ CLIP_EMBEDDING_BYTES_LENGTH, CLIP_EMBEDDING_DIMENSIONS, CLIP_ML_VERSION, ClipEmbedding,+ ClipRow, EmbeddingVector,+};+pub use codec::{decode_evector, decode_f32, encode_evector, encode_f32};+pub use constants::{+ FACE_ML_VERSION, LAPLACIAN_HARD_THRESHOLD, LAPLACIAN_SOFT_THRESHOLD,+ LAPLACIAN_VERY_SOFT_THRESHOLD, MEDIUM_QUALITY_FACE_SCORE, MINIMUM_QUALITY_FACE_SCORE,+ PET_ML_VERSION, is_bad_face_for_clustering,+};+pub use filedata::{FdStatus, PreviewInfo};+pub use types::{+ ClusterCentroidRow, ClusterSummary, FaceDbInfoForClustering, FaceRow, FaceWithoutEmbedding,+ PetBodyRow, PetBodyVectorRow, PetFaceRow, PetFaceVectorRow, PetRowsForFiles,+};++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error(transparent)]+ Database(#[from] crate::db::Error),+ #[error("{0}")]+ Codec(String),+ #[error(transparent)]+ Io(#[from] std::io::Error),+ #[error("{0}")]+ InvalidArgument(String),+}++pub type Result<T> = std::result::Result<T, Error>;pub const TARGET_VERSION: i64 = schema::MIGRATION_SCRIPTS.len() as i64;@@ -60,10 +86,9 @@ mod tests {use std::fmt::Debug;use std::path::Path;+ use super::clip::tests::full_clip;+ use super::{Error, MlDb, TARGET_VERSION, caches, clip, filedata};use crate::db::Connection;- use crate::ml_db::constants::CLIP_EMBEDDING_DIMENSIONS;- use crate::ml_db::schema::ALL_TABLES;- use crate::ml_db::{ClipEmbedding, Error, FdStatus, MlDb, PreviewInfo, TARGET_VERSION};use tempfile::TempDir;type Query<T> = fn(&MlDb) -> Result<T, Error>;@@ -76,7 +101,7 @@ mod tests {pub(super) use cases;- fn open() -> (TempDir, MlDb) {+ pub(super) fn open() -> (TempDir, MlDb) {let directory = tempfile::tempdir().unwrap();let db = MlDb::open(directory.path().join("ente.ml.db")).unwrap();(directory, db)@@ -100,70 +125,17 @@ mod tests {.unwrap()}- pub(super) fn clip(file_id: i64, embedding: Vec<f64>) -> ClipEmbedding {- ClipEmbedding {- file_id,- embedding,- version: 1,- }- }-- pub(super) fn full_clip(file_id: i64) -> ClipEmbedding {- clip(file_id, vec![0.25; CLIP_EMBEDDING_DIMENSIONS])- }-- pub(super) fn status(file_id: i64, data_type: &str, object_id: Option<&str>) -> FdStatus {- FdStatus {- file_id,- user_id: 42,- data_type: data_type.to_string(),- size: file_id * 10,- object_id: object_id.map(str::to_string),- object_nonce: None,- updated_at: 1000,- }- }-- pub(super) fn preview(object_id: &str, object_size: i64) -> PreviewInfo {- PreviewInfo {- object_id: object_id.to_string(),- object_size,- }- }-- pub(super) fn ids<const N: usize>(values: [i64; N]) -> HashSet<i64> {- HashSet::from(values)- }-- pub(super) fn check_seeded<T: PartialEq + Debug>(cases: &[(&str, T, Query<T>)]) {- let (_directory, db) = seeded();+ pub(super) fn check<T: PartialEq + Debug>(db: &MlDb, cases: &[(&str, T, Query<T>)]) {for (name, expected, query) in cases {- assert_eq!(&query(&db).unwrap(), expected, "{name}");+ assert_eq!(&query(db).unwrap(), expected, "{name}");}}- pub(super) fn seeded() -> (TempDir, MlDb) {+ fn seeded() -> (TempDir, MlDb) {let (directory, db) = open();- db.insert_clip_rows(&[- full_clip(1),- ClipEmbedding {- version: 2,- ..full_clip(2)- },- clip(3, vec![1.0, 2.0]),- clip(4, vec![]),- ])- .unwrap();- db.put_fd_status(&[- status(1, "vid_preview", Some("obj1")),- status(2, "mldata", None),- status(3, "vid_preview", Some("obj3")),- ])- .unwrap();- db.put_repeated_text_embedding_cache("dog", &[0.5, -1.0])- .unwrap();- db.put_face_id_cached_for_person_or_cluster("p1", "1_0")- .unwrap();+ clip::tests::seed(&db);+ filedata::tests::seed(&db);+ caches::tests::seed(&db);(directory, db)}@@ -181,7 +153,22 @@ mod tests {assert_eq!(TARGET_VERSION, 15);assert_eq!(user_version(&path), 15);let connection = Connection::open(&path).unwrap();- for table in ALL_TABLES {+ for table in [+ "faces",+ "face_clusters",+ "cluster_person",+ "cluster_summary",+ "not_person_feedback",+ "clip",+ "filedata",+ "face_cache",+ "text_embeddings_cache",+ "cluster_centroid_vector_id_map",+ "pet_faces",+ "pet_bodies",+ "pet_face_vector_id_map",+ "pet_body_vector_id_map",+ ] {let count: i64 = connection.query_row("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?",@@ -278,7 +265,10 @@ mod tests {assert_eq!(row_count("pet_face_vector_id_map"), 0);assert_eq!(row_count("pet_body_vector_id_map"), 0);assert_eq!(db.count_clip_rows().unwrap(), 4);- assert_eq!(db.get_file_ids_with_fd_data(None).unwrap(), ids([1, 2, 3]));+ 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/schema.rs b/rust/crates/photos/src/ml_db/schema.rsindex 9b80d93469..a2b27cc2a6 100644--- a/rust/crates/photos/src/ml_db/schema.rs+++ b/rust/crates/photos/src/ml_db/schema.rs@@ -1,35 +1,3 @@-pub const FACES_TABLE: &str = "faces";-pub const FACE_CLUSTERS_TABLE: &str = "face_clusters";-pub const CLUSTER_PERSON_TABLE: &str = "cluster_person";-pub const CLUSTER_SUMMARY_TABLE: &str = "cluster_summary";-pub const NOT_PERSON_FEEDBACK_TABLE: &str = "not_person_feedback";-pub const CLIP_TABLE: &str = "clip";-pub const FILEDATA_TABLE: &str = "filedata";-pub const FACE_CACHE_TABLE: &str = "face_cache";-pub const TEXT_EMBEDDINGS_CACHE_TABLE: &str = "text_embeddings_cache";-pub const CLUSTER_CENTROID_VECTOR_ID_MAP_TABLE: &str = "cluster_centroid_vector_id_map";-pub const PET_FACES_TABLE: &str = "pet_faces";-pub const PET_BODIES_TABLE: &str = "pet_bodies";-pub const PET_FACE_VECTOR_ID_MAP_TABLE: &str = "pet_face_vector_id_map";-pub const PET_BODY_VECTOR_ID_MAP_TABLE: &str = "pet_body_vector_id_map";--pub const ALL_TABLES: [&str; 14] = [- FACES_TABLE,- FACE_CLUSTERS_TABLE,- CLUSTER_PERSON_TABLE,- CLUSTER_SUMMARY_TABLE,- NOT_PERSON_FEEDBACK_TABLE,- CLIP_TABLE,- FILEDATA_TABLE,- FACE_CACHE_TABLE,- TEXT_EMBEDDINGS_CACHE_TABLE,- CLUSTER_CENTROID_VECTOR_ID_MAP_TABLE,- PET_FACES_TABLE,- PET_BODIES_TABLE,- PET_FACE_VECTOR_ID_MAP_TABLE,- PET_BODY_VECTOR_ID_MAP_TABLE,-];-pub const CREATE_FACES_TABLE: &str = "CREATE TABLE IF NOT EXISTS faces (file_id INTEGER NOT NULL,face_id TEXT NOT NULL UNIQUE,diff --git a/rust/crates/photos/src/ml_db/types.rs b/rust/crates/photos/src/ml_db/types.rsindex 01671e432b..b7a1a21581 100644--- a/rust/crates/photos/src/ml_db/types.rs+++ b/rust/crates/photos/src/ml_db/types.rs@@ -77,25 +77,6 @@ pub struct PetRowsForFiles {pub bodies: Vec<PetBodyVectorRow>,}-#[derive(Clone, Debug, PartialEq)]-pub struct ClipEmbedding {- pub file_id: i64,- pub embedding: Vec<f64>,- pub version: i64,-}--#[derive(Clone, Debug, PartialEq)]-pub struct EmbeddingVector {- pub file_id: i64,- pub embedding: Vec<f32>,-}--#[derive(Clone, Debug, PartialEq)]-pub struct ClipRow {- pub file_id: i64,- pub embedding: Vec<u8>,-}-#[derive(Clone, Debug, PartialEq, Eq)]pub struct ClusterSummary {pub avg: Vec<u8>,@@ -107,20 +88,3 @@ pub struct ClusterCentroidRow {pub cluster_id: String,pub avg: Vec<u8>,}--#[derive(Clone, Debug, PartialEq, Eq)]-pub struct FdStatus {- pub file_id: i64,- pub user_id: i64,- pub data_type: String,- pub size: i64,- pub object_id: Option<String>,- pub object_nonce: Option<String>,- pub updated_at: i64,-}--#[derive(Clone, Debug, PartialEq, Eq)]-pub struct PreviewInfo {- pub object_id: String,- pub object_size: i64,-}