π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
vecdb: add opt-in int8 storage with fp32 in and out
laurenspriem2264c118ede8
diff --git a/rust/bindings/frb/photos/src/api/vecdb_api.rs b/rust/bindings/frb/photos/src/api/vecdb_api.rsindex f1c81698ff..27a8e2c08c 100644--- a/rust/bindings/frb/photos/src/api/vecdb_api.rs+++ b/rust/bindings/frb/photos/src/api/vecdb_api.rs@@ -17,6 +17,7 @@ pub enum RustVecDbError {InvalidDimensions { message: String },UnboundedSearch { message: String },LengthMismatch { message: String },+ StorageMismatch { message: String },}impl From<vecdb::VecDbError> for RustVecDbError {@@ -32,13 +33,34 @@ impl From<vecdb::VecDbError> for RustVecDbError {vecdb::VecDbError::InvalidVector(_) => Self::InvalidVector { message },vecdb::VecDbError::InvalidAttributes(_) => Self::InvalidAttributes { message },vecdb::VecDbError::DimensionMismatch { .. } => Self::DimensionMismatch { message },- vecdb::VecDbError::InvalidDimensions(_) => Self::InvalidDimensions { message },+ vecdb::VecDbError::InvalidDimensions { .. } => Self::InvalidDimensions { message },vecdb::VecDbError::UnboundedSearch => Self::UnboundedSearch { message },vecdb::VecDbError::LengthMismatch { .. } => Self::LengthMismatch { message },+ vecdb::VecDbError::StorageMismatch { .. } => Self::StorageMismatch { message },}}}+#[derive(Clone, Copy, Debug)]+pub enum VecDbStorage {+ F32,+ I8,+}++fn to_engine_storage(storage: VecDbStorage) -> vecdb::StorageKind {+ match storage {+ VecDbStorage::F32 => vecdb::StorageKind::F32,+ VecDbStorage::I8 => vecdb::StorageKind::I8,+ }+}++fn to_api_storage(storage: vecdb::StorageKind) -> VecDbStorage {+ match storage {+ vecdb::StorageKind::F32 => VecDbStorage::F32,+ vecdb::StorageKind::I8 => VecDbStorage::I8,+ }+}+#[derive(Clone, Debug)]pub enum VecDbAttrValue {Str(String),@@ -101,6 +123,7 @@ pub struct VecDbStats {pub live_count: u32,pub dead_count: u32,pub dims: u32,+ pub storage: VecDbStorage,pub log_bytes: u64,pub records_since_snapshot: u32,pub approximate_memory_bytes: u64,@@ -142,10 +165,20 @@ pub struct VecDb {}impl VecDb {- pub fn new(file_path: String, dimensions: u32) -> Result<Self, RustVecDbError> {- Ok(Self {- inner: vecdb::VecDb::open(Path::new(&file_path), dimensions as usize)?,- })+ pub fn new(+ file_path: String,+ dimensions: u32,+ storage: Option<VecDbStorage>,+ ) -> 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)?,+ };+ Ok(Self { inner })}pub fn open_read_only(file_path: String, dimensions: u32) -> Result<Self, RustVecDbError> {@@ -323,6 +356,7 @@ impl VecDb {live_count: stats.live_count as u32,dead_count: stats.dead_count as u32,dims: stats.dims as u32,+ storage: to_api_storage(stats.storage),log_bytes: stats.log_bytes,records_since_snapshot: stats.records_since_snapshot as u32,approximate_memory_bytes: stats.approximate_memory_bytes as u64,@@ -379,7 +413,7 @@ mod tests {#[test]fn add_search_stats_round_trip() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, 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();@@ -434,7 +468,7 @@ mod tests {#[test]fn bulk_add_rejects_length_mismatch() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, None).unwrap();let error = db.bulk_add_vectors(vec![key("a")], vec![basis(0), basis(1)]).unwrap_err();@@ -445,7 +479,7 @@ mod tests {#[test]fn similarity_threshold_conversion_edges() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, None).unwrap();db.add_vector(key("a"), basis(0)).unwrap();db.add_vector(key("b"), basis(1)).unwrap();let close = db@@ -469,7 +503,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).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, None).unwrap();db.bulk_add_vectors(vec![key("a"), key("b"), key("c")],vec![basis(0), basis(1), basis(2)],@@ -535,7 +569,7 @@ mod tests {#[test]fn bulk_filtered_search_stays_query_aligned() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, None).unwrap();db.bulk_add_vectors(vec![key("a"), key("b"), key("c")],vec![basis(0), basis(1), basis(2)],@@ -589,7 +623,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).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, None).unwrap();db.bulk_add_vectors(vec![key("a"), key("b"), key("c")],vec![basis(0), basis(1), basis(2)],@@ -627,7 +661,7 @@ mod tests {#[test]fn attrs_round_trip_through_the_api() {let dir = TestDir::create();- let db = VecDb::new(dir.db_path(), DIMS).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, None).unwrap();let attrs = vec![VecDbAttr {name: key("model"),@@ -720,7 +754,7 @@ mod tests {check_open_cost(dir.db_path()),VecDbOpenCost::Absent));- let db = VecDb::new(dir.db_path(), DIMS).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, None).unwrap();db.add_vector(key("a"), basis(0)).unwrap();assert!(matches!(check_open_cost(dir.db_path()),@@ -742,7 +776,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).unwrap();+ let db = VecDb::new(dir.db_path(), DIMS, None).unwrap();db.add_vector(key("a"), basis(0)).unwrap();db.flush().unwrap();delete_vec_db_files(dir.db_path()).unwrap();@@ -753,7 +787,7 @@ mod tests {db.get_index_stats(),Err(RustVecDbError::Closed { .. })));- let reopened = VecDb::new(dir.db_path(), DIMS).unwrap();+ let reopened = VecDb::new(dir.db_path(), DIMS, None).unwrap();assert_eq!(reopened.get_index_stats().unwrap().live_count, 0);reopened.add_vector(key("b"), basis(1)).unwrap();drop(reopened);@@ -761,4 +795,99 @@ mod tests {assert!(!PathBuf::from(dir.db_path()).exists());delete_vec_db_files(dir.db_path()).unwrap();}++ fn i8_vector(seed: u32) -> Vec<f32> {+ let raw: Vec<f32> = (0..32)+ .map(|index| ((index * 7 + seed * 13) % 23) as f32 - 11.0)+ .collect();+ let norm = raw.iter().map(|value| value * value).sum::<f32>().sqrt();+ raw.into_iter().map(|value| value / norm).collect()+ }++ #[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();+ assert!(matches!(+ db.get_index_stats().unwrap().storage,+ VecDbStorage::I8+ ));+ let vector = i8_vector(1);+ db.add_vector(key("a"), vector.clone()).unwrap();+ db.bulk_add_vectors(vec![key("b"), key("c")], vec![i8_vector(2), i8_vector(3)])+ .unwrap();+ let max_abs = vector+ .iter()+ .fold(0.0f32, |acc, value| acc.max(value.abs()));+ let fetched = db.bulk_get_vectors(vec![key("a"), key("missing")]);+ assert!(fetched[1].is_none());+ for (restored, original) in fetched[0].as_ref().unwrap().iter().zip(&vector) {+ assert!((restored - original).abs() <= max_abs / 254.0 + 1.0e-6);+ }+ let found = db+ .search(vector.clone(), Some(1), None, true, None)+ .unwrap();+ assert_eq!(found[0].key, "a");+ assert!(found[0].distance.abs() < 0.02);+ let stats = db.get_index_stats().unwrap();+ assert_eq!(stats.live_count, 3);+ assert_eq!(stats.dims, 32);+ assert!(matches!(stats.storage, VecDbStorage::I8));+ assert!(matches!(+ VecDb::new(dir.db_path(), 32, Some(VecDbStorage::F32)),+ Err(RustVecDbError::StorageMismatch { .. })+ ));+ let joined = VecDb::new(dir.db_path(), 32, None).unwrap();+ assert!(matches!(+ joined.get_index_stats().unwrap().storage,+ VecDbStorage::I8+ ));+ drop(joined);+ db.flush().unwrap();+ drop(db);+ let read_only = VecDb::open_read_only(dir.db_path(), 32).unwrap();+ assert!(matches!(+ read_only.get_index_stats().unwrap().storage,+ VecDbStorage::I8+ ));+ 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)),+ Err(RustVecDbError::StorageMismatch { message }) if message.contains("f32") && message.contains("i8")+ ));+ let reopened = VecDb::new(dir.db_path(), 32, None).unwrap();+ assert!(matches!(+ reopened.get_index_stats().unwrap().storage,+ VecDbStorage::I8+ ));+ let again = reopened.search(vector, Some(1), None, false, None).unwrap();+ assert_eq!(again[0].key, "a");+ }++ #[test]+ fn storage_defaults_to_f32_and_rejects_i8_dims_off_the_lane_grid() {+ let dir = TestDir::create();+ let db = VecDb::new(dir.db_path(), DIMS, None).unwrap();+ assert!(matches!(+ db.get_index_stats().unwrap().storage,+ VecDbStorage::F32+ ));+ let explicit = VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::F32)).unwrap();+ assert!(matches!(+ explicit.get_index_stats().unwrap().storage,+ VecDbStorage::F32+ ));+ assert!(matches!(+ VecDb::new(dir.db_path(), DIMS, Some(VecDbStorage::I8)),+ Err(RustVecDbError::StorageMismatch { .. })+ ));+ let other = TestDir::create();+ assert!(matches!(+ VecDb::new(other.db_path(), DIMS, Some(VecDbStorage::I8)),+ 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());+ }}diff --git a/rust/crates/ml/examples/vecdb_bench.rs b/rust/crates/ml/examples/vecdb_bench.rsindex 93cc90fcaa..acff613a8d 100644--- a/rust/crates/ml/examples/vecdb_bench.rs+++ b/rust/crates/ml/examples/vecdb_bench.rs@@ -2,7 +2,7 @@ use std::collections::HashSet;use std::path::{Path, PathBuf};use std::time::{Duration, Instant};-use ente_ml::vecdb::{AttrValue, Attribute, Match, SearchParams, VecDb};+use ente_ml::vecdb::{AttrValue, Attribute, Match, SearchParams, StorageKind, VecDb};const SEED: u64 = 0xE47E_0000_0000_0001;const LATENT_DIMS: usize = 24;@@ -20,6 +20,7 @@ struct Config {scales: Vec<usize>,dims: usize,attrs: bool,+ storage: StorageKind,}struct BenchData {@@ -30,6 +31,7 @@ struct BenchData {}struct VecdbReport {+ storage: StorageKind,single_count: usize,single_total: Duration,bulk_count: usize,@@ -38,6 +40,7 @@ struct VecdbReport {approx_total: Duration,exact_total: Duration,recall: f64,+ truth_recall: Option<f64>,threshold: f32,threshold_total: Duration,threshold_avg_hits: f64,@@ -58,8 +61,9 @@ struct VecdbReport {fn main() {let config = parse_args();println!(- "vecdb bench dims={} queries={} seed={:#018x}{}",+ "vecdb bench dims={} storage={} queries={} seed={:#018x}{}",config.dims,+ storage_name(config.storage),QUERY_COUNT,SEED,if config.attrs { " attrs=on" } else { "" }@@ -75,7 +79,13 @@ fn main() {);let temp_root = tempfile::TempDir::new().expect("create bench temp dir");for &scale in &config.scales {- run_scale(scale, config.dims, config.attrs, temp_root.path());+ run_scale(+ scale,+ config.dims,+ config.attrs,+ config.storage,+ temp_root.path(),+ );}}@@ -83,6 +93,7 @@ fn parse_args() -> Config {let mut scales = parse_scales(DEFAULT_SCALES);let mut dims = DEFAULT_DIMS;let mut attrs = false;+ let mut storage = StorageKind::F32;let mut args = std::env::args().skip(1);while let Some(arg) = args.next() {match arg.as_str() {@@ -93,17 +104,32 @@ fn parse_args() -> Config {.unwrap_or_else(|_| usage_exit())}"--attrs" => attrs = true,+ "--storage" => {+ storage = match required_value(args.next()).as_str() {+ "f32" => StorageKind::F32,+ "i8" => StorageKind::I8,+ _ => usage_exit(),+ }+ }_ => usage_exit(),}}- if dims == 0 || !dims.is_multiple_of(8) {- eprintln!("--dims must be a nonzero multiple of 8");+ let lane_width = match storage {+ StorageKind::F32 => 8,+ StorageKind::I8 => 32,+ };+ if dims == 0 || !dims.is_multiple_of(lane_width) {+ eprintln!(+ "--dims must be a nonzero multiple of {lane_width} for {} storage",+ storage_name(storage)+ );std::process::exit(2);}Config {scales,dims,attrs,+ storage,}}@@ -128,20 +154,30 @@ fn parse_scales(list: &str) -> Vec<usize> {fn usage_exit() -> ! {eprintln!("usage: cargo run -p ente-ml --example vecdb_bench --release -- \- [--scales 10000,100000] [--dims 512] [--attrs]"+ [--scales 10000,100000] [--dims 512] [--attrs] [--storage f32|i8]");std::process::exit(2);}-fn run_scale(scale: usize, dims: usize, attrs: bool, temp_root: &Path) {+fn storage_name(storage: StorageKind) -> &'static str {+ match storage {+ StorageKind::F32 => "f32",+ StorageKind::I8 => "i8",+ }+}++fn run_scale(scale: usize, dims: usize, attrs: bool, storage: StorageKind, temp_root: &Path) {let clusters = (scale / 150).max(1) as u64;println!();- println!("=== scale {scale} dims {dims} clusters {clusters} ===");+ println!(+ "=== scale {scale} dims {dims} storage {} clusters {clusters} ===",+ storage_name(storage)+ );eprintln!("[scale {scale}] generating data");let data = generate_data(scale, dims, clusters);let dir = temp_root.join(format!("scale-{scale}-{dims}"));std::fs::create_dir_all(&dir).expect("create bench dir");- let vecdb = run_vecdb(&data, dims, attrs, &dir, scale);+ let vecdb = run_vecdb(&data, dims, attrs, storage, &dir, scale);print_vecdb_report(&vecdb);let _ = std::fs::remove_dir_all(&dir);}@@ -245,6 +281,7 @@ struct SearchTimings {approx_total: Duration,exact_total: Duration,recall: f64,+ truth_recall: Option<f64>,threshold: f32,threshold_total: Duration,threshold_avg_hits: f64,@@ -265,11 +302,18 @@ struct CompactionTimings {compaction_fired: bool,}-fn run_vecdb(data: &BenchData, dims: usize, attrs: bool, dir: &Path, scale: usize) -> VecdbReport {+fn run_vecdb(+ data: &BenchData,+ dims: usize,+ attrs: bool,+ storage: StorageKind,+ dir: &Path,+ scale: usize,+) -> VecdbReport {let path = dir.join("bench.vecdb");- let mut db = VecDb::open(&path, dims).expect("open vecdb");+ let mut db = VecDb::open_with_storage(&path, dims, storage).expect("open vecdb");let ingest = ingest_phase(&mut db, data, attrs, scale);- let searches = search_phase(&db, data, scale);+ let searches = search_phase(&db, data, storage, scale);let stats = db.stats().expect("vecdb stats");let snapshot_file = PathBuf::from(format!("{}.graph", path.display()));let snapshot_bytes = std::fs::metadata(&snapshot_file)@@ -280,6 +324,7 @@ fn run_vecdb(data: &BenchData, dims: usize, attrs: bool, dir: &Path, scale: usizlet compaction = compaction_phase(&mut db, data, scale);db.delete().expect("vecdb delete");VecdbReport {+ storage,single_count: ingest.single_count,single_total: ingest.single_total,bulk_count: ingest.bulk_count,@@ -288,6 +333,7 @@ fn run_vecdb(data: &BenchData, dims: usize, attrs: bool, dir: &Path, scale: usizapprox_total: searches.approx_total,exact_total: searches.exact_total,recall: searches.recall,+ truth_recall: searches.truth_recall,threshold: searches.threshold,threshold_total: searches.threshold_total,threshold_avg_hits: searches.threshold_avg_hits,@@ -391,7 +437,7 @@ fn ingest_phase(db: &mut VecDb, data: &BenchData, attrs: bool, scale: usize) ->}}-fn search_phase(db: &VecDb, data: &BenchData, scale: usize) -> SearchTimings {+fn search_phase(db: &VecDb, data: &BenchData, storage: StorageKind, scale: usize) -> SearchTimings {eprintln!("[scale {scale}] vecdb searches");let approx_params = limit_params(SEARCH_K, false);let exact_params = limit_params(SEARCH_K, true);@@ -400,6 +446,14 @@ fn search_phase(db: &VecDb, data: &BenchData, scale: usize) -> SearchTimings {warm(db, &data.queries, &exact_params);let (exact_total, exact_results) = timed_searches(db, &data.queries, &exact_params);let recall = recall_at_k(&exact_results, &approx_results, SEARCH_K);+ let truth_recall = match storage {+ StorageKind::F32 => None,+ StorageKind::I8 => {+ eprintln!("[scale {scale}] f32 ground truth (brute force)");+ let truth = f32_ground_truth(data, SEARCH_K);+ Some(recall_at_k(&truth, &exact_results, SEARCH_K))+ }+ };let threshold = one_percent_threshold(db, data);let threshold_params = SearchParams {limit: None,@@ -458,6 +512,7 @@ fn search_phase(db: &VecDb, data: &BenchData, scale: usize) -> SearchTimings {approx_total,exact_total,recall,+ truth_recall,threshold,threshold_total,threshold_avg_hits,@@ -537,6 +592,49 @@ fn timed_searches((started.elapsed(), results)}+fn dot(a: &[f32], b: &[f32]) -> f32 {+ let mut partials = [0.0f32; 8];+ for (x, y) in a.as_chunks::<8>().0.iter().zip(b.as_chunks::<8>().0) {+ for (partial, (left, right)) in partials.iter_mut().zip(x.iter().zip(y)) {+ *partial += left * right;+ }+ }+ partials.iter().sum()+}++fn f32_ground_truth(data: &BenchData, k: usize) -> Vec<Vec<Match>> {+ let corpus: Vec<(&str, &[f32])> = data+ .entries+ .iter()+ .map(|(key, vector)| (key.as_str(), vector.as_slice()))+ .chain(std::iter::once(("bench-probe", data.probe.as_slice())))+ .collect();+ data.queries+ .iter()+ .map(|query| {+ let mut scored: Vec<(f32, &str)> = corpus+ .iter()+ .map(|(key, vector)| (1.0 - dot(query, vector), *key))+ .collect();+ let keep = k.min(scored.len());+ if keep < scored.len() {+ scored.select_nth_unstable_by(keep, |a, b| {+ a.0.total_cmp(&b.0).then_with(|| a.1.cmp(b.1))+ });+ }+ scored.truncate(keep);+ scored.sort_unstable_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(b.1)));+ scored+ .into_iter()+ .map(|(distance, key)| Match {+ key: key.to_string(),+ distance,+ })+ .collect()+ })+ .collect()+}+fn recall_at_k(truth: &[Vec<Match>], found: &[Vec<Match>], k: usize) -> f64 {let mut hits = 0usize;let mut total = 0usize;@@ -608,8 +706,18 @@ fn print_vecdb_report(report: &VecdbReport) {);println!(" {:<44} {:.4}",- "recall@10 (approx vs exact)", report.recall+ match report.storage {+ StorageKind::F32 => "recall@10 (approx vs exact)",+ StorageKind::I8 => "recall@10 (approx vs i8-exact)",+ },+ report.recall);+ if let Some(truth_recall) = report.truth_recall {+ println!(+ " {:<44} {:.4}",+ "recall@10 (i8-exact vs f32 truth)", truth_recall+ );+ }row(&format!("search approx threshold d<={:.4} (~1%)", report.threshold),format!("{QUERY_COUNT} queries"),diff --git a/rust/crates/ml/src/vecdb/arena.rs b/rust/crates/ml/src/vecdb/arena.rsindex 9641aaac2b..4c24fcd3e6 100644--- a/rust/crates/ml/src/vecdb/arena.rs+++ b/rust/crates/ml/src/vecdb/arena.rs@@ -1,9 +1,11 @@use std::collections::HashMap;-use super::VecDbError;use super::kernel::{- F32Kernel, LANE_WIDTH, Lane, VectorKernel, pack_lanes, pack_lanes_into, unpack_lanes,+ F32Kernel, I8Kernel, Lane, LaneI8, StoredVector, VectorKernel, VectorPayload, dequantize,+ 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};pub(crate) const VECTORS_PER_CHUNK: usize = 4096;pub(crate) const MAX_KEY_BYTES: usize = 256;@@ -28,10 +30,81 @@ pub(crate) fn validate_key(key: &str) -> Result<(), VecDbError> {Ok(())}+enum Storage {+ F32 {+ chunks: Vec<Vec<Lane>>,+ },+ I8 {+ chunks: Vec<Vec<LaneI8>>,+ scales: Vec<f32>,+ },+}++impl Storage {+ fn kind(&self) -> StorageKind {+ match self {+ Self::F32 { .. } => StorageKind::F32,+ Self::I8 { .. } => StorageKind::I8,+ }+ }++ fn chunk_count(&self) -> usize {+ match self {+ Self::F32 { chunks } => chunks.len(),+ Self::I8 { chunks, .. } => chunks.len(),+ }+ }++ fn push_chunk(&mut self, lanes_per_vector: usize) {+ match self {+ Self::F32 { chunks } => {+ chunks.push(vec![Lane::ZERO; VECTORS_PER_CHUNK * lanes_per_vector]);+ }+ Self::I8 { chunks, .. } => {+ chunks.push(vec![LaneI8::ZERO; VECTORS_PER_CHUNK * lanes_per_vector]);+ }+ }+ }+}++pub(crate) enum PackedQuery {+ F32(Vec<Lane>),+ I8 { scale: f32, lanes: Vec<LaneI8> },+}++impl PackedQuery {+ pub(crate) fn as_query(&self) -> Query<'_> {+ match self {+ Self::F32(lanes) => Query::F32(lanes),+ Self::I8 { scale, lanes } => Query::I8 {+ scale: *scale,+ lanes,+ },+ }+ }+}++#[derive(Clone, Copy)]+pub(crate) enum Query<'a> {+ F32(&'a [Lane]),+ I8 { scale: f32, lanes: &'a [LaneI8] },+}++impl Query<'_> {+ pub(crate) fn is_finite(&self) -> bool {+ match self {+ Self::F32(lanes) => lanes+ .iter()+ .all(|lane| lane.to_array().iter().all(|value| value.is_finite())),+ Self::I8 { scale, .. } => scale.is_finite(),+ }+ }+}+pub(crate) struct VectorArena {dims: usize,lanes_per_vector: usize,- chunks: Vec<Vec<Lane>>,+ storage: Storage,keys_to_slots: HashMap<Box<str>, u32>,slots_to_keys: Vec<Box<str>>,alive: Vec<u64>,@@ -41,13 +114,22 @@ pub(crate) struct VectorArena {impl VectorArena {pub(crate) fn new(dims: usize) -> Result<Self, VecDbError> {- if dims == 0 || !dims.is_multiple_of(LANE_WIDTH) {- return Err(VecDbError::InvalidDimensions(dims));- }+ Self::with_storage(dims, StorageKind::F32)+ }++ pub(crate) fn with_storage(dims: usize, storage: StorageKind) -> Result<Self, VecDbError> {+ validate_dims(dims, storage)?;+ let storage = match storage {+ StorageKind::F32 => Storage::F32 { chunks: Vec::new() },+ StorageKind::I8 => Storage::I8 {+ chunks: Vec::new(),+ scales: Vec::new(),+ },+ };Ok(Self {dims,- lanes_per_vector: dims / LANE_WIDTH,- chunks: Vec::new(),+ lanes_per_vector: dims / storage.kind().lane_width(),+ storage,keys_to_slots: HashMap::new(),slots_to_keys: Vec::new(),alive: Vec::new(),@@ -60,6 +142,10 @@ impl VectorArena {self.dims}+ pub(crate) fn storage_kind(&self) -> StorageKind {+ self.storage.kind()+ }+pub(crate) fn live_count(&self) -> usize {self.live_count}@@ -76,20 +162,46 @@ impl VectorArena {self.live_count == 0}+ 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>(),+ }+ }++ #[cfg(test)]pub(crate) fn upsert(&mut self,key: &str,vector: &[f32],+ ) -> Result<UpsertOutcome, VecDbError> {+ match quantize_for(self.storage_kind(), vector) {+ Some(quantized) => self.upsert_payload(key, quantized.as_payload()),+ None => self.upsert_payload(key, VectorPayload::F32(vector)),+ }+ }++ pub(crate) fn upsert_payload(+ &mut self,+ key: &str,+ payload: VectorPayload<'_>,) -> Result<UpsertOutcome, VecDbError> {validate_key(key)?;- if vector.len() != self.dims {+ if payload.storage() != self.storage_kind() {+ return Err(VecDbError::StorageMismatch {+ expected: self.storage_kind(),+ actual: payload.storage(),+ });+ }+ if payload.dims() != self.dims {return Err(VecDbError::DimensionMismatch {expected: self.dims,- actual: vector.len(),+ actual: payload.dims(),});}if let Some(&slot) = self.keys_to_slots.get(key) {- self.write_vector(slot, vector);+ self.write_vector(slot, payload);return Ok(UpsertOutcome::ReplacedInPlace(slot));}if let Some(slot) = self.free_slots.pop() {@@ -97,13 +209,15 @@ impl VectorArena {self.keys_to_slots.insert(Box::from(key), slot);self.mark_alive(slot);self.live_count += 1;- self.write_vector(slot, vector);+ self.write_vector(slot, payload);return Ok(UpsertOutcome::RecycledSlot(slot));}let slot = self.slots_to_keys.len() as u32;- if slot as usize == self.chunks.len() * VECTORS_PER_CHUNK {- self.chunks- .push(vec![Lane::ZERO; VECTORS_PER_CHUNK * self.lanes_per_vector]);+ if slot as usize == self.storage.chunk_count() * VECTORS_PER_CHUNK {+ self.storage.push_chunk(self.lanes_per_vector);+ }+ if let Storage::I8 { scales, .. } = &mut self.storage {+ scales.push(0.0);}if slot as usize / 64 == self.alive.len() {self.alive.push(0);@@ -112,7 +226,7 @@ impl VectorArena {self.keys_to_slots.insert(Box::from(key), slot);self.mark_alive(slot);self.live_count += 1;- self.write_vector(slot, vector);+ self.write_vector(slot, payload);Ok(UpsertOutcome::NewSlot(slot))}@@ -145,8 +259,19 @@ impl VectorArena {self.slots_to_keys.truncate(live);self.slots_to_keys.shrink_to_fit();self.keys_to_slots.shrink_to_fit();- self.chunks.truncate(live.div_ceil(VECTORS_PER_CHUNK));- self.chunks.shrink_to_fit();+ let chunk_count = live.div_ceil(VECTORS_PER_CHUNK);+ match &mut self.storage {+ Storage::F32 { chunks } => {+ chunks.truncate(chunk_count);+ chunks.shrink_to_fit();+ }+ Storage::I8 { chunks, scales } => {+ chunks.truncate(chunk_count);+ chunks.shrink_to_fit();+ scales.truncate(live);+ scales.shrink_to_fit();+ }+ }self.alive.clear();self.alive.resize(live.div_ceil(64), u64::MAX);self.alive.shrink_to_fit();@@ -160,16 +285,12 @@ impl VectorArena {fn move_vector(&mut self, src: u32, dst: u32) {let lanes = self.lanes_per_vector;- let src_chunk = src as usize / VECTORS_PER_CHUNK;- let dst_chunk = dst as usize / VECTORS_PER_CHUNK;- let src_start = (src as usize % VECTORS_PER_CHUNK) * lanes;- let dst_start = (dst as usize % VECTORS_PER_CHUNK) * lanes;- if src_chunk == dst_chunk {- self.chunks[src_chunk].copy_within(src_start..src_start + lanes, dst_start);- } else {- let (front, back) = self.chunks.split_at_mut(src_chunk);- front[dst_chunk][dst_start..dst_start + lanes]- .copy_from_slice(&back[0][src_start..src_start + lanes]);+ match &mut self.storage {+ Storage::F32 { chunks } => move_lanes(chunks, lanes, src, dst),+ Storage::I8 { chunks, scales } => {+ move_lanes(chunks, lanes, src, dst);+ scales[dst as usize] = scales[src as usize];+ }}}@@ -195,40 +316,104 @@ impl VectorArena {(0..self.slots_to_keys.len() as u32).filter(|slot| self.is_alive(*slot))}- pub(crate) fn vector_lanes(&self, slot: u32) -> &[Lane] {- let start = (slot as usize % VECTORS_PER_CHUNK) * self.lanes_per_vector;- &self.chunks[slot as usize / VECTORS_PER_CHUNK][start..start + self.lanes_per_vector]+ pub(crate) fn stored_query(&self, slot: u32) -> Query<'_> {+ let lanes = self.lanes_per_vector;+ match &self.storage {+ Storage::F32 { chunks } => Query::F32(slot_lanes(chunks, lanes, slot)),+ Storage::I8 { chunks, scales } => Query::I8 {+ scale: scales[slot as usize],+ lanes: slot_lanes(chunks, lanes, slot),+ },+ }}pub(crate) fn vector_values(&self, slot: u32) -> Vec<f32> {- unpack_lanes(self.vector_lanes(slot))+ match self.stored_query(slot) {+ Query::F32(lanes) => unpack_lanes(lanes),+ Query::I8 { scale, lanes } => dequantize(scale, &unpack_lanes_i8(lanes)),+ }}- pub(crate) fn pack_query(&self, values: &[f32]) -> Result<Vec<Lane>, VecDbError> {+ 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 {+ scale,+ values: unpack_lanes_i8(lanes),+ },+ }+ }++ pub(crate) fn pack_query(&self, values: &[f32]) -> Result<PackedQuery, VecDbError> {if values.len() != self.dims {return Err(VecDbError::DimensionMismatch {expected: self.dims,actual: values.len(),});}- Ok(pack_lanes(values))+ 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)),+ })}pub(crate) fn distance_between_slots(&self, a: u32, b: u32) -> f32 {- F32Kernel::distance(self.vector_lanes(a), self.vector_lanes(b))- }-- pub(crate) fn distance_to_query(&self, query: &[Lane], slot: u32) -> f32 {- F32Kernel::distance(query, self.vector_lanes(slot))+ 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],+ ),+ }}- fn vector_lanes_mut(&mut self, slot: u32) -> &mut [Lane] {- let start = (slot as usize % VECTORS_PER_CHUNK) * self.lanes_per_vector;- &mut self.chunks[slot as usize / VECTORS_PER_CHUNK][start..start + self.lanes_per_vector]+ 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))+ }+ (+ Storage::I8 { chunks, scales },+ Query::I8 {+ scale,+ lanes: query,+ },+ ) => 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")+ }+ }}- fn write_vector(&mut self, slot: u32, values: &[f32]) {- pack_lanes_into(values, self.vector_lanes_mut(slot));+ fn write_vector(&mut self, slot: u32, payload: VectorPayload<'_>) {+ let lanes = self.lanes_per_vector;+ match (&mut self.storage, payload) {+ (Storage::F32 { chunks }, VectorPayload::F32(values)) => {+ pack_lanes_into(values, slot_lanes_mut(chunks, lanes, slot));+ }+ (Storage::I8 { chunks, scales }, VectorPayload::I8 { scale, values }) => {+ pack_lanes_i8_into(values, slot_lanes_mut(chunks, lanes, slot));+ scales[slot as usize] = scale;+ }+ (Storage::F32 { .. }, VectorPayload::I8 { .. })+ | (Storage::I8 { .. }, VectorPayload::F32(_)) => {+ unreachable!("payload kind is validated before a slot is written")+ }+ }}fn mark_alive(&mut self, slot: u32) {@@ -240,6 +425,30 @@ impl VectorArena {}}+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]+}++fn slot_lanes_mut<T>(chunks: &mut [Vec<T>], lanes_per_vector: usize, slot: u32) -> &mut [T] {+ let start = (slot as usize % VECTORS_PER_CHUNK) * lanes_per_vector;+ &mut chunks[slot as usize / VECTORS_PER_CHUNK][start..start + lanes_per_vector]+}++fn move_lanes<T: Copy>(chunks: &mut [Vec<T>], lanes: usize, src: u32, dst: u32) {+ let src_chunk = src as usize / VECTORS_PER_CHUNK;+ let dst_chunk = dst as usize / VECTORS_PER_CHUNK;+ let src_start = (src as usize % VECTORS_PER_CHUNK) * lanes;+ let dst_start = (dst as usize % VECTORS_PER_CHUNK) * lanes;+ if src_chunk == dst_chunk {+ chunks[src_chunk].copy_within(src_start..src_start + lanes, dst_start);+ } else {+ let (front, back) = chunks.split_at_mut(src_chunk);+ front[dst_chunk][dst_start..dst_start + lanes]+ .copy_from_slice(&back[0][src_start..src_start + lanes]);+ }+}+#[cfg(test)]mod tests {use super::super::kernel::splitmix64;@@ -255,6 +464,15 @@ mod tests {.collect()}+ fn seeded_unit_vector(seed: u64, dims: usize) -> Vec<f32> {+ let mut values = seeded_vector(seed, dims);+ let norm = values.iter().map(|value| value * value).sum::<f32>().sqrt();+ for value in &mut values {+ *value /= norm;+ }+ values+ }+fn basis_vector(dims: usize, axis: usize) -> Vec<f32> {let mut values = vec![0.0; dims];values[axis] = 1.0;@@ -271,20 +489,74 @@ mod tests {arena}+ fn lane_address(query: Query<'_>) -> usize {+ match query {+ Query::F32(lanes) => lanes.as_ptr() as usize,+ Query::I8 { lanes, .. } => lanes.as_ptr() as usize,+ }+ }++ fn stored_i8(arena: &VectorArena, slot: u32) -> (f32, Vec<i8>) {+ match arena.stored_vector(slot) {+ StoredVector::I8 { scale, values } => (scale, values),+ StoredVector::F32(_) => panic!("expected i8 storage"),+ }+ }+#[test]fn rejects_invalid_dimensions() {assert!(matches!(VectorArena::new(0),- Err(VecDbError::InvalidDimensions(0))+ Err(VecDbError::InvalidDimensions {+ dims: 0,+ storage: StorageKind::F32+ })));assert!(matches!(VectorArena::new(12),- Err(VecDbError::InvalidDimensions(12))+ Err(VecDbError::InvalidDimensions {+ dims: 12,+ storage: StorageKind::F32+ })));assert!(VectorArena::new(8).is_ok());assert!(VectorArena::new(512).is_ok());}+ #[test]+ fn i8_storage_requires_a_nonzero_multiple_of_32_dims() {+ for dims in [0usize, 8, 16, 24, 40, 100] {+ assert!(matches!(+ VectorArena::with_storage(dims, StorageKind::I8),+ Err(VecDbError::InvalidDimensions {+ dims: rejected,+ storage: StorageKind::I8+ }) if rejected == dims+ ));+ }+ for dims in [32usize, 64, 512, 1024] {+ let arena = VectorArena::with_storage(dims, StorageKind::I8).unwrap();+ assert_eq!(arena.storage_kind(), StorageKind::I8);+ assert_eq!(arena.dims(), dims);+ }+ assert_eq!(+ VectorArena::with_storage(8, StorageKind::F32)+ .unwrap()+ .storage_kind(),+ StorageKind::F32+ );+ assert_eq!(+ VectorArena::new(8).unwrap().storage_kind(),+ StorageKind::F32+ );+ let Err(error) = VectorArena::with_storage(8, StorageKind::I8) else {+ panic!("expected an invalid dimensions error");+ };+ let message = error.to_string();+ assert!(message.contains("i8"));+ assert!(message.contains("32"));+ }+#[test]fn rejects_invalid_keys() {let mut arena = VectorArena::new(8).unwrap();@@ -325,6 +597,62 @@ mod tests {actual: 24})));+ let mut i8_arena = VectorArena::with_storage(32, StorageKind::I8).unwrap();+ assert!(matches!(+ i8_arena.upsert("key", &seeded_vector(1, 64)),+ Err(VecDbError::DimensionMismatch {+ expected: 32,+ actual: 64+ })+ ));+ assert!(matches!(+ i8_arena.pack_query(&seeded_vector(1, 8)),+ Err(VecDbError::DimensionMismatch {+ expected: 32,+ actual: 8+ })+ ));+ assert_eq!(i8_arena.slot_count(), 0);+ }++ #[test]+ fn payload_kind_must_match_the_arena_storage() {+ let mut f32_arena = VectorArena::new(32).unwrap();+ let mut i8_arena = VectorArena::with_storage(32, StorageKind::I8).unwrap();+ let values = seeded_vector(3, 32);+ let quantized = StoredVector::quantize(&values);+ assert!(matches!(+ f32_arena.upsert_payload("k", quantized.as_payload()),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::F32,+ actual: StorageKind::I8+ })+ ));+ assert!(matches!(+ i8_arena.upsert_payload("k", VectorPayload::F32(&values)),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::I8,+ actual: StorageKind::F32+ })+ ));+ assert_eq!(f32_arena.slot_count(), 0);+ assert_eq!(i8_arena.slot_count(), 0);+ assert!(f32_arena.slot_of_key("k").is_none());+ assert!(i8_arena.slot_of_key("k").is_none());+ assert_eq!(+ f32_arena+ .upsert_payload("k", VectorPayload::F32(&values))+ .unwrap(),+ UpsertOutcome::NewSlot(0)+ );+ assert_eq!(+ i8_arena+ .upsert_payload("k", quantized.as_payload())+ .unwrap(),+ UpsertOutcome::NewSlot(0)+ );+ assert_eq!(f32_arena.vector_values(0), values);+ assert_eq!(i8_arena.stored_vector(0), quantized);}#[test]@@ -558,7 +886,7 @@ mod tests {.upsert(&format!("key-{index}"), &seeded_vector(index, 8)).unwrap();}- assert_eq!(arena.chunks.len(), 2);+ assert_eq!(arena.storage.chunk_count(), 2);for index in (0..1000u64).step_by(2) {assert!(arena.remove(&format!("key-{index}")).is_some());}@@ -575,7 +903,7 @@ mod tests {let live = count - 500;assert_eq!(arena.live_count(), live);assert_eq!(arena.slot_count(), live);- assert_eq!(arena.chunks.len(), 1);+ assert_eq!(arena.storage.chunk_count(), 1);assert_eq!(arena.alive.len(), live.div_ceil(64));assert!(arena.free_slots.is_empty());for (index, (key, vector)) in expected.iter().enumerate() {@@ -583,7 +911,7 @@ mod tests {assert_eq!(&arena.vector_values(index as u32), vector);}for slot in arena.live_slots() {- assert_eq!(arena.vector_lanes(slot).as_ptr() as usize % 32, 0);+ assert_eq!(lane_address(arena.stored_query(slot)) % 32, 0);}}@@ -618,7 +946,7 @@ mod tests {assert_eq!(arena.live_count(), 0);assert_eq!(arena.slot_count(), 0);assert_eq!(arena.dead_count(), 0);- assert!(arena.chunks.is_empty());+ assert_eq!(arena.storage.chunk_count(), 0);assert!(arena.alive.is_empty());assert_eq!(arena.upsert("d", &seeded_vector(4, 8)).unwrap(),@@ -686,8 +1014,27 @@ mod tests {.unwrap();}for slot in arena.live_slots() {- assert_eq!(arena.vector_lanes(slot).as_ptr() as usize % 32, 0);+ assert_eq!(lane_address(arena.stored_query(slot)) % 32, 0);+ }+ }++ #[test]+ fn every_i8_slotted_vector_is_32_byte_aligned_across_chunks() {+ let mut arena = VectorArena::with_storage(32, StorageKind::I8).unwrap();+ for index in 0..4200u64 {+ arena+ .upsert(&format!("key-{index}"), &seeded_vector(index, 32))+ .unwrap();+ }+ assert_eq!(arena.storage.chunk_count(), 2);+ assert_eq!(arena.slot_of_key("key-4199"), Some(4199));+ for slot in arena.live_slots() {+ assert_eq!(lane_address(arena.stored_query(slot)) % 32, 0);}+ let Storage::I8 { scales, .. } = &arena.storage else {+ panic!("expected i8 storage");+ };+ assert_eq!(scales.len(), 4200);}#[test]@@ -698,7 +1045,221 @@ mod tests {assert_eq!(arena.distance_between_slots(0, 0), 0.0);assert_eq!(arena.distance_between_slots(0, 1), 1.0);let query = arena.pack_query(&basis_vector(16, 0)).unwrap();- assert_eq!(arena.distance_to_query(&query, 0), 0.0);- assert_eq!(arena.distance_to_query(&query, 1), 1.0);+ assert_eq!(arena.distance_to_query(query.as_query(), 0), 0.0);+ assert_eq!(arena.distance_to_query(query.as_query(), 1), 1.0);+ }++ #[test]+ fn i8_upsert_quantizes_and_reads_back_within_half_a_step() {+ let dims = 64;+ let mut arena = VectorArena::with_storage(dims, StorageKind::I8).unwrap();+ for seed in 0..20u64 {+ let values = seeded_unit_vector(seed, dims);+ let key = format!("key-{seed}");+ assert_eq!(+ arena.upsert(&key, &values).unwrap(),+ UpsertOutcome::NewSlot(seed as u32)+ );+ let expected = StoredVector::quantize(&values);+ assert_eq!(arena.stored_vector(seed as u32), expected);+ let StoredVector::I8 { scale, .. } = expected else {+ panic!("expected i8 storage");+ };+ let read_back = arena.vector_values(seed as u32);+ assert_eq!(read_back.len(), dims);+ for (original, restored) in values.iter().zip(&read_back) {+ assert!((original - restored).abs() <= scale / 2.0 + scale * 1.0e-6);+ }+ }+ assert_eq!(arena.storage_kind(), StorageKind::I8);+ }++ #[test]+ fn i8_payloads_are_stored_and_returned_bit_for_bit() {+ let dims = 32;+ let mut arena = VectorArena::with_storage(dims, StorageKind::I8).unwrap();+ let mut values: Vec<i8> = (0..dims as i32)+ .map(|index| (index * 9 - 127) as i8)+ .collect();+ values[0] = -127;+ values[1] = 127;+ values[2] = 0;+ values[3] = -1;+ let scale = f32::from_bits(0x3a1f_8f3c);+ let payload = VectorPayload::I8 {+ scale,+ values: &values,+ };+ assert_eq!(+ arena.upsert_payload("exact", payload).unwrap(),+ UpsertOutcome::NewSlot(0)+ );+ let (stored_scale, stored_values) = stored_i8(&arena, 0);+ assert_eq!(stored_scale.to_bits(), scale.to_bits());+ assert_eq!(stored_values, values);+ assert_eq!(arena.vector_values(0), dequantize(scale, &values));+ assert_eq!(+ arena.upsert_payload("exact", payload).unwrap(),+ UpsertOutcome::ReplacedInPlace(0)+ );+ assert_eq!(stored_i8(&arena, 0), (scale, values.clone()));+ assert_eq!(arena.remove("exact"), Some(0));+ assert_eq!(stored_i8(&arena, 0), (scale, values.clone()));+ let other = VectorPayload::I8 {+ scale: 0.5,+ values: &vec![3i8; dims],+ };+ assert_eq!(+ arena.upsert_payload("recycled", other).unwrap(),+ UpsertOutcome::RecycledSlot(0)+ );+ assert_eq!(stored_i8(&arena, 0), (0.5, vec![3i8; dims]));+ }++ #[test]+ fn i8_distances_follow_the_scaled_dot_formula() {+ let dims = 64;+ let mut arena = VectorArena::with_storage(dims, StorageKind::I8).unwrap();+ let a = seeded_unit_vector(11, dims);+ let b = seeded_unit_vector(12, dims);+ arena.upsert("a", &a).unwrap();+ arena.upsert("b", &b).unwrap();+ let (scale_a, values_a) = stored_i8(&arena, 0);+ let (scale_b, values_b) = stored_i8(&arena, 1);+ let dot: i32 = values_a+ .iter()+ .zip(&values_b)+ .map(|(x, y)| i32::from(*x) * i32::from(*y))+ .sum();+ let expected = 1.0 - dot as f32 * scale_a * scale_b;+ assert_eq!(+ arena.distance_between_slots(0, 1).to_bits(),+ expected.to_bits()+ );+ assert_eq!(+ arena.distance_between_slots(1, 0).to_bits(),+ expected.to_bits()+ );+ let query = arena.pack_query(&a).unwrap();+ assert_eq!(+ arena.distance_to_query(query.as_query(), 1).to_bits(),+ expected.to_bits()+ );+ assert_eq!(+ arena.distance_to_query(arena.stored_query(0), 1).to_bits(),+ expected.to_bits()+ );+ let f32_distance = 1.0 - a.iter().zip(&b).map(|(x, y)| x * y).sum::<f32>();+ assert!((expected - f32_distance).abs() < 0.01);+ assert!(arena.distance_between_slots(0, 0).abs() < 0.02);+ }++ #[test]+ fn i8_zero_vector_stores_scale_zero_and_sits_at_unit_distance() {+ let dims = 32;+ let mut arena = VectorArena::with_storage(dims, StorageKind::I8).unwrap();+ arena.upsert("zero", &vec![0.0; dims]).unwrap();+ arena.upsert("unit", &basis_vector(dims, 5)).unwrap();+ assert_eq!(stored_i8(&arena, 0), (0.0, vec![0i8; dims]));+ assert_eq!(arena.vector_values(0), vec![0.0; dims]);+ assert_eq!(arena.distance_between_slots(0, 1), 1.0);+ assert_eq!(arena.distance_between_slots(0, 0), 1.0);+ let query = arena.pack_query(&basis_vector(dims, 5)).unwrap();+ assert_eq!(arena.distance_to_query(query.as_query(), 0), 1.0);+ let zero_query = arena.pack_query(&vec![0.0; dims]).unwrap();+ assert!(zero_query.as_query().is_finite());+ assert_eq!(arena.distance_to_query(zero_query.as_query(), 1), 1.0);+ }++ #[test]+ fn non_finite_queries_pack_as_non_finite_for_both_storages() {+ let f32_arena = VectorArena::new(32).unwrap();+ let i8_arena = VectorArena::with_storage(32, StorageKind::I8).unwrap();+ for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {+ let mut values = seeded_vector(1, 32);+ values[7] = bad;+ assert!(+ !f32_arena+ .pack_query(&values)+ .unwrap()+ .as_query()+ .is_finite()+ );+ assert!(!i8_arena.pack_query(&values).unwrap().as_query().is_finite());+ }+ let values = seeded_vector(2, 32);+ assert!(+ f32_arena+ .pack_query(&values)+ .unwrap()+ .as_query()+ .is_finite()+ );+ assert!(i8_arena.pack_query(&values).unwrap().as_query().is_finite());+ }++ #[test]+ fn i8_compact_in_place_moves_scales_with_their_vectors_across_chunks() {+ let dims = 32;+ let mut arena = VectorArena::with_storage(dims, StorageKind::I8).unwrap();+ let count = VECTORS_PER_CHUNK + 200;+ for index in 0..count as u64 {+ arena+ .upsert(&format!("key-{index}"), &seeded_vector(index, dims))+ .unwrap();+ }+ assert_eq!(arena.storage.chunk_count(), 2);+ for index in (0..900u64).step_by(3) {+ assert!(arena.remove(&format!("key-{index}")).is_some());+ }+ let expected: Vec<(String, StoredVector)> = arena+ .live_slots()+ .map(|slot| {+ (+ arena.key_of_slot(slot).unwrap().to_string(),+ arena.stored_vector(slot),+ )+ })+ .collect();+ arena.compact_in_place();+ assert_eq!(arena.live_count(), count - 300);+ assert_eq!(arena.slot_count(), count - 300);+ assert_eq!(arena.storage.chunk_count(), 1);+ let Storage::I8 { scales, .. } = &arena.storage else {+ panic!("expected i8 storage");+ };+ assert_eq!(scales.len(), count - 300);+ for (index, (key, stored)) in expected.iter().enumerate() {+ let slot = index as u32;+ assert_eq!(arena.slot_of_key(key), Some(slot));+ assert_eq!(&arena.stored_vector(slot), stored);+ assert_eq!(lane_address(arena.stored_query(slot)) % 32, 0);+ }+ assert_eq!(+ arena.upsert("fresh", &seeded_vector(9999, dims)).unwrap(),+ UpsertOutcome::NewSlot((count - 300) as u32)+ );+ }++ #[test]+ fn i8_arena_reports_a_quarter_of_the_f32_vector_memory() {+ let dims = 512;+ let mut f32_arena = VectorArena::new(dims).unwrap();+ let mut i8_arena = VectorArena::with_storage(dims, StorageKind::I8).unwrap();+ assert_eq!(f32_arena.vector_memory_bytes(), 0);+ assert_eq!(i8_arena.vector_memory_bytes(), 0);+ for index in 0..100u64 {+ let values = seeded_vector(index, dims);+ f32_arena.upsert(&format!("key-{index}"), &values).unwrap();+ i8_arena.upsert(&format!("key-{index}"), &values).unwrap();+ }+ assert_eq!(+ f32_arena.vector_memory_bytes(),+ VECTORS_PER_CHUNK * dims * size_of::<f32>()+ );+ assert_eq!(+ i8_arena.vector_memory_bytes(),+ VECTORS_PER_CHUNK * dims + 100 * size_of::<f32>()+ );}}diff --git a/rust/crates/ml/src/vecdb/graph.rs b/rust/crates/ml/src/vecdb/graph.rsindex 417c980067..21674dded1 100644--- a/rust/crates/ml/src/vecdb/graph.rs+++ b/rust/crates/ml/src/vecdb/graph.rs@@ -1,8 +1,8 @@use std::cmp::{Ordering, Reverse};use std::collections::{BinaryHeap, HashSet};-use super::arena::VectorArena;-use super::kernel::{Lane, splitmix64};+use super::arena::{PackedQuery, Query, VectorArena};+use super::kernel::splitmix64;use super::{Match, SearchParams, VecDbError};const M: usize = 16;@@ -266,7 +266,7 @@ impl Graph {self.entry_point = Some(slot);return;};- let query = arena.vector_lanes(slot);+ let query = arena.stored_query(slot);let entry_level = self.level_of(entry).map_or(0, usize::from);let mut entries = {let context = QueryContext {@@ -566,7 +566,7 @@ impl Graph {struct QueryContext<'a> {graph: &'a Graph,arena: &'a VectorArena,- query: &'a [Lane],+ query: Query<'a>,}impl QueryContext<'_> {@@ -774,11 +774,11 @@ fn keep_frontier(frontier: &mut BinaryHeap<Scored>, scored: Scored) {pub(crate) fn search(graph: &Graph,arena: &VectorArena,- query: &[Lane],+ query: &PackedQuery,params: &SearchParams,allowed_slots: Option<&HashSet<u32>>,) -> Vec<Match> {- search_from(graph, arena, query, params, allowed_slots, None)+ search_from(graph, arena, query.as_query(), params, allowed_slots, None)}pub(crate) fn search_stored(@@ -791,7 +791,7 @@ pub(crate) fn search_stored(search_from(graph,arena,- arena.vector_lanes(slot),+ arena.stored_query(slot),params,allowed_slots,Some(slot),@@ -801,7 +801,7 @@ pub(crate) fn search_stored(fn search_from(graph: &Graph,arena: &VectorArena,- query: &[Lane],+ query: Query<'_>,params: &SearchParams,allowed_slots: Option<&HashSet<u32>>,stored_slot: Option<u32>,@@ -813,7 +813,7 @@ fn search_from(if arena.live_count() == 0|| params.limit == Some(0)|| allowed_slots.is_some_and(HashSet::is_empty)- || !query_is_finite(query)+ || !query.is_finite(){return Vec::new();}@@ -844,12 +844,6 @@ fn search_from(}}-fn query_is_finite(query: &[Lane]) -> bool {- query- .iter()- .all(|lane| lane.to_array().iter().all(|value| value.is_finite()))-}-fn small_filter_cap(limit: Option<usize>) -> usize {limit.map_or(SMALL_FILTER_FLOOR, |limit| {limit@@ -923,7 +917,7 @@ fn approx_threshold(fn brute_force(arena: &VectorArena,- query: &[Lane],+ query: Query<'_>,params: &SearchParams,allowed: Option<&HashSet<u32>>,banned: Option<u32>,@@ -999,6 +993,7 @@ mod tests {use std::f32::consts::FRAC_1_SQRT_2;use std::sync::LazyLock;+ use super::super::StorageKind;use super::super::arena::UpsertOutcome;use super::super::test_support::{assert_identical_graphs, stale_downward_edge_exists};use super::*;@@ -1049,7 +1044,17 @@ mod tests {clusters: u64,seed: u64,) -> (VectorArena, Graph) {- let mut arena = VectorArena::new(dims).unwrap();+ build_clustered_fixture_with(count, dims, clusters, seed, StorageKind::F32)+ }++ fn build_clustered_fixture_with(+ count: usize,+ dims: usize,+ clusters: u64,+ seed: u64,+ storage: StorageKind,+ ) -> (VectorArena, Graph) {+ let mut arena = VectorArena::with_storage(dims, storage).unwrap();for index in 0..count as u64 {arena.upsert(@@ -1173,13 +1178,13 @@ mod tests {fn reference_ranking(arena: &VectorArena,- query: &[Lane],+ query: &PackedQuery,allowed: Option<&HashSet<u32>>,) -> Vec<(f32, u32)> {let mut scored: Vec<(f32, u32)> = arena.live_slots().filter(|slot| allowed.is_none_or(|set| set.contains(slot)))- .map(|slot| (arena.distance_to_query(query, slot), slot))+ .map(|slot| (arena.distance_to_query(query.as_query(), slot), slot)).collect();scored.sort_unstable_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));scored@@ -1420,7 +1425,7 @@ mod tests {let (arena, graph) = (&FIXTURE.0, &FIXTURE.1);let entry = graph.entry_point().unwrap();let entry_key = arena.key_of_slot(entry).unwrap();- let query = arena.vector_lanes(entry).to_vec();+ let query = arena.pack_query(&arena.vector_values(entry)).unwrap();let reference = reference_ranking(arena, &query, None);assert_eq!(reference[0].1, entry);for exact in [true, false] {@@ -1652,7 +1657,7 @@ mod tests {assert!(top[0].distance < 1e-3);}let old_query = arena.pack_query(&old_vector).unwrap();- let moved_distance = arena.distance_to_query(&old_query, 7);+ let moved_distance = arena.distance_to_query(old_query.as_query(), 7);assert!(moved_distance > 0.3);let near_old = search(&graph,@@ -1870,7 +1875,10 @@ mod tests {if let Some(threshold) = max_distance {assert!(hit.distance <= threshold);}- assert_eq!(hit.distance, arena.distance_to_query(&query, slot));+ assert_eq!(+ hit.distance,+ arena.distance_to_query(query.as_query(), slot)+ );}let expected: Vec<(f32, u32)> = reference.iter()@@ -2291,7 +2299,10 @@ mod tests {for hit in &top {let slot = arena.slot_of_key(&hit.key).unwrap();assert!(arena.is_alive(slot));- assert_eq!(hit.distance, arena.distance_to_query(&query, slot));+ assert_eq!(+ hit.distance,+ arena.distance_to_query(query.as_query(), slot)+ );}let expected: HashSet<&str> = reference.iter()@@ -2456,4 +2467,73 @@ mod tests {});assert!(recall >= 0.97, "recall@10 was {recall}");}++ #[test]+ fn i8_approx_recall_at_10_meets_the_bar_on_8k_vectors() {+ let seed = 0x9000_0000u64;+ let (arena, graph) = build_clustered_fixture_with(8000, 64, 64, seed, StorageKind::I8);+ assert_eq!(arena.storage_kind(), StorageKind::I8);+ let recall = measured_recall(&arena, &graph, 50, |index| {+ clustered_unit_vector(seed + index % 64, seed + 0x0200_0000 + index, 64)+ });+ assert!(recall >= 0.975, "i8 recall@10 was {recall}");+ }++ #[test]+ fn i8_uniform_random_recall_stays_above_the_documented_floor() {+ let mut arena = VectorArena::with_storage(64, StorageKind::I8).unwrap();+ for index in 0..8000u64 {+ arena+ .upsert(+ &format!("key-{index}"),+ &seeded_unit_vector(0x9500_0000 + index, 64),+ )+ .unwrap();+ }+ let graph = Graph::rebuild(&arena);+ let recall = measured_recall(&arena, &graph, 50, |index| {+ seeded_unit_vector(0x9511_0000 + index, 64)+ });+ assert!(recall >= 0.895, "i8 recall@10 was {recall}");+ }++ #[test]+ fn i8_exact_search_recovers_the_f32_ground_truth_at_10() {+ let seed = 0x9000_0000u64;+ let (f32_arena, _) = build_clustered_fixture(8000, 64, 64, seed);+ let (i8_arena, i8_graph) =+ build_clustered_fixture_with(8000, 64, 64, seed, StorageKind::I8);+ let mut hits = 0usize;+ for index in 0..50u64 {+ let values = clustered_unit_vector(seed + index % 64, seed + 0x0200_0000 + index, 64);+ let f32_query = f32_arena.pack_query(&values).unwrap();+ let truth: HashSet<&str> = reference_ranking(&f32_arena, &f32_query, None)[..10]+ .iter()+ .map(|&(_, slot)| f32_arena.key_of_slot(slot).unwrap())+ .collect();+ let i8_query = i8_arena.pack_query(&values).unwrap();+ let exact = search(+ &i8_graph,+ &i8_arena,+ &i8_query,+ ¶ms(Some(10), None, true),+ None,+ );+ assert_eq!(exact.len(), 10);+ let reference = reference_ranking(&i8_arena, &i8_query, None);+ for (hit, &(distance, slot)) in exact.iter().zip(&reference) {+ assert_eq!(hit.key, i8_arena.key_of_slot(slot).unwrap());+ assert_eq!(hit.distance, distance);+ }+ hits += exact+ .iter()+ .filter(|hit| truth.contains(hit.key.as_str()))+ .count();+ }+ let recall = hits as f64 / 500.0;+ assert!(+ recall >= 0.99,+ "i8-exact vs f32 truth recall@10 was {recall}"+ );+ }}diff --git a/rust/crates/ml/src/vecdb/kernel.rs b/rust/crates/ml/src/vecdb/kernel.rsindex 23a80cbc9b..b074bd2ff9 100644--- a/rust/crates/ml/src/vecdb/kernel.rs+++ b/rust/crates/ml/src/vecdb/kernel.rs@@ -1,4 +1,8 @@+use super::{StorageKind, VecDbError};+pub(crate) const LANE_WIDTH: usize = 8;+pub(crate) const LANE_WIDTH_I8: usize = 32;+const I8_LIMIT: f32 = 127.0;#[repr(C, align(32))]#[derive(Clone, Copy)]@@ -18,6 +22,105 @@ impl From<[f32; LANE_WIDTH]> for Lane {}}+#[repr(C, align(32))]+#[derive(Clone, Copy)]+pub(crate) struct LaneI8([i8; LANE_WIDTH_I8]);++impl LaneI8 {+ pub(crate) const ZERO: Self = Self([0; LANE_WIDTH_I8]);++ pub(crate) fn to_array(self) -> [i8; LANE_WIDTH_I8] {+ self.0+ }+}++impl From<[i8; LANE_WIDTH_I8]> for LaneI8 {+ fn from(values: [i8; LANE_WIDTH_I8]) -> Self {+ Self(values)+ }+}++#[derive(Debug, Clone, Copy, PartialEq)]+pub(crate) enum VectorPayload<'a> {+ F32(&'a [f32]),+ I8 { scale: f32, values: &'a [i8] },+}++impl VectorPayload<'_> {+ pub(crate) fn storage(&self) -> StorageKind {+ match self {+ Self::F32(_) => StorageKind::F32,+ Self::I8 { .. } => StorageKind::I8,+ }+ }++ pub(crate) fn dims(&self) -> usize {+ match self {+ Self::F32(values) => values.len(),+ Self::I8 { values, .. } => values.len(),+ }+ }+}++#[derive(Debug, Clone, PartialEq)]+pub(crate) enum StoredVector {+ F32(Vec<f32>),+ I8 { scale: f32, values: Vec<i8> },+}++impl StoredVector {+ pub(crate) fn quantize(values: &[f32]) -> Self {+ let finite = values.iter().all(|value| value.is_finite());+ let max_abs = values+ .iter()+ .fold(0.0f32, |acc, value| acc.max(value.abs()));+ let scale = if finite { max_abs / I8_LIMIT } else { f32::NAN };+ let quantized = if scale > 0.0 {+ values+ .iter()+ .map(|value| (value / scale).round().clamp(-I8_LIMIT, I8_LIMIT) as i8)+ .collect()+ } else {+ vec![0; values.len()]+ };+ Self::I8 {+ scale,+ values: quantized,+ }+ }++ pub(crate) fn as_payload(&self) -> VectorPayload<'_> {+ match self {+ Self::F32(values) => VectorPayload::F32(values),+ Self::I8 { scale, values } => VectorPayload::I8 {+ scale: *scale,+ values,+ },+ }+ }+}++pub(crate) fn quantize_for(storage: StorageKind, values: &[f32]) -> Option<StoredVector> {+ match storage {+ StorageKind::F32 => None,+ StorageKind::I8 => Some(StoredVector::quantize(values)),+ }+}++pub(crate) fn dequantize(scale: f32, values: &[i8]) -> Vec<f32> {+ values+ .iter()+ .map(|&value| f32::from(value) * scale)+ .collect()+}++pub(crate) fn validate_dims(dims: usize, storage: StorageKind) -> Result<(), VecDbError> {+ if dims == 0 || !dims.is_multiple_of(storage.lane_width()) || u32::try_from(dims).is_err() {+ return Err(VecDbError::InvalidDimensions { dims, storage });+ }+ Ok(())+}+pub(crate) fn splitmix64(state: &mut u64) -> u64 {*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);let mut mixed = *state;@@ -53,6 +156,49 @@ impl VectorKernel for F32Kernel {}}+pub(crate) struct I8Kernel;++impl I8Kernel {+ pub(crate) fn dot(a: &[LaneI8], b: &[LaneI8]) -> i32 {+ debug_assert_eq!(a.len(), b.len());+ let mut partials = [0i32; LANE_WIDTH_I8];+ for (x, y) in a.iter().zip(b.iter()) {+ for (partial, (left, right)) in partials.iter_mut().zip(x.0.iter().zip(&y.0)) {+ *partial += i32::from(*left) * i32::from(*right);+ }+ }+ partials.iter().sum()+ }++ pub(crate) fn distance(a: &[LaneI8], scale_a: f32, b: &[LaneI8], scale_b: f32) -> f32 {+ 1.0 - Self::dot(a, b) as f32 * scale_a * scale_b+ }+}++pub(crate) fn pack_lanes_i8(values: &[i8]) -> Vec<LaneI8> {+ debug_assert_eq!(values.len() % LANE_WIDTH_I8, 0);+ let mut lanes = vec![LaneI8::ZERO; values.len() / LANE_WIDTH_I8];+ pack_lanes_i8_into(values, &mut lanes);+ lanes+}++pub(crate) fn pack_lanes_i8_into(values: &[i8], lanes: &mut [LaneI8]) {+ debug_assert_eq!(values.len(), lanes.len() * LANE_WIDTH_I8);+ let (groups, remainder) = values.as_chunks::<LANE_WIDTH_I8>();+ debug_assert!(remainder.is_empty());+ for (lane, group) in lanes.iter_mut().zip(groups) {+ *lane = LaneI8::from(*group);+ }+}++pub(crate) fn unpack_lanes_i8(lanes: &[LaneI8]) -> Vec<i8> {+ let mut values = Vec::with_capacity(lanes.len() * LANE_WIDTH_I8);+ for lane in lanes {+ values.extend_from_slice(&lane.to_array());+ }+ values+}+pub(crate) fn pack_lanes(values: &[f32]) -> Vec<Lane> {debug_assert_eq!(values.len() % LANE_WIDTH, 0);let mut lanes = vec![Lane::ZERO; values.len() / LANE_WIDTH];@@ -147,4 +293,239 @@ mod tests {assert_eq!(lanes.as_ptr() as usize % 32, 0);}}++ fn seeded_unit_values(seed: u64, count: usize) -> Vec<f32> {+ let mut state = seed;+ let mut values: Vec<f32> = (0..count)+ .map(|_| {+ let unit = (splitmix64(&mut state) >> 40) as f32 / (1u64 << 24) as f32;+ unit * 2.0 - 1.0+ })+ .collect();+ let norm = values.iter().map(|value| value * value).sum::<f32>().sqrt();+ for value in &mut values {+ *value /= norm;+ }+ values+ }++ fn seeded_i8_values(seed: u64, count: usize) -> Vec<i8> {+ let mut state = seed;+ (0..count)+ .map(|_| ((splitmix64(&mut state) % 255) as i64 - 127) as i8)+ .collect()+ }++ fn quantized_parts(values: &[f32]) -> (f32, Vec<i8>) {+ match StoredVector::quantize(values) {+ StoredVector::I8 { scale, values } => (scale, values),+ StoredVector::F32(_) => panic!("quantize must produce i8 storage"),+ }+ }++ #[test]+ fn i8_dot_matches_the_scalar_reference_bit_exactly() {+ for (dims, seed) in [(32, 11), (64, 22), (512, 33)] {+ let a = seeded_i8_values(seed, dims);+ let b = seeded_i8_values(seed.wrapping_mul(977), dims);+ let simd = I8Kernel::dot(&pack_lanes_i8(&a), &pack_lanes_i8(&b));+ let mut partials = [0i32; LANE_WIDTH_I8];+ for (index, (x, y)) in a.iter().zip(&b).enumerate() {+ partials[index % LANE_WIDTH_I8] += i32::from(*x) * i32::from(*y);+ }+ let reference: i32 = partials.iter().sum();+ assert_ne!(reference, 0);+ assert_eq!(simd, reference);+ let saturated = vec![127i8; dims];+ let negated = vec![-127i8; dims];+ assert_eq!(+ I8Kernel::dot(&pack_lanes_i8(&saturated), &pack_lanes_i8(&negated)),+ -(dims as i32) * 127 * 127+ );+ }+ }++ #[test]+ fn i8_distance_pins_the_evaluation_order() {+ let a = pack_lanes_i8(&seeded_i8_values(5, 64));+ let b = pack_lanes_i8(&seeded_i8_values(6, 64));+ let scale_a = 0.012_345_6f32;+ let scale_b = 0.045_678_9f32;+ let dot = I8Kernel::dot(&a, &b);+ let scaled_once = dot as f32 * scale_a;+ let expected = 1.0 - scaled_once * scale_b;+ assert_eq!(+ I8Kernel::distance(&a, scale_a, &b, scale_b).to_bits(),+ expected.to_bits()+ );+ assert_eq!(+ I8Kernel::distance(&b, scale_b, &a, scale_a).to_bits(),+ (1.0 - (dot as f32 * scale_b) * scale_a).to_bits()+ );+ }++ #[test]+ fn i8_distance_of_basis_vectors_is_orthogonal_exactly_and_self_within_rounding() {+ let (scale_0, values_0) = quantized_parts(&basis_vector(32, 0));+ let (scale_5, values_5) = quantized_parts(&basis_vector(32, 5));+ assert_eq!(scale_0, 1.0 / 127.0);+ assert_eq!(values_0[0], 127);+ assert!(values_0[1..].iter().all(|&value| value == 0));+ let e0 = pack_lanes_i8(&values_0);+ let e5 = pack_lanes_i8(&values_5);+ assert_eq!(I8Kernel::distance(&e0, scale_0, &e5, scale_5), 1.0);+ assert!(I8Kernel::distance(&e0, scale_0, &e0, scale_0).abs() < 1.0e-6);+ }++ #[test]+ fn quantize_bounds_every_value_and_maps_the_extreme_component_to_127() {+ for seed in 0..40u64 {+ let values = seeded_values(seed, 128);+ let max_abs = values+ .iter()+ .fold(0.0f32, |acc, value| acc.max(value.abs()));+ let (scale, quantized) = quantized_parts(&values);+ assert_eq!(scale.to_bits(), (max_abs / 127.0).to_bits());+ assert!(quantized.iter().all(|&value| (-127..=127).contains(&value)));+ let extreme = values+ .iter()+ .position(|value| value.abs() == max_abs)+ .unwrap();+ assert_eq!(+ quantized[extreme],+ if values[extreme] > 0.0 { 127 } else { -127 }+ );+ for (value, &q) in values.iter().zip(&quantized) {+ if value.abs() >= scale {+ assert_eq!(q.signum(), value.signum() as i8);+ }+ }+ }+ }++ #[test]+ fn quantize_is_bit_stable_and_handles_zero_and_non_finite_inputs() {+ let values = seeded_unit_values(7, 512);+ let first = StoredVector::quantize(&values);+ for _ in 0..5 {+ let again = StoredVector::quantize(&values);+ let (+ StoredVector::I8 { scale, values: q },+ StoredVector::I8 {+ scale: s2,+ values: q2,+ },+ ) = (&first, &again)+ else {+ panic!("quantize must produce i8 storage");+ };+ assert_eq!(scale.to_bits(), s2.to_bits());+ assert_eq!(q, q2);+ }+ let (zero_scale, zeros) = quantized_parts(&[0.0; 64]);+ assert_eq!(zero_scale.to_bits(), 0.0f32.to_bits());+ assert!(zeros.iter().all(|&value| value == 0));+ let (negative_zero_scale, _) = quantized_parts(&[-0.0; 64]);+ assert_eq!(negative_zero_scale.to_bits(), 0.0f32.to_bits());+ for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {+ let mut poisoned = values.clone();+ poisoned[100] = bad;+ let (scale, q) = quantized_parts(&poisoned);+ assert!(scale.is_nan());+ assert!(q.iter().all(|&value| value == 0));+ }+ assert_eq!(quantize_for(StorageKind::F32, &values), None);+ assert_eq!(quantize_for(StorageKind::I8, &values), Some(first));+ }++ #[test]+ fn quantize_pins_half_way_ties_signed_zeros_and_denormals() {+ let mut values = [0.0f32; 32];+ values[..14].copy_from_slice(&[+ 127.0,+ 2.5,+ -2.5,+ 0.5,+ -0.5,+ 1.5,+ -1.5,+ 126.5,+ -126.5,+ 0.0,+ -0.0,+ 1.0e-40,+ -1.0e-40,+ f32::MIN_POSITIVE,+ ]);+ let (scale, quantized) = quantized_parts(&values);+ assert_eq!(scale.to_bits(), 1.0f32.to_bits());+ let mut expected = [0i8; 32];+ expected[..9].copy_from_slice(&[127, 3, -3, 1, -1, 2, -2, 127, -127]);+ assert_eq!(quantized, expected);+ let mut tiny = [0.0f32; 32];+ tiny[0] = 1.0e-40;+ tiny[1] = -1.0e-40;+ tiny[2] = f32::from_bits(1);+ let (tiny_scale, tiny_quantized) = quantized_parts(&tiny);+ assert_eq!(tiny_scale.to_bits(), (1.0e-40f32 / 127.0).to_bits());+ assert!(tiny_scale > 0.0);+ assert_eq!(tiny_quantized[0], 127);+ assert_eq!(tiny_quantized[1], -127);+ assert_eq!(tiny_quantized[2], 0);+ assert!(tiny_quantized[3..].iter().all(|&value| value == 0));+ let (min_scale, min_quantized) = quantized_parts(&[f32::from_bits(1); 32]);+ assert_eq!(min_scale.to_bits(), 0.0f32.to_bits());+ assert!(min_quantized.iter().all(|&value| value == 0));+ for _ in 0..3 {+ assert_eq!(quantized_parts(&values), (scale, quantized.clone()));+ assert_eq!(quantized_parts(&tiny), (tiny_scale, tiny_quantized.clone()));+ }+ }++ #[test]+ fn dequantize_stays_within_half_a_step_of_the_input() {+ for (dims, seed) in [(64usize, 1u64), (512, 2), (32, 3)] {+ let values = seeded_unit_values(seed, dims);+ let (scale, quantized) = quantized_parts(&values);+ let restored = dequantize(scale, &quantized);+ assert_eq!(restored.len(), dims);+ for (original, restored) in values.iter().zip(&restored) {+ assert!((original - restored).abs() <= scale / 2.0 + scale * 1.0e-6);+ }+ }+ }++ #[test]+ fn i8_distance_tracks_f32_distance_on_unit_vectors_within_the_bound() {+ let mut max_delta = 0.0f32;+ for (dims, pairs, seed) in [(512usize, 300u64, 0x1000u64), (64, 300, 0x2000)] {+ for pair in 0..pairs {+ let a = seeded_unit_values(seed + pair * 2, dims);+ let b = seeded_unit_values(seed + pair * 2 + 1, dims);+ let f32_distance = F32Kernel::distance(&pack_lanes(&a), &pack_lanes(&b));+ let (scale_a, qa) = quantized_parts(&a);+ let (scale_b, qb) = quantized_parts(&b);+ let i8_distance =+ I8Kernel::distance(&pack_lanes_i8(&qa), scale_a, &pack_lanes_i8(&qb), scale_b);+ let delta = (i8_distance - f32_distance).abs();+ assert!(delta <= 0.01, "dims {dims} pair {pair}: delta {delta}");+ max_delta = max_delta.max(delta);+ }+ }+ assert!(max_delta > 0.0);+ assert!(max_delta <= 0.005, "max delta {max_delta}");+ }++ #[test]+ fn packed_i8_lanes_are_32_byte_aligned_and_round_trip() {+ assert_eq!(align_of::<LaneI8>(), 32);+ assert_eq!(size_of::<LaneI8>(), 32);+ for dims in [32, 64, 512] {+ let values = seeded_i8_values(9, dims);+ let lanes = pack_lanes_i8(&values);+ assert_eq!(lanes.len(), dims / LANE_WIDTH_I8);+ assert_eq!(lanes.as_ptr() as usize % 32, 0);+ assert_eq!(unpack_lanes_i8(&lanes), values);+ }+ }}diff --git a/rust/crates/ml/src/vecdb/log.rs b/rust/crates/ml/src/vecdb/log.rsindex 06a58c1425..ffbacbf53e 100644--- a/rust/crates/ml/src/vecdb/log.rs+++ b/rust/crates/ml/src/vecdb/log.rs@@ -6,13 +6,13 @@ use std::time::{SystemTime, UNIX_EPOCH};use super::arena::{MAX_KEY_BYTES, validate_key};use super::crc::{Crc32, crc32};-use super::kernel::{LANE_WIDTH, splitmix64};-use super::{AttrValue, Attribute, VecDbError};+use super::kernel::{StoredVector, VectorPayload, splitmix64, validate_dims};+use super::{AttrValue, Attribute, StorageKind, VecDbError};pub(crate) const HEADER_LEN: usize = 32;const MAGIC: [u8; 4] = *b"EVDB";const FORMAT_VERSION: u16 = 1;-const SCALAR_TAG_F32: u8 = 0;+const STORAGE_TAG_OFFSET: usize = 6;const METRIC_TAG_INNER_PRODUCT: u8 = 0;const RECORD_TYPE_ADD: u8 = 1;const RECORD_TYPE_TOMBSTONE: u8 = 2;@@ -35,7 +35,7 @@ static GENERATION_COUNTER: AtomicU64 = AtomicU64::new(0);pub(crate) enum LogEntry<'a> {Add {key: &'a str,- vector: &'a [f32],+ vector: VectorPayload<'a>,attrs: &'a [Attribute],},Tombstone {@@ -47,7 +47,7 @@ pub(crate) enum LogEntry<'a> {pub(crate) enum LogRecord {Add {key: String,- vector: Vec<f32>,+ vector: StoredVector,attrs: Vec<Attribute>,},Tombstone {@@ -60,6 +60,7 @@ pub(crate) struct Log {file: File,path: PathBuf,dims: usize,+ storage: StorageKind,generation: [u8; 16],end_offset: u64,encode_buffer: Vec<u8>,@@ -67,23 +68,29 @@ pub(crate) struct Log {}impl Log {- pub(crate) fn create(path: &Path, dims: usize) -> Result<Self, VecDbError> {- validate_dims(dims)?;+ pub(crate) fn create(+ path: &Path,+ dims: usize,+ storage: StorageKind,+ ) -> Result<Self, VecDbError> {+ validate_dims(dims, storage)?;let file = File::options().read(true).write(true).create_new(true).open(path).map_err(|source| VecDbError::io(path, source))?;- Self::initialize(file, path, dims)+ Self::initialize(file, path, dims, storage)}pub(crate) fn open(mut file: File,path: &Path,expected_dims: usize,+ requested: Option<StorageKind>,) -> Result<Self, VecDbError> {- validate_dims(expected_dims)?;+ let fallback = requested.unwrap_or(StorageKind::F32);+ validate_dims(expected_dims, fallback)?;let file_len = file.metadata().map_err(|source| VecDbError::io(path, source))?@@ -93,18 +100,28 @@ impl Log {"reinitializing {} whose {file_len}-byte header was never completed",path.display());- return Self::initialize(file, path, expected_dims);+ return Self::initialize(file, path, expected_dims, fallback);}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 = decode_header(&header, expected_dims)?;+ let (generation, storage) = decode_header(&header, expected_dims)?;+ if let Some(requested) = requested+ && requested != storage+ {+ return Err(VecDbError::StorageMismatch {+ expected: requested,+ actual: storage,+ });+ }+ validate_dims(expected_dims, storage)?;Ok(Self {file,path: path.to_path_buf(),dims: expected_dims,+ storage,generation,end_offset: file_len,encode_buffer: Vec::new(),@@ -112,11 +129,16 @@ impl Log {})}- fn initialize(mut file: File, path: &Path, dims: usize) -> Result<Self, VecDbError> {+ fn initialize(+ mut file: File,+ path: &Path,+ dims: usize,+ storage: StorageKind,+ ) -> 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))+ file.write_all(&encode_header(dims as u32, &generation, storage)).map_err(|source| VecDbError::io(path, source))?;file.sync_all().map_err(|source| VecDbError::io(path, source))?;@@ -125,6 +147,7 @@ impl Log {file,path: path.to_path_buf(),dims,+ storage,generation,end_offset: HEADER_LEN as u64,encode_buffer: Vec::new(),@@ -135,10 +158,11 @@ impl Log {pub(crate) fn create_temp_sibling(path: &Path,dims: usize,+ storage: StorageKind,) -> Result<(Self, PathBuf), VecDbError> {remove_stale_temp_sibling(path)?;let temp_path = temp_sibling_path(path);- let log = Self::create(&temp_path, dims)?;+ let log = Self::create(&temp_path, dims, storage)?;Ok((log, temp_path))}@@ -150,6 +174,7 @@ impl Log {reader: BufReader::new(&mut self.file),path: &self.path,dims: self.dims,+ storage: self.storage,log_end: self.end_offset,offset: HEADER_LEN as u64,scratch: Vec::new(),@@ -173,7 +198,7 @@ impl Log {return Ok(());}for entry in entries {- validate_entry(entry, self.dims)?;+ validate_entry(entry, self.dims, self.storage)?;}if self.rollback_pending {self.discard_unacked_tail()?;@@ -275,7 +300,7 @@ impl Log {}let tail_len = self.end_offset - start;let step = step_bytes.max(1);- let overlap = max_record_len(self.dims).saturating_sub(1);+ let overlap = max_record_len(self.storage, self.dims).saturating_sub(1);let window_len = (step.saturating_add(overlap) as u64).min(tail_len) as usize;let mut window = vec![0u8; window_len];let mut base = 0u64;@@ -289,7 +314,9 @@ impl Log {.map_err(|source| VecDbError::io(&self.path, source))?;let reaches_end = base + len as u64 == tail_len;let probe_end = if reaches_end { len } else { step.min(len) };- if (0..probe_end).any(|offset| valid_record_at(&window[offset..len], self.dims)) {+ if (0..probe_end)+ .any(|offset| valid_record_at(&window[offset..len], self.storage, self.dims))+ {return Ok(true);}if reaches_end {@@ -317,6 +344,10 @@ impl Log {self.generation}+ pub(crate) fn storage(&self) -> StorageKind {+ self.storage+ }+pub(crate) fn path(&self) -> &Path {&self.path}@@ -330,6 +361,7 @@ pub(crate) struct LogScanner<'a> {reader: BufReader<&'a mut File>,path: &'a Path,dims: usize,+ storage: StorageKind,log_end: u64,offset: u64,scratch: Vec<u8>,@@ -360,7 +392,7 @@ impl LogScanner<'_> {return Ok(self.stop());}let fixed_len = match record_type {- RECORD_TYPE_ADD => key_len + self.dims * size_of::<f32>() + 1,+ RECORD_TYPE_ADD => key_len + vector_payload_len(self.storage, self.dims) + 1,RECORD_TYPE_TOMBSTONE => key_len,_ => return Ok(self.stop()),};@@ -382,7 +414,9 @@ impl LogScanner<'_> {if hasher.finalize() != u32::from_le_bytes(crc_bytes) {return Ok(self.stop());}- let Some(record) = decode_body(record_type, key_len, self.dims, &self.scratch) else {+ let Some(record) =+ decode_body(record_type, key_len, self.storage, self.dims, &self.scratch)+ else {return Ok(self.stop());};self.offset = start + (RECORD_PREFIX_LEN + self.scratch.len() + RECORD_CRC_LEN) as u64;@@ -478,23 +512,59 @@ impl LogScanner<'_> {}}-fn decode_body(record_type: u8, key_len: usize, dims: usize, body: &[u8]) -> Option<LogRecord> {+fn vector_payload_len(storage: StorageKind, dims: usize) -> usize {+ match storage {+ StorageKind::F32 => dims.saturating_mul(size_of::<f32>()),+ StorageKind::I8 => dims.saturating_add(size_of::<f32>()),+ }+}++fn decode_body(+ record_type: u8,+ key_len: usize,+ storage: StorageKind,+ dims: usize,+ body: &[u8],+) -> Option<LogRecord> {let (key_bytes, rest) = body.split_at(key_len);let key = std::str::from_utf8(key_bytes).ok()?.to_string();if record_type == RECORD_TYPE_TOMBSTONE {return Some(LogRecord::Tombstone { key });}- let (payload, attr_bytes) = rest.split_at(dims * size_of::<f32>());- let vector = payload- .as_chunks::<4>()- .0- .iter()- .map(|bytes| f32::from_le_bytes(*bytes))- .collect();+ let (payload, attr_bytes) = rest.split_at(vector_payload_len(storage, dims));+ let vector = decode_vector(storage, payload);let attrs = decode_attrs(attr_bytes)?;Some(LogRecord::Add { key, vector, attrs })}+fn decode_vector(storage: StorageKind, payload: &[u8]) -> StoredVector {+ match storage {+ StorageKind::F32 => StoredVector::F32(+ payload+ .as_chunks::<4>()+ .0+ .iter()+ .map(|bytes| f32::from_le_bytes(*bytes))+ .collect(),+ ),+ StorageKind::I8 => {+ let (scale_bytes, values) = payload.split_at(size_of::<f32>());+ StoredVector::I8 {+ scale: f32::from_le_bytes([+ scale_bytes[0],+ scale_bytes[1],+ scale_bytes[2],+ scale_bytes[3],+ ]),+ values: values+ .iter()+ .map(|&byte| i8::from_le_bytes([byte]))+ .collect(),+ }+ }+ }+}+fn decode_attrs(bytes: &[u8]) -> Option<Vec<Attribute>> {let (&count, mut rest) = bytes.split_first()?;let mut attrs = Vec::with_capacity(count as usize);@@ -540,14 +610,14 @@ fn decode_attrs(bytes: &[u8]) -> Option<Vec<Attribute>> {rest.is_empty().then_some(attrs)}-fn max_record_len(dims: usize) -> usize {- dims.saturating_mul(size_of::<f32>()).saturating_add(+fn max_record_len(storage: StorageKind, dims: usize) -> usize {+ vector_payload_len(storage, dims).saturating_add(RECORD_PREFIX_LEN + MAX_KEY_BYTES + 1 + MAX_ATTRS_TOTAL_BYTES + RECORD_CRC_LEN,)}-fn valid_record_at(bytes: &[u8], dims: usize) -> bool {- let Some(record_len) = plausible_record_len(bytes, dims) else {+fn valid_record_at(bytes: &[u8], storage: StorageKind, dims: usize) -> bool {+ let Some(record_len) = plausible_record_len(bytes, storage, dims) else {return false;};let crc_start = record_len - RECORD_CRC_LEN;@@ -560,7 +630,7 @@ fn valid_record_at(bytes: &[u8], dims: usize) -> bool {crc32(&bytes[..crc_start]) == stored}-fn plausible_record_len(bytes: &[u8], dims: usize) -> Option<usize> {+fn plausible_record_len(bytes: &[u8], storage: StorageKind, dims: usize) -> Option<usize> {if bytes.len() < RECORD_PREFIX_LEN + RECORD_CRC_LEN {return None;}@@ -570,7 +640,7 @@ fn plausible_record_len(bytes: &[u8], dims: usize) -> Option<usize> {}let body_len = match bytes[0] {RECORD_TYPE_ADD => {- let fixed = key_len + dims * size_of::<f32>();+ let fixed = key_len + vector_payload_len(storage, dims);fixed + plausible_attrs_len(bytes.get(RECORD_PREFIX_LEN + fixed..)?)?}RECORD_TYPE_TOMBSTONE => key_len,@@ -616,11 +686,11 @@ fn plausible_attrs_len(bytes: &[u8]) -> Option<usize> {Some(1 + attr_bytes)}-fn encode_header(dims: u32, generation: &[u8; 16]) -> [u8; HEADER_LEN] {+fn encode_header(dims: u32, generation: &[u8; 16], storage: StorageKind) -> [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[6] = SCALAR_TAG_F32;+ bytes[STORAGE_TAG_OFFSET] = storage.header_tag();bytes[7] = METRIC_TAG_INNER_PRODUCT;bytes[8..12].copy_from_slice(&dims.to_le_bytes());bytes[12..28].copy_from_slice(generation);@@ -631,10 +701,13 @@ fn encode_header(dims: u32, generation: &[u8; 16]) -> [u8; HEADER_LEN] {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)+ decode_header(bytes, dims).map(|(generation, _)| generation)}-fn decode_header(bytes: &[u8; HEADER_LEN], expected_dims: usize) -> Result<[u8; 16], VecDbError> {+fn decode_header(+ bytes: &[u8; HEADER_LEN],+ expected_dims: usize,+) -> Result<([u8; 16], StorageKind), VecDbError> {if bytes[0..4] != MAGIC {return Err(VecDbError::Corrupt(format!("bad log magic {:02x?}",@@ -654,12 +727,9 @@ fn decode_header(bytes: &[u8; HEADER_LEN], expected_dims: usize) -> Result<[u8;"unsupported log format version {version}")));}- if bytes[6] != SCALAR_TAG_F32 {- return Err(VecDbError::Corrupt(format!(- "unknown scalar tag {}",- bytes[6]- )));- }+ let storage = StorageKind::from_header_tag(bytes[STORAGE_TAG_OFFSET]).ok_or_else(|| {+ VecDbError::Corrupt(format!("unknown scalar tag {}", bytes[STORAGE_TAG_OFFSET]))+ })?;if bytes[7] != METRIC_TAG_INNER_PRODUCT {return Err(VecDbError::Corrupt(format!("unknown metric tag {}",@@ -675,24 +745,27 @@ fn decode_header(bytes: &[u8; HEADER_LEN], expected_dims: usize) -> Result<[u8;}let mut generation = [0u8; 16];generation.copy_from_slice(&bytes[12..28]);- Ok(generation)-}--fn validate_dims(dims: usize) -> Result<(), VecDbError> {- if dims == 0 || !dims.is_multiple_of(LANE_WIDTH) || u32::try_from(dims).is_err() {- return Err(VecDbError::InvalidDimensions(dims));- }- Ok(())+ Ok((generation, storage))}-fn validate_entry(entry: &LogEntry<'_>, dims: usize) -> Result<(), VecDbError> {+fn validate_entry(+ entry: &LogEntry<'_>,+ dims: usize,+ storage: StorageKind,+) -> Result<(), VecDbError> {match entry {LogEntry::Add { key, vector, attrs } => {validate_key(key)?;- if vector.len() != dims {+ if vector.storage() != storage {+ return Err(VecDbError::StorageMismatch {+ expected: storage,+ actual: vector.storage(),+ });+ }+ if vector.dims() != dims {return Err(VecDbError::DimensionMismatch {expected: dims,- actual: vector.len(),+ actual: vector.dims(),});}validate_attrs(attrs)@@ -763,8 +836,16 @@ fn encode_record_into(buffer: &mut Vec<u8>, entry: &LogEntry<'_>) {buffer.push(RECORD_TYPE_ADD);buffer.extend_from_slice(&(key.len() as u16).to_le_bytes());buffer.extend_from_slice(key.as_bytes());- for value in *vector {- buffer.extend_from_slice(&value.to_le_bytes());+ match vector {+ VectorPayload::F32(values) => {+ for value in *values {+ buffer.extend_from_slice(&value.to_le_bytes());+ }+ }+ VectorPayload::I8 { scale, values } => {+ buffer.extend_from_slice(&scale.to_le_bytes());+ buffer.extend(values.iter().flat_map(|value| value.to_le_bytes()));+ }}buffer.push(attrs.len() as u8);for attr in *attrs {@@ -882,7 +963,7 @@ mod tests {fn reopen(path: &Path, dims: usize) -> Log {let file = File::options().read(true).write(true).open(path).unwrap();- Log::open(file, path, dims).unwrap()+ Log::open(file, path, dims, None).unwrap()}fn append_bounds(log: &mut Log, entries: &[LogEntry<'_>]) -> (u64, u64) {@@ -903,7 +984,7 @@ mod tests {&mut bytes,&LogEntry::Add {key,- vector,+ vector: VectorPayload::F32(vector),attrs: &[],},);@@ -919,11 +1000,21 @@ mod tests {(records, scanner.recoverable_end())}+ fn owned(vector: VectorPayload<'_>) -> StoredVector {+ match vector {+ VectorPayload::F32(values) => StoredVector::F32(values.to_vec()),+ VectorPayload::I8 { scale, values } => StoredVector::I8 {+ scale,+ values: values.to_vec(),+ },+ }+ }+fn expected_record(entry: &LogEntry<'_>) -> LogRecord {match entry {LogEntry::Add { key, vector, attrs } => LogRecord::Add {key: (*key).to_string(),- vector: vector.to_vec(),+ vector: owned(*vector),attrs: attrs.to_vec(),},LogEntry::Tombstone { key } => LogRecord::Tombstone {@@ -943,7 +1034,7 @@ mod tests {}fn write_log_file(path: &Path, dims: u32, record_bytes: &[u8]) {- let mut bytes = encode_header(dims, &[9u8; 16]).to_vec();+ let mut bytes = encode_header(dims, &[9u8; 16], StorageKind::F32).to_vec();bytes.extend_from_slice(record_bytes);std::fs::write(path, bytes).unwrap();}@@ -959,18 +1050,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]);+ let mut bytes = encode_header(8, &[7u8; 16], StorageKind::F32);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)+ Log::open(file, &path, expected_dims, 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).unwrap();+ let created = Log::create(&path, 512, StorageKind::F32).unwrap();let generation = created.generation();assert_eq!(created.current_end_offset(), HEADER_LEN as u64);assert_eq!(created.path(), path.as_path());@@ -1010,7 +1101,7 @@ mod tests {fn rejects_unknown_scalar_tag() {let error = open_with_header(|bytes| {- bytes[6] = 1;+ bytes[6] = 2;refresh_crc(bytes);},8,@@ -1057,7 +1148,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).unwrap();+ let mut log = Log::open(file, &path, 8, 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);@@ -1067,7 +1158,7 @@ mod tests {&mut log,&[LogEntry::Add {key: "reborn",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);@@ -1084,12 +1175,12 @@ mod tests {fn create_rejects_invalid_dimensions() {let dir = TempDir::new().unwrap();assert!(matches!(- Log::create(&dir.path().join("a"), 0),- Err(VecDbError::InvalidDimensions(0))+ Log::create(&dir.path().join("a"), 0, StorageKind::F32),+ Err(VecDbError::InvalidDimensions { dims: 0, .. })));assert!(matches!(- Log::create(&dir.path().join("b"), 12),- Err(VecDbError::InvalidDimensions(12))+ Log::create(&dir.path().join("b"), 12, StorageKind::F32),+ Err(VecDbError::InvalidDimensions { dims: 12, .. })));}@@ -1097,11 +1188,11 @@ mod tests {fn open_rejects_invalid_dimensions() {let dir = TempDir::new().unwrap();let path = dir.path().join("log");- drop(Log::create(&path, 8).unwrap().into_file());+ drop(Log::create(&path, 8, StorageKind::F32).unwrap().into_file());let file = File::options().read(true).write(true).open(&path).unwrap();assert!(matches!(- Log::open(file, &path, 12),- Err(VecDbError::InvalidDimensions(12))+ Log::open(file, &path, 12, None),+ Err(VecDbError::InvalidDimensions { dims: 12, .. })));}@@ -1146,13 +1237,16 @@ mod tests {value: AttrValue::F64(1.5),},];- assert_eq!(encode_header(8, &generation), golden_header);+ assert_eq!(+ encode_header(8, &generation, StorageKind::F32),+ golden_header+ );let mut encoded = Vec::new();encode_record_into(&mut encoded,&LogEntry::Add {key: "k1",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],},);@@ -1162,7 +1256,7 @@ mod tests {&mut encoded,&LogEntry::Add {key: "k2",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &attrs,},);@@ -1186,7 +1280,7 @@ mod tests {(LogRecord::Add {key: "k1".to_string(),- vector: vector.to_vec(),+ vector: StoredVector::F32(vector.to_vec()),attrs: Vec::new()},32@@ -1194,7 +1288,7 @@ mod tests {(LogRecord::Add {key: "k2".to_string(),- vector: vector.to_vec(),+ vector: StoredVector::F32(vector.to_vec()),attrs: attrs.clone()},74@@ -1215,12 +1309,12 @@ 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).unwrap();+ let mut log = Log::create(&path, dims, StorageKind::F32).unwrap();let vector = seeded_vector(1, dims);let entries = [LogEntry::Add {key: "alpha",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],},LogEntry::Tombstone { key: "beta" },@@ -1255,12 +1349,12 @@ mod tests {];let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = seeded_vector(5, 8);for key in keys {log.append(&[LogEntry::Add {key,- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}]).unwrap();@@ -1273,7 +1367,7 @@ mod tests {records[index * 2].0,LogRecord::Add {key: (*key).to_string(),- vector: vector.clone(),+ vector: StoredVector::F32(vector.clone()),attrs: Vec::new()});@@ -1290,7 +1384,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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = [f32::NAN,f32::INFINITY,@@ -1303,14 +1397,14 @@ mod tests {];log.append(&[LogEntry::Add {key: "weird",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}]).unwrap();let (records, _) = scan_all(&mut log);let LogRecord::Add {key,- vector: decoded,+ vector: StoredVector::F32(decoded),..} = &records[0].0else {@@ -1326,7 +1420,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).unwrap();+ let mut log = Log::create(&build_path, 8, StorageKind::F32).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() {@@ -1335,7 +1429,7 @@ mod tests {&mut log,&[LogEntry::Add {key: &key,- vector,+ vector: VectorPayload::F32(vector),attrs: &[],}],));@@ -1359,13 +1453,13 @@ 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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = seeded_vector(1, 8);let (_, first_end) = append_bounds(&mut log,&[LogEntry::Add {key: "kept",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);@@ -1373,7 +1467,7 @@ mod tests {&mut log,&[LogEntry::Add {key: "torn",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);@@ -1394,7 +1488,7 @@ mod tests {&mut log,&[LogEntry::Add {key: "fresh",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);@@ -1410,13 +1504,13 @@ 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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = seeded_vector(1, 8);let (_, captured_end) = append_bounds(&mut log,&[LogEntry::Add {key: "first",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);@@ -1450,13 +1544,13 @@ 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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = seeded_vector(1, 8);let (_, acked_end) = append_bounds(&mut log,&[LogEntry::Add {key: "acked",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);@@ -1480,13 +1574,13 @@ 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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = seeded_vector(6, 8);let (_, acked_end) = append_bounds(&mut log,&[LogEntry::Add {key: "acked",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);@@ -1502,7 +1596,7 @@ mod tests {&mut log,&[LogEntry::Add {key: "fresh",- vector: &fresh,+ vector: VectorPayload::F32(&fresh),attrs: &[],}],);@@ -1516,7 +1610,7 @@ mod tests {assert_eq!(records.len(), 2);assert!(matches!(&records[0].0, LogRecord::Add { key, .. } if key == "acked"));assert!(matches!(&records[1].0, LogRecord::Add { key, vector, .. }- if key == "fresh" && vector == &fresh));+ if key == "fresh" && vector == &StoredVector::F32(fresh.clone())));assert_eq!(records[1].1, acked_end);assert_eq!(recoverable_end, end);}@@ -1526,8 +1620,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).unwrap();- let mut staged = Log::create(&staged_path, 8).unwrap();+ let mut synced = Log::create(&synced_path, 8, StorageKind::F32).unwrap();+ let mut staged = Log::create(&staged_path, 8, StorageKind::F32).unwrap();let vectors: Vec<Vec<f32>> = (0..3).map(|seed| seeded_vector(seed, 8)).collect();let attrs = [Attribute {name: "model".to_string(),@@ -1537,12 +1631,12 @@ mod tests {vec![LogEntry::Add {key: "a",- vector: &vectors[0],+ vector: VectorPayload::F32(&vectors[0]),attrs: &[],},LogEntry::Add {key: "b",- vector: &vectors[1],+ vector: VectorPayload::F32(&vectors[1]),attrs: &attrs,},],@@ -1550,7 +1644,7 @@ mod tests {LogEntry::Tombstone { key: "a" },LogEntry::Add {key: "c",- vector: &vectors[2],+ vector: VectorPayload::F32(&vectors[2]),attrs: &[],},],@@ -1577,23 +1671,23 @@ 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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = seeded_vector(2, 8);let (_, acked_end) = append_bounds(&mut log,&[LogEntry::Add {key: "kept",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);drop(log);let unwritable = File::open(&path).unwrap();- let mut log = Log::open(unwritable, &path, 8).unwrap();+ let mut log = Log::open(unwritable, &path, 8, None).unwrap();assert!(matches!(log.append(&[LogEntry::Add {key: "lost",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[]}]),Err(VecDbError::Io { .. })@@ -1611,13 +1705,13 @@ 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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = seeded_vector(3, 8);let (_, acked_end) = append_bounds(&mut log,&[LogEntry::Add {key: "first",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);@@ -1627,7 +1721,7 @@ mod tests {&mut log,&[LogEntry::Add {key: "third",- vector: &replacement,+ vector: VectorPayload::F32(&replacement),attrs: &[],}],);@@ -1652,7 +1746,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).unwrap();+ let mut log = Log::create(&build_path, 8, StorageKind::F32).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() {@@ -1661,7 +1755,7 @@ mod tests {&mut log,&[LogEntry::Add {key: &key,- vector,+ vector: VectorPayload::F32(vector),attrs: &[],}],));@@ -1698,7 +1792,7 @@ mod tests {&mut good,&LogEntry::Add {key: "good",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],},);@@ -1731,7 +1825,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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();log.append(&[]).unwrap();assert_eq!(log.current_end_offset(), HEADER_LEN as u64);let vector = seeded_vector(7, 8);@@ -1743,7 +1837,7 @@ mod tests {&mut log,&[LogEntry::Add {key: &key,- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],}],);@@ -1766,13 +1860,13 @@ 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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = seeded_vector(1, 8);let wrong_dims = seeded_vector(1, 16);assert!(matches!(log.append(&[LogEntry::Add {key: "",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[]}]),Err(VecDbError::InvalidKey(_))@@ -1780,7 +1874,7 @@ mod tests {assert!(matches!(log.append(&[LogEntry::Add {key: "ok",- vector: &wrong_dims,+ vector: VectorPayload::F32(&wrong_dims),attrs: &[]}]),Err(VecDbError::DimensionMismatch {@@ -1792,7 +1886,7 @@ mod tests {log.append(&[LogEntry::Add {key: "good",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[]},LogEntry::Tombstone { key: "" }@@ -1808,8 +1902,8 @@ mod tests {#[test]fn generation_is_distinct_across_creates() {let dir = TempDir::new().unwrap();- let first = Log::create(&dir.path().join("first"), 8).unwrap();- let second = Log::create(&dir.path().join("second"), 8).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();assert_ne!(first.generation(), second.generation());}@@ -1817,10 +1911,10 @@ 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).unwrap();+ let log = Log::create(&path, 8, StorageKind::F32).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).unwrap();+ let (temp_log, temp_path) = Log::create_temp_sibling(&path, 8, StorageKind::F32).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);@@ -1849,12 +1943,12 @@ mod tests {.zip(&vectors).map(|(key, vector)| LogEntry::Add {key,- vector,+ vector: VectorPayload::F32(vector),attrs: &[],}).collect();- let mut bulk_log = Log::create(&bulk_path, dims).unwrap();- let mut sequential_log = Log::create(&sequential_path, dims).unwrap();+ 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 (_, bulk_end) = append_bounds(&mut bulk_log, &entries);let mut sequential_end = 0;for entry in &entries {@@ -1879,23 +1973,23 @@ mod tests {let entries = vec![LogEntry::Add {key: "a",- vector: &vectors[0],+ vector: VectorPayload::F32(&vectors[0]),attrs: &[],},LogEntry::Tombstone { key: "b" },LogEntry::Add {key: "c",- vector: &vectors[2],+ vector: VectorPayload::F32(&vectors[2]),attrs: &[],},LogEntry::Add {key: "d",- vector: &vectors[3],+ vector: VectorPayload::F32(&vectors[3]),attrs: &[],},];- let mut bulk_log = Log::create(&bulk_path, 8).unwrap();- let mut sequential_log = Log::create(&sequential_path, 8).unwrap();+ 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 (bulk_start, bulk_end) = append_bounds(&mut bulk_log, &entries);let mut sequential_end = 0;for entry in &entries {@@ -1944,10 +2038,10 @@ 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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();log.append(&[LogEntry::Add {key: "k",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs,}]).unwrap();@@ -1979,10 +2073,10 @@ 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).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();log.append(&[LogEntry::Add {key: "k",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs,}]).unwrap();@@ -2017,13 +2111,13 @@ mod tests {];let dir = TempDir::new().unwrap();let path = dir.path().join("log");- let mut log = Log::create(&path, 8).unwrap();+ let mut log = Log::create(&path, 8, StorageKind::F32).unwrap();let vector = seeded_vector(10, 8);for attrs in &invalid {assert!(matches!(log.append(&[LogEntry::Add {key: "k",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs,}]),Err(VecDbError::InvalidAttributes(_))@@ -2032,12 +2126,12 @@ mod tests {log.append(&[LogEntry::Add {key: "good",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],},LogEntry::Add {key: "bad",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs,}]),@@ -2057,11 +2151,11 @@ 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).unwrap();+ let mut log = Log::create(&dir.path().join("log"), 8, StorageKind::F32).unwrap();let vector = seeded_vector(11, 8);log.append(&[LogEntry::Add {key: "k",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &attrs,}]).unwrap();@@ -2084,7 +2178,7 @@ mod tests {&mut good,&LogEntry::Add {key: "good",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[attr("kept", AttrValue::Bool(true))],},);@@ -2176,7 +2270,7 @@ mod tests {&mut good,&LogEntry::Add {key: "good",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[],},);@@ -2185,7 +2279,7 @@ mod tests {&mut torn,&LogEntry::Add {key: "torn",- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &[attr("first", AttrValue::Str("value".to_string())),attr("second", AttrValue::I64(7)),@@ -2294,7 +2388,7 @@ mod tests {let mut record_bytes = good.clone();record_bytes.extend_from_slice(&vec![0xAA; step - 19]);record_bytes.extend_from_slice(&straddler);- record_bytes.extend_from_slice(&vec![0xAA; step + max_record_len(dims)]);+ record_bytes.extend_from_slice(&vec![0xAA; step + max_record_len(StorageKind::F32, dims)]);let dir = TempDir::new().unwrap();let path = dir.path().join("log");write_log_file(&path, dims as u32, &record_bytes);@@ -2307,7 +2401,7 @@ mod tests {assert!(straddler_start < step as u64);assert!(straddler_end > step as u64);let tail_len = log.current_end_offset() - recoverable_end - 1;- assert!(tail_len as usize > step + max_record_len(dims) - 1);+ assert!(tail_len as usize > step + max_record_len(StorageKind::F32, dims) - 1);assert!(log.tail_contains_valid_record_windowed(recoverable_end, step).unwrap()@@ -2322,7 +2416,10 @@ mod tests {let vector = seeded_vector(32, dims);let good = encoded_add("good", &vector);let mut record_bytes = good.clone();- record_bytes.extend_from_slice(&vec![0x01; 3 * (step + max_record_len(dims))]);+ record_bytes.extend_from_slice(&vec![+ 0x01;+ 3 * (step + max_record_len(StorageKind::F32, dims))+ ]);let dir = TempDir::new().unwrap();let path = dir.path().join("log");write_log_file(&path, dims as u32, &record_bytes);@@ -2357,7 +2454,7 @@ mod tests {assert_eq!(records.len(), 1);assert_eq!(recoverable_end, HEADER_LEN as u64 + good.len() as u64);let tail_len = log.current_end_offset() - recoverable_end - 1;- assert!(tail_len as usize > step + max_record_len(dims) - 1);+ assert!(tail_len as usize > step + max_record_len(StorageKind::F32, dims) - 1);assert!(log.tail_contains_valid_record_windowed(recoverable_end, step).unwrap()@@ -2372,7 +2469,7 @@ mod tests {fn windowed_probe_sees_a_max_length_record_ending_exactly_at_the_window_visible_end() {let dims = 8usize;let step = 4096usize;- let overlap = max_record_len(dims) - 1;+ let overlap = max_record_len(StorageKind::F32, dims) - 1;let vector = seeded_vector(34, dims);let good = encoded_add("good", &vector);let attrs: Vec<Attribute> = (b'a'..b'a' + 16)@@ -2387,11 +2484,11 @@ mod tests {&mut max_record,&LogEntry::Add {key: &key,- vector: &vector,+ vector: VectorPayload::F32(&vector),attrs: &attrs,},);- assert_eq!(max_record.len(), max_record_len(dims));+ assert_eq!(max_record.len(), max_record_len(StorageKind::F32, dims));let mut record_bytes = good.clone();record_bytes.extend_from_slice(&vec![0xAA; step]);record_bytes.extend_from_slice(&max_record);@@ -2426,4 +2523,538 @@ mod tests {.unwrap());}++ fn encoded_i8_add(key: &str, scale: f32, values: &[i8]) -> Vec<u8> {+ let mut bytes = Vec::new();+ encode_record_into(+ &mut bytes,+ &LogEntry::Add {+ key,+ vector: VectorPayload::I8 { scale, values },+ attrs: &[],+ },+ );+ bytes+ }++ fn write_i8_log_file(path: &Path, dims: u32, record_bytes: &[u8]) {+ let mut bytes = encode_header(dims, &[9u8; 16], StorageKind::I8).to_vec();+ bytes.extend_from_slice(record_bytes);+ std::fs::write(path, bytes).unwrap();+ }++ fn seeded_i8_values(seed: u64, dims: usize) -> Vec<i8> {+ let mut state = seed;+ (0..dims)+ .map(|_| (splitmix64(&mut state) % 255) as i64 as i8)+ .collect::<Vec<i8>>()+ .into_iter()+ .map(|value| value.max(-127))+ .collect()+ }++ fn golden_i8_values() -> Vec<i8> {+ let mut values: Vec<i8> = (0..32).map(|index| (index * 8 - 124) as i8).collect();+ values[0] = -127;+ values[1] = 127;+ values[2] = 0;+ values[3] = -1;+ values+ }++ #[test]+ fn i8_golden_bytes_pin_the_header_and_add_record() {+ let generation: [u8; 16] = std::array::from_fn(|index| index as u8);+ let golden_header: [u8; 32] = [+ 0x45, 0x56, 0x44, 0x42, 0x01, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x01,+ 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,+ 0x2f, 0xd0, 0x62, 0xc1,+ ];+ let golden_add: [u8; 46] = [+ 0x01, 0x02, 0x00, 0x6b, 0x31, 0x0a, 0xd7, 0x23, 0x3c, 0x81, 0x7f, 0x00, 0xff, 0xa4,+ 0xac, 0xb4, 0xbc, 0xc4, 0xcc, 0xd4, 0xdc, 0xe4, 0xec, 0xf4, 0xfc, 0x04, 0x0c, 0x14,+ 0x1c, 0x24, 0x2c, 0x34, 0x3c, 0x44, 0x4c, 0x54, 0x5c, 0x64, 0x6c, 0x74, 0x7c, 0x00,+ 0x72, 0x96, 0xfc, 0xa0,+ ];+ let scale = 0.01f32;+ assert_eq!(scale.to_bits(), 0x3c23_d70a);+ let values = golden_i8_values();+ let header = encode_header(32, &generation, StorageKind::I8);+ assert_eq!(header[STORAGE_TAG_OFFSET], 1);+ assert_eq!(header[..28], golden_header[..28]);+ let encoded = encoded_i8_add("k1", scale, &values);+ assert_eq!(encoded.len(), 46);+ assert_eq!(encoded[..42], golden_add[..42]);+ assert_eq!(header, golden_header);+ assert_eq!(encoded, golden_add);+ let mut tombstone = Vec::new();+ encode_record_into(&mut tombstone, &LogEntry::Tombstone { key: "k1" });+ assert_eq!(+ tombstone,+ [0x02, 0x02, 0x00, 0x6b, 0x31, 0xa0, 0xde, 0x3c, 0xc1]+ );+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("log");+ let mut bytes = golden_header.to_vec();+ bytes.extend_from_slice(&golden_add);+ bytes.extend_from_slice(&tombstone);+ std::fs::write(&path, &bytes).unwrap();+ let mut log = reopen(&path, 32);+ assert_eq!(log.storage(), StorageKind::I8);+ assert_eq!(log.generation(), generation);+ let (records, recoverable_end) = scan_all(&mut log);+ assert_eq!(+ records,+ vec![+ (+ LogRecord::Add {+ key: "k1".to_string(),+ vector: StoredVector::I8 {+ scale,+ values: values.clone()+ },+ attrs: Vec::new()+ },+ 32+ ),+ (+ LogRecord::Tombstone {+ key: "k1".to_string()+ },+ 78+ )+ ]+ );+ assert_eq!(recoverable_end, 87);+ }++ #[test]+ fn f32_headers_leave_the_storage_tag_zero() {+ let header = encode_header(8, &[7u8; 16], StorageKind::F32);+ assert_eq!(header[STORAGE_TAG_OFFSET], 0);+ assert_eq!(+ decode_header(&header, 8).unwrap(),+ ([7u8; 16], StorageKind::F32)+ );+ }++ #[test]+ fn rejects_unknown_storage_tag() {+ for tag in [2u8, 3, 0x7f, 0xff] {+ let error = open_with_header(+ |bytes| {+ bytes[STORAGE_TAG_OFFSET] = tag;+ refresh_crc(bytes);+ },+ 8,+ )+ .unwrap_err();+ assert!(matches!(&error, VecDbError::Corrupt(message) if message.contains("scalar")));+ }+ }++ #[test]+ fn storage_kind_round_trips_and_mismatches_are_reported() {+ 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();+ assert_eq!(created.storage(), StorageKind::I8);+ let generation = created.generation();+ drop(created.into_file());+ drop(+ Log::create(&f32_path, 32, StorageKind::F32)+ .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)+ };+ let detected = open(&i8_path, None).unwrap();+ assert_eq!(detected.storage(), StorageKind::I8);+ assert_eq!(detected.generation(), generation);+ assert_eq!(+ open(&i8_path, Some(StorageKind::I8)).unwrap().storage(),+ StorageKind::I8+ );+ assert!(matches!(+ open(&i8_path, Some(StorageKind::F32)),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::F32,+ actual: StorageKind::I8+ })+ ));+ assert_eq!(open(&f32_path, None).unwrap().storage(), StorageKind::F32);+ assert!(matches!(+ open(&f32_path, Some(StorageKind::I8)),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::I8,+ actual: StorageKind::F32+ })+ ));+ assert_eq!(std::fs::read(&i8_path).unwrap()[STORAGE_TAG_OFFSET], 1);+ assert_eq!(std::fs::read(&f32_path).unwrap()[STORAGE_TAG_OFFSET], 0);+ }++ #[test]+ fn short_files_reinitialize_with_the_requested_storage() {+ let dir = TempDir::new().unwrap();+ 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();+ assert_eq!(log.storage(), StorageKind::I8);+ drop(log);+ assert_eq!(reopen(&path, 64).storage(), StorageKind::I8);+ let other = dir.path().join("other");+ 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(),+ StorageKind::F32+ );+ }++ #[test]+ fn i8_logs_require_a_multiple_of_32_dims() {+ 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),+ 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()+ );+ }+ assert!(Log::create(&dir.path().join("c"), 32, StorageKind::I8).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)),+ Err(VecDbError::InvalidDimensions {+ dims: 8,+ storage: StorageKind::I8+ })+ ));+ let mut forged = encode_header(8, &[3u8; 16], StorageKind::I8);+ refresh_crc(&mut forged);+ let forged_path = dir.path().join("forged");+ std::fs::write(&forged_path, forged).unwrap();+ let file = File::options()+ .read(true)+ .write(true)+ .open(&forged_path)+ .unwrap();+ assert!(matches!(+ Log::open(file, &forged_path, 8, None),+ Err(VecDbError::InvalidDimensions {+ dims: 8,+ storage: StorageKind::I8+ })+ ));+ }++ #[test]+ fn i8_add_records_round_trip_bit_for_bit() {+ 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 scales = [+ f32::from_bits(0x3a1f_8f3c),+ 0.0,+ f32::NAN,+ -2.5,+ f32::MIN_POSITIVE,+ ];+ let mut expected = Vec::new();+ for (index, scale) in scales.iter().enumerate() {+ let mut values = seeded_i8_values(index as u64, dims);+ values[0] = -127;+ values[1] = 127;+ let key = format!("key-{index}");+ let (start, _) = append_bounds(+ &mut log,+ &[LogEntry::Add {+ key: &key,+ vector: VectorPayload::I8 {+ scale: *scale,+ values: &values,+ },+ attrs: &[],+ }],+ );+ expected.push((key, *scale, values, start));+ }+ let (records, _) = scan_all(&mut log);+ assert_eq!(records.len(), scales.len());+ for ((record, offset), (key, scale, values, start)) in records.iter().zip(&expected) {+ assert_eq!(offset, start);+ let LogRecord::Add {+ key: decoded_key,+ vector:+ StoredVector::I8 {+ scale: decoded_scale,+ values: decoded_values,+ },+ ..+ } = record+ else {+ panic!("expected an i8 add record");+ };+ assert_eq!(decoded_key, key);+ assert_eq!(decoded_scale.to_bits(), scale.to_bits());+ assert_eq!(decoded_values, values);+ }+ drop(log);+ let (reopened, _) = scan_all(&mut reopen(&path, dims));+ assert_eq!(reopened.len(), records.len());+ for ((record, offset), (again, again_offset)) in records.iter().zip(&reopened) {+ assert_eq!(offset, again_offset);+ assert_eq!(format!("{record:?}"), format!("{again:?}"));+ }+ }+ }++ #[test]+ fn payload_kind_must_match_the_log_storage() {+ 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 values = seeded_vector(4, 32);+ let quantized = StoredVector::quantize(&values);+ assert!(matches!(+ i8_log.append(&[LogEntry::Add {+ key: "k",+ vector: VectorPayload::F32(&values),+ attrs: &[],+ }]),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::I8,+ actual: StorageKind::F32+ })+ ));+ assert!(matches!(+ f32_log.append(&[LogEntry::Add {+ key: "k",+ vector: quantized.as_payload(),+ attrs: &[],+ }]),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::F32,+ actual: StorageKind::I8+ })+ ));+ assert!(matches!(+ i8_log.append(&[LogEntry::Add {+ key: "k",+ vector: VectorPayload::I8 {+ scale: 1.0,+ values: &[1i8; 64],+ },+ attrs: &[],+ }]),+ Err(VecDbError::DimensionMismatch {+ expected: 32,+ actual: 64+ })+ ));+ assert_eq!(i8_log.current_end_offset(), HEADER_LEN as u64);+ assert_eq!(f32_log.current_end_offset(), HEADER_LEN as u64);+ assert_eq!(+ std::fs::metadata(&i8_path).unwrap().len(),+ HEADER_LEN as u64+ );+ assert_eq!(+ std::fs::metadata(&f32_path).unwrap().len(),+ HEADER_LEN as u64+ );+ }++ #[test]+ fn max_record_len_is_storage_aware() {+ let fixed = RECORD_PREFIX_LEN + MAX_KEY_BYTES + 1 + MAX_ATTRS_TOTAL_BYTES + RECORD_CRC_LEN;+ assert_eq!(max_record_len(StorageKind::F32, 32), fixed + 128);+ assert_eq!(max_record_len(StorageKind::I8, 32), fixed + 36);+ assert_eq!(max_record_len(StorageKind::F32, 512), fixed + 2048);+ assert_eq!(max_record_len(StorageKind::I8, 512), fixed + 516);+ assert_eq!(vector_payload_len(StorageKind::I8, 512), 516);+ assert_eq!(vector_payload_len(StorageKind::F32, 512), 2048);+ }++ #[test]+ fn i8_scanner_stops_at_every_torn_length_and_at_f32_sized_records() {+ 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 boundaries = Vec::new();+ for index in 0..3u64 {+ let key = format!("key-{index}");+ let values = seeded_i8_values(index, dims);+ boundaries.push(append_bounds(+ &mut log,+ &[LogEntry::Add {+ key: &key,+ vector: VectorPayload::I8 {+ scale: 0.25,+ values: &values,+ },+ attrs: &[],+ }],+ ));+ }+ drop(log);+ let full_bytes = std::fs::read(&build_path).unwrap();+ let intact_end = boundaries[1].1;+ for cut in intact_end..boundaries[2].1 {+ let torn_path = dir.path().join(format!("torn-{cut}"));+ std::fs::write(&torn_path, &full_bytes[..cut as usize]).unwrap();+ let mut torn_log = reopen(&torn_path, dims);+ let (records, recoverable_end) = scan_all(&mut torn_log);+ assert_eq!(records.len(), 2);+ assert_eq!(recoverable_end, intact_end);+ }+ let f32_sized = encoded_add("f32-sized", &seeded_vector(5, dims));+ let mut mixed = full_bytes[..intact_end as usize].to_vec();+ mixed.extend_from_slice(&f32_sized);+ let mixed_path = dir.path().join("mixed");+ std::fs::write(&mixed_path, &mixed).unwrap();+ let mut mixed_log = reopen(&mixed_path, dims);+ let (records, recoverable_end) = scan_all(&mut mixed_log);+ assert_eq!(records.len(), 2);+ assert_eq!(recoverable_end, intact_end);+ assert!(+ !mixed_log+ .tail_contains_valid_record(recoverable_end)+ .unwrap()+ );+ }++ #[test]+ fn i8_tail_probe_finds_an_intact_record_beyond_mid_log_damage() {+ let dims = 32usize;+ let first = encoded_i8_add("first", 0.5, &seeded_i8_values(21, dims));+ let mut tombstone = Vec::new();+ encode_record_into(&mut tombstone, &LogEntry::Tombstone { key: "gone" });+ let survivors = [+ encoded_i8_add("second", 0.75, &seeded_i8_values(22, dims)),+ tombstone,+ ];+ let dir = TempDir::new().unwrap();+ for (index, survivor) in survivors.iter().enumerate() {+ for garbage_len in [1usize, 7, 19] {+ let path = dir.path().join(format!("log-{index}-{garbage_len}"));+ let mut record_bytes = first.clone();+ record_bytes.extend_from_slice(&vec![0xAA; garbage_len]);+ record_bytes.extend_from_slice(survivor);+ write_i8_log_file(&path, dims as u32, &record_bytes);+ let mut log = reopen(&path, dims);+ assert_eq!(log.storage(), StorageKind::I8);+ let (records, recoverable_end) = scan_all(&mut log);+ assert_eq!(records.len(), 1);+ assert_eq!(recoverable_end, HEADER_LEN as u64 + first.len() as u64);+ assert!(log.tail_contains_valid_record(recoverable_end).unwrap());+ }+ }+ }++ #[test]+ fn i8_windowed_probe_sees_a_max_length_record_ending_exactly_at_the_window_visible_end() {+ let dims = 32usize;+ let step = 4096usize;+ let overlap = max_record_len(StorageKind::I8, dims) - 1;+ let good = encoded_i8_add("good", 0.5, &seeded_i8_values(34, dims));+ let attrs: Vec<Attribute> = (b'a'..b'a' + 16)+ .map(|name| Attribute {+ name: (name as char).to_string(),+ value: AttrValue::Str("v".repeat(251)),+ })+ .collect();+ let key = "k".repeat(256);+ let values = seeded_i8_values(35, dims);+ let mut max_record = Vec::new();+ encode_record_into(+ &mut max_record,+ &LogEntry::Add {+ key: &key,+ vector: VectorPayload::I8 {+ scale: 0.125,+ values: &values,+ },+ attrs: &attrs,+ },+ );+ assert_eq!(max_record.len(), max_record_len(StorageKind::I8, dims));+ assert!(max_record.len() < max_record_len(StorageKind::F32, dims));+ let mut record_bytes = good.clone();+ record_bytes.extend_from_slice(&vec![0xAA; step]);+ record_bytes.extend_from_slice(&max_record);+ record_bytes.extend_from_slice(&vec![0xAA; 256]);+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("log");+ write_i8_log_file(&path, dims as u32, &record_bytes);+ let mut log = reopen(&path, dims);+ let (records, recoverable_end) = scan_all(&mut log);+ assert_eq!(records.len(), 1);+ assert_eq!(recoverable_end, HEADER_LEN as u64 + good.len() as u64);+ let record_tail_start = step - 1;+ assert_eq!(record_tail_start + max_record.len(), step + overlap);+ let tail_len = (log.current_end_offset() - recoverable_end - 1) as usize;+ assert!(tail_len > step + overlap);+ assert!(+ log.tail_contains_valid_record_windowed(recoverable_end, step)+ .unwrap()+ );+ assert!(log.tail_contains_valid_record(recoverable_end).unwrap());+ let mut corrupted_bytes = record_bytes.clone();+ let crc_last = good.len() + step + max_record.len() - 1;+ corrupted_bytes[crc_last] ^= 0xFF;+ let corrupted_path = dir.path().join("log-corrupted");+ write_i8_log_file(&corrupted_path, dims as u32, &corrupted_bytes);+ let mut corrupted_log = reopen(&corrupted_path, dims);+ let (corrupted_records, corrupted_end) = scan_all(&mut corrupted_log);+ assert_eq!(corrupted_records.len(), 1);+ assert!(+ !corrupted_log+ .tail_contains_valid_record_windowed(corrupted_end, step)+ .unwrap()+ );+ }++ #[test]+ fn i8_windowed_probe_finds_a_straddling_record_with_a_step_smaller_than_the_record() {+ let dims = 32usize;+ let step = 4usize;+ let good = encoded_i8_add("good", 0.5, &seeded_i8_values(36, dims));+ let straddler = encoded_i8_add("straddler", 0.5, &seeded_i8_values(37, dims));+ assert!(step < straddler.len());+ let mut record_bytes = good.clone();+ record_bytes.extend_from_slice(&vec![0x01; 5000]);+ record_bytes.extend_from_slice(&straddler);+ record_bytes.extend_from_slice(&[0x01; 20]);+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("log");+ write_i8_log_file(&path, dims as u32, &record_bytes);+ let mut log = reopen(&path, dims);+ let (records, recoverable_end) = scan_all(&mut log);+ assert_eq!(records.len(), 1);+ assert_eq!(recoverable_end, HEADER_LEN as u64 + good.len() as u64);+ assert!(+ log.tail_contains_valid_record_windowed(recoverable_end, step)+ .unwrap()+ );+ let tail_len = log.current_end_offset() - recoverable_end - 1;+ assert!(+ !log.tail_contains_valid_record_windowed(recoverable_end - 1 + tail_len, step)+ .unwrap()+ );+ }}diff --git a/rust/crates/ml/src/vecdb/mod.rs b/rust/crates/ml/src/vecdb/mod.rsindex 3a12145bf3..71297295f1 100644--- a/rust/crates/ml/src/vecdb/mod.rs+++ b/rust/crates/ml/src/vecdb/mod.rs@@ -13,6 +13,45 @@ mod store;pub use store::{OpenCost, Stats, VecDb};+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum StorageKind {+ F32,+ I8,+}++impl StorageKind {+ pub(crate) fn lane_width(self) -> usize {+ match self {+ Self::F32 => kernel::LANE_WIDTH,+ Self::I8 => kernel::LANE_WIDTH_I8,+ }+ }++ pub(crate) fn header_tag(self) -> u8 {+ match self {+ Self::F32 => 0,+ Self::I8 => 1,+ }+ }++ pub(crate) fn from_header_tag(tag: u8) -> Option<Self> {+ match tag {+ 0 => Some(Self::F32),+ 1 => Some(Self::I8),+ _ => None,+ }+ }+}++impl std::fmt::Display for StorageKind {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(match self {+ Self::F32 => "f32",+ Self::I8 => "i8",+ })+ }+}+#[derive(Debug, Clone, PartialEq)]pub enum AttrValue {Str(String),@@ -71,8 +110,13 @@ pub enum VecDbError {InvalidAttributes(String),#[error("dimension mismatch: expected {expected}, got {actual}")]DimensionMismatch { expected: usize, actual: usize },- #[error("invalid dimensions {0}: must be a nonzero multiple of 8")]- InvalidDimensions(usize),+ #[error("invalid dimensions {dims}: {storage} storage needs a nonzero multiple of {}", .storage.lane_width())]+ InvalidDimensions { dims: usize, storage: StorageKind },+ #[error("storage mismatch: expected {expected}, found {actual}")]+ StorageMismatch {+ expected: StorageKind,+ actual: StorageKind,+ },#[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 f1ecc1f1e4..4856aeae32 100644--- a/rust/crates/ml/src/vecdb/store.rs+++ b/rust/crates/ml/src/vecdb/store.rs@@ -9,8 +9,9 @@ use std::sync::{};use std::time::{Duration, Instant};-use super::arena::{UpsertOutcome, VECTORS_PER_CHUNK, VectorArena};+use super::arena::{UpsertOutcome, VectorArena};use super::graph::{Graph, search as graph_search, search_stored};+use super::kernel::{StoredVector, VectorPayload, quantize_for};use super::lock::WriterLock;use super::log::{HEADER_LEN, Log, LogEntry, LogRecord, header_generation, remove_if_present,@@ -19,7 +20,7 @@ use super::log::{use super::snapshot::{LoadedSnapshot, load_snapshot, remove_snapshot, snapshot_path, write_snapshot,};-use super::{AttrValue, Attribute, KeyMatches, Match, SearchParams, VecDbError};+use super::{AttrValue, Attribute, KeyMatches, Match, SearchParams, StorageKind, VecDbError};const SNAPSHOT_HARD_CAP: usize = 5000;const SNAPSHOT_QUIET_THRESHOLD: usize = 1000;@@ -62,6 +63,7 @@ pub struct Stats {pub live_count: usize,pub dead_count: usize,pub dims: usize,+ pub storage: StorageKind,pub log_bytes: u64,pub records_since_snapshot: usize,pub approximate_memory_bytes: usize,@@ -75,6 +77,7 @@ pub struct VecDb {struct Shared {path: PathBuf,dims: usize,+ storage: StorageKind,registry_key: Option<PathBuf>,closed: AtomicBool,writer: Mutex<WriterHalf>,@@ -297,13 +300,26 @@ fn registry_key_for(path: &Path) -> Result<PathBuf, VecDbError> {Ok(canonical_parent.join(file_name))}-fn join_live(shared: Arc<Shared>, dims: usize, read_only: bool) -> Result<VecDb, VecDbError> {+fn join_live(+ shared: Arc<Shared>,+ dims: usize,+ storage: Option<StorageKind>,+ read_only: bool,+) -> Result<VecDb, VecDbError> {if shared.dims != dims {return Err(VecDbError::DimensionMismatch {expected: dims,actual: shared.dims,});}+ if let Some(requested) = storage+ && requested != shared.storage+ {+ return Err(VecDbError::StorageMismatch {+ expected: requested,+ actual: shared.storage,+ });+ }Ok(VecDb { shared, read_only })}@@ -355,6 +371,22 @@ fn warn_handoff_cap(path: &Path) {impl VecDb {pub fn open(path: &Path, dims: usize) -> Result<Self, VecDbError> {+ Self::open_with(path, dims, None)+ }++ pub fn open_with_storage(+ path: &Path,+ dims: usize,+ storage: StorageKind,+ ) -> Result<Self, VecDbError> {+ Self::open_with(path, dims, Some(storage))+ }++ fn open_with(+ path: &Path,+ dims: usize,+ storage: Option<StorageKind>,+ ) -> Result<Self, VecDbError> {let key = registry_key_for(path)?;let slot = path_slot(&key);let mut guard = lock_slot(&slot);@@ -362,17 +394,19 @@ impl VecDb {let observed = guard.live.as_ref().and_then(Weak::upgrade);drop(guard);match observed {- Some(shared) if !shared.is_closed() => return join_live(shared, dims, false),+ Some(shared) if !shared.is_closed() => {+ return join_live(shared, dims, storage, false);+ }observed => drop(observed),}match wait_for_teardown_handoff(&slot, &key) {- SlotHandoff::Join(shared) => return join_live(shared, dims, false),+ SlotHandoff::Join(shared) => return join_live(shared, dims, storage, false),SlotHandoff::Released(reacquired) | SlotHandoff::Expired(reacquired) => {guard = reacquired;}}}- let built = match build_writer(&key, key.clone(), dims) {+ let built = match build_writer(&key, key.clone(), dims, storage) {Ok(built) => built,Err(error) => {drop(guard);@@ -422,11 +456,13 @@ impl VecDb {if let Some(slot) = existing_path_slot(&resolved) {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, true),+ Some(shared) if !shared.is_closed() => {+ return join_live(shared, dims, None, true);+ }Some(closing) => {drop(closing);match wait_for_teardown_handoff(&slot, &resolved) {- SlotHandoff::Join(shared) => return join_live(shared, dims, true),+ SlotHandoff::Join(shared) => return join_live(shared, dims, None, true),SlotHandoff::Released(released) | SlotHandoff::Expired(released) => {drop(released);}@@ -455,8 +491,16 @@ impl VecDb {let mut half = self.writable_half()?;let state = active_state(&mut half)?;ensure_finite(key, vector)?;- state.log.append(&[LogEntry::Add { key, vector, attrs }])?;- apply_add(&self.shared, key, vector, attrs)?;+ let quantized = quantize_for(self.shared.storage, vector);+ let payload = quantized+ .as_ref()+ .map_or(VectorPayload::F32(vector), StoredVector::as_payload);+ state.log.append(&[LogEntry::Add {+ key,+ vector: payload,+ attrs,+ }])?;+ apply_add(&self.shared, key, payload, attrs)?;apply_policy(&self.shared, &mut half, 1, now)}@@ -505,19 +549,31 @@ impl VecDb {for (key, vector) in keys.iter().zip(vectors) {ensure_finite(key, vector)?;}+ let quantized: Option<Vec<StoredVector>> = match self.shared.storage {+ StorageKind::F32 => None,+ StorageKind::I8 => Some(+ vectors+ .iter()+ .map(|vector| StoredVector::quantize(vector))+ .collect(),+ ),+ };+ let payload_of = |index: usize| match &quantized {+ Some(stored) => stored[index].as_payload(),+ None => VectorPayload::F32(&vectors[index]),+ };let records: Vec<LogEntry<'_>> = keys.iter()- .zip(vectors).enumerate()- .map(|(index, (key, vector))| LogEntry::Add {+ .map(|(index, key)| LogEntry::Add {key,- vector,+ vector: payload_of(index),attrs: attrs_of(index),}).collect();state.log.append(&records)?;- for (index, (key, vector)) in keys.iter().zip(vectors).enumerate() {- apply_add(&self.shared, key, vector, attrs_of(index))?;+ for (index, key) in keys.iter().enumerate() {+ apply_add(&self.shared, key, payload_of(index), attrs_of(index))?;}apply_policy(&self.shared, &mut half, keys.len(), now)}@@ -722,8 +778,9 @@ impl VecDb {let old_generation = log.generation();drop(log);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));+ .and_then(|()| Log::create(&self.shared.path, dims, storage));let log = match recreated {Ok(log) => log,Err(error) => {@@ -737,7 +794,7 @@ impl VecDb {return Err(error);}};- let arena = VectorArena::new(dims)?;+ let arena = VectorArena::with_storage(dims, storage)?;{let mut st = self.shared.state_write();st.arena = arena;@@ -822,6 +879,7 @@ impl VecDb {live_count,dead_count: st.total_records.saturating_sub(live_count as u64) as usize,dims: st.arena.dims(),+ storage: self.shared.storage,log_bytes,records_since_snapshot,approximate_memory_bytes: approximate_memory_bytes(&st),@@ -949,7 +1007,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::new(shared.dims) {+ if let Ok(empty) = VectorArena::with_storage(shared.dims, shared.storage) {st.arena = empty;st.graph = Some(Graph::new());st.attrs.reset();@@ -976,7 +1034,7 @@ fn close_live_instance(shared: &Arc<Shared>) -> Result<(), VecDbError> {fn apply_add(shared: &Shared,key: &str,- vector: &[f32],+ vector: VectorPayload<'_>,attrs: &[Attribute],) -> Result<(), VecDbError> {let mut st = shared.state_write();@@ -986,7 +1044,7 @@ fn apply_add(attrs: attr_table,total_records,} = &mut *st;- let outcome = arena.upsert(key, vector)?;+ let outcome = arena.upsert_payload(key, vector)?;attr_table.set(slot_of_outcome(outcome), attrs);if let Some(graph) = graph {apply_outcome(graph, arena, outcome);@@ -1064,8 +1122,8 @@ fn write_snapshot_now(shared: &Shared, half: &mut WriterHalf) -> Result<(), VecDfn compact(shared: &Shared, half: &mut WriterHalf) -> Result<(), VecDbError> {active_state(half)?;- let dims = shared.dims;- let (mut temp_log, temp_path) = Log::create_temp_sibling(&shared.path, dims)?;+ let (mut temp_log, temp_path) =+ Log::create_temp_sibling(&shared.path, shared.dims, shared.storage)?;let staged = {let st = shared.state_read();stage_live_entries(&st, &mut temp_log)@@ -1128,7 +1186,7 @@ fn restore_writer_mode(last_write: Option<Instant>,mutations_since_snapshot: usize,) -> Result<(), VecDbError> {- match reopen_log(&shared.path, shared.dims) {+ match reopen_log(&shared.path, shared.dims, Some(shared.storage)) {Ok(log) => {half.mode = WriterMode::Active(WriterState {lock,@@ -1164,7 +1222,7 @@ fn recover_after_failed_reset(if old_log_restored {return;}- if let Ok(empty) = VectorArena::new(shared.dims) {+ if let Ok(empty) = VectorArena::with_storage(shared.dims, shared.storage) {let mut st = shared.state_write();st.arena = empty;st.graph = Some(Graph::new());@@ -1190,15 +1248,17 @@ fn build_writer(path: &Path,registry_key: PathBuf,dims: usize,+ storage: Option<StorageKind>,) -> Result<BuiltWriter, VecDbError> {let lock = WriterLock::acquire(path)?;- let mut log = match Log::create(path, dims) {+ let mut log = match Log::create(path, dims, storage.unwrap_or(StorageKind::F32)) {Ok(created) => created,Err(VecDbError::Io { source, .. }) if source.kind() == ErrorKind::AlreadyExists => {- reopen_log(path, dims)?+ reopen_log(path, dims, storage)?}Err(error) => return Err(error),};+ let storage = log.storage();remove_stale_temp_sibling(path)?;let snapshot_present = std::fs::metadata(snapshot_path(path)).is_ok();let replayed = replay(&mut log, dims, ReplayMode::Writer)?;@@ -1234,6 +1294,7 @@ fn build_writer(path,registry_key,dims,+ storage,WriterState {lock,log,@@ -1253,6 +1314,7 @@ fn build_writer(path,registry_key,dims,+ storage,WriterState {lock,log,@@ -1276,12 +1338,14 @@ fn writer_shared(path: &Path,registry_key: PathBuf,dims: usize,+ storage: StorageKind,writer: WriterState,state: SearchState,) -> Shared {Shared {path: path.to_path_buf(),dims,+ storage,registry_key: Some(registry_key),closed: AtomicBool::new(false),writer: Mutex::new(WriterHalf {@@ -1349,7 +1413,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)?;+ let mut log = Log::open(file, path, dims, None)?;let replayed = replay(&mut log, dims, ReplayMode::ReadOnly)?;drop(log);let ReplayedState {@@ -1363,7 +1427,6 @@ fn build_read_only(path: &Path, dims: usize) -> Result<Shared, VecDbError> {let graph = graph.unwrap_or_else(|| Graph::rebuild(&arena));Ok(read_only_shared(path,- dims,arena,graph,attrs,@@ -1375,7 +1438,6 @@ 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,- dims,VectorArena::new(dims)?,Graph::new(),AttrTable::default(),@@ -1386,7 +1448,6 @@ fn empty_read_only(path: &Path, dims: usize) -> Result<Shared, VecDbError> {fn read_only_shared(path: &Path,- dims: usize,arena: VectorArena,graph: Graph,attrs: AttrTable,@@ -1395,7 +1456,8 @@ fn read_only_shared() -> Shared {Shared {path: path.to_path_buf(),- dims,+ dims: arena.dims(),+ storage: arena.storage_kind(),registry_key: None,closed: AtomicBool::new(false),writer: Mutex::new(WriterHalf {@@ -1412,10 +1474,7 @@ fn read_only_shared(}fn approximate_memory_bytes(state: &SearchState) -> usize {- let vector_bytes = state.arena.slot_count().div_ceil(VECTORS_PER_CHUNK)- * VECTORS_PER_CHUNK- * state.arena.dims()- * size_of::<f32>();+ let vector_bytes = state.arena.vector_memory_bytes();let key_bytes: usize = state.arena.live_slots()@@ -1462,7 +1521,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::new(dims)?;+ let mut arena = VectorArena::with_storage(dims, log.storage())?;let mut attrs = AttrTable::default();let mut graph: Option<Graph> = None;let mut tail_records = 0u64;@@ -1482,7 +1541,7 @@ fn replay(log: &mut Log, dims: usize, mode: ReplayMode) -> Result<ReplayedState,vector,attrs: record_attrs,} => {- let outcome = arena.upsert(&key, &vector)?;+ let outcome = arena.upsert_payload(&key, vector.as_payload())?;attrs.set(slot_of_outcome(outcome), &record_attrs);if let Some(graph) = &mut graph {apply_outcome(graph, &arena, outcome);@@ -1567,13 +1626,13 @@ fn ensure_finite(key: &str, vector: &[f32]) -> Result<(), VecDbError> {Ok(())}-fn reopen_log(path: &Path, dims: usize) -> Result<Log, VecDbError> {+fn reopen_log(path: &Path, dims: usize, storage: Option<StorageKind>) -> Result<Log, VecDbError> {let file = File::options().read(true).write(true).open(path).map_err(|source| VecDbError::io(path, source))?;- Log::open(file, path, dims)+ Log::open(file, path, dims, storage)}fn promote_compacted_log(temp_path: &Path, path: &Path) -> Result<(), VecDbError> {@@ -1589,7 +1648,7 @@ fn remove_data_files(path: &Path) -> Result<(), VecDbError> {}fn stage_live_entries(source: &SearchState, log: &mut Log) -> Result<(), VecDbError> {- let mut batch: Vec<(String, Vec<f32>, Vec<Attribute>)> =+ let mut batch: Vec<(String, StoredVector, Vec<Attribute>)> =Vec::with_capacity(COMPACTION_BATCH_SIZE);for slot in source.arena.live_slots() {let Some(key) = source.arena.key_of_slot(slot) else {@@ -1597,7 +1656,7 @@ fn stage_live_entries(source: &SearchState, log: &mut Log) -> Result<(), VecDbEr};batch.push((key.to_string(),- source.arena.vector_values(slot),+ source.arena.stored_vector(slot),source.attrs.get(slot)@@ -1612,7 +1671,7 @@ fn stage_live_entries(source: &SearchState, log: &mut Log) -> Result<(), VecDbEr}fn flush_stage_batch(- batch: &mut Vec<(String, Vec<f32>, Vec<Attribute>)>,+ batch: &mut Vec<(String, StoredVector, Vec<Attribute>)>,log: &mut Log,) -> Result<(), VecDbError> {if batch.is_empty() {@@ -1620,7 +1679,11 @@ fn flush_stage_batch(}let records: Vec<LogEntry<'_>> = batch.iter()- .map(|(key, vector, attrs)| LogEntry::Add { key, vector, attrs })+ .map(|(key, vector, attrs)| LogEntry::Add {+ key,+ vector: vector.as_payload(),+ attrs,+ }).collect();log.append_unsynced_for_staging(&records)?;batch.clear();@@ -2028,8 +2091,8 @@ mod tests {bulk_add(&db, &bulk_entries(0, 2, 500)).unwrap();db.flush().unwrap();drop(db);- let mut captured_for_read_only = reopen_log(&path, DIMS).unwrap();- let mut captured_for_writer = reopen_log(&path, DIMS).unwrap();+ let mut captured_for_read_only = reopen_log(&path, DIMS, None).unwrap();+ let mut captured_for_writer = reopen_log(&path, DIMS, 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();@@ -2064,7 +2127,7 @@ mod tests {bulk_add(&db, &bulk_entries(0, 2, 700)).unwrap();db.flush().unwrap();drop(db);- let mut captured_for_read_only = reopen_log(&path, DIMS).unwrap();+ let mut captured_for_read_only = reopen_log(&path, DIMS, 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();@@ -2749,6 +2812,7 @@ mod tests {live_count: 0,dead_count: 0,dims: DIMS,+ storage: StorageKind::F32,log_bytes: 0,records_since_snapshot: 0,approximate_memory_bytes: 0,@@ -3332,16 +3396,24 @@ mod tests {fn promote_compacted_log_replaces_the_log_durably() {let dir = TempDir::new().unwrap();let path = dir.path().join("db");- drop(Log::create(&path, DIMS).unwrap().into_file());+ drop(+ Log::create(&path, DIMS, StorageKind::F32)+ .unwrap()+ .into_file(),+ );let old_generation = generation_of(&path);let temp = temp_sibling(&path);- drop(Log::create(&temp, DIMS).unwrap().into_file());+ drop(+ Log::create(&temp, DIMS, StorageKind::F32)+ .unwrap()+ .into_file(),+ );let new_generation = generation_of(&temp);promote_compacted_log(&temp, &path).unwrap();assert!(!temp.exists());assert_eq!(generation_of(&path), new_generation);assert_ne!(generation_of(&path), old_generation);- let log = reopen_log(&path, DIMS).unwrap();+ let log = reopen_log(&path, DIMS, None).unwrap();assert_eq!(log.generation(), new_generation);drop(log);assert!(matches!(@@ -3538,6 +3610,7 @@ mod tests {live_count: 0,dead_count: 0,dims: DIMS,+ storage: StorageKind::F32,log_bytes: 32,records_since_snapshot: 0,approximate_memory_bytes: 0,@@ -3628,7 +3701,11 @@ mod tests {let WriterState { lock, log, .. } = take_writer(&db);drop(log);remove_data_files(&path).unwrap();- drop(Log::create(&path, DIMS).unwrap().into_file());+ drop(+ Log::create(&path, DIMS, StorageKind::F32)+ .unwrap()+ .into_file(),+ );{let mut half = db.shared.writer_half();recover_after_failed_reset(&db.shared, &mut half, lock, old_generation, 5);@@ -4853,4 +4930,382 @@ mod tests {let with_attrs = db.stats().unwrap().approximate_memory_bytes;assert!(with_attrs > without_attrs + 512);}++ const I8_DIMS: usize = 32;++ fn i8_entries(start: usize, count: usize, seed: u64) -> Vec<(String, Vec<f32>)> {+ (start..start + count)+ .map(|index| {+ (+ format!("key-{index}"),+ seeded_unit_vector(seed + index as u64, I8_DIMS),+ )+ })+ .collect()+ }++ fn open_i8(path: &Path) -> VecDb {+ VecDb::open_with_storage(path, I8_DIMS, StorageKind::I8).unwrap()+ }++ fn stored_vectors(db: &VecDb) -> Vec<(String, StoredVector)> {+ let st = db.shared.state_read();+ st.arena+ .live_slots()+ .map(|slot| {+ (+ st.arena.key_of_slot(slot).unwrap().to_string(),+ st.arena.stored_vector(slot),+ )+ })+ .collect()+ }++ fn assert_same_stored(left: &[(String, StoredVector)], right: &[(String, StoredVector)]) {+ assert_eq!(left.len(), right.len());+ for ((left_key, left_vector), (right_key, right_vector)) in left.iter().zip(right) {+ assert_eq!(left_key, right_key);+ assert_eq!(format!("{left_vector:?}"), format!("{right_vector:?}"));+ }+ }++ fn assert_own_nearest_i8(db: &VecDb, key: &str, vector: &[f32]) {+ let matches = db.search(vector, &limit_params(1)).unwrap();+ assert_eq!(matches[0].key, key);+ assert!(matches[0].distance.abs() < 0.02);+ }++ fn logged_add_records(path: &Path, dims: usize) -> Vec<(String, StoredVector)> {+ let mut log = reopen_log(path, dims, None).unwrap();+ let mut scanner = log.scan().unwrap();+ let mut records = Vec::new();+ while let Some((record, _)) = scanner.next_record().unwrap() {+ if let LogRecord::Add { key, vector, .. } = record {+ records.push((key, vector));+ }+ }+ records+ }++ #[test]+ fn storage_kind_is_verified_on_every_open_path_and_auto_detected_otherwise() {+ let dir = TempDir::new().unwrap();+ let f32_path = dir.path().join("f32");+ let i8_path = dir.path().join("i8");+ let f32_db = VecDb::open(&f32_path, I8_DIMS).unwrap();+ f32_db.add("f", &seeded_unit_vector(1, I8_DIMS)).unwrap();+ assert_eq!(f32_db.stats().unwrap().storage, StorageKind::F32);+ assert!(matches!(+ VecDb::open_with_storage(&f32_path, I8_DIMS, StorageKind::I8),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::I8,+ actual: StorageKind::F32+ })+ ));+ let verified = VecDb::open_with_storage(&f32_path, I8_DIMS, StorageKind::F32).unwrap();+ assert!(Arc::ptr_eq(&verified.shared, &f32_db.shared));+ drop(verified);+ drop(f32_db);+ assert!(matches!(+ VecDb::open_with_storage(&f32_path, I8_DIMS, StorageKind::I8),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::I8,+ actual: StorageKind::F32+ })+ ));+ assert_eq!(+ VecDb::open(&f32_path, I8_DIMS)+ .unwrap()+ .stats()+ .unwrap()+ .storage,+ StorageKind::F32+ );+ let i8_db = open_i8(&i8_path);+ let vector = seeded_unit_vector(2, I8_DIMS);+ i8_db.add("i", &vector).unwrap();+ assert_eq!(i8_db.stats().unwrap().storage, StorageKind::I8);+ let joined = VecDb::open(&i8_path, I8_DIMS).unwrap();+ assert!(Arc::ptr_eq(&joined.shared, &i8_db.shared));+ assert_eq!(joined.stats().unwrap().storage, StorageKind::I8);+ assert!(matches!(+ VecDb::open_with_storage(&i8_path, I8_DIMS, StorageKind::F32),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::F32,+ actual: StorageKind::I8+ })+ ));+ let read_alias = VecDb::open_read_only(&i8_path, I8_DIMS).unwrap();+ assert!(Arc::ptr_eq(&read_alias.shared, &i8_db.shared));+ assert_eq!(read_alias.stats().unwrap().storage, StorageKind::I8);+ i8_db.flush().unwrap();+ drop(read_alias);+ drop(joined);+ drop(i8_db);+ assert_eq!(VecDb::open_cost(&i8_path), OpenCost::Ready);+ let standalone = VecDb::open_read_only(&i8_path, I8_DIMS).unwrap();+ assert_eq!(standalone.stats().unwrap().storage, StorageKind::I8);+ assert!(standalone.contains("i"));+ assert_own_nearest_i8(&standalone, "i", &vector);+ drop(standalone);+ assert!(matches!(+ VecDb::open_with_storage(&i8_path, I8_DIMS, StorageKind::F32),+ Err(VecDbError::StorageMismatch {+ expected: StorageKind::F32,+ actual: StorageKind::I8+ })+ ));+ let detected = VecDb::open(&i8_path, I8_DIMS).unwrap();+ assert_eq!(detected.stats().unwrap().storage, StorageKind::I8);+ assert!(detected.contains("i"));+ assert_own_nearest_i8(&detected, "i", &vector);+ assert!(matches!(+ VecDb::open_with_storage(&dir.path().join("narrow"), 16, StorageKind::I8),+ Err(VecDbError::InvalidDimensions {+ dims: 16,+ storage: StorageKind::I8+ })+ ));+ assert!(VecDb::open_with_storage(&dir.path().join("narrow"), 16, StorageKind::F32).is_ok());+ assert_eq!(+ VecDb::open_read_only(&dir.path().join("absent"), DIMS)+ .unwrap()+ .stats()+ .unwrap()+ .storage,+ StorageKind::F32+ );+ }++ #[test]+ fn i8_add_paths_log_exactly_the_quantized_bytes_the_arena_holds() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ let db = open_i8(&path);+ let single = seeded_unit_vector(10, I8_DIMS);+ db.add_with_attrs("single", &single, &sample_attrs(1))+ .unwrap();+ let entries = i8_entries(0, 5, 20);+ bulk_add(&db, &entries).unwrap();+ let expected: Vec<(String, StoredVector)> =+ std::iter::once(("single".to_string(), single.clone()))+ .chain(entries.iter().cloned())+ .map(|(key, vector)| (key, StoredVector::quantize(&vector)))+ .collect();+ assert_same_stored(&logged_add_records(&path, I8_DIMS), &expected);+ assert_same_stored(&stored_vectors(&db), &expected);+ assert_eq!(db.get_attrs("single").unwrap(), sample_attrs(1));+ let restored = db.get("single").unwrap();+ let StoredVector::I8 { scale, .. } = &expected[0].1 else {+ panic!("expected i8 storage");+ };+ for (original, restored) in single.iter().zip(&restored) {+ assert!((original - restored).abs() <= scale / 2.0 + scale * 1.0e-6);+ }+ let stats = db.stats().unwrap();+ assert_eq!(stats.storage, StorageKind::I8);+ let record_len = 3 + "key-0".len() as u64 + 4 + I8_DIMS as u64 + 1 + 4;+ let single_len = 3 + "single".len() as u64 + 4 + I8_DIMS as u64 + 1 + 4;+ let attr_len: u64 = sample_attrs(1)+ .iter()+ .map(|attr| {+ 2 + attr.name.len() as u64+ + match &attr.value {+ AttrValue::Str(value) => 2 + value.len() as u64,+ AttrValue::Bool(_) => 1,+ AttrValue::I64(_) | AttrValue::F64(_) => 8,+ }+ })+ .sum();+ assert_eq!(+ stats.log_bytes,+ HEADER_LEN as u64 + single_len + attr_len + 5 * record_len+ );+ }++ #[test]+ fn i8_index_survives_compaction_replay_and_snapshot_with_identical_bytes_and_results() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ let copy_path = dir.path().join("copy");+ let db = open_i8(&path);+ bulk_add(&db, &i8_entries(0, 300, 500)).unwrap();+ for index in 0..20u64 {+ db.add(+ &format!("key-{}", index * 3),+ &seeded_unit_vector(9000 + index, I8_DIMS),+ )+ .unwrap();+ }+ let query = seeded_unit_vector(31337, I8_DIMS);+ let approx = limit_params(10);+ let exact = SearchParams {+ limit: Some(80),+ exact: true,+ ..SearchParams::default()+ };+ let stored_keys: Vec<String> = ["key-1", "key-50", "key-100", "key-299"]+ .iter()+ .map(|key| key.to_string())+ .collect();+ let exact_before = db.search(&query, &exact).unwrap();+ assert_eq!(exact_before.len(), 80);+ let stored_before = stored_vectors(&db);+ let removals: Vec<String> = (0..40).map(|index| format!("key-{}", index * 7)).collect();+ let generation_before = generation_of(&path);+ assert_eq!(db.bulk_remove(&removals).unwrap(), 40);+ assert_ne!(generation_of(&path), generation_before);+ let stats = db.stats().unwrap();+ assert_eq!(stats.live_count, 260);+ assert_eq!(stats.dead_count, 0);+ assert_eq!(stats.storage, StorageKind::I8);+ let survivors: Vec<(String, StoredVector)> = stored_before+ .into_iter()+ .filter(|(key, _)| !removals.contains(key))+ .collect();+ assert_same_stored(&stored_vectors(&db), &survivors);+ assert_same_stored(&logged_add_records(&path, I8_DIMS), &survivors);+ let expected_exact: Vec<Match> = exact_before+ .into_iter()+ .filter(|hit| !removals.contains(&hit.key))+ .take(10)+ .collect();+ let exact_ten = SearchParams {+ limit: Some(10),+ exact: true,+ ..SearchParams::default()+ };+ assert_eq!(db.search(&query, &exact_ten).unwrap(), expected_exact);+ let threshold = SearchParams {+ max_distance: Some(expected_exact[9].distance),+ ..SearchParams::default()+ };+ let approx_after = db.search(&query, &approx).unwrap();+ let threshold_after = db.search(&query, &threshold).unwrap();+ let stored_after = db+ .bulk_search_stored(&stored_keys, 10, None, false, false)+ .unwrap();+ assert_eq!(approx_after.len(), 10);+ assert!(!threshold_after.is_empty());+ assert_eq!(stored_after.len(), 4);+ db.flush().unwrap();+ fs::copy(&path, ©_path).unwrap();+ drop(db);+ let verify = |db: &VecDb| {+ assert_eq!(db.stats().unwrap().storage, StorageKind::I8);+ assert_same_stored(&stored_vectors(db), &survivors);+ assert_eq!(db.search(&query, &exact_ten).unwrap(), expected_exact);+ assert_eq!(db.search(&query, &approx).unwrap(), approx_after);+ assert_eq!(db.search(&query, &threshold).unwrap(), threshold_after);+ assert_eq!(+ db.bulk_search_stored(&stored_keys, 10, None, false, false)+ .unwrap(),+ stored_after+ );+ };+ let read_only = VecDb::open_read_only(&path, I8_DIMS).unwrap();+ verify(&read_only);+ drop(read_only);+ let with_snapshot = VecDb::open(&path, I8_DIMS).unwrap();+ verify(&with_snapshot);+ drop(with_snapshot);+ fs::remove_file(snapshot_path(&path)).unwrap();+ let rebuilt = VecDb::open(&path, I8_DIMS).unwrap();+ verify(&rebuilt);+ let from_copy = open_i8(©_path);+ verify(&from_copy);+ let rebuilt_state = rebuilt.shared.state_read();+ let copy_state = from_copy.shared.state_read();+ test_support::assert_identical_graphs(+ rebuilt_state.graph.as_ref().unwrap(),+ copy_state.graph.as_ref().unwrap(),+ );+ }++ #[test]+ fn i8_interrupted_sessions_build_the_same_graph_as_one_uninterrupted_session() {+ let dir = TempDir::new().unwrap();+ let split_path = dir.path().join("split");+ let whole_path = dir.path().join("whole");+ let tail_new = seeded_unit_vector(4242, I8_DIMS);+ let older_upsert = {+ let mut values = tail_new.clone();+ values[0] += 0.05;+ let norm = values.iter().map(|value| value * value).sum::<f32>().sqrt();+ for value in &mut values {+ *value /= norm;+ }+ values+ };+ {+ let db = open_i8(&split_path);+ bulk_add(&db, &i8_entries(0, 40, 500)).unwrap();+ db.flush().unwrap();+ }+ {+ let db = VecDb::open(&split_path, I8_DIMS).unwrap();+ assert_eq!(db.stats().unwrap().storage, StorageKind::I8);+ db.add("tail-new", &tail_new).unwrap();+ db.add("key-3", &older_upsert).unwrap();+ }+ let split = VecDb::open(&split_path, I8_DIMS).unwrap();+ let whole = open_i8(&whole_path);+ bulk_add(&whole, &i8_entries(0, 40, 500)).unwrap();+ whole.add("tail-new", &tail_new).unwrap();+ whole.add("key-3", &older_upsert).unwrap();+ assert_same_stored(&stored_vectors(&split), &stored_vectors(&whole));+ let split_state = split.shared.state_read();+ let whole_state = whole.shared.state_read();+ let split_graph = split_state.graph.as_ref().unwrap();+ let whole_graph = whole_state.graph.as_ref().unwrap();+ assert_eq!(split_graph.insert_ordinal(), 42);+ assert_eq!(whole_graph.insert_ordinal(), 42);+ assert!(+ split_graph+ .slots()+ .any(|slot| split_graph.level_of(slot).unwrap() > 0)+ );+ test_support::assert_identical_graphs(split_graph, whole_graph);+ }++ #[test]+ fn i8_stats_report_the_storage_and_a_quarter_of_the_vector_memory() {+ let dir = TempDir::new().unwrap();+ let dims = 512;+ let f32_db = VecDb::open(&dir.path().join("f32"), dims).unwrap();+ let i8_db =+ VecDb::open_with_storage(&dir.path().join("i8"), dims, StorageKind::I8).unwrap();+ let entries: Vec<(String, Vec<f32>)> = (0..200u64)+ .map(|index| (format!("key-{index}"), seeded_unit_vector(index, dims)))+ .collect();+ bulk_add(&f32_db, &entries).unwrap();+ bulk_add(&i8_db, &entries).unwrap();+ let f32_stats = f32_db.stats().unwrap();+ let i8_stats = i8_db.stats().unwrap();+ assert_eq!(f32_stats.storage, StorageKind::F32);+ assert_eq!(i8_stats.storage, StorageKind::I8);+ assert_eq!(i8_stats.live_count, 200);+ assert_eq!(i8_stats.dims, dims);+ assert!(i8_stats.approximate_memory_bytes < f32_stats.approximate_memory_bytes / 3);+ assert!(i8_stats.log_bytes < f32_stats.log_bytes / 3);+ let key = "key-7".to_string();+ let restored = i8_db.get(&key).unwrap();+ let original = &entries[7].1;+ let max_abs = original+ .iter()+ .fold(0.0f32, |acc, value| acc.max(value.abs()));+ for (original, restored) in original.iter().zip(&restored) {+ assert!((original - restored).abs() <= max_abs / 254.0 + 1.0e-6);+ }+ assert_eq!(f32_db.get(&key).unwrap(), *original);+ assert_own_nearest_i8(&i8_db, &key, original);+ i8_db.reset().unwrap();+ assert_eq!(i8_db.stats().unwrap().storage, StorageKind::I8);+ i8_db.add("again", original).unwrap();+ assert_own_nearest_i8(&i8_db, "again", original);+ assert_same_stored(+ &logged_add_records(&dir.path().join("i8"), dims),+ &[("again".to_string(), StoredVector::quantize(original))],+ );+ }}