pub mod filter;
pub mod postings;
pub mod score;
pub mod simd;
pub mod slots;
pub mod stem;
pub mod text;
use crate::store::ValueRef;
use ahash::AHashMap;
use parking_lot::RwLock;
use rand::Rng;
use std::sync::Arc;
use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize};
pub static SNAPSHOT_INDEX_REBUILD: AtomicBool = AtomicBool::new(false);
pub static DEFER_INDEXING: AtomicBool = AtomicBool::new(false);
#[inline]
fn indexing_deferred() -> bool {
DEFER_INDEXING.load(Relaxed)
}
#[derive(Debug, Clone, PartialEq)]
pub enum DistanceMetric {
L2,
Cosine,
InnerProduct,
}
impl DistanceMetric {
pub fn metric_from_str(s: &str) -> Option<Self> {
match s.to_ascii_uppercase().as_str() {
"L2" => Some(Self::L2),
"COSINE" => Some(Self::Cosine),
"IP" | "INNERPRODUCT" => Some(Self::InnerProduct),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum VectorAlgo {
Flat,
Hnsw {
m: usize,
ef_construction: usize,
ef_runtime: usize,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VectorType {
#[default]
Float32,
Float64,
Float16,
BFloat16,
}
impl VectorType {
pub fn parse(s: &str) -> Option<Self> {
match s.to_ascii_uppercase().as_str() {
"FLOAT32" => Some(Self::Float32),
"FLOAT64" => Some(Self::Float64),
"FLOAT16" => Some(Self::Float16),
"BFLOAT16" => Some(Self::BFloat16),
_ => None,
}
}
pub fn name(self) -> &'static str {
match self {
Self::Float32 => "FLOAT32",
Self::Float64 => "FLOAT64",
Self::Float16 => "FLOAT16",
Self::BFloat16 => "BFLOAT16",
}
}
pub fn size(self) -> usize {
match self {
Self::Float32 => 4,
Self::Float64 => 8,
Self::Float16 | Self::BFloat16 => 2,
}
}
pub fn decode(self, blob: &[u8], dim: usize) -> Option<Vec<f32>> {
if blob.len() != dim * self.size() {
return None;
}
Some(match self {
Self::Float32 => blob
.as_chunks::<4>()
.0
.iter()
.map(|b| f32::from_le_bytes(*b))
.collect(),
Self::Float64 => blob
.as_chunks::<8>()
.0
.iter()
.map(|b| f64::from_le_bytes(*b) as f32)
.collect(),
Self::Float16 => blob
.as_chunks::<2>()
.0
.iter()
.map(|b| crate::commands::json_fpha::f16_bits_to_f32(u16::from_le_bytes(*b)))
.collect(),
Self::BFloat16 => blob
.as_chunks::<2>()
.0
.iter()
.map(|b| f32::from_bits(u32::from(u16::from_le_bytes(*b)) << 16))
.collect(),
})
}
pub fn encode(self, value: f64, out: &mut Vec<u8>) {
match self {
Self::Float32 => out.extend_from_slice(&(value as f32).to_le_bytes()),
Self::Float64 => out.extend_from_slice(&value.to_le_bytes()),
Self::Float16 => out.extend_from_slice(
&crate::commands::json_fpha::f32_to_f16_bits(value as f32).to_le_bytes(),
),
Self::BFloat16 => {
let rounded = crate::commands::json_fpha::f32_to_bf16(value as f32);
out.extend_from_slice(&((rounded.to_bits() >> 16) as u16).to_le_bytes());
}
}
}
}
#[derive(Debug, Clone)]
pub enum FieldType {
Text,
Tag,
Numeric,
Vector {
algo: VectorAlgo,
dim: usize,
metric: DistanceMetric,
data_type: VectorType,
},
}
#[derive(Debug, Clone)]
pub struct SchemaField {
pub name: String,
pub field_type: FieldType,
pub options: FieldOptions,
}
impl SchemaField {
pub fn attribute(&self) -> &str {
self.options.alias.as_deref().unwrap_or(&self.name)
}
pub fn type_name(&self) -> &'static str {
match self.field_type {
FieldType::Text => "TEXT",
FieldType::Tag => "TAG",
FieldType::Numeric => "NUMERIC",
FieldType::Vector { .. } => "VECTOR",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FieldOptions {
pub alias: Option<String>,
pub sortable: bool,
pub unf: bool,
pub noindex: bool,
pub weight: f64,
pub nostem: bool,
pub phonetic: Option<String>,
pub separator: char,
pub case_sensitive: bool,
pub with_suffix_trie: bool,
pub index_empty: bool,
pub index_missing: bool,
}
impl Default for FieldOptions {
fn default() -> Self {
Self {
alias: None,
sortable: false,
unf: false,
noindex: false,
weight: 1.0,
nostem: false,
phonetic: None,
separator: ',',
case_sensitive: false,
with_suffix_trie: false,
index_empty: false,
index_missing: false,
}
}
}
impl FieldOptions {
pub fn consume(
&mut self,
field: &str,
field_type: &FieldType,
args: &[&[u8]],
i: &mut usize,
) -> Result<(), String> {
let text = matches!(field_type, FieldType::Text);
let tag = matches!(field_type, FieldType::Tag);
let vector = matches!(field_type, FieldType::Vector { .. });
while let Some(word) = args.get(*i).and_then(|a| std::str::from_utf8(a).ok()) {
let mut value = |what: &str| -> Result<String, String> {
let value = args
.get(*i + 1)
.and_then(|a| std::str::from_utf8(a).ok())
.ok_or_else(|| format!("{what} of field `{field}` needs a value"))?;
*i += 1;
Ok(value.to_string())
};
match word.to_ascii_uppercase().as_str() {
"SORTABLE" if !vector => {
self.sortable = true;
if args
.get(*i + 1)
.is_some_and(|a| a.eq_ignore_ascii_case(b"UNF"))
{
self.unf = true;
*i += 1;
}
}
"NOINDEX" if !vector => self.noindex = true,
"INDEXMISSING" => self.index_missing = true,
"INDEXEMPTY" if text || tag => self.index_empty = true,
"WITHSUFFIXTRIE" if text || tag => self.with_suffix_trie = true,
"WEIGHT" if text => {
let raw = value("WEIGHT")?;
self.weight = raw
.parse::<f64>()
.ok()
.filter(|w| w.is_finite() && *w >= 0.0)
.ok_or_else(|| format!("Invalid WEIGHT `{raw}` for field `{field}`"))?;
}
"NOSTEM" if text => self.nostem = true,
"PHONETIC" if text => self.phonetic = Some(value("PHONETIC")?),
"SEPARATOR" if tag => {
let raw = value("SEPARATOR")?;
let mut chars = raw.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => self.separator = c,
_ => {
return Err(format!(
"Tag separator of field `{field}` must be a single character"
));
}
}
}
"CASESENSITIVE" if tag => self.case_sensitive = true,
_ => break,
}
*i += 1;
}
Ok(())
}
pub fn words(&self, field_type: &FieldType) -> Vec<String> {
let mut out = Vec::new();
match field_type {
FieldType::Text => {
out.push("WEIGHT".to_string());
out.push(format_weight(self.weight));
if self.nostem {
out.push("NOSTEM".into());
}
if let Some(matcher) = &self.phonetic {
out.push("PHONETIC".into());
out.push(matcher.clone());
}
}
FieldType::Tag => {
out.push("SEPARATOR".to_string());
out.push(self.separator.to_string());
if self.case_sensitive {
out.push("CASESENSITIVE".into());
}
}
FieldType::Numeric | FieldType::Vector { .. } => {}
}
if self.with_suffix_trie {
out.push("WITHSUFFIXTRIE".into());
}
if self.index_empty {
out.push("INDEXEMPTY".into());
}
if self.index_missing {
out.push("INDEXMISSING".into());
}
if self.sortable {
out.push("SORTABLE".into());
if self.unf {
out.push("UNF".into());
}
}
if self.noindex {
out.push("NOINDEX".into());
}
out
}
}
impl IndexDef {
pub fn create_args(&self) -> Vec<Vec<u8>> {
let mut a: Vec<String> = vec![
"FT.CREATE".into(),
self.name.clone(),
"ON".into(),
match self.on {
IndexOn::Hash => "HASH",
IndexOn::Json => "JSON",
}
.into(),
];
if !self.prefixes.is_empty() {
a.push("PREFIX".into());
a.push(self.prefixes.len().to_string());
a.extend(self.prefixes.iter().cloned());
}
a.extend(self.language.words());
if let Some(words) = &self.stopwords {
a.push("STOPWORDS".into());
a.push(words.len().to_string());
a.extend(words.iter().cloned());
}
if self.default_score != 1.0 {
a.push("SCORE".into());
a.push(self.default_score.to_string());
}
if let Some(field) = &self.score_field {
a.push("SCORE_FIELD".into());
a.push(field.clone());
}
a.push("SCHEMA".into());
for field in &self.fields {
a.push(field.name.clone());
if let Some(alias) = &field.options.alias {
a.push("AS".into());
a.push(alias.clone());
}
a.push(field.type_name().into());
if let FieldType::Vector {
algo,
dim,
metric,
data_type,
} = &field.field_type
{
let mut attrs: Vec<String> = vec![
"TYPE".into(),
data_type.name().into(),
"DIM".into(),
dim.to_string(),
"DISTANCE_METRIC".into(),
match metric {
DistanceMetric::L2 => "L2",
DistanceMetric::Cosine => "COSINE",
DistanceMetric::InnerProduct => "IP",
}
.into(),
];
match algo {
VectorAlgo::Flat => a.push("FLAT".into()),
VectorAlgo::Hnsw {
m,
ef_construction,
ef_runtime,
} => {
a.push("HNSW".into());
attrs.extend([
"M".into(),
m.to_string(),
"EF_CONSTRUCTION".into(),
ef_construction.to_string(),
"EF_RUNTIME".into(),
ef_runtime.to_string(),
]);
}
}
a.push(attrs.len().to_string());
a.extend(attrs);
}
a.extend(field.options.words(&field.field_type));
}
a.into_iter().map(String::into_bytes).collect()
}
}
fn format_weight(weight: f64) -> String {
if weight.fract() == 0.0 {
format!("{}", weight as i64)
} else {
weight.to_string()
}
}
pub fn field_option_owner(word: &str) -> Option<&'static str> {
match word.to_ascii_uppercase().as_str() {
"WEIGHT" | "NOSTEM" | "PHONETIC" => Some("TEXT"),
"SEPARATOR" | "CASESENSITIVE" => Some("TAG"),
"SORTABLE" | "UNF" | "NOINDEX" => Some("TEXT, TAG and NUMERIC"),
"WITHSUFFIXTRIE" | "INDEXEMPTY" => Some("TEXT and TAG"),
"INDEXMISSING" => Some("every type of"),
_ => None,
}
}
#[derive(Debug, Clone)]
pub enum IndexOn {
Hash,
Json,
}
#[derive(Debug, Clone)]
pub enum LiveIndex {
Flat(Arc<VectorIndex>),
Hnsw(Arc<HnswIndex>),
}
pub type SynonymGroups = AHashMap<String, Vec<String>>;
#[inline]
pub(crate) fn is_token_separator(c: char) -> bool {
c.is_whitespace()
|| matches!(
c,
',' | '.'
| '/'
| '('
| ')'
| '{'
| '}'
| '['
| ']'
| ':'
| ';'
| '\\'
| '~'
| '!'
| '@'
| '#'
| '$'
| '%'
| '^'
| '&'
| '*'
| '-'
| '='
| '+'
| '|'
| '\''
| '`'
| '"'
| '<'
| '>'
| '?'
)
}
pub fn tokenize_for_vocab(text: &str) -> impl Iterator<Item = String> + '_ {
if text.contains('\\') {
Words::Escaped(text)
} else {
Words::Plain(
text.split(is_token_separator)
.filter(|word| !word.is_empty())
.map(str::to_lowercase),
)
}
}
enum Words<'a, P> {
Plain(P),
Escaped(&'a str),
}
impl<P: Iterator<Item = String>> Iterator for Words<'_, P> {
type Item = String;
fn next(&mut self) -> Option<String> {
match self {
Words::Plain(words) => words.next(),
Words::Escaped(rest) => loop {
let start = rest.find(|c| c == '\\' || !is_token_separator(c))?;
let text = &rest[start..];
let mut word = String::new();
let mut chars = text.char_indices();
let mut end = text.len();
while let Some((i, c)) = chars.next() {
if c == '\\' {
word.extend(chars.next().map(|(_, escaped)| escaped));
} else if is_token_separator(c) {
end = i;
break;
} else {
word.push(c);
}
}
*rest = &text[end..];
if !word.is_empty() {
return Some(word.to_lowercase());
}
},
}
}
}
pub fn is_stopword(tok: &str) -> bool {
matches!(
tok,
"a" | "an"
| "and"
| "are"
| "as"
| "at"
| "be"
| "but"
| "by"
| "for"
| "if"
| "in"
| "into"
| "is"
| "it"
| "no"
| "not"
| "of"
| "on"
| "or"
| "such"
| "that"
| "the"
| "their"
| "then"
| "there"
| "these"
| "they"
| "this"
| "to"
| "was"
| "will"
| "with"
)
}
#[derive(Debug, Clone)]
pub struct IndexDef {
pub name: String,
pub db_index: usize,
pub on: IndexOn,
pub prefixes: Vec<String>,
pub fields: Vec<SchemaField>,
pub indexes: AHashMap<String, LiveIndex>,
pub stopwords: Option<Arc<Vec<String>>>,
pub synonyms: SynonymGroups,
pub language: stem::LanguageOptions,
pub default_score: f64,
pub score_field: Option<String>,
pub doc_languages: Arc<RwLock<AHashMap<String, stem::Language>>>,
pub text: Arc<RwLock<text::TextIndex>>,
pub postings: postings::SharedPostings,
}
impl IndexDef {
pub fn text_fields(&self) -> impl Iterator<Item = &SchemaField> {
self.fields
.iter()
.filter(|f| matches!(f.field_type, FieldType::Text) && !f.options.noindex)
}
pub fn text_field(&self, name: &str) -> Option<u16> {
self.text_fields()
.position(|f| f.name == name)
.map(|i| i as u16)
}
pub fn text_units(&self) -> Vec<u32> {
self.text_fields()
.map(|f| (f.options.weight as u32).max(1))
.collect()
}
#[inline]
pub fn gives_ids(&self) -> bool {
self.fields.iter().any(|f| match f.field_type {
FieldType::Tag | FieldType::Numeric => true,
FieldType::Text => !f.options.noindex,
_ => false,
})
}
pub fn write_text(&self, doc: u32, changes: &[(u16, Vec<String>)]) {
if changes.is_empty() {
return;
}
let units = self.text_units();
self.text.write().set(doc, changes, |f| {
units.get(f as usize).copied().unwrap_or(1)
});
}
fn text_write(
&self,
mut changes: Vec<(u16, Vec<String>)>,
restemmed: Vec<(u16, bool)>,
language: stem::Language,
) -> Option<postings::WithId> {
if changes.is_empty() && restemmed.is_empty() {
return None;
}
let text = Arc::clone(&self.text);
let units = self.text_units();
Some(Box::new(move |doc| {
let mut text = text.write();
for (number, stems) in restemmed {
if let Some(tokens) = restem(&text, doc, number, stems, language) {
changes.push((number, tokens));
}
}
if !changes.is_empty() {
text.set(doc, &changes, |f| {
units.get(f as usize).copied().unwrap_or(1)
});
}
}))
}
fn text_removal(&self) -> Option<postings::WithId> {
self.text_fields().next()?;
let text = Arc::clone(&self.text);
let units = self.text_units();
Some(Box::new(move |doc| {
text.write()
.remove(doc, |f| units.get(f as usize).copied().unwrap_or(1));
}))
}
fn forget_language(&self, key: &str) {
if self.language.field.is_some() {
self.doc_languages.write().remove(key);
}
}
fn doc_language(
&self,
key: &str,
fields: &[(String, Arc<[u8]>)],
whole: bool,
) -> stem::Language {
let Some(name) = &self.language.field else {
return self.language.language;
};
let given = fields.iter().find(|(n, _)| n == name).map(|(_, v)| &**v);
if given.is_none() && !whole {
return self
.doc_languages
.read()
.get(key)
.copied()
.unwrap_or(self.language.language);
}
let language = self.language.of(given);
let mut languages = self.doc_languages.write();
if language == self.language.language {
languages.remove(key);
} else {
languages.insert(key.to_string(), language);
}
language
}
fn language_of(&self, key: &str, doc: &Fields) -> stem::Language {
let Some(name) = &self.language.field else {
return self.language.language;
};
let language = self.language.of(doc.get(name.as_str()).map(|v| &**v));
let mut languages = self.doc_languages.write();
if language == self.language.language {
languages.remove(key);
} else {
languages.insert(key.to_string(), language);
}
language
}
#[inline]
pub fn keeps_postings(&self) -> bool {
self.fields
.iter()
.any(|f| matches!(f.field_type, FieldType::Tag | FieldType::Numeric))
}
#[inline]
pub fn covers(&self, key: &[u8]) -> bool {
self.prefixes.is_empty() || self.prefixes.iter().any(|p| key.starts_with(p.as_bytes()))
}
pub fn is_stopword(&self, token: &str) -> bool {
match &self.stopwords {
Some(words) => words.iter().any(|w| w == token),
None => is_stopword(token),
}
}
pub fn field_by_attribute(&self, attribute: &str) -> Option<&SchemaField> {
self.fields.iter().find(|f| f.attribute() == attribute)
}
pub fn vector_fields(&self) -> impl Iterator<Item = &SchemaField> {
self.fields
.iter()
.filter(|f| matches!(f.field_type, FieldType::Vector { .. }))
}
pub fn vector_field_by_name(&self, name: &str) -> Option<&SchemaField> {
self.fields
.iter()
.find(|f| f.name == name && matches!(f.field_type, FieldType::Vector { .. }))
}
#[deprecated(note = "use vector_fields() or vector_field_by_name() instead")]
pub fn vector_field(&self) -> Option<&SchemaField> {
self.vector_fields().next()
}
}
pub type IndexStore = Arc<Indexes>;
#[derive(Default)]
pub struct Indexes {
any: OwnLine,
map: RwLock<AHashMap<String, IndexDef>>,
raising: AtomicUsize,
}
#[derive(Default)]
#[repr(align(128))]
struct OwnLine(AtomicBool);
impl Indexes {
#[inline]
pub fn read(&self) -> parking_lot::RwLockReadGuard<'_, AHashMap<String, IndexDef>> {
self.map.read()
}
pub fn write(&self) -> IndexesWriteGuard<'_> {
let map = self.map.write();
self.any.0.store(true, std::sync::atomic::Ordering::SeqCst);
IndexesWriteGuard {
map,
any: &self.any.0,
raising: &self.raising,
}
}
pub fn write_to_add(&self) -> Result<IndexesWriteGuard<'_>, &'static str> {
let mut map = self.map.write();
let first = map.is_empty() && !crate::command_gate::alone_on_this_thread();
if first && (crate::tag_locks::beside_others() || crate::write_order::holds_stripes()) {
return Err(FIRST_INDEX_BESIDE_OTHERS);
}
self.any.0.store(true, std::sync::atomic::Ordering::SeqCst);
if first {
self.raising.fetch_add(1, Relaxed);
drop(map);
crate::write_order::barrier();
map = self.map.write();
self.raising.fetch_sub(1, Relaxed);
}
Ok(IndexesWriteGuard {
map,
any: &self.any.0,
raising: &self.raising,
})
}
#[inline]
pub fn none(&self) -> bool {
!self.any.0.load(Acquire)
}
}
pub const FIRST_INDEX_BESIDE_OTHERS: &str = "ERR the first search index cannot be created \
from a script that runs beside other scripts (lua-parallel-scripts): create it outside \
the script";
pub struct IndexesWriteGuard<'a> {
map: parking_lot::RwLockWriteGuard<'a, AHashMap<String, IndexDef>>,
any: &'a AtomicBool,
raising: &'a AtomicUsize,
}
impl std::ops::Deref for IndexesWriteGuard<'_> {
type Target = AHashMap<String, IndexDef>;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl std::ops::DerefMut for IndexesWriteGuard<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.map
}
}
impl Drop for IndexesWriteGuard<'_> {
fn drop(&mut self) {
let any = !self.map.is_empty() || self.raising.load(Relaxed) > 0;
self.any.store(any, Release);
}
}
#[inline]
pub fn is_alias(key: &str, def: &IndexDef) -> bool {
key != def.name
}
pub fn resolve_index_name(store: &AHashMap<String, IndexDef>, name: &str) -> Option<String> {
let def = store.get(name)?;
store.contains_key(&def.name).then(|| def.name.clone())
}
pub fn alias_target(store: &AHashMap<String, IndexDef>, name: &str) -> Option<String> {
let def = store.get(name)?;
(is_alias(name, def) && store.contains_key(&def.name)).then(|| def.name.clone())
}
pub fn index_aliases(store: &AHashMap<String, IndexDef>, index: &str) -> Vec<String> {
let mut aliases: Vec<String> = store
.iter()
.filter(|(key, def)| def.name == index && is_alias(key, def))
.map(|(key, _)| key.clone())
.collect();
aliases.sort_unstable();
aliases
}
pub fn set_alias(store: &mut AHashMap<String, IndexDef>, alias: &str, index: &IndexDef) {
let marker = IndexSchema {
name: index.name.clone(),
db_index: index.db_index,
on: index.on.clone(),
prefixes: Vec::new(),
fields: Vec::new(),
aliases: Vec::new(),
stopwords: None,
synonyms: Default::default(),
language: Default::default(),
default_score: 1.0,
score_field: None,
}
.into_def();
store.insert(alias.to_string(), marker);
}
pub fn remove_index(store: &mut AHashMap<String, IndexDef>, index: &str) -> bool {
if store.get(index).is_none_or(|def| is_alias(index, def)) {
return false;
}
store.retain(|_, def| def.name != index);
true
}
pub fn new_index_store() -> IndexStore {
Arc::new(Indexes::default())
}
pub fn drop_all_indexes(index_store: &IndexStore) -> usize {
let mut g = index_store.write();
let n = g.len();
*g = AHashMap::new();
n
}
pub fn drop_indexes_for_db(index_store: &IndexStore, db_index: usize) -> usize {
let mut g = index_store.write();
let before = g.len();
g.retain(|_, def| def.db_index != db_index);
before - g.len()
}
#[derive(Debug, Clone)]
pub struct IndexSchema {
pub name: String,
pub db_index: usize,
pub on: IndexOn,
pub prefixes: Vec<String>,
pub fields: Vec<SchemaField>,
pub aliases: Vec<String>,
pub stopwords: Option<Vec<String>>,
pub synonyms: SynonymGroups,
pub language: stem::LanguageOptions,
pub default_score: f64,
pub score_field: Option<String>,
}
impl IndexSchema {
pub fn into_def(self) -> IndexDef {
let mut indexes: AHashMap<String, LiveIndex> = AHashMap::new();
for f in &self.fields {
if let FieldType::Vector { algo, .. } = &f.field_type {
let live = match algo {
VectorAlgo::Flat => LiveIndex::Flat(Arc::new(VectorIndex::new())),
VectorAlgo::Hnsw {
m, ef_construction, ..
} => LiveIndex::Hnsw(Arc::new(HnswIndex::new(*m, *ef_construction))),
};
indexes.insert(f.name.clone(), live);
}
}
let postings = postings::PostingsLock::new(postings::Postings::new(&self.fields));
IndexDef {
name: self.name,
db_index: self.db_index,
on: self.on,
prefixes: self.prefixes,
fields: self.fields,
indexes,
stopwords: self.stopwords.map(Arc::new),
synonyms: self.synonyms,
language: self.language,
default_score: self.default_score,
score_field: self.score_field,
doc_languages: Arc::new(RwLock::new(AHashMap::new())),
text: Arc::new(RwLock::new(text::TextIndex::new())),
postings,
}
}
}
pub fn backfill_text_fields(db: &crate::store::Db, def: &IndexDef, fields: &[String]) {
walk_documents(db, def, |key, inner| {
let language = def.language_of(key, &inner);
let mut changes = Vec::new();
for field in fields {
let Some(text) = inner.get(field).and_then(|b| std::str::from_utf8(b).ok()) else {
continue;
};
let Some(schema) = def.fields.iter().find(|f| &f.name == field) else {
continue;
};
let Some(number) = def.text_field(field) else {
continue;
};
changes.push((number, stem::index_words(def, schema, language, text)));
}
if !changes.is_empty() {
let doc = def.postings.write().ensure(key);
def.write_text(doc, &changes);
}
});
}
pub fn backfill_postings(db: &crate::store::Db, def: &IndexDef, added: &[SchemaField], scan: bool) {
def.postings.write().add_fields(added);
walk_documents(db, def, |key, inner| {
let mut postings = def.postings.write();
if scan {
postings.write_doc(key, &inner);
} else {
postings.ensure(key);
}
def.postings.done(postings);
});
}
pub fn walk_documents(
db: &crate::store::Db,
def: &IndexDef,
mut visit: impl FnMut(&str, DocFields<'_>),
) {
for shard in db.iter() {
let keys: Vec<crate::store::Key> = shard
.read()
.keys()
.filter(|key| def.covers(key))
.map(crate::store::Key::new)
.collect();
for key in keys {
let _order = crate::write_order::lock_key_for_walk(def.db_index, &key);
let map = shard.read();
let Some(inner) = map
.peek(&key)
.and_then(|value| doc_fields(&def.on, &def.fields, value))
else {
continue;
};
crate::aof::failpoint("index-walk-read");
visit(&crate::key_bytes::text_of(&key), inner);
}
}
}
pub fn rebuild_indexes(index_store: &IndexStore, store: &crate::store::Store) {
let rebuilt: Vec<IndexDef> = {
let mut indexes = index_store.write();
let names: Vec<String> = indexes
.iter()
.filter(|(name, def)| !is_alias(name, def))
.map(|(name, _)| name.clone())
.collect();
let mut rebuilt = Vec::with_capacity(names.len());
for name in names {
let def = &indexes[&name];
let fresh = IndexSchema {
name: def.name.clone(),
db_index: def.db_index,
on: def.on.clone(),
prefixes: def.prefixes.clone(),
fields: def.fields.clone(),
aliases: Vec::new(),
stopwords: def.stopwords.as_deref().cloned(),
synonyms: def.synonyms.clone(),
language: def.language.clone(),
default_score: def.default_score,
score_field: def.score_field.clone(),
}
.into_def();
indexes.insert(name, fresh.clone());
rebuilt.push(fresh);
}
rebuilt
};
for def in rebuilt {
if let Some(db) = store.get(def.db_index) {
backfill_from_db(db, &def);
}
}
}
pub fn backfill_from_db(db: &crate::store::Db, def: &IndexDef) {
backfill_from_db_progress(db, def, false, false);
}
const BACKFILL_PROGRESS_KEYS: usize = 50_000;
pub fn backfill_from_db_progress(
db: &crate::store::Db,
def: &IndexDef,
log_progress: bool,
keep_loaded_hnsw: bool,
) {
struct VecFieldWork {
name: String,
dim: usize,
data_type: VectorType,
metric: DistanceMetric,
live: LiveIndex,
loaded: bool,
}
let mut vec_work: Vec<VecFieldWork> = Vec::new();
for vf in def.vector_fields() {
let (dim, data_type, metric) = match &vf.field_type {
FieldType::Vector {
dim,
data_type,
metric,
..
} => (*dim, *data_type, metric.clone()),
_ => continue,
};
let live = match def.indexes.get(&vf.name) {
Some(LiveIndex::Flat(a)) => LiveIndex::Flat(Arc::clone(a)),
Some(LiveIndex::Hnsw(a)) => LiveIndex::Hnsw(Arc::clone(a)),
None => continue,
};
let loaded = keep_loaded_hnsw
&& matches!(&live, LiveIndex::Hnsw(idx) if idx.live_count.load(Relaxed) > 0);
vec_work.push(VecFieldWork {
name: vf.name.clone(),
dim,
data_type,
metric,
live,
loaded,
});
}
let text_fields: Vec<&SchemaField> = def.text_fields().collect();
let gives_ids = def.gives_ids();
let mut keys_matched: usize = 0;
walk_documents(db, def, |key, inner| {
keys_matched += 1;
if log_progress && keys_matched.is_multiple_of(BACKFILL_PROGRESS_KEYS) {
log_verbose!(
"Index backfill `{}`: processed ~{} matching keysā¦",
def.name,
keys_matched
);
}
let doc = if gives_ids {
let mut postings = def.postings.write();
let doc = postings.write_doc(key, &inner);
def.postings.done(postings);
doc
} else {
postings::NO_DOC
};
for w in &vec_work {
let raw_bytes = match inner.get(&w.name) {
Some(b) => b.clone(),
None => continue,
};
let Some(vec) = w.data_type.decode(&raw_bytes, w.dim) else {
continue;
};
match &w.live {
LiveIndex::Flat(idx) => idx.insert(key.to_string(), vec),
LiveIndex::Hnsw(idx) => {
if w.loaded && holds_vector(idx, key, &vec, &w.metric) {
continue;
}
hnsw_insert_doc(idx, key.to_string(), vec, &w.metric, doc);
}
}
}
if text_fields.is_empty() {
return;
}
let language = def.language_of(key, &inner);
let mut changes = Vec::new();
for (number, field) in text_fields.iter().enumerate() {
if let Some(raw) = inner.get(&field.name)
&& let Ok(s) = std::str::from_utf8(raw)
{
changes.push((number as u16, stem::index_words(def, field, language, s)));
}
}
def.write_text(doc, &changes);
});
for w in vec_work.iter().filter(|w| w.loaded) {
let LiveIndex::Hnsw(idx) = &w.live else {
continue;
};
let keys: Vec<String> = idx.key_to_id.read().keys().cloned().collect();
for key in keys {
let raw = crate::key_bytes::bytes_of(&key);
let map = crate::store::get_shard(db, &*raw).read();
let holds = def.covers(&raw)
&& map
.peek(&*raw)
.and_then(|value| doc_fields(&def.on, &def.fields, value))
.and_then(|inner| {
inner
.get(&w.name)
.map(|raw| w.data_type.decode(raw, w.dim).is_some())
})
.unwrap_or(false);
if !holds {
unindex_vector(&w.live, &key);
}
}
}
}
fn holds_vector(index: &HnswIndex, key: &str, vector: &[f32], metric: &DistanceMetric) -> bool {
let Some(id) = index.key_to_id.read().get(key).copied() else {
return false;
};
let nodes = index.nodes.read();
let Some(held) = index.vector_of(&nodes, id, key) else {
return false;
};
if matches!(metric, DistanceMetric::Cosine) {
held == normalize_to_unit(vector.to_vec()).as_slice()
} else {
held == vector
}
}
#[derive(Debug, Clone)]
pub struct CompactionRequest {
pub index_name: String,
pub field_name: String,
}
pub type CompactionTx = std::sync::mpsc::SyncSender<CompactionRequest>;
pub type CompactionRx = std::sync::mpsc::Receiver<CompactionRequest>;
pub const COMPACTION_CHANNEL_CAPACITY: usize = 32;
pub fn new_compaction_channel() -> (CompactionTx, CompactionRx) {
std::sync::mpsc::sync_channel(COMPACTION_CHANNEL_CAPACITY)
}
pub const COMPACTION_THRESHOLD: f64 = 0.20;
pub const COMPACTION_MIN_TOMBSTONES: usize = 64;
pub type DictStore = Arc<RwLock<AHashMap<String, ahash::AHashSet<String>>>>;
static DICT_STORES: RwLock<Vec<(usize, DictStore)>> = RwLock::new(Vec::new());
pub fn register_dict_store(index_store: &IndexStore, dicts: &DictStore) {
let id = Arc::as_ptr(index_store) as usize;
let mut stores = DICT_STORES.write();
stores.retain(|(other, _)| *other != id);
stores.push((id, Arc::clone(dicts)));
}
pub fn dict_store_for(index_store: &IndexStore) -> Option<DictStore> {
let id = Arc::as_ptr(index_store) as usize;
DICT_STORES
.read()
.iter()
.find(|(other, _)| *other == id)
.map(|(_, dicts)| Arc::clone(dicts))
}
pub fn restore_dictionaries(index_store: &IndexStore, dictionaries: Vec<(String, Vec<String>)>) {
if dictionaries.is_empty() {
return;
}
let Some(dicts) = dict_store_for(index_store) else {
return;
};
let mut dicts = dicts.write();
for (name, terms) in dictionaries {
dicts.entry(name).or_default().extend(terms);
}
}
pub fn new_dict_store() -> DictStore {
Arc::new(RwLock::new(AHashMap::new()))
}
pub fn drop_all_dicts(dict_store: &DictStore) {
let mut g = dict_store.write();
*g = AHashMap::new();
}
#[derive(Debug, Default)]
pub struct VectorIndex {
pub vectors: RwLock<AHashMap<String, Vec<f32>>>,
}
impl VectorIndex {
pub fn new() -> Self {
Self {
vectors: RwLock::new(AHashMap::new()),
}
}
pub fn insert(&self, key: String, vec: Vec<f32>) {
self.vectors.write().insert(key, vec);
}
}
#[derive(Debug)]
pub struct HnswNode {
pub key: String,
upper: parking_lot::Mutex<Vec<Vec<u32>>>,
level: usize,
pub doc: AtomicU32,
}
impl HnswNode {
fn new(key: String, level: usize, upper: Vec<Vec<u32>>, doc: u32) -> Self {
Self {
key,
upper: parking_lot::Mutex::new(upper),
level,
doc: AtomicU32::new(doc),
}
}
fn empty() -> Self {
Self::new(String::new(), 0, Vec::new(), postings::NO_DOC)
}
pub fn layer_count(&self) -> usize {
self.level + 1
}
}
pub type HnswNodes = boxcar::Vec<HnswNode>;
type NodesGuard<'a> = parking_lot::RwLockReadGuard<'a, HnswNodes>;
#[derive(Debug, Default)]
pub struct HnswIndex {
pub nodes: RwLock<HnswNodes>,
slots: std::sync::OnceLock<slots::Slots>,
pub key_to_id: RwLock<AHashMap<String, usize>>,
pub entry_point: RwLock<Option<usize>>, pub m: usize, pub m0: usize, pub ef_construction: usize,
pub ml: f64,
pub live_count: AtomicUsize,
pub tombstone_count: AtomicUsize,
pub compaction_in_progress: AtomicBool,
free: parking_lot::Mutex<Vec<u32>>,
reused: AtomicU64,
}
impl HnswIndex {
pub fn new(m: usize, ef_construction: usize) -> Self {
Self {
nodes: RwLock::new(HnswNodes::new()),
slots: std::sync::OnceLock::new(),
key_to_id: RwLock::new(AHashMap::new()),
entry_point: RwLock::new(None),
m,
m0: m * 2,
ef_construction,
ml: 1.0 / (m as f64).ln(),
live_count: AtomicUsize::new(0),
tombstone_count: AtomicUsize::new(0),
compaction_in_progress: AtomicBool::new(false),
free: parking_lot::Mutex::new(Vec::new()),
reused: AtomicU64::new(0),
}
}
pub fn restore(
m: usize,
ef_construction: usize,
nodes: Vec<Option<RestoredNode>>,
entry_point: Option<usize>,
) -> Self {
let mut index = Self::new(m, ef_construction);
let dim = nodes.iter().flatten().map(|n| n.vector.len()).next();
let slots = dim.map(|dim| {
index
.slots
.get_or_init(|| slots::Slots::new(dim, index.m0 + slack(index.m0)))
});
let count = nodes.len();
{
let graph = index.nodes.get_mut();
let mut key_to_id = index.key_to_id.write();
let mut free = index.free.lock();
for (id, entry) in nodes.into_iter().enumerate() {
if let Some(slots) = slots {
slots.reserve(id);
}
let node = match (entry, slots) {
(Some(n), Some(slots)) if n.vector.len() == slots.dim() => {
let mut layers = n.neighbors.into_iter().map(|list| {
list.into_iter()
.filter(|&nb| nb < count && nb != id)
.map(|nb| nb as u32)
.collect::<Vec<u32>>()
});
let layer0 = layers.next().unwrap_or_default();
let upper: Vec<Vec<u32>> = layers.collect();
unsafe { slots.write_vector(id, &n.vector) };
slots.write_links(id, layer0);
slots.flag(id).store(1, Release);
key_to_id.insert(n.key.clone(), id);
index.live_count.fetch_add(1, Relaxed);
HnswNode::new(n.key, upper.len(), upper, postings::NO_DOC)
}
_ => {
free.push(id as u32);
index.tombstone_count.fetch_add(1, Relaxed);
HnswNode::empty()
}
};
graph.push(node);
}
free.reverse();
}
let entry_point = match entry_point {
Some(id) if index.is_live(id) => Some(id),
_ => index.key_to_id.read().values().next().copied(),
};
*index.entry_point.write() = entry_point;
index
}
#[inline]
pub fn slots(&self) -> Option<&slots::Slots> {
self.slots.get()
}
#[inline]
pub fn is_live(&self, id: usize) -> bool {
self.slots.get().is_some_and(|s| s.has(id) && s.is_live(id))
}
#[inline]
pub fn vector(&self, id: usize) -> Option<&[f32]> {
let s = self.slots.get()?;
(s.has(id) && s.is_live(id)).then(|| s.vector(id))
}
#[inline]
pub fn vector_of<'a>(
&'a self,
nodes: &'a HnswNodes,
id: usize,
key: &str,
) -> Option<&'a [f32]> {
let v = self.vector(id)?;
nodes.get(id).filter(|n| n.key == key).map(|_| v)
}
pub fn links(&self, nodes: &HnswNodes, id: usize, layer: usize, out: &mut Vec<u32>) {
if layer == 0 {
if let Some(s) = self.slots.get()
&& s.has(id)
{
s.read_links(id, out);
}
} else if let Some(node) = nodes.get(id)
&& let Some(list) = node.upper.lock().get(layer - 1)
{
out.extend_from_slice(list);
}
}
pub fn slot_bytes(&self) -> usize {
self.slots.get().map_or(0, |s| s.bytes())
}
fn delete(&self, nodes: &mut HnswNodes, id: usize) {
if !self.is_live(id) {
return;
}
let Some(s) = self.slots.get() else { return };
s.flag(id).store(0, Release);
s.write_links(id, std::iter::empty());
if let Some(node) = nodes.get_mut(id) {
*node = HnswNode::empty();
}
self.free.lock().push(id as u32);
self.tombstone_count.fetch_add(1, Relaxed);
self.live_count.fetch_sub(1, Relaxed);
}
pub fn random_level(&self) -> usize {
let mut rng = rand::thread_rng();
let f: f64 = rng.r#gen::<f64>();
(-f.ln() * self.ml).floor() as usize
}
pub fn tombstone_ratio(&self) -> f64 {
use std::sync::atomic::Ordering::Relaxed;
let tomb = self.tombstone_count.load(Relaxed);
let live = self.live_count.load(Relaxed);
let total = tomb + live;
if total == 0 {
0.0
} else {
tomb as f64 / total as f64
}
}
}
pub struct RestoredNode {
pub key: String,
pub vector: Vec<f32>,
pub neighbors: Vec<Vec<usize>>,
}
pub fn register_index_schemas(
index_store: &IndexStore,
schemas: &[IndexSchema],
hnsw_graphs: &std::collections::HashMap<
String,
std::collections::HashMap<String, Arc<HnswIndex>>,
>,
) {
if schemas.is_empty() {
return;
}
let mut idx = index_store
.write_to_add()
.unwrap_or_else(|_| index_store.write());
for schema in schemas {
let mut def = schema.clone().into_def();
if let Some(field_graphs) = hnsw_graphs.get(&def.name) {
for (field_name, hnsw_arc) in field_graphs {
if let Some(live) = def.indexes.get_mut(field_name) {
*live = LiveIndex::Hnsw(Arc::clone(hnsw_arc));
}
}
}
for alias in &schema.aliases {
if !idx.contains_key(alias) {
set_alias(&mut idx, alias, &def);
}
}
idx.insert(schema.name.clone(), def);
}
}
pub type Fields = crate::types::HashFields;
pub enum DocFields<'a> {
Hash(parking_lot::RwLockReadGuard<'a, Fields>),
HashEx(parking_lot::RwLockReadGuard<'a, crate::types::HashInner>),
Json {
fields: Fields,
doc: parking_lot::RwLockReadGuard<'a, serde_json::Value>,
},
}
impl DocFields<'_> {
pub fn json(&self) -> Option<&serde_json::Value> {
match self {
DocFields::Json { doc, .. } => Some(doc),
_ => None,
}
}
}
impl std::ops::Deref for DocFields<'_> {
type Target = Fields;
fn deref(&self) -> &Fields {
match self {
DocFields::Hash(fields) => fields,
DocFields::HashEx(hash) => &hash.fields,
DocFields::Json { fields, .. } => fields,
}
}
}
pub fn is_document(on: &IndexOn, value: crate::store::ValueRef<'_>) -> bool {
matches!(
(on, value),
(IndexOn::Hash, crate::store::ValueRef::Hash(_))
| (IndexOn::Hash, crate::store::ValueRef::HashEx(_))
| (IndexOn::Json, crate::store::ValueRef::Json(_))
)
}
pub fn doc_fields<'a>(
on: &IndexOn,
schema: &[SchemaField],
value: crate::store::ValueRef<'a>,
) -> Option<DocFields<'a>> {
match (on, value) {
(IndexOn::Hash, crate::store::ValueRef::Hash(hash)) => Some(DocFields::Hash(hash.read())),
(IndexOn::Hash, crate::store::ValueRef::HashEx(hash)) => {
Some(DocFields::HashEx(hash.read()))
}
(IndexOn::Json, crate::store::ValueRef::Json(doc)) => {
let doc = doc.read();
Some(DocFields::Json {
fields: project_json(schema, &doc),
doc,
})
}
_ => None,
}
}
fn json_path(path: &str) -> Option<Arc<crate::commands::json_path::Query>> {
use crate::commands::json_path::Query;
thread_local! {
static PARSED: std::cell::RefCell<AHashMap<String, Option<Arc<Query>>>> =
std::cell::RefCell::new(AHashMap::new());
}
PARSED.with(|parsed| {
let mut parsed = parsed.borrow_mut();
if let Some(query) = parsed.get(path) {
return query.clone();
}
if parsed.len() >= 1024 {
parsed.clear();
}
let query = Query::parse(path).ok().map(Arc::new);
parsed.insert(path.to_string(), query.clone());
query
})
}
pub fn project_json(schema: &[SchemaField], doc: &serde_json::Value) -> Fields {
let mut fields = Fields::with_capacity_and_hasher(schema.len(), Default::default());
for field in schema {
let Some(query) = json_path(&field.name) else {
continue;
};
let values = query.values(doc);
if let Some(bytes) = json_field_bytes(field, &values) {
fields.insert(field.name.clone(), bytes);
}
}
fields
}
fn json_strings<'a>(
values: &'a [std::borrow::Cow<'a, serde_json::Value>],
booleans: bool,
) -> Vec<std::borrow::Cow<'a, str>> {
use serde_json::Value;
use std::borrow::Cow;
let mut out = Vec::new();
let mut take = |value: &'a Value| match value {
Value::String(s) => out.push(Cow::Borrowed(s.as_str())),
Value::Bool(b) if booleans => out.push(Cow::Borrowed(if *b { "true" } else { "false" })),
_ => {}
};
for value in values {
match value.as_ref() {
Value::Array(items) => items.iter().for_each(&mut take),
other => take(other),
}
}
out
}
fn json_field_bytes(
field: &SchemaField,
values: &[std::borrow::Cow<'_, serde_json::Value>],
) -> Option<Arc<[u8]>> {
use serde_json::Value;
let first = values.first()?;
match &field.field_type {
FieldType::Text => {
let words = json_strings(values, false);
(!words.is_empty()).then(|| Arc::from(words.join(" ").into_bytes()))
}
FieldType::Tag => {
let tags = json_strings(values, true);
let separator = field.options.separator.to_string();
(!tags.is_empty()).then(|| Arc::from(tags.join(&separator).into_bytes()))
}
FieldType::Numeric => {
let number = values.iter().find_map(|value| match value.as_ref() {
Value::Number(n) => Some(n),
Value::Array(items) => items.iter().find_map(|item| match item {
Value::Number(n) => Some(n),
_ => None,
}),
_ => None,
})?;
Some(Arc::from(number.to_string().into_bytes()))
}
FieldType::Vector { dim, data_type, .. } => {
let Value::Array(items) = first.as_ref() else {
return None;
};
if items.len() != *dim {
return None;
}
let mut bytes = Vec::with_capacity(dim * data_type.size());
for item in items {
data_type.encode(item.as_f64()?, &mut bytes);
}
Some(Arc::from(bytes))
}
}
}
pub(crate) fn json_score_field_number(path: &str, doc: &serde_json::Value) -> Option<f64> {
let query = json_path(path)?;
let values = query.values(doc);
let serde_json::Value::Number(number) = values.first()?.as_ref() else {
return None;
};
number.as_f64()
}
pub fn json_return_value(doc: &serde_json::Value, path: &str) -> Option<Vec<u8>> {
let query = json_path(path)?;
let values = query.values(doc);
Some(match values.first()?.as_ref() {
serde_json::Value::String(s) => s.clone().into_bytes(),
other => serde_json::to_vec(other).ok()?,
})
}
pub fn maybe_index_json(
index_store: &IndexStore,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
doc: &serde_json::Value,
) {
let key = key.as_ref();
if indexing_deferred() || index_store.none() {
return;
}
let store = index_store.read();
for (name, def) in store.iter() {
if is_alias(name, def)
|| !matches!(def.on, IndexOn::Json)
|| def.db_index != db
|| !def.covers(key)
{
continue;
}
let fields: Vec<(String, Arc<[u8]>)> = project_json(&def.fields, doc).into_iter().collect();
index_fields(def, &crate::key_bytes::text_of(key), &fields, Write::Whole);
}
}
pub fn reindex_json_key(
index_store: &IndexStore,
store: &crate::store::Store,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
) {
let key = key.as_ref();
if indexing_deferred()
|| index_store.none()
|| !index_store
.read()
.values()
.any(|def| matches!(def.on, IndexOn::Json))
{
return;
}
let Some(db_ref) = store.get(db) else {
return;
};
let value = crate::store::get_shard(db_ref, key)
.read()
.get(key)
.map(ValueRef::to_value);
if let Some(crate::types::KiviDBValue::Json(doc)) = value {
maybe_index_json(index_store, db, key, &doc.read());
}
}
pub fn reindex_key(
index_store: &IndexStore,
store: &crate::store::Store,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
how: Write,
) {
let key = key.as_ref();
if indexing_deferred() || index_store.none() {
return;
}
let indexes = index_store.read();
if !indexes
.iter()
.any(|(name, def)| !is_alias(name, def) && def.db_index == db && def.covers(key))
{
return;
}
let Some(db_ref) = store.get(db) else {
return;
};
let value = crate::store::get_shard(db_ref, key)
.read()
.get(key)
.map(ValueRef::to_value);
for (name, def) in indexes.iter() {
if is_alias(name, def) || def.db_index != db || !def.covers(key) {
continue;
}
match (&def.on, &value) {
(IndexOn::Hash, Some(crate::types::KiviDBValue::Hash(hash))) => {
let pairs: Vec<(String, Arc<[u8]>)> = hash
.read()
.iter()
.map(|(field, value)| (field.to_string(), Arc::clone(value)))
.collect();
index_fields(def, &crate::key_bytes::text_of(key), &pairs, how);
}
(IndexOn::Hash, Some(crate::types::KiviDBValue::HashEx(hash))) => {
let pairs: Vec<(String, Arc<[u8]>)> = hash
.read()
.fields
.iter()
.map(|(field, value)| (field.to_string(), Arc::clone(value)))
.collect();
index_fields(def, &crate::key_bytes::text_of(key), &pairs, how);
}
(IndexOn::Json, Some(crate::types::KiviDBValue::Json(doc))) => {
let fields: Vec<(String, Arc<[u8]>)> =
project_json(&def.fields, &doc.read()).into_iter().collect();
index_fields(def, &crate::key_bytes::text_of(key), &fields, how);
}
_ => unindex_from(def, &crate::key_bytes::text_of(key)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Write {
Fields,
Whole,
Refresh,
}
pub fn maybe_index(
index_store: &IndexStore,
db: usize,
key: &(impl AsRef<[u8]> + ?Sized),
fields: &[(String, Arc<[u8]>)],
how: Write,
) {
let key = key.as_ref();
if indexing_deferred() || index_store.none() {
return;
}
let store = index_store.read();
for (name, def) in store.iter() {
if is_alias(name, def)
|| !matches!(def.on, IndexOn::Hash)
|| def.db_index != db
|| !def.covers(key)
{
continue;
}
index_fields(def, &crate::key_bytes::text_of(key), fields, how);
}
}
fn index_fields(def: &IndexDef, key: &str, fields: &[(String, Arc<[u8]>)], how: Write) {
#[cfg(test)]
crate::test_hooks::at("index_fields: fields read");
let whole = how != Write::Fields;
let mut changes: Vec<(u16, Vec<String>)> = Vec::new();
let mut restemmed: Vec<(u16, bool)> = Vec::new();
let mut language = def.language.language;
if def.text_fields().next().is_some() {
let before = (def.language.field.is_some() && !whole).then(|| {
def.doc_languages
.read()
.get(key)
.copied()
.unwrap_or(def.language.language)
});
language = def.doc_language(key, fields, whole);
for (number, f) in def.text_fields().enumerate() {
let number = number as u16;
let Some((_, raw)) = fields.iter().find(|(n, _)| n == &f.name) else {
if whole {
changes.push((number, Vec::new()));
} else if before.is_some_and(|before| before != language) {
restemmed.push((number, !f.options.nostem));
}
continue;
};
let tokens: Vec<String> = match std::str::from_utf8(raw) {
Ok(s) => stem::index_words(def, f, language, s),
Err(_) => Vec::new(),
};
changes.push((number, tokens));
}
}
let doc = if def.gives_ids() {
let words = def.text_write(changes, restemmed, language);
def.postings.write_fields(key, fields, whole, words)
} else {
postings::NO_DOC
};
{
for f in &def.fields {
let (dim, data_type, metric) = match &f.field_type {
FieldType::Vector {
dim,
data_type,
metric,
..
} => (*dim, *data_type, metric.clone()),
_ => continue,
};
let Some(live) = def.indexes.get(&f.name) else {
continue;
};
let vec = fields
.iter()
.find(|(n, _)| n == &f.name)
.and_then(|(_, b)| data_type.decode(b, dim));
let Some(vec) = vec else {
if whole {
unindex_vector(live, key);
}
continue;
};
match live {
LiveIndex::Flat(idx) => idx.insert(key.to_string(), vec),
LiveIndex::Hnsw(idx) => {
if how == Write::Refresh && idx.key_to_id.read().contains_key(key) {
continue;
}
hnsw_insert_doc(idx, key.to_string(), vec, &metric, doc);
}
}
}
}
}
fn restem(
text: &text::TextIndex,
doc: u32,
number: u16,
stems: bool,
language: stem::Language,
) -> Option<Vec<String>> {
let words = text.field_words(doc, number)?;
let mut tokens = Vec::with_capacity(words.len() * 2);
for word in words {
let stemmed = if stems {
stem::index_stem(language, &word)
} else {
None
};
tokens.push(word);
if let Some(s) = stemmed {
tokens.push(format!("{}{s}", stem::STEM_PREFIX));
}
}
Some(tokens)
}
fn unindex_vector(live: &LiveIndex, key: &str) {
match live {
LiveIndex::Flat(idx) => {
idx.vectors.write().remove(key);
}
LiveIndex::Hnsw(idx) => {
let node_id = idx.key_to_id.write().remove(key);
if let Some(node_id) = node_id {
let mut nodes = idx.nodes.write();
if nodes.get(node_id).is_some_and(|n| n.key == key) {
idx.delete(&mut nodes, node_id);
}
}
}
}
}
fn unindex_from(def: &IndexDef, key: &str) {
for live in def.indexes.values() {
unindex_vector(live, key);
}
if def.gives_ids() {
def.postings.remove(key, def.text_removal());
}
def.forget_language(key);
}
static INDEX_STORES: RwLock<Vec<(usize, IndexStore)>> = RwLock::new(Vec::new());
pub(crate) fn store_id(store: &crate::store::Store) -> usize {
Arc::as_ptr(store) as *const () as usize
}
pub fn register_index_store(store: &crate::store::Store, index_store: &IndexStore) {
let id = store_id(store);
let mut stores = INDEX_STORES.write();
stores.retain(|(other, _)| *other != id);
stores.push((id, Arc::clone(index_store)));
}
pub fn unindex_expired_in(id: usize, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) {
let index_store = INDEX_STORES
.read()
.iter()
.find(|(other, _)| *other == id)
.map(|(_, index_store)| Arc::clone(index_store));
if let Some(index_store) = index_store {
maybe_unindex(&index_store, db, key);
}
}
static LEAVING: parking_lot::Mutex<Vec<(usize, usize, Box<str>)>> =
parking_lot::Mutex::new(Vec::new());
pub fn has_index_of(index_store: &IndexStore, db: usize) -> bool {
!index_store.none() && index_store.read().values().any(|def| def.db_index == db)
}
pub fn indexes_of(id: usize, db: usize) -> Option<IndexStore> {
let index_store = INDEX_STORES
.read()
.iter()
.find(|(other, _)| *other == id)
.map(|(_, index_store)| Arc::clone(index_store))?;
has_index_of(&index_store, db).then_some(index_store)
}
pub fn mark_leaving(id: usize, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) {
let key: Box<str> = crate::key_bytes::text_of(key.as_ref()).into();
LEAVING.lock().push((id, db, key));
}
pub fn unmark_leaving(id: usize, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) {
let key = crate::key_bytes::text_of(key.as_ref());
let key: &str = &key;
let mut leaving = LEAVING.lock();
if let Some(at) = leaving
.iter()
.position(|(i, d, k)| *i == id && *d == db && **k == *key)
{
leaving.swap_remove(at);
}
}
pub fn leaving(id: usize, db: usize) -> Vec<Box<str>> {
LEAVING
.lock()
.iter()
.filter(|(i, d, _)| *i == id && *d == db)
.map(|(_, _, key)| key.clone())
.collect()
}
#[cfg(test)]
mod leaving_tests {
use super::*;
#[test]
fn a_key_is_leaving_from_its_mark_to_its_unmark() {
let id = usize::MAX - 249;
assert!(leaving(id, 0).is_empty());
mark_leaving(id, 0, "a");
mark_leaving(id, 0, "b");
mark_leaving(id, 1, "a");
let mut keys = leaving(id, 0);
keys.sort();
assert_eq!(keys, vec![Box::from("a"), Box::from("b")]);
unmark_leaving(id, 0, "a");
assert_eq!(leaving(id, 0), vec![Box::from("b")]);
assert_eq!(leaving(id, 1), vec![Box::from("a")]);
unmark_leaving(id, 0, "b");
unmark_leaving(id, 1, "a");
assert!(leaving(id, 0).is_empty());
assert!(leaving(id, 1).is_empty());
}
}
#[cfg(test)]
mod indexes_tests {
use super::*;
fn schema(name: &str) -> IndexDef {
IndexSchema {
name: name.into(),
db_index: 0,
on: IndexOn::Hash,
prefixes: Vec::new(),
fields: Vec::new(),
aliases: Vec::new(),
stopwords: None,
synonyms: Default::default(),
language: Default::default(),
default_score: 1.0,
score_field: None,
}
.into_def()
}
#[test]
fn none_follows_the_map_and_is_false_while_it_is_changed() {
let store = new_index_store();
assert!(store.none());
{
let mut indexes = store.write();
assert!(!store.none(), "held to change: not none");
indexes.insert("idx".into(), schema("idx"));
}
assert!(!store.none());
set_alias(&mut store.write(), "al", &schema("idx"));
assert!(!store.none());
{
let indexes = store.write();
assert!(!store.none());
drop(indexes);
}
assert!(!store.none(), "still has its index");
assert!(remove_index(&mut store.write(), "idx"));
assert!(store.none(), "the index and its alias are gone");
assert!(store.read().is_empty());
{
let _held = store.write();
assert!(!store.none());
}
assert!(store.none(), "nothing was added");
store.write().insert("other".into(), schema("other"));
assert!(has_index_of(&store, 0));
assert_eq!(drop_all_indexes(&store), 1);
assert!(store.none());
assert!(!has_index_of(&store, 0));
}
#[test]
fn the_first_index_waits_for_the_writes_that_found_none() {
use std::sync::atomic::Ordering::SeqCst;
use std::time::{Duration, Instant};
let store = new_index_store();
let writing = crate::write_order::lock_key_shared(0, b"doc:570");
let added = Arc::new(AtomicBool::new(false));
let adder = {
let (store, added) = (Arc::clone(&store), Arc::clone(&added));
std::thread::spawn(move || {
store
.write_to_add()
.unwrap()
.insert("idx".into(), schema("idx"));
added.store(true, SeqCst);
})
};
let deadline = Instant::now() + Duration::from_secs(10);
while store.none() {
assert!(Instant::now() < deadline, "none never became false");
std::thread::yield_now();
}
std::thread::sleep(Duration::from_millis(100));
assert!(
!added.load(SeqCst),
"added beside a write that found no index"
);
assert!(store.read().is_empty());
assert!(!store.none(), "none while the adder waits");
drop(writing);
adder.join().unwrap();
assert!(store.read().contains_key("idx"));
assert!(!store.none());
let writing = crate::write_order::lock_key_shared(0, b"doc:570");
let more = Arc::clone(&store);
std::thread::spawn(move || {
more.write_to_add()
.unwrap()
.insert("other".into(), schema("other"));
})
.join()
.unwrap();
drop(writing);
assert_eq!(drop_all_indexes(&store), 2);
assert!(store.none());
}
}
pub fn dist_l2_sq(a: &[f32], b: &[f32]) -> f32 {
simd::l2_sq(a, b)
}
pub fn dist_cosine(a: &[f32], b: &[f32]) -> f32 {
let (dot, na, nb) = simd::dot_norms(a, b);
let denom = na.sqrt() * nb.sqrt();
if denom == 0.0 {
return 1.0;
}
1.0 - (dot / denom)
}
pub fn dist_ip(a: &[f32], b: &[f32]) -> f32 {
1.0 - simd::dot(a, b)
}
pub fn distance(metric: &DistanceMetric, a: &[f32], b: &[f32]) -> f32 {
match metric {
DistanceMetric::L2 => dist_l2_sq(a, b),
DistanceMetric::Cosine => dist_cosine(a, b),
DistanceMetric::InnerProduct => dist_ip(a, b),
}
}
#[inline(always)]
pub(crate) fn distance_prenorm(metric: &DistanceMetric, a: &[f32], b: &[f32]) -> f32 {
match metric {
DistanceMetric::Cosine => dist_ip(a, b), DistanceMetric::L2 => dist_l2_sq(a, b),
DistanceMetric::InnerProduct => dist_ip(a, b),
}
}
fn normalize_to_unit(mut v: Vec<f32>) -> Vec<f32> {
let mag = simd::norm_sq(&v).sqrt();
if mag > 0.0 {
for x in &mut v {
*x /= mag;
}
}
v
}
pub struct PreparedQuery<'a> {
metric: &'a DistanceMetric,
vector: std::borrow::Cow<'a, [f32]>,
}
impl<'a> PreparedQuery<'a> {
pub fn new(metric: &'a DistanceMetric, query: &'a [f32]) -> Self {
let vector = match metric {
DistanceMetric::Cosine => std::borrow::Cow::Owned(normalize_to_unit(query.to_vec())),
_ => std::borrow::Cow::Borrowed(query),
};
Self { metric, vector }
}
pub fn vector(&self) -> &[f32] {
&self.vector
}
#[inline]
pub fn to_raw(&self, stored: &[f32]) -> f32 {
match self.metric {
DistanceMetric::Cosine => {
let (dot, nb) = simd::dot_norm_b(&self.vector, stored);
if nb == 0.0 {
return 1.0;
}
1.0 - dot / nb.sqrt()
}
DistanceMetric::L2 => dist_l2_sq(&self.vector, stored),
DistanceMetric::InnerProduct => dist_ip(&self.vector, stored),
}
}
#[inline]
pub fn to_unit(&self, stored: &[f32]) -> f32 {
distance_prenorm(self.metric, &self.vector, stored)
}
}
#[derive(Debug)]
pub struct KnnResult {
pub key: String,
pub score: f32,
}
pub fn knn_flat(
index: &VectorIndex,
query: &[f32],
k: usize,
metric: &DistanceMetric,
) -> Vec<KnnResult> {
let vectors = index.vectors.read();
let prepared = PreparedQuery::new(metric, query);
let mut scored: Vec<(f32, &str)> = vectors
.iter()
.filter(|(_, vec)| vec.len() == query.len())
.map(|(key, vec)| (prepared.to_raw(vec), key.as_str()))
.collect();
if scored.len() > k {
scored.select_nth_unstable_by(k, |a, b| a.0.total_cmp(&b.0));
scored.truncate(k);
}
scored.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
scored
.into_iter()
.map(|(score, key)| KnnResult {
key: key.to_string(),
score,
})
.collect()
}
fn select_neighbors_heuristic(
slots: &slots::Slots,
nodes: &mut NodesGuard<'_>,
candidates: &[(f32, u32)],
m_max: usize,
metric: &DistanceMetric,
keep_pruned: bool,
) -> Vec<u32> {
let mut result: Vec<(f32, u32)> = Vec::with_capacity(m_max);
let mut discarded: Vec<(f32, u32)> = Vec::new();
let next_lines = PREFETCH_NEXT;
'cand: for (i, &(d_to_q, cand_id)) in candidates.iter().enumerate() {
if result.len() >= m_max {
break;
}
if i > 0 && i.is_multiple_of(EXPANSIONS_PER_YIELD) {
parking_lot::RwLockReadGuard::bump(nodes);
}
if let Some(&(_, next)) = candidates.get(i + 1) {
slots.prefetch(next as usize, next_lines);
}
let cand = cand_id as usize;
if !slots.is_live(cand) {
continue;
}
let cand_vec = slots.vector(cand);
for &(_, sel_id) in &result {
let d_cand_to_sel = distance_prenorm(metric, cand_vec, slots.vector(sel_id as usize));
if d_cand_to_sel < d_to_q {
discarded.push((d_to_q, cand_id));
continue 'cand;
}
}
result.push((d_to_q, cand_id));
}
if keep_pruned {
for &(d, id) in &discarded {
if result.len() >= m_max {
break;
}
result.push((d, id));
}
}
result.into_iter().map(|(_, id)| id).collect()
}
fn nearest_of(
slots: &slots::Slots,
metric: &DistanceMetric,
of: &[f32],
ids: &[u32],
m_max: usize,
) -> Vec<u32> {
BACKLINK_SCRATCH.with(|cell| {
let mut scored = cell.borrow_mut();
scored.clear();
scored.reserve(ids.len());
for &id in ids {
if !slots.is_live(id as usize) {
continue;
}
scored.push((distance_prenorm(metric, of, slots.vector(id as usize)), id));
}
scored.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
scored.truncate(m_max);
scored.iter().map(|&(_, id)| id).collect()
})
}
pub fn hnsw_insert(index: &Arc<HnswIndex>, key: String, vector: Vec<f32>, metric: &DistanceMetric) {
hnsw_insert_doc(index, key, vector, metric, postings::NO_DOC);
}
type PrecomputedBacklink = (u32, usize, Vec<u32>, Vec<u32>);
const NEW_NODE: u32 = u32::MAX;
pub fn hnsw_insert_doc(
index: &Arc<HnswIndex>,
key: String,
vector: Vec<f32>,
metric: &DistanceMetric,
doc: u32,
) {
let old_id = index.key_to_id.write().remove(&key);
if let Some(old_id) = old_id {
let mut nodes = index.nodes.write();
if nodes.get(old_id).is_some_and(|n| n.key == key) {
index.delete(&mut nodes, old_id);
}
}
let vector = if matches!(metric, DistanceMetric::Cosine) {
normalize_to_unit(vector)
} else {
vector
};
let slots = index
.slots
.get_or_init(|| slots::Slots::new(vector.len(), index.m0 + slack(index.m0)));
if vector.len() != slots.dim() {
return;
}
let level = {
use rand::Rng;
let f: f64 = rand::thread_rng().r#gen::<f64>();
(-f.ln() * index.ml).floor() as usize
};
let ep_snapshot = *index.entry_point.read();
let mut precomputed_backlinks: Vec<PrecomputedBacklink> = Vec::new();
let mut nodes = index.nodes.read();
let mut neighbors_per_layer: Vec<Vec<u32>> = if let Some(mut ep) = ep_snapshot {
if !index.is_live(ep) {
let k2id = index.key_to_id.read();
match k2id.values().next().copied() {
Some(id) => ep = id,
None => {
drop(k2id);
let mut links: Vec<Vec<u32>> = (0..=level).map(|_| Vec::new()).collect();
let new_id = publish(
index,
slots,
&mut nodes,
key.clone(),
&vector,
level,
doc,
&mut links,
);
index.key_to_id.write().insert(key, new_id);
index.live_count.fetch_add(1, Relaxed);
*index.entry_point.write() = Some(new_id);
return;
}
}
}
let ep_level = nodes.get(ep).map_or(0, |n| n.level);
let mut curr_ep = ep as u32;
let mut per_layer: Vec<Vec<u32>> = Vec::with_capacity(level + 1);
for lc in (level + 1..=ep_level).rev() {
let results = search_layer(index, slots, &mut nodes, &vector, curr_ep, 1, lc, metric);
if let Some(&(_, best)) = results.first() {
curr_ep = best;
}
}
for lc in (0..=level.min(ep_level)).rev() {
let m_max = if lc == 0 { index.m0 } else { index.m };
let candidates = search_layer(
index,
slots,
&mut nodes,
&vector,
curr_ep,
index.ef_construction,
lc,
metric,
);
if let Some(&(_, best)) = candidates.first() {
curr_ep = best;
}
let selected =
select_neighbors_heuristic(slots, &mut nodes, &candidates, m_max, metric, true);
per_layer.push(selected);
}
per_layer.reverse(); while per_layer.len() <= level {
per_layer.push(vec![]);
}
let mut seen: Vec<u32> = Vec::with_capacity(index.m0);
for (lc, forward_neighbors) in per_layer.iter().enumerate() {
let m_max = if lc == 0 { index.m0 } else { index.m };
for &nb_id in forward_neighbors {
let nb = nb_id as usize;
if !slots.is_live(nb) {
continue;
}
seen.clear();
index.links(&nodes, nb, lc, &mut seen);
if seen.len() < m_max + slack(m_max) {
continue; }
let nb_vec = slots.vector(nb);
let vector_of = |id: u32| {
if id == NEW_NODE {
&vector[..]
} else {
slots.vector(id as usize)
}
};
let mut scored: Vec<(f32, u32)> = seen
.iter()
.filter(|&&id| slots.is_live(id as usize))
.map(|&id| {
(
distance_prenorm(metric, nb_vec, slots.vector(id as usize)),
id,
)
})
.collect();
scored.push((distance_prenorm(metric, nb_vec, &vector), NEW_NODE));
scored.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
for i in 0..scored.len() {
let (d_i, id_i) = scored[i];
let vec_i = vector_of(id_i);
let mut checks = 0usize;
for j in 0..i {
let (d_j, id_j) = scored[j];
if d_j.is_infinite() {
continue;
}
if distance_prenorm(metric, vec_i, vector_of(id_j)) < d_i {
scored[i].0 = f32::INFINITY;
break;
}
checks += 1;
if checks >= 4 {
break;
}
}
}
let mut pruned = Vec::with_capacity(m_max);
let kept = scored.iter().filter(|(d, _)| !d.is_infinite());
let dropped = scored.iter().filter(|(d, _)| d.is_infinite());
pruned.extend(kept.chain(dropped).take(m_max).map(|&(_, id)| id));
precomputed_backlinks.push((nb_id, lc, seen.clone(), pruned));
parking_lot::RwLockReadGuard::bump(&mut nodes);
}
}
per_layer
} else {
(0..=level).map(|_| vec![]).collect()
};
let new_id = publish(
index,
slots,
&mut nodes,
key.clone(),
&vector,
level,
doc,
&mut neighbors_per_layer,
);
index.key_to_id.write().insert(key, new_id);
index.live_count.fetch_add(1, Relaxed);
{
let mut ep = index.entry_point.write();
match *ep {
None => *ep = Some(new_id),
Some(current_ep) => {
let current_level = nodes.get(current_ep).map_or(0, |n| n.level);
if level > current_level || !index.is_live(current_ep) {
*ep = Some(new_id);
}
}
}
}
let mut list: Vec<u32> = Vec::with_capacity(index.m0 + 1);
for (lc, forward) in neighbors_per_layer.iter().enumerate() {
let m_max = if lc == 0 { index.m0 } else { index.m };
for &nb_id in forward {
let nb = nb_id as usize;
if nb == new_id || !slots.is_live(nb) {
continue;
}
let Some(nb_node) = nodes.get(nb) else {
continue;
};
let mut upper = nb_node.upper.lock();
if lc == 0 {
if slots.push_link(nb, new_id as u32) {
continue;
}
list.clear();
slots.read_links(nb, &mut list);
} else {
while upper.len() < lc {
upper.push(Vec::new());
}
let links = &mut upper[lc - 1];
if links.len() < m_max + slack(m_max) {
links.push(new_id as u32);
continue;
}
list.clear();
list.extend_from_slice(links);
}
let fresh = precomputed_backlinks
.iter()
.find(|(pid, plc, seen, _)| *pid == nb_id && *plc == lc && *seen == list);
let replacement: Vec<u32> = if let Some((_, _, _, pruned)) = fresh {
pruned
.iter()
.map(|&id| if id == NEW_NODE { new_id as u32 } else { id })
.collect()
} else {
list.push(new_id as u32);
nearest_of(slots, metric, slots.vector(nb), &list, m_max)
};
if lc == 0 {
slots.write_links(nb, replacement);
} else {
upper[lc - 1] = replacement;
}
}
}
}
const PRUNE_SLACK: usize = 4;
fn slack(m_max: usize) -> usize {
PRUNE_SLACK.min(m_max / 4)
}
#[allow(clippy::too_many_arguments)]
fn publish(
index: &HnswIndex,
slots: &slots::Slots,
nodes: &mut NodesGuard<'_>,
key: String,
vector: &[f32],
level: usize,
doc: u32,
links: &mut [Vec<u32>],
) -> usize {
let reuse = index.free.lock().pop();
if let Some(id) = reuse {
for list in links.iter_mut() {
list.retain(|&x| x != id);
}
let id = id as usize;
let upper = links[1..].to_vec();
let layer0 = &links[0];
parking_lot::RwLockReadGuard::unlocked(nodes, || {
let mut graph = index.nodes.write();
unsafe { slots.write_vector(id, vector) };
slots.write_links(id, layer0.iter().copied());
if let Some(node) = graph.get_mut(id) {
*node = HnswNode::new(key, level, upper, doc);
}
slots.flag(id).store(1, Release);
index.reused.fetch_add(1, Release);
index.tombstone_count.fetch_sub(1, Relaxed);
});
id
} else {
let upper = links[1..].to_vec();
let layer0 = &links[0];
nodes.push_with(|id| {
slots.reserve(id);
unsafe { slots.write_vector(id, vector) };
slots.write_links(id, layer0.iter().copied());
slots.flag(id).store(1, Release);
HnswNode::new(key, level, upper, doc)
})
}
}
thread_local! {
static BACKLINK_SCRATCH: std::cell::RefCell<Vec<(f32, u32)>> =
std::cell::RefCell::new(Vec::with_capacity(64));
}
type MinHeap =
std::collections::BinaryHeap<std::cmp::Reverse<(ordered_float::OrderedFloat<f32>, u32)>>;
type MaxHeap = std::collections::BinaryHeap<(ordered_float::OrderedFloat<f32>, u32)>;
struct SearchBuffers {
visited: slots::Visited,
candidates: MinHeap,
dynamic: MaxHeap,
neighbor_scratch: Vec<u32>,
}
impl SearchBuffers {
fn new() -> Self {
Self {
visited: slots::Visited::default(),
candidates: std::collections::BinaryHeap::with_capacity(256),
dynamic: std::collections::BinaryHeap::with_capacity(256),
neighbor_scratch: Vec::with_capacity(64),
}
}
fn clear(&mut self, nodes: usize) {
self.visited.reset(nodes);
self.candidates.clear();
self.dynamic.clear();
self.neighbor_scratch.clear();
}
}
thread_local! {
static SEARCH_BUFFERS: std::cell::RefCell<SearchBuffers> =
std::cell::RefCell::new(SearchBuffers::new());
}
const EXPANSIONS_PER_YIELD: usize = 4;
const PREFETCH_FIRST: usize = 4;
const PREFETCH_NEXT: usize = 8;
#[allow(clippy::too_many_arguments)]
fn search_layer(
index: &HnswIndex,
slots: &slots::Slots,
nodes: &mut NodesGuard<'_>,
query: &[f32],
ep: u32,
ef: usize,
layer: usize,
metric: &DistanceMetric,
) -> Vec<(f32, u32)> {
use ordered_float::OrderedFloat;
use std::cmp::Reverse;
let ep_id = ep as usize;
if !slots.has(ep_id) || !slots.is_live(ep_id) {
return vec![];
}
let ep_dist = distance_prenorm(metric, query, slots.vector(ep_id));
let (first, next) = (PREFETCH_FIRST, PREFETCH_NEXT);
SEARCH_BUFFERS.with(|cell| {
let mut guard = cell.borrow_mut();
let bufs = &mut *guard;
bufs.clear(nodes.count());
let of_ep = OrderedFloat(ep_dist);
bufs.visited.insert(ep);
bufs.candidates.push(Reverse((of_ep, ep)));
bufs.dynamic.push((of_ep, ep));
let mut expanded = 0usize;
while let Some(Reverse((c_dist, c_id))) = bufs.candidates.pop() {
let worst = bufs.dynamic.peek().map(|(d, _)| d.0).unwrap_or(f32::MAX);
if bufs.dynamic.len() >= ef && c_dist.0 > worst {
break;
}
expanded += 1;
if expanded.is_multiple_of(EXPANSIONS_PER_YIELD) {
parking_lot::RwLockReadGuard::bump(nodes);
}
bufs.neighbor_scratch.clear();
index.links(nodes, c_id as usize, layer, &mut bufs.neighbor_scratch);
let mut fresh = 0;
for i in 0..bufs.neighbor_scratch.len() {
let id = bufs.neighbor_scratch[i];
if bufs.visited.insert(id) {
bufs.neighbor_scratch[fresh] = id;
fresh += 1;
slots.prefetch(id as usize, first);
}
}
for i in 0..fresh {
if i + 1 < fresh {
slots.prefetch(bufs.neighbor_scratch[i + 1] as usize, next);
}
let nb_id = bufs.neighbor_scratch[i];
if !slots.is_live(nb_id as usize) {
continue;
}
let nb_dist = distance_prenorm(metric, query, slots.vector(nb_id as usize));
let worst = bufs.dynamic.peek().map(|(d, _)| d.0).unwrap_or(f32::MAX);
if nb_dist < worst || bufs.dynamic.len() < ef {
let of = OrderedFloat(nb_dist);
bufs.candidates.push(Reverse((of, nb_id)));
bufs.dynamic.push((of, nb_id));
if bufs.dynamic.len() > ef {
bufs.dynamic.pop();
}
}
}
}
let mut result: Vec<(f32, u32)> = bufs.dynamic.drain().map(|(d, id)| (d.0, id)).collect();
result.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
result
})
}
#[allow(clippy::too_many_arguments)]
fn into_results(
index: &HnswIndex,
slots: &slots::Slots,
nodes: &HnswNodes,
query: &[f32],
metric: &DistanceMetric,
mut found: Vec<(f32, u32)>,
k: usize,
reused: u64,
) -> Vec<KnnResult> {
if index.reused.load(Acquire) != reused {
for r in found.iter_mut() {
let id = r.1 as usize;
r.0 = if slots.is_live(id) {
distance_prenorm(metric, query, slots.vector(id))
} else {
f32::INFINITY
};
}
found.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
}
found.truncate(k);
found
.into_iter()
.filter(|(_, id)| slots.is_live(*id as usize))
.filter_map(|(score, id)| {
nodes.get(id as usize).map(|n| KnnResult {
key: n.key.clone(),
score,
})
})
.collect()
}
pub fn knn_hnsw(
index: &HnswIndex,
query: &[f32],
k: usize,
ef: usize,
metric: &DistanceMetric,
) -> Vec<KnnResult> {
let ef = ef.max(k).max(50);
let query_buf: Vec<f32>;
let query: &[f32] = if matches!(metric, DistanceMetric::Cosine) {
query_buf = normalize_to_unit(query.to_vec());
&query_buf
} else {
query
};
let Some(slots) = index.slots() else {
return vec![];
};
if query.len() != slots.dim() {
return vec![];
}
let mut ep_id = match *index.entry_point.read() {
Some(id) => id,
None => return vec![],
};
let mut nodes = index.nodes.read();
let reused = index.reused.load(Acquire);
if !index.is_live(ep_id) {
let k2id = index.key_to_id.read();
match k2id.values().next().copied() {
Some(id) => ep_id = id,
None => return vec![],
}
}
let live_count = index.live_count.load(std::sync::atomic::Ordering::Relaxed);
if live_count < 500 {
let mut scored: Vec<(f32, u32)> = nodes
.iter()
.filter(|(i, _)| slots.is_live(*i))
.map(|(i, _)| (distance_prenorm(metric, query, slots.vector(i)), i as u32))
.collect();
scored.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
return into_results(index, slots, &nodes, query, metric, scored, k, reused);
}
let ep_level = nodes.get(ep_id).map_or(0, |n| n.level);
let mut curr_ep = ep_id as u32;
for lc in (1..=ep_level).rev() {
let candidates = search_layer(index, slots, &mut nodes, query, curr_ep, 1, lc, metric);
if let Some(&(_, best)) = candidates.first() {
curr_ep = best;
}
}
let mut results = search_layer(index, slots, &mut nodes, query, curr_ep, ef, 0, metric);
if results.len() < k && curr_ep as usize != ep_id {
let mut more = search_layer(index, slots, &mut nodes, query, ep_id as u32, ef, 0, metric);
results.append(&mut more);
let mut seen: AHashMap<u32, f32> = AHashMap::new();
for (dist, id) in results {
seen.entry(id)
.and_modify(|d| {
if dist < *d {
*d = dist;
}
})
.or_insert(dist);
}
results = seen.into_iter().map(|(id, dist)| (dist, id)).collect();
results.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
}
into_results(index, slots, &nodes, query, metric, results, k, reused)
}
#[allow(clippy::too_many_arguments)]
pub fn knn_hnsw_admitting(
index: &HnswIndex,
query: &[f32],
k: usize,
ef: usize,
metric: &DistanceMetric,
admit: &mut dyn FnMut(&HnswNode) -> bool,
budget: usize,
deadline: Option<std::time::Instant>,
) -> Option<(Vec<KnnResult>, bool)> {
use ordered_float::OrderedFloat;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
let ef = ef.max(k);
let slots = index.slots()?;
if query.len() != slots.dim() {
return Some((Vec::new(), false));
}
let mut ep_id = (*index.entry_point.read())?;
let mut nodes = index.nodes.read();
let reused = index.reused.load(Acquire);
if !index.is_live(ep_id) {
ep_id = index.key_to_id.read().values().next().copied()?;
}
let ep_level = nodes.get(ep_id).map_or(0, |n| n.level);
let mut curr = ep_id as u32;
for lc in (1..=ep_level).rev() {
let found = search_layer(index, slots, &mut nodes, query, curr, 1, lc, metric);
if let Some(&(_, best)) = found.first() {
curr = best;
}
}
let (first, next) = (PREFETCH_FIRST, PREFETCH_NEXT);
let mut spent = 0usize;
let mut visited = slots::Visited::default();
visited.reset(nodes.count());
let mut candidates: BinaryHeap<Reverse<(OrderedFloat<f32>, u32)>> = BinaryHeap::new();
let mut results: BinaryHeap<(OrderedFloat<f32>, u32)> = BinaryHeap::new();
let mut neighbors: Vec<u32> = Vec::with_capacity(64);
if !index.is_live(curr as usize) {
return Some((Vec::new(), false));
}
let d = OrderedFloat(distance_prenorm(metric, query, slots.vector(curr as usize)));
spent += 1;
visited.insert(curr);
candidates.push(Reverse((d, curr)));
if let Some(n) = nodes.get(curr as usize)
&& admit(n)
{
results.push((d, curr));
}
let mut bound = if results.len() >= ef {
results.peek().map_or(f32::INFINITY, |(d, _)| d.0)
} else {
f32::INFINITY
};
let mut expanded = 0usize;
let mut cut = false;
while let Some(Reverse((d, id))) = candidates.pop() {
if d.0 > bound && results.len() >= ef {
break;
}
expanded += 1;
if expanded.is_multiple_of(DEADLINE_EXPANSIONS)
&& deadline.is_some_and(|d| std::time::Instant::now() >= d)
{
cut = true;
break;
}
if expanded.is_multiple_of(EXPANSIONS_PER_YIELD) {
parking_lot::RwLockReadGuard::bump(&mut nodes);
}
neighbors.clear();
slots.read_links(id as usize, &mut neighbors);
let mut fresh = 0;
for i in 0..neighbors.len() {
let nb = neighbors[i];
if visited.insert(nb) {
neighbors[fresh] = nb;
fresh += 1;
slots.prefetch(nb as usize, first);
}
}
for i in 0..fresh {
if i + 1 < fresh {
slots.prefetch(neighbors[i + 1] as usize, next);
}
let nb = neighbors[i];
if !slots.is_live(nb as usize) {
continue;
}
spent += 1;
if spent > budget {
return None;
}
let dist = distance_prenorm(metric, query, slots.vector(nb as usize));
if results.len() < ef || dist < bound {
candidates.push(Reverse((OrderedFloat(dist), nb)));
if let Some(n) = nodes.get(nb as usize)
&& admit(n)
{
results.push((OrderedFloat(dist), nb));
if results.len() > ef {
results.pop();
}
if results.len() >= ef {
bound = results.peek().map_or(f32::INFINITY, |(d, _)| d.0);
}
}
}
}
}
let mut found: Vec<(f32, u32)> = results.into_iter().map(|(d, id)| (d.0, id)).collect();
found.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
if index.reused.load(Acquire) != reused {
found.retain(|(_, id)| match nodes.get(*id as usize) {
Some(n) => admit(n),
None => false,
});
}
let nearest = into_results(index, slots, &nodes, query, metric, found, k, reused);
Some((nearest, cut))
}
const DEADLINE_EXPANSIONS: usize = 64;
pub fn maybe_unindex(index_store: &IndexStore, db: usize, key: &(impl AsRef<[u8]> + ?Sized)) {
let key = key.as_ref();
if indexing_deferred() || index_store.none() {
return;
}
let store = index_store.read();
for (name, def) in store.iter() {
if is_alias(name, def) || def.db_index != db || !def.covers(key) {
continue;
}
unindex_from(def, &crate::key_bytes::text_of(key));
}
}
pub fn compact_hnsw(
index_store: &IndexStore,
db_store: &crate::store::Store,
index_name: &str,
field_name: &str,
) -> Result<usize, &'static str> {
use std::sync::atomic::Ordering;
let (old_arc, metric, dim, data_type, prefixes, m, ef_construction) = {
let store = index_store.read();
let def = match store.get(index_name) {
Some(d) => d,
None => return Err("index not found"),
};
let old_arc = match def.indexes.get(field_name) {
Some(LiveIndex::Hnsw(arc)) => Arc::clone(arc),
Some(_) => return Err("field is not HNSW"),
None => return Err("no such vector field on index"),
};
if old_arc
.compaction_in_progress
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return Err("compaction already in progress");
}
let vf = match def.vector_field_by_name(field_name) {
Some(f) => f,
None => {
old_arc
.compaction_in_progress
.store(false, Ordering::Release);
return Err("vector field metadata missing");
}
};
let (dim, data_type, metric) = match &vf.field_type {
FieldType::Vector {
dim,
data_type,
metric,
..
} => (*dim, *data_type, metric.clone()),
_ => {
old_arc
.compaction_in_progress
.store(false, Ordering::Release);
return Err("vector field type mismatch");
}
};
let m = old_arc.m;
let ef_construction = old_arc.ef_construction;
let prefixes = def.prefixes.clone();
(
old_arc,
metric,
dim,
data_type,
prefixes,
m,
ef_construction,
)
};
struct CompactionGuard<'a>(&'a HnswIndex);
impl<'a> Drop for CompactionGuard<'a> {
fn drop(&mut self) {
self.0
.compaction_in_progress
.store(false, std::sync::atomic::Ordering::Release);
}
}
let _guard = CompactionGuard(&old_arc);
let live_pairs: Vec<(String, Vec<f32>)> = {
let nodes = old_arc.nodes.read();
nodes
.iter()
.filter_map(|(id, n)| Some((n.key.clone(), old_arc.vector(id)?.to_vec())))
.collect()
};
let new_index = Arc::new(HnswIndex::new(m, ef_construction));
for (key, vec) in &live_pairs {
hnsw_insert(&new_index, key.clone(), vec.clone(), &metric);
}
let (doc_on, doc_schema) = {
let mut store = index_store.write();
let def = match store.get_mut(index_name) {
Some(d) => d,
None => return Err("index dropped during compaction"),
};
match def.indexes.get(field_name) {
Some(LiveIndex::Hnsw(current)) => {
if !Arc::ptr_eq(current, &old_arc) {
return Err("index was replaced during compaction");
}
}
_ => return Err("field changed type during compaction"),
}
def.indexes.insert(
field_name.to_string(),
LiveIndex::Hnsw(Arc::clone(&new_index)),
);
(def.on.clone(), def.fields.clone())
};
let mut catchup = 0usize;
{
let already: ahash::AHashSet<String> = {
let kti = new_index.key_to_id.read();
kti.keys().cloned().collect()
};
let db_ref = &db_store[0];
for shard in db_ref.iter() {
#[cfg(target_os = "linux")]
let map = shard.read();
#[cfg(not(target_os = "linux"))]
let map = shard.read();
for (key, value) in map.iter() {
let matches =
prefixes.is_empty() || prefixes.iter().any(|p| key.starts_with(p.as_bytes()));
let key = crate::key_bytes::text_of(key);
let key: &str = &key;
if !matches || already.contains(key) {
continue;
}
let Some(inner) = doc_fields(&doc_on, &doc_schema, value) else {
continue;
};
let raw = match inner.get(field_name) {
Some(b) => b,
None => continue,
};
let Some(v) = data_type.decode(raw, dim) else {
continue;
};
hnsw_insert(&new_index, key.to_string(), v, &metric);
catchup += 1;
}
}
}
Ok(live_pairs.len() + catchup)
}
pub fn spawn_compaction_worker(
index_store: IndexStore,
db_store: crate::store::Store,
rx: CompactionRx,
) {
std::thread::Builder::new()
.name("hnsw-compaction".into())
.spawn(move || {
while let Ok(req) = rx.recv() {
match compact_hnsw(&index_store, &db_store, &req.index_name, &req.field_name) {
Ok(n) => {
log_info!(
"HNSW compaction complete for '{}' field '{}': {n} live vectors",
req.index_name,
req.field_name
);
}
Err(e) => {
log_warn!(
"HNSW compaction skipped for '{}' field '{}': {e}",
req.index_name,
req.field_name
);
}
}
}
})
.expect("failed to spawn HNSW compaction worker");
}
pub fn maybe_request_compaction(
index_store: &IndexStore,
compaction_tx: &CompactionTx,
deleted_key: &(impl AsRef<[u8]> + ?Sized),
) {
let deleted_key = deleted_key.as_ref();
use std::sync::atomic::Ordering::Relaxed;
if index_store.none() {
return;
}
let store = index_store.read();
for (name, def) in store.iter() {
if is_alias(name, def) {
continue;
}
let matches = def.prefixes.is_empty()
|| def
.prefixes
.iter()
.any(|p| deleted_key.starts_with(p.as_bytes()));
if !matches {
continue;
}
for (field_name, live) in def.indexes.iter() {
let idx = match live {
LiveIndex::Hnsw(i) => i,
_ => continue,
};
let tomb = idx.tombstone_count.load(Relaxed);
if tomb < COMPACTION_MIN_TOMBSTONES {
continue;
}
if idx.tombstone_ratio() < COMPACTION_THRESHOLD {
continue;
}
if idx.compaction_in_progress.load(Relaxed) {
continue;
}
let _ = compaction_tx.try_send(CompactionRequest {
index_name: name.clone(),
field_name: field_name.clone(),
});
}
}
}
#[cfg(test)]
mod prepared_query_tests {
use super::*;
fn vector(dim: usize, seed: u64) -> Vec<f32> {
let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
(0..dim)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
((state >> 40) as f32 / (1u64 << 24) as f32) * 4.0 - 2.0
})
.collect()
}
fn scalar_cosine(a: &[f32], b: &[f32]) -> f32 {
let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
let ma = a.iter().map(|x| x * x).sum::<f32>().sqrt();
let mb = b.iter().map(|x| x * x).sum::<f32>().sqrt();
if ma * mb == 0.0 {
return 1.0;
}
1.0 - dot / (ma * mb)
}
#[test]
fn a_prepared_query_measures_what_distance_does() {
let metrics = [
DistanceMetric::Cosine,
DistanceMetric::L2,
DistanceMetric::InnerProduct,
];
for dim in [1usize, 3, 7, 8, 15, 16, 25, 128, 512, 1536, 2048] {
let q = vector(dim, dim as u64);
let s = vector(dim, 7 + dim as u64);
for metric in &metrics {
let prepared = PreparedQuery::new(metric, &q);
let want = distance(metric, &q, &s);
let tol = 1e-4 * want.abs().max(1.0) * (dim as f32).sqrt();
let got = prepared.to_raw(&s);
assert!(
(got - want).abs() <= tol,
"{metric:?} {dim}: {got} vs {want}"
);
}
let cosine = DistanceMetric::Cosine;
let unit = normalize_to_unit(s.clone());
let got = PreparedQuery::new(&cosine, &q).to_unit(&unit);
let want = scalar_cosine(&q, &s);
assert!(
(got - want).abs() <= 1e-5,
"unit cosine {dim}: {got} vs {want}"
);
assert!(
(dist_cosine(&q, &s) - want).abs() <= 1e-5,
"dist_cosine {dim}"
);
}
}
#[test]
fn a_zero_vector_is_at_cosine_distance_one() {
let cosine = DistanceMetric::Cosine;
let zero = vec![0.0f32; 16];
let v = vector(16, 3);
assert_eq!(dist_cosine(&zero, &v), 1.0);
assert_eq!(PreparedQuery::new(&cosine, &zero).to_raw(&v), 1.0);
assert_eq!(PreparedQuery::new(&cosine, &v).to_raw(&zero), 1.0);
assert_eq!(
PreparedQuery::new(&cosine, &zero).to_unit(&normalize_to_unit(v)),
1.0
);
}
}
#[cfg(test)]
mod flush_index_tests {
use super::*;
#[test]
fn drop_all_indexes_drops_hnsw_arc() {
let store = new_index_store();
let def = IndexSchema {
name: "idx".into(),
db_index: 0,
on: IndexOn::Hash,
prefixes: vec!["v:".into()],
fields: vec![SchemaField {
name: "vec".into(),
field_type: FieldType::Vector {
algo: VectorAlgo::Hnsw {
m: 16,
ef_construction: 64,
ef_runtime: 10,
},
dim: 2,
metric: DistanceMetric::L2,
data_type: VectorType::Float32,
},
options: FieldOptions::default(),
}],
aliases: Vec::new(),
stopwords: None,
synonyms: Default::default(),
language: Default::default(),
default_score: 1.0,
score_field: None,
}
.into_def();
let graph = match def.indexes.get("vec") {
Some(LiveIndex::Hnsw(arc)) => Arc::clone(arc),
_ => panic!("expected HNSW field"),
};
hnsw_insert(&graph, "v:1".into(), vec![1.0, 0.0], &DistanceMetric::L2);
store.write().insert("idx".into(), def);
let weak = Arc::downgrade(&graph);
drop(graph);
assert_eq!(drop_all_indexes(&store), 1);
assert!(store.read().is_empty());
assert!(
weak.upgrade().is_none(),
"HNSW graph must be freed when FLUSHALL drops the index"
);
}
#[test]
fn create_args_carries_score_and_score_field() {
let def = IndexSchema {
name: "idx".into(),
db_index: 0,
on: IndexOn::Hash,
prefixes: vec!["s:".into()],
fields: vec![SchemaField {
name: "title".into(),
field_type: FieldType::Text,
options: FieldOptions::default(),
}],
aliases: Vec::new(),
stopwords: None,
synonyms: Default::default(),
language: Default::default(),
default_score: 0.5,
score_field: Some("rank".into()),
}
.into_def();
let args: Vec<String> = def
.create_args()
.into_iter()
.map(|a| String::from_utf8(a).unwrap())
.collect();
let at = |word: &str| args.iter().position(|a| a == word).unwrap();
assert_eq!(args[at("SCORE") + 1], "0.5");
assert_eq!(args[at("SCORE_FIELD") + 1], "rank");
assert!(at("SCORE_FIELD") < at("SCHEMA"));
}
#[test]
fn drop_indexes_for_db_keeps_other_dbs() {
let store = new_index_store();
let mk = |name: &str, db: usize| {
IndexSchema {
name: name.into(),
db_index: db,
on: IndexOn::Hash,
prefixes: vec![],
fields: vec![SchemaField {
name: "t".into(),
field_type: FieldType::Text,
options: FieldOptions::default(),
}],
aliases: Vec::new(),
stopwords: None,
synonyms: Default::default(),
language: Default::default(),
default_score: 1.0,
score_field: None,
}
.into_def()
};
store.write().insert("a".into(), mk("a", 0));
store.write().insert("b".into(), mk("b", 1));
assert_eq!(drop_indexes_for_db(&store, 1), 1);
let g = store.read();
assert!(g.contains_key("a"));
assert!(!g.contains_key("b"));
}
}
#[cfg(test)]
mod alias_tests {
use super::*;
fn index(name: &str) -> IndexDef {
IndexSchema {
name: name.into(),
db_index: 0,
on: IndexOn::Hash,
prefixes: vec!["doc:".into()],
fields: vec![SchemaField {
name: "t".into(),
field_type: FieldType::Text,
options: FieldOptions::default(),
}],
aliases: Vec::new(),
stopwords: None,
synonyms: Default::default(),
language: Default::default(),
default_score: 1.0,
score_field: None,
}
.into_def()
}
#[test]
fn an_alias_resolves_to_its_index_and_goes_with_it() {
let mut store = AHashMap::new();
store.insert("idx".to_string(), index("idx"));
let def = store["idx"].clone();
set_alias(&mut store, "b", &def);
set_alias(&mut store, "a", &def);
assert_eq!(resolve_index_name(&store, "a").as_deref(), Some("idx"));
assert_eq!(resolve_index_name(&store, "idx").as_deref(), Some("idx"));
assert_eq!(resolve_index_name(&store, "nope"), None);
assert_eq!(index_aliases(&store, "idx"), ["a", "b"]);
assert!(is_alias("a", &store["a"]));
assert!(!is_alias("idx", &store["idx"]));
assert!(!remove_index(&mut store, "a"));
assert!(remove_index(&mut store, "idx"));
assert!(store.is_empty(), "aliases go with their index");
}
#[test]
fn documents_are_not_indexed_through_aliases() {
let store = new_index_store();
store.write().insert("idx".to_string(), index("idx"));
{
let mut g = store.write();
let def = g["idx"].clone();
set_alias(&mut g, "alias", &def);
}
maybe_index(
&store,
0,
"doc:1",
&[("t".to_string(), Arc::from(&b"hello world"[..]))],
Write::Fields,
);
let g = store.read();
assert_eq!(g["idx"].text.read().doc_count(), 1);
assert_eq!(g["alias"].text.read().doc_count(), 0);
}
#[test]
fn aliases_are_restored_with_their_schema() {
let store = new_index_store();
let schema = IndexSchema {
name: "idx".into(),
db_index: 0,
on: IndexOn::Hash,
prefixes: vec![],
fields: vec![],
aliases: vec!["a".into()],
stopwords: None,
synonyms: Default::default(),
language: Default::default(),
default_score: 1.0,
score_field: None,
};
register_index_schemas(&store, &[schema], &Default::default());
let g = store.read();
assert_eq!(resolve_index_name(&g, "a").as_deref(), Some("idx"));
assert_eq!(index_aliases(&g, "idx"), ["a"]);
}
}
#[cfg(test)]
mod concurrent_insert_tests {
use super::*;
use rand::{Rng, SeedableRng};
fn random_vectors(n: usize, dim: usize, seed: u64) -> Vec<Vec<f32>> {
let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
(0..n)
.map(|_| (0..dim).map(|_| rng.r#gen::<f32>() - 0.5).collect())
.collect()
}
#[test]
fn concurrent_inserts_searches_and_overwrites_leave_a_whole_graph() {
const THREADS: usize = 8;
const PER_THREAD: usize = 1500;
const DIM: usize = 16;
let metric = DistanceMetric::Cosine;
let index = Arc::new(HnswIndex::new(16, 100));
let vectors: Vec<Vec<Vec<f32>>> = (0..THREADS)
.map(|t| random_vectors(PER_THREAD, DIM, t as u64))
.collect();
std::thread::scope(|s| {
for (t, vs) in vectors.iter().enumerate() {
let index = &index;
let metric = &metric;
s.spawn(move || {
for (i, v) in vs.iter().enumerate() {
hnsw_insert(index, format!("k:{t}:{i}"), v.clone(), metric);
if i % 10 == 0 {
knn_hnsw(index, v, 5, 50, metric);
}
if i % 100 == 99 {
let j = i - 50;
hnsw_insert(index, format!("k:{t}:{j}"), vs[j].clone(), metric);
}
}
});
}
});
let nodes = index.nodes.read();
let count = nodes.count();
let overwrites = THREADS * (PER_THREAD / 100);
let tombstones = index.tombstone_count.load(Relaxed);
assert_eq!(index.live_count.load(Relaxed), THREADS * PER_THREAD);
assert!(tombstones <= overwrites, "{tombstones} empty slots");
assert_eq!(count, THREADS * PER_THREAD + tombstones);
let mut list = Vec::new();
for (id, node) in nodes.iter() {
for lc in 0..node.layer_count() {
list.clear();
index.links(&nodes, id, lc, &mut list);
let m_max = if lc == 0 { index.m0 } else { index.m };
assert!(
list.len() <= m_max + slack(m_max),
"node {id} layer {lc}: {} links",
list.len()
);
for &nb in &list {
let nb = nb as usize;
assert!(nb < count && nb != id, "node {id} links to {nb}");
}
}
}
drop(nodes);
let mut found = 0;
for (t, vs) in vectors.iter().enumerate() {
for (i, v) in vs.iter().enumerate() {
let hits = knn_hnsw(&index, v, 1, 100, &metric);
if hits.first().is_some_and(|h| h.key == format!("k:{t}:{i}")) {
found += 1;
}
}
}
let total = THREADS * PER_THREAD;
assert!(found * 100 >= total * 98, "found {found} of {total}");
}
}
#[cfg(test)]
mod slot_reuse_tests {
use super::*;
fn point(i: usize) -> Vec<f32> {
vec![i as f32, (i % 7) as f32, 1.0, 2.0]
}
fn graph(n: usize) -> Arc<HnswIndex> {
let index = Arc::new(HnswIndex::new(8, 64));
for i in 0..n {
hnsw_insert(&index, format!("k{i}"), point(i), &DistanceMetric::L2);
}
index
}
#[test]
fn a_deleted_nodes_slot_is_filled_by_the_next_insert() {
let metric = DistanceMetric::L2;
let index = graph(600);
let live = LiveIndex::Hnsw(Arc::clone(&index));
unindex_vector(&live, "k10");
assert_eq!(index.tombstone_count.load(Relaxed), 1);
assert_eq!(index.live_count.load(Relaxed), 599);
let slots_before = index.nodes.read().count();
hnsw_insert(&index, "new".into(), vec![10.25, 3.0, 1.0, 2.0], &metric);
assert_eq!(index.nodes.read().count(), slots_before, "no new slot");
assert_eq!(index.tombstone_count.load(Relaxed), 0);
assert_eq!(index.live_count.load(Relaxed), 600);
assert_eq!(index.key_to_id.read().get("new"), Some(&10));
let hits = knn_hnsw(&index, &[10.25, 3.0, 1.0, 2.0], 1, 64, &metric);
assert_eq!(hits[0].key, "new");
assert!(hits[0].score < 1e-6);
let all = knn_hnsw(&index, &point(10), 600, 600, &metric);
assert!(
all.iter().all(|h| h.key != "k10"),
"the deleted key is gone"
);
for h in &all {
let i: usize = match h.key.strip_prefix('k') {
Some(i) => i.parse().unwrap(),
None => continue,
};
let want = dist_l2_sq(&point(10), &point(i));
assert!(
(h.score - want).abs() < 1e-3,
"{}: {} vs {want}",
h.key,
h.score
);
}
}
#[test]
fn an_overwritten_key_keeps_its_slot() {
let metric = DistanceMetric::L2;
let index = graph(600);
let slots_before = index.nodes.read().count();
for round in 0..3 {
hnsw_insert(
&index,
"k5".into(),
vec![1000.0 + round as f32, 0.0, 0.0, 0.0],
&metric,
);
}
assert_eq!(index.nodes.read().count(), slots_before);
assert_eq!(index.live_count.load(Relaxed), 600);
assert_eq!(index.tombstone_count.load(Relaxed), 0);
let hits = knn_hnsw(&index, &[1002.0, 0.0, 0.0, 0.0], 1, 64, &metric);
assert_eq!(hits[0].key, "k5");
assert!(hits[0].score < 1e-3);
}
#[test]
fn a_restored_graph_fills_its_deleted_slots_first() {
let metric = DistanceMetric::L2;
let node = |key: &str, v: [f32; 2], links: Vec<usize>| {
Some(RestoredNode {
key: key.into(),
vector: v.to_vec(),
neighbors: vec![links],
})
};
let nodes = vec![
node("a", [1.0, 0.0], vec![2, 9]),
None,
node("c", [0.0, 1.0], vec![0]),
];
let index = Arc::new(HnswIndex::restore(8, 64, nodes, Some(1)));
assert_eq!(index.live_count.load(Relaxed), 2);
assert_eq!(index.tombstone_count.load(Relaxed), 1);
let ep = index.entry_point.read().unwrap();
assert!(index.is_live(ep));
let mut links = Vec::new();
index.links(&index.nodes.read(), 0, 0, &mut links);
assert_eq!(links, [2]);
hnsw_insert(&index, "b".into(), vec![1.0, 1.0], &metric);
assert_eq!(index.nodes.read().count(), 3);
assert_eq!(index.key_to_id.read().get("b"), Some(&1));
let hits = knn_hnsw(&index, &[1.0, 1.0], 3, 50, &metric);
assert_eq!(hits[0].key, "b");
assert_eq!(hits.len(), 3);
}
#[test]
fn deletes_and_inserts_racing_searches_leave_every_answer_right() {
let metric = DistanceMetric::L2;
let index = graph(1000);
std::thread::scope(|s| {
for t in 0..4 {
let index = &index;
let metric = &metric;
s.spawn(move || {
for r in 0..200 {
let i = (t * 250 + r) % 1000;
let live = LiveIndex::Hnsw(Arc::clone(index));
unindex_vector(&live, &format!("k{i}"));
hnsw_insert(index, format!("k{i}"), point(i), metric);
}
});
}
for _ in 0..2 {
let index = &index;
let metric = &metric;
s.spawn(move || {
for r in 0..300 {
let q = point(r * 3 % 1000);
for h in knn_hnsw(index, &q, 10, 64, metric) {
let i: usize = h.key[1..].parse().unwrap();
let want = dist_l2_sq(&q, &point(i));
assert!((h.score - want).abs() < 1e-3, "{}: {}", h.key, h.score);
}
}
});
}
});
assert_eq!(index.live_count.load(Relaxed), 1000);
assert_eq!(
index.nodes.read().count(),
1000 + index.tombstone_count.load(Relaxed)
);
}
}