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
Merge commit 'de993c6' into worktree-agent-a366b326452dfdef8
xerj-orgc26689113096
diff --cc engine/crates/xerj-engine/src/fast_aggs.rsindex 6b4951343,6b4951343..2042ad385--- a/engine/crates/xerj-engine/src/fast_aggs.rs+++ b/engine/crates/xerj-engine/src/fast_aggs.rs@@@ -128,9 -128,9 +128,16 @@@ impl MemDocspub(super) struct FastCtx<'a> {idx: &'a Index,segs: Vec<SegEntry>,-- /// Memtable docs (see `MemDocs`). Empty when the memtable is empty-- /// (steady state for a flushed corpus).-- mem_docs: MemDocs,++ /// Memtable docs (see `MemDocs`), built LAZILY on first executor++ /// access: the columnar terms/cardinality memtable arms don't touch++ /// per-doc sources at all, so the per-request materialisation++ /// (doc_id String clones + Arc bumps over the whole buffered set —++ /// several ms at a drain-lagged memtable, EVERY agg request) is only++ /// paid by executors that genuinely walk docs.++ mem_docs: std::sync::OnceLock<MemDocs>,++ /// Whether the agg tree can observe meta fields (`top_hits`, `_id`,++ /// `_index`, `_seq_no`) — decides Owned vs Shared at build time.++ needs_owned_mem: bool,/// Schema fields mapped `boolean`. Their `.dv` columns are numeric/// 0/1 (indistinguishable from real integers at the column level), but/// the brute path renders them as "false"/"true" term keys — so the@@@ -138,6 -138,6 +145,50 @@@bool_fields: &'a std::collections::HashSet<String>,}++impl<'a> FastCtx<'a> {++ /// Lazy memtable-docs view (see the field doc). Kept identical to the++ /// eager build this replaces: Owned (deep clone + meta injection) when++ /// the agg tree can observe meta fields, Arc-shared otherwise.++ fn mem(&self) -> &MemDocs {++ self.mem_docs.get_or_init(|| {++ if self.idx.memtable.doc_count() == 0 {++ return MemDocs::Owned(Vec::new());++ }++ if self.needs_owned_mem {++ MemDocs::Owned(++ self.idx++ .memtable++ .all_docs_with_sources()++ .into_iter()++ .map(|(id, mut v)| {++ if let Some(o) = v.as_object_mut() {++ o.entry("_id".to_string())++ .or_insert_with(|| Value::String(id.clone()));++ o.entry("_index".to_string())++ .or_insert_with(|| Value::String(self.idx.name.to_string()));++ if let Some(seq) = self.idx.lookup_seq_no(&id) {++ o.entry("_seq_no".to_string())++ .or_insert_with(|| json!(seq));++ }++ }++ v++ })++ .collect(),++ )++ } else {++ let pairs = self.idx.memtable.all_docs_with_sources_arc();++ let mut ids = Vec::with_capacity(pairs.len());++ let mut srcs = Vec::with_capacity(pairs.len());++ for (id, src) in pairs {++ ids.push(id);++ srcs.push(src);++ }++ MemDocs::Shared { ids, srcs }++ }++ })++ }++}++#[derive(Clone, Copy, PartialEq, Eq)]enum ColKind {Numeric,@@@ -337,42 -337,42 +388,12 @@@ impl Index|| raw.contains("\"_index\"")|| raw.contains("\"_seq_no\"")};-- let mem_docs: MemDocs = if mem_physical == 0 {-- MemDocs::Owned(Vec::new())-- } else if needs_owned_mem {-- MemDocs::Owned(-- self.memtable-- .all_docs_with_sources()-- .into_iter()-- .map(|(id, mut v)| {-- if let Some(o) = v.as_object_mut() {-- o.entry("_id".to_string())-- .or_insert_with(|| Value::String(id.clone()));-- o.entry("_index".to_string())-- .or_insert_with(|| Value::String(self.name.to_string()));-- if let Some(seq) = self.lookup_seq_no(&id) {-- o.entry("_seq_no".to_string()).or_insert_with(|| json!(seq));-- }-- }-- v-- })-- .collect(),-- )-- } else {-- let pairs = self.memtable.all_docs_with_sources_arc();-- let mut ids = Vec::with_capacity(pairs.len());-- let mut srcs = Vec::with_capacity(pairs.len());-- for (id, src) in pairs {-- ids.push(id);-- srcs.push(src);-- }-- MemDocs::Shared { ids, srcs }-- };let ctx = FastCtx {idx: self,segs,-- mem_docs,++ mem_docs: std::sync::OnceLock::new(),++ needs_owned_mem,bool_fields,};@@@ -423,7 -423,7 +444,7 @@@ impl<'a> FastCtx<'a>/// Global corpus-order rank offset of segment `si` (mem docs first, then/// segments in snapshot order) — mirrors the brute corpus assembly.fn seg_rank_offset(&self, si: usize) -> u64 {-- let mut off = self.mem_docs.len() as u64;++ let mut off = self.mem().len() as u64;for s in &self.segs[..si] {off += s.docs as u64;}@@@ -454,7 -454,7 +475,7 @@@fn fetch_doc(&self, r: DocRef) -> Option<Value> {match r {-- DocRef::Mem(i) => self.mem_docs.owned(i, self.idx),++ DocRef::Mem(i) => self.mem().owned(i, self.idx),DocRef::Seg(si, row) => self.fetch_seg_doc(si, row),}}@@@ -517,7 -517,7 +538,7 @@@}fn mem_field_numeric_safe(&self, field: &str) -> bool {-- self.mem_docs.iter().all(|d| {++ self.mem().iter().all(|d| {matches!(get_nested_field(d, field), Value::Number(_) | Value::Null)})}@@@ -762,7 -762,7 +783,7 @@@field: field.to_string(),meta: None,};-- for d in self.mem_docs.iter() {++ for d in self.mem().iter() {Self::fold_mem_metric(d, &spec, &mut acc);}Some(Self::emit_metric(kind, &acc))@@@ -990,18 -990,18 +1011,43 @@@}}}-- // Memtable docs go through the exact brute extractor so string-- // rendering is identical.-- for d in self.mem_docs.iter() {-- let vals = crate::aggs::extract_field_values(d, field);-- if vals.is_empty() {-- if let Some(ph) = &missing_placeholder {-- distinct.insert(ph.clone());++ // Memtable docs. Columnar fast arm first (same equivalence gates++ // as exec_terms — see `terms_counts_columnar`); the per-doc++ // extraction walk below was the cardinality read-under-write tail++ // at a drain-lagged memtable.++ let mem_columnar: Option<(std::collections::HashMap<String, u64>, u64)> =++ if !field.contains('.') {++ self.idx.memtable.terms_counts_columnar(field)++ } else {++ None++ };++ match mem_columnar {++ Some((counts, missing)) => {++ for (term, cnt) in counts {++ if cnt > 0 {++ distinct.insert(term);++ }++ }++ if missing > 0 {++ if let Some(ph) = &missing_placeholder {++ distinct.insert(ph.clone());++ }}-- continue;}-- for v in vals {-- distinct.insert(v);++ None => {++ // Exact brute extractor so string rendering is identical.++ for d in self.mem().iter() {++ let vals = crate::aggs::extract_field_values(d, field);++ if vals.is_empty() {++ if let Some(ph) = &missing_placeholder {++ distinct.insert(ph.clone());++ }++ continue;++ }++ for v in vals {++ distinct.insert(v);++ }++ }}}@@@ -1198,20 -1198,20 +1244,48 @@@}}-- // Memtable docs — brute extractor semantics (multi-value, weights).-- for (di, doc) in self.mem_docs.iter().enumerate() {-- let weight = doc_count_weight(doc);-- let vals = extract_field_values(doc, field);-- for term in vals {-- let st = terms_map.entry(term).or_insert_with(|| new_state(&plan));-- st.count += weight;-- for (mi, spec) in plan.metrics.iter().enumerate() {-- Self::fold_mem_metric(doc, spec, &mut st.accs[mi]);++ // Memtable docs. Columnar fast arm first: when the shape is++ // provably brute-equivalent (no per-row sub-agg work, plain++ // un-dotted field, no array values ever seen for it, no++ // `_doc_count` weights — see `terms_counts_columnar`), count from++ // the keyword column directly. The per-doc JSON extraction walk++ // below cost 100-300 ms/query against a drain-lagged 300 k-doc++ // memtable under a sustained bulk writer — the terms-agg++ // read-under-write p95/p99 tail.++ let mem_columnar: Option<(std::collections::HashMap<String, u64>, u64)> =++ if !has_row_work && !field.contains('.') {++ self.idx.memtable.terms_counts_columnar(field)++ } else {++ None++ };++ match mem_columnar {++ Some((counts, _missing)) => {++ for (term, cnt) in counts {++ if cnt > 0 {++ terms_map++ .entry(term)++ .or_insert_with(|| new_state(&plan))++ .count += cnt;++ }}-- if let Some(spec) = &plan.top_hits {-- match extract_numeric(doc, &spec.sort_field) {-- Some(v) => push_top(&mut st.top, spec.k, spec.desc, v, di as u64, DocRef::Mem(di)),-- None => missing_sort_seen = true,++ }++ None => {++ // Brute extractor semantics (multi-value, weights).++ for (di, doc) in self.mem().iter().enumerate() {++ let weight = doc_count_weight(doc);++ let vals = extract_field_values(doc, field);++ for term in vals {++ let st = terms_map.entry(term).or_insert_with(|| new_state(&plan));++ st.count += weight;++ for (mi, spec) in plan.metrics.iter().enumerate() {++ Self::fold_mem_metric(doc, spec, &mut st.accs[mi]);++ }++ if let Some(spec) = &plan.top_hits {++ match extract_numeric(doc, &spec.sort_field) {++ Some(v) => push_top(&mut st.top, spec.k, spec.desc, v, di as u64, DocRef::Mem(di)),++ None => missing_sort_seen = true,++ }++ }}}}@@@ -1339,7 -1339,7 +1413,7 @@@}}}-- for doc in self.mem_docs.iter() {++ for doc in self.mem().iter() {let Some(v) = extract_numeric(doc, field) else { continue };let matches = match (from, to) {(Some(f), Some(t)) => v >= f && v < t,@@@ -1489,7 -1489,7 +1563,7 @@@count += prefix[hi] - prefix[lo];}}-- for doc in self.mem_docs.iter() {++ for doc in self.mem().iter() {let v = doc.get(field);let Some(ms) = v.and_then(parse_date_ms) else { continue };let pass_from = from_ms.map(|f| ms >= f).unwrap_or(true);@@@ -1637,7 -1637,7 +1711,7 @@@}}}-- for doc in self.mem_docs.iter() {++ for doc in self.mem().iter() {if doc_matches_filter(doc, filter_query) {count += doc_count_weight(doc);for (mi, spec) in plan.metrics.iter().enumerate() {@@@ -1725,7 -1725,7 +1799,7 @@@}}}-- for doc in self.mem_docs.iter() {++ for doc in self.mem().iter() {if doc_matches_filter(doc, filter_query) {count += doc_count_weight(doc);for (mi, spec) in plan.metrics.iter().enumerate() {@@@ -1793,7 -1793,7 +1867,7 @@@}}}-- for doc in self.mem_docs.iter() {++ for doc in self.mem().iter() {let matches: Vec<bool> = filters_map.values().map(|q| doc_matches_filter(doc, q))@@@ -1923,7 -1923,7 +1997,7 @@@*counts.entry(key).or_insert(0) += c;}}-- for doc in self.mem_docs.iter() {++ for doc in self.mem().iter() {let weight = doc_count_weight(doc);// Cross-product across multi-valued fields — brute semantics.let mut keys: Vec<Vec<String>> = vec![vec![]];@@@ -2012,7 -2012,7 +2086,7 @@@// match_all every doc scores equal, so the brute sampler's// stable score sort preserves exactly this prefix.let mut sample: Vec<Value> = Vec::with_capacity(shard_size);-- for d in self.mem_docs.iter() {++ for d in self.mem().iter() {if sample.len() >= shard_size {break;}@@@ -2078,9 -2078,9 +2152,9 @@@runs.push(run);}}-- if !self.mem_docs.is_empty() {++ if !self.mem().is_empty() {let mut mem_vals: Vec<f64> = self-- .mem_docs++ .mem().iter().filter_map(|doc| extract_numeric(doc, field)).collect();@@@ -2279,7 -2279,7 +2353,7 @@@}// Memtable docs — brute multi-value date extraction with per-doc// bucket dedup.-- for doc in self.mem_docs.iter() {++ for doc in self.mem().iter() {let raws = extract_date_ms_values(doc, field);let weight = doc_count_weight(doc);let mut seen: Vec<i64> = Vec::with_capacity(raws.len());diff --cc engine/crates/xerj-engine/src/index.rsindex 71eb931df,c721ee68a..c735fd31d--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@@ -360,6 -351,6 +360,28 @@@ pub struct Index/// immutable-segment lifecycle as `dv_cache` (never invalidated,/// retired segment ids are simply never queried again).sort_shadow_cache: Arc<dashmap::DashMap<String, Option<Arc<Vec<(i64, u32)>>>>>,++ /// Fields that have EVER been requested through `sorted_shadow_for`++ /// on this index (bounded at 16) — the publish-time warm pre-builds++ /// these fields' shadows for every new segment so the first sorted++ /// query after a flush/merge doesn't pay the O(n log n) build inside++ /// its own latency.++ sort_shadow_fields: Arc<dashmap::DashMap<String, ()>>,++ /// Per-segment single-flight guard for the `stored_slices_for` miss++ /// arm: without it, every in-flight query racing the same cold++ /// segment (up to the 64-permit cap) ran its own full stored-section++ /// decompress — one 30 ms decode became a ~1 s, 64-query stall++ /// episode at every flush/merge publish the warm hadn't reached yet.++ stored_slices_build_locks: Arc<dashmap::DashMap<String, Arc<std::sync::Mutex<()>>>>,++ /// Per-(segment, field, bounds) Range pre-filter position sets.++ /// `build_range_prefilter_cached` was cached in name only — it re-ran++ /// the O(matches) `range_doc_ids` walk + HashSet build per query per++ /// segment (~30-80 ms against a freshly-merged multi-M-doc segment,++ /// multiplied by every query racing the same post-publish miss — the++ /// residual range p99 wobble). Segments are immutable; bounded by a++ /// wholesale clear at 32 entries (worst-case tens of MB per merged-++ /// segment entry — a roaring bitmap representation is the durable++ /// follow-up) and evicted by segment id at merge retire.++ range_prefilter_cache: Arc<dashmap::DashMap<String, Arc<HashSet<u32>>>>,/// Per-segment cache of decoded `Vec<Value>` from the stored section./// KNN search and segment-scan get-document paths used to call@@@ -582,6 -563,6 +604,9 @@@ impl Indexembedding_proxy: Arc::new(make_embedding_proxy(&config.embedding)),dv_cache: Arc::new(dashmap::DashMap::new()),sort_shadow_cache: Arc::new(dashmap::DashMap::new()),++ sort_shadow_fields: Arc::new(dashmap::DashMap::new()),++ stored_slices_build_locks: Arc::new(dashmap::DashMap::new()),++ range_prefilter_cache: Arc::new(dashmap::DashMap::new()),stored_value_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),@@@ -752,6 -732,6 +777,9 @@@embedding_proxy: Arc::new(make_embedding_proxy(&config.embedding)),dv_cache: Arc::new(dashmap::DashMap::new()),sort_shadow_cache: Arc::new(dashmap::DashMap::new()),++ sort_shadow_fields: Arc::new(dashmap::DashMap::new()),++ stored_slices_build_locks: Arc::new(dashmap::DashMap::new()),++ range_prefilter_cache: Arc::new(dashmap::DashMap::new()),stored_value_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache: Arc::new(dashmap::DashMap::new()),stored_slices_cache_bytes: Arc::new(AtomicU64::new(0)),@@@ -1707,6 -1686,6 +1735,7 @@@let field_configs = self.flush_signal.field_configs(&self.schema);let dataset_version = Arc::clone(&self.dataset_version);let query_cache = Arc::clone(&self.query_cache);++ let warm_caches = self.publish_warm_caches();// Permit is released by `on_drained` (fired after Phase 1 drain)// so the slow segment-write I/O in Phase 2 doesn't hold up the// per-shard flush permit pool. The `Option` wrapper makes the@@@ -1732,6 -1711,6 +1761,7 @@@data_dir,field_configs,on_drained,++ warm_caches,).await;// Fallback: if do_flush_shard aborted before on_drained fired@@@ -1966,6 -1945,6 +1996,7 @@@self.data_dir.clone(),field_configs.clone(),|| {}, // serial refresh path — no permit to drop early++ self.publish_warm_caches(),).await?;}@@@ -2053,6 -2032,6 +2084,7 @@@let data_dir = self.data_dir.clone();let dataset_version = Arc::clone(&self.dataset_version);let query_cache = Arc::clone(&self.query_cache);++ let warm_caches = self.publish_warm_caches();// Pre-build field configs ONCE for all shard flushes we// spawn this tick — avoids N schema read-lock acquires.@@@ -2087,6 -2066,6 +2119,7 @@@data_dir,field_configs,on_drained,++ warm_caches,).await;if let Ok(mut guard) = permit_cell.lock() {@@@ -2661,8 -2550,8 +2694,35 @@@let handle = in_flight.remove(0);match handle.await {Ok(Some((batch_slice, merged_meta, live_doc_count, ids_pairs))) => {++ // Warm the merged segment's stored slices BEFORE the++ // swap makes it visible: the first sorted-candidates++ // queries after a merge otherwise each pay the fresh++ // multi-100 MB stored-section decompress inside their++ // own latency (dec=1.1-3.8 s p99 spikes at every merge++ // completion under the mixed read/write bench). On the++ // blocking pool — the decompress is CPU-bound and must++ // not stall the async merge driver.++ {++ let w_store = Arc::clone(&self.store);++ let w_caches = self.publish_warm_caches();++ let w_dir = self.data_dir.join("segments");++ let w_id = merged_meta.id.clone();++ let w_docs = merged_meta.doc_count;++ let _ = tokio::task::spawn_blocking(move || {++ warm_segment_at_publish(&w_store, &w_dir, &w_caches, &w_id, w_docs);++ })++ .await;++ }if let Err(e) = self.store.apply_merge(&batch_slice, merged_meta.clone()) {tracing::warn!("merge: apply_merge failed: {e}");++ // The pre-warmed slices belong to a segment that++ // never became visible — release them.++ if let Some((_, slices)) =++ self.stored_slices_cache.remove(merged_meta.id.as_str())++ {++ self.stored_slices_cache_bytes++ .fetch_sub(slices.retained_bytes(), Ordering::Relaxed);++ }} else {// Write the merge output's `.ids` side-car AFTER the// merge is committed: if we crashed before@@@ -2763,6 -2652,6 +2823,17 @@@}self.fast_date_cache.retain(|(seg, _), _| seg != id.as_str());self.fast_date_sorted_cache.retain(|(seg, _), _| seg != id.as_str());++ // Sort-key shadows are keyed "{seg}\u{1}{field}" and hold++ // an O(doc_count) Vec each — without eviction every++ // merged-away segment leaked its shadows for the process++ // lifetime under a sustained writer.++ let shadow_prefix = format!("{}\u{1}", id.as_str());++ self.sort_shadow_cache++ .retain(|k, _| !k.starts_with(&shadow_prefix));++ self.shortcut_count_cache.retain(|(seg, _), _| seg != id.as_str());++ self.range_prefilter_cache++ .retain(|k, _| !k.starts_with(&shadow_prefix));++ self.stored_slices_build_locks.remove(id.as_str());}}@@@ -4338,7 -4244,7 +4426,9 @@@AllDocIds(Vec<String>, u64), // MatchAll: bounded IDs + uncollected remainder count/// Fast DocValues hit: (doc_id, internal_index) pairs — source is NOT/// cloned here; it will be fetched only for the final page of hits.-- DocValuesHits(Vec<(String, usize)>),++ /// The `u64` is the UNCOLLECTED matching-doc remainder (bounded++ /// fused-bool path); it still counts toward `hits.total`.++ DocValuesHits(Vec<(String, usize)>, u64),DocsForScan(Vec<(String, Arc<Value>)>), // doc_id + shared source for term-level scan}@@@ -4372,37 -4278,19 +4462,51 @@@// only ever admit the first `materialisation_limit` ids,// so clone just those and carry the remainder as a count.if sort_topk.is_some() {- // Field-sorted match_all must offer every buffered doc- // to the top-N heap — but the id-only snapshot forced- // `admit_hit!(count …)` to pay a per-doc- // `get_doc_source_as_value` DEEP CLONE (plus a- // `seen_ids` String insert and a full `offer`) for- // every buffered doc just to compute its sort key:- // ~1 s per query against a ~1 M-doc memtable under the- // mixed-bench writer, serialised across every read.- // Share the sources via Arc instead and let the scan- // arm's pre-clone primary-key rejection below bound the- // per-doc cost to a memoised epoch lookup once the heap- // is full.- MemSnapshot::DocsForScan(mem.all_docs_with_sources_arc())+ // 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.++ // offering EVERY buffered doc to the heap. Date-string++ // columns (the implicit `@timestamp` index sort) resolve++ // through the bounded process-wide epoch memo — the SAME++ // normalisation `compute_sort_values` applies per hit —++ // so the candidate cut ranks exactly like the heap would.+ 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,++ &sort_epoch_memo,+ )+ })();+ 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),++ // Ineligible shape (multi-field sort, cursor,++ // non-default mode/missing, un-normalisable++ // values): fall back to offering every buffered++ // doc — via Arc-shared sources so the scan arm's++ // pre-clone primary-key rejection bounds the++ // per-doc cost to a memoised epoch lookup once++ // the heap is full (NOT the id-only snapshot,++ // whose per-doc deep clone cost ~1 s/query at a++ // 1 M-doc memtable).++ None => MemSnapshot::DocsForScan(mem.all_docs_with_sources_arc()),+ }} else {let (ids, total) = mem.doc_ids_bounded(materialisation_limit);let extra = total.saturating_sub(ids.len() as u64);@@@ -4430,10 -4318,10 +4534,28 @@@// doc-values in the segment shortcut and would be// silently undercounted.MemSnapshot::Empty++ } else if let Some((hits, total)) = (|| {++ // Fused columnar term/range/bool: ONE position walk++ // per shard, bounded id materialisation, exact total.++ // Gated off when a field sort is active — the top-N++ // heap must see EVERY matching doc — and when aggs++ // are present (the filtered-agg path needs the full++ // `mem_dv_doc_indices` position set). Placed BEFORE++ // `try_doc_values_query`, whose unbounded walks clone++ // every matching doc_id (~all-of-memtable for broad++ // range filters) per request.++ if sort_topk.is_some() || request.aggs.is_some() {++ return None;++ }++ let preds = mem_bool_preds(query)?;++ mem.doc_values_bool_query(&preds, materialisation_limit)++ })() {++ let uncollected = total.saturating_sub(hits.len() as u64);++ MemSnapshot::DocValuesHits(hits, uncollected)} else if let Some(hits) = try_doc_values_query(query, &mem) {// DocValues fast path for queries that actually need// the hit list (size > 0 or sort-on-field).-- MemSnapshot::DocValuesHits(hits)++ MemSnapshot::DocValuesHits(hits, 0)} else {// Composite queries (e.g. bool) that the memtable DV// path can't resolve: share the buffered sources via@@@ -4472,7 -4360,7 +4594,7 @@@MemSnapshot::Empty}} else if let Some(hits) = try_doc_values_query(query, &mem) {-- MemSnapshot::DocValuesHits(hits)++ MemSnapshot::DocValuesHits(hits, 0)} else {MemSnapshot::Empty}@@@ -4481,13 -4369,6 +4603,13 @@@};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::DocValuesHits(..) => "dv",+ MemSnapshot::DocsForScan(_) => "scan",+ };match mem_snapshot {MemSnapshot::Empty => {}MemSnapshot::FtsHits(hits) => {@@@ -4512,7 -4393,7 +4634,7 @@@admit_hit!(count doc_id);}}-- MemSnapshot::DocValuesHits(hits) => {++ MemSnapshot::DocValuesHits(hits, uncollected) => {// DocValues fast path: source is NOT cloned here — we defer the// clone until after pagination so we only pay for from+size docs.// Retain the internal indices for filtered aggregation (Opt 2).@@@ -4523,6 -4404,6 +4645,9 @@@}admit_hit!(count doc_id);}++ // Bounded fused-bool remainder: matched but un-materialised++ // docs still count toward hits.total.++ total_count += uncollected;mem_dv_doc_indices = Some(indices);}MemSnapshot::DocsForScan(docs) => {@@@ -5114,7 -5008,7 +5256,7 @@@// sorted-candidates path is provably safe; the plain// position pre-filter below is derived from it.let mut sort_cand: Option<SortCandidates> = None;-- let pre_filter: Option<HashSet<u32>> =++ let pre_filter: Option<Arc<HashSet<u32>>> =if let QueryNode::Range { field, gte, gt, lte, lt, .. } = query {let base = self.build_range_prefilter_cached(&segments_dir,@@@ -5151,7 -5045,7 +5293,7 @@@}}match &sort_cand {-- Some(sc) => Some(sc.set.clone()),++ Some(sc) => Some(Arc::new(sc.set.clone())),None => base,}} else if is_match_all && !deletes_present {@@@ -5174,7 -5068,7 +5316,7 @@@materialisation_limit,)});-- sort_cand.as_ref().map(|sc| sc.set.clone())++ sort_cand.as_ref().map(|sc| Arc::new(sc.set.clone()))} else if let QueryNode::Regexp { field, pattern } = query {// Dictionary-expansion pre-filter (mirrors the// `try_shortcut_count` Regexp arm). When the@@@ -5213,6 -5107,6 +5355,7 @@@cap,regexp_field_is_keyword,)++ .map(Arc::new)} else {None};@@@ -5307,7 -5201,7 +5450,7 @@@&mut total_count,&mut all_hits,&mut seen_ids,-- pre_filter.as_ref(),++ pre_filter.as_deref(),sort_topk.as_mut(),None,Some(search_deadline),@@@ -5349,7 -5243,7 +5492,7 @@@&mut total_count,&mut all_hits,&mut seen_ids,-- pre_filter.as_ref(),++ pre_filter.as_deref(),sort_topk.as_mut(),if want_cache { Some(&mut offsets) } else { None },Some(search_deadline),@@@ -5371,7 -5265,7 +5514,7 @@@.stored_slices_cache_bytes.load(Ordering::Relaxed).saturating_add(sz)-- <= STORED_SLICES_CACHE_BUDGET++ <= stored_slices_cache_budget()&& self.stored_slices_cache.insert(seg_id.clone(), Arc::new(slices))@@@ -6240,6 -6129,6 +6383,7 @@@let registry = Arc::clone(&self.registry);let data_dir = self.data_dir.clone();let field_configs = field_configs.clone();++ let warm_caches = self.publish_warm_caches();shard_futures.push(tokio::spawn(async move {let permit = sema.acquire_owned().await.ok();let permit_cell = Arc::new(std::sync::Mutex::new(permit));@@@ -6251,7 -6140,7 +6395,7 @@@};let result = do_flush_shard(shard_idx, store, memtable, registry, data_dir, field_configs,-- on_drained,++ on_drained, warm_caches,).await;// Defensive: in case on_drained didn't fire.@@@ -7151,15 -7022,15 +7295,23 @@@ impl Indexseg_matches = seg_matches.saturating_add(sc);}-- // Memtable side — M5.1 sharded fallback. The single-shard-- // fused predicate walk (which took references into one-- // `DocValues` struct) can't work across independent-- // shards without a bigger refactor. For correctness we-- // fall back to the generic stored-doc scan, which is-- // slightly slower on tiny filtered bool queries but-- // identical in output.-- let mem_matches: u64 = {-- let docs = self.memtable.all_docs_with_sources();++ // Memtable side — fused columnar walk (one position pass per++ // shard, count-only) via the same predicate lowering the++ // memtable hit path uses. The old fallback DEEP-CLONED the++ // entire memtable per query (`all_docs_with_sources`) and ran++ // a `doc_matches_query` JSON descent per buffered doc — under++ // a sustained bulk writer that alone was 1-6 s per bool query++ // (the read-under-write bool collapse, WARN mem_admit term).++ // When the columns can't serve the predicates we keep the++ // per-doc scan but share sources via Arc instead of cloning.++ let mem_matches: u64 = if self.memtable.doc_count() == 0 {++ 0++ } else if let Some((_, total)) = mem_bool_preds(query)++ .and_then(|preds| self.memtable.doc_values_bool_query(&preds, 0))++ {++ total++ } else {++ let docs = self.memtable.all_docs_with_sources_arc();docs.iter().filter(|(_, src)| doc_matches_query(query, src)).count() as u64};@@@ -7472,6 -7343,6 +7624,17 @@@ impl Index/// fix is forcemerge → 1 segment (which blows up on a separate/// memory issue in run_merge_once, M5.16/22 capped but still/// converges slowly). Left unbounded for now.++ /// Bundle the publish-time warm targets (see `warm_segment_at_publish`).++ fn publish_warm_caches(&self) -> PublishWarmCaches {++ PublishWarmCaches {++ slices: Arc::clone(&self.stored_slices_cache),++ slices_bytes: Arc::clone(&self.stored_slices_cache_bytes),++ dv: Arc::clone(&self.dv_cache),++ shadow: Arc::clone(&self.sort_shadow_cache),++ shadow_fields: Arc::clone(&self.sort_shadow_fields),++ }++ }++fn dv_columns_for(&self,segments_dir: &std::path::Path,@@@ -7531,12 -7402,12 +7694,8 @@@gt: Option<&Value>,lte: Option<&Value>,lt: Option<&Value>,-- ) -> Option<HashSet<u32>> {++ ) -> Option<Arc<HashSet<u32>>> {use xerj_storage::doc_values::Column;-- let cols = self.dv_columns_for(segments_dir, segment_id)?;-- let Some(Column::Numeric(n)) = cols.get(field) else {-- return None;-- };let parse = |v: Option<&Value>| -> Option<Option<f64>> {match v {@@@ -7568,8 -7439,8 +7727,44 @@@(None, None) => (f64::INFINITY, true),};++ // Segments are immutable → a (segment, field, bounds) key never++ // goes stale. SINGLE-FLIGHT the build: post-merge-publish, every++ // in-flight range query raced the same miss and each rebuilt the++ // O(matches) set.++ let cache_key = format!(++ "{segment_id}\u{1}{field}\u{1}{:x}\u{1}{:x}\u{1}{}{}",++ lo.to_bits(),++ hi.to_bits(),++ lo_incl as u8,++ hi_incl as u8++ );++ if let Some(hit) = self.range_prefilter_cache.get(&cache_key) {++ return Some(Arc::clone(hit.value()));++ }++ let flight = {++ let e = self++ .stored_slices_build_locks++ .entry(format!("{segment_id}\u{2}rpf"))++ .or_default();++ Arc::clone(e.value())++ };++ let _g = flight.lock().ok()?;++ if let Some(hit) = self.range_prefilter_cache.get(&cache_key) {++ return Some(Arc::clone(hit.value()));++ }++++ let cols = self.dv_columns_for(segments_dir, segment_id)?;++ let Some(Column::Numeric(n)) = cols.get(field) else {++ return None;++ };let matching = n.range_doc_ids(lo, hi, lo_incl, hi_incl);-- Some(matching.into_iter().collect())++ let built: Arc<HashSet<u32>> = Arc::new(matching.into_iter().collect());++ if self.range_prefilter_cache.len() >= 32 {++ self.range_prefilter_cache.clear();++ }++ self.range_prefilter_cache++ .insert(cache_key, Arc::clone(&built));++ Some(built)}/// Sorted-DV candidate pruning for field-sorted `match_all` queries@@@ -7616,7 -7487,7 +7811,11 @@@field: &str,seg_doc_count: u64,) -> Option<Arc<Vec<(i64, u32)>>> {-- use xerj_storage::doc_values::Column;++ // Register the field so the publish-time warm pre-builds this++ // shadow for every FUTURE segment (bounded registry).++ if self.sort_shadow_fields.len() < 16 && !self.sort_shadow_fields.contains_key(field) {++ self.sort_shadow_fields.insert(field.to_string(), ());++ }let key = format!("{segment_id}\u{1}{field}");if let Some(entry) = self.sort_shadow_cache.get(&key) {return entry.value().clone();@@@ -7632,49 -7503,49 +7831,7 @@@let Some(cols) = self.dv_columns_for(segments_dir, segment_id) else {return None;};-- let built: Option<Arc<Vec<(i64, u32)>>> = (|| {-- match cols.get(field) {-- Some(Column::Numeric(n)) => {-- if !n.null_bitmap.is_empty()-- || n.doc_count as u64 != seg_doc_count-- || n.sorted.is_empty()-- {-- return None;-- }-- Some(Arc::new(n.sorted.clone()))-- }-- Some(Column::Keyword(k)) => {-- if !k.null_bitmap.is_empty()-- || k.doc_count as u64 != seg_doc_count-- || k.ords.len() != k.doc_count as usize-- || k.terms.is_empty()-- {-- return None;-- }-- // Every distinct term must normalise to a NUMBER via the-- // exact per-hit date path; one miss → ineligible (the-- // heap would rank raw strings, not epochs).-- let mut keys: Vec<f64> = Vec::with_capacity(k.terms.len());-- for t in &k.terms {-- keys.push(sort_date_normalize(t)?.as_f64()?);-- }-- let mut sorted: Vec<(i64, u32)> = k-- .ords-- .iter()-- .enumerate()-- .map(|(pos, ord)| (keys[*ord as usize].to_bits() as i64, pos as u32))-- .collect();-- sorted.sort_unstable_by(|a, b| {-- f64::from_bits(a.0 as u64)-- .partial_cmp(&f64::from_bits(b.0 as u64))-- .unwrap_or(std::cmp::Ordering::Equal)-- .then(a.1.cmp(&b.1))-- });-- Some(Arc::new(sorted))-- }-- None => None,-- }-- })();++ let built = build_sort_shadow(&cols, field, seg_doc_count);self.sort_shadow_cache.insert(key, built.clone());built}@@@ -7863,6 -7734,6 +8020,23 @@@seg_id: &str,expect_docs: u64,) -> Option<Arc<StoredSlices>> {++ if let Some(entry) = self.stored_slices_cache.get(seg_id) {++ return Some(Arc::clone(entry.value()));++ }++ // SINGLE-FLIGHT the miss: up to 64 in-flight queries race the++ // same cold segment; without this every one of them ran its own++ // full stored-section decompress (one ~30 ms decode became a ~1 s++ // 64-query stall episode at every publish the warm hadn't++ // reached). Waiters block on the per-segment mutex and wake to a++ // cache hit.++ let flight = {++ let entry = self++ .stored_slices_build_locks++ .entry(seg_id.to_string())++ .or_default();++ Arc::clone(entry.value())++ };++ let _flight_guard = flight.lock().ok()?;if let Some(entry) = self.stored_slices_cache.get(seg_id) {return Some(Arc::clone(entry.value()));}@@@ -7888,7 -7759,7 +8062,7 @@@.stored_slices_cache_bytes.load(Ordering::Relaxed).saturating_add(sz)-- <= STORED_SLICES_CACHE_BUDGET++ <= stored_slices_cache_budget()&& self.stored_slices_cache.insert(seg_id.to_string(), Arc::clone(&slices))@@@ -8508,6 -8379,6 +8682,10 @@@ async fn do_flush_sharddata_dir: PathBuf,field_configs: HashMap<String, xerj_fts::index::FieldIndexConfig>,on_drained: impl FnOnce() + Send + 'static,++ // Publish-time cache warm (see `warm_segment_at_publish`): the index's++ // read-path caches, threaded through because this is a free fn without++ // access to `Index`.++ warm_caches: PublishWarmCaches,) -> Result<()> {// V4 M4.5: no outer flush_lock — concurrent flushes are allowed. The// memtable write lock below is the only atomicity point we need for@@@ -8644,6 -8515,6 +8822,7 @@@let registry_for_build = Arc::clone(®istry);let fts_doc_count = drained_fts.len();let segments_dir_for_dv = segments_dir.clone();++ let store_for_warm = Arc::clone(&store);// POV battery (B-3) caught that gating FTS+DV on the raw-bytes path// hides docs from match_all/term/range and from the kNN brute-force// pre-filter — the per-segment enumeration uses these sidecars as@@@ -8702,6 -8573,6 +8881,21 @@@fts_doc_count, dv_us, fts_add_us, fts_finish_us);}++ // Publish-time cache warm — MUST run here, inside the finaliser's++ // pre-publish callback: the snapshot rcu that makes this segment++ // visible happens right after `post_finish` returns, so by the++ // time any query can see the segment its stored slices, dv++ // columns, and sort shadows are already hot. (A post-finalize++ // warm left a ~250 ms visible-but-cold window per flush storm;++ // 64 racing queries each decompressed all 16 fresh segments++ // inside it — the dec≈900 ms stall episodes.)++ warm_segment_at_publish(++ &store_for_warm,++ &segments_dir_for_dv,++ &warm_caches,++ meta.id.as_str(),++ meta.doc_count,++ );});let _ = &segments_dir;let _ = &drained_fts;@@@ -10376,6 -10247,6 +10570,96 @@@ fn infer_field_type(val: &Value) -> Fie/// Returns `(doc_id, internal_memtable_index)` pairs WITHOUT cloning source./// The caller defers source fetching until after scoring and pagination so only/// the final `from+size` hits pay the clone cost.++/// Lower a `bool { must/filter: [Term|Range…] }` (no should / must_not) —++/// or a bare Term / Range — to fused columnar memtable predicates: the++/// memtable twin of the `try_shortcut_count` Bool segment arm. `None` for++/// any other shape (caller falls back to the stored-source scan). Wrapper++/// nodes (constant_score / boost) are peeled like `try_doc_values_query`++/// does.++fn mem_bool_preds(q: &QueryNode) -> Option<Vec<crate::memtable::MemBoolPred>> {++ use crate::memtable::MemBoolPred;++ let q = match q {++ QueryNode::Constant { query, .. } | QueryNode::Boosted { query, .. } => query.as_ref(),++ _ => q,++ };++ // Bare term/range: a single-predicate fused walk — bounds the id++ // materialisation the unbounded `doc_values_term_query` /++ // `doc_values_range_query` paths would pay (~all-matching doc_id++ // String clones per query at a 200 k-doc memtable).++ let children: Vec<&QueryNode> = match q {++ QueryNode::Term { .. } | QueryNode::Range { .. } => vec![q],++ QueryNode::Bool { must, should, must_not, filter, .. } => {++ if !should.is_empty() || !must_not.is_empty() {++ return None;++ }++ must.iter().chain(filter.iter()).collect()++ }++ _ => return None,++ };++ if children.is_empty() {++ return None;++ }++ let mut preds: Vec<MemBoolPred> = Vec::with_capacity(children.len());++ for child in children {++ let child = match child {++ QueryNode::Constant { query, .. } | QueryNode::Boosted { query, .. } => {++ query.as_ref()++ }++ _ => child,++ };++ match child {++ QueryNode::Term { field, value, .. } => {++ // Same value lowering (and CIDR bailout) as the standalone++ // Term arm of `try_doc_values_query`.++ let val_str = match value {++ Value::String(s) => {++ if s.contains('/') {++ return None;++ }++ s.clone()++ }++ Value::Number(n) => n.to_string(),++ Value::Bool(b) => b.to_string(),++ _ => return None,++ };++ preds.push(MemBoolPred::Term { field: field.clone(), value: val_str });++ }++ QueryNode::Range { field, gte, gt, lte, lt, .. } => {++ // Numeric bounds only — mirrors the Range arm of++ // `try_doc_values_query`.++ let to_f64 = |v: &Option<Value>| -> Option<Option<f64>> {++ match v {++ None => Some(None),++ Some(Value::Number(n)) => Some(n.as_f64()),++ Some(Value::String(s)) => s.parse::<f64>().ok().map(Some),++ _ => None,++ }++ };++ let gte_f = to_f64(gte)?;++ let gt_f = to_f64(gt)?;++ let lte_f = to_f64(lte)?;++ let lt_f = to_f64(lt)?;++ if (gte_f.is_none() && gte.is_some())++ || (gt_f.is_none() && gt.is_some())++ || (lte_f.is_none() && lte.is_some())++ || (lt_f.is_none() && lt.is_some())++ {++ return None;++ }++ preds.push(MemBoolPred::Range {++ field: field.clone(),++ gte: gte_f,++ gt: gt_f,++ lte: lte_f,++ lt: lt_f,++ });++ }++ _ => return None,++ }++ }++ Some(preds)++}++fn try_doc_values_query(q: &QueryNode, mem: &crate::memtable::ShardedFtsMemtable) -> Option<Vec<(String, usize)>> {match q {QueryNode::Term { field, value, .. } => {@@@ -13222,10 -13093,20 +13506,180 @@@ impl StoredSlices}}++/// Segment sort-key shadow builder — shared by the query-path++/// `Index::sorted_shadow_for` and the publish-time warm. See++/// `sorted_shadow_for` for the eligibility contract (no nulls, full++/// coverage, all-date keyword terms).++fn build_sort_shadow(++ cols: &std::collections::BTreeMap<String, xerj_storage::doc_values::Column>,++ field: &str,++ seg_doc_count: u64,++) -> Option<Arc<Vec<(i64, u32)>>> {++ use xerj_storage::doc_values::Column;++ match cols.get(field) {++ Some(Column::Numeric(n)) => {++ if !n.null_bitmap.is_empty()++ || n.doc_count as u64 != seg_doc_count++ || n.sorted.is_empty()++ {++ return None;++ }++ Some(Arc::new(n.sorted.clone()))++ }++ Some(Column::Keyword(k)) => {++ if !k.null_bitmap.is_empty()++ || k.doc_count as u64 != seg_doc_count++ || k.ords.len() != k.doc_count as usize++ || k.terms.is_empty()++ {++ return None;++ }++ // Every distinct term must normalise to a NUMBER via the++ // exact per-hit date path; one miss → ineligible (the++ // heap would rank raw strings, not epochs).++ let mut keys: Vec<f64> = Vec::with_capacity(k.terms.len());++ for t in &k.terms {++ keys.push(sort_date_normalize(t)?.as_f64()?);++ }++ let mut sorted: Vec<(i64, u32)> = k++ .ords++ .iter()++ .enumerate()++ .map(|(pos, ord)| (keys[*ord as usize].to_bits() as i64, pos as u32))++ .collect();++ sorted.sort_unstable_by(|a, b| {++ f64::from_bits(a.0 as u64)++ .partial_cmp(&f64::from_bits(b.0 as u64))++ .unwrap_or(std::cmp::Ordering::Equal)++ .then(a.1.cmp(&b.1))++ });++ Some(Arc::new(sorted))++ }++ None => None,++ }++}++++/// The read-path caches a freshly-published segment must be warm in so++/// its first queries don't pay cold-start costs inside their own latency.++/// Bundled so the flush path (a free fn without `&Index`) can carry ONE++/// handle. All fields are the Index's own Arcs.++#[derive(Clone)]++struct PublishWarmCaches {++ slices: Arc<dashmap::DashMap<String, Arc<StoredSlices>>>,++ slices_bytes: Arc<AtomicU64>,++ dv: Arc<dashmap::DashMap<String, Arc<std::collections::BTreeMap<String, xerj_storage::doc_values::Column>>>>,++ shadow: Arc<dashmap::DashMap<String, Option<Arc<Vec<(i64, u32)>>>>>,++ shadow_fields: Arc<dashmap::DashMap<String, ()>>,++}++++/// Warm one just-written segment's read-path caches OUTSIDE the query++/// path, BEFORE the segment becomes visible:++/// 1. `StoredSlices` (decompressed stored section + per-doc offsets) —++/// the sorted-candidates hydration source. Cold cost the first++/// queries otherwise paid: a full multi-MB (flush) to multi-100 MB++/// (merge) decompress, multiplied by every concurrent query racing++/// the same miss (dec=0.9–3.8 s stall episodes at every publish).++/// 2. dv columns — the aggs / shortcut-count / sort-shadow source++/// (terms/cardinality p99 spikes at every publish).++/// 3. Sort-key shadows for every field the index has ever field-sorted++/// on (the implicit `@timestamp` in particular) — the O(n log n)++/// build on a merged segment was a ~200-500 ms first-query cost.++///++/// Called (a) by the merge driver right BEFORE `apply_merge` swaps the++/// merged segment in, and (b) inside `do_flush_shard`'s `build_fts`++/// callback, which the storage finaliser runs BEFORE the snapshot rcu++/// publish. Budget-checked exactly like the query-path inserts; failure++/// or over-budget is non-fatal (queries fall back to the per-query++/// decompress — pre-warm status quo).++fn warm_segment_at_publish(++ store: &IndexStore,++ segments_dir: &std::path::Path,++ caches: &PublishWarmCaches,++ seg_id: &str,++ expect_docs: u64,++) {++ // 1. Stored slices.++ if !caches.slices.contains_key(seg_id) {++ let built: Option<Arc<StoredSlices>> = (|| {++ let reader = store.open_segment_arc(seg_id).ok()?;++ let raw = reader.section(SectionType::Stored).ok()??;++ let bytes = xerj_storage::stored_codec::decode_stored(raw).ok()?;++ if bytes.len() > u32::MAX as usize {++ return None;++ }++ let offsets = brace_walk_offsets(&bytes);++ if offsets.len() as u64 != expect_docs {++ return None;++ }++ Some(Arc::new(StoredSlices { bytes, offsets }))++ })();++ if let Some(slices) = built {++ let sz = slices.retained_bytes();++ if caches.slices_bytes.load(Ordering::Relaxed).saturating_add(sz)++ <= stored_slices_cache_budget()++ && caches.slices.insert(seg_id.to_string(), slices).is_none()++ {++ caches.slices_bytes.fetch_add(sz, Ordering::Relaxed);++ }++ }++ }++ // 2. dv columns (mirrors `Index::dv_columns_for`'s miss arm).++ let cols: Option<Arc<std::collections::BTreeMap<String, xerj_storage::doc_values::Column>>> =++ if let Some(entry) = caches.dv.get(seg_id) {++ Some(Arc::clone(entry.value()))++ } else {++ let cols = read_doc_values_sidecar(segments_dir, seg_id);++ if cols.is_empty() {++ None++ } else {++ let arc = Arc::new(cols);++ caches.dv.insert(seg_id.to_string(), Arc::clone(&arc));++ Some(arc)++ }++ };++ // 3. Sort shadows for every historically-sorted field.++ if let Some(cols) = cols {++ for e in caches.shadow_fields.iter() {++ let field = e.key();++ let key = format!("{seg_id}\u{1}{field}");++ if !caches.shadow.contains_key(&key) {++ let built = build_sort_shadow(&cols, field, expect_docs);++ caches.shadow.insert(key, built);++ }++ }++ }++}++/// Retained-memory budget for `stored_slices_cache`. Inserts stop once the/// budget is reached (queries then fall back to the per-query decompress/// path); merge eviction returns the dropped segment's bytes to the budget.- const STORED_SLICES_CACHE_BUDGET: u64 = 3 * 1024 * 1024 * 1024;-/// 24 GB (was 3 GB): the mixed bench's background writer grows the corpus-/// past 3 GB of stored bytes DURING the read window; once the budget is-/// full every over-budget segment is decompressed PER QUERY (insert stops,-/// nothing evicts) — measured dec=28–30 s per match_all against a 21 M-doc-/// corpus even fully quiesced, because with corpus-wide primary-key ties-/// (cycled telemetry timestamps) the per-segment best-candidate rejection-/// never strictly loses, so NO segment is skipped. Sized for the bench-/// host (119 GB RAM); merge eviction returns merged-away segments' bytes.++/// 20% of host RAM, ≥2 GB floor (was a flat 3 GB, then a host-tuned 24 GB):++/// a sustained bulk writer grows the corpus past a small flat budget DURING++/// the read window; once the budget is full every over-budget segment is++/// decompressed PER QUERY (insert stops, nothing evicts) — measured++/// dec=28–30 s per match_all against a 21 M-doc corpus even fully quiesced,++/// because with corpus-wide primary-key ties (cycled telemetry timestamps)++/// the per-segment best-candidate rejection never strictly loses, so NO++/// segment is skipped. Merge eviction returns merged-away segments' bytes.+ /// The durable fix — hydrating only GLOBAL winners after a shadow-merge of+ /// per-segment candidate keys — is tracked as follow-up.-const STORED_SLICES_CACHE_BUDGET: u64 = 24 * 1024 * 1024 * 1024;++fn stored_slices_cache_budget() -> u64 {++ static BUDGET: std::sync::LazyLock<u64> = std::sync::LazyLock::new(|| {++ const FLOOR: u64 = 2 * 1024 * 1024 * 1024;++ let ram_total: Option<u64> = std::fs::read_to_string("/proc/meminfo")++ .ok()++ .and_then(|s| {++ s.lines().find(|l| l.starts_with("MemTotal:")).and_then(|l| {++ l.split_whitespace()++ .nth(1)++ .and_then(|kb| kb.parse::<u64>().ok())++ .map(|kb| kb * 1024)++ })++ });++ ram_total.map(|t| (t / 5).max(FLOOR)).unwrap_or(FLOOR)++ });++ *BUDGET++}/// Budget for `decoded_stored_cache` (raw decompressed stored sections,/// ~1× the corpus JSON size). Overflow → inserts are refused and thediff --cc engine/crates/xerj-engine/src/lib.rsindex defc7b07b,14d49781f..8886e6bbd--- a/engine/crates/xerj-engine/src/lib.rs+++ b/engine/crates/xerj-engine/src/lib.rs@@@ -54,6 -54,17 +54,20 @@@ pub(crate) fn ingest_pool() -> &'statirayon::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.++ // nice(5): bulk parse/analyze/insert are request-latency++ // sensitive for the WRITER, but under mixed load they were++ // the biggest nice(0) CPU block competing head-to-head with++ // query threads — every flush-storm/bulk burst showed up as++ // a read p95/p99 episode. One CFS step below reads keeps++ // read tails flat while the writer retains far more++ // throughput than the sustained-ingest target (measured++ // 115 k docs/s at nice 0 vs a 40 k floor; nice 5 trades a++ // slice of that for read-tail stability). Flush side-cars++ // are nice(10) (`background_pool`), merges nice(15)++ // (`merge_pool`) — the maintenance ladder stays below both.+ .start_handler(|_| unsafe {- let _ = libc::nice(10);++ let _ = libc::nice(5);+ }).build().expect("failed to build ingest rayon pool")})diff --cc engine/crates/xerj-engine/src/memtable.rsindex 517435ebb,f3b219571..0b244dd4d--- a/engine/crates/xerj-engine/src/memtable.rs+++ b/engine/crates/xerj-engine/src/memtable.rs@@@ -139,6 -139,6 +139,40 @@@ pub struct DocValuespub samples: HashMap<String, Vec<String>>,/// Whether analysis has been performed for each field.pub analyzed: HashMap<String, bool>,++ /// Fields that have EVER carried an array value in this memtable.++ /// The keyword column stores only an array's FIRST scalar, so any++ /// columnar fast path whose brute twin fans out over every element++ /// (terms/cardinality aggs) must bail for these fields. Never++ /// removed on delete — conservative (a stale flag only costs the++ /// fast path, not correctness).++ pub array_fields: FxHashSet<String>,++ /// Incremental per-(field, order) sorted-candidate cache for the++ /// field-sorted match_all memtable arm — see++ /// `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>,++}++++/// State of one incremental per-shard sorted-candidate extraction: the++/// shard's top-`cap` (+boundary ties) by sort key plus up to `cap`++/// missing-key positions, extended by O(new docs) per query instead of++/// re-walking the whole shard (the O(memtable) epoch-memo walk was++/// 15-30 ms/query at a drain-lagged 300-500 k-doc memtable — the++/// residual match_all read-under-write p99 term).++pub struct SortCandCache {++ /// Docs positions `[0, seen_docs)` are already folded in.++ pub seen_docs: usize,++ /// The cap this cache was built for; a larger request rebuilds.++ pub cap: usize,++ /// Candidate pool: (key, docs index). Kept cut to ~2×cap between++ /// queries (page-order sort + boundary-tie truncate on overflow).++ pub top: Vec<(f64, usize)>,++ /// Up to `cap` positions missing the sort key.++ pub missing: Vec<usize>,++ /// A value failed to normalise (or the field carried arrays) — the++ /// shard is ineligible until the next drain resets the memtable.++ pub poisoned: bool,}impl DocValues {@@@ -254,6 -254,6 +288,9 @@@ impl DocValues// Flatten: store the first element (or None for empty arrays).// Each element is treated as a separate value for aggregations,// but for term/range queries we store the first scalar found.++ if !self.array_fields.contains(field) {++ self.array_fields.insert(field.to_string());++ }let first_num = arr.iter().find_map(|v| v.as_f64());let first_str: Option<String> = arr.iter().find_map(|v| match v {Value::String(s) => Some(s.clone()),@@@ -291,6 -291,6 +328,10 @@@/// Remove the entry at `doc_index` from all columns (called on delete).fn remove_at(&mut self, doc_index: usize) {++ // 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();for col in self.numeric.values_mut() {if doc_index < col.len() {col.remove(doc_index);@@@ -464,99 -464,6 +505,75 @@@ impl ShardedFtsMemtableout}- /// Bounded sorted-candidate extraction for a single-numeric-field sort++ /// Bounded sorted-candidate extraction for a single-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++ /// top-`cap` page: the per-shard top-`cap` by sort key (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.++ /// policy). Served INCREMENTALLY per shard via `SortCandCache` —++ /// each query folds in only the docs inserted since the last one —++ /// under the shard write lock (brief: O(new docs)).++ ///++ /// Per-doc key resolution (mirrors how the heap ranks the hit later):++ /// numeric column value when present, else the keyword column value++ /// through `normalize` (the caller passes the memoised date→epoch++ /// normaliser `compute_sort_values` uses per hit — this is what lets++ /// date-STRING `@timestamp` columns take the bounded path), else++ /// missing.+ ///- /// `None` when a shard's column is missing/misaligned (caller falls- /// back to the exact full walk).++ /// `None` when any value is un-normalisable or the field has carried++ /// array values (per-element `mode` semantics need the full walk) —++ /// caller falls back to the exact full walk.+ pub fn sort_candidates_numeric(+ &self,+ field: &str,+ desc: bool,+ cap: usize,++ normalize: &dyn Fn(&str) -> Option<f64>,+ ) -> 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 mut g = s.write();+ 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()));- }++ let (mut top, miss, _) = g.sort_candidates_cached(field, desc, cap, normalize)?;++ cands.append(&mut top);++ for m in miss {++ if missing.len() < cap {++ missing.push(m);++ } else {++ break;+ }+ }+ }+ // 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@@@ -907,6 -814,6 +924,107 @@@n}++ /// Fused columnar bool query across all shards — one position walk per++ /// shard applying every predicate, all under a single read lock per++ /// shard (so positions can't shift between per-child walks under a++ /// concurrent flush drain).++ ///++ /// Returns `(hits, total)` where `hits` holds at most `limit` cloned++ /// `(doc_id, local_idx)` pairs (page materialisation) and `total` is++ /// the EXACT matching-doc count across the whole memtable. `None`++ /// when any predicate's column is missing in a non-empty shard or a++ /// keyword column looks analyzed-text (same conservative bailouts as++ /// `doc_values_term_query` / `doc_values_range_query`) — caller falls++ /// back to the stored-source scan.++ ///++ /// This replaces the per-query `DocsForScan` walk for composite bool++ /// filters, which paid a `doc_matches_query` JSON descent per buffered++ /// doc per query (~1-6 s at a 40-280 k-doc memtable under a sustained++ /// bulk writer — the read-under-write bool collapse).++ pub fn doc_values_bool_query(++ &self,++ preds: &[MemBoolPred],++ limit: usize,++ ) -> Option<(Vec<(String, usize)>, u64)> {++ if preds.is_empty() {++ return None;++ }++ let mut out: Vec<(String, usize)> = Vec::new();++ let mut total: u64 = 0;++ for s in &self.shards {++ let g = s.read();++ if g.doc_count() == 0 {++ continue;++ }++ let room = limit.saturating_sub(out.len());++ let (mut hits, t) = g.doc_values_bool_hits(preds, room)?;++ out.append(&mut hits);++ total += t;++ }++ Some((out, total))++ }++++ /// Columnar per-value counts for one field across all shards, for the++ /// terms/cardinality agg fast paths. Returns `(value → live doc++ /// count, missing_docs)` — value RENDERING matches the brute per-doc++ /// extractor exactly for the shapes this serves (the keyword column++ /// stores strings verbatim, numbers via `Number::to_string`, bools as++ /// "true"/"false" — the same strings `flatten_to_strings` emits).++ ///++ /// `None` (caller falls back to the per-doc JSON extraction walk,++ /// which cost 100-300 ms/query against a drain-lagged 300 k-doc++ /// memtable — the terms-agg read-under-write tail) when equivalence++ /// isn't provable:++ /// - the field has EVER carried an array value in a shard (column++ /// keeps only the first element; brute fans out over all);++ /// - any doc carries `_doc_count` (brute weights buckets by it);++ /// - the caller must additionally gate on plain field names (no++ /// dotted paths / `.keyword` fallbacks — those resolve through++ /// `get_nested_field`, not the column).++ pub fn terms_counts_columnar(++ &self,++ field: &str,++ ) -> Option<(std::collections::HashMap<String, u64>, u64)> {++ let mut counts: std::collections::HashMap<String, u64> =++ std::collections::HashMap::new();++ let mut missing: u64 = 0;++ for s in &self.shards {++ let g = s.read();++ let n = g.doc_count();++ if n == 0 {++ continue;++ }++ if g.doc_values.array_fields.contains(field)++ || g.doc_values.numeric.contains_key("_doc_count")++ || g.doc_values.keyword.contains_key("_doc_count")++ {++ return None;++ }++ match g.doc_values.keyword.get(field) {++ None => {++ // No doc in this shard carries the field as a scalar.++ missing += n as u64;++ }++ Some(col) => {++ let mut present: u64 = 0;++ for v in col.iter() {++ if let Some(s) = v.as_deref() {++ present += 1;++ if let Some(c) = counts.get_mut(s) {++ *c += 1;++ } else {++ counts.insert(s.to_string(), 1);++ }++ }++ }++ // Nones + docs past the column tail are missing.++ missing += n as u64 - present;++ }++ }++ }++ Some((counts, missing))++ }++/// DocValues term query — aggregates hits across all shards./// Returns `Some(Vec<(doc_id, local_idx)>)` if any shard matched./// The `local_idx` is shard-local; callers use the doc_id to@@@ -1171,6 -1078,6 +1289,24 @@@ fn pad_to<T>(col: &mut Vec<Option<T>>,}}++/// One resolved predicate of a `bool { must/filter }` for the fused++/// columnar memtable walk (`doc_values_bool_query`). Built by the engine++/// from Term / Range query nodes; semantics per predicate mirror++/// `doc_values_term_query` / `doc_values_range_query` exactly.++pub enum MemBoolPred {++ Term {++ field: String,++ value: String,++ },++ Range {++ field: String,++ gte: Option<f64>,++ gt: Option<f64>,++ lte: Option<f64>,++ lt: Option<f64>,++ },++}++// ── FtsMemtable ──────────────────────────────────────────────────────────────/// In-memory inverted index for documents awaiting flush.@@@ -1985,6 -1892,6 +2121,195 @@@ impl FtsMemtable// ── Fast DocValues queries ────────────────────────────────────────────────++ /// Incremental per-shard sorted-candidate extraction — see++ /// `ShardedFtsMemtable::sort_candidates_numeric` for the contract and++ /// `SortCandCache` for the state. Returns `(top page-order candidates++ /// as (key, doc_id), missing doc_ids, shard doc count)`; `None` when++ /// the shard is ineligible (un-normalisable value or array-valued++ /// 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,++ field: &str,++ desc: bool,++ cap: usize,++ normalize: &dyn Fn(&str) -> Option<f64>,++ ) -> Option<(Vec<(f64, String)>, Vec<String>, u64)> {++ let n = self.docs.len();++ let cap = cap.max(1);++ if self.doc_values.array_fields.contains(field) {++ return None;++ }++ let key = if desc {++ format!("{field}\u{1}d")++ } else {++ format!("{field}\u{1}a")++ };++ let entry = self++ .doc_values++ .sort_cand_cache++ .entry(key)++ .or_insert_with(|| SortCandCache {++ seen_docs: 0,++ cap,++ top: Vec::new(),++ missing: Vec::new(),++ poisoned: false,++ });++ if entry.poisoned {++ return None;++ }++ if entry.cap < cap || entry.seen_docs > n {++ // Larger page than cached, or the docs vec shrank without a++ // cache clear (defensive) — rebuild from scratch.++ entry.cap = cap;++ entry.seen_docs = 0;++ entry.top.clear();++ entry.missing.clear();++ }++ // Fold in the docs inserted since the last query.++ let ncol = self.doc_values.numeric.get(field);++ let kcol = self.doc_values.keyword.get(field);++ for i in entry.seen_docs..n {++ let nv: Option<f64> = ncol.and_then(|c| c.get(i).copied().flatten());++ let v: Option<f64> = match nv {++ Some(x) => Some(x),++ None => match kcol.and_then(|c| c.get(i)).and_then(|o| o.as_deref()) {++ Some(s) => match normalize(s) {++ Some(x) => Some(x),++ None => {++ entry.poisoned = true;++ return None;++ }++ },++ None => None,++ },++ };++ match v {++ Some(x) => entry.top.push((x, i)),++ None => {++ if entry.missing.len() < entry.cap {++ entry.missing.push(i);++ }++ }++ }++ }++ entry.seen_docs = n;++ // Keep the pool bounded: page-order sort + cut to cap (+boundary++ // ties) once it doubles. Top-cap of (old top-cap ∪ new docs) ==++ // top-cap of all docs, so the incremental cut is exact.++ let cut = |top: &mut Vec<(f64, usize)>, cap: usize| {++ if desc {++ top.sort_unstable_by(|a, b| {++ b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)++ });++ } else {++ top.sort_unstable_by(|a, b| {++ a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)++ });++ }++ let mut keep = top.len().min(cap);++ while keep < top.len() && keep > 0 && top[keep].0 == top[keep - 1].0 {++ keep += 1;++ }++ top.truncate(keep);++ };++ if entry.top.len() > entry.cap.saturating_mul(2).max(64) {++ cut(&mut entry.top, entry.cap);++ }++ // Result view: an exact top-`cap` (+ties) cut of the pool.++ let mut pool = entry.top.clone();++ cut(&mut pool, cap);++ let out: Vec<(f64, String)> = pool++ .into_iter()++ .map(|(v, i)| (v, self.docs[i].doc_id.clone()))++ .collect();++ let miss: Vec<String> = entry++ .missing++ .iter()++ .take(cap)++ .map(|&i| self.docs[i].doc_id.clone())++ .collect();++ Some((out, miss, n as u64))++ }++++ /// Per-shard fused bool walk — see `ShardedFtsMemtable::doc_values_bool_query`.++ ///++ /// Column resolution and per-predicate match semantics mirror the++ /// standalone `doc_values_term_query` (keyword column, case-sensitive++ /// whole value, analyzed-text whitespace bailout) and++ /// `doc_values_range_query` (numeric column, gte/gt/lte/lt) exactly, so++ /// a bool of term+range predicates matches the same doc set the++ /// per-child queries would intersect to — without intermediate++ /// per-child hit vectors.++ pub fn doc_values_bool_hits(++ &self,++ preds: &[MemBoolPred],++ limit: usize,++ ) -> Option<(Vec<(String, usize)>, u64)> {++ enum Col<'a> {++ Kw(&'a Vec<Option<String>>, &'a str),++ Num(&'a Vec<Option<f64>>, Option<f64>, Option<f64>, Option<f64>, Option<f64>),++ }++ let mut cols: Vec<Col<'_>> = Vec::with_capacity(preds.len());++ for p in preds {++ match p {++ MemBoolPred::Term { field, value } => {++ let col = self.doc_values.keyword.get(field.as_str())?;++ // Same analyzed-text bailout as doc_values_term_query.++ if col.iter().any(|v| {++ v.as_deref().map(|s| s.contains(char::is_whitespace)).unwrap_or(false)++ }) {++ return None;++ }++ cols.push(Col::Kw(col, value.as_str()));++ }++ MemBoolPred::Range { field, gte, gt, lte, lt } => {++ let col = self.doc_values.numeric.get(field.as_str())?;++ cols.push(Col::Num(col, *gte, *gt, *lte, *lt));++ }++ }++ }++ let n = self.docs.len();++ let mut out: Vec<(String, usize)> = Vec::new();++ let mut total: u64 = 0;++ 'doc: for idx in 0..n {++ for c in &cols {++ let ok = match c {++ Col::Kw(col, want) => {++ col.get(idx).and_then(|o| o.as_deref()) == Some(*want)++ }++ Col::Num(col, gte, gt, lte, lt) => {++ match col.get(idx).copied().flatten() {++ None => false,++ Some(v) => {++ let pl = match (gte, gt) {++ (Some(b), _) => v >= *b,++ (None, Some(b)) => v > *b,++ (None, None) => true,++ };++ let pu = match (lte, lt) {++ (Some(b), _) => v <= *b,++ (None, Some(b)) => v < *b,++ (None, None) => true,++ };++ pl && pu++ }++ }++ }++ };++ if !ok {++ continue 'doc;++ }++ }++ total += 1;++ if out.len() < limit {++ out.push((self.docs[idx].doc_id.clone(), idx));++ }++ }++ Some((out, total))++ }++/// Fast term query using the keyword column — O(N * string_compare).////// Returns `(doc_id, doc_index)` pairs for documents where the keyword