π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
vecdb: harden durability and consolidate internals after review
laurenspriemb17160b02382
diff --git a/rust/crates/ml/CONTEXT.md b/rust/crates/ml/CONTEXT.mdindex 999ff6ddab..262d71f3de 100644--- a/rust/crates/ml/CONTEXT.md+++ b/rust/crates/ml/CONTEXT.md@@ -11,7 +11,7 @@ Glossary of terms for the ML crate's domain. Definitions describe meaning, not i- **Tombstone** β A logged record marking a key as removed. Tombstoned entries are dead but still occupy log and graph space until compaction.- **Compaction** β Rewriting the vector log to contain only live entries and rebuilding the graph, triggered when dead entries exceed a threshold.- **Writer** β The single instance per index file allowed to mutate it, enforced by an OS lock. All other opens are read-only and see a point-in-time view.-- **Flush** β Explicitly persisting the current graph snapshot so the next open needs no replay.+- **Flush** β Explicitly persisting the current graph snapshot so the next open replays no records into the graph; every open still scans the log to rebuild the arena.- **Exact search** β Brute-force scan over all live embeddings; results are ground truth.- **Approximate search** β Index-backed (HNSW) search; may miss neighbours in exchange for speed.- **Distance** β 1 β inner product of L2-normalized embeddings, in [0, 2]; lower is closer. The only metric vecdb speaks.diff --git a/rust/crates/ml/docs/adr/0001-vecdb-durable-log-plus-derived-graph.md b/rust/crates/ml/docs/adr/0001-vecdb-durable-log-plus-derived-graph.mdindex 258b03ac2c..8eebdce3f4 100644--- a/rust/crates/ml/docs/adr/0001-vecdb-durable-log-plus-derived-graph.md+++ b/rust/crates/ml/docs/adr/0001-vecdb-durable-log-plus-derived-graph.md@@ -15,7 +15,8 @@ We replaced usearch (C++ under the hood, broken on the napi desktop toolchain, r- Deletes are tombstones; dead entries are compacted away (log rewrite + graph rebuild) past a ~10% dead ratio with a small absolute floor.- Exactly one writer instance per index file, enforced by an OS advisory lock; read-only opens hold no lock and no fds, and see a point-in-time view β which is what makes rename-based compaction safe on Windows.- Single metric (inner product on L2-normalized vectors, distance = 1 β dot) and single scalar (f32) are hardcoded; the file header carries scalar/metric tags and the distance kernel sits behind one internal seam so smaller scalars (f16/i8) can be added without a format break.-- Keys are strings (non-empty UTF-8, β€ 256 bytes), not integers: file/face/cluster IDs are used directly, which retires the four AUTOINCREMENT key-mapping tables the app kept in sqlite solely for usearch's u64 keys. Internally keys are interned to u32 slots; the graph, arena, and log replay speak slots.+- Keys are strings (non-empty UTF-8, β€ 256 bytes), not integers: file/face/cluster IDs are used directly, which clears the way to retire the four AUTOINCREMENT key-mapping tables the app kept in sqlite solely for usearch's u64 keys once vecdb replaces usearch. Internally keys are interned to u32 slots; the graph, arena, and log replay speak slots.- Vectors live on disk as raw little-endian f32 payloads in the framed log records, and in memory in a chunked, 32-byte-aligned arena (chunks of SIMD lanes; free-list slot reuse; growth never reallocates existing chunks). Memory-mapping the log was rejected: it breaks wasm compatibility, fights rename-based compaction on Windows, and framed records give no alignment guarantee.- vecdb is layered as an IO-free core (graph, arena, SIMD kernels β wasm32-compatible) beneath a native-only storage layer (fs, fsync, locking). The writer lock is hand-rolled (`flock` on unix, `LockFileEx` on Windows) rather than a crate: with `wide`, `crc32fast`, `libc`, and `windows-sys` already in the dependency tree, vecdb adds zero new Cargo.lock entries.- usearch stays in the tree, feature-gated, while vecdb runs as a parallel engine for internal users; removal is a separate later decision.+- Derived-state failures degrade instead of failing writes: snapshot and compaction errors are logged as warnings and never fail an acknowledged write, open never fails for snapshot reasons, and only an explicit `flush()` surfaces snapshot errors to the caller.diff --git a/rust/crates/ml/examples/vecdb_bench.rs b/rust/crates/ml/examples/vecdb_bench.rsindex 1bf70d6bf0..452a0e0574 100644--- a/rust/crates/ml/examples/vecdb_bench.rs+++ b/rust/crates/ml/examples/vecdb_bench.rs@@ -241,9 +241,74 @@ fn generate_data(scale: usize, dims: usize, clusters: u64) -> BenchData {}}+struct IngestTimings {+ single_count: usize,+ single_total: Duration,+ bulk_count: usize,+ bulk_total: Duration,+ snapshot_write: Duration,+}++struct SearchTimings {+ approx_total: Duration,+ exact_total: Duration,+ recall: f64,+ threshold: f32,+ threshold_total: Duration,+ threshold_avg_hits: f64,+ filtered_total: Duration,+}++struct ReopenTimings {+ open_with_snapshot: Duration,+ open_full_rebuild: Duration,+}++struct CompactionTimings {+ removed: usize,+ remove_and_compact: Duration,+ compaction_fired: bool,+}+fn run_vecdb(data: &BenchData, dims: usize, dir: &Path, scale: usize) -> VecdbReport {let path = dir.join("bench.vecdb");let mut db = VecDb::open(&path, dims).expect("open vecdb");+ let ingest = ingest_phase(&mut db, data, scale);+ let searches = search_phase(&db, data, scale);+ let stats = db.stats();+ let snapshot_file = PathBuf::from(format!("{}.graph", path.display()));+ let snapshot_bytes = std::fs::metadata(&snapshot_file)+ .map(|meta| meta.len())+ .unwrap_or(0);+ drop(db);+ let (reopens, mut db) = reopen_phase(&path, dims, &snapshot_file, scale);+ let compaction = compaction_phase(&mut db, data, scale);+ db.delete().expect("vecdb delete");+ VecdbReport {+ single_count: ingest.single_count,+ single_total: ingest.single_total,+ bulk_count: ingest.bulk_count,+ bulk_total: ingest.bulk_total,+ snapshot_write: ingest.snapshot_write,+ approx_total: searches.approx_total,+ exact_total: searches.exact_total,+ recall: searches.recall,+ threshold: searches.threshold,+ threshold_total: searches.threshold_total,+ threshold_avg_hits: searches.threshold_avg_hits,+ filtered_total: searches.filtered_total,+ open_with_snapshot: reopens.open_with_snapshot,+ open_full_rebuild: reopens.open_full_rebuild,+ removed: compaction.removed,+ remove_and_compact: compaction.remove_and_compact,+ compaction_fired: compaction.compaction_fired,+ log_bytes: stats.log_bytes,+ snapshot_bytes,+ memory_bytes: stats.approximate_memory_bytes,+ }+}++fn ingest_phase(db: &mut VecDb, data: &BenchData, scale: usize) -> IngestTimings {let single_count = SINGLE_ADD_COUNT.min(data.entries.len());eprintln!("[scale {scale}] vecdb single adds");let started = Instant::now();@@ -261,33 +326,38 @@ fn run_vecdb(data: &BenchData, dims: usize, dir: &Path, scale: usize) -> VecdbRedb.add("bench-probe", &data.probe).expect("vecdb probe add");let started = Instant::now();db.flush().expect("vecdb flush");- let snapshot_write = started.elapsed();+ IngestTimings {+ single_count,+ single_total,+ bulk_count: rest.len(),+ bulk_total,+ snapshot_write: started.elapsed(),+ }+}+fn search_phase(db: &VecDb, data: &BenchData, scale: usize) -> SearchTimings {eprintln!("[scale {scale}] vecdb searches");let approx_params = limit_params(SEARCH_K, false);let exact_params = limit_params(SEARCH_K, true);- warm(&db, &data.queries, &approx_params);- let (approx_total, approx_results) = timed_searches(&db, &data.queries, &approx_params);- warm(&db, &data.queries, &exact_params);- let (exact_total, exact_results) = timed_searches(&db, &data.queries, &exact_params);+ warm(db, &data.queries, &approx_params);+ let (approx_total, approx_results) = timed_searches(db, &data.queries, &approx_params);+ 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 threshold = one_percent_threshold(&db, data);+ let threshold = one_percent_threshold(db, data);let threshold_params = SearchParams {limit: None,max_distance: Some(threshold),exact: false,allowed_keys: None,};- warm(&db, &data.queries, &threshold_params);- let (threshold_total, threshold_results) =- timed_searches(&db, &data.queries, &threshold_params);+ warm(db, &data.queries, &threshold_params);+ let (threshold_total, threshold_results) = timed_searches(db, &data.queries, &threshold_params);let threshold_avg_hits = threshold_results.iter().map(|found| found.len()).sum::<usize>() as f64/ threshold_results.len().max(1) as f64;-let filtered_params = SearchParams {limit: Some(SEARCH_K),max_distance: None,@@ -299,27 +369,45 @@ fn run_vecdb(data: &BenchData, dims: usize, dir: &Path, scale: usize) -> VecdbRe.collect(),),};- warm(&db, &data.queries, &filtered_params);- let (filtered_total, _) = timed_searches(&db, &data.queries, &filtered_params);-- let stats = db.stats();- let snapshot_file = PathBuf::from(format!("{}.graph", path.display()));- let snapshot_bytes = std::fs::metadata(&snapshot_file)- .map(|meta| meta.len())- .unwrap_or(0);+ warm(db, &data.queries, &filtered_params);+ let (filtered_total, _) = timed_searches(db, &data.queries, &filtered_params);+ SearchTimings {+ approx_total,+ exact_total,+ recall,+ threshold,+ threshold_total,+ threshold_avg_hits,+ filtered_total,+ }+}+fn reopen_phase(+ path: &Path,+ dims: usize,+ snapshot_file: &Path,+ scale: usize,+) -> (ReopenTimings, VecDb) {eprintln!("[scale {scale}] vecdb cold open with snapshot");- drop(db);let started = Instant::now();- let reopened = VecDb::open(&path, dims).expect("vecdb reopen with snapshot");+ let reopened = VecDb::open(path, dims).expect("vecdb reopen with snapshot");let open_with_snapshot = started.elapsed();drop(reopened);- std::fs::remove_file(&snapshot_file).expect("remove snapshot");+ std::fs::remove_file(snapshot_file).expect("remove snapshot");eprintln!("[scale {scale}] vecdb cold open without snapshot (full rebuild)");let started = Instant::now();- let mut db = VecDb::open(&path, dims).expect("vecdb reopen without snapshot");+ let db = VecDb::open(path, dims).expect("vecdb reopen without snapshot");let open_full_rebuild = started.elapsed();+ (+ ReopenTimings {+ open_with_snapshot,+ open_full_rebuild,+ },+ db,+ )+}+fn compaction_phase(db: &mut VecDb, data: &BenchData, scale: usize) -> CompactionTimings {eprintln!("[scale {scale}] vecdb remove {REMOVAL_PERCENT}% + compact");let removed = data.entries.len() * REMOVAL_PERCENT / 100;let removals: Vec<String> = (0..removed).map(|index| format!("vec-{index}")).collect();@@ -328,30 +416,10 @@ fn run_vecdb(data: &BenchData, dims: usize, dir: &Path, scale: usize) -> VecdbRedb.bulk_remove(&removals).expect("vecdb bulk remove");let remove_and_compact = started.elapsed();let stats_after = db.stats();- let compaction_fired = stats_after.log_bytes < log_before && stats_after.dead_count == 0;- db.delete().expect("vecdb delete");-- VecdbReport {- single_count,- single_total,- bulk_count: rest.len(),- bulk_total,- snapshot_write,- approx_total,- exact_total,- recall,- threshold,- threshold_total,- threshold_avg_hits,- filtered_total,- open_with_snapshot,- open_full_rebuild,+ CompactionTimings {removed,remove_and_compact,- compaction_fired,- log_bytes: stats.log_bytes,- snapshot_bytes,- memory_bytes: stats.approximate_memory_bytes,+ compaction_fired: stats_after.log_bytes < log_before && stats_after.dead_count == 0,}}diff --git a/rust/crates/ml/src/vecdb/arena.rs b/rust/crates/ml/src/vecdb/arena.rsindex 221b368983..8c0d337c95 100644--- a/rust/crates/ml/src/vecdb/arena.rs+++ b/rust/crates/ml/src/vecdb/arena.rs@@ -17,16 +17,6 @@ pub(crate) enum UpsertOutcome {ReplacedInPlace(u32),}-impl UpsertOutcome {- pub(crate) fn slot(self) -> u32 {- match self {- UpsertOutcome::NewSlot(slot)- | UpsertOutcome::RecycledSlot(slot)- | UpsertOutcome::ReplacedInPlace(slot) => slot,- }- }-}-pub(crate) fn validate_key(key: &str) -> Result<(), VecDbError> {if key.is_empty() {return Err(VecDbError::InvalidKey("key is empty".to_string()));@@ -205,16 +195,9 @@ impl VectorArena {#[cfg(test)]mod tests {+ use super::super::kernel::splitmix64;use super::*;- fn splitmix64(state: &mut u64) -> u64 {- *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);- let mut z = *state;- z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);- z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);- z ^ (z >> 31)- }-fn seeded_vector(seed: u64, dims: usize) -> Vec<f32> {let mut state = seed;(0..dims)diff --git a/rust/crates/ml/src/vecdb/graph.rs b/rust/crates/ml/src/vecdb/graph.rsindex aad2c5aab1..da5b461357 100644--- a/rust/crates/ml/src/vecdb/graph.rs+++ b/rust/crates/ml/src/vecdb/graph.rs@@ -4,6 +4,7 @@ use std::collections::{BinaryHeap, HashSet};use wide::f32x8;use super::arena::VectorArena;+use super::kernel::splitmix64;use super::{Match, SearchParams, VecDbError};const M: usize = 16;@@ -17,14 +18,6 @@ const SMALL_FILTER_LIMIT_FACTOR: usize = 4;const THRESHOLD_STEP_COUNTS: [usize; 5] = [200, 500, 2000, 5000, 10000];const LEVEL_SEED: u64 = 0x9E37_79B9_7F4A_7C15;-fn splitmix64(state: &mut u64) -> u64 {- *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);- let mut z = *state;- z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);- z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);- z ^ (z >> 31)-}-fn neighbor_cap(level: usize) -> usize {if level == 0 {LEVEL_ZERO_NEIGHBOR_CAP@@ -105,12 +98,6 @@ pub(crate) struct Graph {level_state: u64,}-impl Default for Graph {- fn default() -> Self {- Self::new()- }-}-impl Graph {pub(crate) fn new() -> Self {Self {@@ -472,7 +459,7 @@ impl QueryContext<'_> {}pub(crate) fn search(- graph: Option<&Graph>,+ graph: &Graph,arena: &VectorArena,query: &[f32x8],params: &SearchParams,@@ -497,9 +484,9 @@ pub(crate) fn search({return brute_force(arena, query, params, allowed_slots);}- let Some(graph) = graph.filter(|graph| graph.entry_point.is_some()) else {+ if graph.entry_point.is_none() {return brute_force(arena, query, params, allowed_slots);- };+ }let context = QueryContext {graph,arena,@@ -523,7 +510,9 @@ fn query_is_finite(query: &[f32x8]) -> bool {fn small_filter_cap(limit: Option<usize>) -> usize {limit.map_or(SMALL_FILTER_FLOOR, |limit| {- (SMALL_FILTER_LIMIT_FACTOR * limit).max(SMALL_FILTER_FLOOR)+ limit+ .saturating_mul(SMALL_FILTER_LIMIT_FACTOR)+ .max(SMALL_FILTER_FLOOR)})}@@ -660,17 +649,17 @@ fn to_matches(#[cfg(test)]mod tests {use std::f32::consts::FRAC_1_SQRT_2;-- use once_cell::sync::Lazy;+ use std::sync::LazyLock;use super::super::arena::UpsertOutcome;+ use super::super::test_support::{assert_identical_graphs, stale_downward_edge_exists};use super::*;const FIXTURE_DIMS: usize = 16;const FIXTURE_COUNT: usize = 1500;- static FIXTURE: Lazy<(VectorArena, Graph)> =- Lazy::new(|| build_fixture(FIXTURE_COUNT, FIXTURE_DIMS, 0x00F1_0000));+ static FIXTURE: LazyLock<(VectorArena, Graph)> =+ LazyLock::new(|| build_fixture(FIXTURE_COUNT, FIXTURE_DIMS, 0x00F1_0000));fn normalized(mut values: Vec<f32>) -> Vec<f32> {let norm = values.iter().map(|value| value * value).sum::<f32>().sqrt();@@ -850,18 +839,6 @@ mod tests {.collect()}- fn stale_downward_edge_exists(graph: &Graph) -> bool {- graph.slots().any(|slot| {- let level = graph.level_of(slot).unwrap();- (0..=level).any(|layer| {- graph- .neighbors_of(slot, layer)- .iter()- .any(|&neighbor| graph.level_of(neighbor).unwrap() < layer)- })- })- }-fn assert_graph_invariants(graph: &Graph) {for slot in graph.slots() {let level = graph.level_of(slot).unwrap();@@ -876,24 +853,6 @@ mod tests {}}- fn assert_identical_graphs(first: &Graph, second: &Graph) {- assert_eq!(first.entry_point(), second.entry_point());- assert_eq!(- first.slots().collect::<Vec<_>>(),- second.slots().collect::<Vec<_>>()- );- for slot in first.slots() {- assert_eq!(first.level_of(slot), second.level_of(slot));- let level = first.level_of(slot).unwrap();- for layer in 0..=level {- assert_eq!(- first.neighbors_of(slot, layer),- second.neighbors_of(slot, layer)- );- }- }- }-fn axis_vector(dims: usize, axis: usize) -> Vec<f32> {let mut values = vec![0.0; dims];values[axis] = 1.0;@@ -944,13 +903,7 @@ mod tests {.iter().map(|&(_, slot)| arena.key_of_slot(slot).unwrap()).collect();- let found = search(- Some(graph),- arena,- &query,- ¶ms(Some(10), None, false),- None,- );+ let found = search(graph, arena, &query, ¶ms(Some(10), None, false), None);assert_eq!(found.len(), 10);hits += found.iter()@@ -964,28 +917,16 @@ mod tests {fn exact_search_matches_handcrafted_ground_truth() {let (arena, graph) = handcrafted();let query = arena.pack_query(&axis_vector(8, 0)).unwrap();- let all = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(10), None, true),- None,- );+ let all = search(&graph, &arena, &query, ¶ms(Some(10), None, true), None);assert_eq!(keys(&all), ["a", "b", "t1", "t2", "c", "d"]);let expected = [0.0, 1.0 - FRAC_1_SQRT_2, 0.5, 0.5, 1.0, 2.0];for (found, expected) in all.iter().zip(expected) {assert_eq!(found.distance, expected);}- let inclusive = search(- Some(&graph),- &arena,- &query,- ¶ms(None, Some(0.5), true),- None,- );+ let inclusive = search(&graph, &arena, &query, ¶ms(None, Some(0.5), true), None);assert_eq!(keys(&inclusive), ["a", "b", "t1", "t2"]);let below_ties = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(0.499), true),@@ -993,7 +934,7 @@ mod tests {);assert_eq!(keys(&below_ties), ["a", "b"]);let tie_cut = search(- Some(&graph),+ &graph,&arena,&query,¶ms(Some(3), Some(0.5), true),@@ -1001,7 +942,7 @@ mod tests {);assert_eq!(keys(&tie_cut), ["a", "b", "t1"]);let closest = search(- Some(&graph),+ &graph,&arena,&query,¶ms(Some(1), Some(2.0), true),@@ -1014,16 +955,10 @@ mod tests {fn tiny_index_approx_equals_exact() {let (arena, graph) = handcrafted();let query = arena.pack_query(&axis_vector(8, 0)).unwrap();- let all = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(10), None, false),- None,- );+ let all = search(&graph, &arena, &query, ¶ms(Some(10), None, false), None);assert_eq!(keys(&all), ["a", "b", "t1", "t2", "c", "d"]);let inclusive = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(0.5), false),@@ -1031,7 +966,7 @@ mod tests {);assert_eq!(keys(&inclusive), ["a", "b", "t1", "t2"]);let tie_cut = search(- Some(&graph),+ &graph,&arena,&query,¶ms(Some(3), Some(0.5), false),@@ -1039,7 +974,7 @@ mod tests {);assert_eq!(keys(&tie_cut), ["a", "b", "t1"]);let closest = search(- Some(&graph),+ &graph,&arena,&query,¶ms(Some(1), Some(2.0), false),@@ -1056,22 +991,14 @@ mod tests {for exact in [false, true] {for (limit, max_distance) in [(Some(5), None), (None, Some(1.0)), (Some(1), Some(0.5))]{- let with_graph = search(- Some(&graph),- &arena,- &query,- ¶ms(limit, max_distance, exact),- None,- );- assert!(with_graph.is_empty());- let without_graph = search(- None,+ let found = search(+ &graph,&arena,&query,¶ms(limit, max_distance, exact),None,);- assert!(without_graph.is_empty());+ assert!(found.is_empty());}}assert_eq!(graph.entry_point(), None);@@ -1085,17 +1012,11 @@ mod tests {let graph = Graph::rebuild(&arena);let query = arena.pack_query(&axis_vector(8, 0)).unwrap();for exact in [false, true] {- let by_limit = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(10), None, exact),- None,- );+ let by_limit = search(&graph, &arena, &query, ¶ms(Some(10), None, exact), None);assert_eq!(keys(&by_limit), ["only"]);assert_eq!(by_limit[0].distance, 0.0);let by_threshold = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(0.0), exact),@@ -1103,7 +1024,13 @@ mod tests {);assert_eq!(keys(&by_threshold), ["only"]);}- let without_graph = search(None, &arena, &query, ¶ms(Some(3), None, false), None);+ let without_graph = search(+ &Graph::new(),+ &arena,+ &query,+ ¶ms(Some(3), None, false),+ None,+ );assert_eq!(keys(&without_graph), ["only"]);}@@ -1116,16 +1043,10 @@ mod tests {}let query = arena.pack_query(&axis_vector(8, 0)).unwrap();for exact in [false, true] {- let by_limit = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(3), None, exact),- None,- );+ let by_limit = search(&graph, &arena, &query, ¶ms(Some(3), None, exact), None);assert!(by_limit.is_empty());let by_threshold = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(2.5), exact),@@ -1154,13 +1075,7 @@ mod tests {arena.remove(key).unwrap();}for exact in [false, true] {- let found = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(10), None, exact),- None,- );+ let found = search(&graph, &arena, &query, ¶ms(Some(10), None, exact), None);assert_eq!(found.len(), 10);for hit in &found {assert!(!removed.contains(&hit.key));@@ -1171,7 +1086,7 @@ mod tests {}let nearest_distance = reference[0].0;let within = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(nearest_distance), false),@@ -1182,7 +1097,7 @@ mod tests {}let allowed: HashSet<u32> = reference[..12].iter().map(|&(_, slot)| slot).collect();let filtered = search(- Some(&graph),+ &graph,&arena,&query,¶ms(Some(12), None, false),@@ -1202,7 +1117,7 @@ mod tests {let new_query = arena.pack_query(&new_vector).unwrap();for exact in [false, true] {let top = search(- Some(&graph),+ &graph,&arena,&new_query,¶ms(Some(1), None, exact),@@ -1215,7 +1130,7 @@ mod tests {let moved_distance = arena.distance_to_query(&old_query, 7);assert!(moved_distance > 0.3);let near_old = search(- Some(&graph),+ &graph,&arena,&old_query,¶ms(None, Some(0.3), false),@@ -1225,7 +1140,7 @@ mod tests {assert_ne!(hit.key, "key-7");}let everything = search(- Some(&graph),+ &graph,&arena,&new_query,¶ms(None, Some(2.5), false),@@ -1245,16 +1160,10 @@ mod tests {graph.reinsert(entry_slot, &arena);assert!(graph.entry_point().is_some());let query = arena.pack_query(&new_vector).unwrap();- let top = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(1), None, false),- None,- );+ let top = search(&graph, &arena, &query, ¶ms(Some(1), None, false), None);assert_eq!(keys(&top), [entry_key.as_str()]);let everything = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(2.5), false),@@ -1273,17 +1182,11 @@ mod tests {graph.reinsert(3, &arena);let query = arena.pack_query(&new_vector).unwrap();for exact in [false, true] {- let top = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(1), None, exact),- None,- );+ let top = search(&graph, &arena, &query, ¶ms(Some(1), None, exact), None);assert_eq!(keys(&top), ["fresh"]);}let everything = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(2.5), false),@@ -1304,13 +1207,7 @@ mod tests {graph.reinsert(0, &arena);assert_eq!(graph.entry_point(), Some(0));let query = arena.pack_query(&axis_vector(8, 3)).unwrap();- let found = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(5), None, false),- None,- );+ let found = search(&graph, &arena, &query, ¶ms(Some(5), None, false), None);assert_eq!(keys(&found), ["solo"]);assert_eq!(found[0].distance, 0.0);}@@ -1327,7 +1224,7 @@ mod tests {assert_eq!(allowed.len(), 10);let reference = reference_ranking(arena, &query, Some(&allowed));let found = search(- Some(graph),+ graph,arena,&query,¶ms(Some(3), None, false),@@ -1341,6 +1238,31 @@ mod tests {}}+ #[test]+ fn usize_max_limit_does_not_overflow_with_or_without_filter() {+ let (arena, graph) = (&FIXTURE.0, &FIXTURE.1);+ let query = arena+ .pack_query(&seeded_unit_vector(0x00DD_0006, FIXTURE_DIMS))+ .unwrap();+ let allowed: HashSet<u32> = (0..3).collect();+ let filtered = search(+ graph,+ arena,+ &query,+ ¶ms(Some(usize::MAX), None, false),+ Some(&allowed),+ );+ assert_eq!(filtered.len(), 3);+ let unfiltered = search(+ graph,+ arena,+ &query,+ ¶ms(Some(usize::MAX), None, false),+ None,+ );+ assert_eq!(unfiltered.len(), FIXTURE_COUNT);+ }+#[test]fn large_filter_traverses_the_graph_and_respects_the_filter() {let (arena, graph) = (&FIXTURE.0, &FIXTURE.1);@@ -1351,7 +1273,7 @@ mod tests {assert!(allowed.len() > small_filter_cap(Some(10)));let reference = reference_ranking(arena, &query, Some(&allowed));let found = search(- Some(graph),+ graph,arena,&query,¶ms(Some(10), None, false),@@ -1372,7 +1294,7 @@ mod tests {.count();assert!(hits >= 8, "filtered recall@10 was {hits}/10");let within = search(- Some(graph),+ graph,arena,&query,¶ms(None, Some(0.9), false),@@ -1404,7 +1326,7 @@ mod tests {continue;}let found = search(- Some(graph),+ graph,arena,&query,¶ms(limit, max_distance, exact),@@ -1456,13 +1378,7 @@ mod tests {let query = arena.pack_query(&seeded_unit_vector(0x00DD_0004, FIXTURE_DIMS)).unwrap();- let everything = search(- Some(graph),- arena,- &query,- ¶ms(None, Some(2.5), false),- None,- );+ let everything = search(graph, arena, &query, ¶ms(None, Some(2.5), false), None);assert_eq!(everything.len(), FIXTURE_COUNT);assert_sorted(&everything);}@@ -1476,7 +1392,7 @@ mod tests {let reference = reference_ranking(arena, &query, None);let threshold = reference[4].0;let found = search(- Some(graph),+ graph,arena,&query,¶ms(None, Some(threshold), false),@@ -1509,15 +1425,9 @@ mod tests {let query = arena.pack_query(&seeded_unit_vector(0x8111_0000, 16)).unwrap();- let from_original = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(10), None, false),- None,- );+ let from_original = search(&graph, &arena, &query, ¶ms(Some(10), None, false), None);let from_rebuilt = search(- Some(&rebuilt),+ &rebuilt,&arena,&query,¶ms(Some(10), None, false),@@ -1606,13 +1516,7 @@ mod tests {.unwrap();arena.upsert("c", &axis_vector(8, 1)).unwrap();let query = arena.pack_query(&axis_vector(8, 1)).unwrap();- let found = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(3), None, false),- None,- );+ let found = search(&graph, &arena, &query, ¶ms(Some(3), None, false), None);assert_eq!(keys(&found), ["c", "b", "a"]);}@@ -1637,19 +1541,13 @@ mod tests {.pack_query(&seeded_unit_vector(0x00E1_0000, dims)).unwrap();let reference = reference_ranking(&arena, &query, None);- let top = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(10), None, false),- None,- );+ let top = search(&graph, &arena, &query, ¶ms(Some(10), None, false), None);for (hit, &(distance, slot)) in top.iter().zip(&reference) {assert_eq!(hit.key, arena.key_of_slot(slot).unwrap());assert_eq!(hit.distance, distance);}let everything = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(2.5), false),@@ -1667,7 +1565,7 @@ mod tests {.pack_query(&seeded_unit_vector(0x00E2_0000, dims)).unwrap();let found = search(- Some(&graph),+ &graph,&arena,&fresh_query,¶ms(Some(1), None, false),@@ -1675,7 +1573,7 @@ mod tests {);assert_eq!(keys(&found), ["fresh"]);let all = search(- Some(&graph),+ &graph,&arena,&fresh_query,¶ms(None, Some(2.5), false),@@ -1708,13 +1606,7 @@ mod tests {arena.upsert("b", &axis_vector(8, 1)).unwrap();arena.upsert("c", &axis_vector(8, 2)).unwrap();let query = arena.pack_query(&axis_vector(8, 2)).unwrap();- let found = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(3), None, false),- None,- );+ let found = search(&graph, &arena, &query, ¶ms(Some(3), None, false), None);assert_eq!(found.len(), 3);assert_eq!(found[0].key, "c");}@@ -1739,16 +1631,10 @@ mod tests {.unwrap();assert_identical_graphs(&reloaded, &graph);let query = arena.pack_query(&vector).unwrap();- let top = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(1), None, false),- None,- );+ let top = search(&graph, &arena, &query, ¶ms(Some(1), None, false), None);assert_eq!(keys(&top), [key.as_str()]);let everything = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(2.5), false),@@ -1764,15 +1650,9 @@ mod tests {let query = arena.pack_query(&seeded_unit_vector(0xB200_0000, 16)).unwrap();- let from_churned = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(10), None, false),- None,- );+ let from_churned = search(&graph, &arena, &query, ¶ms(Some(10), None, false), None);let from_rebuilt = search(- Some(&rebuilt),+ &rebuilt,&arena,&query,¶ms(Some(10), None, false),@@ -1833,13 +1713,7 @@ mod tests {let query_vector = seeded_unit_vector(splitmix64(&mut state), dims);let query = arena.pack_query(&query_vector).unwrap();let reference = reference_ranking(arena, &query, None);- let top = search(- Some(graph),- arena,- &query,- ¶ms(Some(10), None, false),- None,- );+ let top = search(graph, arena, &query, ¶ms(Some(10), None, false), None);assert_sorted(&top);assert_eq!(top.len(), reference.len().min(10));for hit in &top {@@ -1861,19 +1735,14 @@ mod tests {"churn recall was {hits}/{}",top.len());- let everything = search(- Some(graph),- arena,- &query,- ¶ms(None, Some(2.5), false),- None,- );+ let everything =+ search(graph, arena, &query, ¶ms(None, Some(2.5), false), None);assert_sorted(&everything);assert_eq!(everything.len(), live.len());if reference.len() >= 5 {let threshold = reference[4].0;let within = search(- Some(graph),+ graph,arena,&query,¶ms(None, Some(threshold), false),@@ -1894,7 +1763,7 @@ mod tests {arena.live_slots().filter(|slot| slot % 2 == 0).collect();if !allowed.is_empty() {let filtered = search(- Some(graph),+ graph,arena,&query,¶ms(Some(5), None, false),@@ -1916,15 +1785,9 @@ mod tests {let query = arena.pack_query(&seeded_unit_vector(0xC900_0000, dims)).unwrap();- let from_churned = search(- Some(graph),- arena,- &query,- ¶ms(Some(10), None, false),- None,- );+ let from_churned = search(graph, arena, &query, ¶ms(Some(10), None, false), None);let from_rebuilt = search(- Some(&rebuilt),+ &rebuilt,arena,&query,¶ms(Some(10), None, false),@@ -1950,16 +1813,10 @@ mod tests {.iter().map(|&(_, slot)| arena.key_of_slot(slot).unwrap()).collect();- let top = search(- Some(&graph),- &arena,- &query,- ¶ms(Some(10), None, false),- None,- );+ let top = search(&graph, &arena, &query, ¶ms(Some(10), None, false), None);assert_eq!(keys(&top), expected);let everything = search(- Some(&graph),+ &graph,&arena,&query,¶ms(None, Some(2.5), false),@@ -1978,7 +1835,7 @@ mod tests {for exact in [false, true] {for (limit, max_distance) in [(Some(3), None), (None, Some(1.0))] {let found = search(- Some(&graph),+ &graph,&arena,&query,¶ms(limit, max_distance, exact),diff --git a/rust/crates/ml/src/vecdb/kernel.rs b/rust/crates/ml/src/vecdb/kernel.rsindex 92d0667f71..0efb74ce85 100644--- a/rust/crates/ml/src/vecdb/kernel.rs+++ b/rust/crates/ml/src/vecdb/kernel.rs@@ -2,6 +2,14 @@ use wide::f32x8;pub(crate) const LANE_WIDTH: usize = 8;+pub(crate) fn splitmix64(state: &mut u64) -> u64 {+ *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);+ let mut mixed = *state;+ mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ mixed ^ (mixed >> 31)+}+pub(crate) trait VectorKernel {type Lane;@@ -55,14 +63,6 @@ pub(crate) fn unpack_lanes(lanes: &[f32x8]) -> Vec<f32> {mod tests {use super::*;- fn splitmix64(state: &mut u64) -> u64 {- *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);- let mut z = *state;- z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);- z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);- z ^ (z >> 31)- }-fn seeded_values(seed: u64, count: usize) -> Vec<f32> {let mut state = seed;(0..count)diff --git a/rust/crates/ml/src/vecdb/log.rs b/rust/crates/ml/src/vecdb/log.rsindex 25cff11ae1..c4996b4847 100644--- a/rust/crates/ml/src/vecdb/log.rs+++ b/rust/crates/ml/src/vecdb/log.rs@@ -6,9 +6,9 @@ use std::time::{SystemTime, UNIX_EPOCH};use super::VecDbError;use super::arena::{MAX_KEY_BYTES, validate_key};-use super::kernel::LANE_WIDTH;+use super::kernel::{LANE_WIDTH, splitmix64};-const HEADER_LEN: usize = 32;+pub(crate) const HEADER_LEN: usize = 32;const MAGIC: [u8; 4] = *b"EVDB";const FORMAT_VERSION: u16 = 1;const SCALAR_TAG_F32: u8 = 0;@@ -46,25 +46,13 @@ pub(crate) struct Log {impl Log {pub(crate) fn create(path: &Path, dims: usize) -> Result<Self, VecDbError> {validate_dims(dims)?;- let mut file = File::options()+ let file = File::options().read(true).write(true).create_new(true).open(path)- .map_err(|source| io_error(path, source))?;- let generation = fresh_generation();- file.write_all(&encode_header(dims as u32, &generation))- .map_err(|source| io_error(path, source))?;- file.sync_all().map_err(|source| io_error(path, source))?;- sync_parent_dir(path)?;- Ok(Self {- file,- path: path.to_path_buf(),- dims,- generation,- end_offset: HEADER_LEN as u64,- encode_buffer: Vec::new(),- })+ .map_err(|source| VecDbError::io(path, source))?;+ Self::initialize(file, path, dims)}pub(crate) fn open(@@ -75,18 +63,20 @@ impl Log {validate_dims(expected_dims)?;let file_len = file.metadata()- .map_err(|source| io_error(path, source))?+ .map_err(|source| VecDbError::io(path, source))?.len();if file_len < HEADER_LEN as u64 {- return Err(VecDbError::Corrupt(format!(- "log is {file_len} bytes, smaller than its {HEADER_LEN}-byte header"- )));+ log::warn!(+ "reinitializing {} whose {file_len}-byte header was never completed",+ path.display()+ );+ return Self::initialize(file, path, expected_dims);}file.seek(SeekFrom::Start(0))- .map_err(|source| io_error(path, source))?;+ .map_err(|source| VecDbError::io(path, source))?;let mut header = [0u8; HEADER_LEN];file.read_exact(&mut header)- .map_err(|source| io_error(path, source))?;+ .map_err(|source| VecDbError::io(path, source))?;let generation = decode_header(&header, expected_dims)?;Ok(Self {file,@@ -98,6 +88,25 @@ impl Log {})}+ fn initialize(mut file: File, path: &Path, dims: usize) -> 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))+ .map_err(|source| VecDbError::io(path, source))?;+ file.sync_all()+ .map_err(|source| VecDbError::io(path, source))?;+ sync_parent_dir(path)?;+ Ok(Self {+ file,+ path: path.to_path_buf(),+ dims,+ generation,+ end_offset: HEADER_LEN as u64,+ encode_buffer: Vec::new(),+ })+ }+pub(crate) fn create_temp_sibling(path: &Path,dims: usize,@@ -111,7 +120,7 @@ impl Log {pub(crate) fn scan(&mut self) -> Result<LogScanner<'_>, VecDbError> {self.file.seek(SeekFrom::Start(HEADER_LEN as u64))- .map_err(|source| io_error(&self.path, source))?;+ .map_err(|source| VecDbError::io(&self.path, source))?;Ok(LogScanner {reader: BufReader::new(&mut self.file),path: &self.path,@@ -123,17 +132,29 @@ impl Log {})}- pub(crate) fn append(&mut self, entries: &[LogEntry<'_>]) -> Result<(u64, u64), VecDbError> {- let start = self.end_offset;+ pub(crate) fn append(&mut self, entries: &[LogEntry<'_>]) -> Result<(), VecDbError> {if entries.is_empty() {- return Ok((start, start));+ return Ok(());}for entry in entries {validate_entry(entry, self.dims)?;}+ match self.write_records(entries) {+ Ok(written) => {+ self.end_offset += written;+ Ok(())+ }+ Err(error) => {+ self.discard_unacked_tail();+ Err(error)+ }+ }+ }++ fn write_records(&mut self, entries: &[LogEntry<'_>]) -> Result<u64, VecDbError> {self.file- .seek(SeekFrom::Start(start))- .map_err(|source| io_error(&self.path, source))?;+ .seek(SeekFrom::Start(self.end_offset))+ .map_err(|source| VecDbError::io(&self.path, source))?;self.encode_buffer.clear();let mut written = 0u64;for entry in entries {@@ -145,9 +166,13 @@ impl Log {written += self.drain_encode_buffer()?;self.file.sync_all()- .map_err(|source| io_error(&self.path, source))?;- self.end_offset = start + written;- Ok((start, self.end_offset))+ .map_err(|source| VecDbError::io(&self.path, source))?;+ Ok(written)+ }++ fn discard_unacked_tail(&mut self) {+ let _ = self.file.set_len(self.end_offset);+ let _ = self.file.sync_all();}fn drain_encode_buffer(&mut self) -> Result<u64, VecDbError> {@@ -156,7 +181,7 @@ impl Log {}self.file.write_all(&self.encode_buffer)- .map_err(|source| io_error(&self.path, source))?;+ .map_err(|source| VecDbError::io(&self.path, source))?;let written = self.encode_buffer.len() as u64;self.encode_buffer.clear();Ok(written)@@ -174,11 +199,11 @@ impl Log {);self.file.set_len(target)- .map_err(|source| io_error(&self.path, source))?;+ .map_err(|source| VecDbError::io(&self.path, source))?;self.end_offset = target;self.file.sync_all()- .map_err(|source| io_error(&self.path, source))?;+ .map_err(|source| VecDbError::io(&self.path, source))?;Ok(())}@@ -190,10 +215,6 @@ impl Log {self.generation}- pub(crate) fn dims(&self) -> usize {- self.dims- }-pub(crate) fn path(&self) -> &Path {&self.path}@@ -303,7 +324,7 @@ impl LogScanner<'_> {Err(error) if error.kind() == ErrorKind::UnexpectedEof => Ok(false),Err(source) => {self.done = true;- Err(io_error(self.path, source))+ Err(VecDbError::io(self.path, source))}}}@@ -418,20 +439,28 @@ fn fresh_generation() -> [u8; 16] {generation}-fn splitmix64(state: &mut u64) -> u64 {- *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);- let mut mixed = *state;- mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);- mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);- mixed ^ (mixed >> 31)+pub(crate) fn remove_stale_temp_sibling(path: &Path) -> Result<(), VecDbError> {+ remove_if_present(&temp_sibling_path(path))}-pub(crate) fn remove_stale_temp_sibling(path: &Path) -> Result<(), VecDbError> {- let temp_path = temp_sibling_path(path);- match std::fs::remove_file(&temp_path) {+pub(crate) fn remove_if_present(path: &Path) -> Result<(), VecDbError> {+ match std::fs::remove_file(path) {Ok(()) => Ok(()),Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),- Err(source) => Err(io_error(&temp_path, source)),+ Err(source) => Err(VecDbError::io(path, source)),+ }+}++pub(crate) fn rename_with_windows_fallback(from: &Path, to: &Path) -> Result<(), VecDbError> {+ match std::fs::rename(from, to) {+ Ok(()) => Ok(()),+ #[cfg(windows)]+ Err(_) => {+ let _ = std::fs::remove_file(to);+ std::fs::rename(from, to).map_err(|source| VecDbError::io(from, source))+ }+ #[cfg(not(windows))]+ Err(source) => Err(VecDbError::io(from, source)),}}@@ -441,26 +470,19 @@ fn temp_sibling_path(path: &Path) -> PathBuf {PathBuf::from(temp)}-fn io_error(path: &Path, source: std::io::Error) -> VecDbError {- VecDbError::Io {- path: path.to_path_buf(),- source,- }-}-#[cfg(unix)]-fn sync_parent_dir(path: &Path) -> Result<(), VecDbError> {+pub(crate) fn sync_parent_dir(path: &Path) -> Result<(), VecDbError> {let parent = match path.parent() {Some(parent) if !parent.as_os_str().is_empty() => parent,_ => Path::new("."),};File::open(parent).and_then(|dir| dir.sync_all())- .map_err(|source| io_error(parent, source))+ .map_err(|source| VecDbError::io(parent, source))}#[cfg(not(unix))]-fn sync_parent_dir(_path: &Path) -> Result<(), VecDbError> {+pub(crate) fn sync_parent_dir(_path: &Path) -> Result<(), VecDbError> {Ok(())}@@ -484,6 +506,24 @@ mod tests {Log::open(file, path, dims).unwrap()}+ fn append_bounds(log: &mut Log, entries: &[LogEntry<'_>]) -> (u64, u64) {+ let start = log.current_end_offset();+ log.append(entries).unwrap();+ (start, log.current_end_offset())+ }++ fn append_raw_bytes(path: &Path, bytes: &[u8]) {+ let mut surgeon = File::options().append(true).open(path).unwrap();+ surgeon.write_all(bytes).unwrap();+ surgeon.sync_all().unwrap();+ }++ fn encoded_add(key: &str, vector: &[f32]) -> Vec<u8> {+ let mut bytes = Vec::new();+ encode_record_into(&mut bytes, &LogEntry::Add { key, vector });+ bytes+ }+fn scan_all(log: &mut Log) -> (Vec<(LogRecord, u64)>, u64) {let mut scanner = log.scan().unwrap();let mut records = Vec::new();@@ -545,13 +585,11 @@ mod tests {let path = dir.path().join("log");let created = Log::create(&path, 512).unwrap();let generation = created.generation();- assert_eq!(created.dims(), 512);assert_eq!(created.current_end_offset(), HEADER_LEN as u64);assert_eq!(created.path(), path.as_path());drop(created.into_file());let reopened = reopen(&path, 512);assert_eq!(reopened.generation(), generation);- assert_eq!(reopened.dims(), 512);assert_eq!(reopened.current_end_offset(), HEADER_LEN as u64);}@@ -626,13 +664,32 @@ mod tests {}#[test]- fn rejects_file_shorter_than_header() {- let dir = TempDir::new().unwrap();- let path = dir.path().join("log");- std::fs::write(&path, [1u8; 10]).unwrap();- let file = File::options().read(true).write(true).open(&path).unwrap();- let error = Log::open(file, &path, 8).unwrap_err();- assert!(matches!(&error, VecDbError::Corrupt(message) if message.contains("header")));+ fn writer_open_reinitializes_files_shorter_than_the_header() {+ for junk_len in [0usize, 10, 31] {+ let dir = TempDir::new().unwrap();+ 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();+ 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);+ assert!(records.is_empty());+ let vector = seeded_vector(6, 8);+ let (start, end) = append_bounds(+ &mut log,+ &[LogEntry::Add {+ key: "reborn",+ vector: &vector,+ }],+ );+ assert_eq!(start, HEADER_LEN as u64);+ let generation = log.generation();+ drop(log);+ let reopened = reopen(&path, 8);+ assert_eq!(reopened.generation(), generation);+ assert_eq!(reopened.current_end_offset(), end);+ }}#[test]@@ -732,8 +789,8 @@ mod tests {},LogEntry::Tombstone { key: "beta" },];- let (first, _) = log.append(&entries[0..1]).unwrap();- let (second, end) = log.append(&entries[1..2]).unwrap();+ let (first, _) = append_bounds(&mut log, &entries[0..1]);+ let (second, end) = append_bounds(&mut log, &entries[1..2]);assert_eq!(first, HEADER_LEN as u64);let (records, recoverable_end) = scan_all(&mut log);assert_eq!(@@ -764,7 +821,7 @@ mod tests {vector: &vectors[2],},];- let (start, end) = log.append(&entries).unwrap();+ let (start, end) = append_bounds(&mut log, &entries);assert_eq!(start, HEADER_LEN as u64);assert_eq!(end, log.current_end_offset());let (records, recoverable_end) = scan_all(&mut log);@@ -863,8 +920,10 @@ mod tests {let mut boundaries = Vec::new();for (index, vector) in vectors.iter().enumerate() {let key = format!("key-{index}");- let bounds = log.append(&[LogEntry::Add { key: &key, vector }]).unwrap();- boundaries.push(bounds);+ boundaries.push(append_bounds(+ &mut log,+ &[LogEntry::Add { key: &key, vector }],+ ));}drop(log);let full_bytes = std::fs::read(&build_path).unwrap();@@ -887,18 +946,20 @@ mod tests {let path = dir.path().join("log");let mut log = Log::create(&path, 8).unwrap();let vector = seeded_vector(1, 8);- let (_, first_end) = log- .append(&[LogEntry::Add {+ let (_, first_end) = append_bounds(+ &mut log,+ &[LogEntry::Add {key: "kept",vector: &vector,- }])- .unwrap();- let (_, torn_end) = log- .append(&[LogEntry::Add {+ }],+ );+ let (_, torn_end) = append_bounds(+ &mut log,+ &[LogEntry::Add {key: "torn",vector: &vector,- }])- .unwrap();+ }],+ );drop(log);let cut = first_end + (torn_end - first_end) / 2;let file = File::options().read(true).write(true).open(&path).unwrap();@@ -912,12 +973,13 @@ mod tests {log.truncate_to(recoverable_end).unwrap();assert_eq!(log.current_end_offset(), first_end);assert_eq!(std::fs::metadata(&path).unwrap().len(), first_end);- let (start, end) = log- .append(&[LogEntry::Add {+ let (start, end) = append_bounds(+ &mut log,+ &[LogEntry::Add {key: "fresh",vector: &vector,- }])- .unwrap();+ }],+ );assert_eq!(start, first_end);let (records, recoverable_end) = scan_all(&mut log);assert_eq!(records.len(), 2);@@ -926,6 +988,106 @@ mod tests {assert_eq!(std::fs::metadata(&path).unwrap().len(), end);}+ #[test]+ 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 vector = seeded_vector(1, 8);+ let (_, acked_end) = append_bounds(+ &mut log,+ &[LogEntry::Add {+ key: "acked",+ vector: &vector,+ }],+ );+ let phantom = encoded_add("phantom", &vector);+ append_raw_bytes(&path, &phantom);+ assert_eq!(+ std::fs::metadata(&path).unwrap().len(),+ acked_end + phantom.len() as u64+ );+ log.discard_unacked_tail();+ assert_eq!(std::fs::metadata(&path).unwrap().len(), acked_end);+ drop(log);+ let mut reopened = reopen(&path, 8);+ let (records, recoverable_end) = scan_all(&mut reopened);+ assert_eq!(records.len(), 1);+ assert!(matches!(&records[0].0, LogRecord::Add { key, .. } if key == "acked"));+ assert_eq!(recoverable_end, acked_end);+ }++ #[test]+ 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 vector = seeded_vector(2, 8);+ let (_, acked_end) = append_bounds(+ &mut log,+ &[LogEntry::Add {+ key: "kept",+ vector: &vector,+ }],+ );+ drop(log);+ let unwritable = File::open(&path).unwrap();+ let mut log = Log::open(unwritable, &path, 8).unwrap();+ assert!(matches!(+ log.append(&[LogEntry::Add {+ key: "lost",+ vector: &vector+ }]),+ Err(VecDbError::Io { .. })+ ));+ assert_eq!(log.current_end_offset(), acked_end);+ drop(log);+ assert_eq!(std::fs::metadata(&path).unwrap().len(), acked_end);+ let mut reopened = reopen(&path, 8);+ let (records, _) = scan_all(&mut reopened);+ assert_eq!(records.len(), 1);+ assert!(matches!(&records[0].0, LogRecord::Add { key, .. } if key == "kept"));+ }++ #[test]+ 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 vector = seeded_vector(3, 8);+ let (_, acked_end) = append_bounds(+ &mut log,+ &[LogEntry::Add {+ key: "first",+ vector: &vector,+ }],+ );+ append_raw_bytes(&path, &encoded_add("ghost", &vector));+ let replacement = seeded_vector(4, 8);+ let (start, end) = append_bounds(+ &mut log,+ &[LogEntry::Add {+ key: "third",+ vector: &replacement,+ }],+ );+ assert_eq!(start, acked_end);+ let (records, recoverable_end) = scan_all(&mut log);+ assert_eq!(records.len(), 2);+ assert_eq!(records[1].1, acked_end);+ assert!(matches!(&records[1].0, LogRecord::Add { key, .. } if key == "third"));+ assert_eq!(recoverable_end, end);+ drop(log);+ let mut reopened = reopen(&path, 8);+ let (records, _) = scan_all(&mut reopened);+ assert_eq!(records.len(), 2);+ assert!(+ records+ .iter()+ .all(|(record, _)| !matches!(record, LogRecord::Add { key, .. } if key == "ghost"))+ );+ }+#[test]fn scanner_stops_at_corrupted_middle_record() {let dir = TempDir::new().unwrap();@@ -935,8 +1097,10 @@ mod tests {let mut boundaries = Vec::new();for (index, vector) in vectors.iter().enumerate() {let key = format!("key-{index}");- let bounds = log.append(&[LogEntry::Add { key: &key, vector }]).unwrap();- boundaries.push(bounds);+ boundaries.push(append_bounds(+ &mut log,+ &[LogEntry::Add { key: &key, vector }],+ ));}drop(log);let bytes = std::fs::read(&build_path).unwrap();@@ -1003,21 +1167,20 @@ mod tests {let dir = TempDir::new().unwrap();let path = dir.path().join("log");let mut log = Log::create(&path, 8).unwrap();- assert_eq!(- log.append(&[]).unwrap(),- (HEADER_LEN as u64, HEADER_LEN as u64)- );+ log.append(&[]).unwrap();+ assert_eq!(log.current_end_offset(), HEADER_LEN as u64);let vector = seeded_vector(7, 8);let mut expected_offsets = Vec::new();let mut previous_end = HEADER_LEN as u64;for index in 0..5u32 {let key = format!("entry-{index}");- let (start, end) = log- .append(&[LogEntry::Add {+ let (start, end) = append_bounds(+ &mut log,+ &[LogEntry::Add {key: &key,vector: &vector,- }])- .unwrap();+ }],+ );assert_eq!(start, previous_end);expected_offsets.push(start);previous_end = end;@@ -1130,13 +1293,10 @@ mod tests {.collect();let mut bulk_log = Log::create(&bulk_path, dims).unwrap();let mut sequential_log = Log::create(&sequential_path, dims).unwrap();- let (_, bulk_end) = bulk_log.append(&entries).unwrap();+ let (_, bulk_end) = append_bounds(&mut bulk_log, &entries);let mut sequential_end = 0;for entry in &entries {- sequential_end = sequential_log- .append(std::slice::from_ref(entry))- .unwrap()- .1;+ sequential_end = append_bounds(&mut sequential_log, std::slice::from_ref(entry)).1;}assert_eq!(bulk_end, sequential_end);assert!(bulk_end - HEADER_LEN as u64 > ENCODE_FLUSH_BYTES as u64);@@ -1171,13 +1331,10 @@ mod tests {];let mut bulk_log = Log::create(&bulk_path, 8).unwrap();let mut sequential_log = Log::create(&sequential_path, 8).unwrap();- let (bulk_start, bulk_end) = bulk_log.append(&entries).unwrap();+ let (bulk_start, bulk_end) = append_bounds(&mut bulk_log, &entries);let mut sequential_end = 0;for entry in &entries {- sequential_end = sequential_log- .append(std::slice::from_ref(entry))- .unwrap()- .1;+ sequential_end = append_bounds(&mut sequential_log, std::slice::from_ref(entry)).1;}assert_eq!(bulk_start, HEADER_LEN as u64);assert_eq!(bulk_end, sequential_end);diff --git a/rust/crates/ml/src/vecdb/mod.rs b/rust/crates/ml/src/vecdb/mod.rsindex b0e8e6ad7d..6133839200 100644--- a/rust/crates/ml/src/vecdb/mod.rs+++ b/rust/crates/ml/src/vecdb/mod.rs@@ -1,4 +1,4 @@-use std::path::PathBuf;+use std::path::{Path, PathBuf};use thiserror::Error;@@ -51,3 +51,47 @@ pub enum VecDbError {#[error("search requires a limit or a max distance")]UnboundedSearch,}++impl VecDbError {+ pub(crate) fn io(path: &Path, source: std::io::Error) -> Self {+ Self::Io {+ path: path.to_path_buf(),+ source,+ }+ }+}++#[cfg(test)]+pub(crate) mod test_support {+ use super::graph::Graph;++ pub(crate) fn assert_identical_graphs(first: &Graph, second: &Graph) {+ assert_eq!(first.entry_point(), second.entry_point());+ assert_eq!(+ first.slots().collect::<Vec<_>>(),+ second.slots().collect::<Vec<_>>()+ );+ for slot in first.slots() {+ assert_eq!(first.level_of(slot), second.level_of(slot));+ let level = first.level_of(slot).unwrap();+ for layer in 0..=level {+ assert_eq!(+ first.neighbors_of(slot, layer),+ second.neighbors_of(slot, layer)+ );+ }+ }+ }++ pub(crate) fn stale_downward_edge_exists(graph: &Graph) -> bool {+ graph.slots().any(|slot| {+ let level = graph.level_of(slot).unwrap();+ (0..=level).any(|layer| {+ graph+ .neighbors_of(slot, layer)+ .iter()+ .any(|&neighbor| graph.level_of(neighbor).unwrap() < layer)+ })+ })+ }+}diff --git a/rust/crates/ml/src/vecdb/snapshot.rs b/rust/crates/ml/src/vecdb/snapshot.rsindex 87c74d22c0..74fc978410 100644--- a/rust/crates/ml/src/vecdb/snapshot.rs+++ b/rust/crates/ml/src/vecdb/snapshot.rs@@ -4,6 +4,7 @@ use std::path::{Path, PathBuf};use super::VecDbError;use super::graph::{Graph, GraphNodeParts};+use super::log::{remove_if_present, rename_with_windows_fallback, sync_parent_dir};const MAGIC: [u8; 4] = *b"EVDG";const FORMAT_VERSION: u16 = 1;@@ -238,37 +239,17 @@ impl<'a> BodyReader<'a> {}fn write_and_swap(bytes: &[u8], temp: &Path, target: &Path) -> Result<(), VecDbError> {- let mut file = File::create(temp).map_err(|source| io_error(temp, source))?;+ let mut file = File::create(temp).map_err(|source| VecDbError::io(temp, source))?;file.write_all(bytes)- .map_err(|source| io_error(temp, source))?;- file.sync_all().map_err(|source| io_error(temp, source))?;+ .map_err(|source| VecDbError::io(temp, source))?;+ file.sync_all()+ .map_err(|source| VecDbError::io(temp, source))?;drop(file);- rename_over(temp, target)?;- sync_parent_dir_best_effort(target);+ rename_with_windows_fallback(temp, target)?;+ let _ = sync_parent_dir(target);Ok(())}-fn rename_over(temp: &Path, target: &Path) -> Result<(), VecDbError> {- match std::fs::rename(temp, target) {- Ok(()) => Ok(()),- #[cfg(windows)]- Err(_) => {- let _ = std::fs::remove_file(target);- std::fs::rename(temp, target).map_err(|source| io_error(temp, source))- }- #[cfg(not(windows))]- Err(source) => Err(io_error(temp, source)),- }-}--fn remove_if_present(path: &Path) -> Result<(), VecDbError> {- match std::fs::remove_file(path) {- Ok(()) => Ok(()),- Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),- Err(source) => Err(io_error(path, source)),- }-}-fn temp_snapshot_path(log_path: &Path) -> PathBuf {append_suffix(log_path, ".graph.tmp")}@@ -279,25 +260,6 @@ fn append_suffix(path: &Path, suffix: &str) -> PathBuf {PathBuf::from(extended)}-fn io_error(path: &Path, source: std::io::Error) -> VecDbError {- VecDbError::Io {- path: path.to_path_buf(),- source,- }-}--#[cfg(unix)]-fn sync_parent_dir_best_effort(path: &Path) {- let parent = match path.parent() {- Some(parent) if !parent.as_os_str().is_empty() => parent,- _ => Path::new("."),- };- let _ = File::open(parent).and_then(|dir| dir.sync_all());-}--#[cfg(not(unix))]-fn sync_parent_dir_best_effort(_path: &Path) {}-#[cfg(test)]mod tests {use tempfile::TempDir;@@ -305,6 +267,8 @@ mod tests {use super::super::SearchParams;use super::super::arena::{UpsertOutcome, VectorArena};use super::super::graph::search;+ use super::super::kernel::splitmix64;+ use super::super::test_support::{assert_identical_graphs, stale_downward_edge_exists};use super::*;const GOLDEN: [u8; 86] = [@@ -364,14 +328,6 @@ mod tests {assert!(load_golden(&log_path).is_none());}- fn splitmix64(state: &mut u64) -> u64 {- *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);- let mut z = *state;- z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);- z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);- z ^ (z >> 31)- }-fn seeded_unit_vector(seed: u64, dims: usize) -> Vec<f32> {let mut state = seed;let mut values: Vec<f32> = (0..dims)@@ -400,36 +356,6 @@ mod tests {arena}- fn stale_downward_edge_exists(graph: &Graph) -> bool {- graph.slots().any(|slot| {- let level = graph.level_of(slot).unwrap();- (0..=level).any(|layer| {- graph- .neighbors_of(slot, layer)- .iter()- .any(|&neighbor| graph.level_of(neighbor).unwrap() < layer)- })- })- }-- fn assert_identical_graphs(first: &Graph, second: &Graph) {- assert_eq!(first.entry_point(), second.entry_point());- assert_eq!(- first.slots().collect::<Vec<_>>(),- second.slots().collect::<Vec<_>>()- );- for slot in first.slots() {- assert_eq!(first.level_of(slot), second.level_of(slot));- let level = first.level_of(slot).unwrap();- for layer in 0..=level {- assert_eq!(- first.neighbors_of(slot, layer),- second.neighbors_of(slot, layer)- );- }- }- }-fn churned_fixture(dims: usize) -> (VectorArena, Graph) {let mut arena = build_arena(600, dims, 0x00A1_0000);let mut graph = Graph::rebuild(&arena);@@ -443,17 +369,22 @@ mod tests {.filter(|&slot| arena.is_alive(slot)).unwrap_or_else(|| arena.live_slots().next().unwrap());let key = arena.key_of_slot(victim).unwrap().to_string();- let outcome = arena- .upsert(&key, &seeded_unit_vector(0x00A2_0000 + round, dims))- .unwrap();- graph.reinsert(outcome.slot(), &arena);+ assert_eq!(+ arena+ .upsert(&key, &seeded_unit_vector(0x00A2_0000 + round, dims))+ .unwrap(),+ UpsertOutcome::ReplacedInPlace(victim)+ );+ graph.reinsert(victim, &arena);stale_seen |= stale_downward_edge_exists(&graph);}- let outcome = arena+ let UpsertOutcome::RecycledSlot(recycled) = arena.upsert("recycled", &seeded_unit_vector(0x00A3_0000, dims))- .unwrap();- assert!(matches!(outcome, UpsertOutcome::RecycledSlot(_)));- graph.reinsert(outcome.slot(), &arena);+ .unwrap()+ else {+ panic!("expected a recycled slot");+ };+ graph.reinsert(recycled, &arena);assert!(stale_seen);(arena, graph)}@@ -533,8 +464,8 @@ mod tests {params(None, Some(0.9)),params(Some(3), Some(1.2)),] {- let original = search(Some(&graph), &arena, &query, &search_params, None);- let reconstructed = search(Some(&rebuilt), &arena, &query, &search_params, None);+ let original = search(&graph, &arena, &query, &search_params, None);+ let reconstructed = search(&rebuilt, &arena, &query, &search_params, None);assert_eq!(original, reconstructed);assert!(!original.is_empty());}@@ -615,7 +546,7 @@ mod tests {return;};for search_params in [params(Some(2), None), params(None, Some(2.5))] {- let found = search(Some(&graph), &arena, &query, &search_params, None);+ let found = search(&graph, &arena, &query, &search_params, None);assert!(found.len() <= 3);}searched += 1;diff --git a/rust/crates/ml/src/vecdb/store.rs b/rust/crates/ml/src/vecdb/store.rsindex 91ae458ed2..ca51d2b8aa 100644--- a/rust/crates/ml/src/vecdb/store.rs+++ b/rust/crates/ml/src/vecdb/store.rs@@ -4,10 +4,13 @@ use std::io::ErrorKind;use std::path::{Path, PathBuf};use std::time::{Duration, Instant};-use super::arena::{UpsertOutcome, VECTORS_PER_CHUNK, VectorArena, validate_key};+use super::arena::{UpsertOutcome, VECTORS_PER_CHUNK, VectorArena};use super::graph::{Graph, search as graph_search};use super::lock::lock_exclusive;-use super::log::{Log, LogEntry, LogRecord, remove_stale_temp_sibling};+use super::log::{+ HEADER_LEN, Log, LogEntry, LogRecord, remove_if_present, remove_stale_temp_sibling,+ rename_with_windows_fallback, sync_parent_dir,+};use super::snapshot::{load_snapshot, remove_snapshot, snapshot_path, write_snapshot};use super::{Match, SearchParams, VecDbError};@@ -17,6 +20,10 @@ const SNAPSHOT_QUIET_GAP: Duration = Duration::from_secs(10);const COMPACTION_MIN_DEAD_RECORDS: u64 = 64;const COMPACTION_DEAD_RATIO: u64 = 10;const COMPACTION_BATCH_SIZE: usize = 1000;+const KEY_TABLE_COPIES: usize = 2;+const KEY_ENTRY_OVERHEAD_BYTES: usize = 48;+const GRAPH_NODE_OVERHEAD_BYTES: usize = 48;+const NEIGHBOR_LIST_OVERHEAD_BYTES: usize = 24;#[derive(Debug, Clone, PartialEq, Eq)]pub struct Stats {@@ -33,6 +40,7 @@ pub struct VecDb {arena: VectorArena,graph: Graph,total_records: u64,+ compaction_retry_at_dead: u64,mode: Mode,}@@ -56,12 +64,11 @@ impl VecDb {.read(true).write(true).open(path)- .map_err(|source| io_error(path, source))?+ .map_err(|source| VecDbError::io(path, source))?}Err(error) => return Err(error),};- lock_exclusive(&file, path)?;- let mut log = Log::open(file, path, dims)?;+ let mut log = open_locked(file, path, dims)?;remove_stale_temp_sibling(path)?;let snapshot_present = std::fs::metadata(snapshot_path(path)).is_ok();let replayed = replay(&mut log, dims)?;@@ -73,19 +80,31 @@ impl VecDb {} else {replayed.total_records > 0 || snapshot_present};+ let pending_records = if replayed.used_snapshot {+ replayed.tail_records+ } else {+ replayed.total_records+ } as usize;let mut db = Self {path: path.to_path_buf(),arena: replayed.arena,graph: replayed.graph,total_records: replayed.total_records,+ compaction_retry_at_dead: 0,mode: Mode::Writer(WriterState {log,mutations_since_snapshot: 0,last_write: None,}),};- if snapshot_stale {- db.write_snapshot_now()?;+ if snapshot_stale && let Err(error) = db.write_snapshot_now() {+ log::warn!(+ "continuing without an open-time snapshot for {}: {error}",+ path.display()+ );+ if let Mode::Writer(state) = &mut db.mode {+ state.mutations_since_snapshot = pending_records.max(1);+ }}Ok(db)}@@ -94,16 +113,17 @@ impl VecDb {let file = match File::open(path) {Ok(file) => file,Err(error) if error.kind() == ErrorKind::NotFound => {- return Ok(Self {- path: path.to_path_buf(),- arena: VectorArena::new(dims)?,- graph: Graph::new(),- total_records: 0,- mode: Mode::ReadOnly { log_bytes: 0 },- });+ return Self::empty_read_only(path, dims);}- Err(source) => return Err(io_error(path, source)),+ Err(source) => return Err(VecDbError::io(path, source)),};+ let file_len = file+ .metadata()+ .map_err(|source| VecDbError::io(path, source))?+ .len();+ if file_len < HEADER_LEN as u64 {+ return Self::empty_read_only(path, dims);+ }let mut log = Log::open(file, path, dims)?;let replayed = replay(&mut log, dims)?;drop(log);@@ -112,16 +132,28 @@ impl VecDb {arena: replayed.arena,graph: replayed.graph,total_records: replayed.total_records,+ compaction_retry_at_dead: 0,mode: Mode::ReadOnly {log_bytes: replayed.recoverable_end,},})}+ fn empty_read_only(path: &Path, dims: usize) -> Result<Self, VecDbError> {+ Ok(Self {+ path: path.to_path_buf(),+ arena: VectorArena::new(dims)?,+ graph: Graph::new(),+ total_records: 0,+ compaction_retry_at_dead: 0,+ mode: Mode::ReadOnly { log_bytes: 0 },+ })+ }+pub fn add(&mut self, key: &str, vector: &[f32]) -> Result<(), VecDbError> {let now = Instant::now();- self.writer_state()?;- self.validate_entry(key, vector)?;+ self.ensure_writer()?;+ ensure_finite(key, vector)?;self.writer_state()?.log.append(&[LogEntry::Add { key, vector }])?;@@ -132,12 +164,12 @@ impl VecDb {pub fn bulk_add(&mut self, entries: &[(String, Vec<f32>)]) -> Result<(), VecDbError> {let now = Instant::now();- self.writer_state()?;+ self.ensure_writer()?;if entries.is_empty() {return Ok(());}for (key, vector) in entries {- self.validate_entry(key, vector)?;+ ensure_finite(key, vector)?;}let records: Vec<LogEntry<'_>> = entries.iter()@@ -153,7 +185,7 @@ impl VecDb {pub fn remove(&mut self, key: &str) -> Result<bool, VecDbError> {let now = Instant::now();- self.writer_state()?;+ self.ensure_writer()?;if self.arena.slot_of_key(key).is_none() {return Ok(false);}@@ -167,7 +199,7 @@ impl VecDb {pub fn bulk_remove(&mut self, keys: &[String]) -> Result<usize, VecDbError> {let now = Instant::now();- self.writer_state()?;+ self.ensure_writer()?;let mut scheduled: Vec<&str> = Vec::new();let mut seen: HashSet<&str> = HashSet::new();for key in keys {@@ -216,7 +248,7 @@ impl VecDb {.collect()});Ok(graph_search(- Some(&self.graph),+ &self.graph,&self.arena,&packed,params,@@ -233,23 +265,23 @@ impl VecDb {}pub fn reset(&mut self) -> Result<(), VecDbError> {- self.writer_state()?;+ let old_state = self.take_writer_state()?;+ drop(old_state);let dims = self.arena.dims();- let Mode::Writer(old_state) =- std::mem::replace(&mut self.mode, Mode::ReadOnly { log_bytes: 0 })- else {- return Err(VecDbError::ReadOnly);+ let recreated = remove_index_files(&self.path)+ .and_then(|()| Log::create(&self.path, dims))+ .and_then(|created| open_locked(created.into_file(), &self.path, dims));+ let log = match recreated {+ Ok(log) => log,+ Err(error) => {+ let _ = self.restore_writer_mode(dims, None);+ return Err(error);+ }};- drop(old_state);- remove_if_present(&self.path)?;- remove_snapshot(&self.path)?;- remove_stale_temp_sibling(&self.path)?;- let file = Log::create(&self.path, dims)?.into_file();- lock_exclusive(&file, &self.path)?;- let log = Log::open(file, &self.path, dims)?;self.arena = VectorArena::new(dims)?;self.graph = Graph::new();self.total_records = 0;+ self.compaction_retry_at_dead = 0;self.mode = Mode::Writer(WriterState {log,mutations_since_snapshot: 0,@@ -263,10 +295,7 @@ impl VecDb {return Err(VecDbError::ReadOnly);};drop(state);- remove_if_present(&self.path)?;- remove_snapshot(&self.path)?;- remove_stale_temp_sibling(&self.path)?;- Ok(())+ remove_index_files(&self.path)}pub fn stats(&self) -> Stats {@@ -303,20 +332,47 @@ impl VecDb {}}- fn validate_entry(&self, key: &str, vector: &[f32]) -> Result<(), VecDbError> {- validate_key(key)?;- if vector.len() != self.arena.dims() {- return Err(VecDbError::DimensionMismatch {- expected: self.arena.dims(),- actual: vector.len(),- });+ fn ensure_writer(&self) -> Result<(), VecDbError> {+ match &self.mode {+ Mode::Writer(_) => Ok(()),+ Mode::ReadOnly { .. } => Err(VecDbError::ReadOnly),}- if let Some(index) = vector.iter().position(|value| !value.is_finite()) {- return Err(VecDbError::InvalidVector(format!(- "component {index} of the vector for key {key:?} is not finite"- )));+ }++ fn take_writer_state(&mut self) -> Result<WriterState, VecDbError> {+ self.ensure_writer()?;+ match std::mem::replace(&mut self.mode, Mode::ReadOnly { log_bytes: 0 }) {+ Mode::Writer(state) => Ok(state),+ Mode::ReadOnly { .. } => Err(VecDbError::ReadOnly),+ }+ }++ fn restore_writer_mode(+ &mut self,+ dims: usize,+ last_write: Option<Instant>,+ ) -> Result<(), VecDbError> {+ match open_path_locked(&self.path, dims) {+ Ok(log) => {+ self.mode = Mode::Writer(WriterState {+ log,+ mutations_since_snapshot: 0,+ last_write,+ });+ Ok(())+ }+ Err(error) => {+ let log_bytes = std::fs::metadata(&self.path)+ .map(|meta| meta.len())+ .unwrap_or(0);+ log::warn!(+ "degrading {} to read-only after failing to restore its writer: {error}",+ self.path.display()+ );+ self.mode = Mode::ReadOnly { log_bytes };+ Err(error)+ }}- Ok(())}fn record_mutations(&mut self, count: usize, now: Instant) -> Result<(), VecDbError> {@@ -335,11 +391,21 @@ impl VecDb {let dead = total.saturating_sub(live);if dead >= COMPACTION_MIN_DEAD_RECORDS&& dead.saturating_mul(COMPACTION_DEAD_RATIO) >= total+ && dead >= self.compaction_retry_at_dead{- return self.compact();+ match self.compact() {+ Ok(()) => self.compaction_retry_at_dead = 0,+ Err(error) => {+ log::warn!("compaction of {} failed: {error}", self.path.display());+ self.compaction_retry_at_dead = dead + COMPACTION_MIN_DEAD_RECORDS;+ }+ }+ return Ok(());}- if mutations >= SNAPSHOT_HARD_CAP || (mutations >= SNAPSHOT_QUIET_THRESHOLD && quiet) {- return self.write_snapshot_now();+ if (mutations >= SNAPSHOT_HARD_CAP || (mutations >= SNAPSHOT_QUIET_THRESHOLD && quiet))+ && let Err(error) = self.write_snapshot_now()+ {+ log::warn!("snapshot of {} failed: {error}", self.path.display());}Ok(())}@@ -360,11 +426,9 @@ impl VecDb {}fn compact(&mut self) -> Result<(), VecDbError> {- let Mode::Writer(state) = &mut self.mode else {- return Err(VecDbError::ReadOnly);- };- let dims = state.log.dims();- let (mut temp_log, temp_path) = Log::create_temp_sibling(state.log.path(), dims)?;+ self.ensure_writer()?;+ let dims = self.arena.dims();+ let (mut temp_log, temp_path) = Log::create_temp_sibling(&self.path, dims)?;let mut compacted = VectorArena::new(dims)?;if let Err(error) = stage_live_entries(&self.arena, &mut compacted, &mut temp_log) {drop(temp_log);@@ -375,32 +439,21 @@ impl VecDb {if let Err(source) = temp_file.sync_all() {drop(temp_file);let _ = std::fs::remove_file(&temp_path);- return Err(io_error(&temp_path, source));+ return Err(VecDbError::io(&temp_path, source));}drop(temp_file);- let last_write = state.last_write;- let Mode::Writer(old_state) =- std::mem::replace(&mut self.mode, Mode::ReadOnly { log_bytes: 0 })- else {- return Err(VecDbError::ReadOnly);- };- drop(old_state);- std::fs::rename(&temp_path, &self.path).map_err(|source| io_error(&self.path, source))?;- let file = File::options()- .read(true)- .write(true)- .open(&self.path)- .map_err(|source| io_error(&self.path, source))?;- lock_exclusive(&file, &self.path)?;- let log = Log::open(file, &self.path, dims)?;- self.arena = compacted;- self.graph = Graph::rebuild(&self.arena);- self.total_records = self.arena.live_count() as u64;- self.mode = Mode::Writer(WriterState {- log,- mutations_since_snapshot: 0,- last_write,- });+ let last_write = self.take_writer_state()?.last_write;+ let promoted = promote_compacted_log(&temp_path, &self.path);+ if temp_path.exists() {+ let _ = std::fs::remove_file(&temp_path);+ } else {+ self.arena = compacted;+ self.graph = Graph::rebuild(&self.arena);+ self.total_records = self.arena.live_count() as u64;+ }+ let restored = self.restore_writer_mode(dims, last_write);+ promoted?;+ restored?;self.write_snapshot_now()}@@ -413,7 +466,7 @@ impl VecDb {.arena.live_slots().filter_map(|slot| self.arena.key_of_slot(slot))- .map(|key| 2 * (key.len() + 48))+ .map(|key| KEY_TABLE_COPIES * (key.len() + KEY_ENTRY_OVERHEAD_BYTES)).sum();let free_list_bytes = self.arena.dead_count() * size_of::<u32>();let graph_bytes: usize = self@@ -421,9 +474,13 @@ impl VecDb {.slots().map(|slot| {let level = self.graph.level_of(slot).unwrap_or(0);- 48 + (0..=level)- .map(|layer| 24 + size_of_val(self.graph.neighbors_of(slot, layer)))- .sum::<usize>()+ GRAPH_NODE_OVERHEAD_BYTES+ + (0..=level)+ .map(|layer| {+ NEIGHBOR_LIST_OVERHEAD_BYTES+ + size_of_val(self.graph.neighbors_of(slot, layer))+ })+ .sum::<usize>()}).sum();vector_bytes + key_bytes + free_list_bytes + graph_bytes@@ -504,12 +561,46 @@ fn replay(log: &mut Log, dims: usize) -> Result<ReplayedState, VecDbError> {fn apply_outcome(graph: &mut Graph, arena: &VectorArena, outcome: UpsertOutcome) {match outcome {UpsertOutcome::NewSlot(slot) => graph.insert(slot, arena),- UpsertOutcome::RecycledSlot(_) | UpsertOutcome::ReplacedInPlace(_) => {- graph.reinsert(outcome.slot(), arena);+ UpsertOutcome::RecycledSlot(slot) | UpsertOutcome::ReplacedInPlace(slot) => {+ graph.reinsert(slot, arena);}}}+fn ensure_finite(key: &str, vector: &[f32]) -> Result<(), VecDbError> {+ if let Some(index) = vector.iter().position(|value| !value.is_finite()) {+ return Err(VecDbError::InvalidVector(format!(+ "component {index} of the vector for key {key:?} is not finite"+ )));+ }+ Ok(())+}++fn open_locked(file: File, path: &Path, dims: usize) -> Result<Log, VecDbError> {+ lock_exclusive(&file, path)?;+ Log::open(file, path, dims)+}++fn open_path_locked(path: &Path, dims: usize) -> Result<Log, VecDbError> {+ let file = File::options()+ .read(true)+ .write(true)+ .open(path)+ .map_err(|source| VecDbError::io(path, source))?;+ open_locked(file, path, dims)+}++fn promote_compacted_log(temp_path: &Path, path: &Path) -> Result<(), VecDbError> {+ rename_with_windows_fallback(temp_path, path)?;+ sync_parent_dir(path)+}++fn remove_index_files(path: &Path) -> Result<(), VecDbError> {+ remove_if_present(path)?;+ remove_snapshot(path)?;+ remove_stale_temp_sibling(path)+}+fn stage_live_entries(source: &VectorArena,target: &mut VectorArena,@@ -547,41 +638,19 @@ fn flush_stage_batch(Ok(())}-fn remove_if_present(path: &Path) -> Result<(), VecDbError> {- match std::fs::remove_file(path) {- Ok(()) => Ok(()),- Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),- Err(source) => Err(io_error(path, source)),- }-}--fn io_error(path: &Path, source: std::io::Error) -> VecDbError {- VecDbError::Io {- path: path.to_path_buf(),- source,- }-}-#[cfg(test)]mod tests {use std::fs;use tempfile::TempDir;+ use super::super::kernel::splitmix64;use super::*;const DIMS: usize = 16;const ADD_RECORD_LEN: u64 = 3 + 5 + (DIMS as u64) * 4 + 4;const TOMBSTONE_RECORD_LEN: u64 = 3 + 5 + 4;- fn splitmix64(state: &mut u64) -> u64 {- *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);- let mut z = *state;- z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);- z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);- z ^ (z >> 31)- }-fn seeded_unit_vector(seed: u64, dims: usize) -> Vec<f32> {let mut state = seed;let mut values: Vec<f32> = (0..dims)@@ -1399,22 +1468,165 @@ mod tests {}#[test]- fn open_of_a_short_file_fails_clean_without_altering_it() {+ fn writer_open_reinitializes_a_file_shorter_than_the_header() {let dir = TempDir::new().unwrap();let path = dir.path().join("db");let partial = [0x45u8, 0x56, 0x44, 0x42, 0x01, 0x00, 0x00];fs::write(&path, partial).unwrap();+ let mut db = open_writer(&path);+ assert!(db.is_empty());+ assert_eq!(db.stats().log_bytes, 32);+ db.add("fresh", &seeded_unit_vector(11, DIMS)).unwrap();+ drop(db);+ let reopened = open_writer(&path);+ assert_eq!(reopened.len(), 1);+ assert_own_nearest(&reopened, "fresh", &seeded_unit_vector(11, DIMS));+ }++ #[test]+ fn read_only_open_of_a_short_file_is_empty_and_unaltered() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ let partial = [0x45u8, 0x56, 0x44, 0x42, 0x01, 0x00, 0x00];+ fs::write(&path, partial).unwrap();+ let db = VecDb::open_read_only(&path, DIMS).unwrap();+ assert!(db.is_empty());+ assert_eq!(db.stats().log_bytes, 0);+ assert_eq!(fs::read(&path).unwrap(), partial);+ assert!(!snapshot_exists(&path));+ }++ #[test]+ 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());+ let old_generation = generation_of(&path);+ let temp = temp_sibling(&path);+ drop(Log::create(&temp, DIMS).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 = open_path_locked(&path, DIMS).unwrap();+ assert_eq!(log.generation(), new_generation);+ drop(log);+ assert!(matches!(+ promote_compacted_log(&temp, &path),+ Err(VecDbError::Io { .. })+ ));+ assert_eq!(generation_of(&path), new_generation);+ }++ #[test]+ fn restore_writer_mode_relocks_and_reenables_writes() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ let mut db = open_writer(&path);+ db.bulk_add(&bulk_entries(0, 3, 260)).unwrap();+ drop(db.take_writer_state().unwrap());+ assert!(matches!(db.mode, Mode::ReadOnly { .. }));+ db.restore_writer_mode(DIMS, None).unwrap();+ db.add("after", &seeded_unit_vector(4, DIMS)).unwrap();assert!(matches!(VecDb::open(&path, DIMS),- Err(VecDbError::Corrupt(_))+ Err(VecDbError::Locked(_))));- assert_eq!(fs::read(&path).unwrap(), partial);+ assert_eq!(db.len(), 4);+ drop(db);+ let reopened = open_writer(&path);+ assert_eq!(reopened.len(), 4);+ assert!(reopened.contains("after"));+ }++ #[test]+ fn restore_writer_mode_degrades_to_accurate_read_only_when_reopen_fails() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ let mut db = open_writer(&path);+ db.bulk_add(&bulk_entries(0, 3, 270)).unwrap();+ drop(db.take_writer_state().unwrap());+ let mut bytes = fs::read(&path).unwrap();+ bytes[20] ^= 0x5A;+ fs::write(&path, &bytes).unwrap();assert!(matches!(- VecDb::open_read_only(&path, DIMS),+ db.restore_writer_mode(DIMS, None),Err(VecDbError::Corrupt(_))));- assert_eq!(fs::read(&path).unwrap(), partial);- assert!(!snapshot_exists(&path));+ assert!(matches!(db.mode, Mode::ReadOnly { log_bytes } if log_bytes == bytes.len() as u64));+ assert_eq!(db.stats().log_bytes, bytes.len() as u64);+ let vector = seeded_unit_vector(5, DIMS);+ assert!(matches!(db.add("x", &vector), Err(VecDbError::ReadOnly)));+ }++ #[test]+ fn snapshot_failure_degrades_the_write_and_flush_still_errors() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ let mut db = open_writer(&path);+ db.add("seed", &seeded_unit_vector(1, DIMS)).unwrap();+ fs::create_dir(snapshot_path(&path)).unwrap();+ writer(&mut db).mutations_since_snapshot = 4999;+ db.record_mutations(1, Instant::now()).unwrap();+ assert_eq!(writer(&mut db).mutations_since_snapshot, 5000);+ assert!(matches!(db.flush(), Err(VecDbError::Io { .. })));+ db.add("more", &seeded_unit_vector(2, DIMS)).unwrap();+ drop(db);+ let reopened = open_writer(&path);+ assert_eq!(reopened.len(), 2);+ assert!(reopened.contains("seed"));+ assert!(reopened.contains("more"));+ }++ #[test]+ fn failed_compaction_keeps_the_write_ok_and_backs_off() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ let mut db = open_writer(&path);+ db.bulk_add(&bulk_entries(0, 100, 280)).unwrap();+ let generation_before = generation_of(&path);+ fs::create_dir(temp_sibling(&path)).unwrap();+ let removals: Vec<String> = (0..64).map(|index| format!("key-{index}")).collect();+ assert_eq!(db.bulk_remove(&removals).unwrap(), 64);+ assert_eq!(db.stats().dead_count, 128);+ assert_eq!(generation_of(&path), generation_before);+ db.add("probe", &seeded_unit_vector(7, DIMS)).unwrap();+ assert!(matches!(+ VecDb::open(&path, DIMS),+ Err(VecDbError::Locked(_))+ ));+ fs::remove_dir(temp_sibling(&path)).unwrap();+ db.bulk_add(&bulk_entries(64, 36, 290)).unwrap();+ assert_eq!(db.stats().dead_count, 164);+ assert_eq!(generation_of(&path), generation_before);+ db.bulk_add(&bulk_entries(64, 28, 295)).unwrap();+ assert_eq!(db.stats().dead_count, 0);+ assert_ne!(generation_of(&path), generation_before);+ drop(db);+ let reopened = open_writer(&path);+ assert_eq!(reopened.len(), 37);+ assert!(reopened.contains("probe"));+ assert!(reopened.contains("key-64"));+ assert!(!reopened.contains("key-0"));+ }++ #[test]+ fn open_succeeds_and_serves_data_when_the_snapshot_cannot_be_written() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ let mut db = open_writer(&path);+ db.bulk_add(&bulk_entries(0, 5, 300)).unwrap();+ drop(db);+ fs::create_dir(snapshot_path(&path)).unwrap();+ let mut db = open_writer(&path);+ assert_eq!(db.len(), 5);+ assert_own_nearest(&db, "key-2", &seeded_unit_vector(302, DIMS));+ assert!(matches!(db.flush(), Err(VecDbError::Io { .. })));+ drop(db);+ fs::remove_dir(snapshot_path(&path)).unwrap();+ drop(open_writer(&path));+ assert!(snapshot_exists(&path));}#[test]