Skip to content
Closed
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

- 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.

## [@ruvector/router 0.1.32] - 2026-09-30
### Fixed
- `maxElements` was typed and documented as "Maximum number of elements" but
Expand Down
59 changes: 41 additions & 18 deletions crates/ruvector-core/src/index/hnsw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,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 Expand Up @@ -257,22 +266,31 @@ impl HnswIndex {
return Ok(vec![]);
}

// ef_search < k causes hnsw_rs to return fewer than k candidates; clamp.
let effective_ef = ef_search.max(k);

let neighbors = inner.hnsw.search(query, k, effective_ef);

let mut results: Vec<SearchResult> = neighbors
.into_iter()
.filter_map(|(idx, distance)| {
inner.idx_to_id.get(&idx).map(|id| SearchResult {
id: id.clone(),
score: distance,
vector: None,
metadata: None,
let target = k.min(inner.vectors.len());
let mut candidate_k = k;
let mut results;
loop {
// Deleted/replaced graph positions remain physically allocated.
// Widen only when those positions crowd live rows out of top-k.
let neighbors = inner
.hnsw
.search(query, candidate_k, ef_search.max(candidate_k));
results = neighbors
.into_iter()
.filter_map(|(idx, distance)| {
inner.idx_to_id.get(&idx).map(|id| SearchResult {
id: id.clone(),
score: distance,
vector: None,
metadata: None,
})
})
})
.collect();
.collect::<Vec<_>>();
if results.len() >= target || candidate_k >= inner.next_idx {
break;
}
candidate_k = candidate_k.saturating_mul(2).min(inner.next_idx);
}

// hnsw_rs does not guarantee sort order — ensure ascending distance.
results.sort_unstable_by(|a, b| {
Expand All @@ -281,6 +299,7 @@ impl HnswIndex {
.unwrap_or(std::cmp::Ordering::Equal)
});

results.truncate(target);
Ok(results)
}
}
Expand All @@ -302,7 +321,9 @@ impl VectorIndex for HnswIndex {

// Store mappings
inner.vectors.insert(id.clone(), vector);
inner.id_to_idx.insert(id.clone(), idx);
if let Some(previous_idx) = inner.id_to_idx.insert(id.clone(), idx) {
inner.idx_to_id.remove(&previous_idx);
}
inner.idx_to_id.insert(idx, id);

Ok(())
Expand Down Expand Up @@ -337,7 +358,9 @@ impl VectorIndex for HnswIndex {
// Store mappings
for (id, idx, vector) in data_with_ids {
inner.vectors.insert(id.clone(), vector);
inner.id_to_idx.insert(id.clone(), idx);
if let Some(previous_idx) = inner.id_to_idx.insert(id.clone(), idx) {
inner.idx_to_id.remove(&previous_idx);
}
inner.idx_to_id.insert(idx, id);
}

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.
172 changes: 172 additions & 0 deletions crates/ruvector-core/tests/hnsw_live_replacements.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
//! 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);
}

#[test]
fn sparse_deleted_labels_survive_restore_and_new_insertion() {
let mut index = index();
for i in 0..8 {
index.add(i.to_string(), vec![i as f32, 0.0]).unwrap();
}
for i in 0..6 {
assert!(index.remove(&i.to_string()).unwrap());
}
// Restore inserts only labels 6 and 7 at dense positions 0 and 1.
let mut restored = HnswIndex::deserialize(&index.serialize().unwrap()).unwrap();
let hits = restored.search(&[0.0, 0.0], 2).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]
);
restored.add("new".into(), vec![0.0, 0.0]).unwrap();
let again = HnswIndex::deserialize(&restored.serialize().unwrap()).unwrap();
let hits = again.search(&[0.0, 0.0], 3).unwrap();
assert_eq!(
hits.iter().map(|hit| hit.id.as_str()).collect::<Vec<_>>(),
vec!["new", "6", "7"]
);
}
23 changes: 23 additions & 0 deletions docs/adr/ADR-core-hnsw-live-replacements.md
Original file line number Diff line number Diff line change
@@ -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.
Loading