Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion crates/ruvector-core/src/index/hnsw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,16 @@ impl HnswIndex {
.collect();

let id_to_idx: DashMap<VectorId, usize> = state.id_to_idx.into_iter().collect();
let idx_to_id: DashMap<usize, VectorId> = 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<usize, VectorId> = 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
Expand Down
83 changes: 70 additions & 13 deletions crates/ruvector-core/src/storage_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<String> {
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<VectorId> {
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
Expand All @@ -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 {
Expand All @@ -68,19 +91,25 @@ impl MemoryStorage {

/// Insert multiple vectors in a batch
pub fn insert_batch(&self, entries: &[VectorEntry]) -> Result<Vec<VectorId>> {
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 {
expected: self.dimensions,
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(
Expand Down Expand Up @@ -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();
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -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.
143 changes: 143 additions & 0 deletions crates/ruvector-core/tests/hnsw_live_replacements.rs
Original file line number Diff line number Diff line change
@@ -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<_>>(),
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<_>>(),
vec!["6", "7"]
);
assert_eq!(
hits.iter().map(|hit| hit.score).collect::<Vec<_>>(),
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<_>>(),
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<_>>(),
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<_>>(),
vec!["keeper", "new"]
);
assert_eq!(restored.len(), 2);
}
Loading
Loading