AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
Merge remote-tracking branch 'origin/main' into wf-pr64
xerj-orgd4d2233613c8
diff --cc engine/crates/xerj-vector/src/hnsw.rsindex 03f1847ee,9d67e8785..22a622d5f--- a/engine/crates/xerj-vector/src/hnsw.rs+++ b/engine/crates/xerj-vector/src/hnsw.rs@@@ -420,49 -496,128 +496,166 @@@ wher}}}+ }- let mut results: Vec<(f32, u32)> = w.into_iter().map(|(d, s)| (d.0, s)).collect();- results.sort_unstable_by(|a, b| a.0.partial_cmp(&b.0).unwrap());- results- }-- /// Neighbor selection — Malkov & Yashunin Algorithm 4 (the "heuristic"- /// variant used by hnswlib and Lucene): walk candidates in ascending- /// distance-to-base order and keep a candidate only if it is closer to- /// the base than to every already-kept neighbor. Enforces direction- /// diversity in each node's link list; plain closest-M packed all links- /// into one tight cluster (recall@10 0.565 @ ef=100 on 50k random- /// 128-d where the heuristic-built graph reaches ~0.95+).- fn select_diverse(&self, cands: &[(f32, u32)], m: usize) -> Vec<(f32, u32)> {- let mut sorted = cands.to_vec();- sorted.sort_unstable_by(|a, b| a.0.partial_cmp(&b.0).unwrap());- let mut kept: Vec<(f32, u32)> = Vec::with_capacity(m);- for &(d_c, c) in &sorted {- if kept.len() >= m {- break;- }- let cv = self.vec_of(c);- let ci = self.inv_norms[c as usize];- // Diverse iff no already-kept neighbor is closer to the- // candidate than the base is.- let diverse = kept.iter().all(|&(_, r)| self.slot_dist(cv, ci, r) >= d_c);- if diverse {- kept.push((d_c, c));+ let mut ordered: Vec<(f32, u32)> = results+ .into_iter()+ .map(|(distance, slot)| (distance.0, slot))+ .collect();+ ordered.sort_unstable_by(|left, right| left.0.partial_cmp(&right.0).unwrap());+ ordered+ }++ fn select_diverse(+ graph: &impl GraphStorageRead,+ candidates: &[(f32, u32)],+ max_neighbors: usize,+ ) -> Vec<(f32, u32)> {+ let mut sorted = candidates.to_vec();+ sorted.sort_unstable_by(|left, right| left.0.partial_cmp(&right.0).unwrap());+ let mut kept = Vec::with_capacity(max_neighbors);+ for &(candidate_distance, candidate) in &sorted {+ if kept.len() >= max_neighbors {+ break;+ }+ let vector = graph.vector(candidate);+ let inverse_norm = graph.inverse_norm(candidate);+ let diverse = kept.iter().all(|&(_, retained)| {+ slot_distance(graph, vector, inverse_norm, retained) >= candidate_distance+ });+ if diverse {+ kept.push((candidate_distance, candidate));+ }+ }+ kept+ }++ fn backlink_distances(graph: &impl GraphStorageRead, base: u32, layer: usize) -> Vec<(f32, u32)> {+ let vector = graph.vector(base);+ let inverse_norm = graph.inverse_norm(base);+ graph+ .neighbors(base, layer)+ .iter()+ .map(|&neighbor| {+ (+ slot_distance(graph, vector, inverse_norm, neighbor),+ neighbor,+ )+ })+ .collect()+ }+++/// True when `slot` is the current slot for its external ID. A reused++/// external ID orphans its old slot: the orphan stays in the slab as++/// traversal-only topology and must never surface as a hit or be++/// persisted as graph metadata.++#[inline]++fn is_live_slot(graph: &impl GraphStorageRead, slot: u32) -> bool {++ graph.current_slot(graph.external_id(slot)) == Some(slot)++}++++/// The live slot with the highest layer, preferring the stored entry++/// point when it is still live. This is the entry the graph should++/// advertise: after an external-ID reuse the stored `entry_slot` /++/// `entry_layer` pair can describe an orphan slot (or pair the current++/// identity with the orphan's layer), which persisted as a corrupt++/// header and resurfaced stale vectors.++fn highest_live_entry(graph: &impl GraphStorageRead) -> Option<(u32, usize)> {++ let slot_layer = |slot: u32| graph.layer_count(slot).saturating_sub(1);++ let mut best = graph++ .entry_slot()++ .filter(|&slot| is_live_slot(graph, slot))++ .map(|slot| (slot, slot_layer(slot)));++ for slot in 0..graph.node_count() as u32 {++ if !is_live_slot(graph, slot) {++ continue;++ }++ let layer = slot_layer(slot);++ if best.is_none_or(|(_, best_layer)| layer > best_layer) {++ best = Some((slot, layer));++ }++ }++ best++}+++ fn encode_graph_bytes(+ params: &HnswParams,+ graph: &impl GraphStorageRead,+ ) -> Result<(Vec<u8>, usize)> {+ let mut buffer = Vec::with_capacity(1024 * 1024);+ buffer.write_all(HNSW_MAGIC).map_err(io_to_xerj)?;+ buffer+ .write_u32::<LittleEndian>(HNSW_FORMAT_VERSION)+ .map_err(io_to_xerj)?;+ buffer+ .write_u32::<LittleEndian>(params.m as u32)+ .map_err(io_to_xerj)?;+ buffer+ .write_u32::<LittleEndian>(params.ef_construction as u32)+ .map_err(io_to_xerj)?;+ buffer+ .write_u8(metric_to_u8(params.metric))+ .map_err(io_to_xerj)?;+ buffer+ .write_u32::<LittleEndian>(graph.dimension() as u32)+ .map_err(io_to_xerj)?;+- let entry_id = graph.entry_slot().map(|slot| graph.external_id(slot));++ // Derive the entry header from live topology rather than trusting the++ // stored entry metadata: after an external-ID reuse the stored pair can++ // name an orphan slot or an inflated layer, and a reload would reject++ // or mis-descend the graph.++ let live_entry = highest_live_entry(graph);++ let entry_id = live_entry.map(|(slot, _)| graph.external_id(slot));+ buffer+ .write_u64::<LittleEndian>(entry_id.unwrap_or(u64::MAX))+ .map_err(io_to_xerj)?;+ buffer- .write_u32::<LittleEndian>(graph.entry_layer() as u32)++ .write_u32::<LittleEndian>(live_entry.map_or(0, |(_, layer)| layer) as u32)+ .map_err(io_to_xerj)?;++ // Live slots only (a reused external ID orphans its old slot).+ let live: Vec<u32> = (0..graph.node_count() as u32)- .filter(|&slot| graph.current_slot(graph.external_id(slot)) == Some(slot))++ .filter(|&slot| is_live_slot(graph, slot))+ .collect();+ buffer+ .write_u32::<LittleEndian>(live.len() as u32)+ .map_err(io_to_xerj)?;+ for &slot in &live {+ buffer+ .write_u64::<LittleEndian>(graph.external_id(slot))+ .map_err(io_to_xerj)?;+ buffer+ .write_u32::<LittleEndian>(graph.layer_count(slot).saturating_sub(1) as u32)+ .map_err(io_to_xerj)?;+ for &value in graph.vector(slot) {+ buffer+ .write_f32::<LittleEndian>(value)+ .map_err(io_to_xerj)?;+ }+ for layer in 0..graph.layer_count(slot) {+ let neighbors = graph.neighbors(slot, layer);+ buffer+ .write_u32::<LittleEndian>(neighbors.len() as u32)+ .map_err(io_to_xerj)?;+ for &neighbor in neighbors {+ buffer+ .write_u64::<LittleEndian>(graph.external_id(neighbor))+ .map_err(io_to_xerj)?;}}- kept}- /// Distances from `base` to each of its current neighbors at `layer`- /// (used when a saturated node re-selects after gaining a back-link).- fn backlink_dists(&self, base: u32, layer: usize) -> Vec<(f32, u32)> {- let bv = self.vec_of(base);- let bi = self.inv_norms[base as usize];- self.neighbors[base as usize][layer]- .iter()- .map(|&nb| (self.slot_dist(bv, bi, nb), nb))- .collect()+ buffer+ .write_u32::<LittleEndian>(graph.tombstone_count() as u32)+ .map_err(io_to_xerj)?;+ for tombstone in graph.tombstone_ids() {+ buffer+ .write_u64::<LittleEndian>(tombstone)+ .map_err(io_to_xerj)?;}+ let crc = crc32fast::hash(&buffer);+ buffer.write_u32::<LittleEndian>(crc).map_err(io_to_xerj)?;+ Ok((buffer, live.len()))}// ─────────────────────────────────────────────────────────────────────────────@@@ -643,11 -797,7 +841,11 @@@ impl HnswIndex}// Update entry point if the new node reached a higher layer.- if node_level > g.entry_layer {+ if reuses_entry_identity {- let (entry, layer) = g.highest_live_entry().unwrap_or((slot, node_level));++ let (entry, layer) = highest_live_entry(&g.read_view()).unwrap_or((slot, node_level));+ g.entry_slot = Some(entry);+ g.entry_layer = layer;+ } else if node_level > g.entry_layer {g.entry_slot = Some(slot);g.entry_layer = node_level;}@@@ -701,8 -852,8 +900,10 @@@// recall collapses) but excluded from the result set. The whole// search runs under one read guard, so it sees a consistent// tombstone set even if mark_deleted runs mid-query.- let admit = |s: u32| g.is_live_slot(s) && !g.tomb[s as usize] && filter(g.ids[s as usize]);- let candidates = g.beam(query, q_inv, curr_ep, ef.max(k), 0, &admit);- let admit = |slot: u32| !graph.tombstoned(slot) && filter(graph.external_id(slot));++ let admit = |slot: u32| {++ is_live_slot(&graph, slot) && !graph.tombstoned(slot) && filter(graph.external_id(slot))++ };+ let candidates = beam(&graph, query, q_inv, curr_ep, ef.max(k), 0, &admit);Ok(candidates.into_iter()@@@ -1215,89 -1585,155 +1635,238 @@@ mod testsassert_eq!(aset, bset, "neighbour set differs after save/load");}+ #[test]+ fn reused_entry_external_id_with_lower_layer_saves_a_reloadable_graph() {+ let idx = HnswIndex::new(HnswParams::new(2, DistanceMetric::Cosine));+ idx.insert_at_level(7, vec![1.0, 0.0], 3).unwrap();+ idx.insert_at_level(7, vec![0.0, 1.0], 0).unwrap();++ let structure = idx.debug_structure();+ assert_eq!(structure.0, Some(7));+ assert_eq!(structure.1, 0);+ let runtime_hit = idx.search(&[1.0, 0.0], 1, 8).unwrap()[0];+ assert_eq!(runtime_hit.0, 7);+ assert!(+ runtime_hit.1 > 0.9,+ "the superseded slot must be traversal-only, not a stale hit"+ );++ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("graph.bin");+ idx.save_to(&path).unwrap();+ let reopened = HnswIndex::load_from(&path).unwrap();++ assert_eq!(reopened.len(), 1);+ assert!(reopened.vector_matches(7, &[0.0, 1.0]));+ let structure = reopened.debug_structure();+ assert_eq!(structure.0, Some(7));+ assert_eq!(structure.1, 0);+ }++ #[test]+ fn reused_entry_id_falls_back_to_the_highest_remaining_live_node() {+ let idx = HnswIndex::new(HnswParams::new(2, DistanceMetric::L2));+ for (id, vector, level) in [+ (7, vec![1.0, 0.0], 3),+ (8, vec![0.5, 0.5], 2),+ (7, vec![0.0, 1.0], 0),+ ] {+ idx.insert_at_level(id, vector, level).unwrap();+ }++ let structure = idx.debug_structure();+ assert_eq!(structure.0, Some(8));+ assert_eq!(structure.1, 2);+ assert_eq!(idx.search(&[0.0, 1.0], 1, 16).unwrap()[0].0, 7);+ assert_eq!(idx.search(&[0.5, 0.5], 1, 16).unwrap()[0].0, 8);++ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("graph.bin");+ idx.save_to(&path).unwrap();+ let reopened = HnswIndex::load_from(&path).unwrap();+ assert_eq!(reopened.len(), 2);+ let structure = reopened.debug_structure();+ assert_eq!(structure.0, Some(8));+ assert_eq!(structure.1, 2);+ assert_eq!(reopened.search(&[0.0, 1.0], 1, 16).unwrap()[0].0, 7);+ assert_eq!(reopened.search(&[0.5, 0.5], 1, 16).unwrap()[0].0, 8);+ }++ #[test]+ fn writer_repairs_a_stale_reused_id_entry_header() {+ let idx = HnswIndex::new(HnswParams::new(2, DistanceMetric::Cosine));+ idx.insert_at_level(7, vec![1.0, 0.0], 3).unwrap();+ idx.insert_at_level(7, vec![0.0, 1.0], 0).unwrap();++ // Recreate the stale in-memory state produced before this fix.+ // Persistence must derive its header from live topology rather than+ // pairing the orphan slot's layer with the current slot's identity.+ {+ let mut graph = idx.inner.write().unwrap();+ graph.entry_slot = Some(0);+ graph.entry_layer = 3;+ }++ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("graph.bin");+ idx.save_to(&path).unwrap();+ let reopened = HnswIndex::load_from(&path).unwrap();+ assert_eq!(reopened.len(), 1);+ assert!(reopened.vector_matches(7, &[0.0, 1.0]));+ let structure = reopened.debug_structure();+ assert_eq!(structure.0, Some(7));+ assert_eq!(structure.1, 0);+ }++ #[test]+ fn slab_read_view_preserves_search_and_graph_bytes() {+ for metric in [+ DistanceMetric::Cosine,+ DistanceMetric::L2,+ DistanceMetric::DotProduct,+ ] {+ let index = HnswIndex::new(HnswParams::new(3, metric));+ let ids = [17, (1u64 << 48) + 9, 23, 41, 99];+ let vectors = [+ vec![1.0, 0.0, 0.0],+ vec![1.0, 0.0, 0.0],+ vec![0.5, 0.5, 0.0],+ vec![0.0, 1.0, 0.0],+ vec![0.0, 0.0, 1.0],+ ];+ for (&id, vector) in ids.iter().zip(vectors) {+ index.insert(id, vector).unwrap();+ }+ index.mark_deleted(ids[4]);+ index.mark_deleted(999_999_999_999);++ for query in [[1.0, 0.0, 0.0], [0.25, 0.75, 0.0]] {+ let expected = {+ let slab = index.inner.read().unwrap();+ legacy_search(&slab, &query, 4, 32, &|id| id != ids[3])+ };+ let actual = index+ .search_filtered(&query, 4, 32, &|id| id != ids[3])+ .unwrap();+ assert_eq!(+ actual, expected,+ "metric, tie, or filter behavior changed for {metric:?}"+ );+ }++ let slab = index.inner.read().unwrap();+ let view = slab.read_view();+ assert_eq!(view.node_count(), slab.ids.len());+ assert_eq!(view.entry_slot(), slab.entry_slot);+ assert_eq!(view.entry_layer(), slab.entry_layer);+ for slot in 0..view.node_count() as u32 {+ assert_eq!(view.external_id(slot), slab.ids[slot as usize]);+ assert_eq!(+ view.current_slot(view.external_id(slot)),+ slab.slot_of.get(&slab.ids[slot as usize]).copied()+ );+ let start = slot as usize * slab.dim;+ assert_eq!(view.vector(slot), &slab.vectors[start..start + slab.dim]);+ assert_eq!(view.inverse_norm(slot), slab.inv_norms[slot as usize]);+ assert_eq!(view.layer_count(slot), slab.neighbors[slot as usize].len());+ assert_eq!(view.tombstoned(slot), slab.tomb[slot as usize]);+ for layer in 0..view.layer_count(slot) {+ assert_eq!(+ view.neighbors(slot, layer),+ slab.neighbors[slot as usize][layer]+ );+ }+ }+ assert_eq!(+ encode_graph_bytes(&index.params, &view).unwrap().0,+ legacy_encode_graph_bytes(&index.params, &slab),+ "writer bytes changed for {metric:?}"+ );+ }+ }++ #[test]+ fn generic_read_boundary_accepts_fragmented_backend() {+ let graph = FragmentedTestGraph {+ ids: vec![17, (1u64 << 48) + 5, 91],+ vectors: vec![vec![1.0, 0.0], vec![0.8, 0.2], vec![0.0, 1.0]],+ inverse_norms: vec![1.0, 1.0 / 0.68f32.sqrt(), 1.0],+ neighbors: vec![vec![vec![1]], vec![vec![0, 2]], vec![vec![1]]],+ tombstones: vec![91],+ entry: Some(0),+ };+ let query = [1.0, 0.0];+ let inverse = query_inverse(&graph, &query);+ let candidates = beam(+ &graph,+ &query,+ inverse,+ graph.entry_slot().unwrap(),+ 8,+ 0,+ &|slot| !graph.tombstoned(slot),+ );+ let hits: Vec<_> = candidates+ .into_iter()+ .map(|(distance, slot)| (graph.external_id(slot), distance))+ .collect();+ assert_eq!(hits[0], (17, 0.0));+ assert_eq!(hits.len(), 2);++ let params = HnswParams::new(2, DistanceMetric::Cosine);+ let (bytes, nodes) = encode_graph_bytes(¶ms, &graph).unwrap();+ assert_eq!(nodes, 3);+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("fragmented.bin");+ std::fs::write(&path, bytes).unwrap();+ let loaded = HnswIndex::load_from(&path).unwrap();+ assert_eq!(loaded.len(), 3);+ assert!(loaded.is_deleted(91));+ assert_eq!(loaded.search(&query, 3, 8).unwrap()[0], (17, 0.0));+ }++ #[test]+ fn checked_in_pre_view_v2_fixture_reads_and_current_writer_reopens() {+ let directory = tempfile::tempdir().unwrap();+ let fixture_path = directory.path().join("pre-view.bin");+ std::fs::write(&fixture_path, checked_in_pre_view_v2_fixture()).unwrap();+ let old = HnswIndex::load_from(&fixture_path).unwrap();+ let large_id = (1u64 << 48) + 3;+ assert_eq!(old.len(), 2);+ assert!(old.vector_matches(17, &[1.0, 0.0]));+ assert!(old.is_deleted(large_id));+ assert!(old.is_deleted(999_999_999_999));+ assert_eq!(old.search(&[1.0, 0.0], 2, 16).unwrap(), vec![(17, 0.0)]);++ let output_path = directory.path().join("current-writer.bin");+ old.save_to(&output_path).unwrap();+ let reopened = HnswIndex::load_from(&output_path).unwrap();+ assert_eq!(+ reopened.search(&[1.0, 0.0], 2, 16).unwrap(),+ vec![(17, 0.0)]+ );+ assert!(reopened.is_deleted(large_id));+ assert!(reopened.is_deleted(999_999_999_999));+ }++ #[test]+ fn reused_external_id_writer_omits_orphaned_slot() {+ let index = make_index(3);+ index.insert(17, vec![1.0, 0.0, 0.0]).unwrap();+ index.insert(23, vec![0.0, 1.0, 0.0]).unwrap();+ index.insert(17, vec![0.0, 0.0, 1.0]).unwrap();+ assert_eq!(index.len(), 3, "old slot remains in the mutable slab");+ assert!(index.vector_matches(17, &[0.0, 0.0, 1.0]));++ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("reused-id.bin");+ index.save_to(&path).unwrap();+ let reopened = HnswIndex::load_from(&path).unwrap();+ assert_eq!(reopened.len(), 2);+ assert!(reopened.vector_matches(17, &[0.0, 0.0, 1.0]));+ assert!(reopened.vector_matches(23, &[0.0, 1.0, 0.0]));+ }+#[test]fn load_rejects_corrupt_file() {let dir = tempfile::tempdir().unwrap();