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(flush): cut flush-finalize CPU 40s -> 16s per 1M docs — c8 bulk 250k -> 289k docs/s (+15.6%)
xerj-org59fdf371e272
diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex 29ec1f316..e8cf662e3 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -3875,6 +3875,7 @@ dependencies = ["lz4_flex","memmap2","roaring",+ "rustc-hash","serde","serde_json","tempfile",diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 4a4336f0e..ab33460bd 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -6094,6 +6094,10 @@ fn build_doc_value_columns<'a>(if field.starts_with('_') {continue;}+ // Lookup-first (`get_mut` before `entry`) so the common case+ // (field already has a column) skips the per-doc-field+ // `field.clone()` String allocation `entry()` would force —+ // ~370k allocs per 31k-doc flush segment on a 12-field corpus.match val {Value::Number(n) => {// Always store as f64 bit-pattern. The agg reader uses@@ -6104,17 +6108,26 @@ fn build_doc_value_columns<'a>(// kind flag yet, so commit to one representation.let Some(f) = n.as_f64() else { continue };let v = f.to_bits() as i64;- let col = numeric.entry(field.clone()).or_default();+ if !numeric.contains_key(field) {+ numeric.insert(field.clone(), Vec::new());+ }+ let col = numeric.get_mut(field).expect("just inserted");pad_with_none(col, doc_idx);col.push(Some(v));}Value::String(s) => {- let col = keyword.entry(field.clone()).or_default();+ if !keyword.contains_key(field) {+ keyword.insert(field.clone(), Vec::new());+ }+ let col = keyword.get_mut(field).expect("just inserted");pad_with_none(col, doc_idx);col.push(Some(s.clone()));}Value::Bool(b) => {- let col = numeric.entry(field.clone()).or_default();+ if !numeric.contains_key(field) {+ numeric.insert(field.clone(), Vec::new());+ }+ let col = numeric.get_mut(field).expect("just inserted");pad_with_none(col, doc_idx);let v = (if *b { 1.0_f64 } else { 0.0_f64 }).to_bits() as i64;col.push(Some(v));@@ -7551,6 +7564,12 @@ async fn do_flush_shard(// Peek BEFORE drain to determine if docs came from raw-bytes or FTS insert.let is_raw_bytes_path = memtable.peek_shard_has_raw_bytes(shard_idx);+ // THROWAWAY prof: per-flush finalize breakdown, gated on XERJ_PROF.+ let prof = std::env::var_os("XERJ_PROF").is_some();+ let t_flush_start = std::time::Instant::now();+ let mut prof_drain_us: u128 = 0;+ let mut prof_prep_us: u128 = 0;+let drained_opt: Option<(Vec<(String,@@ -7559,11 +7578,15 @@ async fn do_flush_shard()>,xerj_storage::index_store::DrainedMemtable,)> = {+ let t_drain = std::time::Instant::now();let raw = if is_raw_bytes_path {memtable.drain_shard_raw(shard_idx)} else {memtable.drain_shard(shard_idx)};+ prof_drain_us = t_drain.elapsed().as_micros();+ let t_prep = std::time::Instant::now();+ let _ = &t_prep;if raw.is_empty() {None} else {@@ -7580,8 +7603,13 @@ async fn do_flush_shard(// CPU per flush — irrelevant against the 50-100 ms segment// write. Always build the drained_fts payload so the FTS// sidecar carries the full doc set.- let drained_fts: Vec<(String, std::collections::HashMap<String, String>, std::sync::Arc<serde_json::Value>)> =- raw.iter()+ // Rayon: the per-doc text-field extraction (plus the JSON+ // parse on the raw-bytes path) is pure and was a ~140 ms+ // SERIAL stretch per 31k-doc flush on the flush task —+ // par_iter preserves order and spreads it across the pool.+ let drained_fts: Vec<(String, std::collections::HashMap<String, String>, std::sync::Arc<serde_json::Value>)> = {+ use rayon::prelude::*;+ raw.par_iter().map(|(_seq, doc_id, arc, bytes)| {// Raw-bytes path stores Value::Null in `arc` and// the actual JSON in `bytes` (skip-parse drain).@@ -7602,7 +7630,8 @@ async fn do_flush_shard(let fields = crate::memtable::extract_text_fields_from(&val);(doc_id.clone(), fields, val)})- .collect();+ .collect()+ };let storage_entries: Vec<xerj_storage::index_store::MemEntry> = raw.into_iter()@@ -7616,6 +7645,7 @@ async fn do_flush_shard(let storage_drained = xerj_storage::index_store::DrainedMemtable {entries: storage_entries,};+ prof_prep_us = t_prep.elapsed().as_micros();Some((drained_fts, storage_drained))}};@@ -7658,6 +7688,7 @@ async fn do_flush_shard(// bench numbers are unaffected.let build_fts = move |meta: &xerj_storage::segment::SegmentMeta| -> xerj_storage::Result<()> {// ── Doc-values side-car (always built) ────────────────────+ let t_dv = std::time::Instant::now();{let columns = build_doc_value_columns(drained_fts.iter().map(|(_id, _fields, src)| Some(src.as_ref())),@@ -7672,6 +7703,9 @@ async fn do_flush_shard(}}}+ let dv_us = t_dv.elapsed().as_micros();+ let mut fts_add_us: u128 = 0;+ let mut fts_finish_us: u128 = 0;// Build FTS sidecars when the drained docs have inverted-index data.if fts_doc_count > 0 {let mut fts_writer = xerj_fts::index::FtsIndexWriter::new(@@ -7682,10 +7716,20 @@ async fn do_flush_shard(for (field_name, cfg) in &field_configs {fts_writer.configure_field(field_name.clone(), cfg.clone());}+ let t_add = std::time::Instant::now();fts_writer.add_documents_parallel(&drained_fts);+ fts_add_us = t_add.elapsed().as_micros();+ let t_fin = std::time::Instant::now();if let Err(e) = fts_writer.finish() {tracing::warn!("flush: FTS build failed: {e}");}+ fts_finish_us = t_fin.elapsed().as_micros();+ }+ if prof {+ eprintln!(+ "XERJ_PROF flush-sidecar docs={} dv_us={} fts_add_us={} fts_finish_us={}",+ fts_doc_count, dv_us, fts_add_us, fts_finish_us+ );}let _ = &segments_dir;let _ = &drained_fts;@@ -7694,6 +7738,7 @@ async fn do_flush_shard(};// Hand the pre-drained storage entries to the finaliser.+ let t_finalize = std::time::Instant::now();let meta = match store.finalize_flush_with_publisher(storage_drained, build_fts)? {Some(m) => m,None => {@@ -7701,6 +7746,17 @@ async fn do_flush_shard(return Ok(());}};+ if prof {+ eprintln!(+ "XERJ_PROF flush-total shard={} docs={} drain_us={} prep_us={} finalize_us={} total_us={}",+ shard_idx,+ fts_doc_count,+ prof_drain_us,+ prof_prep_us,+ t_finalize.elapsed().as_micros(),+ t_flush_start.elapsed().as_micros()+ );+ }info!(segment_id = meta.id.as_str(),diff --git a/engine/crates/xerj-fts/src/index.rs b/engine/crates/xerj-fts/src/index.rsindex b5f4a3cfd..4714afd9b 100644--- a/engine/crates/xerj-fts/src/index.rs+++ b/engine/crates/xerj-fts/src/index.rs@@ -530,13 +530,19 @@ impl FtsIndexWriter {use std::collections::HashMap as StdHashMap;// Column-major reshape: field_name → Vec<(doc_ordinal, text)>.+ // Lookup-first so the common case (field already seen) skips the+ // per-doc-field `field_name.clone()` the `entry()` API forced.let mut per_field: StdHashMap<String, Vec<(u32, &str)>> = StdHashMap::new();for (ord, (_id, fields, _src)) in docs.iter().enumerate() {for (field_name, text) in fields {- per_field- .entry(field_name.clone())- .or_default()- .push((ord as u32, text.as_str()));+ if let Some(v) = per_field.get_mut(field_name) {+ v.push((ord as u32, text.as_str()));+ } else {+ per_field+ .entry(field_name.clone())+ .or_default()+ .push((ord as u32, text.as_str()));+ }}}@@ -697,14 +703,24 @@ impl FtsIndexWriter {.collect();sorted_terms.sort_unstable();+ // Pre-compute per-term (doc_freq, ttf) ONCE. The previous code+ // called `term_stats().find(..)` INSIDE the per-term loop — an+ // O(T²) scan that also re-summed every candidate's ttf on each+ // probe. On numeric-heavy segments (thousands of distinct terms+ // per field, e.g. `latency_ms`/`@timestamp` string tokens) this+ // was the dominant flush-finalize CPU cost.+ let stats_by_term: HashMap<&str, (u32, u64)> = field_data+ .postings+ .term_stats()+ .map(|(t, df, ttf)| (t, (df, ttf)))+ .collect();+for term in &sorted_terms {if let Some((offset, _skip)) = field_data.postings.encode_term(term, &mut post_data) {// Calculate doc_freq and ttf from the writer's internal stats- let (doc_freq, ttf) = field_data- .postings- .term_stats()- .find(|(t, _, _)| *t == term.as_str())- .map(|(_, df, ttf)| (df, ttf))+ let (doc_freq, ttf) = stats_by_term+ .get(term.as_str())+ .copied().unwrap_or((0, 0));let end_offset = post_data.len() as u64;diff --git a/engine/crates/xerj-fts/src/postings.rs b/engine/crates/xerj-fts/src/postings.rsindex 620067d1e..4982cf498 100644--- a/engine/crates/xerj-fts/src/postings.rs+++ b/engine/crates/xerj-fts/src/postings.rs@@ -153,27 +153,44 @@ impl PostingsWriter {/// When the writer was constructed without positions, `position` is/// ignored and no heap growth happens in the `positions` Vec.pub fn add_occurrence(&mut self, term: &str, doc_id: u32, position: u32) {- let list = self.postings.entry(term.to_owned()).or_default();-- if let Some(last) = list.last_mut() {- if last.doc_id == doc_id {- last.term_freq += 1;- if self.store_positions {- last.positions.push(position);+ // Lookup-first to avoid the `term.to_owned()` String allocation+ // that `entry()` forced on EVERY occurrence (13M+ allocs per 1M+ // docs at flush time). Misses (first occurrence of a term) pay+ // one extra BTreeMap descent — postings are Zipf-shaped, so hits+ // dominate.+ if let Some(list) = self.postings.get_mut(term) {+ if let Some(last) = list.last_mut() {+ if last.doc_id == doc_id {+ last.term_freq += 1;+ if self.store_positions {+ last.positions.push(position);+ }+ return;}- return;}+ list.push(RawPosting {+ doc_id,+ term_freq: 1,+ positions: if self.store_positions {+ vec![position]+ } else {+ Vec::new()+ },+ });+ return;}-- list.push(RawPosting {- doc_id,- term_freq: 1,- positions: if self.store_positions {- vec![position]- } else {- Vec::new()- },- });+ self.postings.insert(+ term.to_owned(),+ vec![RawPosting {+ doc_id,+ term_freq: 1,+ positions: if self.store_positions {+ vec![position]+ } else {+ Vec::new()+ },+ }],+ );}/// Returns an iterator over `(term, doc_frequency, total_term_frequency)`diff --git a/engine/crates/xerj-storage/Cargo.toml b/engine/crates/xerj-storage/Cargo.tomlindex 99c40cfb7..b35d8f0ae 100644--- a/engine/crates/xerj-storage/Cargo.toml+++ b/engine/crates/xerj-storage/Cargo.toml@@ -33,6 +33,10 @@ crc32fast = { workspace = true }# so that concurrent bulk ingest batches target different shards.xxhash-rust = { workspace = true }+# FxHash for the stored-codec dict-encode hot maps (trusted keys only —+# field values of the tenant's own documents; no HashDoS surface).+rustc-hash = { workspace = true }+# Compression (WAL payload compression + stored-section codec v2)lz4_flex = { workspace = true }zstd = { workspace = true }diff --git a/engine/crates/xerj-storage/src/doc_values.rs b/engine/crates/xerj-storage/src/doc_values.rsindex ad8a9e3e4..4900e070c 100644--- a/engine/crates/xerj-storage/src/doc_values.rs+++ b/engine/crates/xerj-storage/src/doc_values.rs@@ -366,18 +366,22 @@ impl KeywordColumn {// **lexicographic** order so the on-disk ordinal space is stable// and the FST insert (which requires keys in sorted order) just// walks the same iteration order as the assignment loop.- let mut term_keys: BTreeMap<String, ()> = BTreeMap::new();- for v in &values {- if let Some(s) = v {- term_keys.entry(s.clone()).or_insert(());- }- }- // Now `term_keys` iteration is sorted; ordinal = position in iteration.- let terms: Vec<String> = term_keys.keys().cloned().collect();- let term_to_ord: BTreeMap<String, u32> = terms+ //+ // sort+dedup over borrowed &str instead of the previous+ // `BTreeMap<String, ()>` build, which CLONED every non-null cell+ // (hundreds of thousands of String allocs per 31k-doc flush+ // segment) — only unique terms are cloned now.+ let mut refs: Vec<&str> = values+ .iter()+ .filter_map(|v| v.as_deref())+ .collect();+ refs.sort_unstable();+ refs.dedup();+ let terms: Vec<String> = refs.iter().map(|s| (*s).to_string()).collect();+ let term_to_ord: std::collections::HashMap<&str, u32> = refs.iter().enumerate()- .map(|(i, s)| (s.clone(), i as u32))+ .map(|(i, s)| (*s, i as u32)).collect();// Build FST term → ord (keys must be sorted ascending — they are@@ -399,10 +403,10 @@ impl KeywordColumn {let mut null_bitmap = RoaringBitmap::new();let mut ords = Vec::with_capacity(values.len());let mut per_ord_count: Vec<u32> = vec![0; terms.len()];- for (i, v) in values.into_iter().enumerate() {+ for (i, v) in values.iter().enumerate() {match v {Some(s) => {- let ord = *term_to_ord.get(&s).unwrap();+ let ord = *term_to_ord.get(s.as_str()).unwrap();ords.push(ord);per_ord_count[ord as usize] += 1;}diff --git a/engine/crates/xerj-storage/src/index_store.rs b/engine/crates/xerj-storage/src/index_store.rsindex 687e9fd8c..9ae4eb4da 100644--- a/engine/crates/xerj-storage/src/index_store.rs+++ b/engine/crates/xerj-storage/src/index_store.rs@@ -1029,6 +1029,12 @@ impl IndexStore {return Ok(None);}+ // THROWAWAY prof (XERJ_PROF): finalize phase breakdown.+ let prof = std::env::var_os("XERJ_PROF").is_some();+ let t_fin_start = std::time::Instant::now();+ let mut prof_ser_us: u128 = 0;+ let mut prof_encode_us: u128 = 0;+let doc_count = entries.iter().filter(|e| e.source.is_some()).count() as u64;let min_seq = entries.iter().map(|e| e.seq_no).min().unwrap_or(0);let max_seq = entries.iter().map(|e| e.seq_no).max().unwrap_or(0);@@ -1048,49 +1054,67 @@ impl IndexStore {entries.iter().filter(|e| e.source.is_some()).collect();let has_stored = !live_entries.is_empty();if has_stored {- let mut stored_bytes: Vec<u8> = Vec::with_capacity(live_entries.len() * 512);- stored_bytes.push(b'[');- let mut first = true;- for e in &live_entries {- if !first {- stored_bytes.push(b',');- }- first = false;- stored_bytes.extend_from_slice(br#"{"_id":"#);- serde_json::to_writer(&mut stored_bytes, &e.doc_id)?;- stored_bytes.extend_from_slice(br#","_seq_no":"#);- use std::io::Write;- write!(stored_bytes, "{}", e.seq_no)?;- stored_bytes.extend_from_slice(br#","_source":"#);- if !e.source_bytes.is_empty() {- // Raw bytes available — write directly, skip serde round-trip- stored_bytes.extend_from_slice(&e.source_bytes);- } else if let Some(src) = &e.source {- serde_json::to_writer(&mut stored_bytes, src.as_ref())?;- } else {- stored_bytes.extend_from_slice(b"null");- }- stored_bytes.push(b'}');- }- stored_bytes.push(b']');- // V4 M4.6 — columnar V2 codec: per-column dict+bitpack,- // cross-column determinism (URL→status/bytes collapses to a- // mode table + exception bitmap), fallback to LZ4 on small- // segments. The encoder picks v1 or v2 internally based on- // which is smaller on this segment, so we never write a- // larger file than the pre-M4.6 format.- //// P2.2 — when every live entry carries a parsed `source`// (the HTTP `_bulk` turbo path: engine memtable drained// parsed Values, `source_bytes` empty), feed the encoder the- // Values directly instead of letting it re-parse the JSON- // array we just serialised (~10s background CPU per 1M- // docs). Byte-identical output by contract — see- // `encode_stored_v2_from_values`; assert it live with- // `XERJ_FLUSH_PARITY=1`.+ // Values directly instead of letting it re-parse a JSON+ // array (~10s background CPU per 1M docs).let all_parsed = live_entries.iter().all(|e| e.source_bytes.is_empty() && e.source.is_some());+ let parity =+ std::env::var("XERJ_FLUSH_PARITY").map(|v| v == "1").unwrap_or(false);+ // Flush fast path: on large all-parsed segments skip the+ // canonical JSON-array serialisation entirely (it existed+ // only to feed the v1-LZ4 "never make things worse" size+ // net, which columnar V2 wins on every real segment this+ // size — ~90 ms serialise + ~25 ms LZ4 per 31k-doc flush,+ // ~3 s of background CPU per 1M ingested docs). Small or+ // mixed segments keep the exact legacy behaviour.+ const SKIP_JSON_MIN_DOCS: usize = 4096;+ let skip_json = all_parsed && live_entries.len() >= SKIP_JSON_MIN_DOCS && !parity;++ let t_ser = std::time::Instant::now();+ let stored_bytes: Vec<u8> = if skip_json {+ Vec::new()+ } else {+ let mut stored_bytes: Vec<u8> =+ Vec::with_capacity(live_entries.len() * 512);+ stored_bytes.push(b'[');+ let mut first = true;+ for e in &live_entries {+ if !first {+ stored_bytes.push(b',');+ }+ first = false;+ stored_bytes.extend_from_slice(br#"{"_id":"#);+ serde_json::to_writer(&mut stored_bytes, &e.doc_id)?;+ stored_bytes.extend_from_slice(br#","_seq_no":"#);+ use std::io::Write;+ write!(stored_bytes, "{}", e.seq_no)?;+ stored_bytes.extend_from_slice(br#","_source":"#);+ if !e.source_bytes.is_empty() {+ // Raw bytes available — write directly, skip serde round-trip+ stored_bytes.extend_from_slice(&e.source_bytes);+ } else if let Some(src) = &e.source {+ serde_json::to_writer(&mut stored_bytes, src.as_ref())?;+ } else {+ stored_bytes.extend_from_slice(b"null");+ }+ stored_bytes.push(b'}');+ }+ stored_bytes.push(b']');+ stored_bytes+ };+ // V4 M4.6 — columnar V2 codec: per-column dict+bitpack,+ // cross-column determinism (URL→status/bytes collapses to a+ // mode table + exception bitmap), fallback to LZ4 on small+ // segments. Byte-identical output by contract between the+ // from-values and legacy encoders — see+ // `encode_stored_v2_from_values`; assert it live with+ // `XERJ_FLUSH_PARITY=1`.+ prof_ser_us = t_ser.elapsed().as_micros();+ let t_enc = std::time::Instant::now();let encoded = if all_parsed {let doc_refs: Vec<(&str, u64, &serde_json::Value)> = live_entries.iter()@@ -1102,9 +1126,12 @@ impl IndexStore {)}).collect();- let enc =- crate::stored_codec::encode_stored_v2_from_values(&stored_bytes, &doc_refs);- if std::env::var("XERJ_FLUSH_PARITY").map(|v| v == "1").unwrap_or(false) {+ let enc = if skip_json {+ crate::stored_codec::encode_stored_v2_from_values_nojson(&doc_refs)+ } else {+ crate::stored_codec::encode_stored_v2_from_values(&stored_bytes, &doc_refs)+ };+ if parity {let legacy = crate::stored_codec::encode_stored_v2(&stored_bytes);assert_eq!(legacy, enc,@@ -1122,6 +1149,7 @@ impl IndexStore {} else {crate::stored_codec::encode_stored_v2(&stored_bytes)};+ prof_encode_us = t_enc.elapsed().as_micros();writer.add_section(SectionType::Stored, &encoded)?;}@@ -1133,7 +1161,9 @@ impl IndexStore {writer.add_section(SectionType::Tombstones, &ts_bytes)?;}+ let t_wfin = std::time::Instant::now();let meta = writer.finish(doc_count, min_seq, max_seq)?;+ let prof_wfin_us = t_wfin.elapsed().as_micros();let segment_id = meta.id.clone();// When using an object-store backend, upload the freshly-written segment@@ -1213,9 +1243,12 @@ impl IndexStore {// succeed BEFORE we publish the segment to the snapshot — otherwise// a racing query could open the segment and find the side-cars// (e.g. FTS index) missing, returning wrong results.+ let t_pf = std::time::Instant::now();post_finish(&meta)?;+ let prof_pf_us = t_pf.elapsed().as_micros();// Update version map: point live docs at the new segment+ let t_vm = std::time::Instant::now();let segment_id_arc: std::sync::Arc<str> = std::sync::Arc::from(segment_id.as_str());for entry in &entries {if entry.source.is_some() {@@ -1227,6 +1260,18 @@ impl IndexStore {);}}+ if prof {+ eprintln!(+ "XERJ_PROF finalize docs={} ser_us={} encode_us={} writer_finish_us={} post_finish_us={} vm_us={} total_so_far_us={}",+ doc_count,+ prof_ser_us,+ prof_encode_us,+ prof_wfin_us,+ prof_pf_us,+ t_vm.elapsed().as_micros(),+ t_fin_start.elapsed().as_micros()+ );+ }// Publish the new segment via ArcSwap::rcu so concurrent shard// flushes (one per shard, run in parallel by `Index::flush`)diff --git a/engine/crates/xerj-storage/src/stored_codec.rs b/engine/crates/xerj-storage/src/stored_codec.rsindex 287f14f46..f3c38aed8 100644--- a/engine/crates/xerj-storage/src/stored_codec.rs+++ b/engine/crates/xerj-storage/src/stored_codec.rs@@ -90,6 +90,15 @@ const CROSS_DEP_MIN_DETERMINISM: f64 = 0.90;/// zstd over LZ4-JSON.const DICT_MAX_CARDINALITY: usize = 16_384;+/// Cardinality cap for CROSS_DEP candidate SOURCES. A mode table with+/// thousands of entries (e.g. a `@timestamp` keyword column) is never a+/// good cross-dep source in practice, and probing one costs a full+/// O(rows) tally per (target, source) pair — flush-finalize profiling+/// showed this scan dominating the stored-encode time. Skipping+/// high-cardinality sources only changes which codec a column picks+/// (all codecs decode identically); it never affects correctness.+const CROSS_DEP_MAX_SRC_CARDINALITY: usize = 256;+/// Zstd level used for every per-column / dict / cross-dep / fallback/// payload in V2.///@@ -195,7 +204,7 @@ pub fn encode_stored_v2(stored_docs_json: &[u8]) -> Vec<u8> {}}- encode_v2_columns(num_docs, &col_order, &columns, stored_docs_json)+ encode_v2_columns(num_docs, &col_order, &columns, Some(stored_docs_json))}/// P2.2 — columnar V2 encoder fed directly from already-parsed values.@@ -216,11 +225,59 @@ pub fn encode_stored_v2(stored_docs_json: &[u8]) -> Vec<u8> {pub fn encode_stored_v2_from_values(stored_docs_json: &[u8],docs: &[(&str, u64, &serde_json::Value)],+) -> Vec<u8> {+ encode_stored_v2_from_values_inner(Some(stored_docs_json), docs)+}++/// Flush fast path: encode straight from parsed Values with NO canonical+/// JSON-array serialisation at all. Skips the v1-LZ4 "never make things+/// worse" size net (the columnar form wins on every real segment above a+/// few thousand docs; serialising a ~10 MB JSON array per flush purely to+/// run that comparison was ~3 s of background CPU per 1M ingested docs).+/// On sub-`V2_MIN_DOCS` inputs the canonical JSON array is built here so+/// the v1 fallback output stays byte-identical to the legacy path.+pub fn encode_stored_v2_from_values_nojson(+ docs: &[(&str, u64, &serde_json::Value)],+) -> Vec<u8> {+ encode_stored_v2_from_values_inner(None, docs)+}++/// Serialise the canonical `[{"_id":…,"_seq_no":…,"_source":…}, …]` array+/// exactly as `IndexStore::finalize_flush_with_publisher` builds it.+fn serialize_canonical_stored_json(docs: &[(&str, u64, &serde_json::Value)]) -> Vec<u8> {+ let mut stored_bytes: Vec<u8> = Vec::with_capacity(docs.len() * 512);+ stored_bytes.push(b'[');+ let mut first = true;+ for (id, seq_no, src) in docs {+ if !first {+ stored_bytes.push(b',');+ }+ first = false;+ stored_bytes.extend_from_slice(br#"{"_id":"#);+ let _ = serde_json::to_writer(&mut stored_bytes, id);+ stored_bytes.extend_from_slice(br#","_seq_no":"#);+ let _ = write!(stored_bytes, "{}", seq_no);+ stored_bytes.extend_from_slice(br#","_source":"#);+ let _ = serde_json::to_writer(&mut stored_bytes, src);+ stored_bytes.push(b'}');+ }+ stored_bytes.push(b']');+ stored_bytes+}++fn encode_stored_v2_from_values_inner(+ stored_docs_json: Option<&[u8]>,+ docs: &[(&str, u64, &serde_json::Value)],) -> Vec<u8> {if docs.len() < V2_MIN_DOCS {- return encode_stored_lz4(stored_docs_json);+ return match stored_docs_json {+ Some(json) => encode_stored_lz4(json),+ None => encode_stored_lz4(&serialize_canonical_stored_json(docs)),+ };}let num_docs = docs.len();+ let prof = std::env::var_os("XERJ_PROF").is_some();+ let t_build = std::time::Instant::now();// Synthetic __id / __seq_no columns need owned Values to borrow from.let ids: Vec<serde_json::Value> = docs@@ -233,32 +290,67 @@ pub fn encode_stored_v2_from_values(.collect();let mut col_order: Vec<String> = vec!["__id".into(), "__seq_no".into()];- let mut col_seen: HashMap<String, usize> = HashMap::new();- col_seen.insert("__id".into(), 0);- col_seen.insert("__seq_no".into(), 1);-- for (_, _, src) in docs {- if let Some(obj) = src.as_object() {- for key in obj.keys() {- if !col_seen.contains_key(key) {- col_seen.insert(key.clone(), col_order.len());- col_order.push(key.clone());- }- }- }- }+ let mut col_seen: rustc_hash::FxHashMap<&str, usize> = rustc_hash::FxHashMap::default();+ col_seen.insert("__id", 0);+ col_seen.insert("__seq_no", 1);static NULL: serde_json::Value = serde_json::Value::Null;- let mut columns: Vec<Vec<&serde_json::Value>> =- vec![Vec::with_capacity(num_docs); col_order.len()];++ // Single pass over the docs: discover columns on first sight+ // (backfilling NULLs for rows already consumed) and route each+ // field value straight to its column. The previous two-pass build+ // (discover, then `obj.get(cname)` per column per doc) performed+ // ~2× the map lookups — measured at ~115 ms per 31k-doc flush.+ let mut columns: Vec<Vec<&serde_json::Value>> = vec![+ Vec::with_capacity(num_docs),+ Vec::with_capacity(num_docs),+ ];for (i, (_, _, src)) in docs.iter().enumerate() {columns[0].push(&ids[i]);columns[1].push(&seqs[i]);- let src_obj = src.as_object();- for (cix, cname) in col_order.iter().enumerate().skip(2) {- let val = src_obj.and_then(|m| m.get(cname)).unwrap_or(&NULL);- columns[cix].push(val);+ if let Some(obj) = src.as_object() {+ for (key, val) in obj {+ let cix = match col_seen.get(key.as_str()) {+ // A source field literally named `__id` / `__seq_no`+ // must NOT route into the synthetic columns (the+ // legacy fill loop skipped them too).+ Some(&cix) if cix < 2 => continue,+ Some(&cix) => cix,+ None => {+ let cix = col_order.len();+ // `col_seen` borrows the key from the doc's+ // source object (outlives this fn's locals);+ // `col_order` owns an independent clone.+ col_seen.insert(key.as_str(), cix);+ col_order.push(key.clone());+ let mut fresh: Vec<&serde_json::Value> =+ Vec::with_capacity(num_docs);+ fresh.resize(i, &NULL); // rows before this doc lack the field+ columns.push(fresh);+ cix+ }+ };+ let col = &mut columns[cix];+ // A duplicate key inside one object is impossible+ // (serde Map), so len == i here means every earlier pad+ // is in place — pad any gap, then push this doc's value.+ col.resize(i, &NULL);+ col.push(val);+ }}+ // Columns absent from this doc get padded lazily by the resize+ // above on their next occurrence, and by the final pass below.+ }+ for col in columns.iter_mut() {+ col.resize(num_docs, &NULL);+ }++ if prof {+ eprintln!(+ "XERJ_PROF encode-build docs={} build_us={}",+ num_docs,+ t_build.elapsed().as_micros()+ );}encode_v2_columns(num_docs, &col_order, &columns, stored_docs_json)@@ -266,18 +358,29 @@ pub fn encode_stored_v2_from_values(/// Shared tail of the two V2 entry points: per-column codec selection +/// payload assembly + the v1-LZ4 "never make things worse" size net.+///+/// `stored_docs_json` is the canonical JSON-array serialisation used for+/// the LZ4 size net; pass `None` to skip the net (used by the flush+/// fast path on large segments where the columnar form always wins and+/// serialising a multi-MB JSON array per flush is measurable CPU).fn encode_v2_columns(num_docs: usize,col_order: &[String],columns: &[Vec<&serde_json::Value>],- stored_docs_json: &[u8],+ stored_docs_json: Option<&[u8]>,) -> Vec<u8> {+ // THROWAWAY prof (XERJ_PROF): encode-phase breakdown.+ let prof = std::env::var_os("XERJ_PROF").is_some();+ let t_dict = std::time::Instant::now();+// Build dict-encoded form for each column as a stable side representation.// `dict_encode(col)` returns Some((dict_entries, ids)) where ids[i] is the// 1-based id (0 reserved for null, we add 1 here). Returns None when// the column has non-scalar values or unique-count exceeds DICT_MAX_CARDINALITY.let dict_encoded: Vec<Option<(Vec<serde_json::Value>, Vec<u32>)>> =columns.iter().map(|c| dict_encode_column(c)).collect();+ let dict_us = t_dict.elapsed().as_micros();+ let t_cross = std::time::Instant::now();// For each numeric column, try to find a dict-encoded keyword-like// source column that determines it. First match wins.@@ -289,9 +392,25 @@ fn encode_v2_columns(// float columns fall through to the lossless dict / raw path so// fractional values (e.g. `0.010127`) survive intact.if !col_is_all_integer(col) { return None; }+ // Provable upper bound: with a source of ≤S dict entries, the+ // mode table yields at most one hit-value per source id, so+ // misses ≥ distinct(target) − S and det ≤ 1 − (D − S)/N.+ // If D > N/10 + S the 0.90 determinism gate CANNOT pass for+ // any admissible source — skip the whole O(sources × rows)+ // probe. This is what stops per-row-unique columns like+ // `__seq_no` from paying a full cross-dep scan every flush.+ let target_distinct = dict_encoded[cix]+ .as_ref()+ .map(|(e, _)| e.len())+ .unwrap_or(DICT_MAX_CARDINALITY + 1);+ if target_distinct > num_docs / 10 + CROSS_DEP_MAX_SRC_CARDINALITY {+ return None;+ }best_cross_dep_source(&dict_encoded, cix, col)}).collect();+ let cross_us = t_cross.elapsed().as_micros();+ let t_cols = std::time::Instant::now();// Pick a codec per column and build its payload.let mut col_payloads: Vec<(String, u8, Vec<u8>)> = Vec::with_capacity(col_order.len());@@ -342,11 +461,27 @@ fn encode_v2_columns(out.extend_from_slice(payload);}+ if prof {+ eprintln!(+ "XERJ_PROF encode-cols docs={} cols={} dict_us={} cross_us={} colpay_us={}",+ num_docs,+ col_order.len(),+ dict_us,+ cross_us,+ t_cols.elapsed().as_micros()+ );+ }+// If v1 LZ4 would have been smaller, use it instead. This is the// "never make things worse" safety net that mirrors cz's per-column// best-of-codec picker.- let v1 = encode_stored_lz4(stored_docs_json);- if v1.len() < out.len() { v1 } else { out }+ if let Some(json) = stored_docs_json {+ let v1 = encode_stored_lz4(json);+ if v1.len() < out.len() {+ return v1;+ }+ }+ out}/// Decode a stored section written by any supported codec version.@@ -512,22 +647,62 @@ fn all_scalar_dict_entries(entries: &[serde_json::Value]) -> bool {////// Returns `None` if the column contains any non-scalar (object/array) value/// or if the unique-count explodes beyond the cap.-fn dict_encode_column<B: std::borrow::Borrow<serde_json::Value>>(- col: &[B],+/// Typed dictionary key — replaces the old `v.to_string()` keying, which+/// allocated a fresh String per CELL (13 columns × 31k rows ≈ 400k allocs+/// per flush segment). Strings are borrowed straight from the column;+/// numbers are keyed by their exact serde variant so `1`, `1.0` and+/// `"1"` stay distinct exactly as their serialized forms did.+#[derive(PartialEq, Eq, Hash)]+enum DictKey<'a> {+ Str(&'a str),+ PosInt(u64),+ NegInt(i64),+ Float(u64), // f64 bit pattern+ Bool(bool),+}++fn dict_key(v: &serde_json::Value) -> Option<DictKey<'_>> {+ match v {+ serde_json::Value::String(s) => Some(DictKey::Str(s.as_str())),+ serde_json::Value::Bool(b) => Some(DictKey::Bool(*b)),+ serde_json::Value::Number(n) => {+ if let Some(u) = n.as_u64() {+ Some(DictKey::PosInt(u))+ } else if let Some(i) = n.as_i64() {+ Some(DictKey::NegInt(i))+ } else {+ n.as_f64().map(|f| DictKey::Float(f.to_bits()))+ }+ }+ _ => None,+ }+}++fn dict_encode_column<'a, B: std::borrow::Borrow<serde_json::Value>>(+ col: &'a [B],) -> Option<(Vec<serde_json::Value>, Vec<u32>)> {- let mut map: HashMap<String, u32> = HashMap::new();+ // FxHashMap: this map sees one lookup per row per column at flush+ // time (~400k per 31k-doc segment); SipHash was measurable there and+ // the keys are the tenant's own field values (no HashDoS surface).+ let mut map: rustc_hash::FxHashMap<DictKey<'a>, u32> = rustc_hash::FxHashMap::default();let mut entries: Vec<serde_json::Value> = Vec::new();let mut ids: Vec<u32> = Vec::with_capacity(col.len());+ // Early abort for id-like columns: if the first `UNIQUE_PREFIX_ABORT`+ // non-null values are ALL distinct (`__id` on auto-id bulk, UUIDs…),+ // no dictionary ≤ DICT_MAX_CARDINALITY can emerge from ≤ 65k rows+ // worth scanning — bail before cloning thousands of entries. A+ // column that merely starts diverse (e.g. timestamps) repeats within+ // this window and is unaffected.+ const UNIQUE_PREFIX_ABORT: usize = 8_192;+ let mut non_null = 0usize;for v in col {let v = v.borrow();if v.is_null() {ids.push(u32::MAX); // resolved to "null id" latercontinue;}- if v.is_object() || v.is_array() { return None; }- // Key values by their serialized form — fast enough, correct for- // string / number / bool.- let k = v.to_string();+ non_null += 1;+ let Some(k) = dict_key(v) else { return None }; // object / arrayif let Some(&id) = map.get(&k) {ids.push(id);} else {@@ -536,8 +711,17 @@ fn dict_encode_column<B: std::borrow::Borrow<serde_json::Value>>(map.insert(k, id);ids.push(id);}- if entries.len() > DICT_MAX_CARDINALITY * 4 {- return None; // way above the payload-worthy cap+ if entries.len() >= UNIQUE_PREFIX_ABORT && entries.len() == non_null {+ return None;+ }+ if entries.len() > DICT_MAX_CARDINALITY {+ // Above the payload cap: both the DICT_BITPACK pick in+ // `encode_v2_columns` and the cross-dep source filter reject+ // dictionaries larger than DICT_MAX_CARDINALITY, so building+ // one bigger than that (the old cap was 4×) was pure wasted+ // work — e.g. the per-doc-unique `__id` column cloned ~31k+ // Values per flush segment only to be discarded.+ return None;}}// Replace u32::MAX with the reserved-null id.@@ -561,40 +745,65 @@ fn best_cross_dep_source<B: std::borrow::Borrow<serde_json::Value>>(let (entries, ids) = match de { Some(e) => e, None => continue };if !all_scalar_dict_entries(entries) { continue; }if entries.len() < 2 { continue; } // constant source: useless- if entries.len() > DICT_MAX_CARDINALITY { continue; }-- // Build mode table: mode_values[src_id] = most frequent target int- let mut mode_tally: HashMap<u32, HashMap<i64, usize>> = HashMap::new();- for (row, t_val) in target_col.iter().enumerate() {- let t_val = t_val.borrow();- let Some(t) = t_val.as_i64().or_else(|| t_val.as_f64().map(|f| f as i64)) else { continue };- let sid = ids[row];- *mode_tally.entry(sid).or_default().entry(t).or_insert(0) += 1;- }- // Count deterministic rows: row matches mode[src_id].- let mut mode_pick: HashMap<u32, i64> = HashMap::new();- for (sid, tally) in &mode_tally {- if let Some((v, _)) = tally.iter().max_by_key(|(_, c)| *c) {- mode_pick.insert(*sid, *v);+ if entries.len() > CROSS_DEP_MAX_SRC_CARDINALITY { continue; }++ // Sampled prefilter: tally only the first `SAMPLE` rows first.+ // Cross-dep is a codec CHOICE — a false negative here just means+ // the column keeps its dict/zstd codec (identical decode), so a+ // cheap sample with a slightly relaxed threshold is safe. The+ // full O(rows) tally (below) runs only for sources that pass,+ // which cuts the per-flush cross-dep probe from ~110 ms to ~5 ms+ // on non-deterministic corpora (the common case).+ const SAMPLE: usize = 2048;+ const SAMPLE_SLACK: f64 = 0.05;+ if target_col.len() > SAMPLE * 2 {+ if let Some(det) = cross_dep_determinism(&target_col[..SAMPLE], ids) {+ if det < CROSS_DEP_MIN_DETERMINISM - SAMPLE_SLACK {+ continue;+ }+ } else {+ continue;}}- let mut hits = 0usize;- let mut total_numeric = 0usize;- for (row, t_val) in target_col.iter().enumerate() {- let t_val = t_val.borrow();- let Some(t) = t_val.as_i64().or_else(|| t_val.as_f64().map(|f| f as i64)) else { continue };- total_numeric += 1;- if mode_pick.get(&ids[row]) == Some(&t) { hits += 1; }- }- if total_numeric == 0 { continue; }- let det = hits as f64 / total_numeric as f64;- if det >= CROSS_DEP_MIN_DETERMINISM {- return Some(src_ix);++ // Full single-pass tally. The number of rows matching their+ // source-id's mode equals Σ_sid max_count(tally[sid]) — no second+ // row scan needed (the old two-pass version re-walked every row+ // against `mode_pick`, doubling the cost for an identical result).+ match cross_dep_determinism(target_col, ids) {+ Some(det) if det >= CROSS_DEP_MIN_DETERMINISM => return Some(src_ix),+ _ => {}}}None}+/// Fraction of numeric rows whose value equals the mode of their source+/// dict id (`None` when no numeric rows). Shared by the sampled+/// prefilter and the full pass in [`best_cross_dep_source`].+fn cross_dep_determinism<B: std::borrow::Borrow<serde_json::Value>>(+ target_col: &[B],+ ids: &[u32],+) -> Option<f64> {+ let mut mode_tally: HashMap<u32, HashMap<i64, usize>> = HashMap::new();+ let mut total_numeric = 0usize;+ for (row, t_val) in target_col.iter().enumerate() {+ let t_val = t_val.borrow();+ let Some(t) = t_val.as_i64().or_else(|| t_val.as_f64().map(|f| f as i64)) else { continue };+ total_numeric += 1;+ let sid = ids[row];+ *mode_tally.entry(sid).or_default().entry(t).or_insert(0) += 1;+ }+ if total_numeric == 0 {+ return None;+ }+ let hits: usize = mode_tally+ .values()+ .map(|tally| tally.values().copied().max().unwrap_or(0))+ .sum();+ Some(hits as f64 / total_numeric as f64)+}+fn try_encode_constant<B: std::borrow::Borrow<serde_json::Value>>(col: &[B]) -> Option<Vec<u8>> {let first = col.iter().map(|v| v.borrow()).find(|v| !v.is_null())?;if col.iter().all(|v| { let v = v.borrow(); v == first || v.is_null() })@@ -1147,6 +1356,53 @@ mod tests {}}+ /// The single-pass column build discovers columns lazily and must+ /// backfill NULLs for rows consumed before a field first appears —+ /// exercise a column whose first occurrence is deep into the batch,+ /// plus a source field named `__id` (must not clobber the synthetic+ /// id column), and assert byte parity with the legacy two-pass+ /// parse-based encoder.+ #[test]+ fn v2_from_values_late_discovered_column_parity() {+ let mut docs: Vec<(String, u64, serde_json::Value)> = Vec::new();+ for i in 0..1500usize {+ let mut src = json!({+ "kind": format!("k{}", i % 5),+ "n": i as i64,+ });+ if i >= 700 {+ // late-discovered column → backfill path+ src.as_object_mut().unwrap().insert("late".into(), json!(i % 9));+ }+ if i % 13 == 0 {+ // reserved-name source field → must be ignored+ src.as_object_mut().unwrap().insert("__id".into(), json!("evil"));+ }+ docs.push((format!("id-{}", i), 5_000 + i as u64, src));+ }+ let stored = stored_json_like_flush(&docs);+ let refs: Vec<(&str, u64, &serde_json::Value)> = docs+ .iter()+ .map(|(id, seq, src)| (id.as_str(), *seq, src))+ .collect();++ let legacy = encode_stored_v2(&stored);+ let from_values = encode_stored_v2_from_values(&stored, &refs);+ assert_eq!(legacy, from_values, "late-column build diverged from legacy");++ // And the no-JSON fast path must produce the same v2 bytes when+ // v2 wins the size net (it does on this shape).+ let nojson = encode_stored_v2_from_values_nojson(&refs);+ assert_eq!(from_values, nojson, "nojson fast path diverged");++ let decoded = decode_stored(&from_values).unwrap();+ let round: Vec<serde_json::Value> = serde_json::from_slice(&decoded).unwrap();+ assert_eq!(round.len(), docs.len());+ assert!(round[0]["_source"].get("late").map(|v| v.is_null()).unwrap_or(true));+ assert_eq!(round[0]["_id"].as_str().unwrap(), "id-0");+ assert_eq!(round[750]["_source"]["late"], json!(750 % 9));+ }+/// Below `V2_MIN_DOCS` both entry points must produce the identical/// v1 LZ4 fallback bytes.#[test]