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
- Memory-backed Rust batches validate all vector dimensions before storing any
row or allocating generated IDs. A rejected batch preserves existing vectors,
metadata, and storage/search consistency.

## [@ruvector/router 0.1.32] - 2026-09-30
### Fixed
- `maxElements` was typed and documented as "Maximum number of elements" but
Expand Down
7 changes: 5 additions & 2 deletions crates/ruvector-core/src/storage_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,19 @@ 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 mut ids = Vec::with_capacity(entries.len());
for entry in entries {
let id = entry.id.clone().unwrap_or_else(|| self.generate_id());

self.vectors.insert(id.clone(), entry.vector.clone());
Expand Down
125 changes: 125 additions & 0 deletions crates/ruvector-core/tests/memory_batch_validation.rs
Original file line number Diff line number Diff line change
@@ -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<f32>) -> VectorEntry {
VectorEntry {
id: id.map(str::to_owned),
vector,
metadata: None,
}
}

fn search_ids(db: &VectorDB) -> Vec<String> {
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::<VectorEntry>::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]);
}
40 changes: 40 additions & 0 deletions docs/adr/ADR-core-memory-batch-validation.md
Original file line number Diff line number Diff line change
@@ -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.