#![warn(clippy::undocumented_unsafe_blocks)]
pub mod distance;
mod error;
mod half;
mod header;
mod hnsw;
mod legacy;
mod prefetch;
mod storage;
#[cfg(test)]
mod power_loss;
#[cfg(feature = "internals")]
pub use hnsw::*;
pub use distance::{DistanceMetric, cosine_distance, euclidean_distance};
pub use error::{Error, ErrorKind, Result};
pub use half::Precision;
pub use hnsw::SearchResult;
#[cfg(feature = "internals")]
pub use header::{MAGIC, VERSION};
#[cfg(feature = "internals")]
pub use hnsw::{HnswGraph, HnswParams, NodeRecordParams};
#[cfg(feature = "internals")]
pub use storage::Storage;
#[cfg(not(feature = "internals"))]
use {
hnsw::{HnswGraph, HnswParams},
storage::Storage,
};
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
#[cfg(all(doctest, chassis_skill))]
#[doc = include_str!("../../plugins/chassis/skills/chassis/SKILL.md")]
struct SkillDoctests;
use error::fail;
use hnsw::layer_from_uniform;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
#[derive(Debug, Clone)]
pub struct IndexOptions {
pub max_connections: u16,
pub ef_construction: usize,
pub ef_search: usize,
pub metric: DistanceMetric,
pub precision: Precision,
pub huge_pages: bool,
pub warm: bool,
}
impl Default for IndexOptions {
fn default() -> Self {
Self {
max_connections: 16,
ef_construction: 200,
ef_search: 50,
metric: DistanceMetric::Euclidean,
precision: Precision::Full,
huge_pages: false,
warm: false,
}
}
}
#[derive(Debug)]
pub struct VectorIndex {
graph: HnswGraph,
options: IndexOptions,
ml: f32,
ids: OnceLock<IdTable>,
building: Mutex<()>,
path: PathBuf,
}
impl VectorIndex {
pub fn open<P: AsRef<Path>>(path: P, dims: u32, options: IndexOptions) -> Result<Self> {
let params = hnsw_params(&options);
let mut path = path.as_ref().to_path_buf();
if path.symlink_metadata().is_ok_and(|meta| meta.file_type().is_symlink()) {
path = std::fs::canonicalize(&path).unwrap_or(path);
}
let storage = Storage::open_with_precision(
&path,
dims,
params.to_record_params(),
options.metric,
options.precision,
)?;
if storage.metric() != options.metric {
let (held, asked) = (metric_name(storage.metric()), metric_name(options.metric));
fail!(
OptionsMismatch,
"The index at {} was created with {held} distance, so it has to be opened with \
{held} distance too, not {asked}\nhelp: open it with the {held} metric, or \
create a new index at another path for {asked} distance",
path.display()
);
}
if storage.precision() != options.precision {
let (held, asked) =
(precision_name(storage.precision()), precision_name(options.precision));
fail!(
OptionsMismatch,
"The index at {} keeps its vectors in {held} precision, so it has to be opened \
with {held} precision too, not {asked}\nhelp: open it with {held} precision, or \
create a new index at another path for {asked} precision",
path.display()
);
}
let graph = HnswGraph::open_no_reset(storage, params)?;
let _ = std::fs::remove_file(storage::sibling(&path, "compacting"));
let (ids, building) = (OnceLock::new(), Mutex::new(()));
let mut index = Self { graph, ml: params.ml, options, ids, building, path };
index.apply_options();
Ok(index)
}
fn apply_options(&mut self) {
if self.options.huge_pages {
self.use_huge_pages();
}
if self.options.warm {
self.warm();
}
}
pub fn add(&mut self, vector: &[f32]) -> Result<u64> {
check_finite(vector, "The vector")?;
let id = self.next_ids(1)?.start;
self.insert(id, vector)?;
Ok(id)
}
fn next_ids(&mut self, count: u64) -> Result<std::ops::Range<u64>> {
let first =
if self.graph.custom_ids { self.id_table()?.next } else { self.graph.node_count() };
match first.checked_add(count) {
Some(end) => Ok(first..end),
None => {
fail!(
Full,
"No ids are left for add to give: the largest in use is {}\nhelp: choose \
free ids yourself with add_with_id",
u64::MAX - 1
)
}
}
}
pub fn add_with_id(&mut self, id: u64, vector: &[f32]) -> Result<()> {
check_id(id)?;
check_finite(vector, "The vector")?;
if self.slot_of(id)?.is_some() {
fail!(
IdInUse,
"Id {id} is already in use\nhelp: delete it first to replace its vector, or use \
another id"
);
}
let switch = !self.graph.custom_ids && id != self.graph.node_count();
if switch {
self.id_table()?;
}
self.insert(id, vector)?;
self.graph.custom_ids |= switch;
Ok(())
}
pub fn add_batch(&mut self, vectors: &[f32]) -> Result<Vec<u64>> {
let count = self.batch_len(vectors)? as u64;
let ids: Vec<u64> = self.next_ids(count)?.collect();
self.insert_batch(&ids, vectors)?;
Ok(ids)
}
pub fn add_batch_with_ids(&mut self, ids: &[u64], vectors: &[f32]) -> Result<()> {
let count = self.batch_len(vectors)?;
if count != ids.len() {
fail!(
InvalidArgument,
"{} ids were given for {count} vectors\nhelp: give one id per vector, in the same \
order",
ids.len()
);
}
let mut seen = HashSet::with_capacity(ids.len());
for &id in ids {
check_id(id)?;
if !seen.insert(id) {
fail!(
InvalidArgument,
"Id {id} is given twice in the batch\nhelp: give each vector its own id"
);
}
if self.slot_of(id)?.is_some() {
fail!(
IdInUse,
"Id {id} is already in use\nhelp: delete it first to replace its vector, or use \
another id"
);
}
}
let first = self.graph.node_count();
let switch =
!self.graph.custom_ids && ids.iter().zip(first..).any(|(&id, slot)| id != slot);
if switch {
self.id_table()?;
}
self.insert_batch(ids, vectors)?;
self.graph.custom_ids |= switch;
Ok(())
}
fn dims(&self) -> usize {
self.graph.storage.dimensions() as usize
}
fn batch_len(&self, vectors: &[f32]) -> Result<usize> {
let dims = self.dims();
if !vectors.len().is_multiple_of(dims) {
fail!(
DimensionMismatch,
"A batch of {} floats is not a whole number of vectors of {dims}\nhelp: pass the \
vectors back to back, {dims} floats each",
vectors.len()
);
}
for (row, vector) in vectors.chunks_exact(dims).enumerate() {
check_finite(vector, &format!("Vector {row} of the batch"))?;
}
Ok(vectors.len() / dims)
}
fn insert_batch(&mut self, ids: &[u64], vectors: &[f32]) -> Result<()> {
if ids.is_empty() {
return Ok(());
}
match self.graph.storage.metric() {
DistanceMetric::Euclidean => self.insert_stored(ids, vectors),
DistanceMetric::Cosine => {
let rows = vectors.chunks_exact(self.dims()).map(distance::unit);
self.insert_stored(ids, &rows.collect::<anyhow::Result<Vec<_>>>()?.concat())
}
}
}
fn insert_stored(&mut self, ids: &[u64], vectors: &[f32]) -> Result<()> {
if ids.is_empty() {
return Ok(());
}
if self.graph.storage.precision() == Precision::Half {
half::check(vectors, self.dims())?;
}
let layers: Vec<usize> = ids.iter().map(|_| self.select_layer()).collect();
let first = self.graph.node_count();
let saved = (self.graph.entry_point, self.graph.max_layer);
let linked = self.write_and_link(first, ids, vectors, &layers);
if let Err(e) = linked {
self.graph.node_count = first;
(self.graph.entry_point, self.graph.max_layer) = saved;
self.graph.storage.truncate_logical(first);
return Err(e.into());
}
self.graph.storage.publish_routing(self.graph.node_count);
if let Some(table) = self.ids.get_mut() {
table.slots.extend(ids.iter().copied().zip(first..));
table.next = table.next.max(ids.iter().max().map_or(0, |&id| id + 1));
}
Ok(())
}
fn write_and_link(
&mut self,
first: u64,
ids: &[u64],
vectors: &[f32],
layers: &[usize],
) -> anyhow::Result<()> {
let dims = self.dims();
let storage = &mut self.graph.storage;
storage.truncate_logical(first);
storage.huge_pages_up_to(first + ids.len() as u64);
for ((&id, vector), &layer) in ids.iter().zip(vectors.chunks_exact(dims)).zip(layers) {
let slot = storage.append(id, vector)?;
storage.write_record(slot, &vec![Vec::new(); layer + 1])?;
}
let start = if self.graph.entry_point.is_none() {
(self.graph.entry_point, self.graph.max_layer) = (Some(first), layers[0]);
1
} else {
0
};
let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
let ef = self.options.ef_construction;
self.graph.link_batch(first + start as u64, &layers[start..], ef, threads.min(ids.len()))
}
pub fn delete(&mut self, id: u64) -> Result<bool> {
let Some(slot) = self.slot_of(id)? else {
return Ok(false);
};
self.graph.mark_deleted(slot)?;
if let Some(table) = self.ids.get_mut() {
table.slots.remove(&id);
}
Ok(true)
}
fn slot_of(&self, id: u64) -> Result<Option<u64>> {
if !self.graph.custom_ids {
let live = id < self.graph.node_count() && !self.graph.is_deleted(id)?;
return Ok(live.then_some(id));
}
Ok(self.id_table()?.slots.get(&id).copied())
}
fn id_table(&self) -> Result<&IdTable> {
if let Some(table) = self.ids.get() {
return Ok(table);
}
let _building = self.building.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(table) = self.ids.get() {
return Ok(table);
}
let live = self.graph.node_count() - self.graph.deleted_count;
let mut pairs = Vec::with_capacity(live as usize);
let mut next = self.graph.storage.next_id();
for slot in 0..self.graph.node_count() {
let id = self.graph.id_of(slot)?;
next = next.max(id + 1);
if !self.graph.is_deleted(slot)? {
pairs.push((id, slot));
}
}
let mut slots = IdMap::with_capacity_and_hasher(pairs.len(), IdHasher::default());
slots.extend(pairs);
Ok(self.ids.get_or_init(|| IdTable { slots, next }))
}
fn insert(&mut self, id: u64, vector: &[f32]) -> Result<()> {
let dims = self.graph.storage.dimensions() as usize;
if vector.len() != dims {
fail!(
DimensionMismatch,
"The vector has {} components, but this index holds vectors of {dims}\nhelp: make \
the vector with the same model as the index's vectors",
vector.len()
);
}
let unit;
let vector = match self.graph.storage.metric() {
DistanceMetric::Euclidean => vector,
DistanceMetric::Cosine => {
unit = distance::unit(vector)?;
&unit[..]
}
};
let slot = self.graph.node_count();
self.graph.storage.truncate_logical(slot);
let new_id = self.graph.storage.append(id, vector)?;
let kept;
let vector = match self.graph.storage.precision() {
Precision::Full => vector,
Precision::Half => {
kept = self.graph.storage.get_vector(new_id)?;
&kept[..]
}
};
let layer = self.select_layer();
let layer_count = layer + 1;
let neighbors = match self.graph.entry_point {
Some(entry) if self.graph.node_count() > 0 => {
let start = (entry, self.graph.max_layer);
let ef = self.options.ef_construction;
self.graph.find_neighbors(vector, new_id, layer, start, ef)?
}
_ => vec![vec![]; layer_count],
};
self.graph.write_node_with_id_and_backlinks(new_id, id, layer_count, &neighbors)?;
self.graph.publish_node(new_id, layer_count)?;
if let Some(table) = self.ids.get_mut() {
table.slots.insert(id, new_id);
table.next = table.next.max(id + 1);
}
Ok(())
}
pub fn search(&self, query: &[f32], k: usize) -> Result<Vec<SearchResult>> {
search_graph(&self.graph, query, k, self.options.ef_search, None)
}
pub fn search_filtered(
&self,
query: &[f32],
k: usize,
filter: impl Fn(u64) -> bool,
) -> Result<Vec<SearchResult>> {
search_graph(&self.graph, query, k, self.options.ef_search, Some(&filter))
}
pub fn flush(&mut self) -> Result<()> {
Ok(self.graph.commit()?)
}
pub fn rollback(&mut self) -> Result<()> {
let storage = self.graph.storage.reopened(&self.path)?;
let graph = HnswGraph::open_no_reset(storage, hnsw_params(&self.options));
self.graph = graph.inspect_err(|_| self.graph.storage.poison())?;
self.ids = OnceLock::new();
self.apply_options();
Ok(())
}
pub fn compact(&mut self) -> Result<()> {
self.flush()?;
let temp = storage::sibling(&self.path, "compacting");
let swapped = self.compacted_copy(&temp).and_then(|fresh| {
self.graph.storage.set_superseded(true)?;
self.swap_in(fresh, &temp)
});
if swapped.is_err() {
let _ = std::fs::remove_file(&temp);
}
swapped
}
fn compacted_copy(&mut self, temp: &Path) -> Result<Self> {
match std::fs::remove_file(temp) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
_ => {}
}
let next_id = self.id_table()?.next;
let dims = self.dims();
let mut fresh = Self::open(temp, dims as u32, self.options.clone())?;
fresh.id_table()?;
let count = self.graph.node_count();
let chunk = ((32 << 20) / (dims * 4)).max(1);
let (mut ids, mut vectors) = (Vec::new(), Vec::new());
for start in (0..count).step_by(chunk) {
ids.clear();
vectors.clear();
for slot in start..(start + chunk as u64).min(count) {
if !self.graph.is_deleted(slot)? {
ids.push(self.graph.id_of(slot)?);
vectors.extend_from_slice(&self.graph.storage.vector(slot)?);
}
}
let first = fresh.graph.node_count();
fresh.graph.custom_ids |= ids.iter().zip(first..).any(|(&id, slot)| id != slot);
fresh.insert_stored(&ids, &vectors)?;
}
fresh.graph.custom_ids |= next_id != fresh.graph.node_count();
fresh.ids.get_mut().expect("built above").next = next_id;
let user_version = self.graph.storage.user_version();
fresh.graph.storage.carry_over(next_id, self.graph.storage.epoch() + 1, user_version);
fresh.flush()?;
Ok(fresh)
}
#[cfg(unix)]
fn swap_in(&mut self, mut fresh: Self, temp: &Path) -> Result<()> {
if let Err(e) = std::fs::rename(temp, &self.path) {
self.graph.storage.set_superseded(false)?;
return Err(e.into());
}
fresh.path = std::mem::take(&mut self.path);
fresh.graph.storage.moved_to(&fresh.path);
*self = fresh;
Ok(storage::sync_dir(&self.path)?)
}
#[cfg(windows)]
fn swap_in(&mut self, fresh: Self, temp: &Path) -> Result<()> {
let (path, dims, options) = (self.path.clone(), self.dims() as u32, self.options.clone());
drop(std::mem::replace(self, fresh));
if let Err(e) = storage::rename_over(temp, &path) {
match Self::open(&path, dims, options) {
Ok(old) => *self = old,
Err(reopen) => {
self.graph.storage.poison();
let e = e.context(format!("and the index couldn't be reopened: {reopen}"));
return Err(e.into());
}
}
return Err(e.into());
}
self.graph.storage.moved_to(&path);
self.path = path;
Ok(())
}
pub fn use_huge_pages(&mut self) {
self.options.huge_pages = true;
self.graph.storage.use_huge_pages();
}
pub fn warm(&mut self) {
self.options.warm = true;
self.graph.storage.warm();
}
pub fn get(&self, id: u64) -> Result<Option<Vec<f32>>> {
let Some(slot) = self.slot_of(id)? else {
return Ok(None);
};
Ok(Some(self.graph.storage.get_vector(slot)?))
}
pub fn contains(&self, id: u64) -> Result<bool> {
Ok(self.slot_of(id)?.is_some())
}
pub fn ids(&self) -> Result<Vec<u64>> {
live_ids(&self.graph)
}
pub fn check(&self) -> Result<Check> {
Ok(Check { unreachable: unreachable(&self.graph)?, not_finite: not_finite(&self.graph)? })
}
pub fn len(&self) -> u64 {
self.graph.node_count() - self.graph.deleted_count
}
pub fn deleted_count(&self) -> u64 {
self.graph.deleted_count
}
pub fn user_version(&self) -> u64 {
self.graph.storage.user_version()
}
pub fn set_user_version(&mut self, version: u64) {
self.graph.storage.set_user_version(version);
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn dimensions(&self) -> u32 {
self.graph.storage.dimensions()
}
pub fn metric(&self) -> DistanceMetric {
self.graph.storage.metric()
}
pub fn precision(&self) -> Precision {
self.graph.storage.precision()
}
fn select_layer(&self) -> usize {
let uniform: f32 = rand::random();
layer_from_uniform(uniform, self.ml, self.graph.record_params.max_layers)
}
}
type IdMap = HashMap<u64, u64, IdHasher>;
struct IdTable {
slots: IdMap,
next: u64,
}
impl std::fmt::Debug for IdTable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IdTable").field("ids", &self.slots.len()).field("next", &self.next).finish()
}
}
#[derive(Default)]
struct MappedIds {
slots: IdMap,
mapped: u64,
}
impl std::fmt::Debug for MappedIds {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MappedIds")
.field("ids", &self.slots.len())
.field("mapped", &self.mapped)
.finish()
}
}
#[derive(Clone, Copy)]
struct IdHasher(u64);
impl Default for IdHasher {
fn default() -> Self {
Self(rand::random())
}
}
impl std::hash::BuildHasher for IdHasher {
type Hasher = Self;
fn build_hasher(&self) -> Self {
*self
}
}
impl std::hash::Hasher for IdHasher {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for chunk in bytes.chunks(8) {
let mut word = [0u8; 8];
word[..chunk.len()].copy_from_slice(chunk);
self.write_u64(u64::from_le_bytes(word));
}
}
fn write_u64(&mut self, id: u64) {
let product = u128::from(id ^ self.0) * 0x9e37_79b9_7f4a_7c15;
self.0 = (product as u64) ^ ((product >> 64) as u64);
}
}
fn search_graph(
graph: &HnswGraph,
query: &[f32],
k: usize,
ef: usize,
filter: Option<&dyn Fn(u64) -> bool>,
) -> Result<Vec<SearchResult>> {
if k == 0 {
fail!(
InvalidArgument,
"k is 0, but has to be at least 1\nhelp: pass how many results to return, such as 10"
);
}
let dims = graph.storage.dimensions() as usize;
if query.len() != dims {
fail!(
DimensionMismatch,
"The query has {} components, but this index holds vectors of {dims}\nhelp: make the \
query with the same model as the index's vectors",
query.len()
);
}
check_finite(query, "The query")?;
let search = |query: &[f32]| match filter {
None => graph.search(query, k, ef),
Some(filter) => graph.search_filtered(query, k, ef, &|slot| {
Ok(filter(if graph.custom_ids { graph.id_of(slot)? } else { slot }))
}),
};
let mut results = match graph.storage.metric() {
DistanceMetric::Euclidean => search(query)?,
DistanceMetric::Cosine => {
let query = distance::unit(query)?;
let mut results = search(&query)?;
for result in &mut results {
result.distance = (result.distance * result.distance / 2.0).min(2.0);
}
results
}
};
if graph.custom_ids {
for result in &mut results {
result.id = graph.id_of(result.id)?;
}
}
Ok(results)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Check {
pub unreachable: Vec<u64>,
pub not_finite: Vec<u64>,
}
impl Check {
pub fn is_ok(&self) -> bool {
self.unreachable.is_empty() && self.not_finite.is_empty()
}
}
fn unreachable(graph: &HnswGraph) -> Result<Vec<u64>> {
let count = graph.node_count();
let mut reached = vec![false; count as usize];
let mut next: Vec<u64> = graph.entry_point.into_iter().collect();
next.iter().for_each(|&slot| reached[slot as usize] = true);
while let Some(slot) = next.pop() {
for layer in 0..graph.storage.layer_count(slot)? {
for neighbor in graph.neighbors_iter_from_mmap(slot, layer)? {
if neighbor < count && !std::mem::replace(&mut reached[neighbor as usize], true) {
next.push(neighbor);
}
}
}
}
let mut ids = Vec::new();
for slot in 0..count {
if !reached[slot as usize] && !graph.is_deleted(slot)? {
ids.push(graph.id_of(slot)?);
}
}
Ok(ids)
}
fn not_finite(graph: &HnswGraph) -> Result<Vec<u64>> {
let mut ids = Vec::new();
for slot in 0..graph.node_count() {
if !graph.is_deleted(slot)? && graph.storage.vector(slot)?.iter().any(|x| !x.is_finite()) {
ids.push(graph.id_of(slot)?);
}
}
Ok(ids)
}
fn live_ids(graph: &HnswGraph) -> Result<Vec<u64>> {
let mut ids = Vec::new();
for slot in 0..graph.node_count() {
if !graph.is_deleted(slot)? {
ids.push(graph.id_of(slot)?);
}
}
Ok(ids)
}
fn check_finite(vector: &[f32], what: &str) -> Result<()> {
if let Some(i) = vector.iter().position(|x| !x.is_finite()) {
fail!(
InvalidArgument,
"{what} has {} at component {i}, but every component has to be a finite number\nhelp: \
check how it was made; a division by zero, as in normalizing a zero vector, gives NaN",
vector[i]
);
}
Ok(())
}
fn check_id(id: u64) -> Result<()> {
if id == u64::MAX {
fail!(InvalidArgument, "Id {id} is reserved\nhelp: ids go from 0 to {}", u64::MAX - 1);
}
Ok(())
}
fn metric_name(metric: DistanceMetric) -> &'static str {
match metric {
DistanceMetric::Euclidean => "euclidean",
DistanceMetric::Cosine => "cosine",
}
}
fn precision_name(precision: Precision) -> &'static str {
match precision {
Precision::Half => "half",
_ => "full",
}
}
fn hnsw_params(options: &IndexOptions) -> HnswParams {
HnswParams {
max_connections: options.max_connections,
ml: 1.0 / f32::from(options.max_connections).ln(),
max_layers: 16, }
}
#[derive(Debug)]
pub struct IndexReader {
graph: HnswGraph,
ef_search: usize,
path: PathBuf,
dims: u32,
options: IndexOptions,
ids: Option<MappedIds>,
}
impl IndexReader {
pub fn open<P: AsRef<Path>>(path: P, dims: u32, options: IndexOptions) -> Result<Self> {
let path = path.as_ref().to_path_buf();
let storage = Storage::open_read_only(&path, dims)?;
let graph = HnswGraph::reader(storage, hnsw_params(&options))?;
let mut reader =
Self { graph, ef_search: options.ef_search, path, dims, options, ids: None };
if reader.options.huge_pages {
reader.use_huge_pages();
}
if reader.options.warm {
reader.warm();
}
Ok(reader)
}
fn sync(&mut self) -> Result<()> {
self.graph.refresh()?;
if self.graph.storage.superseded() && !self.graph.storage.is_at(&self.path)? {
*self = Self::open(&self.path, self.dims, self.options.clone())?;
}
Ok(())
}
pub fn search(&mut self, query: &[f32], k: usize) -> Result<Vec<SearchResult>> {
self.sync()?;
search_graph(&self.graph, query, k, self.ef_search, None)
}
pub fn search_filtered(
&mut self,
query: &[f32],
k: usize,
filter: impl Fn(u64) -> bool,
) -> Result<Vec<SearchResult>> {
self.sync()?;
search_graph(&self.graph, query, k, self.ef_search, Some(&filter))
}
pub fn dimensions(&self) -> u32 {
self.graph.storage.dimensions()
}
pub fn metric(&self) -> DistanceMetric {
self.graph.storage.metric()
}
pub fn precision(&self) -> Precision {
self.graph.storage.precision()
}
pub fn refresh(&mut self) -> Result<()> {
self.sync()
}
pub fn snapshot(&self) -> (u64, u64) {
self.graph.view.map_or((0, 0), |view| (view.committed, view.epoch))
}
pub fn use_huge_pages(&mut self) {
self.options.huge_pages = true;
self.graph.storage.use_huge_pages();
}
pub fn warm(&mut self) {
self.options.warm = true;
self.graph.storage.warm();
}
pub fn get(&mut self, id: u64) -> Result<Option<Vec<f32>>> {
let Some(slot) = self.slot_of(id)? else {
return Ok(None);
};
Ok(Some(self.graph.storage.get_vector(slot)?))
}
pub fn contains(&mut self, id: u64) -> Result<bool> {
Ok(self.slot_of(id)?.is_some())
}
pub fn ids(&mut self) -> Result<Vec<u64>> {
self.sync()?;
live_ids(&self.graph)
}
pub fn check(&mut self) -> Result<Check> {
self.sync()?;
Ok(Check { unreachable: unreachable(&self.graph)?, not_finite: not_finite(&self.graph)? })
}
fn slot_of(&mut self, id: u64) -> Result<Option<u64>> {
self.sync()?;
let graph = &self.graph;
let committed = graph.view.map_or(0, |view| view.committed);
let slot = if graph.custom_ids {
let ids = self.ids.get_or_insert_with(MappedIds::default);
ids.slots.reserve(committed.saturating_sub(ids.mapped) as usize);
for slot in ids.mapped..committed {
ids.slots.insert(graph.id_of(slot)?, slot);
ids.mapped = slot + 1;
}
ids.slots.get(&id).copied()
} else {
Some(id)
};
match slot {
Some(slot) if slot < committed && !graph.is_deleted(slot)? => Ok(Some(slot)),
_ => Ok(None),
}
}
pub fn len(&self) -> u64 {
self.graph.view.map_or(0, |view| view.committed) - self.graph.deleted_count
}
pub fn deleted_count(&self) -> u64 {
self.graph.deleted_count
}
pub fn user_version(&self) -> u64 {
self.graph.storage.user_version()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::NamedTempFile;
fn random_vector(id: u64) -> Vec<f32> {
let mut x = id.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
(0..16)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
(x >> 40) as f32 / (1u64 << 24) as f32
})
.collect()
}
#[test]
fn test_asking_to_warm_turns_the_option_on_for_a_reopen() {
let file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
index.add(&random_vector(0)).unwrap();
index.flush().unwrap();
let mut reader = IndexReader::open(file.path(), 16, IndexOptions::default()).unwrap();
index.warm();
reader.warm();
assert!(index.options.warm && reader.options.warm);
}
fn filter_index(file: &NamedTempFile) -> VectorIndex {
let options = IndexOptions { ef_construction: 64, ..IndexOptions::default() };
let mut index = VectorIndex::open(file.path(), 16, options).unwrap();
for id in 0..2500 {
index.add(&random_vector(id)).unwrap();
}
index
}
#[test]
fn test_filtered_search_estimates_matches_and_picks_its_path() {
let file = NamedTempFile::new().unwrap();
let mut index = filter_index(&file);
let graph = &index.graph;
let estimate = |allow: &dyn Fn(u64) -> bool| graph.estimated_matches(&|s| Ok(allow(s)));
assert_eq!(estimate(&|_| true).unwrap(), 2500);
assert_eq!(estimate(&|_| false).unwrap(), 0);
let odd = estimate(&|slot| slot % 2 == 1).unwrap();
assert!((1000..=1500).contains(&odd), "odd slots estimated at {odd}");
let query = random_vector(99_999);
let nearest = index.search(&query, 1).unwrap()[0].id;
let path = |allow: &dyn Fn(u64) -> bool| {
index.graph.search_filtered_reporting(&query, 10, 50, &|s| Ok(allow(s))).unwrap()
};
let (found, scanned) = path(&|slot| slot != nearest);
assert!(!scanned && found.len() == 10, "a broad filter walks the graph");
let (found, scanned) = path(&|slot| slot % 250 == 7);
assert!(scanned && found.len() == 10, "a selective filter scans");
for slot in (0..2500).step_by(2) {
index.delete(slot).unwrap();
}
let live = index.graph.estimated_matches(&|_| Ok(true)).unwrap();
assert!((1000..=1500).contains(&live), "deleted slots counted as matches: {live}");
}
#[cfg(unix)]
#[test]
fn test_a_failed_swap_clears_the_flag_and_removes_the_copy() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("index.chassis");
let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
for id in 0..50 {
index.add(&random_vector(id)).unwrap();
}
index.flush().unwrap();
let blocked = dir.path().join("blocked");
std::fs::create_dir(&blocked).unwrap();
std::fs::write(blocked.join("file"), b"").unwrap();
index.path = blocked.clone();
assert!(index.compact().is_err());
assert!(!dir.path().join("blocked.compacting").exists(), "the copy was left behind");
assert!(!index.graph.storage.superseded(), "readers would wait for a file that won't come");
index.path = path.clone();
assert_eq!(index.search(&random_vector(7), 1).unwrap()[0].id, 7);
let mut reader = IndexReader::open(&path, 16, IndexOptions::default()).unwrap();
assert!(!reader.graph.storage.superseded());
assert_eq!(reader.search(&random_vector(7), 1).unwrap()[0].id, 7);
index.compact().unwrap();
assert_eq!(index.len(), 50);
}
#[test]
fn test_a_superseded_flag_left_by_a_crash_is_cleared() {
let file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
for id in 0..50 {
index.add(&random_vector(id)).unwrap();
}
index.flush().unwrap();
index.graph.storage.set_superseded(true).unwrap();
drop(index);
let mut reader = IndexReader::open(file.path(), 16, IndexOptions::default()).unwrap();
assert!(reader.graph.storage.superseded());
assert_eq!(reader.search(&random_vector(7), 1).unwrap()[0].id, 7);
let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
assert!(!index.graph.storage.superseded(), "the next writer clears the flag");
index.add(&random_vector(50)).unwrap();
index.flush().unwrap();
assert_eq!(reader.search(&random_vector(50), 1).unwrap()[0].id, 50);
assert!(!reader.graph.storage.superseded());
}
fn lists(index: &VectorIndex) -> Vec<Vec<Vec<u64>>> {
let graph = &index.graph;
let list = |slot, layer| {
let mut ids: Vec<u64> = graph.neighbors_iter_from_mmap(slot, layer).unwrap().collect();
ids.sort_unstable();
ids
};
let layers = |slot| graph.storage.layer_count(slot).unwrap();
(0..graph.node_count())
.map(|slot| (0..layers(slot)).map(|l| list(slot, l)).collect())
.collect()
}
fn index_with_unflushed_adds(path: &Path) -> (VectorIndex, Vec<Vec<Vec<u64>>>) {
let mut index = VectorIndex::open(path, 16, IndexOptions::default()).unwrap();
let flat = |ids: std::ops::Range<u64>| ids.flat_map(random_vector).collect::<Vec<f32>>();
index.add_batch(&flat(0..300)).unwrap();
index.flush().unwrap();
let committed = lists(&index);
for id in 300..600 {
index.add(&random_vector(id)).unwrap();
}
index.add_batch(&flat(600..2000)).unwrap();
(index, committed)
}
#[test]
fn test_adds_lost_to_a_crash_leave_no_trace_in_committed_lists() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("index.chassis");
let undo = storage::sibling(&path, "undo");
let (index, committed) = index_with_unflushed_adds(&path);
assert_ne!(lists(&index)[..300], committed[..], "the adds changed committed lists");
assert!(undo.exists());
drop(index);
let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
assert_eq!(lists(&index), committed);
assert!(!undo.exists(), "rolling back removes the undo file");
index.add(&random_vector(300)).unwrap();
assert!(undo.exists());
index.flush().unwrap();
assert!(!undo.exists(), "a flush removes the undo file");
let flushed = lists(&index);
drop(index);
let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
assert_eq!(lists(&index), flushed);
}
#[test]
fn test_a_rollback_leaves_what_a_reopen_would_and_keeps_the_lock() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("index.chassis");
let (mut index, committed) = index_with_unflushed_adds(&path);
index.add_with_id(5000, &random_vector(5000)).unwrap();
assert!(index.delete(5).unwrap());
index.set_user_version(7);
index.rollback().unwrap();
assert_eq!(lists(&index), committed);
assert_eq!((index.len(), index.deleted_count(), index.user_version()), (300, 0, 0));
assert!(index.contains(5).unwrap() && !index.contains(5000).unwrap());
assert!(!storage::sibling(&path, "undo").exists());
let second = VectorIndex::open(&path, 16, IndexOptions::default());
assert_eq!(second.unwrap_err().kind(), ErrorKind::Locked);
assert_eq!(index.add(&random_vector(300)).unwrap(), 300);
index.flush().unwrap();
let flushed = lists(&index);
drop(index);
let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
assert_eq!(lists(&index), flushed);
assert_eq!(index.len(), 301);
assert!(index.check().unwrap().is_ok());
}
#[test]
fn test_a_rollback_forgets_the_ids_given_since_the_flush() {
let file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
index.add_with_id(10, &random_vector(10)).unwrap();
index.flush().unwrap();
index.add_with_id(20, &random_vector(20)).unwrap();
index.rollback().unwrap();
assert!(!index.contains(20).unwrap());
assert_eq!(index.add(&random_vector(11)).unwrap(), 11, "the next id is past 10, not 20");
}
#[test]
fn test_a_rollback_finds_what_opening_after_a_crash_finds() {
for seed in 1..=40u64 {
let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
let mut rng = move |n: u64| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x % n
};
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.chassis");
let mut options = IndexOptions::default();
if seed % 3 == 0 {
options.metric = DistanceMetric::Cosine;
}
if seed % 4 == 0 {
options.precision = Precision::Half;
}
let mut index = VectorIndex::open(&path, 16, options.clone()).unwrap();
let (custom, mut next) = (seed % 2 == 0, 0u64);
let mut write = |index: &mut VectorIndex, rng: &mut dyn FnMut(u64) -> u64| {
let vector = |id: u64| random_vector(id + seed * 7919);
match rng(10) {
0..=3 => {
let ids: Vec<u64> = (0..1 + rng(40)).map(|i| next + i * 3).collect();
let flat: Vec<f32> = ids.iter().flat_map(|&id| vector(id)).collect();
next = if custom {
index.add_batch_with_ids(&ids, &flat).unwrap();
ids[ids.len() - 1] + 3
} else {
index.add_batch(&flat).unwrap().last().unwrap() + 1
};
}
4..=5 if custom => {
index.add_with_id(next, &vector(next)).unwrap();
next += 2;
}
4..=5 => next = index.add(&vector(next)).unwrap() + 1,
6..=8 => {
let ids = index.ids().unwrap();
if !ids.is_empty() {
index.delete(ids[rng(ids.len() as u64) as usize]).unwrap();
}
}
_ => index.set_user_version(rng(1000)),
}
};
for _ in 0..rng(12) {
write(&mut index, &mut rng);
}
index.flush().unwrap();
if seed % 5 == 0 {
index.compact().unwrap();
}
for _ in 0..rng(20) {
write(&mut index, &mut rng);
}
if seed % 7 == 0 {
index.flush().unwrap();
for _ in 0..rng(10) {
write(&mut index, &mut rng);
}
}
let crashed = dir.path().join("b.chassis");
std::fs::copy(&path, &crashed).unwrap();
let undo = storage::sibling(&path, "undo");
if undo.exists() {
std::fs::copy(&undo, storage::sibling(&crashed, "undo")).unwrap();
}
index.rollback().unwrap();
if seed % 6 == 0 {
index.rollback().unwrap();
}
let state = |index: &VectorIndex| {
let mut ids = index.ids().unwrap();
ids.sort_unstable();
let vectors: Vec<_> = ids.iter().map(|&id| index.get(id).unwrap()).collect();
let found: Vec<Vec<u64>> = (0..5u64)
.map(|q| {
let hits = index.search(&random_vector(q + 100_000), 10).unwrap();
hits.iter().map(|hit| hit.id).collect()
})
.collect();
let graph = &index.graph;
let shape = (graph.entry_point, graph.max_layer, graph.custom_ids);
let counts = (index.len(), index.deleted_count(), index.user_version());
format!("{:?}", (lists(index), ids, vectors, found, shape, counts, index.check()))
};
let reopened = VectorIndex::open(&crashed, 16, options.clone()).unwrap();
assert_eq!(state(&index), state(&reopened), "seed {seed}");
drop(reopened);
let committed = lists(&index);
for _ in 0..1 + rng(15) {
write(&mut index, &mut rng);
}
drop(index);
let index = VectorIndex::open(&path, 16, options).unwrap();
assert_eq!(lists(&index), committed, "seed {seed}, after a crash");
}
}
#[test]
fn test_an_undo_file_saved_from_an_earlier_commit_is_ignored() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("index.chassis");
let undo = storage::sibling(&path, "undo");
let (mut index, _) = index_with_unflushed_adds(&path);
let stale = std::fs::read(&undo).unwrap();
index.flush().unwrap();
let flushed = lists(&index);
drop(index);
std::fs::write(&undo, stale).unwrap();
let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
assert_eq!(lists(&index), flushed);
assert!(!undo.exists());
}
#[test]
fn test_a_torn_undo_file_restores_the_entries_it_holds_whole() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("index.chassis");
let undo = storage::sibling(&path, "undo");
let (index, committed) = index_with_unflushed_adds(&path);
drop(index);
let saved = std::fs::read(&undo).unwrap();
std::fs::write(&undo, &saved[..saved.len() - 3]).unwrap();
let differing = |index: &VectorIndex| {
let restored = lists(index);
(0..300).filter(|&slot| restored[slot] != committed[slot]).count()
};
let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
assert_eq!(differing(&index), 1, "only the node whose entry was torn keeps lost links");
drop(index);
let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
index.add_batch(&(300..2000).flat_map(random_vector).collect::<Vec<f32>>()).unwrap();
drop(index);
let mut saved = std::fs::read(&undo).unwrap();
saved[23] ^= 1; std::fs::write(&undo, &saved).unwrap();
let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
assert!(differing(&index) > 100, "nothing after the corrupt entry is trusted");
}
#[test]
fn test_links_an_older_crash_left_dont_stop_a_rollback() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("index.chassis");
let (index, _) = index_with_unflushed_adds(&path);
drop(index);
std::fs::remove_file(storage::sibling(&path, "undo")).unwrap();
let committed_only = |index: &VectorIndex| -> Vec<Vec<Vec<u64>>> {
let keep = |ids: Vec<u64>| ids.into_iter().filter(|&id| id < 300).collect();
lists(index).into_iter().map(|node| node.into_iter().map(keep).collect()).collect()
};
let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
assert_ne!(lists(&index), committed_only(&index), "links to lost slots remain");
let before = committed_only(&index);
index.add_batch(&(300..2000).flat_map(random_vector).collect::<Vec<f32>>()).unwrap();
drop(index);
let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
assert_eq!(committed_only(&index), before);
}
#[test]
fn test_adds_lost_after_a_compaction_are_rolled_back_too() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("index.chassis");
let (mut index, _) = index_with_unflushed_adds(&path);
index.compact().unwrap();
let committed = lists(&index);
index.add_batch(&(2000..4000).flat_map(random_vector).collect::<Vec<f32>>()).unwrap();
assert!(storage::sibling(&path, "undo").exists(), "the undo file follows the rename");
drop(index);
let index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
assert_eq!(lists(&index), committed);
}
#[test]
fn test_a_new_index_built_in_one_go_saves_nothing() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("index.chassis");
let mut index = VectorIndex::open(&path, 16, IndexOptions::default()).unwrap();
index.add_batch(&(0..500).flat_map(random_vector).collect::<Vec<f32>>()).unwrap();
for id in 500..600 {
index.add(&random_vector(id)).unwrap();
}
assert!(!storage::sibling(&path, "undo").exists(), "nothing committed could change");
}
#[test]
fn test_selecting_from_known_distances_matches_computing_them() {
let file = NamedTempFile::new().unwrap();
let index = filter_index(&file);
let graph = &index.graph;
for base in [0u64, 7, 1234, 2499] {
let ids: Vec<u64> = (0..300).map(|i| (base + 1 + i * 8) % 2500).collect();
let from = graph.storage.get_vector_slice(base).unwrap();
let to = |id| graph.storage.get_vector_slice(id).unwrap();
let mut near: Vec<(u64, f32)> =
ids.iter().map(|&id| (id, euclidean_distance(from, to(id)))).collect();
near.sort_by(|a, b| a.1.total_cmp(&b.1));
for max in [8, 32] {
let computed = graph.select_neighbors_heuristic(base, &ids, 0, max, None).unwrap();
assert_eq!(graph.select_diverse(&near, max, None).unwrap(), computed);
assert!(!computed.is_empty() && computed.len() <= max);
}
}
}
#[test]
fn test_the_descent_stops_where_no_neighbor_is_nearer() {
let file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
let vectors: Vec<f32> = (0..3000).flat_map(random_vector).collect();
index.add_batch(&vectors).unwrap();
let graph = &index.graph;
let entry = graph.entry_point.unwrap();
let to = |query: &[f32], slot| {
euclidean_distance(query, graph.storage.get_vector_slice(slot).unwrap())
};
assert!(graph.max_layer > 0);
for query in (5000..5020).map(random_vector) {
for layer in 1..=graph.max_layer {
let found = graph.search_layer_greedy(&query, entry, layer).unwrap();
let nearest = to(&query, found);
assert!(nearest <= to(&query, entry));
let mut neighbors = graph.neighbors_iter_from_mmap(found, layer).unwrap();
assert!(neighbors.all(|n| to(&query, n) >= nearest), "layer {layer}");
}
}
}
#[test]
fn test_batch_entry_point_is_on_the_top_layer() {
for existing in [0, 50] {
let file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
for id in 0..existing {
index.add(&random_vector(id)).unwrap();
}
let vectors: Vec<f32> = (existing..existing + 3000).flat_map(random_vector).collect();
index.add_batch(&vectors).unwrap();
let graph = &index.graph;
let layers = |slot| graph.storage.layer_count(slot).unwrap() - 1;
let top = (0..graph.node_count()).map(layers).max().unwrap();
assert!(top > 0, "3,050 draws should reach layer 1");
assert_eq!((graph.max_layer, layers(graph.entry_point.unwrap())), (top, top));
}
}
#[test]
fn test_filtered_scan_is_exact_with_a_nan_vector() {
let file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(file.path(), 16, IndexOptions::default()).unwrap();
index.insert(0, &[f32::NAN; 16]).unwrap();
for id in 1..300 {
index.add(&random_vector(id)).unwrap();
}
let allow = |slot: u64| slot.is_multiple_of(10);
let (found, scanned) = index
.graph
.search_filtered_reporting(&random_vector(150), 3, 50, &|s| Ok(allow(s)))
.unwrap();
assert!(scanned);
assert_eq!(found[0].id, 150, "{found:?}");
}
#[test]
fn test_vector_index_create_and_add() {
let temp_file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(temp_file.path(), 128, IndexOptions::default()).unwrap();
assert_eq!(index.len(), 0);
assert!(index.is_empty());
assert_eq!(index.dimensions(), 128);
let vector = vec![0.1; 128];
let id = index.add(&vector).unwrap();
assert_eq!(id, 0);
assert_eq!(index.len(), 1);
assert!(!index.is_empty());
}
#[test]
fn test_vector_index_dimension_mismatch() {
let temp_file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(temp_file.path(), 128, IndexOptions::default()).unwrap();
let vector = vec![0.1; 64];
let result = index.add(&vector);
assert_eq!(result.unwrap_err().kind(), ErrorKind::DimensionMismatch);
}
#[test]
fn test_vector_index_search() {
let temp_file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(temp_file.path(), 128, IndexOptions::default()).unwrap();
for i in 0..10 {
let mut vector = vec![0.0; 128];
vector[0] = i as f32 / 10.0;
index.add(&vector).unwrap();
}
let query = vec![0.5; 128];
let results = index.search(&query, 5).unwrap();
assert!(results.len() <= 5);
assert!(results.len() <= 10);
}
#[test]
fn test_vector_index_persistence() {
let temp_file = NamedTempFile::new().unwrap();
let path = temp_file.path().to_owned();
{
let mut index = VectorIndex::open(&path, 128, IndexOptions::default()).unwrap();
for i in 0..5 {
let mut vector = vec![0.0; 128];
vector[0] = i as f32;
index.add(&vector).unwrap();
}
index.flush().unwrap();
}
{
let index = VectorIndex::open(&path, 128, IndexOptions::default()).unwrap();
assert_eq!(index.len(), 5);
let mut query = vec![0.0; 128];
query[0] = 2.0;
let results = index.search(&query, 3).unwrap();
assert!(!results.is_empty());
}
}
#[test]
fn test_ghost_node_recovery() {
let temp_file = NamedTempFile::new().unwrap();
let path = temp_file.path().to_owned();
{
let storage = Storage::open(&path, 128).unwrap();
let params = HnswParams::default();
let mut graph = HnswGraph::open(storage, params).unwrap();
let vector = vec![1.0; 128];
graph.storage.insert(&vector).unwrap();
graph.commit().unwrap();
assert_eq!(graph.storage.count(), 1);
assert_eq!(graph.node_count(), 0);
}
{
let mut index = VectorIndex::open(&path, 128, IndexOptions::default()).unwrap();
assert_eq!(index.len(), 0);
let vector = vec![2.0; 128];
let id = index.add(&vector).unwrap();
assert_eq!(id, 0);
assert_eq!(index.len(), 1);
}
}
#[test]
fn test_diverse_neighbor_selection() {
let temp_file = NamedTempFile::new().unwrap();
let mut index = VectorIndex::open(temp_file.path(), 128, IndexOptions::default()).unwrap();
for i in 0..20 {
let mut vector = vec![0.0; 128];
vector[0] = i as f32;
index.add(&vector).unwrap();
}
assert_eq!(index.len(), 20);
let query = vec![10.0; 128];
let results = index.search(&query, 5).unwrap();
assert!(!results.is_empty());
}
}