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(memtable/aggs): read-lock sorted match_all + cache doc_count + structural agg probe
xerj-org12ecf16a7071
diff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rsindex bf193ef00..adcd75b7c 100644--- a/engine/crates/xerj-engine/src/fast_aggs.rs+++ b/engine/crates/xerj-engine/src/fast_aggs.rs@@ -408,13 +408,13 @@ impl Index {// can observe meta fields; Arc-shared otherwise. Conservative// substring probe — false positives merely fall back to the exact// legacy build.- let needs_owned_mem = {- let raw = aggs_def.to_string();- raw.contains("top_hits")- || raw.contains("\"_id\"")- || raw.contains("\"_index\"")- || raw.contains("\"_seq_no\"")- };+ // Structural walk instead of `aggs_def.to_string()` + substring+ // search — the serialize-the-whole-tree probe ran on every fast-agg+ // request. Semantics are preserved exactly: `top_hits` matches as a+ // substring of any key/string (a `top_hits` agg key, or a nested+ // one), while the meta fields match the serialized `"_id"` / `"_index"`+ // / `"_seq_no"` tokens, i.e. an exact object key or string value.+ let needs_owned_mem = agg_tree_mentions_meta(aggs_def);let ctx = FastCtx {idx: self,@@ -2830,6 +2830,28 @@ fn compile_top_pred(filter: &Value) -> Option<Pred> {compile_pred(filter)}+/// Structural equivalent of the old+/// `aggs_def.to_string().contains("top_hits" | "\"_id\"" | ...)` probe.+/// Returns true when the agg tree references a meta field, meaning the+/// memtable docs must be materialised OWNED (with `_id`/`_index`/`_seq_no`+/// injected) rather than Arc-shared. Conservative: a false positive only+/// costs an extra clone, never correctness — so this deliberately mirrors+/// the substring semantics (`top_hits` anywhere; the meta fields as exact+/// key/string tokens, i.e. the serialized quoted form).+fn agg_tree_mentions_meta(v: &Value) -> bool {+ fn is_meta(s: &str) -> bool {+ s.contains("top_hits") || s == "_id" || s == "_index" || s == "_seq_no"+ }+ match v {+ Value::Object(m) => m+ .iter()+ .any(|(k, val)| is_meta(k) || agg_tree_mentions_meta(val)),+ Value::Array(a) => a.iter().any(agg_tree_mentions_meta),+ Value::String(s) => is_meta(s),+ _ => false,+ }+}+/// Compile the (single-clause) filter queries `doc_matches_filter` supports/// into a columnar predicate. Anything not exactly mirrored → `None`.fn compile_pred(filter: &Value) -> Option<Pred> {diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 51880cfd0..09b9c8603 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -4798,9 +4798,17 @@ impl Index {// via segment readers below. This is a known v0.1 limitation: flushed// docs are not yet searchable via the FTS segment reader for match// queries, but MatchAll and doc-scan queries do work via stored segments.+ // Step 4: fan out the 16-shard `doc_count()` sum ONCE per query and+ // reuse it at the mem_snapshot gate and the size=0 total-synthesis+ // arms below, instead of re-locking all 16 shards 3-4×. The memtable+ // is written concurrently, so this is a point-in-time snapshot — every+ // consumer here either feeds a total that a later `live_doc_count()`+ // overwrites (match_all) or gates the empty-memtable fast path, both+ // tolerant of a one-instant-stale count.+ let mem_doc_count = self.memtable.doc_count();let mem_snapshot = {let mem = &*self.memtable;- if mem.doc_count() == 0 {+ if mem_doc_count == 0 {MemSnapshot::Empty} else if matches!(query, QueryNode::MatchAll)&& size == 0@@ -5177,7 +5185,7 @@ impl Index {// `mem_count` again we double-count (visible as the 40 vs 20// failure on `test_terms_agg_bucket_counts` under M5.1).if is_match_all && size == 0 && request.aggs.is_none() {- let mem_count = self.memtable.doc_count() as u64;+ let mem_count = mem_doc_count as u64;total_count = total_count.saturating_add(mem_count);}@@ -5258,10 +5266,7 @@ impl Index {// (later overwritten with the delete-aware live count).None => {let seg_docs: u64 = snap.segments.iter().map(|m| m.doc_count).sum();- let mem_count = {- let mem = &*self.memtable;- mem.doc_count() as u64- };+ let mem_count = mem_doc_count as u64;total_count = seg_docs + mem_count;}}diff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rsindex fa48a4467..0ac46b0ab 100644--- a/engine/crates/xerj-engine/src/memtable.rs+++ b/engine/crates/xerj-engine/src/memtable.rs@@ -196,7 +196,16 @@ pub struct DocValues {/// `FtsMemtable::sort_candidates_cached`. Keyed/// `"{field}\u{1}{asc|desc}"`. Reset with the rest of `DocValues`/// at drain; cleared by `remove_at` (positions shift).- pub sort_cand_cache: FxHashMap<String, SortCandCache>,+ ///+ /// Step 4: behind a `Mutex` so the sorted-`match_all` fast path can+ /// extend the cache under the shard's READ lock instead of forcing a+ /// write lock across all 16 shards (which serialised every sorted read+ /// against concurrent ingest — the residual `match_all` read-under-write+ /// p99 term). The shard write lock is exclusive, so `push_field` /+ /// `remove_at` mutate the columns with no concurrent reader; two+ /// concurrent readers under the shard read lock serialise briefly on+ /// this leaf mutex while one folds in the new docs.+ pub sort_cand_cache: parking_lot::Mutex<FxHashMap<String, SortCandCache>>,}/// State of one incremental per-shard sorted-candidate extraction: the@@ -384,7 +393,7 @@ impl DocValues {// Positions shift left — every cached sorted-candidate pool's// `(key, docs-index)` pairs go stale. Deletes are rare on the// hot ingest path; a wholesale clear is simplest-correct.- self.sort_cand_cache.clear();+ self.sort_cand_cache.lock().clear();for col in self.numeric.values_mut() {if doc_index < col.len() {col.remove(doc_index);@@ -592,7 +601,9 @@ impl ShardedFtsMemtable {let mut cands: Vec<(f64, String)> = Vec::new();let mut missing: Vec<String> = Vec::new();for s in &self.shards {- let mut g = s.write();+ // Step 4: READ lock — sort_candidates_cached now folds new docs+ // into the interior-mutable cache without an exclusive shard lock.+ let g = s.read();let n = g.doc_count();total += n as u64;if n == 0 {@@ -2299,7 +2310,7 @@ impl FtsMemtable {/// field — poisoned until the next drain resets the memtable, so the/// fallback decision itself is O(1) per query, not a re-walk).pub fn sort_candidates_cached(- &mut self,+ &self,field: &str,desc: bool,cap: usize,@@ -2315,9 +2326,9 @@ impl FtsMemtable {} else {format!("{field}\u{1}a")};- let entry = self- .doc_values- .sort_cand_cache+ // Step 4: interior-mutable cache — held under the shard READ lock.+ let mut cache = self.doc_values.sort_cand_cache.lock();+ let entry = cache.entry(key).or_insert_with(|| SortCandCache {seen_docs: 0,