π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[rust] Default VecDB indexes to cosine distance
laurenspriem4186a2b8d4c6
diff --git a/rust/bindings/frb/photos/src/api/vecdb_api.rs b/rust/bindings/frb/photos/src/api/vecdb_api.rsindex a5e21b971f..c7df5bf8b3 100644--- a/rust/bindings/frb/photos/src/api/vecdb_api.rs+++ b/rust/bindings/frb/photos/src/api/vecdb_api.rs@@ -18,6 +18,7 @@ pub enum RustVecDbError {UnboundedSearch { message: String },LengthMismatch { message: String },StorageMismatch { message: String },+ MetricMismatch { message: String },}impl From<vecdb::VecDbError> for RustVecDbError {@@ -37,6 +38,7 @@ impl From<vecdb::VecDbError> for RustVecDbError {vecdb::VecDbError::UnboundedSearch => Self::UnboundedSearch { message },vecdb::VecDbError::LengthMismatch { .. } => Self::LengthMismatch { message },vecdb::VecDbError::StorageMismatch { .. } => Self::StorageMismatch { message },+ vecdb::VecDbError::MetricMismatch { .. } => Self::MetricMismatch { message },}}}@@ -61,6 +63,26 @@ fn to_api_storage(storage: vecdb::StorageKind) -> VecDbStorage {}}+#[derive(Clone, Copy, Debug)]+pub enum VecDbMetric {+ InnerProduct,+ Cosine,+}++fn to_engine_metric(metric: VecDbMetric) -> vecdb::DistanceMetric {+ match metric {+ VecDbMetric::InnerProduct => vecdb::DistanceMetric::InnerProduct,+ VecDbMetric::Cosine => vecdb::DistanceMetric::Cosine,+ }+}++fn to_api_metric(metric: vecdb::DistanceMetric) -> VecDbMetric {+ match metric {+ vecdb::DistanceMetric::InnerProduct => VecDbMetric::InnerProduct,+ vecdb::DistanceMetric::Cosine => VecDbMetric::Cosine,+ }+}+#[derive(Clone, Debug)]pub enum VecDbAttrValue {Str(String),@@ -124,6 +146,7 @@ pub struct VecDbStats {pub dead_count: u32,pub dims: u32,pub storage: VecDbStorage,+ pub metric: VecDbMetric,pub log_bytes: u64,pub records_since_snapshot: u32,pub approximate_memory_bytes: u64,@@ -169,15 +192,16 @@ impl VecDb {file_path: String,dimensions: u32,storage: Option<VecDbStorage>,+ metric: Option<VecDbMetric>,) -> Result<Self, RustVecDbError> {let path = Path::new(&file_path);let dims = dimensions as usize;- let inner = match storage {- Some(storage) => {- vecdb::VecDb::open_with_storage(path, dims, to_engine_storage(storage))?- }- None => vecdb::VecDb::open(path, dims)?,- };+ let inner = vecdb::VecDb::open_with(+ path,+ dims,+ storage.map(to_engine_storage),+ metric.map(to_engine_metric),+ )?;Ok(Self { inner })}@@ -357,6 +381,7 @@ impl VecDb {dead_count: stats.dead_count as u32,dims: stats.dims as u32,storage: to_api_storage(stats.storage),+ metric: to_api_metric(stats.metric),log_bytes: stats.log_bytes,records_since_snapshot: stats.records_since_snapshot as u32,approximate_memory_bytes: stats.approximate_memory_bytes as u64,@@ -410,10 +435,56 @@ mod tests {name.to_string()}+ #[test]+ fn metric_defaults_to_cosine_and_explicit_inner_product_is_immutable() {+ let dir = TestDir::create();+ let db = VecDb::new(dir.db_path(), 32, None, None).unwrap();+ assert!(matches!(+ db.get_index_stats().unwrap().metric,+ VecDbMetric::Cosine+ ));+ assert!(matches!(+ VecDb::new(dir.db_path(), 32, None, Some(VecDbMetric::InnerProduct)),+ Err(RustVecDbError::MetricMismatch { .. })+ ));+ drop(db);+ let dir = TestDir::create();+ let db = VecDb::new(+ dir.db_path(),+ DIMS,+ Some(VecDbStorage::F32),+ Some(VecDbMetric::InnerProduct),+ )+ .unwrap();+ let vector: Vec<f32> = basis(0).iter().map(|value| value * 3.0).collect();+ db.add_vector(key("a"), vector.clone()).unwrap();+ assert_eq!(+ db.search(vector.clone(), Some(1), None, true, None)+ .unwrap()[0]+ .distance,+ -8.0+ );+ db.flush().unwrap();+ drop(db);+ assert!(matches!(+ VecDb::new(dir.db_path(), DIMS, None, Some(VecDbMetric::Cosine)),+ Err(RustVecDbError::MetricMismatch { message }) if message.contains("cosine") && message.contains("inner product")+ ));+ let db = VecDb::new(dir.db_path(), DIMS, None, None).unwrap();+ assert!(matches!(+ db.get_index_stats().unwrap().metric,+ VecDbMetric::InnerProduct+ ));+ assert_eq!(+ db.search(vector, Some(1), None, false, None).unwrap()[0].distance,+ -8.0+ );+ }+#[test]fn add_search_stats_round_trip() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();db.add_vector(key("a"), basis(0)).unwrap();db.bulk_add_vectors(vec![key("b"), key("c")], vec![basis(1), basis(2)]).unwrap();@@ -468,7 +539,7 @@ mod tests {#[test]fn bulk_add_rejects_length_mismatch() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();let error = db.bulk_add_vectors(vec![key("a")], vec![basis(0), basis(1)]).unwrap_err();@@ -479,7 +550,7 @@ mod tests {#[test]fn similarity_threshold_conversion_edges() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();db.add_vector(key("a"), basis(0)).unwrap();db.add_vector(key("b"), basis(1)).unwrap();let close = db@@ -503,7 +574,7 @@ mod tests {#[test]fn bulk_search_within_similarity_honors_per_query_thresholds() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();db.bulk_add_vectors(vec![key("a"), key("b"), key("c")],vec![basis(0), basis(1), basis(2)],@@ -569,7 +640,7 @@ mod tests {#[test]fn bulk_filtered_search_stays_query_aligned() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();db.bulk_add_vectors(vec![key("a"), key("b"), key("c")],vec![basis(0), basis(1), basis(2)],@@ -623,7 +694,7 @@ mod tests {#[test]fn bulk_search_keys_excludes_self_and_honors_the_filters() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();db.bulk_add_vectors(vec![key("a"), key("b"), key("c")],vec![basis(0), basis(1), basis(2)],@@ -661,7 +732,7 @@ mod tests {#[test]fn attrs_round_trip_through_the_api() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();let attrs = vec![VecDbAttr {name: key("model"),@@ -753,7 +824,7 @@ mod tests {check_open_cost(dir.db_path()),VecDbOpenCost::Absent));- let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();db.add_vector(key("a"), basis(0)).unwrap();assert!(matches!(check_open_cost(dir.db_path()),@@ -775,7 +846,7 @@ mod tests {#[test]fn delete_vec_db_files_purges_with_and_without_live_instances() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();db.add_vector(key("a"), basis(0)).unwrap();db.flush().unwrap();delete_vec_db_files(dir.db_path()).unwrap();@@ -786,7 +857,7 @@ mod tests {db.get_index_stats(),Err(RustVecDbError::Closed { .. })));- let reopened = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ let reopened = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32), None).unwrap();assert_eq!(reopened.get_index_stats().unwrap().live_count, 0);reopened.add_vector(key("b"), basis(1)).unwrap();drop(reopened);@@ -806,7 +877,7 @@ mod tests {#[test]fn storage_is_chosen_at_creation_reported_in_stats_and_verified_on_reopen() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), 32, Some(VecDbStorage::I8)).unwrap();+ let db = VecDb::new(dir.db_path(), 32, Some(VecDbStorage::I8), None).unwrap();assert!(matches!(db.get_index_stats().unwrap().storage,VecDbStorage::I8@@ -833,10 +904,10 @@ mod tests {assert_eq!(stats.dims, 32);assert!(matches!(stats.storage, VecDbStorage::I8));assert!(matches!(- VecDb::new(dir.db_path(), 32, Some(VecDbStorage::F32)),+ VecDb::new(dir.db_path(), 32, Some(VecDbStorage::F32), None),Err(RustVecDbError::StorageMismatch { .. })));- let joined = VecDb::new(dir.db_path(), 32, None).unwrap();+ let joined = VecDb::new(dir.db_path(), 32, None, None).unwrap();assert!(matches!(joined.get_index_stats().unwrap().storage,VecDbStorage::I8@@ -852,10 +923,10 @@ mod tests {assert_eq!(read_only.get_index_stats().unwrap().live_count, 3);drop(read_only);assert!(matches!(- VecDb::new(dir.db_path(), 32, Some(VecDbStorage::F32)),+ VecDb::new(dir.db_path(), 32, Some(VecDbStorage::F32), None),Err(RustVecDbError::StorageMismatch { message }) if message.contains("f32") && message.contains("i8")));- let reopened = VecDb::new(dir.db_path(), 32, None).unwrap();+ let reopened = VecDb::new(dir.db_path(), 32, None, None).unwrap();assert!(matches!(reopened.get_index_stats().unwrap().storage,VecDbStorage::I8@@ -867,26 +938,26 @@ mod tests {#[test]fn storage_defaults_to_i8_and_rejects_dims_off_the_lane_grid() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), 32, None).unwrap();+ let db = VecDb::new(dir.db_path(), 32, None, None).unwrap();assert!(matches!(db.get_index_stats().unwrap().storage,VecDbStorage::I8));- let explicit = VecDb::new(dir.db_path(), 32, Some(VecDbStorage::I8)).unwrap();+ let explicit = VecDb::new(dir.db_path(), 32, Some(VecDbStorage::I8), None).unwrap();assert!(matches!(explicit.get_index_stats().unwrap().storage,VecDbStorage::I8));assert!(matches!(- VecDb::new(dir.db_path(), 32, Some(VecDbStorage::F32)),+ VecDb::new(dir.db_path(), 32, Some(VecDbStorage::F32), None),Err(RustVecDbError::StorageMismatch { .. })));let other = TestDir::create();assert!(matches!(- VecDb::new(other.db_path(), DIMS, None),+ VecDb::new(other.db_path(), DIMS, None, None),Err(RustVecDbError::InvalidDimensions { message }) if message.contains("i8") && message.contains("32")));assert!(!PathBuf::from(other.db_path()).exists());- assert!(VecDb::new(other.db_path(), DIMS, Some(VecDbStorage::F32)).is_ok());+ assert!(VecDb::new(other.db_path(), DIMS, Some(VecDbStorage::F32), None).is_ok());}}diff --git a/rust/crates/ml/src/vecdb/README.md b/rust/crates/ml/src/vecdb/README.mdnew file mode 100644index 0000000000..165f7f80dd--- /dev/null+++ b/rust/crates/ml/src/vecdb/README.md@@ -0,0 +1,26 @@+# VecDB index configuration++New indexes default to i8 storage and cosine distance. Storage and distance metric+are persisted at creation and remain unchanged through reopen, compaction, and reset.++`VecDb::open(path, dims)` detects both settings on existing indexes, including older+inner-product indexes. `open_with_storage` and `open_with_metric` select or verify+one setting; `open_with` accepts optional storage and metric together. An explicit+setting that differs from the saved value returns `StorageMismatch` or+`MetricMismatch`. Read-only opens use the saved settings.++```rust+use ente_ml::vecdb::{DistanceMetric, StorageKind, VecDb};++let cosine = VecDb::open(path, 512)?;+let inner_product = VecDb::open_with_metric(other_path, 512, DistanceMetric::InnerProduct)?;+let f32_cosine = VecDb::open_with(third_path, 512, Some(StorageKind::F32), Some(DistanceMetric::Cosine))?;+```++The Flutter constructor exposes optional `storage` and `metric` parameters, and+index stats report both settings.++Cosine distance is `1 - dot(a, b) / (norm(a) * norm(b))`, clamped to `[0, 2]`.+A comparison involving a zero vector has distance `1`, including two zero vectors.+Stored vectors retain their magnitudes; i8 cosine uses the quantized vectors.+Inner-product distance remains `1 - dot(a, b)`.diff --git a/rust/crates/ml/src/vecdb/arena.rs b/rust/crates/ml/src/vecdb/arena.rsindex c1fb37aee4..779a97f272 100644--- a/rust/crates/ml/src/vecdb/arena.rs+++ b/rust/crates/ml/src/vecdb/arena.rs@@ -5,7 +5,7 @@ use super::kernel::{pack_lanes, pack_lanes_i8, pack_lanes_i8_into, pack_lanes_into, quantize_for, unpack_lanes,unpack_lanes_i8, validate_dims,};-use super::{StorageKind, VecDbError};+use super::{DistanceMetric, StorageKind, VecDbError};pub(crate) const VECTORS_PER_CHUNK: usize = 4096;pub(crate) const MAX_KEY_BYTES: usize = 256;@@ -68,17 +68,22 @@ impl Storage {}pub(crate) enum PackedQuery {- F32(Vec<Lane>),- I8 { scale: f32, lanes: Vec<LaneI8> },+ F32(Vec<Lane>, f64),+ I8 {+ scale: f32,+ lanes: Vec<LaneI8>,+ norm: f64,+ },}impl PackedQuery {pub(crate) fn as_query(&self) -> Query<'_> {match self {- Self::F32(lanes) => Query::F32(lanes),- Self::I8 { scale, lanes } => Query::I8 {+ Self::F32(lanes, norm) => Query::F32(lanes, *norm),+ Self::I8 { scale, lanes, norm } => Query::I8 {scale: *scale,lanes,+ norm: *norm,},}}@@ -86,14 +91,18 @@ impl PackedQuery {#[derive(Clone, Copy)]pub(crate) enum Query<'a> {- F32(&'a [Lane]),- I8 { scale: f32, lanes: &'a [LaneI8] },+ F32(&'a [Lane], f64),+ I8 {+ scale: f32,+ lanes: &'a [LaneI8],+ norm: f64,+ },}impl Query<'_> {pub(crate) fn is_finite(&self) -> bool {match self {- Self::F32(lanes) => lanes+ Self::F32(lanes, _) => lanes.iter().all(|lane| lane.to_array().iter().all(|value| value.is_finite())),Self::I8 { scale, .. } => scale.is_finite(),@@ -105,6 +114,8 @@ pub(crate) struct VectorArena {dims: usize,lanes_per_vector: usize,storage: Storage,+ metric: DistanceMetric,+ norms: Vec<f64>,keys_to_slots: HashMap<Box<str>, u32>,slots_to_keys: Vec<Box<str>>,alive: Vec<u64>,@@ -118,7 +129,16 @@ impl VectorArena {Self::with_storage(dims, StorageKind::F32)}+ #[cfg(test)]pub(crate) fn with_storage(dims: usize, storage: StorageKind) -> Result<Self, VecDbError> {+ Self::with_metric(dims, storage, DistanceMetric::InnerProduct)+ }++ pub(crate) fn with_metric(+ dims: usize,+ storage: StorageKind,+ metric: DistanceMetric,+ ) -> Result<Self, VecDbError> {validate_dims(dims, storage)?;let storage = match storage {StorageKind::F32 => Storage::F32 { chunks: Vec::new() },@@ -131,6 +151,8 @@ impl VectorArena {dims,lanes_per_vector: dims / storage.kind().lane_width(),storage,+ metric,+ norms: Vec::new(),keys_to_slots: HashMap::new(),slots_to_keys: Vec::new(),alive: Vec::new(),@@ -139,6 +161,10 @@ impl VectorArena {})}+ pub(crate) fn metric(&self) -> DistanceMetric {+ self.metric+ }+pub(crate) fn dims(&self) -> usize {self.dims}@@ -165,10 +191,11 @@ impl VectorArena {pub(crate) fn vector_memory_bytes(&self) -> usize {let vectors = self.storage.chunk_count() * VECTORS_PER_CHUNK;- match &self.storage {- Storage::F32 { .. } => vectors * self.dims * size_of::<f32>(),- Storage::I8 { .. } => vectors * self.dims + self.slot_count() * size_of::<f32>(),- }+ self.norms.capacity() * size_of::<f64>()+ + match &self.storage {+ Storage::F32 { .. } => vectors * self.dims * size_of::<f32>(),+ Storage::I8 { .. } => vectors * self.dims + self.slot_count() * size_of::<f32>(),+ }}#[cfg(test)]@@ -223,6 +250,9 @@ impl VectorArena {if slot as usize / 64 == self.alive.len() {self.alive.push(0);}+ if self.metric == DistanceMetric::Cosine {+ self.norms.push(0.0);+ }self.slots_to_keys.push(Box::from(key));self.keys_to_slots.insert(Box::from(key), slot);self.mark_alive(slot);@@ -273,6 +303,8 @@ impl VectorArena {scales.shrink_to_fit();}}+ self.norms.truncate(live);+ self.norms.shrink_to_fit();self.alive.clear();self.alive.resize(live.div_ceil(64), u64::MAX);self.alive.shrink_to_fit();@@ -285,6 +317,9 @@ impl VectorArena {}fn move_vector(&mut self, src: u32, dst: u32) {+ if self.metric == DistanceMetric::Cosine {+ self.norms[dst as usize] = self.norms[src as usize];+ }let lanes = self.lanes_per_vector;match &mut self.storage {Storage::F32 { chunks } => move_lanes(chunks, lanes, src, dst),@@ -318,27 +353,29 @@ impl VectorArena {}pub(crate) fn stored_query(&self, slot: u32) -> Query<'_> {+ let norm = self.norms.get(slot as usize).copied().unwrap_or(0.0);let lanes = self.lanes_per_vector;match &self.storage {- Storage::F32 { chunks } => Query::F32(slot_lanes(chunks, lanes, slot)),+ Storage::F32 { chunks } => Query::F32(slot_lanes(chunks, lanes, slot), norm),Storage::I8 { chunks, scales } => Query::I8 {scale: scales[slot as usize],lanes: slot_lanes(chunks, lanes, slot),+ norm,},}}pub(crate) fn vector_values(&self, slot: u32) -> Vec<f32> {match self.stored_query(slot) {- Query::F32(lanes) => unpack_lanes(lanes),- Query::I8 { scale, lanes } => dequantize(scale, &unpack_lanes_i8(lanes)),+ Query::F32(lanes, _) => unpack_lanes(lanes),+ Query::I8 { scale, lanes, .. } => dequantize(scale, &unpack_lanes_i8(lanes)),}}pub(crate) fn stored_vector(&self, slot: u32) -> StoredVector {match self.stored_query(slot) {- Query::F32(lanes) => StoredVector::F32(unpack_lanes(lanes)),- Query::I8 { scale, lanes } => StoredVector::I8 {+ Query::F32(lanes, _) => StoredVector::F32(unpack_lanes(lanes)),+ Query::I8 { scale, lanes, .. } => StoredVector::I8 {scale,values: unpack_lanes_i8(lanes),},@@ -353,54 +390,96 @@ impl VectorArena {});}Ok(match quantize_for(self.storage_kind(), values) {- Some(StoredVector::I8 { scale, values }) => PackedQuery::I8 {- scale,- lanes: pack_lanes_i8(&values),- },- Some(StoredVector::F32(_)) | None => PackedQuery::F32(pack_lanes(values)),+ Some(StoredVector::I8 { scale, values }) => {+ let norm = self.payload_norm(VectorPayload::I8 {+ scale,+ values: &values,+ });+ PackedQuery::I8 {+ scale,+ lanes: pack_lanes_i8(&values),+ norm,+ }+ }+ Some(StoredVector::F32(_)) | None => PackedQuery::F32(+ pack_lanes(values),+ self.payload_norm(VectorPayload::F32(values)),+ ),})}pub(crate) fn distance_between_slots(&self, a: u32, b: u32) -> f32 {- let lanes = self.lanes_per_vector;- match &self.storage {- Storage::F32 { chunks } => {- F32Kernel::distance(slot_lanes(chunks, lanes, a), slot_lanes(chunks, lanes, b))- }- Storage::I8 { chunks, scales } => I8Kernel::distance(- slot_lanes(chunks, lanes, a),- scales[a as usize],- slot_lanes(chunks, lanes, b),- scales[b as usize],- ),- }+ self.distance_to_query(self.stored_query(a), b)}pub(crate) fn distance_to_query(&self, query: Query<'_>, slot: u32) -> f32 {- let lanes = self.lanes_per_vector;- match (&self.storage, query) {- (Storage::F32 { chunks }, Query::F32(query)) => {- F32Kernel::distance(query, slot_lanes(chunks, lanes, slot))+ match (query, self.stored_query(slot)) {+ (Query::F32(a, norm_a), Query::F32(b, norm_b)) => {+ if self.metric == DistanceMetric::InnerProduct {+ return F32Kernel::distance(a, b);+ }+ let denominator = norm_a * norm_b;+ let dot = if denominator >= f64::from(f32::MIN_POSITIVE)+ && denominator <= f64::from(f32::MAX)+ {+ f64::from(F32Kernel::dot(a, b))+ } else {+ a.iter()+ .zip(b)+ .flat_map(|(a, b)| a.to_array().into_iter().zip(b.to_array()))+ .map(|(a, b)| f64::from(a) * f64::from(b))+ .sum()+ };+ cosine_distance(dot, denominator)}(- Storage::I8 { chunks, scales },Query::I8 {- scale,- lanes: query,+ scale: scale_a,+ lanes: a,+ norm: norm_a,},- ) => I8Kernel::distance(- query,- scale,- slot_lanes(chunks, lanes, slot),- scales[slot as usize],- ),- (Storage::F32 { .. }, Query::I8 { .. }) | (Storage::I8 { .. }, Query::F32(_)) => {- unreachable!("queries are packed by the arena that searches them")+ Query::I8 {+ scale: scale_b,+ lanes: b,+ norm: norm_b,+ },+ ) => {+ if self.metric == DistanceMetric::InnerProduct {+ return I8Kernel::distance(a, scale_a, b, scale_b);+ }+ cosine_distance(f64::from(I8Kernel::dot(a, b)), norm_a * norm_b)+ }+ _ => unreachable!("queries are packed by the arena that searches them"),+ }+ }++ fn payload_norm(&self, payload: VectorPayload<'_>) -> f64 {+ if self.metric == DistanceMetric::InnerProduct {+ return 0.0;+ }+ match payload {+ VectorPayload::F32(values) => values+ .iter()+ .map(|&value| f64::from(value).powi(2))+ .sum::<f64>()+ .sqrt(),+ VectorPayload::I8 { scale, values } => {+ if scale == 0.0 {+ return 0.0;+ }+ values+ .iter()+ .map(|&value| f64::from(value).powi(2))+ .sum::<f64>()+ .sqrt()}}}fn write_vector(&mut self, slot: u32, payload: VectorPayload<'_>) {+ if self.metric == DistanceMetric::Cosine {+ self.norms[slot as usize] = self.payload_norm(payload);+ }let lanes = self.lanes_per_vector;match (&mut self.storage, payload) {(Storage::F32 { chunks }, VectorPayload::F32(values)) => {@@ -426,6 +505,13 @@ impl VectorArena {}}+fn cosine_distance(dot: f64, denominator: f64) -> f32 {+ if denominator == 0.0 {+ return 1.0;+ }+ (1.0 - (dot / denominator).clamp(-1.0, 1.0)) as f32+}+fn slot_lanes<T>(chunks: &[Vec<T>], lanes_per_vector: usize, slot: u32) -> &[T] {let start = (slot as usize % VECTORS_PER_CHUNK) * lanes_per_vector;&chunks[slot as usize / VECTORS_PER_CHUNK][start..start + lanes_per_vector]@@ -492,7 +578,7 @@ mod tests {fn lane_address(query: Query<'_>) -> usize {match query {- Query::F32(lanes) => lanes.as_ptr() as usize,+ Query::F32(lanes, _) => lanes.as_ptr() as usize,Query::I8 { lanes, .. } => lanes.as_ptr() as usize,}}diff --git a/rust/crates/ml/src/vecdb/log.rs b/rust/crates/ml/src/vecdb/log.rsindex 5d9afe83b9..fca93796c4 100644--- a/rust/crates/ml/src/vecdb/log.rs+++ b/rust/crates/ml/src/vecdb/log.rs@@ -9,13 +9,13 @@ use super::crc::{Crc32, crc32};use super::kernel::{StoredVector, VectorPayload, is_within_quantized_range, splitmix64, validate_dims,};-use super::{AttrValue, Attribute, StorageKind, VecDbError};+use super::{AttrValue, Attribute, DistanceMetric, StorageKind, VecDbError};pub(crate) const HEADER_LEN: usize = 32;const MAGIC: [u8; 4] = *b"EVDB";const FORMAT_VERSION: u16 = 1;const STORAGE_TAG_OFFSET: usize = 6;-const METRIC_TAG_INNER_PRODUCT: u8 = 0;+const METRIC_TAG_OFFSET: usize = 7;const RECORD_TYPE_ADD: u8 = 1;const RECORD_TYPE_TOMBSTONE: u8 = 2;const RECORD_PREFIX_LEN: usize = 3;@@ -63,6 +63,7 @@ pub(crate) struct Log {path: PathBuf,dims: usize,storage: StorageKind,+ metric: DistanceMetric,generation: [u8; 16],end_offset: u64,encode_buffer: Vec<u8>,@@ -115,10 +116,11 @@ impl Log {path: &Path,dims: usize,storage: StorageKind,+ metric: DistanceMetric,) -> Result<Self, VecDbError> {validate_dims(dims, storage)?;let file = open_writer_file(path, true)?;- Self::initialize(file, path, dims, storage)+ Self::initialize(file, path, dims, storage, metric)}pub(crate) fn open(@@ -126,6 +128,7 @@ impl Log {path: &Path,expected_dims: usize,requested: Option<StorageKind>,+ requested_metric: Option<DistanceMetric>,) -> Result<Self, VecDbError> {let fallback = requested.unwrap_or(StorageKind::I8);let file_len = file@@ -138,20 +141,28 @@ impl Log {path.display());validate_dims(expected_dims, fallback)?;- return Self::initialize(file, path, expected_dims, fallback);+ return Self::initialize(+ file,+ path,+ expected_dims,+ fallback,+ requested_metric.unwrap_or_default(),+ );}file.seek(SeekFrom::Start(0)).map_err(|source| VecDbError::io(path, source))?;let mut header = [0u8; HEADER_LEN];file.read_exact(&mut header).map_err(|source| VecDbError::io(path, source))?;- let (generation, storage) = decode_header(&header, expected_dims, requested)?;+ let (generation, storage, metric) =+ decode_header(&header, expected_dims, requested, requested_metric)?;validate_dims(expected_dims, storage)?;Ok(Self {file,path: path.to_path_buf(),dims: expected_dims,storage,+ metric,generation,end_offset: file_len,encode_buffer: Vec::new(),@@ -164,11 +175,12 @@ impl Log {path: &Path,dims: usize,storage: StorageKind,+ metric: DistanceMetric,) -> Result<Self, VecDbError> {let generation = fresh_generation();file.seek(SeekFrom::Start(0)).map_err(|source| VecDbError::io(path, source))?;- file.write_all(&encode_header(dims as u32, &generation, storage))+ file.write_all(&encode_header(dims as u32, &generation, storage, metric)).map_err(|source| VecDbError::io(path, source))?;file.sync_all().map_err(|source| VecDbError::io(path, source))?;@@ -178,6 +190,7 @@ impl Log {path: path.to_path_buf(),dims,storage,+ metric,generation,end_offset: HEADER_LEN as u64,encode_buffer: Vec::new(),@@ -189,10 +202,11 @@ impl Log {path: &Path,dims: usize,storage: StorageKind,+ metric: DistanceMetric,) -> Result<(Self, PathBuf), VecDbError> {remove_stale_temp_sibling(path)?;let temp_path = temp_sibling_path(path);- let log = Self::create(&temp_path, dims, storage)?;+ let log = Self::create(&temp_path, dims, storage, metric)?;Ok((log, temp_path))}@@ -381,6 +395,10 @@ impl Log {self.generation}+ pub(crate) fn metric(&self) -> DistanceMetric {+ self.metric+ }+pub(crate) fn storage(&self) -> StorageKind {self.storage}@@ -742,12 +760,17 @@ fn plausible_attrs_len(bytes: &[u8]) -> Option<usize> {Some(1 + attr_bytes)}-fn encode_header(dims: u32, generation: &[u8; 16], storage: StorageKind) -> [u8; HEADER_LEN] {+fn encode_header(+ dims: u32,+ generation: &[u8; 16],+ storage: StorageKind,+ metric: DistanceMetric,+) -> [u8; HEADER_LEN] {let mut bytes = [0u8; HEADER_LEN];bytes[0..4].copy_from_slice(&MAGIC);bytes[4..6].copy_from_slice(&FORMAT_VERSION.to_le_bytes());bytes[STORAGE_TAG_OFFSET] = storage.header_tag();- bytes[7] = METRIC_TAG_INNER_PRODUCT;+ bytes[METRIC_TAG_OFFSET] = metric.header_tag();bytes[8..12].copy_from_slice(&dims.to_le_bytes());bytes[12..28].copy_from_slice(generation);let crc = crc32(&bytes[0..28]);@@ -757,14 +780,15 @@ fn encode_header(dims: u32, generation: &[u8; 16], storage: StorageKind) -> [u8;pub(crate) fn header_generation(bytes: &[u8; HEADER_LEN]) -> Result<[u8; 16], VecDbError> {let dims = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;- decode_header(bytes, dims, None).map(|(generation, _)| generation)+ decode_header(bytes, dims, None, None).map(|(generation, _, _)| generation)}fn decode_header(bytes: &[u8; HEADER_LEN],expected_dims: usize,requested: Option<StorageKind>,-) -> Result<([u8; 16], StorageKind), VecDbError> {+ requested_metric: Option<DistanceMetric>,+) -> Result<([u8; 16], StorageKind, DistanceMetric), VecDbError> {if bytes[0..4] != MAGIC {return Err(VecDbError::Corrupt(format!("bad log magic {:02x?}",@@ -795,11 +819,16 @@ fn decode_header(actual: storage,});}- if bytes[7] != METRIC_TAG_INNER_PRODUCT {- return Err(VecDbError::Corrupt(format!(- "unknown metric tag {}",- bytes[7]- )));+ let metric = DistanceMetric::from_header_tag(bytes[METRIC_TAG_OFFSET]).ok_or_else(|| {+ VecDbError::Corrupt(format!("unknown metric tag {}", bytes[METRIC_TAG_OFFSET]))+ })?;+ if let Some(requested) = requested_metric+ && requested != metric+ {+ return Err(VecDbError::MetricMismatch {+ expected: requested,+ actual: metric,+ });}let dims = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;if dims != expected_dims {@@ -810,7 +839,7 @@ fn decode_header(}let mut generation = [0u8; 16];generation.copy_from_slice(&bytes[12..28]);- Ok((generation, storage))+ Ok((generation, storage, metric))}fn validate_entry(@@ -1013,6 +1042,7 @@ pub(crate) fn sync_parent_dir(_path: &Path) -> Result<(), VecDbError> {#[cfg(test)]mod tests {+ use super::DistanceMetric::InnerProduct;use super::*;use tempfile::TempDir;@@ -1028,7 +1058,7 @@ mod tests {fn reopen(path: &Path, dims: usize) -> Log {let file = open_writer_file(path, false).unwrap();- Log::open(file, path, dims, None).unwrap()+ Log::open(file, path, dims, None, None).unwrap()}fn append_bounds(log: &mut Log, entries: &[LogEntry<'_>]) -> (u64, u64) {@@ -1099,7 +1129,7 @@ mod tests {}fn write_log_file(path: &Path, dims: u32, record_bytes: &[u8]) {- let mut bytes = encode_header(dims, &[9u8; 16], StorageKind::F32).to_vec();+ let mut bytes = encode_header(dims, &[9u8; 16], StorageKind::F32, InnerProduct).to_vec();bytes.extend_from_slice(record_bytes);std::fs::write(path, bytes).unwrap();}@@ -1115,18 +1145,18 @@ mod tests {) -> Result<Log, VecDbError> {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut bytes = encode_header(8, &[7u8; 16], StorageKind::F32);+ let mut bytes = encode_header(8, &[7u8; 16], StorageKind::F32, InnerProduct);mutate(&mut bytes);std::fs::write(&path, bytes).unwrap();let file = File::options().read(true).write(true).open(&path).unwrap();- Log::open(file, &path, expected_dims, None)+ Log::open(file, &path, expected_dims, None, None)}#[test]fn header_round_trips_through_create_and_reopen() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let created = Log::create(&path, 512, StorageKind::F32).unwrap();+ let created = Log::create(&path, 512, StorageKind::F32, InnerProduct).unwrap();let generation = created.generation();assert_eq!(created.current_end_offset(), HEADER_LEN as u64);assert_eq!(created.path(), path.as_path());@@ -1142,7 +1172,7 @@ mod tests {let dir = TempDir::new().unwrap();let path = dir.path().join("log");let alias = dir.path().join("alias");- let created = Log::create(&path, 8, StorageKind::F32).unwrap();+ let created = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();std::fs::hard_link(&path, &alias).unwrap();let reader = File::open(&alias).unwrap();assert_eq!(reader.metadata().unwrap().len(), HEADER_LEN as u64);@@ -1257,7 +1287,7 @@ mod tests {let path = dir.path().join("log");std::fs::write(&path, vec![1u8; junk_len]).unwrap();let file = File::options().read(true).write(true).open(&path).unwrap();- let mut log = Log::open(file, &path, 8, Some(StorageKind::F32)).unwrap();+ let mut log = Log::open(file, &path, 8, Some(StorageKind::F32), None).unwrap();assert_eq!(log.current_end_offset(), HEADER_LEN as u64);assert_eq!(std::fs::metadata(&path).unwrap().len(), HEADER_LEN as u64);let (records, _) = scan_all(&mut log);@@ -1284,11 +1314,11 @@ mod tests {fn create_rejects_invalid_dimensions() {let dir = TempDir::new().unwrap();assert!(matches!(- Log::create(&dir.path().join("a"), 0, StorageKind::F32),+ Log::create(&dir.path().join("a"), 0, StorageKind::F32, InnerProduct),Err(VecDbError::InvalidDimensions { dims: 0, .. })));assert!(matches!(- Log::create(&dir.path().join("b"), 12, StorageKind::F32),+ Log::create(&dir.path().join("b"), 12, StorageKind::F32, InnerProduct),Err(VecDbError::InvalidDimensions { dims: 12, .. })));}@@ -1297,10 +1327,14 @@ mod tests {fn open_rejects_invalid_dimensions() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- drop(Log::create(&path, 8, StorageKind::F32).unwrap().into_file());+ drop(+ Log::create(&path, 8, StorageKind::F32, InnerProduct)+ .unwrap()+ .into_file(),+ );let file = File::options().read(true).write(true).open(&path).unwrap();assert!(matches!(- Log::open(file, &path, 12, None),+ Log::open(file, &path, 12, None, None),Err(VecDbError::DimensionMismatch {expected: 12,actual: 8@@ -1350,7 +1384,7 @@ mod tests {},];assert_eq!(- encode_header(8, &generation, StorageKind::F32),+ encode_header(8, &generation, StorageKind::F32, InnerProduct),golden_header);let mut encoded = Vec::new();@@ -1421,7 +1455,7 @@ mod tests {for dims in [8usize, 512] {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, dims, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, dims, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(1, dims);let entries = [LogEntry::Add {@@ -1461,7 +1495,7 @@ mod tests {];let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(5, 8);for key in keys {log.append(&[LogEntry::Add {@@ -1496,7 +1530,7 @@ mod tests {fn decodes_non_finite_components_without_panicking() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = [f32::NAN,f32::INFINITY,@@ -1532,7 +1566,7 @@ mod tests {fn scanner_stops_at_last_complete_record_for_every_torn_length() {let dir = TempDir::new().unwrap();let build_path = dir.path().join("log");- let mut log = Log::create(&build_path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&build_path, 8, StorageKind::F32, InnerProduct).unwrap();let vectors: Vec<Vec<f32>> = (0..3).map(|seed| seeded_vector(seed, 8)).collect();let mut boundaries = Vec::new();for (index, vector) in vectors.iter().enumerate() {@@ -1565,7 +1599,7 @@ mod tests {fn truncate_to_repairs_torn_tail_for_clean_appends() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(1, 8);let (_, first_end) = append_bounds(&mut log,@@ -1616,7 +1650,7 @@ mod tests {fn extend_end_offset_grows_to_target_clamps_to_file_and_never_shrinks() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(1, 8);let (_, captured_end) = append_bounds(&mut log,@@ -1656,7 +1690,7 @@ mod tests {fn discard_unacked_tail_drops_phantom_frames_before_reopen() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(1, 8);let (_, acked_end) = append_bounds(&mut log,@@ -1686,7 +1720,7 @@ mod tests {fn pending_rollback_truncates_stale_records_before_the_next_append() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(6, 8);let (_, acked_end) = append_bounds(&mut log,@@ -1732,8 +1766,8 @@ mod tests {let dir = TempDir::new().unwrap();let synced_path = dir.path().join("synced");let staged_path = dir.path().join("staged");- let mut synced = Log::create(&synced_path, 8, StorageKind::F32).unwrap();- let mut staged = Log::create(&staged_path, 8, StorageKind::F32).unwrap();+ let mut synced = Log::create(&synced_path, 8, StorageKind::F32, InnerProduct).unwrap();+ let mut staged = Log::create(&staged_path, 8, StorageKind::F32, InnerProduct).unwrap();let vectors: Vec<Vec<f32>> = (0..3).map(|seed| seeded_vector(seed, 8)).collect();let attrs = [Attribute {name: "model".to_string(),@@ -1783,7 +1817,7 @@ mod tests {fn append_failure_rolls_back_without_disturbing_acked_records() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(2, 8);let (_, acked_end) = append_bounds(&mut log,@@ -1795,7 +1829,7 @@ mod tests {);drop(log);let unwritable = File::open(&path).unwrap();- let mut log = Log::open(unwritable, &path, 8, None).unwrap();+ let mut log = Log::open(unwritable, &path, 8, None, None).unwrap();assert!(matches!(log.append(&[LogEntry::Add {key: "lost",@@ -1817,7 +1851,7 @@ mod tests {fn append_after_phantom_frames_overwrites_at_the_acked_offset() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(3, 8);let (_, acked_end) = append_bounds(&mut log,@@ -1858,7 +1892,7 @@ mod tests {fn scanner_stops_at_corrupted_middle_record() {let dir = TempDir::new().unwrap();let build_path = dir.path().join("log");- let mut log = Log::create(&build_path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&build_path, 8, StorageKind::F32, InnerProduct).unwrap();let vectors: Vec<Vec<f32>> = (0..3).map(|seed| seeded_vector(seed, 8)).collect();let mut boundaries = Vec::new();for (index, vector) in vectors.iter().enumerate() {@@ -1937,7 +1971,7 @@ mod tests {fn append_offsets_match_scanner_offsets() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();log.append(&[]).unwrap();assert_eq!(log.current_end_offset(), HEADER_LEN as u64);let vector = seeded_vector(7, 8);@@ -1972,7 +2006,7 @@ mod tests {fn append_validates_keys_and_vector_dims() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(1, 8);let wrong_dims = seeded_vector(1, 16);assert!(matches!(@@ -2014,8 +2048,15 @@ mod tests {#[test]fn generation_is_distinct_across_creates() {let dir = TempDir::new().unwrap();- let first = Log::create(&dir.path().join("first"), 8, StorageKind::F32).unwrap();- let second = Log::create(&dir.path().join("second"), 8, StorageKind::F32).unwrap();+ let first =+ Log::create(&dir.path().join("first"), 8, StorageKind::F32, InnerProduct).unwrap();+ let second = Log::create(+ &dir.path().join("second"),+ 8,+ StorageKind::F32,+ InnerProduct,+ )+ .unwrap();assert_ne!(first.generation(), second.generation());}@@ -2023,10 +2064,11 @@ mod tests {fn temp_sibling_gets_fresh_generation_and_replaces_stale_tmp() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let stale_path = dir.path().join("log.tmp");std::fs::write(&stale_path, b"stale leftover").unwrap();- let (temp_log, temp_path) = Log::create_temp_sibling(&path, 8, StorageKind::F32).unwrap();+ let (temp_log, temp_path) =+ Log::create_temp_sibling(&path, 8, StorageKind::F32, InnerProduct).unwrap();assert_eq!(temp_path, stale_path);assert_ne!(temp_log.generation(), log.generation());assert_eq!(temp_log.current_end_offset(), HEADER_LEN as u64);@@ -2059,8 +2101,9 @@ mod tests {attrs: &[],}).collect();- let mut bulk_log = Log::create(&bulk_path, dims, StorageKind::F32).unwrap();- let mut sequential_log = Log::create(&sequential_path, dims, StorageKind::F32).unwrap();+ let mut bulk_log = Log::create(&bulk_path, dims, StorageKind::F32, InnerProduct).unwrap();+ let mut sequential_log =+ Log::create(&sequential_path, dims, StorageKind::F32, InnerProduct).unwrap();let (_, bulk_end) = append_bounds(&mut bulk_log, &entries);let mut sequential_end = 0;for entry in &entries {@@ -2100,8 +2143,9 @@ mod tests {attrs: &[],},];- let mut bulk_log = Log::create(&bulk_path, 8, StorageKind::F32).unwrap();- let mut sequential_log = Log::create(&sequential_path, 8, StorageKind::F32).unwrap();+ let mut bulk_log = Log::create(&bulk_path, 8, StorageKind::F32, InnerProduct).unwrap();+ let mut sequential_log =+ Log::create(&sequential_path, 8, StorageKind::F32, InnerProduct).unwrap();let (bulk_start, bulk_end) = append_bounds(&mut bulk_log, &entries);let mut sequential_end = 0;for entry in &entries {@@ -2150,7 +2194,7 @@ mod tests {let vector = seeded_vector(8, 8);for (index, attrs) in singles.iter().chain([&full_set]).enumerate() {let path = dir.path().join(format!("log-{index}"));- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();log.append(&[LogEntry::Add {key: "k",vector: VectorPayload::F32(&vector),@@ -2185,7 +2229,7 @@ mod tests {let vector = seeded_vector(9, 8);for (index, attrs) in cases.iter().enumerate() {let path = dir.path().join(format!("log-{index}"));- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();log.append(&[LogEntry::Add {key: "k",vector: VectorPayload::F32(&vector),@@ -2223,7 +2267,7 @@ mod tests {];let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(10, 8);for attrs in &invalid {assert!(matches!(@@ -2263,7 +2307,8 @@ mod tests {.map(|(index, value)| attr(&format!("f{index}"), AttrValue::F64(*value))).collect();let dir = TempDir::new().unwrap();- let mut log = Log::create(&dir.path().join("log"), 8, StorageKind::F32).unwrap();+ let mut log =+ Log::create(&dir.path().join("log"), 8, StorageKind::F32, InnerProduct).unwrap();let vector = seeded_vector(11, 8);log.append(&[LogEntry::Add {key: "k",@@ -2666,7 +2711,8 @@ mod tests {];for (name, after_first, intact_record_beyond) in cases {let path = dir.path().join(name);- let mut bytes = encode_header(dims as u32, &[9u8; 16], StorageKind::I8).to_vec();+ let mut bytes =+ encode_header(dims as u32, &[9u8; 16], StorageKind::I8, InnerProduct).to_vec();bytes.extend_from_slice(&first);bytes.extend_from_slice(&after_first);std::fs::write(&path, &bytes).unwrap();@@ -2683,7 +2729,7 @@ mod tests {}fn write_i8_log_file(path: &Path, dims: u32, record_bytes: &[u8]) {- let mut bytes = encode_header(dims, &[9u8; 16], StorageKind::I8).to_vec();+ let mut bytes = encode_header(dims, &[9u8; 16], StorageKind::I8, InnerProduct).to_vec();bytes.extend_from_slice(record_bytes);std::fs::write(path, bytes).unwrap();}@@ -2724,7 +2770,7 @@ mod tests {let scale = 0.01f32;assert_eq!(scale.to_bits(), 0x3c23_d70a);let values = golden_i8_values();- let header = encode_header(32, &generation, StorageKind::I8);+ let header = encode_header(32, &generation, StorageKind::I8, InnerProduct);assert_eq!(header[STORAGE_TAG_OFFSET], 1);assert_eq!(header[..28], golden_header[..28]);let encoded = encoded_i8_add("k1", scale, &values);@@ -2772,11 +2818,11 @@ mod tests {#[test]fn f32_headers_leave_the_storage_tag_zero() {- let header = encode_header(8, &[7u8; 16], StorageKind::F32);+ let header = encode_header(8, &[7u8; 16], StorageKind::F32, InnerProduct);assert_eq!(header[STORAGE_TAG_OFFSET], 0);assert_eq!(- decode_header(&header, 8, None).unwrap(),- ([7u8; 16], StorageKind::F32)+ decode_header(&header, 8, None, None).unwrap(),+ ([7u8; 16], StorageKind::F32, InnerProduct));}@@ -2800,18 +2846,18 @@ mod tests {let dir = TempDir::new().unwrap();let i8_path = dir.path().join("i8");let f32_path = dir.path().join("f32");- let created = Log::create(&i8_path, 32, StorageKind::I8).unwrap();+ let created = Log::create(&i8_path, 32, StorageKind::I8, InnerProduct).unwrap();assert_eq!(created.storage(), StorageKind::I8);let generation = created.generation();drop(created.into_file());drop(- Log::create(&f32_path, 32, StorageKind::F32)+ Log::create(&f32_path, 32, StorageKind::F32, InnerProduct).unwrap().into_file(),);let open = |path: &Path, requested: Option<StorageKind>| {let file = File::options().read(true).write(true).open(path).unwrap();- Log::open(file, path, 32, requested)+ Log::open(file, path, 32, requested, None)};let detected = open(&i8_path, None).unwrap();assert_eq!(detected.storage(), StorageKind::I8);@@ -2845,7 +2891,7 @@ mod tests {let path = dir.path().join("log");std::fs::write(&path, [1u8; 5]).unwrap();let file = File::options().read(true).write(true).open(&path).unwrap();- let log = Log::open(file, &path, 64, Some(StorageKind::I8)).unwrap();+ let log = Log::open(file, &path, 64, Some(StorageKind::I8), None).unwrap();assert_eq!(log.storage(), StorageKind::I8);drop(log);assert_eq!(reopen(&path, 64).storage(), StorageKind::I8);@@ -2853,7 +2899,7 @@ mod tests {std::fs::write(&other, [1u8; 5]).unwrap();let file = File::options().read(true).write(true).open(&other).unwrap();assert_eq!(- Log::open(file, &other, 64, None).unwrap().storage(),+ Log::open(file, &other, 64, None, None).unwrap().storage(),StorageKind::I8);}@@ -2863,27 +2909,33 @@ mod tests {let dir = TempDir::new().unwrap();for dims in [8usize, 16, 24, 40] {assert!(matches!(- Log::create(&dir.path().join(format!("a{dims}")), dims, StorageKind::I8),+ Log::create(&dir.path().join(format!("a{dims}")), dims, StorageKind::I8, InnerProduct),Err(VecDbError::InvalidDimensions {dims: rejected,storage: StorageKind::I8}) if rejected == dims));assert!(- Log::create(&dir.path().join(format!("b{dims}")), dims, StorageKind::F32).is_ok()+ Log::create(+ &dir.path().join(format!("b{dims}")),+ dims,+ StorageKind::F32,+ InnerProduct+ )+ .is_ok());}- assert!(Log::create(&dir.path().join("c"), 32, StorageKind::I8).is_ok());+ assert!(Log::create(&dir.path().join("c"), 32, StorageKind::I8, InnerProduct).is_ok());let path = dir.path().join("c");let file = File::options().read(true).write(true).open(&path).unwrap();assert!(matches!(- Log::open(file, &path, 8, Some(StorageKind::I8)),+ Log::open(file, &path, 8, Some(StorageKind::I8), None),Err(VecDbError::DimensionMismatch {expected: 8,actual: 32})));- let mut forged = encode_header(8, &[3u8; 16], StorageKind::I8);+ let mut forged = encode_header(8, &[3u8; 16], StorageKind::I8, InnerProduct);refresh_crc(&mut forged);let forged_path = dir.path().join("forged");std::fs::write(&forged_path, forged).unwrap();@@ -2893,7 +2945,7 @@ mod tests {.open(&forged_path).unwrap();assert!(matches!(- Log::open(file, &forged_path, 8, None),+ Log::open(file, &forged_path, 8, None, None),Err(VecDbError::InvalidDimensions {dims: 8,storage: StorageKind::I8@@ -2906,7 +2958,7 @@ mod tests {for dims in [32usize, 512] {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, dims, StorageKind::I8).unwrap();+ let mut log = Log::create(&path, dims, StorageKind::I8, InnerProduct).unwrap();let scales = [f32::from_bits(0x3a1f_8f3c),0.0,@@ -2968,8 +3020,8 @@ mod tests {let dir = TempDir::new().unwrap();let i8_path = dir.path().join("i8");let f32_path = dir.path().join("f32");- let mut i8_log = Log::create(&i8_path, 32, StorageKind::I8).unwrap();- let mut f32_log = Log::create(&f32_path, 32, StorageKind::F32).unwrap();+ let mut i8_log = Log::create(&i8_path, 32, StorageKind::I8, InnerProduct).unwrap();+ let mut f32_log = Log::create(&f32_path, 32, StorageKind::F32, InnerProduct).unwrap();let values = seeded_vector(4, 32);let quantized = StoredVector::quantize(&values);assert!(matches!(@@ -3036,7 +3088,7 @@ mod tests {let dims = 32usize;let dir = TempDir::new().unwrap();let build_path = dir.path().join("log");- let mut log = Log::create(&build_path, dims, StorageKind::I8).unwrap();+ let mut log = Log::create(&build_path, dims, StorageKind::I8, InnerProduct).unwrap();let mut boundaries = Vec::new();for index in 0..3u64 {let key = format!("key-{index}");diff --git a/rust/crates/ml/src/vecdb/mod.rs b/rust/crates/ml/src/vecdb/mod.rsindex 1a573a908f..40111e7926 100644--- a/rust/crates/ml/src/vecdb/mod.rs+++ b/rust/crates/ml/src/vecdb/mod.rs@@ -13,6 +13,39 @@ mod store;pub use store::{OpenCost, Stats, VecDb};+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub enum DistanceMetric {+ InnerProduct,+ #[default]+ Cosine,+}++impl DistanceMetric {+ pub(crate) fn header_tag(self) -> u8 {+ match self {+ Self::InnerProduct => 0,+ Self::Cosine => 1,+ }+ }++ pub(crate) fn from_header_tag(tag: u8) -> Option<Self> {+ match tag {+ 0 => Some(Self::InnerProduct),+ 1 => Some(Self::Cosine),+ _ => None,+ }+ }+}++impl std::fmt::Display for DistanceMetric {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(match self {+ Self::InnerProduct => "inner product",+ Self::Cosine => "cosine",+ })+ }+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum StorageKind {F32,@@ -124,6 +157,11 @@ pub enum VecDbError {expected: StorageKind,actual: StorageKind,},+ #[error("distance metric mismatch: expected {expected}, found {actual}")]+ MetricMismatch {+ expected: DistanceMetric,+ actual: DistanceMetric,+ },#[error("search requires a limit or a max distance")]UnboundedSearch,#[error("length mismatch: {keys} keys, {vectors} vectors")]diff --git a/rust/crates/ml/src/vecdb/store.rs b/rust/crates/ml/src/vecdb/store.rsindex b543850a89..7b8b419131 100644--- a/rust/crates/ml/src/vecdb/store.rs+++ b/rust/crates/ml/src/vecdb/store.rs@@ -20,7 +20,9 @@ use super::log::{use super::snapshot::{LoadedSnapshot, load_snapshot, remove_snapshot, snapshot_path, write_snapshot,};-use super::{AttrValue, Attribute, KeyMatches, Match, SearchParams, StorageKind, VecDbError};+use super::{+ AttrValue, Attribute, DistanceMetric, KeyMatches, Match, SearchParams, StorageKind, VecDbError,+};const SNAPSHOT_HARD_CAP: usize = 5000;const SNAPSHOT_QUIET_THRESHOLD: usize = 1000;@@ -64,6 +66,7 @@ pub struct Stats {pub dead_count: usize,pub dims: usize,pub storage: StorageKind,+ pub metric: DistanceMetric,pub log_bytes: u64,pub records_since_snapshot: usize,pub approximate_memory_bytes: usize,@@ -78,6 +81,7 @@ struct Shared {path: PathBuf,dims: usize,storage: StorageKind,+ metric: DistanceMetric,registry_key: Option<PathBuf>,closed: AtomicBool,writer: Mutex<WriterHalf>,@@ -304,6 +308,7 @@ fn join_live(shared: Arc<Shared>,dims: usize,storage: Option<StorageKind>,+ metric: Option<DistanceMetric>,read_only: bool,) -> Result<VecDb, VecDbError> {if shared.dims != dims {@@ -320,6 +325,14 @@ fn join_live(actual: shared.storage,});}+ if let Some(requested) = metric+ && requested != shared.metric+ {+ return Err(VecDbError::MetricMismatch {+ expected: requested,+ actual: shared.metric,+ });+ }Ok(VecDb { shared, read_only })}@@ -371,7 +384,7 @@ fn warn_handoff_cap(path: &Path) {impl VecDb {pub fn open(path: &Path, dims: usize) -> Result<Self, VecDbError> {- Self::open_with(path, dims, None)+ Self::open_with(path, dims, None, None)}pub fn open_with_storage(@@ -379,13 +392,22 @@ impl VecDb {dims: usize,storage: StorageKind,) -> Result<Self, VecDbError> {- Self::open_with(path, dims, Some(storage))+ Self::open_with(path, dims, Some(storage), None)}- fn open_with(+ pub fn open_with_metric(+ path: &Path,+ dims: usize,+ metric: DistanceMetric,+ ) -> Result<Self, VecDbError> {+ Self::open_with(path, dims, None, Some(metric))+ }++ pub fn open_with(path: &Path,dims: usize,storage: Option<StorageKind>,+ metric: Option<DistanceMetric>,) -> Result<Self, VecDbError> {let key = registry_key_for(path)?;let slot = path_slot(&key);@@ -395,18 +417,20 @@ impl VecDb {drop(guard);match observed {Some(shared) if !shared.is_closed() => {- return join_live(shared, dims, storage, false);+ return join_live(shared, dims, storage, metric, false);}observed => drop(observed),}match wait_for_teardown_handoff(&slot, &key) {- SlotHandoff::Join(shared) => return join_live(shared, dims, storage, false),+ SlotHandoff::Join(shared) => {+ return join_live(shared, dims, storage, metric, false);+ }SlotHandoff::Released(reacquired) | SlotHandoff::Expired(reacquired) => {guard = reacquired;}}}- let built = match build_writer(&key, key.clone(), dims, storage) {+ let built = match build_writer(&key, key.clone(), dims, storage, metric) {Ok(built) => built,Err(error) => {drop(guard);@@ -457,12 +481,14 @@ impl VecDb {let observed = lock_slot(&slot).live.as_ref().and_then(Weak::upgrade);match observed {Some(shared) if !shared.is_closed() => {- return join_live(shared, dims, None, true);+ return join_live(shared, dims, None, None, true);}Some(closing) => {drop(closing);match wait_for_teardown_handoff(&slot, &resolved) {- SlotHandoff::Join(shared) => return join_live(shared, dims, None, true),+ SlotHandoff::Join(shared) => {+ return join_live(shared, dims, None, None, true);+ }SlotHandoff::Released(released) | SlotHandoff::Expired(released) => {drop(released);}@@ -780,7 +806,7 @@ impl VecDb {let dims = self.shared.dims;let storage = self.shared.storage;let recreated = remove_data_files(&self.shared.path)- .and_then(|()| Log::create(&self.shared.path, dims, storage));+ .and_then(|()| Log::create(&self.shared.path, dims, storage, self.shared.metric));let log = match recreated {Ok(log) => log,Err(error) => {@@ -794,7 +820,7 @@ impl VecDb {return Err(error);}};- let arena = VectorArena::with_storage(dims, storage)?;+ let arena = VectorArena::with_metric(dims, storage, self.shared.metric)?;{let mut st = self.shared.state_write();st.arena = arena;@@ -880,6 +906,7 @@ impl VecDb {dead_count: st.total_records.saturating_sub(live_count as u64) as usize,dims: st.arena.dims(),storage: self.shared.storage,+ metric: self.shared.metric,log_bytes,records_since_snapshot,approximate_memory_bytes: approximate_memory_bytes(&st),@@ -1006,7 +1033,7 @@ fn close_live_instance(shared: &Arc<Shared>) -> Result<(), VecDbError> {shared.closed.store(true, Ordering::Release);drop(log);let removed = remove_data_files(&shared.path);- if let Ok(empty) = VectorArena::with_storage(shared.dims, shared.storage) {+ if let Ok(empty) = VectorArena::with_metric(shared.dims, shared.storage, shared.metric) {st.arena = empty;st.graph = Some(Graph::new());st.attrs.reset();@@ -1122,7 +1149,7 @@ fn write_snapshot_now(shared: &Shared, half: &mut WriterHalf) -> Result<(), VecDfn compact(shared: &Shared, half: &mut WriterHalf) -> Result<(), VecDbError> {active_state(half)?;let (mut temp_log, temp_path) =- Log::create_temp_sibling(&shared.path, shared.dims, shared.storage)?;+ Log::create_temp_sibling(&shared.path, shared.dims, shared.storage, shared.metric)?;let staged = {let st = shared.state_read();stage_live_entries(&st, &mut temp_log)@@ -1201,7 +1228,13 @@ fn restore_writer_mode("log header was truncated while the writer was closed".to_string(),));}- let mut log = Log::open(file, &shared.path, shared.dims, Some(shared.storage))?;+ let mut log = Log::open(+ file,+ &shared.path,+ shared.dims,+ Some(shared.storage),+ Some(shared.metric),+ )?;let mut pending = mutations_since_snapshot;if log.checkpoint() != expected_checkpoint {let replayed = replay(&mut log, shared.dims, ReplayMode::Writer)?;@@ -1252,7 +1285,7 @@ fn recover_after_failed_reset(if restore_writer_mode(shared, half, lock, None, old_pending, old_checkpoint).is_ok() {return;}- if let Ok(empty) = VectorArena::with_storage(shared.dims, shared.storage) {+ if let Ok(empty) = VectorArena::with_metric(shared.dims, shared.storage, shared.metric) {let mut st = shared.state_write();st.arena = empty;st.graph = Some(Graph::new());@@ -1276,15 +1309,21 @@ fn build_writer(registry_key: PathBuf,dims: usize,storage: Option<StorageKind>,+ metric: Option<DistanceMetric>,) -> Result<BuiltWriter, VecDbError> {let lock = WriterLock::acquire(path)?;let mut log = if std::fs::metadata(path).is_ok() {- open_existing_writer_log(path, dims, storage)?+ open_existing_writer_log(path, dims, storage, metric)?} else {- match Log::create(path, dims, storage.unwrap_or(StorageKind::I8)) {+ match Log::create(+ path,+ dims,+ storage.unwrap_or(StorageKind::I8),+ metric.unwrap_or_default(),+ ) {Ok(created) => created,Err(VecDbError::Io { source, .. }) if source.kind() == ErrorKind::AlreadyExists => {- open_existing_writer_log(path, dims, storage)?+ open_existing_writer_log(path, dims, storage, metric)?}Err(error) => return Err(error),}@@ -1377,6 +1416,7 @@ fn writer_shared(path: path.to_path_buf(),dims,storage,+ metric: state.arena.metric(),registry_key: Some(registry_key),closed: AtomicBool::new(false),writer: Mutex::new(WriterHalf {@@ -1444,7 +1484,7 @@ fn build_read_only(path: &Path, dims: usize) -> Result<Shared, VecDbError> {if file_len < HEADER_LEN as u64 {return empty_read_only(path, dims);}- let mut log = Log::open(file, path, dims, None)?;+ let mut log = Log::open(file, path, dims, None, None)?;let replayed = replay(&mut log, dims, ReplayMode::ReadOnly)?;drop(log);let ReplayedState {@@ -1469,7 +1509,7 @@ fn build_read_only(path: &Path, dims: usize) -> Result<Shared, VecDbError> {fn empty_read_only(path: &Path, dims: usize) -> Result<Shared, VecDbError> {Ok(read_only_shared(path,- VectorArena::with_storage(dims, StorageKind::I8)?,+ VectorArena::with_metric(dims, StorageKind::I8, DistanceMetric::default())?,Graph::new(),AttrTable::default(),0,@@ -1489,6 +1529,7 @@ fn read_only_shared(path: path.to_path_buf(),dims: arena.dims(),storage: arena.storage_kind(),+ metric: arena.metric(),registry_key: None,closed: AtomicBool::new(false),writer: Mutex::new(WriterHalf {@@ -1552,7 +1593,7 @@ fn replay(log: &mut Log, dims: usize, mode: ReplayMode) -> Result<ReplayedState,let snapshot_covered = snapshot.as_ref().map(|loaded| loaded.covered_log_offset);let covered = snapshot_covered.unwrap_or(u64::MAX);let path = log.path().to_path_buf();- let mut arena = VectorArena::with_storage(dims, log.storage())?;+ let mut arena = VectorArena::with_metric(dims, log.storage(), log.metric())?;let mut attrs = AttrTable::default();let mut graph: Option<Graph> = None;let mut tail_records = 0u64;@@ -1661,9 +1702,10 @@ fn open_existing_writer_log(path: &Path,dims: usize,storage: Option<StorageKind>,+ metric: Option<DistanceMetric>,) -> Result<Log, VecDbError> {let file = open_writer_file(path, false)?;- Log::open(file, path, dims, storage)+ Log::open(file, path, dims, storage, metric)}fn promote_compacted_log(temp_path: &Path, path: &Path) -> Result<(), VecDbError> {@@ -1739,6 +1781,233 @@ mod tests {const ADD_RECORD_LEN: u64 = 3 + 5 + (DIMS as u64) * 4 + 1 + 4;const TOMBSTONE_RECORD_LEN: u64 = 3 + 5 + 4;+ #[test]+ fn cosine_defaults_and_metric_mismatches_cover_live_and_disk_opens() {+ let dir = TempDir::new().unwrap();+ let default_path = dir.path().join("default");+ let default = VecDb::open(&default_path, 32).unwrap();+ assert_eq!(default.stats().unwrap().metric, DistanceMetric::Cosine);+ assert_eq!(default.stats().unwrap().storage, StorageKind::I8);+ for storage in [StorageKind::F32, StorageKind::I8] {+ for metric in [DistanceMetric::Cosine, DistanceMetric::InnerProduct] {+ let path = dir.path().join(format!("{storage}-{metric}"));+ let other = match metric {+ DistanceMetric::Cosine => DistanceMetric::InnerProduct,+ DistanceMetric::InnerProduct => DistanceMetric::Cosine,+ };+ let db = VecDb::open_with(&path, 32, Some(storage), Some(metric)).unwrap();+ assert_eq!(db.stats().unwrap().metric, metric);+ assert_eq!(+ VecDb::open(&path, 32).unwrap().stats().unwrap().metric,+ metric+ );+ assert_eq!(+ VecDb::open_with_metric(&path, 32, metric)+ .unwrap()+ .stats()+ .unwrap()+ .metric,+ metric+ );+ assert_eq!(+ VecDb::open_read_only(&path, 32)+ .unwrap()+ .stats()+ .unwrap()+ .metric,+ metric+ );+ assert!(matches!(+ VecDb::open_with_metric(&path, 32, other),+ Err(VecDbError::MetricMismatch { expected, actual })+ if expected == other && actual == metric+ ));+ drop(db);+ let before = std::fs::read(&path).unwrap();+ assert!(matches!(+ VecDb::open_with_metric(&path, 32, other),+ Err(VecDbError::MetricMismatch { .. })+ ));+ assert_eq!(std::fs::read(&path).unwrap(), before);+ assert_eq!(+ VecDb::open_read_only(&path, 32)+ .unwrap()+ .stats()+ .unwrap()+ .metric,+ metric+ );+ assert_eq!(+ VecDb::open(&path, 32).unwrap().stats().unwrap().metric,+ metric+ );+ }+ }+ }++ #[test]+ fn cosine_scores_unnormalized_vectors_in_every_search_path() {+ let dir = TempDir::new().unwrap();+ for storage in [StorageKind::F32, StorageKind::I8] {+ let db = VecDb::open_with_storage(&dir.path().join(storage.to_string()), 32, storage)+ .unwrap();+ let vector = |x, y| {+ let mut values = vec![0.0; 32];+ values[0] = x;+ values[1] = y;+ values+ };+ db.add("aligned", &vector(2.0, 0.0)).unwrap();+ db.add("angled", &vector(30.0, 40.0)).unwrap();+ db.add("orthogonal", &vector(0.0, 3.0)).unwrap();+ db.add("opposite", &vector(-4.0, 0.0)).unwrap();+ db.add("zero", &vector(0.0, 0.0)).unwrap();+ for exact in [false, true] {+ let params = SearchParams {+ limit: Some(5),+ exact,+ ..Default::default()+ };+ for scale in [0.125, 1.0, 100.0] {+ let query = vector(scale, 0.0);+ let matches = db.search(&query, ¶ms).unwrap();+ assert_eq!(matches[0].key, "aligned");+ for (key, distance) in [+ ("aligned", 0.0),+ ("angled", 0.4),+ ("orthogonal", 1.0),+ ("opposite", 2.0),+ ("zero", 1.0),+ ] {+ let found = matches.iter().find(|found| found.key == key).unwrap();+ assert!(+ (found.distance - distance).abs() < 0.005,+ "{storage}: {found:?}"+ );+ }+ assert_eq!(+ db.bulk_search(&[query.clone(), query.clone()], ¶ms)+ .unwrap(),+ vec![matches.clone(), matches]+ );+ for limit in [None, Some(5)] {+ let filtered = SearchParams {+ limit,+ max_distance: Some(0.5),+ exact,+ allowed_keys: Some(vec!["angled".into(), "orthogonal".into()]),+ };+ let matches = db.search(&query, &filtered).unwrap();+ assert_eq!(matches.len(), 1);+ assert_eq!(matches[0].key, "angled");+ let threshold = SearchParams {+ allowed_keys: None,+ ..filtered+ };+ assert_eq!(db.search(&query, &threshold).unwrap().len(), 2);+ }+ }+ let stored = db+ .bulk_search_stored(&["aligned".into()], 4, Some(0.5), exact, false)+ .unwrap();+ assert_eq!(stored[0].matches.len(), 1);+ assert_eq!(stored[0].matches[0].key, "angled");+ assert!((stored[0].matches[0].distance - 0.4).abs() < 0.005);+ assert!(+ db.search(&vector(0.0, 0.0), ¶ms)+ .unwrap()+ .iter()+ .all(|found| found.distance == 1.0)+ );+ }+ assert_eq!(db.get("aligned").unwrap(), vector(2.0, 0.0));+ }+ }++ #[test]+ fn metrics_survive_replacement_compaction_snapshot_replay_and_reset() {+ let dir = TempDir::new().unwrap();+ for storage in [StorageKind::F32, StorageKind::I8] {+ for metric in [DistanceMetric::Cosine, DistanceMetric::InnerProduct] {+ let path = dir.path().join(format!("{storage}-{metric}"));+ let db = VecDb::open_with(&path, 32, Some(storage), Some(metric)).unwrap();+ let mut vector = vec![0.0; 32];+ vector[0] = 4.0;+ db.add("removed", &vector).unwrap();+ db.add("kept", &vector).unwrap();+ db.remove("removed").unwrap();+ vector[0] = 3.0;+ db.add("kept", &vector).unwrap();+ let recycled: Vec<f32> = vector.iter().map(|value| value * 2.0).collect();+ db.add("recycled", &recycled).unwrap();+ db.remove("recycled").unwrap();+ compact(&db.shared, &mut db.shared.writer_half()).unwrap();+ db.flush().unwrap();+ let expected = if metric == DistanceMetric::Cosine {+ 0.0+ } else {+ -8.0+ };+ let assert_score = |db: &VecDb| {+ assert_eq!(db.stats().unwrap().metric, metric);+ for exact in [false, true] {+ let found = db+ .search(+ &vector,+ &SearchParams {+ limit: Some(1),+ exact,+ ..Default::default()+ },+ )+ .unwrap();+ assert_eq!(found[0].key, "kept");+ assert!((found[0].distance - expected).abs() < 1.0e-5);+ }+ };+ assert_score(&db);+ drop(db);+ for snapshot in [true, false] {+ if !snapshot {+ remove_snapshot(&path).unwrap();+ }+ assert_score(&VecDb::open_read_only(&path, 32).unwrap());+ assert_score(&VecDb::open(&path, 32).unwrap());+ }+ let db = VecDb::open(&path, 32).unwrap();+ db.reset().unwrap();+ db.add("kept", &vector).unwrap();+ assert_score(&db);+ drop(db);+ assert_score(&VecDb::open(&path, 32).unwrap());+ }+ }+ }++ #[test]+ fn cosine_f32_handles_extreme_finite_magnitudes() {+ let dir = TempDir::new().unwrap();+ let db = VecDb::open_with_storage(&dir.path().join("db"), 8, StorageKind::F32).unwrap();+ for magnitude in [f32::MAX, f32::MIN_POSITIVE, f32::from_bits(1)] {+ let vector = vec![magnitude; 8];+ db.add("same", &vector).unwrap();+ db.add("opposite", &[-magnitude; 8]).unwrap();+ let found = db+ .search(+ &vector,+ &SearchParams {+ limit: Some(2),+ exact: true,+ ..Default::default()+ },+ )+ .unwrap();+ assert_eq!(found[0].key, "same");+ assert!(found[0].distance.abs() < 1.0e-6);+ assert_eq!(found[1].distance, 2.0);+ }+ }+fn seeded_unit_vector(seed: u64, dims: usize) -> Vec<f32> {let mut state = seed;let mut values: Vec<f32> = (0..dims)@@ -2123,9 +2392,9 @@ mod tests {db.flush().unwrap();drop(db);let mut captured_for_read_only =- Log::open(File::open(&path).unwrap(), &path, DIMS, None).unwrap();+ Log::open(File::open(&path).unwrap(), &path, DIMS, None, None).unwrap();let mut captured_for_writer =- Log::open(File::open(&path).unwrap(), &path, DIMS, None).unwrap();+ Log::open(File::open(&path).unwrap(), &path, DIMS, None, None).unwrap();let stale_end = captured_for_read_only.current_end_offset();let racer = open_writer(&path);bulk_add(&racer, &bulk_entries(2, 2, 500)).unwrap();@@ -2161,7 +2430,7 @@ mod tests {db.flush().unwrap();drop(db);let mut captured_for_read_only =- Log::open(File::open(&path).unwrap(), &path, DIMS, None).unwrap();+ Log::open(File::open(&path).unwrap(), &path, DIMS, None, None).unwrap();let stale_end = captured_for_read_only.current_end_offset();let racer = open_writer(&path);bulk_add(&racer, &bulk_entries(2, 2, 700)).unwrap();@@ -3044,6 +3313,7 @@ mod tests {dead_count: 0,dims: DIMS,storage: StorageKind::I8,+ metric: DistanceMetric::Cosine,log_bytes: 0,records_since_snapshot: 0,approximate_memory_bytes: 0,@@ -3628,14 +3898,14 @@ mod tests {let dir = TempDir::new().unwrap();let path = dir.path().join("db");drop(- Log::create(&path, DIMS, StorageKind::F32)+ Log::create(&path, DIMS, StorageKind::F32, DistanceMetric::Cosine).unwrap().into_file(),);let old_generation = generation_of(&path);let temp = temp_sibling(&path);drop(- Log::create(&temp, DIMS, StorageKind::F32)+ Log::create(&temp, DIMS, StorageKind::F32, DistanceMetric::InnerProduct).unwrap().into_file(),);@@ -3644,7 +3914,7 @@ mod tests {assert!(!temp.exists());assert_eq!(generation_of(&path), new_generation);assert_ne!(generation_of(&path), old_generation);- let log = open_existing_writer_log(&path, DIMS, None).unwrap();+ let log = open_existing_writer_log(&path, DIMS, None, None).unwrap();assert_eq!(log.generation(), new_generation);drop(log);assert!(matches!(@@ -3714,7 +3984,7 @@ mod tests {let WriterState { lock, log, .. } = take_writer(&db);let checkpoint = log.checkpoint();drop(log);- let mut foreign = open_existing_writer_log(&path, DIMS, None).unwrap();+ let mut foreign = open_existing_writer_log(&path, DIMS, None, None).unwrap();foreign.append(&[LogEntry::Add {key: "foreign",@@ -3749,7 +4019,8 @@ mod tests {let old_len = log.current_end_offset();drop(log);fs::remove_file(&path).unwrap();- let mut replacement = Log::create(&path, DIMS, StorageKind::F32).unwrap();+ let mut replacement =+ Log::create(&path, DIMS, StorageKind::F32, DistanceMetric::Cosine).unwrap();replacement.append(&[LogEntry::Add {key: "other",@@ -3981,6 +4252,7 @@ mod tests {dead_count: 0,dims: DIMS,storage: StorageKind::F32,+ metric: DistanceMetric::Cosine,log_bytes: 32,records_since_snapshot: 0,approximate_memory_bytes: 0,@@ -4072,7 +4344,7 @@ mod tests {drop(log);remove_data_files(&path).unwrap();drop(- Log::create(&path, DIMS, StorageKind::F32)+ Log::create(&path, DIMS, StorageKind::F32, DistanceMetric::Cosine).unwrap().into_file(),);@@ -5346,7 +5618,7 @@ mod tests {}fn logged_add_records(path: &Path, dims: usize) -> Vec<(String, StoredVector)> {- let mut log = Log::open(File::open(path).unwrap(), path, dims, None).unwrap();+ let mut log = Log::open(File::open(path).unwrap(), path, dims, None, None).unwrap();let mut scanner = log.scan().unwrap();let mut records = Vec::new();while let Some((record, _)) = scanner.next_record().unwrap() {