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
Stream HNSW graph and ids.json snapshots to disk instead of buffering them (#2809)
xerj-org0b9df255492c
diff --git a/engine/crates/xerj-common/src/fsio.rs b/engine/crates/xerj-common/src/fsio.rsindex 6d8d241e0..c6fc9ebcf 100644--- a/engine/crates/xerj-common/src/fsio.rs+++ b/engine/crates/xerj-common/src/fsio.rs@@ -481,6 +481,30 @@ pub enum DurableWriteStage {pub fn write_file_durable_with_hook(path: &Path,bytes: &[u8],+ hook: impl FnMut(DurableWriteStage) -> std::io::Result<()>,+) -> std::io::Result<()> {+ durable_publish(path, |f| f.write_all(bytes), hook)+}++/// [`write_file_durable`] for a body produced by a writer instead of a slice.+///+/// `write_body` writes the whole file content into the temp file; the temp+/// file is then fsynced, renamed over `path`, and the parent directory is+/// fsynced, exactly like [`write_file_durable`]. Use it when the content is+/// large enough that building it in memory first would double its footprint+/// (an HNSW graph snapshot is the size of the graph, #2427). On error the+/// temp file is removed and `path` is untouched. Buffer the writes yourself+/// (e.g. `std::io::BufWriter`) — the `File` is handed over unbuffered.+pub fn write_file_durable_streaming(+ path: &Path,+ write_body: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>,+) -> std::io::Result<()> {+ durable_publish(path, write_body, |_| Ok(()))+}++fn durable_publish(+ path: &Path,+ write_body: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>,mut hook: impl FnMut(DurableWriteStage) -> std::io::Result<()>,) -> std::io::Result<()> {let nonce = format!("{:x}-{:?}", std::process::id(), std::thread::current().id());@@ -492,8 +516,12 @@ pub fn write_file_durable_with_hook(hook(DurableWriteStage::BeforeTempWrite)?;{let mut f = std::fs::File::create(&tmp)?;- f.write_all(bytes)?;- sync_file_full(&f)?;+ let written = write_body(&mut f).and_then(|()| sync_file_full(&f));+ if let Err(error) = written {+ drop(f);+ let _ = std::fs::remove_file(&tmp);+ return Err(error);+ }}if let Err(error) = hook(DurableWriteStage::BeforeRename) {let _ = std::fs::remove_file(&tmp);@@ -534,6 +562,32 @@ mod tests {assert!(leftovers.is_empty(), "temp files left: {leftovers:?}");}+ #[test]+ fn write_file_durable_streaming_round_trip_and_failure_keeps_old_file() {+ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("graph.bin");+ write_file_durable_streaming(&p, |f| {+ f.write_all(b"hel")?;+ f.write_all(b"lo")+ })+ .unwrap();+ assert_eq!(std::fs::read(&p).unwrap(), b"hello");+ // A body that fails part-way must leave the old file and no temp file.+ let err = write_file_durable_streaming(&p, |f| {+ f.write_all(b"torn")?;+ Err(std::io::Error::other("encode failed"))+ })+ .unwrap_err();+ assert_eq!(err.to_string(), "encode failed");+ assert_eq!(std::fs::read(&p).unwrap(), b"hello");+ let leftovers: Vec<_> = std::fs::read_dir(dir.path())+ .unwrap()+ .filter_map(|e| e.ok())+ .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))+ .collect();+ assert!(leftovers.is_empty(), "temp files left: {leftovers:?}");+ }+#[cfg(not(windows))]#[test]fn fsync_dir_works() {diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex ee21d17c6..8967df151 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -218,6 +218,94 @@ fn hnsw_id_table_bytes(map: &HashMap<HnswDocId, u64>, rev: &HashMap<u64, HnswDoc/// per graphed doc were ~half of the maps' heap).type HnswDocId = Arc<str>;+/// `hnsw/ids.json`, serialized without an intermediate `serde_json::Value`+/// (#2427). Field order matches the loader's historical `json!` layout.+#[derive(serde::Serialize)]+struct HnswIdsSnapshot<'a> {+ next_id: u64,+ map: HnswIdMapJson<'a>,+ field: Option<String>,+ seq_no: u64,+ stale: bool,+ passage_guard_version: u32,+ passage_chunk_fields: Vec<String>,+}++/// The doc-id → node map of [`HnswIdsSnapshot`], streamed in map order.+struct HnswIdMapJson<'a>(&'a HashMap<HnswDocId, u64>);++impl serde::Serialize for HnswIdMapJson<'_> {+ fn serialize<S: serde::Serializer>(+ &self,+ serializer: S,+ ) -> std::result::Result<S::Ok, S::Error> {+ serializer.collect_map(self.0.iter().map(|(doc_id, node)| (&**doc_id, *node)))+ }+}++fn write_hnsw_ids_snapshot(+ file: &mut std::fs::File,+ snapshot: &HnswIdsSnapshot<'_>,+) -> std::io::Result<()> {+ let mut out = std::io::BufWriter::with_capacity(1024 * 1024, file);+ serde_json::to_writer(&mut out, snapshot).map_err(std::io::Error::other)?;+ std::io::Write::flush(&mut out)+}++#[cfg(test)]+mod hnsw_ids_snapshot_tests {+ use super::*;++ /// The streamed ids.json must be byte-identical to the `json!` layout+ /// it replaced, so old and new binaries read each other's files.+ #[test]+ fn streamed_ids_json_matches_value_layout() {+ let mut id_map: HashMap<HnswDocId, u64> = HashMap::new();+ for i in 0..64u64 {+ id_map.insert(Arc::from(format!("doc-\"{i}\"\u{e9}").as_str()), i * 3);+ }+ for (field, chunks) in [+ (+ Some("body".to_string()),+ vec!["a".to_string(), "b".to_string()],+ ),+ (None, Vec::new()),+ ] {+ let legacy = serde_json::json!({+ "next_id": 192u64,+ "map": id_map+ .iter()+ .map(|(doc_id, node)| (doc_id.to_string(), serde_json::Value::from(*node)))+ .collect::<serde_json::Map<String, serde_json::Value>>(),+ "field": field.clone(),+ "seq_no": 41u64,+ "stale": true,+ "passage_guard_version": 1,+ "passage_chunk_fields": chunks.clone(),+ });+ let snapshot = HnswIdsSnapshot {+ next_id: 192,+ map: HnswIdMapJson(&id_map),+ field,+ seq_no: 41,+ stale: true,+ passage_guard_version: 1,+ passage_chunk_fields: chunks,+ };+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("ids.json");+ xerj_common::fsio::write_file_durable_streaming(&path, |file| {+ write_hnsw_ids_snapshot(file, &snapshot)+ })+ .unwrap();+ assert_eq!(+ std::fs::read(&path).unwrap(),+ serde_json::to_vec(&legacy).unwrap()+ );+ }+ }+}+/// Heap bytes of one shared doc id: the string plus the `Arc` counts.fn hnsw_id_key_cost(doc_id: &str) -> usize {doc_id.len() + 2 * std::mem::size_of::<usize>()@@ -22023,18 +22111,15 @@ impl Index {|| seq_after != seq_before|| publication_in_flight != 0|| publication_generation_before != publication_generation_after;- let snapshot = serde_json::json!({- "next_id": self.hnsw_next_id.load(Ordering::Relaxed),- "map": id_map- .iter()- .map(|(doc_id, node)| (doc_id.to_string(), serde_json::Value::from(*node)))- .collect::<serde_json::Map<String, serde_json::Value>>(),- "field": hnsw_field,- "seq_no": seq_before,- "stale": snapshot_stale,- "passage_guard_version": 1,- "passage_chunk_fields": passage_chunk_fields,- });+ let snapshot = HnswIdsSnapshot {+ next_id: self.hnsw_next_id.load(Ordering::Relaxed),+ map: HnswIdMapJson(&id_map),+ field: hnsw_field,+ seq_no: seq_before,+ stale: snapshot_stale,+ passage_guard_version: 1,+ passage_chunk_fields,+ };// Durable atomic publish (RC4 W2 item 19 — same treatment as// graph.bin in HnswIndex::save_to): fsync file + rename + fsync// parent dir, so power loss can't leave a torn/evaporating@@ -22043,10 +22128,14 @@ impl Index {// stamp then mismatches the replayed WAL position → the loader// marks the pair stale and the rebuild path re-derives it (never// serves a mixed pair).- if let Err(e) = xerj_common::fsio::write_file_durable(- &self.hnsw_ids_path(),- &serde_json::to_vec(&snapshot).unwrap_or_default(),- ) {+ //+ // Serialized straight into the temp file (#2427): building a+ // `serde_json::Value` map of every id first cost ~6x the file size.+ if let Err(e) =+ xerj_common::fsio::write_file_durable_streaming(&self.hnsw_ids_path(), |file| {+ write_hnsw_ids_snapshot(file, &snapshot)+ })+ {warn!(error = %e, "HNSW save: ids.json write failed");return Ok(());}diff --git a/engine/crates/xerj-vector/src/hnsw.rs b/engine/crates/xerj-vector/src/hnsw.rsindex a8a333271..641330ea0 100644--- a/engine/crates/xerj-vector/src/hnsw.rs+++ b/engine/crates/xerj-vector/src/hnsw.rs@@ -971,11 +971,76 @@ fn highest_live_entry(graph: &impl GraphStorageRead) -> Option<(u32, usize)> {best}+#[cfg(test)]fn encode_graph_bytes(params: &HnswParams,graph: &impl GraphStorageRead,) -> Result<(Vec<u8>, usize)> {- let mut buffer = Vec::with_capacity(1024 * 1024);+ encode_graph_to(params, graph, Vec::with_capacity(1024 * 1024))+}++/// Feeds every byte written through it into a CRC32 hasher.+struct CrcWriter<W> {+ inner: W,+ hasher: crc32fast::Hasher,+}++impl<W: Write> Write for CrcWriter<W> {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ let n = self.inner.write(buf)?;+ self.hasher.update(&buf[..n]);+ Ok(n)+ }++ fn flush(&mut self) -> std::io::Result<()> {+ self.inner.flush()+ }+}++/// Counts the bytes written through it.+struct CountingWriter<W> {+ inner: W,+ count: u64,+}++impl<W> CountingWriter<W> {+ fn new(inner: W) -> Self {+ Self { inner, count: 0 }+ }+}++impl<W: Write> Write for CountingWriter<W> {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ let n = self.inner.write(buf)?;+ self.count += n as u64;+ Ok(n)+ }++ fn flush(&mut self) -> std::io::Result<()> {+ self.inner.flush()+ }+}++/// Encode the graph into `out` and return it with the live node count.+///+/// This is the whole on-disk format; nothing proportional to the graph is held in memory. Saving a+/// graph used to build the whole file in a `Vec` that grew by doubling, so+/// every save — each flush, including the memory-pressure drain — added+/// one to two times the graph size to RSS (#2427: +1.0 GB for a 0.93 GB+/// graph). Writes go through a 1 MiB buffer and the CRC is computed over+/// the same stream.+fn encode_graph_to<W: Write>(+ params: &HnswParams,+ graph: &impl GraphStorageRead,+ out: W,+) -> Result<(W, usize)> {+ let mut buffer = std::io::BufWriter::with_capacity(+ 1024 * 1024,+ CrcWriter {+ inner: out,+ hasher: crc32fast::Hasher::new(),+ },+ );buffer.write_all(HNSW_MAGIC).map_err(io_to_xerj)?;buffer.write_u32::<LittleEndian>(HNSW_FORMAT_VERSION)@@ -1046,9 +1111,13 @@ fn encode_graph_bytes(.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()))+ let CrcWriter { mut inner, hasher } = buffer+ .into_inner()+ .map_err(|e| io_to_xerj(e.into_error()))?;+ inner+ .write_u32::<LittleEndian>(hasher.finalize())+ .map_err(io_to_xerj)?;+ Ok((inner, live.len()))}// ─────────────────────────────────────────────────────────────────────────────@@ -1595,10 +1664,6 @@ impl HnswIndex {if let Some(parent) = path.parent() {std::fs::create_dir_all(parent).map_err(io_to_xerj)?;}- let g = self.inner.read().unwrap();- let (buf, node_count) = encode_graph_bytes(&self.params, &g.read_view())?;- drop(g);-// Atomic + durable publish (RC4 W2 item 19). The previous// fs::write + rename left both the file bytes and the directory// entry in the volatile page cache: a power loss shortly after a@@ -1606,12 +1671,27 @@ impl HnswIndex {// the next open) or no file at all — and because the id-map/graph// pair then fails to load or fails its freshness stamp, every kNN// after recovery silently degraded to permanent-stale/brute.- // write_file_durable fsyncs the temp file, renames, then fsyncs+ // write_file_durable_streaming fsyncs the temp file, renames, then fsyncs// the parent directory so the rename itself survives power loss.- xerj_common::fsio::write_file_durable(path, &buf).map_err(io_to_xerj)?;+ // Stream straight into the temp file (#2427): the read lock is held+ // while the bytes go to the page cache, and released before fsync.+ let mut written = (0u64, 0usize);+ xerj_common::fsio::write_file_durable_streaming(path, |file| {+ let g = self.inner.read().unwrap();+ let (mut out, node_count) =+ encode_graph_to(&self.params, &g.read_view(), CountingWriter::new(file))+ .map_err(|e| std::io::Error::other(e.to_string()))?;+ drop(g);+ out.flush()?;+ written = (out.count, node_count);+ Ok(())+ })+ .map_err(io_to_xerj)?;+ let (bytes, node_count) = written;+debug!(path = %path.display(),- bytes = buf.len(),+ bytes,nodes = node_count,"HNSW graph persisted");@@ -2584,6 +2664,35 @@ mod tests {}}+ #[test]+ fn streamed_save_writes_legacy_bytes_and_round_trips() {+ let index = HnswIndex::new(HnswParams::new(8, DistanceMetric::Cosine));+ for id in 0..600u64 {+ let v: Vec<f32> = (0..8)+ .map(|d| ((id * 31 + d * 7) % 97) as f32 + 1.0)+ .collect();+ index.insert(id + (1 << 40), v).unwrap();+ }+ for id in (0..600u64).step_by(7) {+ index.mark_deleted(id + (1 << 40));+ }+ let expected = {+ let slab = index.inner.read().unwrap();+ legacy_encode_graph_bytes(&index.params, &slab)+ };+ // Bigger than the 1 MiB write buffer would be ideal, but the CRC and+ // byte layout are what can break; 600 nodes span many buffer refills+ // of the BufWriter's partial-write path through CountingWriter.+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("graph.bin");+ index.save_to(&path).unwrap();+ assert_eq!(std::fs::read(&path).unwrap(), expected);+ let loaded = HnswIndex::load_from(&path).unwrap();+ assert_eq!(loaded.len(), index.len());+ let leftovers = std::fs::read_dir(dir.path()).unwrap().count();+ assert_eq!(leftovers, 1, "temp file left behind");+ }+#[test]fn generic_read_boundary_accepts_fragmented_backend() {let graph = FragmentedTestGraph {diff --git a/engine/crates/xerj-vector/tests/save_peak_memory.rs b/engine/crates/xerj-vector/tests/save_peak_memory.rsnew file mode 100644index 000000000..b04d8cb9d--- /dev/null+++ b/engine/crates/xerj-vector/tests/save_peak_memory.rs@@ -0,0 +1,72 @@+//! #2427: saving an HNSW graph must not hold a copy of the whole file in+//! memory. Before the fix `save_to` encoded into a `Vec` that grew by+//! doubling, so every flush (including the memory-pressure drain) added one+//! to two graph sizes to RSS.++use std::alloc::{GlobalAlloc, Layout, System};+use std::sync::atomic::{AtomicIsize, Ordering};++use xerj_vector::{DistanceMetric, HnswIndex, HnswParams};++struct Counting;++static LIVE: AtomicIsize = AtomicIsize::new(0);+static PEAK: AtomicIsize = AtomicIsize::new(0);++unsafe impl GlobalAlloc for Counting {+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {+ let p = unsafe { System.alloc(layout) };+ if !p.is_null() {+ let now =+ LIVE.fetch_add(layout.size() as isize, Ordering::Relaxed) + layout.size() as isize;+ PEAK.fetch_max(now, Ordering::Relaxed);+ }+ p+ }++ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {+ unsafe { System.dealloc(ptr, layout) };+ LIVE.fetch_sub(layout.size() as isize, Ordering::Relaxed);+ }++ unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {+ let p = unsafe { System.realloc(ptr, layout, new_size) };+ if !p.is_null() {+ let delta = new_size as isize - layout.size() as isize;+ let now = LIVE.fetch_add(delta, Ordering::Relaxed) + delta;+ PEAK.fetch_max(now, Ordering::Relaxed);+ }+ p+ }+}++#[global_allocator]+static GLOBAL: Counting = Counting;++#[test]+fn save_to_does_not_buffer_the_whole_graph() {+ let dim = 128;+ let index = HnswIndex::new(HnswParams::new(dim, DistanceMetric::Cosine));+ for id in 0..12_000u64 {+ let v: Vec<f32> = (0..dim as u64)+ .map(|d| ((id.wrapping_mul(2654435761) ^ (d * 40503)) % 1009) as f32)+ .collect();+ index.insert(id, v).unwrap();+ }+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("graph.bin");++ let base = LIVE.load(Ordering::Relaxed);+ PEAK.store(base, Ordering::Relaxed);+ index.save_to(&path).unwrap();+ let extra = PEAK.load(Ordering::Relaxed) - base;++ let file_len = std::fs::metadata(&path).unwrap().len() as isize;+ assert!(file_len > 6 << 20, "graph too small to tell: {file_len} B");+ // Streaming needs a fixed ~1 MiB write buffer; the old encoder needed+ // at least the file size (and up to twice it while the Vec doubled).+ assert!(+ extra < file_len / 4,+ "save_to allocated {extra} B transient for a {file_len} B graph"+ );+}