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(search): cache the per-segment FTS reader instead of rebuilding it per query
xerj-orgf953b6ef9d66
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 2d635a515..7db6cca12 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -5016,6 +5016,29 @@ pub struct Index {/// Budgeted like `stored_slices_cache`; entries evicted by id at the/// merge-completion site. Segments are immutable → no invalidation.decoded_stored_cache: Arc<dashmap::DashMap<String, Resident<Vec<u8>>>>,+ /// Per-(segment, field-set) cache of an opened `FtsIndexReader`.+ ///+ /// `FtsIndexReader::open` was called INSIDE the per-segment loop of+ /// `search_bounded` on every query, and it is not cheap: it performs TWO+ /// zstd decompressions per field — the whole `.post` blob (`ZPS1`) and the+ /// whole `.meta` flat array (`ZFM4`) — into owned `Vec`s, because a+ /// compressed blob cannot be mmap'd. Measured on one real production field+ /// (`body`, 17.0 MB `.post` -> 25.3 MB, 2.8 MB `.meta` -> 15.8 MB): ~50 ms+ /// and ~41 MB per (segment, field), rebuilt and thrown away every query.+ /// The comment on `PostData` ("open allocates almost nothing per segment")+ /// describes only the uncompressed/mmap path, which modern segments never+ /// take.+ ///+ /// Segments are immutable, so this needs no invalidation — the same+ /// argument every other cache here rests on. Entries are evicted by id at+ /// the merge-completion site and the payload is budget-charged, so a large+ /// corpus degrades to today's open-per-query rather than growing without+ /// bound.+ ///+ /// The key includes the field set because `open` loads exactly the fields+ /// it is asked for; a reader opened for a narrower set must never satisfy+ /// a query needing a wider one.+ fts_reader_cache: Arc<dashmap::DashMap<String, Resident<Arc<FtsIndexReader>>>>,/// Per-(segment, query-shape) match-count cache for the/// `try_shortcut_count` Bool intersection arm. The fused columnar/// walk is O(anchor-predicate matches) per segment PER QUERY — for a@@ -5422,6 +5445,7 @@ impl Index {stored_value_load_semaphore: Arc::new(Semaphore::new(4)),stored_slices_cache: Arc::new(dashmap::DashMap::new()),decoded_stored_cache: Arc::new(dashmap::DashMap::new()),+ fts_reader_cache: Arc::new(dashmap::DashMap::new()),shortcut_count_cache: Arc::new(dashmap::DashMap::new()),ghost_positions_cache: Arc::new(dashmap::DashMap::new()),regexp_expand_cache: Arc::new(dashmap::DashMap::new()),@@ -5768,6 +5792,7 @@ impl Index {stored_value_load_semaphore: Arc::new(Semaphore::new(4)),stored_slices_cache: Arc::new(dashmap::DashMap::new()),decoded_stored_cache: Arc::new(dashmap::DashMap::new()),+ fts_reader_cache: Arc::new(dashmap::DashMap::new()),shortcut_count_cache: Arc::new(dashmap::DashMap::new()),ghost_positions_cache: Arc::new(dashmap::DashMap::new()),regexp_expand_cache: Arc::new(dashmap::DashMap::new()),@@ -14353,13 +14378,13 @@ impl Index {let mut fts_deadline_tripped = false;let t_fts = std::time::Instant::now();let reader_opt = if needs_fts {- FtsIndexReader::open(&fts_dir, &seg_id, &field_refs).ok()+ self.fts_reader_for(&fts_dir, &seg_id, &field_refs)} else {None};dbg_fts_ms += t_fts.elapsed().as_millis() as u64;if let Some(reader) = reader_opt {- let reader = Arc::new(reader);+ let reader = Arc::clone(&*reader);// Arm the cooperative deadline (RC4 blocker 12): the// searcher's multi-term expansions (prefix / wildcard /// fuzzy term-dictionary walks) are otherwise@@ -14540,7 +14565,9 @@ impl Index {// candidate (rare). The exact live count above used// `dead_matches` over the FULL set and is untouched.let mut seg_hits = seg_hits;- if deletes_present && fts_cap != usize::MAX && seg_total > fts_cap as u64+ if deletes_present+ && fts_cap != usize::MAX+ && seg_total > fts_cap as u64{let dead_in_top = ghost_bm.as_deref()@@ -14794,30 +14821,31 @@ impl Index {// set). Shared by the in-walk 2×cap eager// trim and the end-of-run trim so admission// and final ordering always agree.- let trim_to_cap = |hits: Vec<Hit>| -> (Vec<Hit>, Option<f32>) {- let mut decorated: Vec<(u64, Hit)> = hits- .into_iter()- .map(|h| {- (- self.lookup_seq_no(&h.id)- .unwrap_or(u64::MAX),- h,- )- })- .collect();- decorated.sort_by(|a, b| {- b.1.score- .partial_cmp(&a.1.score)- .unwrap_or(std::cmp::Ordering::Equal)- .then_with(|| a.0.cmp(&b.0))- .then_with(|| a.1.id.cmp(&b.1.id))- });- decorated.truncate(materialisation_limit);- let worst = decorated.last().map(|(_, h)| h.score);- let kept =- decorated.into_iter().map(|(_, h)| h).collect();- (kept, worst)- };+ let trim_to_cap =+ |hits: Vec<Hit>| -> (Vec<Hit>, Option<f32>) {+ let mut decorated: Vec<(u64, Hit)> = hits+ .into_iter()+ .map(|h| {+ (+ self.lookup_seq_no(&h.id)+ .unwrap_or(u64::MAX),+ h,+ )+ })+ .collect();+ decorated.sort_by(|a, b| {+ b.1.score+ .partial_cmp(&a.1.score)+ .unwrap_or(std::cmp::Ordering::Equal)+ .then_with(|| a.0.cmp(&b.0))+ .then_with(|| a.1.id.cmp(&b.1.id))+ });+ decorated.truncate(materialisation_limit);+ let worst = decorated.last().map(|(_, h)| h.score);+ let kept =+ decorated.into_iter().map(|(_, h)| h).collect();+ (kept, worst)+ };for sh in &seg_hits {// `seg_hits` descends by score, so once// a hit's score is STRICTLY below the@@ -18604,6 +18632,10 @@ impl Index {self.row_seq_cache.remove(segment_id);self.stored_slices_cache.remove(segment_id);self.decoded_stored_cache.remove(segment_id);+ // Keyed by "<segment_id>\u{1}<field-set>", so evict by prefix.+ let fts_prefix = format!("{segment_id}\u{1}");+ self.fts_reader_cache+ .retain(|key, _| !key.starts_with(&fts_prefix));let shadow_prefix = format!("{segment_id}\u{1}");self.sort_shadow_cache.retain(|key, _| !key.starts_with(&shadow_prefix));@@ -18633,6 +18665,48 @@ impl Index {}}+ /// Open a segment's FTS side-cars, reusing a cached reader when one exists.+ ///+ /// This is the read-side of `fts_reader_cache`. See that field for why the+ /// open is expensive (two zstd decompressions per field, ~50 ms / ~41 MB on+ /// a real production field) and why caching is sound (segments are+ /// immutable).+ ///+ /// Returns `None` exactly where the previous inline+ /// `FtsIndexReader::open(..).ok()` returned `None`, so a missing or+ /// unreadable side-car still falls through to the stored-doc scan rather+ /// than failing the query.+ fn fts_reader_for(+ &self,+ fts_dir: &std::path::Path,+ segment_id: &str,+ fields: &[&str],+ ) -> Option<Resident<Arc<FtsIndexReader>>> {+ // The field set is part of the identity: `open` loads only the fields+ // it is given, so a reader opened for a narrower set must never serve a+ // query that needs a wider one. Sort so that permutations of the same+ // set share one entry.+ let mut sorted: Vec<&str> = fields.to_vec();+ sorted.sort_unstable();+ sorted.dedup();+ let key = format!("{segment_id}\u{1}{}", sorted.join("\u{2}"));++ if let Some(hit) = self.fts_reader_cache.get(&key) {+ return Some(Arc::clone(hit.value()));+ }++ let reader = Arc::new(FtsIndexReader::open(fts_dir, segment_id, fields).ok()?);+ let bytes = reader.retained_bytes();+ Some(self.publish_current(+ &self.fts_reader_cache,+ segment_id,+ key,+ SegmentCacheCategory::FtsReader,+ bytes,+ reader,+ ))+ }+fn dv_columns_for(&self,segments_dir: &std::path::Path,diff --git a/engine/crates/xerj-engine/src/ingest_memory.rs b/engine/crates/xerj-engine/src/ingest_memory.rsindex 33461c8dd..ea58c6374 100644--- a/engine/crates/xerj-engine/src/ingest_memory.rs+++ b/engine/crates/xerj-engine/src/ingest_memory.rs@@ -120,10 +120,11 @@ pub enum Category {CacheIdPositions,CacheRowSequences,CacheDecodedStored,+ CacheFtsReader,}impl Category {- pub const ALL: [Self; 21] = [+ pub const ALL: [Self; 22] = [Self::HttpBody,Self::HttpRewriteBuffer,Self::RawSource,@@ -145,6 +146,7 @@ impl Category {Self::CacheIdPositions,Self::CacheRowSequences,Self::CacheDecodedStored,+ Self::CacheFtsReader,];const COUNT: usize = Self::ALL.len();diff --git a/engine/crates/xerj-engine/src/segment_cache_budget.rs b/engine/crates/xerj-engine/src/segment_cache_budget.rsindex d9caeb97a..4d938872c 100644--- a/engine/crates/xerj-engine/src/segment_cache_budget.rs+++ b/engine/crates/xerj-engine/src/segment_cache_budget.rs@@ -10,7 +10,7 @@ use std::sync::Arc;use crate::ingest_memory::{Category, Retained};-pub const CATEGORY_COUNT: usize = 7;+pub const CATEGORY_COUNT: usize = 8;#[derive(Clone, Copy, Debug, Eq, PartialEq)]#[repr(usize)]@@ -22,6 +22,8 @@ pub enum SegmentCacheCategory {IdPositions,RowSequences,DecodedStored,+ /// Decompressed `.post` + `.meta` blobs behind a cached `FtsIndexReader`.+ FtsReader,}impl SegmentCacheCategory {@@ -33,6 +35,7 @@ impl SegmentCacheCategory {Self::IdPositions,Self::RowSequences,Self::DecodedStored,+ Self::FtsReader,];fn trace_category(self) -> Category {@@ -44,6 +47,7 @@ impl SegmentCacheCategory {Self::IdPositions => Category::CacheIdPositions,Self::RowSequences => Category::CacheRowSequences,Self::DecodedStored => Category::CacheDecodedStored,+ Self::FtsReader => Category::CacheFtsReader,}}}diff --git a/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs b/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rsindex 369293dae..1919b83fc 100644--- a/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs+++ b/engine/crates/xerj-engine/tests/search_bounded_under_ghosts.rs@@ -224,7 +224,10 @@ async fn page_reaching_into_truncated_ghost_segment_is_exact() {// Ground truth: full materialisation.let full = idx.search(&match_body(500, false)).await.unwrap();- assert_eq!(full.total.value, expected_total, "live total wrong under ghosts");+ assert_eq!(+ full.total.value, expected_total,+ "live total wrong under ghosts"+ );// Pages that reach well into the weak segment must equal the ground-truth// prefix — this is the assertion the re-expand exists to satisfy.@@ -232,7 +235,10 @@ async fn page_reaching_into_truncated_ghost_segment_is_exact() {let mut truth = page(&full.hits);truth.truncate(size);let r = idx.search(&match_body(size, false)).await.unwrap();- assert_eq!(r.total.value, expected_total, "size:{size} total drifted under ghosts");+ assert_eq!(+ r.total.value, expected_total,+ "size:{size} total drifted under ghosts"+ );assert_eq!(page(&r.hits),truth,@@ -315,12 +321,23 @@ async fn large_single_segment_with_top_ghost_returns_exact_order() {.unwrap();let full = idx.search(&match_body(500, false)).await.unwrap();- assert_eq!(full.total.value, (n as u64) - 1, "live total wrong under a top ghost");+ assert_eq!(+ full.total.value,+ (n as u64) - 1,+ "live total wrong under a top ghost"+ );for size in [10usize, 50, 200] {let mut truth = page(&full.hits);truth.truncate(size);let r = idx.search(&match_body(size, false)).await.unwrap();- assert_eq!(page(&r.hits), truth, "size:{size} order wrong with a top-scoring ghost");- assert!(r.hits.iter().all(|h| h.id != "weak0000"), "deleted top-scorer leaked");+ assert_eq!(+ page(&r.hits),+ truth,+ "size:{size} order wrong with a top-scoring ghost"+ );+ assert!(+ r.hits.iter().all(|h| h.id != "weak0000"),+ "deleted top-scorer leaked"+ );}}diff --git a/engine/crates/xerj-fts/src/index.rs b/engine/crates/xerj-fts/src/index.rsindex ea6ec7e2d..3254c929c 100644--- a/engine/crates/xerj-fts/src/index.rs+++ b/engine/crates/xerj-fts/src/index.rs@@ -1198,6 +1198,37 @@ impl FtsIndexReader {}}+ /// Heap bytes this reader retains, for the segment-cache budget.+ ///+ /// Only *owned* allocations are counted. `Mmap` backings are deliberately+ /// excluded: they are page-cache pages the kernel can reclaim, not heap the+ /// process is responsible for, and charging them would make the budget+ /// refuse to cache readers that cost almost nothing to hold.+ ///+ /// The dominant terms are the two decompressed blobs. A compressed `.post`+ /// (`ZPS1`) or `.meta` (`ZFM4`) cannot be mmap'd — it must be inflated into+ /// an owned `Vec` at open time — so on a modern segment this is essentially+ /// `post_uncompressed + meta_uncompressed`.+ pub fn retained_bytes(&self) -> u64 {+ let mut total: u64 = 0;+ for (name, f) in &self.fields {+ total += name.len() as u64;+ if let PostData::Owned(v) = &f.post_data {+ total += v.len() as u64;+ }+ if let FstData::Owned(m) = &f.fst {+ total += m.as_fst().as_bytes().len() as u64;+ }+ total += f.meta.flat_records.len() as u64;+ // `norms` is Vec<(u32, u16)>, which pads to 8 bytes per element.+ total += (f.norms.len() as u64) * 8;+ // Legacy ZFM1/ZFM2 keep per-term metadata in a HashMap instead of+ // the flat array; approximate it rather than walking every entry.+ total += (f.meta.terms.len() as u64) * 64;+ }+ total+ }+/// Look up a term in a field.////// Returns `Some(TermPostings)` if the term exists, `None` otherwise.