From 6f5a12bba603c779478a3bd29043c05d517a45f5 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 11 Oct 2026 03:02:36 -0400 Subject: [PATCH] fix(core): reserve generated IDs without overwriting live caller rows --- CHANGELOG.md | 6 + crates/ruvector-core/src/storage_memory.rs | 77 +++++++++++-- .../tests/memory_generated_ids.rs | 107 ++++++++++++++++++ docs/adr/ADR-core-memory-generated-ids.md | 23 ++++ 4 files changed, 201 insertions(+), 12 deletions(-) create mode 100644 crates/ruvector-core/tests/memory_generated_ids.rs create mode 100644 docs/adr/ADR-core-memory-generated-ids.md diff --git a/CHANGELOG.md b/CHANGELOG.md index e5c69d8cbb..96f3ef5eb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to RuVector will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### 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. + ## [@ruvector/router 0.1.32] - 2026-09-30 ### Fixed - `maxElements` was typed and documented as "Maximum number of elements" but diff --git a/crates/ruvector-core/src/storage_memory.rs b/crates/ruvector-core/src/storage_memory.rs index 0c1cf47df2..17681dfbf2 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 { @@ -69,6 +92,10 @@ impl MemoryStorage { /// Insert multiple vectors in a batch pub fn insert_batch(&self, entries: &[VectorEntry]) -> Result> { let mut ids = Vec::with_capacity(entries.len()); + let reserved: HashSet<&str> = entries + .iter() + .filter_map(|entry| entry.id.as_deref()) + .collect(); for entry in entries { if entry.vector.len() != self.dimensions { @@ -78,9 +105,7 @@ impl MemoryStorage { }); } - let id = entry.id.clone().unwrap_or_else(|| self.generate_id()); - - self.vectors.insert(id.clone(), entry.vector.clone()); + let id = self.insert_vector(entry, &reserved)?; if let Some(metadata) = &entry.metadata { self.metadata.insert( @@ -176,6 +201,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/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/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.