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
fix(engine): share one parsed _source between storage and FTS memtables (#2734)
xerj-org8ca0645bec74
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 025bb1637..a22c78229 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -80,6 +80,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0destination. `_source:false` is refused with ES's sentence, and a `script`body is refused before any work instead of silently copying theuntransformed document (this build has no reindex script context).+- A document written through the per-document path (single-doc index and the+ `_bulk` per-document path) is now held once in memory until the next flush+ instead of twice: the storage memtable and the full-text memtable share one+ parsed `_source` rather than each keeping its own deep copy. On a 1 GB+ `_bulk` load a late heap profile had the two copies at ~470 MB of ~1.75 GB+ in use (#2427).+- Publishing a flushed or merged segment no longer decompresses its wholestored section when the result cannot be kept. The publish-time warm nowsizes the stored slices from the section framing first and skips the warmdiff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex f83ffb1ef..01f8a2360 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -274,6 +274,45 @@ mod merge_long_effort_tests {}}+#[cfg(test)]+mod shared_memtable_source_tests {+ use super::*;+ use serde_json::json;++ /// #2427: a document written through the per-document path used to be+ /// deep-copied twice and both copies kept until the next flush, once in+ /// the storage memtable and once in the FTS memtable. A late-run heap+ /// profile of a 1 GB `_bulk` load had these two copies at ~470 MB of+ /// ~1.75 GB in use. Both memtables now hold the same `Arc`.+ #[tokio::test]+ async fn per_doc_write_keeps_one_parsed_source_for_both_memtables_2427() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ let engine = crate::Engine::new(config).unwrap();+ let mut schema = Schema::empty();+ schema+ .add_field(FieldConfig::new("body", FieldType::Text))+ .unwrap();+ engine.create_index("shared-source-2427", schema).unwrap();+ let idx = engine.get_index("shared-source-2427").unwrap();+ idx.abort_background_tasks();+ idx.index_document(Some("one".into()), json!({"body": "alpha beta"}))+ .await+ .unwrap();++ let fts = idx.memtable.get_doc_source_arc("one").unwrap();+ assert_eq!(fts["body"], "alpha beta");+ // Owners: the FTS memtable, the storage memtable and `fts` itself.+ // A private FTS copy would leave only two.+ assert_eq!(+ Arc::strong_count(&fts),+ 3,+ "the FTS memtable must share the storage memtable's source, not deep-copy it"+ );+ }+}+#[cfg(test)]mod collection_publication_fail_closed_tests {use super::*;@@ -12155,7 +12194,11 @@ impl Index {self.collection_publication.handoff_to_readers().await;return Err(e.into());}- let seq_no = match self.store.index(&doc_id, source.clone()) {+ // One parsed tree, shared by the storage memtable and the FTS+ // memtable below; each used to hold its own deep copy until the next+ // flush (#2427).+ let source = Arc::new(source);+ let seq_no = match self.store.index_shared(&doc_id, Arc::clone(&source)) {Ok(seq_no) => seq_no,Err(e) => {collection_publication.cancel();@@ -12179,7 +12222,12 @@ impl Index {{let mem = &*self.memtable;mem.remove(&doc_id);- mem.insert(doc_id.clone(), &source, &schema_guard.schema, seq_no);+ mem.insert_shared(+ doc_id.clone(),+ Arc::clone(&source),+ &schema_guard.schema,+ seq_no,+ );}drop(schema_guard);#[cfg(test)]diff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rsindex e6ab9521b..179d53803 100644--- a/engine/crates/xerj-engine/src/memtable.rs+++ b/engine/crates/xerj-engine/src/memtable.rs@@ -2026,13 +2026,20 @@ impl ShardedFtsMemtable {/// Drop-in replacement for the old single-memtable `insert` used by/// the `IndexStore::index()` single-doc path.pub fn insert(&self, doc_id: String, source: &Value, schema: &Schema, seq_no: u64) {+ self.insert_shared(doc_id, Arc::new(source.clone()), schema, seq_no);+ }++ /// [`Self::insert`] for a source the caller already holds in an `Arc`.+ /// The memtable keeps that `Arc` rather than a deep copy, so a document+ /// the storage memtable also holds is in memory once (#2427).+ pub fn insert_shared(&self, doc_id: String, source: Arc<Value>, schema: &Schema, seq_no: u64) {let s = self.shard_for_dynamic(&doc_id);// New writes always land in the ACTIVE generation — frozen ones are// immutable snapshots held for an in-flight flush (#1015).self.shards[s].write().active- .insert(doc_id, source, schema, seq_no);+ .insert_shared(doc_id, source, schema, seq_no);}/// Drop-in for `insert_pretokenized_with_seq` — picks a shard by@@ -3121,6 +3128,18 @@ impl FtsMemtable {/// Insert a document into the memtable, indexing all text fields.pub fn insert(&mut self, doc_id: String, source: &Value, schema: &Schema, seq_no: u64) {+ self.insert_shared(doc_id, Arc::new(source.clone()), schema, seq_no);+ }++ /// [`Self::insert`] for a source the caller already holds in an `Arc`:+ /// the entry stores that `Arc` instead of a deep copy (#2427).+ pub fn insert_shared(+ &mut self,+ doc_id: String,+ source: Arc<Value>,+ schema: &Schema,+ seq_no: u64,+ ) {// Prefer a "default" analyzer if one was registered via custom settings// (e.g. with synonym expansion), otherwise fall back to "standard".let analyzer = self@@ -3129,13 +3148,13 @@ impl FtsMemtable {.or_else(|| self.registry.get_analyzer("standard")).expect("standard analyzer always present");- let analyzed = analyze_doc(source, schema, &analyzer);+ let analyzed = analyze_doc(&source, schema, &analyzer);// See `insert_pretokenized` for sizing rationale.let raw_size = source.to_string().len() + doc_id.len();let size = raw_size * 3 + 64;- self.insert_analyzed(seq_no, doc_id, Arc::new(source.clone()), &analyzed, size);+ self.insert_analyzed(seq_no, doc_id, source, &analyzed, size);}/// Back half of [`insert`] — everything that MUST run under thediff --git a/engine/crates/xerj-storage/src/index_store.rs b/engine/crates/xerj-storage/src/index_store.rsindex 6aff9b6ef..984f68864 100644--- a/engine/crates/xerj-storage/src/index_store.rs+++ b/engine/crates/xerj-storage/src/index_store.rs@@ -2029,10 +2029,24 @@ impl IndexStore {/// Index a document. Returns the assigned sequence number.pub fn index(&self, doc_id: impl Into<String>, source: serde_json::Value) -> Result<SeqNo> {+ self.index_shared(doc_id, std::sync::Arc::new(source))+ }++ /// Index a document whose parsed source the caller also keeps.+ ///+ /// The storage memtable holds `source` until the next flush. Taking an+ /// `Arc` lets a caller that also puts the document in the engine's FTS+ /// memtable share one parsed tree between the two, instead of each+ /// holding its own deep copy until the flush (#2427).+ pub fn index_shared(+ &self,+ doc_id: impl Into<String>,+ source: std::sync::Arc<serde_json::Value>,+ ) -> Result<SeqNo> {let doc_id = doc_id.into();let entry = WalEntry::Index {doc_id: doc_id.clone(),- source: source.clone(),+ source: (*source).clone(),};let seq_no = {@@ -2051,7 +2065,7 @@ impl IndexStore {mem.push(MemEntry {seq_no,doc_id,- source: Some(std::sync::Arc::new(source)),+ source: Some(source),source_bytes,charge,});