diff --git a/CHANGELOG.md b/CHANGELOG.md index e80e16e2ef..1a5c903498 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Fixed +- Memory-backed Rust batches validate all vector dimensions before storing any - Count undirected edge weights once when scoring modularity in the npm graph helpers and returned minimum-cut partitions. Single-edge and disconnected-component scores now use the correct total edge weight. @@ -78,6 +79,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 skill and installs it into `.claude/skills` (Claude Code) and/or `.agents/skills` (Codex). `skills/` is now in the published files. ### Fixed +- Keep generated memory-storage IDs from overwriting live caller-selected rows, reserve explicit IDs in mixed batches, and refuse generated-counter wraparound while preserving intentional explicit upserts. +- Preserve current HNSW caller IDs across replacements and deletion, widen live top-k retrieval when obsolete graph rows crowd candidates, and repair stale reverse mappings when restoring older snapshots. - Every open-ended `>=` peer range is now bounded. `@ruvector/ruvllm >=2.0.0` resolved to 4.0.1, a different product published under the same name without the runtime that `ruvector llm` / `ruvector sona` load (`ruvllm.RuvLLM is diff --git a/crates/ruvector-core/src/index/hnsw.rs b/crates/ruvector-core/src/index/hnsw.rs index 200b4c0579..8320eb027f 100644 --- a/crates/ruvector-core/src/index/hnsw.rs +++ b/crates/ruvector-core/src/index/hnsw.rs @@ -199,7 +199,16 @@ impl HnswIndex { .collect(); let id_to_idx: DashMap = state.id_to_idx.into_iter().collect(); - let idx_to_id: DashMap = state.idx_to_id.into_iter().collect(); + // Older snapshots retained reverse mappings for replaced versions. + // Reconstruct only each live ID's canonical current graph position. + let idx_to_id: DashMap = state + .idx_to_id + .into_iter() + .filter(|(idx, id)| { + vectors_lookup.contains_key(id.as_str()) + && id_to_idx.get(id).is_some_and(|current| *current == *idx) + }) + .collect(); // Insert vectors into HNSW in index order for deterministic reconstruction. let mut sorted_entries: Vec<_> = idx_to_id diff --git a/crates/ruvector-core/src/storage_memory.rs b/crates/ruvector-core/src/storage_memory.rs index 0c1cf47df2..7634c0caeb 100644 --- a/crates/ruvector-core/src/storage_memory.rs +++ b/crates/ruvector-core/src/storage_memory.rs @@ -5,8 +5,9 @@ use crate::error::{Result, RuvectorError}; use crate::types::{VectorEntry, VectorId}; -use dashmap::DashMap; +use dashmap::{mapref::entry::Entry, DashMap}; use serde_json::Value as JsonValue; +use std::collections::HashSet; use std::sync::atomic::{AtomicU64, Ordering}; /// In-memory storage backend using DashMap for thread-safe concurrent access @@ -30,10 +31,35 @@ impl MemoryStorage { }) } - /// Generate a new unique ID - fn generate_id(&self) -> String { - let id = self.counter.fetch_add(1, Ordering::SeqCst); - format!("vec_{}", id) + /// Generate a candidate without wrapping into previously allocated IDs. + fn generate_id(&self) -> Result { + let id = self + .counter + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |id| id.checked_add(1)) + .map_err(|_| { + RuvectorError::StorageError("Generated vector ID space exhausted".into()) + })?; + Ok(format!("vec_{}", id)) + } + + fn insert_vector(&self, entry: &VectorEntry, reserved: &HashSet<&str>) -> Result { + if let Some(id) = &entry.id { + // Caller-selected IDs retain their intentional upsert semantics. + self.vectors.insert(id.clone(), entry.vector.clone()); + return Ok(id.clone()); + } + loop { + let id = self.generate_id()?; + if reserved.contains(id.as_str()) { + continue; + } + // Claim the vector slot atomically, rather than checking then + // overwriting a caller ID inserted by a concurrent operation. + if let Entry::Vacant(slot) = self.vectors.entry(id.clone()) { + slot.insert(entry.vector.clone()); + return Ok(id); + } + } } /// Insert a vector entry @@ -45,10 +71,7 @@ impl MemoryStorage { }); } - let id = entry.id.clone().unwrap_or_else(|| self.generate_id()); - - // Insert vector - self.vectors.insert(id.clone(), entry.vector.clone()); + let id = self.insert_vector(entry, &HashSet::new())?; // Insert metadata if present if let Some(metadata) = &entry.metadata { @@ -68,8 +91,8 @@ impl MemoryStorage { /// Insert multiple vectors in a batch pub fn insert_batch(&self, entries: &[VectorEntry]) -> Result> { - let mut ids = Vec::with_capacity(entries.len()); - + // Reject the entire batch before allocating IDs or changing stored rows. + // VectorDB updates its search index only after this method succeeds. for entry in entries { if entry.vector.len() != self.dimensions { return Err(RuvectorError::DimensionMismatch { @@ -77,10 +100,16 @@ impl MemoryStorage { actual: entry.vector.len(), }); } + } - let id = entry.id.clone().unwrap_or_else(|| self.generate_id()); + let mut ids = Vec::with_capacity(entries.len()); + let reserved: HashSet<&str> = entries + .iter() + .filter_map(|entry| entry.id.as_deref()) + .collect(); - self.vectors.insert(id.clone(), entry.vector.clone()); + for entry in entries { + let id = self.insert_vector(entry, &reserved)?; if let Some(metadata) = &entry.metadata { self.metadata.insert( @@ -176,6 +205,34 @@ mod tests { use super::*; use std::collections::HashMap; + #[test] + fn exhausted_generated_ids_do_not_wrap_or_replace_existing_rows() { + let storage = MemoryStorage::new(2).unwrap(); + let existing = VectorEntry { + id: Some("vec_0".into()), + vector: vec![1.0, 0.0], + metadata: None, + }; + storage.insert(&existing).unwrap(); + storage.counter.store(u64::MAX, Ordering::SeqCst); + let generated = VectorEntry { + id: None, + vector: vec![2.0, 0.0], + metadata: None, + }; + assert!(matches!( + storage.insert(&generated), + Err(RuvectorError::StorageError(_)) + )); + assert_eq!(storage.counter.load(Ordering::SeqCst), u64::MAX); + assert_eq!(storage.len().unwrap(), 1); + assert_eq!( + storage.get("vec_0").unwrap().unwrap().vector, + existing.vector + ); + assert_eq!(storage.insert(&existing).unwrap(), "vec_0"); + } + #[test] fn test_insert_and_get() { let storage = MemoryStorage::new(128).unwrap(); diff --git a/crates/ruvector-core/tests/fixtures/hnsw-legacy-replacement.bin b/crates/ruvector-core/tests/fixtures/hnsw-legacy-replacement.bin new file mode 100644 index 0000000000..fc927b5455 Binary files /dev/null and b/crates/ruvector-core/tests/fixtures/hnsw-legacy-replacement.bin differ diff --git a/crates/ruvector-core/tests/fixtures/hnsw-legacy-replacement.md b/crates/ruvector-core/tests/fixtures/hnsw-legacy-replacement.md new file mode 100644 index 0000000000..a87f3d3ab8 --- /dev/null +++ b/crates/ruvector-core/tests/fixtures/hnsw-legacy-replacement.md @@ -0,0 +1,5 @@ +# Legacy replacement snapshot + +`hnsw-legacy-replacement.bin` was generated by the public `HnswIndex::serialize` API on original repository revision `07933730fac709457e0c5f41444c9a4adc505aee` using Euclidean distance, dimension 2, m=8, ef_construction=100, ef_search=100 and max_elements=100. + +The generator inserts `changed` at `[1, 0]`, replaces it with `[100, 0]`, then inserts `keeper` at `[2, 0]`. Original search at `[1, 0]` returns `(changed, 0)`, `(keeper, 1)`, `(changed, 99)`. The fixture tests restoration of an actual old-format replacement snapshot rather than constructing serialization bytes by hand. It contains only synthetic vectors and IDs. diff --git a/crates/ruvector-core/tests/hnsw_live_replacements.rs b/crates/ruvector-core/tests/hnsw_live_replacements.rs new file mode 100644 index 0000000000..6e922d04c2 --- /dev/null +++ b/crates/ruvector-core/tests/hnsw_live_replacements.rs @@ -0,0 +1,143 @@ +//! Replacements and deletes must expose only current live HNSW rows. +#![cfg(feature = "hnsw")] +use ruvector_core::index::{hnsw::HnswIndex, VectorIndex}; +use ruvector_core::types::{DistanceMetric, HnswConfig}; + +fn index() -> HnswIndex { + HnswIndex::new( + 2, + DistanceMetric::Euclidean, + HnswConfig { + m: 8, + ef_construction: 100, + ef_search: 100, + max_elements: 100, + }, + ) + .unwrap() +} + +#[test] +fn replacement_returns_only_the_latest_vector_score() { + let mut index = index(); + index.add("changed".into(), vec![1.0, 0.0]).unwrap(); + index.add("changed".into(), vec![100.0, 0.0]).unwrap(); + index.add("keeper".into(), vec![2.0, 0.0]).unwrap(); + let hits = index.search(&[1.0, 0.0], 3).unwrap(); + assert_eq!(hits.len(), 2, "one result per live caller ID"); + assert_eq!(hits[0].id, "keeper"); + assert_eq!(hits[0].score, 1.0); + assert_eq!(hits[1].id, "changed"); + assert_eq!(hits[1].score, 99.0); + assert_eq!(index.len(), 2); +} + +#[test] +fn deleting_a_replaced_id_removes_all_searchable_versions() { + let mut index = index(); + index.add("changed".into(), vec![1.0, 0.0]).unwrap(); + index.add("changed".into(), vec![100.0, 0.0]).unwrap(); + index.add("keeper".into(), vec![2.0, 0.0]).unwrap(); + assert!(index.remove(&"changed".into()).unwrap()); + let hits = index.search(&[1.0, 0.0], 3).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].id, "keeper"); + assert!(!index.remove(&"changed".into()).unwrap()); + assert_eq!(index.len(), 1); +} + +#[test] +fn repeated_ids_in_a_batch_keep_only_the_final_version() { + let mut index = index(); + index + .add_batch(vec![ + ("changed".into(), vec![1.0, 0.0]), + ("changed".into(), vec![100.0, 0.0]), + ("keeper".into(), vec![2.0, 0.0]), + ]) + .unwrap(); + let hits = index.search(&[1.0, 0.0], 3).unwrap(); + assert_eq!( + hits.iter().map(|hit| hit.id.as_str()).collect::>(), + vec!["keeper", "changed"] + ); + assert_eq!(hits[1].score, 99.0); + assert_eq!(index.len(), 2); +} + +#[test] +fn deleted_nearby_graph_nodes_do_not_underfill_live_top_k() { + let mut index = index(); + index + .add_batch( + (0..8) + .map(|i| (i.to_string(), vec![i as f32, 0.0])) + .collect(), + ) + .unwrap(); + for i in 0..6 { + assert!(index.remove(&i.to_string()).unwrap()); + } + let hits = index.search_with_ef(&[0.0, 0.0], 2, 1).unwrap(); + assert_eq!( + hits.iter().map(|hit| hit.id.as_str()).collect::>(), + vec!["6", "7"] + ); + assert_eq!( + hits.iter().map(|hit| hit.score).collect::>(), + vec![6.0, 7.0] + ); +} + +#[test] +fn replacement_roundtrip_keeps_unique_latest_ids() { + let mut index = index(); + index.add("changed".into(), vec![1.0, 0.0]).unwrap(); + index.add("changed".into(), vec![100.0, 0.0]).unwrap(); + index.add("keeper".into(), vec![2.0, 0.0]).unwrap(); + let restored = HnswIndex::deserialize(&index.serialize().unwrap()).unwrap(); + let hits = restored.search(&[1.0, 0.0], 3).unwrap(); + assert_eq!( + hits.iter().map(|hit| hit.id.as_str()).collect::>(), + vec!["keeper", "changed"] + ); + assert_eq!(hits[1].score, 99.0); +} + +#[test] +fn ordinary_search_and_empty_live_index_keep_existing_behavior() { + let mut index = index(); + assert!(index.search(&[0.0, 0.0], 3).unwrap().is_empty()); + index + .add_batch(vec![ + ("near".into(), vec![1.0, 0.0]), + ("far".into(), vec![2.0, 0.0]), + ]) + .unwrap(); + assert_eq!(index.search(&[0.0, 0.0], 1).unwrap()[0].id, "near"); + assert!(index.search(&[0.0, 0.0], 0).unwrap().is_empty()); + assert!(index.search(&[0.0], 1).is_err()); + assert!(index.remove(&"near".into()).unwrap()); + assert!(index.remove(&"far".into()).unwrap()); + assert!(index.search(&[0.0, 0.0], 3).unwrap().is_empty()); +} + +#[test] +fn legacy_replacement_snapshot_restores_only_canonical_live_rows() { + let mut restored = + HnswIndex::deserialize(include_bytes!("fixtures/hnsw-legacy-replacement.bin")).unwrap(); + let hits = restored.search(&[1.0, 0.0], 3).unwrap(); + assert_eq!( + hits.iter().map(|hit| hit.id.as_str()).collect::>(), + vec!["keeper", "changed"] + ); + assert_eq!(hits[1].score, 99.0); + assert!(restored.remove(&"changed".into()).unwrap()); + restored.add("new".into(), vec![3.0, 0.0]).unwrap(); + let hits = restored.search(&[1.0, 0.0], 3).unwrap(); + assert_eq!( + hits.iter().map(|hit| hit.id.as_str()).collect::>(), + vec!["keeper", "new"] + ); + assert_eq!(restored.len(), 2); +} diff --git a/crates/ruvector-core/tests/memory_batch_validation.rs b/crates/ruvector-core/tests/memory_batch_validation.rs new file mode 100644 index 0000000000..15a7f5d963 --- /dev/null +++ b/crates/ruvector-core/tests/memory_batch_validation.rs @@ -0,0 +1,125 @@ +//! Dimension errors must not leave memory storage ahead of the search index. +use ruvector_core::{ + types::{DbOptions, DistanceMetric, SearchQuery, VectorEntry}, + vector_db::VectorDB, +}; + +fn database() -> VectorDB { + VectorDB::new(DbOptions { + dimensions: 2, + distance_metric: DistanceMetric::Euclidean, + storage_path: "memory://batch-validation".into(), + hnsw_config: None, + quantization: None, + }) + .unwrap() +} + +fn entry(id: Option<&str>, vector: Vec) -> VectorEntry { + VectorEntry { + id: id.map(str::to_owned), + vector, + metadata: None, + } +} + +fn search_ids(db: &VectorDB) -> Vec { + db.search(SearchQuery { + vector: vec![1.0, 0.0], + k: 10, + filter: None, + ef_search: None, + }) + .unwrap() + .into_iter() + .map(|hit| hit.id) + .collect() +} + +#[test] +fn rejected_batch_does_not_leave_a_storage_only_prefix() { + let db = database(); + db.insert(entry(Some("seed"), vec![1.0, 0.0])).unwrap(); + let result = db.insert_batch([ + entry(Some("prefix"), vec![0.0, 1.0]), + entry(Some("invalid"), vec![1.0]), + ]); + assert!(result.is_err()); + assert!( + db.get("prefix").unwrap().is_none(), + "rejected batch must not store its valid prefix" + ); + assert_eq!(db.len().unwrap(), 1); + assert_eq!(search_ids(&db), vec!["seed"]); + assert!(db.get("invalid").unwrap().is_none()); +} + +#[test] +fn rejected_batch_preserves_an_existing_vector_and_metadata() { + let db = database(); + let mut seed = entry(Some("seed"), vec![1.0, 0.0]); + seed.metadata = Some(std::collections::HashMap::from([( + "version".into(), + serde_json::json!("old"), + )])); + db.insert(seed).unwrap(); + let mut replacement = entry(Some("seed"), vec![0.0, 1.0]); + replacement.metadata = Some(std::collections::HashMap::from([( + "version".into(), + serde_json::json!("new"), + )])); + assert!(db + .insert_batch([replacement, entry(Some("invalid"), vec![1.0])]) + .is_err()); + let stored = db.get("seed").unwrap().unwrap(); + assert_eq!( + stored.vector, + vec![1.0, 0.0], + "rejected batch must preserve its pre-existing vector" + ); + assert_eq!( + stored.metadata.unwrap()["version"], + serde_json::json!("old") + ); + assert_eq!(search_ids(&db), vec!["seed"]); +} + +#[test] +fn rejected_batch_does_not_consume_generated_ids() { + let db = database(); + assert!(db + .insert_batch([entry(None, vec![1.0, 0.0]), entry(None, vec![1.0])]) + .is_err()); + assert_eq!( + db.insert(entry(None, vec![1.0, 0.0])).unwrap(), + "vec_0", + "rejected batch must not allocate ids" + ); + assert_eq!(db.len().unwrap(), 1); +} + +#[test] +fn invalid_first_entry_and_empty_batch_preserve_storage() { + let db = database(); + assert!(db + .insert_batch([entry(None, vec![1.0]), entry(None, vec![1.0, 0.0])]) + .is_err()); + assert_eq!(db.len().unwrap(), 0); + assert!(db + .insert_batch(Vec::::new()) + .unwrap() + .is_empty()); + assert_eq!(db.len().unwrap(), 0); +} + +#[test] +fn valid_batch_remains_available_to_storage_and_search() { + let db = database(); + let ids = db + .insert_batch([entry(None, vec![1.0, 0.0]), entry(None, vec![0.0, 1.0])]) + .unwrap(); + assert_eq!(ids, vec!["vec_0", "vec_1"]); + assert_eq!(db.len().unwrap(), 2); + assert_eq!(search_ids(&db), ids); + assert_eq!(db.get("vec_1").unwrap().unwrap().vector, vec![0.0, 1.0]); +} diff --git a/crates/ruvector-core/tests/memory_generated_ids.rs b/crates/ruvector-core/tests/memory_generated_ids.rs new file mode 100644 index 0000000000..59ff4c9911 --- /dev/null +++ b/crates/ruvector-core/tests/memory_generated_ids.rs @@ -0,0 +1,107 @@ +//! Generated IDs must not replace caller-owned rows. +use ruvector_core::{ + types::{DbOptions, DistanceMetric, SearchQuery, VectorEntry}, + vector_db::VectorDB, +}; +fn database() -> VectorDB { + VectorDB::new(DbOptions { + dimensions: 2, + distance_metric: DistanceMetric::Euclidean, + storage_path: "memory://generated-ids".into(), + hnsw_config: None, + quantization: None, + }) + .unwrap() +} +fn entry(id: Option<&str>, x: f32) -> VectorEntry { + VectorEntry { + id: id.map(str::to_owned), + vector: vec![x, 0.0], + metadata: Some(std::collections::HashMap::from([( + "marker".into(), + serde_json::json!(x), + )])), + } +} +#[test] +fn default_insert_preserves_a_live_caller_id_and_its_metadata() { + let db = database(); + db.insert(entry(Some("vec_0"), 1.0)).unwrap(); + let generated = db.insert(entry(None, 2.0)).unwrap(); + assert_ne!(generated, "vec_0"); + assert_eq!(db.len().unwrap(), 2); + let kept = db.get("vec_0").unwrap().unwrap(); + assert_eq!(kept.vector, vec![1.0, 0.0]); + assert_eq!(kept.metadata.unwrap()["marker"], serde_json::json!(1.0)); + let hits = db + .search(SearchQuery { + vector: vec![0.0, 0.0], + k: 2, + filter: None, + ef_search: None, + }) + .unwrap(); + assert_eq!(hits.len(), 2); + assert_ne!(hits[0].id, hits[1].id); +} +#[test] +fn batch_defaults_preserve_preexisting_caller_rows() { + let db = database(); + db.insert(entry(Some("vec_0"), 1.0)).unwrap(); + let ids = db + .insert_batch([entry(None, 2.0), entry(None, 3.0)]) + .unwrap(); + assert!(!ids.iter().any(|id| id == "vec_0")); + assert_ne!(ids[0], ids[1]); + assert_eq!(db.len().unwrap(), 3); + assert_eq!(db.get("vec_0").unwrap().unwrap().vector, vec![1.0, 0.0]); +} +#[test] +fn generated_batch_names_do_not_collide_with_later_declared_ids() { + let db = database(); + let ids = db + .insert_batch([entry(None, 1.0), entry(Some("vec_0"), 2.0)]) + .unwrap(); + assert_ne!(ids[0], ids[1]); + assert_eq!(ids[1], "vec_0"); + assert_eq!(db.len().unwrap(), 2); + assert_eq!(db.get(&ids[0]).unwrap().unwrap().vector, vec![1.0, 0.0]); +} +#[test] +fn explicit_upsert_and_normal_default_allocation_remain_supported() { + let db = database(); + let id = db.insert(entry(None, 1.0)).unwrap(); + assert_eq!(id, "vec_0"); + assert_eq!(db.insert(entry(Some(&id), 2.0)).unwrap(), id); + assert_eq!(db.len().unwrap(), 1); + assert_eq!(db.get(&id).unwrap().unwrap().vector, vec![2.0, 0.0]); + assert_eq!(db.insert(entry(None, 3.0)).unwrap(), "vec_1"); +} +#[test] +fn concurrent_generated_inserts_preserve_preexisting_ids() { + let storage = + std::sync::Arc::new(ruvector_core::storage_memory::MemoryStorage::new(2).unwrap()); + for i in 0..8 { + storage + .insert(&entry(Some(&format!("vec_{i}")), i as f32)) + .unwrap(); + } + let threads = (0..16) + .map(|i| { + let storage = storage.clone(); + std::thread::spawn(move || storage.insert(&entry(None, 100.0 + i as f32)).unwrap()) + }) + .collect::>(); + let ids = threads + .into_iter() + .map(|t| t.join().unwrap()) + .collect::>(); + assert_eq!(ids.len(), 16); + assert_eq!(storage.len().unwrap(), 24); + for i in 0..8 { + assert_eq!( + storage.get(&format!("vec_{i}")).unwrap().unwrap().vector, + vec![i as f32, 0.0] + ); + } +} diff --git a/crates/ruvector-graph/src/graph.rs b/crates/ruvector-graph/src/graph.rs index 8bb9883647..671d1cb897 100644 --- a/crates/ruvector-graph/src/graph.rs +++ b/crates/ruvector-graph/src/graph.rs @@ -8,7 +8,7 @@ use crate::node::Node; #[cfg(feature = "storage")] use crate::storage::GraphStorage; use crate::types::{EdgeId, NodeId, PropertyValue}; -use dashmap::DashMap; +use dashmap::{mapref::entry::Entry, DashMap}; #[cfg(feature = "storage")] use std::path::Path; use std::sync::Arc; @@ -107,19 +107,30 @@ impl GraphDB { pub fn create_node(&self, node: Node) -> Result { let id = node.id.clone(); - // Update indexes - self.label_index.add_node(&node); - self.property_index.add_node(&node); + // Serialize replacement of one ID, preserving its existing upsert behavior. + let entry = self.nodes.entry(id.clone()); - // Insert into memory - self.nodes.insert(id.clone(), node.clone()); - - // Persist to storage if available + // A storage error must not change live objects or their index memberships. #[cfg(feature = "storage")] if let Some(storage) = &self.storage { storage.insert_node(&node)?; } + if let Entry::Occupied(ref occupied) = entry { + self.label_index.remove_node(occupied.get()); + self.property_index.remove_node(occupied.get()); + } + self.label_index.add_node(&node); + self.property_index.add_node(&node); + match entry { + Entry::Occupied(mut occupied) => { + occupied.insert(node); + } + Entry::Vacant(vacant) => { + vacant.insert(node); + } + } + Ok(id) } @@ -312,19 +323,30 @@ impl GraphDB { )); } - // Update indexes - self.edge_type_index.add_edge(&edge); - self.adjacency_index.add_edge(&edge); - - // Insert into memory - self.edges.insert(id.clone(), edge.clone()); + // Serialize replacement of one ID, preserving its existing upsert behavior. + let entry = self.edges.entry(id.clone()); - // Persist to storage if available + // A storage error must not change live objects or their index memberships. #[cfg(feature = "storage")] if let Some(storage) = &self.storage { storage.insert_edge(&edge)?; } + if let Entry::Occupied(ref occupied) = entry { + self.edge_type_index.remove_edge(occupied.get()); + self.adjacency_index.remove_edge(occupied.get()); + } + self.edge_type_index.add_edge(&edge); + self.adjacency_index.add_edge(&edge); + match entry { + Entry::Occupied(mut occupied) => { + occupied.insert(edge); + } + Entry::Vacant(vacant) => { + vacant.insert(edge); + } + } + Ok(id) } @@ -451,18 +473,28 @@ impl GraphDB { } } - // Update index - self.hyperedge_node_index.add_hyperedge(&hyperedge); - - // Insert into memory - self.hyperedges.insert(id.clone(), hyperedge.clone()); + // Serialize replacement of one ID, preserving its existing upsert behavior. + let entry = self.hyperedges.entry(id.clone()); - // Persist to storage if available + // A storage error must not change live objects or their index memberships. #[cfg(feature = "storage")] if let Some(storage) = &self.storage { storage.insert_hyperedge(&hyperedge)?; } + if let Entry::Occupied(ref occupied) = entry { + self.hyperedge_node_index.remove_hyperedge(occupied.get()); + } + self.hyperedge_node_index.add_hyperedge(&hyperedge); + match entry { + Entry::Occupied(mut occupied) => { + occupied.insert(hyperedge); + } + Entry::Vacant(vacant) => { + vacant.insert(hyperedge); + } + } + Ok(id) } diff --git a/crates/ruvector-graph/tests/node_replacement_indexes.rs b/crates/ruvector-graph/tests/node_replacement_indexes.rs new file mode 100644 index 0000000000..a523a4d2de --- /dev/null +++ b/crates/ruvector-graph/tests/node_replacement_indexes.rs @@ -0,0 +1,191 @@ +use ruvector_graph::{GraphDB, NodeBuilder, PropertyValue}; + +#[test] +fn replacement_removes_old_label_and_property_membership() { + let db = GraphDB::new(); + db.create_node( + NodeBuilder::new() + .id("same") + .label("Old") + .property("state", "old") + .build(), + ) + .unwrap(); + db.create_node( + NodeBuilder::new() + .id("same") + .label("New") + .property("state", "new") + .build(), + ) + .unwrap(); + assert!(db.get_nodes_by_label("Old").is_empty()); + assert!(db + .get_nodes_by_property("state", &PropertyValue::from("old")) + .is_empty()); + assert_eq!(db.get_nodes_by_label("New").len(), 1); + assert_eq!( + db.get_nodes_by_property("state", &PropertyValue::from("new")) + .len(), + 1 + ); +} + +#[test] +fn deleting_replacement_leaves_no_index_ghosts() { + let db = GraphDB::new(); + db.create_node( + NodeBuilder::new() + .id("same") + .label("Old") + .property("state", "old") + .build(), + ) + .unwrap(); + db.create_node( + NodeBuilder::new() + .id("same") + .label("New") + .property("state", "new") + .build(), + ) + .unwrap(); + db.delete_node("same").unwrap(); + assert!(db.node_ids_by_label("Old").is_empty()); + assert!(db.node_ids_by_label("New").is_empty()); +} + +#[test] +fn ordinary_creation_and_explicit_update_control() { + let db = GraphDB::new(); + db.create_node( + NodeBuilder::new() + .id("one") + .label("One") + .property("state", "old") + .build(), + ) + .unwrap(); + db.create_node(NodeBuilder::new().id("two").label("Two").build()) + .unwrap(); + db.update_node("one", |node| { + node.set_property("state", PropertyValue::from("new")) + }) + .unwrap(); + assert_eq!(db.get_nodes_by_label("One").len(), 1); + assert_eq!(db.get_nodes_by_label("Two").len(), 1); + assert!(db + .get_nodes_by_property("state", &PropertyValue::from("old")) + .is_empty()); +} + +#[test] +fn edge_replacement_refreshes_type_and_adjacency() { + use ruvector_graph::EdgeBuilder; + let db = GraphDB::new(); + for id in ["a", "b", "c"] { + db.create_node(NodeBuilder::new().id(id).build()).unwrap(); + } + db.create_edge( + EdgeBuilder::new("a".into(), "b".into(), "OLD") + .id("same-edge") + .build(), + ) + .unwrap(); + db.create_edge( + EdgeBuilder::new("c".into(), "b".into(), "NEW") + .id("same-edge") + .build(), + ) + .unwrap(); + assert!(db.get_edges_by_type("OLD").is_empty()); + assert!(db.get_outgoing_edges(&"a".to_string()).is_empty()); + assert_eq!(db.get_edges_by_type("NEW").len(), 1); + assert_eq!(db.get_outgoing_edges(&"c".to_string()).len(), 1); +} + +#[test] +fn hyperedge_replacement_refreshes_membership() { + use ruvector_graph::Hyperedge; + let db = GraphDB::new(); + for id in ["a", "b", "c"] { + db.create_node(NodeBuilder::new().id(id).build()).unwrap(); + } + db.create_hyperedge(Hyperedge::with_id( + "same-hyperedge".into(), + vec!["a".into(), "b".into()], + "OLD", + )) + .unwrap(); + db.create_hyperedge(Hyperedge::with_id( + "same-hyperedge".into(), + vec!["b".into(), "c".into()], + "NEW", + )) + .unwrap(); + assert!(db.get_hyperedges_by_node(&"a".to_string()).is_empty()); + assert_eq!(db.get_hyperedges_by_node(&"c".to_string()).len(), 1); +} + +#[test] +fn concurrent_replacements_leave_only_live_memberships() { + use std::sync::{Arc, Barrier}; + let db = Arc::new(GraphDB::new()); + let barrier = Arc::new(Barrier::new(8)); + let threads: Vec<_> = (0..8) + .map(|i| { + let db = db.clone(); + let barrier = barrier.clone(); + std::thread::spawn(move || { + barrier.wait(); + db.create_node( + NodeBuilder::new() + .id("same") + .label(format!("Label{i}")) + .property("version", i as i64) + .build(), + ) + .unwrap(); + }) + }) + .collect(); + for thread in threads { + thread.join().unwrap(); + } + let live = db.get_node("same").unwrap(); + for i in 0..8 { + assert_eq!( + db.get_nodes_by_label(&format!("Label{i}")).len(), + usize::from(live.has_label(&format!("Label{i}"))) + ); + let expected = PropertyValue::from(i as i64); + assert_eq!( + db.get_nodes_by_property("version", &expected).len(), + usize::from(live.get_property("version") == Some(&expected)) + ); + } +} + +#[test] +fn invalid_relationship_replacement_preserves_existing_control() { + use ruvector_graph::EdgeBuilder; + let db = GraphDB::new(); + for id in ["a", "b"] { + db.create_node(NodeBuilder::new().id(id).build()).unwrap(); + } + db.create_edge( + EdgeBuilder::new("a".into(), "b".into(), "OLD") + .id("edge") + .build(), + ) + .unwrap(); + assert!(db + .create_edge( + EdgeBuilder::new("missing".into(), "b".into(), "NEW") + .id("edge") + .build() + ) + .is_err()); + assert_eq!(db.get_edges_by_type("OLD").len(), 1); + assert_eq!(db.get_outgoing_edges(&"a".to_string()).len(), 1); +} diff --git a/crates/ruvector-py/src/graph.rs b/crates/ruvector-py/src/graph.rs index 58ff266b8a..c90c9e5de3 100644 --- a/crates/ruvector-py/src/graph.rs +++ b/crates/ruvector-py/src/graph.rs @@ -63,11 +63,10 @@ impl GraphDB { /// `properties` (an arbitrary JSON-compatible dict, default none). /// /// `id`, if given, must not already exist. The real - /// `GraphDB::create_node` has no such guard: it silently `insert`s - /// over an existing id while adding (not replacing) the new node's - /// labels/properties into the label/property indexes, leaving the old - /// node's index entries stale. Pre-checking here and raising instead - /// turns that footgun into a clear error at the Python boundary. When + /// `GraphDB::create_node` supports replacing an existing id while + /// refreshing its label/property indexes. This Python create-only + /// interface deliberately rejects replacement rather than changing an + /// existing node through a method named create_node. When /// `id` is omitted, the real `NodeBuilder` behaviour applies: a fresh /// UUID is generated. /// diff --git a/docs/adr/ADR-core-hnsw-live-replacements.md b/docs/adr/ADR-core-hnsw-live-replacements.md new file mode 100644 index 0000000000..f49f8c57cf --- /dev/null +++ b/docs/adr/ADR-core-hnsw-live-replacements.md @@ -0,0 +1,23 @@ +# ADR: Preserve current caller identity through HNSW replacements + +## Status + +Accepted for this implementation; exact-revision independent review and scoped checks are required before publication. + +## Context + +The public HNSW index accepts repeated caller IDs as updates. Its forward ID map and current vector were replaced, but obsolete reverse mappings remained searchable. Searches could return an ID twice with its old score; deleting that ID could leave its old version searchable. Removed physical graph rows could also crowd live rows out of a requested top-k. Older serialized snapshots retained the same stale reverse mappings. + +## Decision + +Invalidate the previous reverse mapping on successful single and batch replacement. Keep the underlying graph's allocated rows and existing binary format. Restore only reverse mappings matching the live vector and canonical forward mapping when loading snapshots. + +Hold one read lock while searching. Start with the caller's original k/ef behavior and widen candidate count by bounded doubling when historical positions underfill live results, up to the finite allocated graph-position count. Return at most min(k, live count) current IDs. This does not turn approximate nearest-neighbor search into an exact scan or rebuild. + +## Tradeoffs + +Replacement/deletion-heavy indexes may traverse substantially more historical graph positions, with a correspondingly larger ef. Worst-case candidate expansion approaches the allocated graph size. The unchanged physical graph still consumes memory until reconstruction; this change repairs public identity and underfilled retrieval without adding concurrent graph compaction. The read lock freezes mappings during bounded retries. + +## Validation + +Seven public Rust regressions cover single/batch replacement, deletion after replacement, top-k underfill, current serialization round-trip, a binary snapshot generated by the original source, and ordinary/empty/dimension-error controls. Original source fails six cases and passes the control. The original snapshot contains changed@1, changed@100 and keeper@2 and returns changed twice; fixture provenance is recorded in tests/fixtures/hnsw-legacy-replacement.md. Scoped fixed tests and broader checks are recorded separately before publication; no cross-platform or hosted-CI claim is made. diff --git a/docs/adr/ADR-core-memory-batch-validation.md b/docs/adr/ADR-core-memory-batch-validation.md new file mode 100644 index 0000000000..23830d4bba --- /dev/null +++ b/docs/adr/ADR-core-memory-batch-validation.md @@ -0,0 +1,40 @@ +# ADR: Validate memory batches before mutating storage + +## Status + +Accepted for this implementation; publication requires independent revision review. + +## Context + +`VectorDB::insert_batch` first stores its entries and updates the search index +only after storage succeeds. The persistent backend aborts its redb write +transaction on a dimension error. `MemoryStorage` instead validated and stored +one entry at a time. A valid prefix followed by a wrong-dimensional vector +therefore returned an error after adding storage-only rows, overwriting existing +vectors/metadata, or consuming automatically generated IDs. The search index +retained its prior state. + +The public Rust memory database reproduces all three effects. The Python HNSW +wrapper uses a rectangular array and validates metadata before insertion; it +cannot produce this mixed-dimension batch. This change addresses the Rust API. + +## Decision + +Validate dimensions for every entry before generating IDs or changing the +memory maps. Retain the existing error type, mutation order for accepted +batches, and public API. This adds one O(n) pass over vector lengths, uses O(1) +additional memory, and does not copy vector data during validation. + +## Limits + +This is an all-or-nothing boundary for dimension validation, not a transaction +covering concurrent readers, allocator failures, or arbitrary later index +errors. No memory map locking or persistent storage format changes are added. + +## Validation + +Five public `VectorDB` tests cover an invalid later entry, attempted overwrite +of an existing row and its metadata, generated-ID preservation, an invalid +first entry/empty batch, and successful storage plus search. Original source +fails the first three regressions and passes both controls; fixed source passes +all five. Native Rust execution uses the offline, locked current workspace. diff --git a/docs/adr/ADR-core-memory-generated-ids.md b/docs/adr/ADR-core-memory-generated-ids.md new file mode 100644 index 0000000000..6b8f01b42f --- /dev/null +++ b/docs/adr/ADR-core-memory-generated-ids.md @@ -0,0 +1,23 @@ +# ADR: Claim vacant memory-storage IDs for generated inserts + +## Status + +Accepted for this implementation; exact-revision independent review and scoped checks are required before publication. + +## Context + +Memory storage labels its counter-based IDs as unique, but explicit IDs do not advance that counter. Inserting a caller-owned vec_0 followed by an ID-less vector therefore overwrites the existing vector and metadata. The same collision occurs in batches and with concurrent generated inserts. A batch containing an ID-less entry before an explicit vec_0 reports duplicate IDs and loses a row. + +## Decision + +Retain explicit-ID upserts. For generated IDs, advance the counter with checked arithmetic and atomically claim a vacant DashMap vector entry. Skip occupied IDs rather than separately checking then overwriting them. Within a batch, skip every explicitly declared ID, including IDs appearing later in the batch. Refuse counter exhaustion rather than wrapping to zero. + +This reserves the vector slot at insertion time. A future explicit insert can intentionally upsert that ID; it is not excluded forever. Metadata behavior and the existing storage/index boundary are unchanged. This change does not add a transaction across the vector map, metadata map, or subsequent indexing. + +## Tradeoffs + +An ID-less insert may probe several occupied or batch-reserved names. Each rejected name advances the monotonic counter; the work is bounded by the finite counter space and does not wait on occupied IDs. Batch reservation uses O(m) auxiliary references for m distinct declared IDs. Generated values range from zero through u64::MAX - 1; exhaustion at the terminal counter returns a storage error, while explicit inserts remain supported. Ordinary collision-free generated IDs retain their existing format and sequence. + +## Validation + +Five real public Rust cases cover single and batch collisions, later explicit IDs in a mixed batch, sixteen concurrent inserts around eight preexisting caller IDs, and normal allocation plus intentional explicit upserts. Original source fails four cases and passes the control; fixed source passes all five. A controlled private-counter boundary test demonstrates original wraparound behavior and fixed refusal without changing the old row. Broader scoped checks and exact-binary/source bindings are recorded before publication. No cross-platform or full transaction claim is made. diff --git a/docs/adr/graph-replacement-index-consistency.md b/docs/adr/graph-replacement-index-consistency.md new file mode 100644 index 0000000000..ee24db5692 --- /dev/null +++ b/docs/adr/graph-replacement-index-consistency.md @@ -0,0 +1,19 @@ +# Refresh graph indexes when replacing node, edge or hyperedge IDs + +Status: proposed for review + +## Problem and evidence + +The public Rust create_node/create_edge/create_hyperedge methods currently replace objects with matching IDs while only adding new index memberships. Old labels/properties, relationship types/adjacency and hyperedge memberships continue to return the replacement under attributes it no longer has. Deleting a replaced node also leaves stale node IDs in its old label index. Five actual Rust public-consumer tests against source-identical upstream GraphDB reproduce four failures and one ordinary creation/update control. + +## Decision + +Keep the existing Rust upsert behavior. Hold the corresponding DashMap entry for one object ID, persist the candidate before changing live memory, remove the old object's index memberships, add new memberships and replace the entry. Same-ID replacements are serialized; existing missing-endpoint validation remains before relationship mutation. The Python create-only duplicate guard remains unchanged, with its explanation updated. + +## Validation and limits + +Seven focused public Rust tests additionally cover concurrent same-ID writers and rejected relationship replacement. Full applicable graph tests, formatting, scoped Clippy and independent exact-commit review are required. This is consistency after an operation completes, not a global transaction across index readers, other objects or concurrent node deletion. Existing shard lock ordering follows update_node; no callback executes under these new entry locks. Work is proportional to the replaced object's labels/properties/relationship membership, without cloning entire indexes. + +## Changelog + +Remove stale node, edge and hyperedge index memberships during existing-ID replacement.