Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

16.8 KB
Raw Blame
mod clip_scan;
mod cluster_averages;
mod clustering;
mod face_distances;
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 clip_scan::{ClipQuery, ClipSimilarity};
pub use cluster_averages::MeanSuggestion;
pub use clustering::{
    ClusteredBucket, FaceClusteringPlan, FaceClusteringRequest, FaceClusteringRun,
};
pub use ente_vecdb::{KeyMatches, Match, SearchParams, Stats};
pub use face_distances::{FaceDistance, MedianQuery, MedianSuggestion, PersonFaces};
pub use fill::{FillOutcome, FillReport};
pub use index::{CLUSTER_CENTROID_DIMENSIONS, Index};
pub use state::FillState;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Database(#[from] crate::ml_db::Error),
    #[error(transparent)]
    Index(#[from] VecDbError),
    #[error("{0}")]
    InvalidArgument(String),
    #[error("{0:?} index is not filled")]
    NotFilled(Index),
}

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>) -> 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, db_path, &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> {
        self.ensure_index_open(index)?;
        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 ensure_index_open(&self, index: Index) -> Result<()> {
        let slot = &self.indexes[index.position()];
        if slot.is_open() {
            return Ok(());
        }
        let _mutations = self.lock_mutations();
        slot.reopen(&self.db)
    }

    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;
        }
        for _ in 0..2 {
            self.ensure_index_open(index)?;
            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::cell::{Cell, RefCell};
    use std::collections::HashMap;
    use std::fs;
    use std::path::{Path, PathBuf};

    use ente_vecdb::{OpenCost, SearchParams, VecDb};
    use tempfile::TempDir;

    use super::{CLUSTER_CENTROID_DIMENSIONS, FillOutcome, FillReport, FillState, Index, MlStore};
    use crate::ml_db::vector_encoding::{decode_evector, encode_evector};
    use crate::ml_db::{CLIP_EMBEDDING_DIMENSIONS, ClipEmbedding, ClusterSummary, FaceRow};

    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)).unwrap()
    }

    pub(super) fn open_with_unusable_clip_index() -> (TempDir, MlStore) {
        let (directory, store) = open();
        fs::create_dir(index_path(&directory, Index::Clip)).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 embedding(degrees: f64) -> Vec<f64> {
        let mut values = vec![0.0; CLUSTER_CENTROID_DIMENSIONS];
        let radians = degrees.to_radians();
        values[0] = radians.cos();
        values[1] = radians.sin();
        values
    }

    pub(super) fn face(file_id: i64, degrees: f64) -> FaceRow {
        FaceRow {
            file_id,
            face_id: format!("{file_id}_0"),
            detection_json: "{}".to_string(),
            embedding: embedding(degrees),
            score: 0.9,
            blur: 300.0,
            is_sideways: false,
            image_height: 100,
            image_width: 100,
            ml_version: 1,
        }
    }

    pub(super) fn seed(store: &MlStore, faces: &[(i64, f64)]) {
        let rows: Vec<FaceRow> = faces
            .iter()
            .map(|&(file_id, degrees)| face(file_id, degrees))
            .collect();
        store.db().bulk_insert_faces(&rows).unwrap();
    }

    pub(super) fn assign(store: &MlStore, assignments: &[(i64, &str)]) {
        let assignments: HashMap<String, String> = assignments
            .iter()
            .map(|&(file_id, cluster_id)| (format!("{file_id}_0"), cluster_id.to_string()))
            .collect();
        store
            .db()
            .update_face_id_to_cluster_id(&assignments)
            .unwrap();
    }

    pub(super) fn summary_of(store: &MlStore, cluster_id: &str) -> (Vec<f64>, i64) {
        let summary = store
            .db()
            .get_cluster_to_cluster_summary(&[cluster_id.to_string()])
            .unwrap()
            .remove(cluster_id)
            .unwrap();
        (decode_evector(&summary.avg).unwrap(), summary.count)
    }

    pub(super) fn assert_direction(actual: &[f64], degrees: f64) {
        let expected = embedding(degrees);
        for (actual, expected) in actual.iter().zip(&expected) {
            assert!((actual - expected).abs() < 1e-5, "{actual} != {expected}");
        }
    }

    pub(super) fn nearest(store: &MlStore, index: Index, query: &[f32]) -> String {
        let params = SearchParams {
            limit: Some(1),
            ..SearchParams::default()
        };
        store.search(index, query, &params).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,
        }
    }

    #[cfg(unix)]
    pub(super) fn degrade_clip_index_through_a_failed_compaction(
        directory: &TempDir,
        store: &MlStore,
    ) {
        store.put_clip(&clips(0..70)).unwrap();
        let log = index_path(directory, Index::Clip);
        fs::remove_file(&log).unwrap();
        fs::create_dir(&log).unwrap();
        store.delete_clip(&(0..65).collect::<Vec<_>>()).unwrap();
        fs::remove_dir(&log).unwrap();
    }

    pub(super) fn lose_index_files(store: &MlStore, path: &Path) {
        store.release().unwrap();
        VecDb::purge(path).unwrap();
    }

    pub(super) fn create_usearch_files(directory: &TempDir, name: &str) -> [PathBuf; 2] {
        let index_file = directory.path().join(name);
        let save_temp_file = index_file.with_extension("tmp.1.2");
        [index_file, save_temp_file].map(|path| {
            fs::write(&path, b"usearch").unwrap();
            path
        })
    }

    pub(super) fn all_exist(paths: &[PathBuf]) -> bool {
        paths.iter().all(|path| path.exists())
    }

    fn clear_and_repopulate(writer: &MlStore, file_id: i64) {
        writer.clear_all().unwrap();
        writer.put_clip(&clips([file_id])).unwrap();
        writer.fill_clip_index(false).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
        );
    }

    #[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 cold_reads_open_the_index_and_keep_it_open() {
        let (directory, writer) = open();
        writer.fill_clip_index(false).unwrap();
        writer.put_clip(&clips([1, 2])).unwrap();
        writer.release().unwrap();
        drop(writer);

        let reader = open_in(&directory);
        assert!(reader.contains(Index::Clip, "1").unwrap());
        reader.put_clip(&clips([3])).unwrap();
        let unflushed = reader.stats(Index::Clip).unwrap();
        assert_ne!(unflushed.records_since_snapshot, 0);

        assert!(reader.contains(Index::Clip, "3").unwrap());
        assert_eq!(live_count(&reader, Index::Clip), 3);
        assert_eq!(reader.stats(Index::Clip).unwrap(), unflushed);
    }

    #[test]
    fn cold_reads_run_outside_the_mutation_lock() {
        let (directory, writer) = open();
        writer.fill_clip_index(false).unwrap();
        writer.put_clip(&clips([1])).unwrap();
        writer.release().unwrap();

        let reader = open_in(&directory);
        let lock_is_free = || reader.locks.mutations.try_lock().is_ok();
        let found_unlocked = |key: &str| {
            reader
                .read_index(Index::Clip, |vecdb| {
                    vecdb.contains(key).map(|found| (found, lock_is_free()))
                })
                .unwrap()
        };
        assert_eq!(found_unlocked("1"), (true, true));

        writer.clear_all().unwrap();
        writer.put_clip(&clips([2])).unwrap();
        writer.fill_clip_index(false).unwrap();
        assert_eq!(found_unlocked("2"), (true, true));
    }

    #[test]
    fn cold_reads_closed_during_the_read_retry_outside_the_mutation_lock() {
        let (directory, writer) = open();
        writer.fill_clip_index(false).unwrap();
        writer.put_clip(&clips([1])).unwrap();
        writer.release().unwrap();

        let reader = open_in(&directory);
        let lock_is_free = || reader.locks.mutations.try_lock().is_ok();
        let invocations = Cell::new(0);
        let outcome = reader
            .read_index(Index::Clip, |vecdb| {
                invocations.set(invocations.get() + 1);
                if invocations.get() == 1 {
                    clear_and_repopulate(&writer, 2);
                }
                vecdb.contains("2").map(|found| (found, lock_is_free()))
            })
            .unwrap();
        assert_eq!(invocations.get(), 2);
        assert_eq!(outcome, (true, true));
    }

    #[test]
    fn reads_closed_in_every_unlocked_attempt_fall_back_to_the_locked_path() {
        let (directory, writer) = open();
        writer.fill_clip_index(false).unwrap();
        writer.put_clip(&clips([1])).unwrap();
        writer.release().unwrap();

        let reader = open_in(&directory);
        let lock_is_free = || reader.locks.mutations.try_lock().is_ok();
        let lock_free_per_invocation = RefCell::new(Vec::new());
        let found = reader
            .read_index(Index::Clip, |vecdb| {
                let unlocked = lock_is_free();
                lock_free_per_invocation.borrow_mut().push(unlocked);
                if unlocked {
                    clear_and_repopulate(&writer, 2);
                }
                vecdb.contains("2")
            })
            .unwrap();
        assert!(found);
        assert_eq!(
            *lock_free_per_invocation.borrow(),
            [true, true, false, false]
        );
    }

    #[test]
    fn ml_store_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<MlStore>();
    }
}