Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(vector): chunk HNSW vector storage and account for the graph in the ingest trace (#2724)

xerj-org66f3a54ad12c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 04d102f62..327425c0f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -89,6 +89,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
refused, a transient spike that pushed ingesting nodes over the breaker.
Queries hydrate such a segment on demand, as before (#2427).
+- The in-memory HNSW graph no longer stores every vector in one contiguous
+ buffer. That buffer doubled on growth, so near ~393K 384-dim vectors a
+ single 384 MiB -> 768 MiB realloc kept both copies live (~1.15 GB
+ transient) outside any memory accounting. Vectors now live in 4 MiB
+ chunks (no realloc copy, at most one chunk of slack), and the graph's
+ estimated heap is reported as the new `vector_graph` category in the
+ ingest memory trace. (#2427)
+
- `_bulk` requests of ordinary text and code are no longer refused with a
429 while the node has memory to spare. Each raw bulk reserved 28 bytes
per input byte for analysis, a rate sized for the densest text, so a bulk
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index 66b007d70..0143387b8 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -4512,6 +4512,15 @@ impl Engine {
.sum()
}
+ /// Sum of every open index's in-memory HNSW graph estimate (#2427),
+ /// reported as the `vector_graph` ingest-memory category.
+ pub fn total_vector_graph_bytes(&self) -> u64 {
+ self.indices
+ .iter()
+ .map(|e| e.value().vector_graph_bytes() as u64)
+ .sum()
+ }
+
/// Sum of every open index's version-map estimate (#2427), reported as
/// the `version_map` ingest-memory category.
pub fn total_version_map_bytes(&self) -> u64 {
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 840005402..59aae1b73 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -2,7 +2,7 @@
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use regex::Regex;
@@ -10353,6 +10353,10 @@ pub struct Index {
/// Optional HNSW index for dense-vector KNN search.
/// Lazily created on first vector document insertion.
pub hnsw: Arc<RwLock<Option<HnswIndex>>>,
+ /// Last observed `HnswIndex::heap_bytes` (#2427), refreshed under the
+ /// `hnsw` write guard on every insert and reload so the ingest-memory
+ /// sampler can read it without contending for the graph lock.
+ hnsw_heap_bytes: Arc<AtomicUsize>,
/// Maps string doc-id → u64 node-id used by HNSW.
hnsw_id_map: Arc<RwLock<HashMap<String, u64>>>,
/// Maps u64 node-id → string doc-id (reverse of hnsw_id_map).
@@ -11264,6 +11268,7 @@ impl Index {
test_segment_cache_publish_ready_mask: Arc::new(AtomicU64::new(0)),
enrichments: Arc::new(RwLock::new(HashMap::new())),
hnsw: Arc::new(RwLock::new(None)),
+ hnsw_heap_bytes: Arc::new(AtomicUsize::new(0)),
hnsw_id_map: Arc::new(RwLock::new(HashMap::new())),
hnsw_id_rev: Arc::new(RwLock::new(HashMap::new())),
hnsw_next_id: Arc::new(AtomicU64::new(1)),
@@ -11729,6 +11734,9 @@ impl Index {
schema_hash_cache: Arc::new(std::sync::atomic::AtomicU64::new(0)),
schema_hash_epoch: Arc::new(AtomicU64::new(0)),
last_flush_doc_count: Arc::new(AtomicU64::new(0)),
+ hnsw_heap_bytes: Arc::new(AtomicUsize::new(
+ hnsw_init.as_ref().map_or(0, HnswIndex::heap_bytes),
+ )),
hnsw: Arc::new(RwLock::new(hnsw_init)),
hnsw_id_map: Arc::new(RwLock::new(id_map_init)),
hnsw_id_rev: Arc::new(RwLock::new(id_rev_init)),
@@ -16745,7 +16753,10 @@ impl Index {
if let Some(old) = old_node {
hnsw.mark_deleted(old);
}
- if let Err(e) = hnsw.insert(node_id, vector) {
+ let inserted = hnsw.insert(node_id, vector);
+ 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;
}
@@ -21110,7 +21121,9 @@ impl Index {
self.hnsw_stale
.store(stale, std::sync::atomic::Ordering::Release);
let nodes = loaded.graph.len();
+ let graph_bytes = loaded.graph.heap_bytes();
*self.hnsw.write().await = Some(loaded.graph);
+ self.hnsw_heap_bytes.store(graph_bytes, Ordering::Relaxed);
info!(
nodes,
stale, "HNSW reloaded from disk — skipping WAL replay rebuild"
@@ -28819,6 +28832,12 @@ impl Index {
self.memtable.size_bytes()
}
+ /// Estimated heap held by this index's in-memory HNSW graph (#2427).
+ /// Lock-free: reads the value cached on the last insert/reload.
+ pub fn vector_graph_bytes(&self) -> usize {
+ self.hnsw_heap_bytes.load(Ordering::Relaxed)
+ }
+
/// Estimated heap held by this index's document version map (#2427).
pub fn version_map_bytes(&self) -> usize {
self.store.version_map.heap_bytes()
diff --git a/engine/crates/xerj-engine/src/ingest_memory.rs b/engine/crates/xerj-engine/src/ingest_memory.rs
index 5b7cb1859..d0865c0e9 100644
--- a/engine/crates/xerj-engine/src/ingest_memory.rs
+++ b/engine/crates/xerj-engine/src/ingest_memory.rs
@@ -125,6 +125,10 @@ pub enum Category {
CacheDecodedStored,
CacheFtsReader,
CacheVectorColumn,
+ /// In-memory HNSW graphs (vectors + neighbour lists + id maps), sampled
+ /// from every open index (#2427). Not a cache: it lives as long as the
+ /// index is open and grows with every vector document.
+ VectorGraph,
/// Per-index document version maps (doc id -> seq/segment), sampled
/// from every open index (#2427). Lives as long as the index is open
/// and grows with every distinct doc id.
@@ -132,7 +136,7 @@ pub enum Category {
}
impl Category {
- pub const ALL: [Self; 24] = [
+ pub const ALL: [Self; 25] = [
Self::HttpBody,
Self::HttpRewriteBuffer,
Self::RawSource,
@@ -156,6 +160,7 @@ impl Category {
Self::CacheDecodedStored,
Self::CacheFtsReader,
Self::CacheVectorColumn,
+ Self::VectorGraph,
Self::VersionMap,
];
@@ -511,6 +516,7 @@ fn measurement(category: Category) -> Measurement {
| Category::CacheDecodedStored
| Category::CacheFtsReader
| Category::CacheVectorColumn
+ | Category::VectorGraph
| Category::VersionMap
| Category::MergeDecoded
| Category::MergeSurvivor
diff --git a/engine/crates/xerj-server/src/ingest_memory_trace.rs b/engine/crates/xerj-server/src/ingest_memory_trace.rs
index 7398f8f00..e08c17adf 100644
--- a/engine/crates/xerj-server/src/ingest_memory_trace.rs
+++ b/engine/crates/xerj-server/src/ingest_memory_trace.rs
@@ -146,6 +146,7 @@ fn sample_loop(
fn refresh_snapshot_state(engine: &Engine) {
refresh_snapshot_state_with(
engine.total_memtable_bytes(),
+ engine.total_vector_graph_bytes(),
engine.total_version_map_bytes(),
allocator_snapshot(),
xerj_engine::governor::current_rss_bytes(),
@@ -155,6 +156,7 @@ fn refresh_snapshot_state(engine: &Engine) {
fn refresh_snapshot_state_with(
memtable_bytes: u64,
+ vector_graph_bytes: u64,
version_map_bytes: u64,
allocator: AllocatorSnapshot,
rss: u64,
@@ -164,6 +166,10 @@ fn refresh_snapshot_state_with(
ingest_memory::Category::MemtableActive,
memtable_bytes as usize,
);
+ LEDGER.observe(
+ ingest_memory::Category::VectorGraph,
+ vector_graph_bytes as usize,
+ );
LEDGER.observe(
ingest_memory::Category::VersionMap,
version_map_bytes as usize,
@@ -382,6 +388,7 @@ mod tests {
refresh_snapshot_state_with(
0,
4096,
+ 2048,
AllocatorSnapshot {
allocated: Some(11),
active: Some(12),
@@ -398,11 +405,16 @@ mod tests {
ingest_memory::Measurement::Estimated,
);
assert_eq!(memtable.current, 0);
+ let vector_graph = LEDGER.gauge(
+ ingest_memory::Category::VectorGraph,
+ ingest_memory::Measurement::Estimated,
+ );
+ assert_eq!(vector_graph.current, 4096);
let version_map = LEDGER.gauge(
ingest_memory::Category::VersionMap,
ingest_memory::Measurement::Estimated,
);
- assert_eq!(version_map.current, 4096);
+ assert_eq!(version_map.current, 2048);
}
#[cfg(unix)]
diff --git a/engine/crates/xerj-vector/src/hnsw.rs b/engine/crates/xerj-vector/src/hnsw.rs
index a3c8385f6..32e44dea0 100644
--- a/engine/crates/xerj-vector/src/hnsw.rs
+++ b/engine/crates/xerj-vector/src/hnsw.rs
@@ -178,6 +178,89 @@ impl HnswParams {
// Flat slab storage
// ─────────────────────────────────────────────────────────────────────────────
+/// Upper bound on one vector-storage chunk (#2427).
+///
+/// The slab used to keep every vector in one contiguous `Vec<f32>`, which
+/// grows by doubling. With 384-dim embeddings a 1 GB autoindex corpus
+/// reaches ~393K vectors: the next grow is a single 384 MiB -> 768 MiB
+/// `realloc`, so old and new buffers are both live during the copy
+/// (~1.15 GB for one index) and the freed half stays dirty in the
+/// allocator afterwards. The heap profile of the 1 GB gate attributed the
+/// largest untracked allocation on the ingest node to exactly that grow.
+/// Fixed-size chunks never move existing vectors, never copy, and leave at
+/// most one partly filled chunk of slack.
+const VECTOR_CHUNK_BYTES: usize = 4 << 20;
+
+/// Append-only vector storage in fixed-size chunks. `vector(slot)` stays a
+/// shift + mask + slice, and a vector never straddles two chunks.
+struct ChunkedVectors {
+ dim: usize,
+ /// log2(vectors per chunk).
+ chunk_shift: u32,
+ chunks: Vec<Vec<f32>>,
+ len: usize,
+}
+
+impl ChunkedVectors {
+ fn new(dim: usize) -> Self {
+ let per_vector = dim.max(1) * std::mem::size_of::<f32>();
+ let per_chunk = (VECTOR_CHUNK_BYTES / per_vector).max(1);
+ // Largest power of two <= per_chunk, so slot -> chunk is a shift.
+ let chunk_shift = usize::BITS - 1 - per_chunk.leading_zeros();
+ Self {
+ dim,
+ chunk_shift,
+ chunks: Vec::new(),
+ len: 0,
+ }
+ }
+
+ #[inline(always)]
+ fn per_chunk(&self) -> usize {
+ 1usize << self.chunk_shift
+ }
+
+ fn push(&mut self, vector: &[f32]) {
+ debug_assert_eq!(vector.len(), self.dim);
+ if self.len & (self.per_chunk() - 1) == 0 {
+ // Exact capacity: the chunk is filled by `extend_from_slice`
+ // and never reallocates.
+ self.chunks
+ .push(Vec::with_capacity(self.per_chunk() * self.dim));
+ }
+ let chunk = self.chunks.last_mut().expect("chunk allocated above");
+ chunk.extend_from_slice(vector);
+ self.len += 1;
+ }
+
+ #[inline(always)]
+ fn get(&self, slot: u32) -> &[f32] {
+ let slot = slot as usize;
+ let chunk = &self.chunks[slot >> self.chunk_shift];
+ let start = (slot & (self.per_chunk() - 1)) * self.dim;
+ &chunk[start..start + self.dim]
+ }
+
+ /// Bytes reserved for vector data (capacity, not length).
+ fn reserved_bytes(&self) -> usize {
+ self.chunks
+ .iter()
+ .map(|c| c.capacity() * std::mem::size_of::<f32>())
+ .sum::<usize>()
+ + self.chunks.capacity() * std::mem::size_of::<Vec<f32>>()
+ }
+
+ /// Largest single allocation backing the vectors.
+ #[cfg(test)]
+ fn largest_allocation_bytes(&self) -> usize {
+ self.chunks
+ .iter()
+ .map(|c| c.capacity() * std::mem::size_of::<f32>())
+ .max()
+ .unwrap_or(0)
+ }
+}
+
/// Slot-indexed node storage. A `slot` is a dense `u32` handle assigned in
/// insertion order; all hot-path state is `slot`-addressed so beam search
/// runs on contiguous arrays with no per-node locks or hashing.
@@ -188,8 +271,8 @@ struct SlabGraphStorage {
ids: Vec<u64>,
/// external node id → slot.
slot_of: HashMap<u64, u32>,
- /// Contiguous vector data, `slot * dim ..= slot * dim + dim`.
- vectors: Vec<f32>,
+ /// Vector data by slot, in fixed-size chunks (#2427).
+ vectors: ChunkedVectors,
/// slot → 1/‖v‖ (cosine metric only; 1.0 placeholder otherwise,
/// 0.0 for zero-norm vectors so their cosine similarity is 0 — the
/// same value the previous `cosine()` helper produced).
@@ -203,6 +286,9 @@ struct SlabGraphStorage {
tomb_ids: HashSet<u64>,
entry_slot: Option<u32>,
entry_layer: usize,
+ /// Sum of `node_level` over all slots (layers above 0), for the O(1)
+ /// heap estimate in [`SlabGraphStorage::heap_bytes`].
+ upper_layer_slots: usize,
}
/// Read-only, slot-stable graph storage consumed by HNSW traversal and
@@ -274,8 +360,7 @@ impl GraphStorageRead for SlabGraphRead<'_> {
#[inline(always)]
fn vector(&self, slot: u32) -> &[f32] {
- let start = slot as usize * self.slab.dim;
- &self.slab.vectors[start..start + self.slab.dim]
+ self.slab.vectors.get(slot)
}
#[inline(always)]
@@ -300,11 +385,7 @@ impl GraphStorageRead for SlabGraphRead<'_> {
use core::arch::x86_64::{_mm_prefetch, _MM_HINT_T0};
// Preserve the slab hot path exactly: neighbor lists contain
// allocated slots, so this direct address calculation is valid.
- let base = self
- .slab
- .vectors
- .as_ptr()
- .add(slot as usize * self.slab.dim) as *const i8;
+ let base = self.slab.vectors.get(slot).as_ptr() as *const i8;
_mm_prefetch(base, _MM_HINT_T0);
if self.slab.dim > 16 {
_mm_prefetch(base.add(64), _MM_HINT_T0);
@@ -354,14 +435,35 @@ impl SlabGraphStorage {
metric,
ids: Vec::new(),
slot_of: HashMap::new(),
- vectors: Vec::new(),
+ vectors: ChunkedVectors::new(dim),
inv_norms: Vec::new(),
neighbors: Vec::new(),
tomb: Vec::new(),
tomb_ids: HashSet::new(),
entry_slot: None,
entry_layer: 0,
- }
+ upper_layer_slots: 0,
+ }
+ }
+
+ /// O(1) estimate of the heap this graph holds (#2427). Vector storage is
+ /// exact (reserved capacity); neighbour lists are bounded by the layer
+ /// degree caps (`2m` on layer 0, `m` above), which is what pruning keeps
+ /// them at; hash tables count one control byte per entry slot.
+ fn heap_bytes(&self, m: usize) -> usize {
+ use std::mem::size_of;
+ let nodes = self.ids.len();
+ let layer_slots = nodes + self.upper_layer_slots;
+ let neighbor_ids = nodes * 2 * m + self.upper_layer_slots * m;
+ self.vectors.reserved_bytes()
+ + self.ids.capacity() * size_of::<u64>()
+ + self.inv_norms.capacity() * size_of::<f32>()
+ + self.tomb.capacity()
+ + self.neighbors.capacity() * size_of::<Vec<Vec<u32>>>()
+ + layer_slots * size_of::<Vec<u32>>()
+ + neighbor_ids * size_of::<u32>()
+ + self.slot_of.capacity() * (size_of::<(u64, u32)>() + 1)
+ + self.tomb_ids.capacity() * (size_of::<u64>() + 1)
}
#[inline(always)]
@@ -384,7 +486,7 @@ impl SlabGraphStorage {
};
self.ids.push(id);
self.slot_of.insert(id, slot);
- self.vectors.extend_from_slice(&vector);
+ self.vectors.push(&vector);
self.inv_norms.push(inv);
self.neighbors.push(
(0..=node_level)
@@ -392,6 +494,7 @@ impl SlabGraphStorage {
.collect(),
);
self.tomb.push(self.tomb_ids.contains(&id));
+ self.upper_layer_slots += node_level;
slot
}
}
@@ -834,6 +937,13 @@ pub struct HnswIndex {
}
impl HnswIndex {
+ /// Estimated heap bytes held by this graph (vectors, neighbour lists,
+ /// id maps, tombstones). O(1); takes the read lock briefly. Reported as
+ /// the `vector_graph` ingest-memory category (#2427).
+ pub fn heap_bytes(&self) -> usize {
+ self.inner.read().unwrap().heap_bytes(self.params.m)
+ }
+
/// Create a new empty index.
pub fn new(params: HnswParams) -> Self {
let inner = SlabGraphStorage::new(params.dim, params.metric);
@@ -1393,6 +1503,62 @@ mod ordered_float {
mod tests {
use super::*;
+ /// #2427: the slab's vector storage must grow in bounded chunks. One
+ /// contiguous `Vec<f32>` doubled on every grow; at the 1 GB gate's ~393K
+ /// 384-dim vectors that is a single 384 MiB -> 768 MiB realloc with both
+ /// buffers live, the largest untracked allocation in the ingest heap
+ /// profile. Chunks keep every allocation <= VECTOR_CHUNK_BYTES and the
+ /// unused tail <= one chunk, and vectors read back intact across chunk
+ /// boundaries.
+ #[test]
+ fn slab_vector_storage_grows_in_bounded_chunks_2427() {
+ let dim = 384;
+ let per_vector = dim * std::mem::size_of::<f32>();
+ let n = 3 * (VECTOR_CHUNK_BYTES / per_vector) + 7;
+ let mut slab = SlabGraphStorage::new(dim, DistanceMetric::Cosine);
+ for i in 0..n {
+ let v: Vec<f32> = (0..dim).map(|d| (i * dim + d) as f32).collect();
+ slab.alloc_slot(i as u64, v, 0, 16);
+ }
+ let view = slab.read_view();
+ for i in (0..n).step_by(97).chain([n - 1]) {
+ let v = view.vector(i as u32);
+ assert_eq!(v.len(), dim);
+ assert_eq!(v[0], (i * dim) as f32, "slot {i}");
+ assert_eq!(v[dim - 1], (i * dim + dim - 1) as f32, "slot {i}");
+ }
+ let largest = slab.vectors.largest_allocation_bytes();
+ assert!(
+ largest <= VECTOR_CHUNK_BYTES,
+ "largest vector allocation {largest} B exceeds the {VECTOR_CHUNK_BYTES} B chunk bound"
+ );
+ let used = n * per_vector;
+ let slack = slab.vectors.reserved_bytes() - used;
+ assert!(
+ slack <= VECTOR_CHUNK_BYTES + 4096,
+ "vector storage reserves {slack} B beyond the {used} B in use"
+ );
+ assert!(slab.heap_bytes(16) >= used);
+ }
+
+ /// #2427: `HnswIndex::heap_bytes` is what the `vector_graph` trace
+ /// category reports; it must cover the vectors and grow with inserts.
+ #[test]
+ fn hnsw_heap_bytes_tracks_inserted_vectors_2427() {
+ let dim = 16;
+ let index = HnswIndex::new(HnswParams::new(dim, DistanceMetric::Cosine));
+ let empty = index.heap_bytes();
+ for i in 0..200u64 {
+ let v: Vec<f32> = (0..dim)
+ .map(|d| ((i as usize * 31 + d) % 17) as f32 + 1.0)
+ .collect();
+ index.insert(i, v).unwrap();
+ }
+ let full = index.heap_bytes();
+ assert!(full > empty);
+ assert!(full >= 200 * dim * std::mem::size_of::<f32>());
+ }
+
struct FragmentedTestGraph {
ids: Vec<u64>,
vectors: Vec<Vec<f32>>,
@@ -1539,8 +1705,7 @@ mod tests {
buffer
.write_u32::<LittleEndian>(layers.len().saturating_sub(1) as u32)
.unwrap();
- let start = slot as usize * graph.dim;
- for &value in &graph.vectors[start..start + graph.dim] {
+ for &value in graph.vectors.get(slot) {
buffer.write_f32::<LittleEndian>(value).unwrap();
}
for neighbors in layers {
@@ -1586,8 +1751,7 @@ mod tests {
1.0
};
let distance = |slot: u32| {
- let start = slot as usize * graph.dim;
- let vector = &graph.vectors[start..start + graph.dim];
+ let vector = graph.vectors.get(slot);
match graph.metric {
DistanceMetric::Cosine => {
1.0 - dot_scalar(query, vector)
@@ -1927,8 +2091,7 @@ mod tests {
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.vector(slot), slab.vectors.get(slot));
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]);