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
perf(vector): plan HNSW inserts under a shared lock, in parallel per batch (#2728)
xerj-orgf60885358a53
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 21f4eb6ae..e011323b2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -154,6 +154,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0supersedes the 120 s open quiet period in #2492, which only delayed thesame merges (Refs #2427).+- Vector ingest no longer runs on one core per index: the HNSW construction+ search (greedy descent, `ef_construction` beam and neighbour selection) now+ runs under a shared lock, and only the link writes take the graph's write+ lock. A bulk batch plans its inserts in parallel on the ingest pool, and+ concurrent batches into one index no longer queue behind each other's+ inserts (#2427).+- `_bulk` requests of ordinary text and code are no longer refused with a429 while the node has memory to spare. Each raw bulk reserved 28 bytesper input byte for analysis, a rate sized for the densest text, so a bulkdiff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 6fb62c4c0..97dcbff03 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -8202,6 +8202,82 @@ mod semantic_deadline_regression_tests {assert!(sync_idx.passage_chunks_require_exact("body_vector"));}+ /// #2427: a vector-bearing batch goes into the graph through one+ /// parallel-planned `insert_batch`. Every doc must still get exactly one+ /// live node, a doc id repeated inside the batch must tombstone its+ /// earlier node (the per-doc update semantics), and the graph must+ /// answer exact nearest-neighbour queries.+ #[tokio::test]+ async fn batched_hnsw_inserts_keep_per_doc_semantics_2427() {+ let dir = TempDir::new().unwrap();+ let engine_instance = engine(&dir);+ let mut schema = Schema::empty();+ let mut vector = FieldConfig::new("v", FieldType::Vector);+ vector.options.dimensions = Some(8);+ vector.options.similarity = Some("cosine".into());+ schema.add_field(vector).unwrap();+ engine_instance+ .create_index("batched-hnsw", schema)+ .unwrap();+ let idx = engine_instance.get_index("batched-hnsw").unwrap();++ let vector_for = |i: usize| -> Vec<f32> {+ (0..8u64)+ .map(|d| {+ let h = (i as u64 * 8 + d + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15);+ ((h >> 40) % 2001) as f32 / 1000.0 - 1.0+ })+ .collect()+ };+ let mut docs: Vec<(String, Value)> = (0..1500)+ .map(|i| {+ (+ format!("doc-{i}"),+ serde_json::json!({ "text": "t", "v": vector_for(i) }),+ )+ })+ .collect();+ // Re-index doc-7 later in the same batch with doc-1234's vector.+ docs.push((+ "doc-7".to_string(),+ serde_json::json!({ "text": "t", "v": vector_for(1234) }),+ ));+ idx.index_batch_turbo(docs, true, false).await.unwrap();++ let (graph_len, tombstones) = {+ let guard = idx.hnsw.read().await;+ let hnsw = guard.as_ref().expect("graph built");+ (hnsw.len(), hnsw.tombstone_count())+ };+ assert_eq!(graph_len, 1501, "one node per inserted vector");+ assert_eq!(+ tombstones, 1,+ "the in-batch update tombstones doc-7's first node"+ );+ let id_map = idx.hnsw_id_map.read().await.clone();+ let id_rev = idx.hnsw_id_rev.read().await.clone();+ assert_eq!(id_map.len(), 1500);+ assert_eq!(id_rev.len(), 1500);+ for (doc_id, node) in &id_map {+ assert_eq!(id_rev.get(node), Some(doc_id));+ }+ assert_eq!(idx.vector_doc_count.load(Ordering::Relaxed), 1500);++ for probe in [0usize, 333, 999, 1499] {+ let hits = idx.knn_search(&vector_for(probe), 1).await;+ assert_eq!(+ hits.first().map(|h| h.0.as_str()),+ Some(format!("doc-{probe}").as_str())+ );+ }+ // doc-7 now carries doc-1234's vector; its old vector is gone.+ let hits = idx.knn_search(&vector_for(1234), 2).await;+ let ids: HashSet<&str> = hits.iter().map(|h| h.0.as_str()).collect();+ assert_eq!(ids, HashSet::from(["doc-7", "doc-1234"]));+ let hits = idx.knn_search(&vector_for(7), 1).await;+ assert_ne!(hits.first().map(|h| h.0.as_str()), Some("doc-7"));+ }+#[tokio::test]async fn hnsw_save_racing_first_passage_write_reopens_fail_closed() {let dir = TempDir::new().unwrap();@@ -13019,9 +13095,13 @@ impl Index {}).unwrap_or(false)}) {- for ingest in &processed {- self.index_vectors(&ingest.id, &ingest.source).await;- }+ self.index_vectors_batch(+ processed+ .iter()+ .map(|ingest| (ingest.id.as_str(), ingest.source.as_ref()))+ .collect(),+ )+ .await;}// ── Step 5: check flush threshold ─────────────────────────────────@@ -13473,9 +13553,13 @@ impl Index {if let Some((doc, _)) = docs.first() {self.publication_test_point(doc, PublicationTestPoint::RawBeforeHnsw);}- for (doc, source) in docs.iter().zip(&sources) {- self.index_vectors(&doc.0, source).await;- }+ self.index_vectors_batch(+ docs.iter()+ .zip(&sources)+ .map(|(doc, source)| (doc.0.as_str(), source.as_ref()))+ .collect(),+ )+ .await;self.maybe_spawn_flush().await;@@ -13804,11 +13888,14 @@ impl Index {#[cfg(test)]self.publication_test_point(&vector_sources[0].0, PublicationTestPoint::RawBeforeHnsw);let rt = self.flush_signal.runtime().expect("validated above");- rt.block_on(async {- for (id, source) in vector_sources {- self.index_vectors(&id, &source).await;- }- });+ rt.block_on(+ self.index_vectors_batch(+ vector_sources+ .iter()+ .map(|(id, source)| (id.as_str(), source.as_ref()))+ .collect(),+ ),+ );}for shard in touched_shards {@@ -16990,20 +17077,53 @@ impl Index {/// node before inserting the fresh vector — otherwise the graph would/// keep serving the pre-update vector forever.async fn index_vectors(&self, doc_id: &str, source: &Value) {+ if let Some(vector) = self.graph_vector_for(doc_id, source).await {+ self.hnsw_insert_vector(doc_id, vector).await;+ }+ }++ /// [`index_vectors`](Self::index_vectors) for a whole batch (#2427):+ /// every doc's SQ8 codes and graph field are handled in order exactly as+ /// the per-doc path does, but the graph inserts go through one+ /// [`hnsw_insert_vectors`](Self::hnsw_insert_vectors) call, whose+ /// construction searches run in parallel. A doc id repeated inside the+ /// batch flushes the inserts collected so far first, so the later+ /// version still tombstones the earlier one.+ ///+ /// Takes a collected `Vec`, not an iterator: a borrowing iterator held+ /// across the `.await`s makes the future not provably `Send`.+ async fn index_vectors_batch(&self, docs: Vec<(&str, &Value)>) {+ let mut pending: Vec<(String, Vec<f32>)> = Vec::new();+ let mut pending_ids: HashSet<&str> = HashSet::new();+ for (doc_id, source) in docs {+ let Some(vector) = self.graph_vector_for(doc_id, source).await else {+ continue;+ };+ if !pending_ids.insert(doc_id) {+ self.hnsw_insert_vectors(std::mem::take(&mut pending)).await;+ pending_ids.clear();+ pending_ids.insert(doc_id);+ }+ pending.push((doc_id.to_string(), vector));+ }+ self.hnsw_insert_vectors(pending).await;+ }++ /// SQ8-ingest one doc and return the vector it contributes to the HNSW+ /// graph (pinning the graph field on the first vector-bearing doc), or+ /// `None` when it contributes none.+ async fn graph_vector_for(&self, doc_id: &str, source: &Value) -> Option<Vec<f32>> {// #392: SQ8 code stores are maintained for EVERY scalar8 field on// every write, independent of the single field the HNSW graph pins.self.sq8_ingest(doc_id, source).await;let obj = match source.as_object() {Some(o) => o,- None => return,+ None => return None,};let pinned: Option<String> = self.hnsw_field.read().unwrap().clone();if let Some(field) = pinned {// Enforced path: only the pinned field ever enters the graph.- if let Some(vector) = extract_numeric_vector(source, &field) {- self.hnsw_insert_vector(doc_id, vector).await;- }- return;+ return extract_numeric_vector(source, &field);}// No pinned field yet. Cheap sync pre-screen: bail before any async@@ -17024,15 +17144,12 @@ impl Index {.unwrap_or(false)});if !has_candidate {- return;+ return None;}// First vector-bearing doc: decide the field, then pin it under the// write lock (re-checking, so concurrent deciders agree on one).- let decided = match self.choose_hnsw_field(source).await {- Some(f) => f,- None => return,- };+ let decided = self.choose_hnsw_field(source).await?;let field = {let mut fg = self.hnsw_field.write().unwrap();match fg.as_ref() {@@ -17043,9 +17160,7 @@ impl Index {}}};- if let Some(vector) = extract_numeric_vector(source, &field) {- self.hnsw_insert_vector(doc_id, vector).await;- }+ extract_numeric_vector(source, &field)}/// Pick the field the HNSW graph will index, given the first@@ -17084,57 +17199,134 @@ impl Index {/// insert error) — the doc then has no `hnsw_id_map` entry, so the/// coverage guard keeps the kNN query path on brute force.async fn hnsw_insert_vector(&self, doc_id: &str, vector: Vec<f32>) -> bool {- let dim = vector.len();- if dim == 0 {- return false;+ self.hnsw_insert_vectors(vec![(doc_id.to_string(), vector)])+ .await+ .first()+ .copied()+ .unwrap_or(false)+ }++ /// Insert several docs' vectors (distinct doc ids) into the HNSW graph+ /// under one write-guard hold, with the per-doc semantics of+ /// [`hnsw_insert_vector`](Self::hnsw_insert_vector). Returns, per item,+ /// whether it went in.+ ///+ /// #2427: the graph inserts go through [`HnswIndex::insert_batch`] on the+ /// ingest pool, which runs the construction searches (the+ /// `ef_construction` beams — ~a quarter of node CPU in the 1 GB gate) in+ /// parallel and keeps only the link writes serial. Before, each doc's+ /// whole insert ran serially on one runtime thread under the graph+ /// write guard, so a vector-bearing bulk was bounded by one core no+ /// matter how idle the rest of the machine was, and concurrent bulks+ /// into one index queued behind each other. Inserts now hold the outer+ /// guard shared, so concurrent batches also plan in parallel.+ async fn hnsw_insert_vectors(&self, items: Vec<(String, Vec<f32>)>) -> Vec<bool> {+ let mut inserted = vec![false; items.len()];+ if items.iter().all(|(_, vector)| vector.is_empty()) {+ return inserted;}// UPDATE staleness fix: a doc_id that already has a node must have// that node tombstoned before the fresh vector goes in (fresh// node_id; the old node is never unmarked).- let old_node: Option<u64> = self.hnsw_id_map.read().await.get(doc_id).copied();- if old_node.is_none() {- // Item 8: a new vector-bearing doc-id. Counted on ATTEMPT (here),- // not on success below: if the insert then fails (dim mismatch /- // graph error), `id_map.len()` stays behind `vector_doc_count`,- // which holds the coverage gate on brute force — the safe- // direction (a doc that isn't in the graph must not be answered- // from it). An update (old_node.is_some()) is already counted.- self.vector_doc_count.fetch_add(1, Ordering::Relaxed);- }- let node_id = self.hnsw_next_id.fetch_add(1, Ordering::Relaxed);+ let old_nodes: Vec<Option<u64>> = {+ let id_map = self.hnsw_id_map.read().await;+ items+ .iter()+ .map(|(doc_id, _)| id_map.get(doc_id).copied())+ .collect()+ };+ let mut node_ids = Vec::with_capacity(items.len());+ for ((_, vector), old_node) in items.iter().zip(&old_nodes) {+ if vector.is_empty() {+ node_ids.push(None);+ continue;+ }+ if old_node.is_none() {+ // Item 8: a new vector-bearing doc-id. Counted on ATTEMPT+ // (here), not on success below: if the insert then fails (dim+ // mismatch / graph error), `id_map.len()` stays behind+ // `vector_doc_count`, which holds the coverage gate on brute+ // force — the safe direction (a doc that isn't in the graph+ // must not be answered from it). An update (old_node.is_some())+ // is already counted.+ self.vector_doc_count.fetch_add(1, Ordering::Relaxed);+ }+ node_ids.push(Some(self.hnsw_next_id.fetch_add(1, Ordering::Relaxed)));+ }+ let mut items = items;{- let mut hnsw_guard = self.hnsw.write().await;- if hnsw_guard.is_none() {- let params = HnswParams::new(dim, DistanceMetric::Cosine);- *hnsw_guard = Some(HnswIndex::new(params));- }- if let Some(ref hnsw) = *hnsw_guard {- if hnsw.params().dim != dim {- // Mismatched dimension — skip (no id_map entry → the- // coverage guard keeps queries on brute force).- return false;+ // Inserts share the outer guard (#2427): `HnswIndex` serializes+ // its own link writes under its inner lock, so concurrent batches+ // only overlap in the read-only construction searches. The+ // exclusive guard is taken once, to create the graph. Save and+ // the ANN query paths stay fail-closed against a concurrent+ // insert through the publication guard every vector write holds+ // (`hnsw_publications_in_flight` / `hnsw_publication_generation`),+ // not through this lock.+ let hnsw_guard = {+ let read = self.hnsw.read().await;+ if read.is_some() {+ read+ } else {+ drop(read);+ let mut write = self.hnsw.write().await;+ if write.is_none() {+ let dim = items+ .iter()+ .map(|(_, vector)| vector.len())+ .find(|&dim| dim > 0)+ .unwrap_or(0);+ let params = HnswParams::new(dim, DistanceMetric::Cosine);+ *write = Some(HnswIndex::new(params));+ }+ write.downgrade()+ }+ };+ let Some(ref hnsw) = *hnsw_guard else {+ return inserted;+ };+ let dim = hnsw.params().dim;+ let mut batch = Vec::with_capacity(items.len());+ for (i, (_, vector)) in items.iter_mut().enumerate() {+ // Mismatched dimension — skip (no id_map entry → the coverage+ // guard keeps queries on brute force).+ let Some(node_id) = node_ids[i] else { continue };+ if vector.len() != dim {+ continue;}- if let Some(old) = old_node {+ if let Some(old) = old_nodes[i] {hnsw.mark_deleted(old);}- let inserted = hnsw.insert(node_id, vector);+ batch.push((node_id, std::mem::take(vector)));+ inserted[i] = true;+ }+ if !batch.is_empty() {+ let result = crate::ingest_pool().install(|| hnsw.insert_batch(batch));self.hnsw_heap_bytes.store(hnsw.heap_bytes(), Ordering::Relaxed);- if let Err(e) = inserted {- warn!(doc_id, error = %e, "HNSW insert failed");- return false;+ if let Err(e) = result {+ // Unreachable after the dim filter above; fail safe by+ // leaving every item of the batch out of the id maps.+ warn!(error = %e, "HNSW batch insert failed");+ return vec![false; items.len()];}}}// Update id maps.let mut id_map = self.hnsw_id_map.write().await;let mut id_rev = self.hnsw_id_rev.write().await;- if let Some(old) = old_node {- id_rev.remove(&old);+ for (i, (doc_id, _)) in items.iter().enumerate() {+ if !inserted[i] {+ continue;+ }+ let node_id = node_ids[i].expect("inserted items have a node id");+ if let Some(old) = old_nodes[i] {+ id_rev.remove(&old);+ }+ id_map.insert(doc_id.clone(), node_id);+ id_rev.insert(node_id, doc_id.clone());}- id_map.insert(doc_id.to_string(), node_id);- id_rev.insert(node_id, doc_id.to_string());- true+ inserted}// ── SQ8 ingest-time code stores (#392) ──────────────────────────────@@ -17953,11 +18145,11 @@ impl Index {.max(HNSW_EF_FLOOR);// LOCK DISCIPLINE: hold the graph read guard only for the sync- // sub-ms beam search and copy the results out — index_vectors takes- // `hnsw.write().await` per ingested doc, so holding this guard- // across the doc-fetch awaits below would head-of-line-block vector- // ingest (and, via writer preference, subsequent readers): exactly- // the mixed-read-under-write failure class.+ // sub-ms beam search and copy the results out — graph creation and+ // snapshot load take `hnsw.write().await`, so holding this guard+ // across the doc-fetch awaits below would head-of-line-block them+ // (and, via writer preference, every later reader and vector+ // insert): exactly the mixed-read-under-write failure class.let raw: Vec<(u64, f32)> = {let hnsw_guard = self.hnsw.read().await;let hnsw = hnsw_guard.as_ref()?;diff --git a/engine/crates/xerj-vector/src/hnsw.rs b/engine/crates/xerj-vector/src/hnsw.rsindex 32e44dea0..3990b2941 100644--- a/engine/crates/xerj-vector/src/hnsw.rs+++ b/engine/crates/xerj-vector/src/hnsw.rs@@ -499,6 +499,65 @@ impl SlabGraphStorage {}}+/// A plan reused at commit time may have been searched on a graph up to+/// `1 / PLAN_STALENESS_DIVISOR` smaller than the one it is linked into.+const PLAN_STALENESS_DIVISOR: usize = 8;+/// Upper bound on the inserts planned concurrently in one wave.+const MAX_PLAN_WAVE: usize = 256;++/// The read-only half of one insert (#2427): the neighbours chosen for a+/// vector, searched under the shared lock, waiting to be linked.+struct PlannedInsert {+ id: u64,+ vector: Vec<f32>,+ level: usize,+ /// Node count of the graph the plan was searched on.+ nodes: usize,+ /// Entry point `(slot, layer)` of that graph.+ entry: Option<(u32, usize)>,+ /// Selected neighbours per layer (index = layer) for layers+ /// `0..=min(level, entry layer)`; `None` when the graph was empty.+ links: Option<Vec<Vec<(f32, u32)>>>,+}++impl SlabGraphStorage {+ /// Greedy descent plus the `ef`-beam and diverse selection on every+ /// layer the new node links into. Reads the graph only. `None` when the+ /// graph has no entry point yet.+ fn plan_links(+ &self,+ query: &[f32],+ level: usize,+ m: usize,+ ef: usize,+ ) -> Option<Vec<Vec<(f32, u32)>>> {+ let graph = self.read_view();+ let ep_slot = self.entry_slot?;+ let ep_layer = self.entry_layer;+ let q_inv = query_inverse(&graph, query);++ // Greedy descent from the top layer down to level+1.+ let mut curr_ep = ep_slot;+ for layer in (level + 1..=ep_layer).rev() {+ curr_ep = greedy_layer(&graph, query, q_inv, curr_ep, layer).0;+ }++ // Search from min(level, ep_layer) down to 0, selecting up to M+ // diverse nearest per layer (Algorithm 4 heuristic).+ let top = level.min(ep_layer);+ let mut links = vec![Vec::new(); top + 1];+ for layer in (0..=top).rev() {+ let m_layer = if layer == 0 { 2 * m } else { m };+ let candidates = beam(&graph, query, q_inv, curr_ep, ef, layer, &|_| true);+ links[layer] = select_diverse(&graph, &candidates, m_layer);+ if let Some(&(_, nearest)) = candidates.first() {+ curr_ep = nearest;+ }+ }+ Some(links)+ }+}+#[inline(always)]fn query_inverse(graph: &impl GraphStorageRead, query: &[f32]) -> f32 {if graph.metric() == DistanceMetric::Cosine {@@ -934,6 +993,16 @@ fn encode_graph_bytes(pub struct HnswIndex {params: HnswParams,inner: RwLock<SlabGraphStorage>,+ /// Test probe: how many construction searches ran at once (#2427).+ #[cfg(test)]+ plan_probe: PlanProbe,+}++#[cfg(test)]+#[derive(Default)]+struct PlanProbe {+ in_flight: std::sync::atomic::AtomicUsize,+ max_in_flight: std::sync::atomic::AtomicUsize,}impl HnswIndex {@@ -950,6 +1019,8 @@ impl HnswIndex {Self {params,inner: RwLock::new(inner),+ #[cfg(test)]+ plan_probe: PlanProbe::default(),}}@@ -1036,6 +1107,13 @@ impl HnswIndex {}fn insert_at_level(&self, id: u64, vector: Vec<f32>, node_level: usize) -> Result<()> {+ self.check_dim(&vector)?;+ let plan = self.plan_insert(id, vector, node_level);+ self.commit_planned(plan);+ Ok(())+ }++ fn check_dim(&self, vector: &[f32]) -> Result<()> {if vector.len() != self.params.dim {return Err(XerjError::invalid_mapping(format!("HNSW insert: vector dim {} != index dim {}",@@ -1043,59 +1121,97 @@ impl HnswIndex {self.params.dim)));}+ Ok(())+ }+ /// Phase 1 of an insert (#2427): the construction search — greedy+ /// descent, the `ef_construction` beam on every linked layer and the+ /// diverse-neighbour selection — runs under the SHARED read lock and+ /// touches nothing. This is where nearly all insert CPU goes, so plans+ /// for different vectors can be computed concurrently.+ fn plan_insert(&self, id: u64, vector: Vec<f32>, level: usize) -> PlannedInsert {+ #[cfg(test)]+ {+ use std::sync::atomic::Ordering;+ let now = self.plan_probe.in_flight.fetch_add(1, Ordering::SeqCst) + 1;+ self.plan_probe+ .max_in_flight+ .fetch_max(now, Ordering::SeqCst);+ }+ let g = self.inner.read().unwrap();+ let links = g.plan_links(&vector, level, self.params.m, self.params.ef_construction);+ #[cfg(test)]+ self.plan_probe+ .in_flight+ .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);+ PlannedInsert {+ id,+ vector,+ level,+ nodes: g.ids.len(),+ entry: g.entry_slot.map(|slot| (slot, g.entry_layer)),+ links,+ }+ }++ /// Phase 2 of an insert: allocate the slot and wire the planned links+ /// and back-links under the exclusive write lock. All graph mutation+ /// stays serial, so neighbour lists never race. A plan searched on a+ /// graph that has since grown by more than `nodes / PLAN_STALENESS_DIVISOR`+ /// (or whose entry point moved above the plan's top layer) is searched+ /// again here, so a stale snapshot can never cost link quality beyond+ /// what a bounded number of concurrent in-flight inserts would.+ fn commit_planned(&self, plan: PlannedInsert) {let m = self.params.m;let ef = self.params.ef_construction;+ let PlannedInsert {+ id,+ vector,+ level,+ nodes,+ entry,+ links,+ } = plan;let mut g = self.inner.write().unwrap();+ let current_entry = g.entry_slot.map(|slot| (slot, g.entry_layer));+ let grown = g.ids.len().saturating_sub(nodes);+ let entry_rose =+ current_entry != entry && entry.is_none_or(|(_, planned_layer)| level > planned_layer);+ let links = if links.is_none() || entry_rose || grown > nodes / PLAN_STALENESS_DIVISOR {+ g.plan_links(&vector, level, m, ef)+ } else {+ links+ };+let reuses_entry_identity = g.entry_slot.is_some_and(|entry| g.ids[entry as usize] == id);- // Query view of the new vector for the construction beams (the- // slab owns the canonical copy after alloc).- let q = vector.clone();- let q_inv = query_inverse(&g.read_view(), &q);-- // The new slot has no in-edges yet, so allocating it before the- // beams run cannot perturb them — and it means the back-link- // re-selection below can score the new node like any other- // neighbor (the pre-slab code dropped the fresh back-link on the- // floor here, disconnecting the graph: layer-0 BFS from the entry- // reached 34 of 50k nodes and recall@10 was 0.000).- let slot = g.alloc_slot(id, vector, node_level, m);+ // The new slot has no in-edges yet, and the plan was searched without+ // it, so allocating it now cannot perturb the planned links — and it+ // means the back-link re-selection below can score the new node like+ // any other neighbor (the pre-slab code dropped the fresh back-link+ // on the floor here, disconnecting the graph: layer-0 BFS from the+ // entry reached 34 of 50k nodes and recall@10 was 0.000).+ let slot = g.alloc_slot(id, vector, level, m);// Handle first insertion.- let (ep_slot, ep_layer) = match g.entry_slot {- None => {- g.entry_slot = Some(slot);- g.entry_layer = node_level;- debug!("HNSW: first node id={id} level={node_level}");- return Ok(());- }- Some(ep) => (ep, g.entry_layer),+ let Some(links) = links else {+ g.entry_slot = Some(slot);+ g.entry_layer = level;+ debug!("HNSW: first node id={id} level={level}");+ return;};- // Greedy descent from the top layer down to node_level+1.- let mut curr_ep = ep_slot;- for layer in (node_level + 1..=ep_layer).rev() {- curr_ep = greedy_layer(&g.read_view(), &q, q_inv, curr_ep, layer).0;- }-- // Search and connect from min(node_level, ep_layer) down to 0.- for layer in (0..=node_level.min(ep_layer)).rev() {+ for (layer, selected) in links.iter().enumerate().rev() {let m_layer = if layer == 0 { 2 * m } else { m };- let candidates = beam(&g.read_view(), &q, q_inv, curr_ep, ef, layer, &|_| true);-- // Select up to M diverse nearest (Algorithm 4 heuristic).- let selected = select_diverse(&g.read_view(), &candidates, m_layer);-// Connect new node → selected.g.neighbors[slot as usize][layer] = selected.iter().map(|&(_, s)| s).collect();// Back-links: add new node to each selected neighbor, and// re-select when a neighbor exceeds its link budget.- for &(_, sel) in &selected {+ for &(_, sel) in selected {g.neighbors[sel as usize][layer].push(slot);if g.neighbors[sel as usize][layer].len() > m_layer {let dists = backlink_distances(&g.read_view(), sel, layer);@@ -1103,24 +1219,19 @@ impl HnswIndex {g.neighbors[sel as usize][layer] = pruned.iter().map(|&(_, s)| s).collect();}}-- if !candidates.is_empty() {- curr_ep = candidates[0].1;- }}// Update entry point if the new node reached a higher layer.if reuses_entry_identity {- let (entry, layer) = highest_live_entry(&g.read_view()).unwrap_or((slot, node_level));+ let (entry, layer) = highest_live_entry(&g.read_view()).unwrap_or((slot, level));g.entry_slot = Some(entry);g.entry_layer = layer;- } else if node_level > g.entry_layer {+ } else if level > g.entry_layer {g.entry_slot = Some(slot);- g.entry_layer = node_level;+ g.entry_layer = level;}- trace!("HNSW: inserted id={id} level={node_level}");- Ok(())+ trace!("HNSW: inserted id={id} level={level}");}/// K-nearest neighbor search.@@ -1182,25 +1293,57 @@ impl HnswIndex {.collect())}- /// Insert a batch of `(id, vector)` items **serially**, one after another.- ///- /// This is a thin convenience wrapper over [`insert`](Self::insert): it- /// forwards each item in order and returns on the first error. It offers- /// no parallel speedup over calling `insert` in a loop yourself — despite- /// this crate depending on `rayon`, no parallelism happens here.+ /// Insert a batch of `(id, vector)` items.///- /// Insertion is kept serial on purpose: concurrent HNSW graph mutation- /// races on neighbour-list updates and can corrupt connectivity/recall,- /// so the batch API trades throughput for a provably consistent graph.+ /// The batch goes in waves (#2427). Each wave's construction searches+ /// ([`plan_insert`](Self::plan_insert), read-only) run in parallel on+ /// the caller's rayon pool against the same graph snapshot; the plans+ /// are then committed one by one under the write lock, so every+ /// neighbour-list mutation stays serial and the graph stays consistent.+ /// A wave is at most `len / PLAN_STALENESS_DIVISOR` items (capped at+ /// `MAX_PLAN_WAVE`, at least one), so an item never misses more than+ /// that fraction of the graph as candidate neighbours — on a small+ /// graph the waves are single items and insertion is exactly serial.///- /// Each item is validated by `insert` (dimension check); a mismatch- /// returns `Err` and leaves already-inserted items in the graph (this- /// API is not transactional).+ /// Items are validated in order (dimension check); on a mismatch the+ /// items before it are inserted and `Err` is returned (this API is not+ /// transactional).pub fn insert_batch(&self, items: Vec<(u64, Vec<f32>)>) -> Result<()> {- for (id, vector) in items {- self.insert(id, vector)?;+ use rayon::prelude::*;++ let mut items = items;+ let invalid = items+ .iter()+ .position(|(_, vector)| vector.len() != self.params.dim);+ let error = invalid.map(|at| self.check_dim(&items[at].1).unwrap_err());+ if let Some(at) = invalid {+ items.truncate(at);+ }++ let mut pending = items+ .into_iter()+ .map(|(id, vector)| (id, vector, self.random_level()))+ .peekable();+ while pending.peek().is_some() {+ let wave_len = (self.len() / PLAN_STALENESS_DIVISOR).clamp(1, MAX_PLAN_WAVE);+ let wave: Vec<(u64, Vec<f32>, usize)> = pending.by_ref().take(wave_len).collect();+ let plans: Vec<PlannedInsert> = if wave.len() == 1 {+ wave.into_iter()+ .map(|(id, vector, level)| self.plan_insert(id, vector, level))+ .collect()+ } else {+ wave.into_par_iter()+ .map(|(id, vector, level)| self.plan_insert(id, vector, level))+ .collect()+ };+ for plan in plans {+ self.commit_planned(plan);+ }+ }+ match error {+ Some(error) => Err(error),+ None => Ok(()),}- Ok(())}// ── Persistence ──────────────────────────────────────────────────────@@ -1378,6 +1521,8 @@ impl HnswIndex {Ok(Self {params,inner: RwLock::new(g),+ #[cfg(test)]+ plan_probe: PlanProbe::default(),})}@@ -1893,6 +2038,124 @@ mod tests {assert_eq!(idx.len(), 1, "only the pre-error item was inserted");}+ /// #2427: a batch's construction searches run concurrently on the+ /// caller's rayon pool (only the link writes are serial), and the+ /// resulting graph keeps the recall of a serial build.+ #[test]+ fn insert_batch_plans_in_parallel_and_keeps_recall_2427() {+ let dim = 16;+ let n = 4000usize;+ let vector_for = |i: usize| -> Vec<f32> {+ (0..dim as u64)+ .map(|d| {+ let h = (i as u64 * dim as u64 + d + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15);+ ((h >> 40) % 2001) as f32 / 1000.0 - 1.0+ })+ .collect()+ };+ let idx = make_index(dim);+ let items: Vec<(u64, Vec<f32>)> = (0..n).map(|i| (i as u64, vector_for(i))).collect();+ let pool = rayon::ThreadPoolBuilder::new()+ .num_threads(4)+ .build()+ .unwrap();+ pool.install(|| idx.insert_batch(items)).unwrap();+ assert_eq!(idx.len(), n);+ let max_in_flight = idx+ .plan_probe+ .max_in_flight+ .load(std::sync::atomic::Ordering::SeqCst);+ assert!(+ max_in_flight > 1,+ "construction searches never overlapped (max in flight {max_in_flight})"+ );++ let cosine = |a: &[f32], b: &[f32]| compute_distance(DistanceMetric::Cosine, a, b);+ let mut hits = 0usize;+ let queries = 50usize;+ for q in 0..queries {+ let query = vector_for(n + q);+ let mut exact: Vec<(f32, u64)> = (0..n)+ .map(|i| (cosine(&query, &vector_for(i)), i as u64))+ .collect();+ exact.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());+ let truth: HashSet<u64> = exact.iter().take(10).map(|&(_, id)| id).collect();+ let found = idx.search(&query, 10, 100).unwrap();+ hits += found.iter().filter(|(id, _)| truth.contains(id)).count();+ }+ let recall = hits as f64 / (queries * 10) as f64;+ assert!(recall >= 0.95, "recall@10 {recall:.3} < 0.95");+ }++ /// #2427: inserts from many threads at once (plans racing other+ /// threads' commits, including stale-plan re-searches) leave a+ /// consistent graph: every node is present, neighbour lists are in+ /// bounds and within their degree caps, and recall holds.+ #[test]+ fn concurrent_inserts_keep_the_graph_consistent_2427() {+ let dim = 16;+ let threads = 8usize;+ let per_thread = 400usize;+ let n = threads * per_thread;+ let vector_for = |i: usize| -> Vec<f32> {+ (0..dim as u64)+ .map(|d| {+ let h = (i as u64 * dim as u64 + d + 7).wrapping_mul(0x9E37_79B9_7F4A_7C15);+ ((h >> 40) % 2001) as f32 / 1000.0 - 1.0+ })+ .collect()+ };+ let idx = std::sync::Arc::new(make_index(dim));+ std::thread::scope(|scope| {+ for t in 0..threads {+ let idx = std::sync::Arc::clone(&idx);+ scope.spawn(move || {+ for i in (t * per_thread)..((t + 1) * per_thread) {+ idx.insert(i as u64, vector_for(i)).unwrap();+ }+ });+ }+ });+ assert_eq!(idx.len(), n);+ {+ let g = idx.inner.read().unwrap();+ let m = idx.params.m;+ for (slot, layers) in g.neighbors.iter().enumerate() {+ for (layer, list) in layers.iter().enumerate() {+ let cap = if layer == 0 { 2 * m } else { m };+ assert!(list.len() <= cap, "slot {slot} layer {layer} over cap");+ for &neighbor in list {+ assert!((neighbor as usize) < n);+ assert_ne!(neighbor as usize, slot, "self link");+ assert!(g.neighbors[neighbor as usize].len() > layer);+ }+ }+ }+ }+ let cosine = |a: &[f32], b: &[f32]| compute_distance(DistanceMetric::Cosine, a, b);+ let mut hits = 0usize;+ let queries = 50usize;+ for q in 0..queries {+ let query = vector_for(n + q);+ let mut exact: Vec<(f32, u64)> = (0..n)+ .map(|i| (cosine(&query, &vector_for(i)), i as u64))+ .collect();+ exact.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());+ let truth: HashSet<u64> = exact.iter().take(10).map(|&(_, id)| id).collect();+ let found = idx.search(&query, 10, 100).unwrap();+ hits += found.iter().filter(|(id, _)| truth.contains(id)).count();+ }+ let recall = hits as f64 / (queries * 10) as f64;+ assert!(recall >= 0.95, "recall@10 {recall:.3} < 0.95");+ for i in (0..n).step_by(97) {+ let found = idx.search(&vector_for(i), 1, 64).unwrap();+ assert_eq!(+ found[0].0, i as u64,+ "node {i} not found as its own nearest"+ );+ }+ }+#[test]fn empty_index_returns_empty() {let idx = make_index(4);