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(read-under-write): port ae86093 — match_all-only implicit @timestamp sort, bounded memtable sort candidates, bool count cache, fg/bg pool split
xerj-org979bd39db5bc
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 7b2636131..46b556be2 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -4472,12 +4472,45 @@ pub async fn search(}).unwrap_or((None, "desc".to_string(), false));if let Some(f) = sort_field {- // Apply the index sort when no sort was requested, OR — for an- // EXPLICITLY declared index sort — when the only sort key is the- // implicit `_doc` order (ES returns docs in index-sort order for- // a `sort: _doc` request against an index-sorted index).- let apply = body.sort.is_none()- || (explicit && body.sort.as_ref().map(is_lone_doc_sort).unwrap_or(false));+ // Apply the index sort ONLY for an EXPLICITLY declared+ // `index.sort` (settings), when no sort was requested or the+ // only sort key is the implicit `_doc` order (ES returns docs+ // in index-sort order for a `sort: _doc` request against an+ // index-sorted index).+ //+ // The auto-@timestamp heuristic (any index that merely MAPS a+ // `@timestamp` date field) is no longer applied: real ES does+ // NOT implicitly sort query results just because @timestamp is+ // mapped (index.sort is a physical layout setting, auto-set+ // only for logsdb/time-series modes), and the injected sort+ // routed EVERY sortless query on such indexes through the+ // global top-N heap — an O(total-docs) walk of every segment+ // per request. Live-verified as the dominant cost of the+ // read-under-write collapse: an LLM-telemetry corpus (maps+ // @timestamp) saw sortless term/match_all size=10 queries walk+ // 1.5 M docs (~2-7 s each, `walked=1500002 admitted=250252+ // allhits_cap=false`) while the same query with an explicit+ // `sort: _doc` took 45 ms.+ // For the implicit auto-@timestamp hint, only match_all-shaped+ // queries get the injected sort: that is the query shape the ES+ // conformance contract observes (search/380_sort_segments_on_+ // timestamp.yml), and the engine serves it via the bounded+ // sorted-DV candidates path (O(from+size) per segment).+ // Filtered queries (term/range/bool) skip the injection — in+ // real ES the physical index sort doesn't impose a query-time+ // global sort on them either, and routing them through the+ // top-N heap costs a full O(total-docs) walk per request.+ let implicit_ok = body.query.is_none()+ || body+ .query+ .as_ref()+ .and_then(|q| q.as_object())+ .map(|o| o.len() == 1 && o.contains_key("match_all"))+ .unwrap_or(false);+ let apply = (explicit || implicit_ok)+ && (body.sort.is_none()+ || (explicit+ && body.sort.as_ref().map(is_lone_doc_sort).unwrap_or(false)));if apply {body.sort = Some(json!([{ f: { "order": sort_order } }]));}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 47db80c04..71eb931df 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -397,6 +397,16 @@ pub struct Index {/// merge-completion site. Segments are immutable → no invalidation.decoded_stored_cache: Arc<dashmap::DashMap<String, Arc<Vec<u8>>>>,decoded_stored_cache_bytes: Arc<AtomicU64>,+ /// 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+ /// dashboard-style fixed bool filter under a bulk writer (query cache+ /// useless: every batch bumps `dataset_version`) that was ~0.6-1 s of+ /// re-counting per request at 1.5 M docs. Segments are immutable, so+ /// a (segment_id, canonical-query-json) key never goes stale; bounded+ /// by wholesale clear at `SHORTCUT_COUNT_CACHE_MAX` since query+ /// shapes are client-supplied.+ shortcut_count_cache: Arc<dashmap::DashMap<(String, String), u64>>,/// Regexp term-dictionary expansion cache — keyed by/// `(segment_id, field, pattern)`, holds the exact union doc count/// plus the first `REGEXP_EXPANSION_POS_CAP` matching doc positions@@ -577,6 +587,7 @@ impl Index {stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),decoded_stored_cache: Arc::new(dashmap::DashMap::new()),decoded_stored_cache_bytes: Arc::new(AtomicU64::new(0)),+ shortcut_count_cache: Arc::new(dashmap::DashMap::new()),regexp_expand_cache: Arc::new(dashmap::DashMap::new()),fast_date_cache: Arc::new(dashmap::DashMap::new()),fast_date_sorted_cache: Arc::new(dashmap::DashMap::new()),@@ -746,6 +757,7 @@ impl Index {stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),decoded_stored_cache: Arc::new(dashmap::DashMap::new()),decoded_stored_cache_bytes: Arc::new(AtomicU64::new(0)),+ shortcut_count_cache: Arc::new(dashmap::DashMap::new()),regexp_expand_cache: Arc::new(dashmap::DashMap::new()),fast_date_cache: Arc::new(dashmap::DashMap::new()),fast_date_sorted_cache: Arc::new(dashmap::DashMap::new()),@@ -4360,8 +4372,37 @@ impl Index {// only ever admit the first `materialisation_limit` ids,// so clone just those and carry the remainder as a count.if sort_topk.is_some() {- let ids: Vec<String> = mem.all_doc_ids();- MemSnapshot::AllDocIds(ids, 0)+ // Bounded sorted candidates for the common shape+ // (single default-flavour field sort, no cursor):+ // columnar per-shard top-cap extraction instead of+ // offering EVERY buffered doc to the heap.+ let bounded: Option<(Vec<String>, u64)> = (|| {+ use xerj_query::sort::{SortMissing, SortMode, SortOrder};+ let topk = sort_topk.as_ref()?;+ if topk.after.is_some() || request.sort.len() != 1 {+ return None;+ }+ let sf = &request.sort[0];+ if sf.is_score()+ || sf.is_doc_order()+ || sf.mode != SortMode::default()+ || sf.missing != SortMissing::default()+ {+ return None;+ }+ mem.sort_candidates_numeric(+ &sf.field,+ sf.order == SortOrder::Desc,+ materialisation_limit,+ )+ })();+ match bounded {+ Some((ids, total)) => {+ let extra = total.saturating_sub(ids.len() as u64);+ MemSnapshot::AllDocIds(ids, extra)+ }+ None => MemSnapshot::AllDocIds(mem.all_doc_ids(), 0),+ }} else {let (ids, total) = mem.doc_ids_bounded(materialisation_limit);let extra = total.saturating_sub(ids.len() as u64);@@ -4440,6 +4481,13 @@ impl Index {};phase_marks.push(("mem_snapshot", phase_t0.elapsed().as_millis() as u64));+ let dbg_mem_arm: &'static str = match &mem_snapshot {+ MemSnapshot::Empty => "empty",+ MemSnapshot::FtsHits(_) => "fts",+ MemSnapshot::AllDocIds(..) => "allids",+ MemSnapshot::DocValuesHits(_) => "dv",+ MemSnapshot::DocsForScan(_) => "scan",+ };match mem_snapshot {MemSnapshot::Empty => {}MemSnapshot::FtsHits(hits) => {@@ -4647,6 +4695,10 @@ impl Index {// agg-section below.let mut precomputed_aggs: Option<Value> = None;phase_marks.push(("mem_admit", phase_t0.elapsed().as_millis() as u64));+ let dbg_sort_topk = sort_topk.is_some();+ let dbg_mem_hits = all_hits.len();+ let dbg_mem_seen = seen_ids.len();+ let dbg_mem_total = total_count;if is_match_all && size == 0 && request.aggs.is_some() && request.min_score.is_none() {if let Some(aggs_def) = &request.aggs {let r_opt = self@@ -6116,7 +6168,7 @@ impl Index {index = self.name.as_str(),phases = %breakdown.join(" "),gates = %format!(- "needs_fts={} shortcut={:?} deletes={} ghosts={} total={} lim={} segs={} dec={}ms scan={}ms ftsopen={}ms walked={} admitted={} allhits_cap={}",+ "needs_fts={} shortcut={:?} deletes={} ghosts={} total={} lim={} segs={} dec={}ms scan={}ms ftsopen={}ms walked={} admitted={} allhits_cap={} memhits={} memseen={} memtotal={} memarm={} sorttopk={}",query_needs_fts,shortcut_count,deletes_present,@@ -6129,7 +6181,12 @@ impl Index {dbg_fts_ms,dbg_walked,dbg_admitted,- scan_hit_cap+ scan_hit_cap,+ dbg_mem_hits,+ dbg_mem_seen,+ dbg_mem_total,+ dbg_mem_arm,+ dbg_sort_topk),"slow search_inner phase breakdown");@@ -6930,10 +6987,21 @@ impl Index {let segments_dir = self.data_dir.join("segments");let mut seg_matches: u64 = 0;+ // Canonical query key for the per-segment count cache.+ let bool_cache_key: Option<String> = serde_json::to_string(query).ok();for meta in &snap.segments {if meta.doc_count == 0 {continue;}+ if let Some(k) = &bool_cache_key {+ if let Some(hit) = self+ .shortcut_count_cache+ .get(&(meta.id.clone(), k.clone()))+ {+ seg_matches = seg_matches.saturating_add(*hit.value());+ continue;+ }+ }let Some(cols) = self.dv_columns_for(&segments_dir, &meta.id) else {return None;};@@ -7073,6 +7141,13 @@ impl Index {sc += 1;}let _ = n_docs; // silence unused+ if let Some(k) = &bool_cache_key {+ if self.shortcut_count_cache.len() >= SHORTCUT_COUNT_CACHE_MAX {+ self.shortcut_count_cache.clear();+ }+ self.shortcut_count_cache+ .insert((meta.id.clone(), k.clone()), sc);+ }seg_matches = seg_matches.saturating_add(sc);}@@ -7546,8 +7621,18 @@ impl Index {if let Some(entry) = self.sort_shadow_cache.get(&key) {return entry.value().clone();}+ // A missing/unreadable dv sidecar is a TRANSIENT state (a segment can+ // become visible a beat before its sidecar read succeeds under heavy+ // flush churn) — return None WITHOUT caching so the next query+ // re-probes. Only a successfully-read sidecar whose column SHAPE is+ // ineligible gets a durable `None` (that never changes for an+ // immutable segment). Caching the transient miss permanently+ // disabled the bounded path for that segment: every subsequent+ // sorted read full-scanned it until a merge retired it.+ let Some(cols) = self.dv_columns_for(segments_dir, segment_id) else {+ return None;+ };let built: Option<Arc<Vec<(i64, u32)>>> = (|| {- let cols = self.dv_columns_for(segments_dir, segment_id)?;match cols.get(field) {Some(Column::Numeric(n)) => {if !n.null_bitmap.is_empty()@@ -8572,7 +8657,7 @@ async fn do_flush_shard(// Whole side-car build runs on the dedicated ingest pool so a// flush burst can't queue search/agg par_iters behind it on the// global rayon pool (read-under-write; see `crate::ingest_pool`).- crate::ingest_pool().install(|| {+ crate::background_pool().install(|| {// ── Doc-values side-car (always built) ────────────────────let t_dv = std::time::Instant::now();{@@ -8628,7 +8713,7 @@ async fn do_flush_shard(let t_finalize = std::time::Instant::now();// Segment encode + side-car build on the deprioritised ingest pool// (build_fts's inner install() is a same-pool no-op).- let meta = match crate::ingest_pool()+ let meta = match crate::background_pool().install(|| store.finalize_flush_with_publisher(storage_drained, build_fts))?{Some(m) => m,@@ -13147,6 +13232,9 @@ const STORED_SLICES_CACHE_BUDGET: u64 = 3 * 1024 * 1024 * 1024;/// query falls back to the per-query decompress (pre-cache behaviour).const DECODED_STORED_CACHE_BUDGET: u64 = 4 * 1024 * 1024 * 1024;+/// Entry cap for `shortcut_count_cache` (cleared wholesale when exceeded).+const SHORTCUT_COUNT_CACHE_MAX: usize = 65_536;+/// Normalize one `search_after` cursor value so it compares against the/// normalized `hit.sort` values `compute_sort_values` produces (date-shaped/// strings → epoch-ms / epoch-ns numbers). `fmt_hint` is the SortField'sdiff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rsindex 61bccb04d..defc7b07b 100644--- a/engine/crates/xerj-engine/src/lib.rs+++ b/engine/crates/xerj-engine/src/lib.rs@@ -54,19 +54,36 @@ pub(crate) fn ingest_pool() -> &'static rayon::ThreadPool {rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("xerj-ingest-{i}"))- // Deprioritise ingest CPU vs foreground reads. Flush/merge- // side-car builds saturate every core for seconds at a time;- // at equal priority a ~20 ms search waits behind them for- // hundreds of ms (measured p50 0.2-1.9 s under a bulk- // writer). nice(10) lets CFS schedule search threads ahead- // of background encode work; with no reads running the pool- // still gets every core, so writer-only throughput is- // unchanged.+ .build()+ .expect("failed to build ingest rayon pool")+ })+}++/// Deprioritised rayon pool for BACKGROUND index maintenance: flush+/// side-car builds (FTS + doc-values), segment finalisation, and merge+/// rebuilds.+///+/// Separate from `ingest_pool` (foreground, normal priority — bulk parse+/// and memtable insert are request-latency-critical) and from the global+/// pool (search fan-out). nice(10) lets CFS schedule foreground search+/// and bulk threads ahead of maintenance encode work, which otherwise+/// saturates every core for seconds per merged segment; with an idle+/// foreground the pool still gets every core, so writer-only throughput+/// is unchanged.+pub(crate) fn background_pool() -> &'static rayon::ThreadPool {+ static POOL: std::sync::OnceLock<rayon::ThreadPool> = std::sync::OnceLock::new();+ POOL.get_or_init(|| {+ let n = std::thread::available_parallelism()+ .map(|n| n.get())+ .unwrap_or(8);+ rayon::ThreadPoolBuilder::new()+ .num_threads(n)+ .thread_name(|i| format!("xerj-bg-{i}")).start_handler(|_| unsafe {let _ = libc::nice(10);}).build()- .expect("failed to build ingest rayon pool")+ .expect("failed to build background rayon pool")})}diff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rsindex f3b219571..517435ebb 100644--- a/engine/crates/xerj-engine/src/memtable.rs+++ b/engine/crates/xerj-engine/src/memtable.rs@@ -464,6 +464,99 @@ impl ShardedFtsMemtable {out}+ /// Bounded sorted-candidate extraction for a single-numeric-field sort+ /// (the implicit `@timestamp desc` index sort in particular).+ ///+ /// Returns `(candidate_ids, total_buffered_docs)` where the candidates+ /// are every buffered doc that could possibly reach the global+ /// top-`cap` page: the per-shard top-`cap` by column value (boundary+ /// ties included) plus up to `cap` docs missing the field (the top-N+ /// heap's full-key comparison places them per the sort's `missing`+ /// policy). Columnar walk — no source clones, no per-doc heap offers.+ /// Pre-fix the field-sorted match_all path offered EVERY buffered doc+ /// to the top-N heap with an O(shard) source lookup per doc: ~1.3 s+ /// per query at a 460 k-doc memtable under sustained bulk load.+ ///+ /// `None` when a shard's column is missing/misaligned (caller falls+ /// back to the exact full walk).+ pub fn sort_candidates_numeric(+ &self,+ field: &str,+ desc: bool,+ cap: usize,+ ) -> Option<(Vec<String>, u64)> {+ let cap = cap.max(1);+ let mut total: u64 = 0;+ let mut cands: Vec<(f64, String)> = Vec::new();+ let mut missing: Vec<String> = Vec::new();+ for s in &self.shards {+ let g = s.read();+ let n = g.doc_count();+ total += n as u64;+ if n == 0 {+ continue;+ }+ match g.doc_values.numeric.get(field) {+ None => {+ // Whole shard lacks the column: every doc is missing+ // the sort field.+ for e in g.docs.iter().take(cap.saturating_sub(missing.len())) {+ missing.push(e.doc_id.clone());+ }+ }+ Some(col) => {+ if col.len() != n {+ return None; // alignment not provable — full walk+ }+ let mut local: Vec<(f64, usize)> = Vec::new();+ for (i, v) in col.iter().enumerate() {+ match v {+ Some(x) => local.push((*x, i)),+ None => {+ if missing.len() < cap {+ missing.push(g.docs[i].doc_id.clone());+ }+ }+ }+ }+ if desc {+ local.sort_unstable_by(|a, b| {+ b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)+ });+ } else {+ local.sort_unstable_by(|a, b| {+ a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)+ });+ }+ let mut keep = local.len().min(cap);+ while keep < local.len() && keep > 0 && local[keep].0 == local[keep - 1].0 {+ keep += 1;+ }+ for (v, i) in local.into_iter().take(keep) {+ cands.push((v, g.docs[i].doc_id.clone()));+ }+ }+ }+ }+ // Global cut to cap (+boundary ties).+ if desc {+ cands.sort_unstable_by(|a, b| {+ b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)+ });+ } else {+ cands.sort_unstable_by(|a, b| {+ a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)+ });+ }+ let mut keep = cands.len().min(cap);+ while keep < cands.len() && keep > 0 && cands[keep].0 == cands[keep - 1].0 {+ keep += 1;+ }+ let mut ids: Vec<String> = cands.into_iter().take(keep).map(|(_, id)| id).collect();+ ids.extend(missing);+ Some((ids, total))+ }+/// Bounded variant: clone at most `limit` doc ids and return the TOTAL/// buffered doc count alongside. The unsorted match_all page only/// needs `from+size+ε` ids, but `all_doc_ids` cloned every buffered id