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
style: rustfmt + clippy pass across the batch-12b surface
xerj-org2735a05b4f94
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 7943512e0..7ed9e13a1 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -4111,11 +4111,6 @@ fn is_lone_doc_sort(v: &Value) -> bool {}}-/// Parse ES sort spec into a Vec<SortField>.-///-/// ES sort can be:-/// - `"_score"` / `"_doc"` (string)-/// - `[{"field": "asc"}, {"field": {"order": "desc", "missing": "_last"}}]`/// Widen an f32 score to the f64 that prints as the SHORTEST f32 repr —/// ES serializes scores as Java floats (`448.4`), while a raw `as f64`/// bit-widening prints `448.3999938964844` on the wire. Order-preserving@@ -4124,6 +4119,11 @@ fn score_wire(v: f32) -> f64 {v.to_string().parse().unwrap_or(v as f64)}+/// Parse ES sort spec into a Vec<SortField>.+///+/// ES sort can be:+/// - `"_score"` / `"_doc"` (string)+/// - `[{"field": "asc"}, {"field": {"order": "desc", "missing": "_last"}}]`fn parse_sort(sort_val: &Value) -> Vec<xerj_query::sort::SortField> {use xerj_query::sort::{SortField, SortMissing, SortMode, SortOrder};let mut fields: Vec<SortField> = Vec::new();@@ -6822,25 +6822,26 @@ pub async fn search(// sort at parse time): live-verified on ES 8.13.4, `[{"_score":"asc"}]`// and `["_score","_doc"]` both return `max_score: null` while their// hits still carry `_score` values.- let sort_tracks_scores =- search_req.sort.is_empty() || body.track_scores.unwrap_or(false);+ let sort_tracks_scores = search_req.sort.is_empty() || body.track_scores.unwrap_or(false);let max_score = if sort_tracks_scores {let explicit_field_sort =!search_req.sort.is_empty() && search_req.sort.iter().any(|s| !s.is_score());if explicit_field_sort {// Prefer the per-index pre-collapse population max; fall back to the// (possibly collapsed/paged) merged hit set when unavailable.- merged_population_max.map(|m| score_wire(m as f32)).or_else(|| {- merged_hits- .iter()- .map(|(_, h)| score_wire(h.score))- .fold(None, |acc: Option<f64>, s| {- Some(match acc {- Some(m) if m >= s => m,- _ => s,- })- })- })+ merged_population_max+ .map(|m| score_wire(m as f32))+ .or_else(|| {+ merged_hits.iter().map(|(_, h)| score_wire(h.score)).fold(+ None,+ |acc: Option<f64>, s| {+ Some(match acc {+ Some(m) if m >= s => m,+ _ => s,+ })+ },+ )+ })} else {merged_hits.first().map(|(_, h)| score_wire(h.score))}diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rsindex 318c810de..5a068480a 100644--- a/engine/crates/xerj-autoindex/src/catalog.rs+++ b/engine/crates/xerj-autoindex/src/catalog.rs@@ -77,8 +77,7 @@ pub struct DatasetDocInput<'a> {pub fn dataset_doc(inp: &DatasetDocInput) -> (String, Value) {let id = format!("ds:{}", inp.pd.slug);- let fields_json =- serde_json::to_string(&inp.pd.specs).unwrap_or_else(|_| "[]".into());+ let fields_json = serde_json::to_string(&inp.pd.specs).unwrap_or_else(|_| "[]".into());let doc = json!({"doc_kind": "dataset","slug": inp.pd.slug,@@ -102,6 +101,7 @@ pub fn dataset_doc(inp: &DatasetDocInput) -> (String, Value) {(id, doc)}+#[allow(clippy::too_many_arguments)] // 1:1 with the file-status doc's fieldspub fn file_doc(file_key: &str,path: &str,@@ -139,9 +139,7 @@ pub fn build_sample_queries(pd: &PlanDataset, correlations: &[KeyCorr]) -> Vec<V// 1. exact filter: keyword field, low-ish cardinality, best coveragelet filter_field = specs.iter()- .filter(|s| {- s.es_type == "keyword" && s.cardinality_est >= 2 && !s.examples.is_empty()- })+ .filter(|s| s.es_type == "keyword" && s.cardinality_est >= 2 && !s.examples.is_empty()).max_by(|a, b| {let score = |s: &crate::infer::FieldSpec| {let card_bonus = if s.cardinality_est <= 1000 { 1.0 } else { 0.0 };@@ -161,9 +159,7 @@ pub fn build_sample_queries(pd: &PlanDataset, correlations: &[KeyCorr]) -> Vec<V// 2. full textlet text_field = specs.iter()- .filter(|s| {- (s.es_type == "text" || s.es_type == "semantic_text") && !s.examples.is_empty()- })+ .filter(|s| (s.es_type == "text" || s.es_type == "semantic_text") && !s.examples.is_empty()).max_by(|a, b| a.avg_len.partial_cmp(&b.avg_len).unwrap());if let Some(f) = text_field {let word = f@@ -285,7 +281,11 @@ pub fn render_map(g("record_count"),g("file_count"),g("formats"),- if g("time_field").is_empty() { "—".into() } else { g("time_field") },+ if g("time_field").is_empty() {+ "—".into()+ } else {+ g("time_field")+ },range));}@@ -340,7 +340,10 @@ pub fn render_map());}if specs.len() > 40 {- s.push_str(&format!("| … {} more fields | | | | | |\n", specs.len() - 40));+ s.push_str(&format!(+ "| … {} more fields | | | | | |\n",+ specs.len() - 40+ ));}s.push('\n');}@@ -349,10 +352,16 @@ pub fn render_map(if let Some(qs) = d.get("sample_queries_json").and_then(|v| v.as_array()) {s.push_str("Ready-to-send queries:\n\n");for q in qs {- if let Some(qv) = q.as_str().and_then(|t| serde_json::from_str::<Value>(t).ok()) {+ if let Some(qv) = q+ .as_str()+ .and_then(|t| serde_json::from_str::<Value>(t).ok())+ {let title = qv.get("title").map(pretty_val).unwrap_or_default();- s.push_str(&format!("**{}** — `{}`\n\n", title,- qv.get("request").map(pretty_val).unwrap_or_default()));+ s.push_str(&format!(+ "**{}** — `{}`\n\n",+ title,+ qv.get("request").map(pretty_val).unwrap_or_default()+ ));if let Some(body) = qv.get("body") {s.push_str("```json\n");s.push_str(&serde_json::to_string_pretty(body).unwrap_or_default());@@ -465,7 +474,13 @@ fn pretty_val(v: &Value) -> String {/// make the rendered map read as a binary file).fn clean(s: &str) -> String {s.chars()- .map(|c| if c.is_control() && c != '\n' && c != '\t' { '\u{FFFD}' } else { c })+ .map(|c| {+ if c.is_control() && c != '\n' && c != '\t' {+ '\u{FFFD}'+ } else {+ c+ }+ }).collect()}diff --git a/engine/crates/xerj-autoindex/src/coerce.rs b/engine/crates/xerj-autoindex/src/coerce.rsindex 81f5ddbb9..ab640b997 100644--- a/engine/crates/xerj-autoindex/src/coerce.rs+++ b/engine/crates/xerj-autoindex/src/coerce.rs@@ -17,7 +17,7 @@ pub enum Coerce {}pub fn enc_from_str(s: &str) -> Option<DateEnc> {- for e in [+ [DateEnc::Rfc3339,DateEnc::IsoNaive,DateEnc::SpaceNaive,@@ -26,12 +26,9 @@ pub fn enc_from_str(s: &str) -> Option<DateEnc> {DateEnc::Rfc2822,DateEnc::EpochMillis,DateEnc::EpochSeconds,- ] {- if e.as_str() == s {- return Some(e);- }- }- None+ ]+ .into_iter()+ .find(|e| e.as_str() == s)}/// Build the coercion plan from the (serialized) field specs.@@ -78,10 +75,7 @@ fn coerce_value(v: &Value, kind: &Coerce) -> Option<Value> {return None;}if let Value::Array(a) = v {- let out: Vec<Value> = a- .iter()- .filter_map(|e| coerce_value(e, kind))- .collect();+ let out: Vec<Value> = a.iter().filter_map(|e| coerce_value(e, kind)).collect();return if out.is_empty() {None} else {@@ -133,9 +127,7 @@ fn coerce_value(v: &Value, kind: &Coerce) -> Option<Value> {Value::String(s) => Some(Value::String(s.clone())),Value::Number(n) => Some(Value::String(n.to_string())),Value::Bool(b) => Some(Value::String(b.to_string())),- Value::Object(m) => Some(Value::String(- serde_json::to_string(m).unwrap_or_default(),- )),+ Value::Object(m) => Some(Value::String(serde_json::to_string(m).unwrap_or_default())),_ => None,},}diff --git a/engine/crates/xerj-autoindex/src/correlate.rs b/engine/crates/xerj-autoindex/src/correlate.rsindex efb503d43..b966897e5 100644--- a/engine/crates/xerj-autoindex/src/correlate.rs+++ b/engine/crates/xerj-autoindex/src/correlate.rs@@ -121,12 +121,8 @@ pub fn key_overlaps(cands: &[Candidate]) -> Vec<KeyCorr> {} else {"moderate"};- let mut examples: Vec<String> = a- .values- .intersection(&b.values)- .take(20)- .cloned()- .collect();+ let mut examples: Vec<String> =+ a.values.intersection(&b.values).take(20).cloned().collect();examples.sort();out.push(KeyCorr {a_slug: a.slug.clone(),@@ -211,7 +207,12 @@ pub struct TimeSeries {}/// Fetch a day (or hour when span < 7d) histogram for a dataset time field.-pub fn fetch_histogram(es: &Es, slug: &str, index: &str, field: &str) -> Result<Option<TimeSeries>> {+pub fn fetch_histogram(+ es: &Es,+ slug: &str,+ index: &str,+ field: &str,+) -> Result<Option<TimeSeries>> {let fetch = |interval: &str| -> Result<Vec<(i64, u64)>> {let body = json!({"size":0,"aggs":{"t":{"date_histogram":{"field": field, "calendar_interval": interval}}}});@@ -220,12 +221,7 @@ pub fn fetch_histogram(es: &Es, slug: &str, index: &str, field: &str) -> Result<.and_then(|b| b.as_array()).map(|arr| {arr.iter()- .filter_map(|b| {- Some((- b.get("key")?.as_i64()?,- b.get("doc_count")?.as_u64()?,- ))- })+ .filter_map(|b| Some((b.get("key")?.as_i64()?, b.get("doc_count")?.as_u64()?))).collect()}).unwrap_or_default())@@ -308,7 +304,7 @@ pub fn time_alignment(series: &[TimeSeries]) -> Vec<Value> {} else {None};- peaks.sort_by(|x, y| y.0.cmp(&x.0));+ peaks.sort_by_key(|p| std::cmp::Reverse(p.0));let top: Vec<String> = peaks.iter().take(3)diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rsindex 0eda1cdc9..1eb2ff1a6 100644--- a/engine/crates/xerj-autoindex/src/esclient.rs+++ b/engine/crates/xerj-autoindex/src/esclient.rs@@ -86,7 +86,9 @@ impl Es {return Ok(());}let text = resp.text().unwrap_or_default();- if text.contains("resource_already_exists") || status.as_u16() == 400 && text.contains("exists") {+ if text.contains("resource_already_exists")+ || status.as_u16() == 400 && text.contains("exists")+ {return Ok(());}Err(anyhow!("PUT /{index} failed: {status} {text}"))@@ -122,8 +124,9 @@ impl Es {if op.get("error").is_some() {item_errors += 1;if first_error.is_none() {- first_error =- Some(op["error"].to_string().chars().take(300).collect());+ first_error = Some(+ op["error"].to_string().chars().take(300).collect(),+ );}}}diff --git a/engine/crates/xerj-autoindex/src/extract/html.rs b/engine/crates/xerj-autoindex/src/extract/html.rsindex e1c1d61b1..68c6ef86e 100644--- a/engine/crates/xerj-autoindex/src/extract/html.rs+++ b/engine/crates/xerj-autoindex/src/extract/html.rs@@ -4,9 +4,7 @@//! one record per row with header-derived field names; otherwise one//! document record {title, headings, body}.-use super::{- emit_document, sanitize_field_name, ExtractStats, RawRecord, Sink, MAX_WHOLE_FILE,-};+use super::{emit_document, sanitize_field_name, ExtractStats, RawRecord, Sink, MAX_WHOLE_FILE};use anyhow::Result;use serde_json::{Map, Value};use std::path::Path;@@ -104,7 +102,9 @@ fn stem_of(path: &Path) -> String {fn looks_like_header(row: &[String]) -> bool {let numericish = |s: &str| {let t = s.trim();- !t.is_empty() && t.chars().all(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-'))+ !t.is_empty()+ && t.chars()+ .all(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-'))};!row.is_empty() && row.iter().all(|c| !numericish(c) && !c.trim().is_empty())}@@ -123,7 +123,10 @@ fn dominant_table(doc: &Doc) -> Option<(&Vec<Vec<String>>, bool)> {if consistent * 10 < rows.len() * 9 {continue;}- if best.map(|b| rows.len() > doc.tables[b].len()).unwrap_or(true) {+ if best+ .map(|b| rows.len() > doc.tables[b].len())+ .unwrap_or(true)+ {best = Some(i);}}@@ -194,7 +197,10 @@ fn parse(html: &str) -> Doc {if bytes[i] == b'<' {// comment?if html[i..].starts_with("<!--") {- i = html[i..].find("-->").map(|p| i + p + 3).unwrap_or(bytes.len());+ i = html[i..]+ .find("-->")+ .map(|p| i + p + 3)+ .unwrap_or(bytes.len());continue;}// parse tag@@ -263,7 +269,8 @@ fn parse(html: &str) -> Doc {cur_row.push(c);}if !cur_row.is_empty() {- table_header_flags.push(cur_row_th.iter().all(|&b| b) && !cur_row_th.is_empty());+ table_header_flags+ .push(cur_row_th.iter().all(|&b| b) && !cur_row_th.is_empty());cur_table.push(std::mem::take(&mut cur_row));}if !cur_table.is_empty() {@@ -278,7 +285,8 @@ fn parse(html: &str) -> Doc {cur_row.push(c);}if !cur_row.is_empty() {- table_header_flags.push(cur_row_th.iter().all(|&b| b) && !cur_row_th.is_empty());+ table_header_flags+ .push(cur_row_th.iter().all(|&b| b) && !cur_row_th.is_empty());cur_table.push(std::mem::take(&mut cur_row));}cur_row_th.clear();@@ -290,17 +298,24 @@ fn parse(html: &str) -> Doc {cur_row_th.push(name == "th");cur_cell = Some(String::new());}- (false, "br") | (false, "p") | (true, "p") | (false, "div") | (true, "div")- | (false, "li") | (true, "tr") => {- if !doc.body.ends_with('\n') && !doc.body.is_empty() {- doc.body.push('\n');- }+ (false, "br")+ | (false, "p")+ | (true, "p")+ | (false, "div")+ | (true, "div")+ | (false, "li")+ | (true, "tr")+ if !doc.body.ends_with('\n') && !doc.body.is_empty() =>+ {+ doc.body.push('\n');}_ => {}}i = tag_end + 1;} else {- let next = memchr::memchr(b'<', &bytes[i..]).map(|p| i + p).unwrap_or(bytes.len());+ let next = memchr::memchr(b'<', &bytes[i..])+ .map(|p| i + p)+ .unwrap_or(bytes.len());cur_text.push_str(&decode_entities(&html[i..next]));i = next;}diff --git a/engine/crates/xerj-autoindex/src/extract/json.rs b/engine/crates/xerj-autoindex/src/extract/json.rsindex ae0a76216..65c6eea12 100644--- a/engine/crates/xerj-autoindex/src/extract/json.rs+++ b/engine/crates/xerj-autoindex/src/extract/json.rs@@ -35,10 +35,11 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {let mut best: Option<(String, usize)> = None;for (k, vv) in obj.iter() {if let Value::Array(a) = vv {- if a.len() >= 2 && a.iter().all(|e| e.is_object()) {- if best.as_ref().map(|(_, n)| a.len() > *n).unwrap_or(true) {- best = Some((k.clone(), a.len()));- }+ if a.len() >= 2+ && a.iter().all(|e| e.is_object())+ && best.as_ref().map(|(_, n)| a.len() > *n).unwrap_or(true)+ {+ best = Some((k.clone(), a.len()));}}}diff --git a/engine/crates/xerj-autoindex/src/extract/jsonl.rs b/engine/crates/xerj-autoindex/src/extract/jsonl.rsindex f348b09b2..97b9464c7 100644--- a/engine/crates/xerj-autoindex/src/extract/jsonl.rs+++ b/engine/crates/xerj-autoindex/src/extract/jsonl.rs@@ -84,7 +84,14 @@ pub fn read_capped_line(r: &mut dyn std::io::BufRead, out: &mut Vec<u8>) -> Resu}fn trim_ws(b: &[u8]) -> &[u8] {- let start = b.iter().position(|c| !c.is_ascii_whitespace()).unwrap_or(b.len());- let end = b.iter().rposition(|c| !c.is_ascii_whitespace()).map(|i| i + 1).unwrap_or(start);+ let start = b+ .iter()+ .position(|c| !c.is_ascii_whitespace())+ .unwrap_or(b.len());+ let end = b+ .iter()+ .rposition(|c| !c.is_ascii_whitespace())+ .map(|i| i + 1)+ .unwrap_or(start);&b[start..end]}diff --git a/engine/crates/xerj-autoindex/src/extract/logs.rs b/engine/crates/xerj-autoindex/src/extract/logs.rsindex f47a47995..bf769b022 100644--- a/engine/crates/xerj-autoindex/src/extract/logs.rs+++ b/engine/crates/xerj-autoindex/src/extract/logs.rs@@ -139,18 +139,17 @@ fn parse_line(line: &str, kind: Kind) -> Option<Map<String, Value>> {/// raw message is kept.fn lift_kv(msg: &str, m: &mut Map<String, Value>) {let t = templates();- let pairs: Vec<(String, String)> = t- .kv- .captures_iter(msg)- .map(|c| {- let k = c.get(1).unwrap().as_str().to_string();- let mut v = c.get(2).unwrap().as_str().to_string();- if v.starts_with('"') && v.ends_with('"') && v.len() >= 2 {- v = v[1..v.len() - 1].replace("\\\"", "\"");- }- (k, v)- })- .collect();+ let pairs: Vec<(String, String)> =+ t.kv.captures_iter(msg)+ .map(|c| {+ let k = c.get(1).unwrap().as_str().to_string();+ let mut v = c.get(2).unwrap().as_str().to_string();+ if v.starts_with('"') && v.ends_with('"') && v.len() >= 2 {+ v = v[1..v.len() - 1].replace("\\\"", "\"");+ }+ (k, v)+ })+ .collect();if pairs.len() >= 2 {let mut message_set = false;for (k, v) in pairs {diff --git a/engine/crates/xerj-autoindex/src/extract/sqldump.rs b/engine/crates/xerj-autoindex/src/extract/sqldump.rsindex 314785dd2..57ceb96ae 100644--- a/engine/crates/xerj-autoindex/src/extract/sqldump.rs+++ b/engine/crates/xerj-autoindex/src/extract/sqldump.rs@@ -97,15 +97,11 @@ pub fn extract(if let Some((t, cols)) = parse_insert_head(&head) {cur_table = t;cur_cols = if cols.is_empty() {- tables- .get(&cur_table)- .cloned()- .unwrap_or_default()+ tables.get(&cur_table).cloned().unwrap_or_default()} else {cols};- let e =- stmt_ord.entry(cur_table.clone()).or_insert(0);+ let e = stmt_ord.entry(cur_table.clone()).or_insert(0);cur_stmt = *e;*e += 1;tuple_ord = 0;@@ -428,7 +424,14 @@ fn process_statement_head(head: &str, tables: &mut HashMap<String, Vec<String>>)}parts.push(part);const NON_COLS: [&str; 8] = [- "primary", "key", "unique", "constraint", "foreign", "index", "check", "fulltext",+ "primary",+ "key",+ "unique",+ "constraint",+ "foreign",+ "index",+ "check",+ "fulltext",];for p in parts {let p = p.trim();diff --git a/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs b/engine/crates/xerj-autoindex/src/extract/sqlite_x.rsindex 00b70eb41..6187cf063 100644--- a/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs+++ b/engine/crates/xerj-autoindex/src/extract/sqlite_x.rs@@ -63,8 +63,7 @@ pub fn extract(path: &Path, per_table_limit: Option<u64>, sink: Sink) -> Result<let start_col = if has_rowid { 1 } else { 0 };let rowid: Option<i64> = if has_rowid { row.get(0).ok() } else { None };let mut fields = Map::new();- for i in start_col..ncols {- let name = &col_names[i];+ for (i, name) in col_names.iter().enumerate().take(ncols).skip(start_col) {let v = match row.get_ref(i) {Ok(v) => v,Err(_) => continue,diff --git a/engine/crates/xerj-autoindex/src/ids.rs b/engine/crates/xerj-autoindex/src/ids.rsindex 326f50e24..abed4b2c5 100644--- a/engine/crates/xerj-autoindex/src/ids.rs+++ b/engine/crates/xerj-autoindex/src/ids.rs@@ -39,7 +39,10 @@ pub fn doc_id(dataset_slug: &str, file_key: &str, locator: &str) -> String {/// Deterministic state-dir key for (root, url, prefix).pub fn state_key(root: &str, url: &str, prefix: &str) -> String {- format!("{:016x}", xxh3_64(format!("{root}\x00{url}\x00{prefix}").as_bytes()))+ format!(+ "{:016x}",+ xxh3_64(format!("{root}\x00{url}\x00{prefix}").as_bytes())+ )}#[cfg(test)]diff --git a/engine/crates/xerj-autoindex/src/infer/dates.rs b/engine/crates/xerj-autoindex/src/infer/dates.rsindex b1ba1962a..197e70c7b 100644--- a/engine/crates/xerj-autoindex/src/infer/dates.rs+++ b/engine/crates/xerj-autoindex/src/infer/dates.rs@@ -134,7 +134,9 @@ pub fn coerce_to_date(v: &serde_json::Value, elected: Option<DateEnc>) -> Optionmatch elected {Some(DateEnc::EpochSeconds) => {if (EPOCH_S_MIN..=EPOCH_S_MAX).contains(&i) {- Utc.timestamp_opt(i, 0).single().map(|d| to_rfc3339_millis(&d))+ Utc.timestamp_opt(i, 0)+ .single()+ .map(|d| to_rfc3339_millis(&d))} else {parse_epoch(i).map(|(d, _)| to_rfc3339_millis(&d))}@@ -167,10 +169,7 @@ mod tests {assert_eq!(e, enc, "{s}");assert!(dt.timestamp() > 0);}- assert_eq!(- parse_epoch(1773107846071).unwrap().1,- DateEnc::EpochMillis- );+ assert_eq!(parse_epoch(1773107846071).unwrap().1, DateEnc::EpochMillis);assert_eq!(parse_epoch(1773107846).unwrap().1, DateEnc::EpochSeconds);assert!(parse_epoch(42).is_none());assert!(parse_date_str("not a date").is_none());diff --git a/engine/crates/xerj-autoindex/src/infer/mod.rs b/engine/crates/xerj-autoindex/src/infer/mod.rsindex 409522725..a0eeabcf6 100644--- a/engine/crates/xerj-autoindex/src/infer/mod.rs+++ b/engine/crates/xerj-autoindex/src/infer/mod.rs@@ -126,7 +126,8 @@ impl FieldAcc {fn note_distinct(&mut self, s: &str) {if self.distinct.len() < DISTINCT_CAP {- self.distinct.insert(xxhash_rust::xxh3::xxh3_64(s.as_bytes()));+ self.distinct+ .insert(xxhash_rust::xxh3::xxh3_64(s.as_bytes()));} else {self.distinct_overflow = true;}@@ -293,8 +294,7 @@ pub fn infer_fields(.unwrap();spec.es_type = "date".into();spec.date_enc = Some(elected.as_str().into());- let mut ev: Vec<(DateEnc, u64)> =- acc.date_hits.iter().map(|(k, v)| (*k, *v)).collect();+ let mut ev: Vec<(DateEnc, u64)> = acc.date_hits.iter().map(|(k, v)| (*k, *v)).collect();ev.sort();spec.date_evidence = ev.iter()@@ -326,9 +326,7 @@ pub fn infer_fields(spec.date_enc = Some(enc.as_str().into());spec.date_evidence =vec![format!("{}: {} (range-guarded)", enc.as_str(), acc.long_ok)];- let to_dt = |v: i64| {- dates::parse_epoch(v).map(|(d, _)| d)- };+ let to_dt = |v: i64| dates::parse_epoch(v).map(|(d, _)| d);if let (Some(a), Some(b)) = (to_dt(lo), to_dt(hi)) {spec.date_min = Some(dates::to_rfc3339_millis(&a));spec.date_max = Some(dates::to_rfc3339_millis(&b));@@ -370,8 +368,8 @@ pub fn infer_fields(} else {acc.distinct.len() as f64 / n as f64};- let is_keyword = (p95_len <= 128 && p95_tok <= 3)- || (!acc.distinct_overflow && card_ratio < 0.1);+ let is_keyword =+ (p95_len <= 128 && p95_tok <= 3) || (!acc.distinct_overflow && card_ratio < 0.1);let is_text = p95_tok > 8 || p95_len > 256;spec.es_type = if is_keyword && !is_text {"keyword".into()@@ -394,7 +392,8 @@ pub fn infer_fields(let spec = &mut specs[idx];spec.es_type = "date".into();spec.date_enc = Some(enc.as_str().into());- spec.notes.push("epoch corroborated by sibling date field range".into());+ spec.notes+ .push("epoch corroborated by sibling date field range".into());spec.date_min = Some(dates::to_rfc3339_millis(&a));spec.date_max = Some(dates::to_rfc3339_millis(&b));}@@ -410,9 +409,9 @@ pub fn infer_fields(.max_by(|a, b| a.1.avg_len.partial_cmp(&b.1.avg_len).unwrap());if let Some((i, _)) = best {specs[i].es_type = "semantic_text".into();- specs[i]- .notes- .push("hybrid lexical+vector body (hash-bucket embedder — lexical, not neural)".into());+ specs[i].notes.push(+ "hybrid lexical+vector body (hash-bucket embedder — lexical, not neural)".into(),+ );}}@@ -431,9 +430,10 @@ pub fn infer_fields(specs.truncate(MAX_FIELDS_PER_DATASET);specs.sort_by(|a, b| a.name.cmp(&b.name));if let Some(first) = specs.first_mut() {- first- .notes- .push(format!("dataset field cap hit; unmapped overflow fields: {}", overflow.join(", ")));+ first.notes.push(format!(+ "dataset field cap hit; unmapped overflow fields: {}",+ overflow.join(", ")+ ));}}specsdiff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 95714d3ad..fb86a96b6 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -104,7 +104,10 @@ fn scan_file(path: &Path, size: u64, sample: usize, max_file_gb: u64) -> FileScaif whole_file && size > max_file_gb * GB {out.junk = Some(("skipped".into(),- format!("oversized for non-streaming family {} (> {max_file_gb} GB)", sn.family.as_str()),+ format!(+ "oversized for non-streaming family {} (> {max_file_gb} GB)",+ sn.family.as_str()+ ),));out.sniffed = Some(sn);return out;@@ -151,10 +154,7 @@ fn scan_file(path: &Path, size: u64, sample: usize, max_file_gb: u64) -> FileSca}}}- out.sketches = groups- .into_iter()- .map(|(g, (f, n))| (g, f, n))- .collect();+ out.sketches = groups.into_iter().map(|(g, (f, n))| (g, f, n)).collect();out.sketches.sort_by(|a, b| a.0.cmp(&b.0));out.sniffed = Some(sn);out@@ -224,7 +224,8 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {.state_dir.clone().unwrap_or_else(|| state::default_state_dir(&root_str, &cfg.url, &cfg.prefix));- let mut journal = state::Journal::open(&state_dir, &root_str, &cfg.url, &cfg.prefix, cfg.fresh)?;+ let mut journal =+ state::Journal::open(&state_dir, &root_str, &cfg.url, &cfg.prefix, cfg.fresh)?;let run_id = journal.run_id.clone();if journal.resumed && !cfg.quiet {eprintln!(@@ -375,8 +376,11 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {}let done0 = journal.done_keys();- let planned_junk: std::collections::HashSet<&str> =- plan.junk_files.iter().map(|j| j.file_key.as_str()).collect();+ let planned_junk: std::collections::HashSet<&str> = plan+ .junk_files+ .iter()+ .map(|j| j.file_key.as_str())+ .collect();let mut new_unplanned: Vec<JunkFile> = Vec::new();let mut todo: Vec<usize> = Vec::new();for i in 0..files.len() {@@ -452,10 +456,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {let mut send_err: Option<String> = None;{let mut sink = |rec: extract::RawRecord| -> bool {- let Some(slug) = asg- .get(&rec.group)- .or_else(|| asg.get(&None))- else {+ let Some(slug) = asg.get(&rec.group).or_else(|| asg.get(&None)) else {file_junk += 1;return true;};@@ -473,10 +474,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {fields.insert("ax_locator".into(), Value::String(rec.locator.clone()));fields.insert("ax_dataset".into(), Value::String(slug.clone()));fields.insert("ax_run".into(), Value::String(run_id.clone()));- fields.insert(- "ax_format".into(),- Value::String(format_str(Some(&sn))),- );+ fields.insert("ax_format".into(), Value::String(format_str(Some(&sn))));let id = ids::doc_id(slug, key, &rec.locator);let action = json!({"index": {"_index": rt.index, "_id": id}});buf.extend_from_slice(action.to_string().as_bytes());@@ -553,11 +551,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {}records_total.fetch_add(file_records, Ordering::Relaxed);junk_records.fetch_add(file_junk, Ordering::Relaxed);- if let Some(rt) = fa- .assignments- .first()- .and_then(|(_, slug)| ds_rt.get(slug))- {+ if let Some(rt) = fa.assignments.first().and_then(|(_, slug)| ds_rt.get(slug)) {rt.bytes.fetch_add(f.size / fa.assignments.len().max(1) as u64,Ordering::Relaxed,@@ -578,11 +572,8 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {}).ok();let dn = files_done.fetch_add(1, Ordering::Relaxed) + 1;- if !cfg.quiet && (dn % 200 == 0 || f.size > 5 * (1 << 20)) {- eprintln!(- " [{dn}/{n_todo}] {} ({} records)",- f.rel, file_records- );+ if !cfg.quiet && (dn.is_multiple_of(200) || f.size > 5 * (1 << 20)) {+ eprintln!(" [{dn}/{n_todo}] {} ({} records)", f.rel, file_records);}}});@@ -717,10 +708,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {.collect();formats.sort();formats.dedup();- let (tmin, tmax) = ds_timerange- .get(&d.slug)- .cloned()- .unwrap_or((None, None));+ let (tmin, tmax) = ds_timerange.get(&d.slug).cloned().unwrap_or((None, None));let (id, doc) = catalog::dataset_doc(&catalog::DatasetDocInput {pd: d,record_count: *ds_counts.get(&d.slug).unwrap_or(&0),@@ -842,11 +830,14 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {.iter().map(|d| (&d.index, *ds_counts.get(&d.slug).unwrap_or(&0))).collect();- rows.sort_by(|a, b| b.1.cmp(&a.1));+ rows.sort_by_key(|r| std::cmp::Reverse(r.1));for (idx, cnt) in rows {println!(" {idx:<40} {cnt:>10} docs");}- println!("\nnext: `xerj autoindex map --url {}` for the data map; search via GET /{}-*/_search", cfg.url, cfg.prefix);+ println!(+ "\nnext: `xerj autoindex map --url {}` for the data map; search via GET /{}-*/_search",+ cfg.url, cfg.prefix+ );}Ok(if junk_total_records > 0 || !all_junk.is_empty() {3@@ -890,11 +881,7 @@ fn run_map(cfg: MapCfg) -> Result<i32> {{"term": {"slug": slug}}]}});}- let datasets = fetch(- ds_query,- 500,- Some(json!([{"record_count": "desc"}])),- )?;+ let datasets = fetch(ds_query, 500, Some(json!([{"record_count": "desc"}])))?;if datasets.is_empty() {eprintln!("no autoindex catalog found at {} (index {}) — run `xerj autoindex <folder>` first",@@ -926,7 +913,10 @@ fn run_map(cfg: MapCfg) -> Result<i32> {.map(|s| s.to_string());all.retain(|c| {c.get("corr_kind").and_then(|k| k.as_str()) != Some(kind)- || c.get("run_id").and_then(|r| r.as_str()).map(|s| s.to_string()) == latest+ || c.get("run_id")+ .and_then(|r| r.as_str())+ .map(|s| s.to_string())+ == latest});}all@@ -992,16 +982,11 @@ fn run_status(cfg: StatusCfg) -> Result<i32> {if let Ok(v) = serde_json::from_str::<Value>(&line) {match v.get("kind").and_then(|k| k.as_str()) {Some("run") => {- root = v- .get("root")- .and_then(|r| r.as_str())- .unwrap_or("")- .into()+ root = v.get("root").and_then(|r| r.as_str()).unwrap_or("").into()}Some("file_done") => {done += 1;- records +=- v.get("records").and_then(|r| r.as_u64()).unwrap_or(0);+ records += v.get("records").and_then(|r| r.as_u64()).unwrap_or(0);}Some("finish") => finished = true,_ => {}diff --git a/engine/crates/xerj-autoindex/src/sniff.rs b/engine/crates/xerj-autoindex/src/sniff.rsindex 46e252fbc..759b3a5bb 100644--- a/engine/crates/xerj-autoindex/src/sniff.rs+++ b/engine/crates/xerj-autoindex/src/sniff.rs@@ -302,8 +302,7 @@ fn txt_kind(nonblank: &[&str]) -> Family {if nonblank.is_empty() {return Family::TxtLines;}- let avg_len =- nonblank.iter().map(|l| l.len()).sum::<usize>() as f64 / nonblank.len() as f64;+ let avg_len = nonblank.iter().map(|l| l.len()).sum::<usize>() as f64 / nonblank.len() as f64;if avg_len > 60.0 {Family::TxtProse} else {@@ -353,7 +352,10 @@ fn sniff_csv_dialect(nonblank: &[&str]) -> Option<CsvDialect> {let sample: Vec<&str> = nonblank.iter().take(64).copied().collect();let mut best: Option<(u8, usize)> = None; // (delim, field count)for delim in [b',', b';', b'\t', b'|'] {- let counts: Vec<usize> = sample.iter().map(|l| split_quoted(l, delim).len()).collect();+ let counts: Vec<usize> = sample+ .iter()+ .map(|l| split_quoted(l, delim).len())+ .collect();let first = counts[0];if first < 2 {continue;@@ -379,7 +381,9 @@ fn sniff_csv_dialect(nonblank: &[&str]) -> Option<CsvDialect> {let has_header = {let mut distinct = std::collections::HashSet::new();let all_nonnum = head_fields.iter().all(|f| !numericish(f));- let all_distinct = head_fields.iter().all(|f| distinct.insert(f.trim().to_string()));+ let all_distinct = head_fields+ .iter()+ .all(|f| distinct.insert(f.trim().to_string()));let body_has_num = sample.iter().skip(1)@@ -424,7 +428,10 @@ mod tests {#[test]fn sniff_families() {assert_eq!(classify("{\"a\":1}\n{\"a\":2}\n{\"a\":3}\n"), Family::Jsonl);- assert_eq!(classify("{\n \"a\": 1,\n \"b\": [1,2]\n}\n"), Family::Json);+ assert_eq!(+ classify("{\n \"a\": 1,\n \"b\": [1,2]\n}\n"),+ Family::Json+ );assert_eq!(classify("<!DOCTYPE html>\n<html><head></head></html>"),Family::Html@@ -433,10 +440,7 @@ mod tests {classify("<?xml version='1.0'?>\n<r><a>1</a></r>"),Family::Xml);- assert_eq!(- classify("a,b,c\n1,2,3\n4,5,6\n"),- Family::Csv- );+ assert_eq!(classify("a,b,c\n1,2,3\n4,5,6\n"), Family::Csv);assert_eq!(classify("CREATE TABLE `t` (\n `a` int\n);\nINSERT INTO `t` VALUES (1);\n"),Family::SqlDumpdiff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex 54cb0b6be..ed15e57b7 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -198,7 +198,7 @@ impl Journal {self.append(&v)?;self.done.insert(fd.file_key.clone(), fd.clone());// fsync batched: every 32 completions- if self.done.len() % 32 == 0 {+ if self.done.len().is_multiple_of(32) {self.file.sync_data().ok();}Ok(())diff --git a/engine/crates/xerj-engine/src/aggs.rs b/engine/crates/xerj-engine/src/aggs.rsindex 79c395b29..c7aa1d03e 100644--- a/engine/crates/xerj-engine/src/aggs.rs+++ b/engine/crates/xerj-engine/src/aggs.rs@@ -9864,8 +9864,8 @@ fn run_date_range(// (b7 DEFECT 2, date_range arm). tz-shifted rendering keeps the// legacy pattern path below.if offset.is_none() && is_named_date_format(fmt) {- let dt_utc = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(ms)- .unwrap_or_default();+ let dt_utc =+ chrono::DateTime::<chrono::Utc>::from_timestamp_millis(ms).unwrap_or_default();return render_date_format(Some(fmt), ms, dt_utc);}let pat = java_to_strftime(fmt);diff --git a/engine/crates/xerj-engine/src/fast_aggs.rs b/engine/crates/xerj-engine/src/fast_aggs.rsindex bf72a33e3..afa550956 100644--- a/engine/crates/xerj-engine/src/fast_aggs.rs+++ b/engine/crates/xerj-engine/src/fast_aggs.rs@@ -49,9 +49,8 @@ use crate::aggs::{extract_field_values, extract_numeric, extract_numeric_values, format_histogram_key,format_number_pattern, format_range_val, get_nested_field, interval_to_ms,is_calendar_interval, java_double_str, matrix_stats_from_rows, next_calendar_bucket,- parse_date_ms, parse_offset_ms,- render_date_format, render_iso_date, resolve_sibling_pipelines, run_pipeline_agg, run_sampler,- run_top_hits_with_total, typed_term_key,+ parse_date_ms, parse_offset_ms, render_date_format, render_iso_date, resolve_sibling_pipelines,+ run_pipeline_agg, run_sampler, run_top_hits_with_total, typed_term_key,};use crate::memtable::MemBoolPred;use serde_json::{json, Map, Value};@@ -1577,7 +1576,7 @@ impl<'a> FastCtx<'a> {let mut dev: Vec<f64> = nums.iter().map(|x| (x - median).abs()).collect();let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);let m = dev.len();- let mad = if m % 2 == 0 {+ let mad = if m.is_multiple_of(2) {// `select_nth_unstable_by(m/2)` places the (m/2)-th order statistic// at `m/2` and leaves everything before it ≤ it, so the low middle// is the max of that left partition — exactly the two positions a@@ -1601,7 +1600,7 @@ impl<'a> FastCtx<'a> {/// `matrix_stats` — single columnar pass gathering, per doc where EVERY/// requested field is present, a value vector straight from the numeric/// `.dv` columns, then the identical count/mean/variance/skewness/kurtosis- /// + pairwise covariance/correlation reduction as brute+ /// plus pairwise covariance/correlation reduction as brute/// (`matrix_stats_from_rows`, shared). Only the plain `{fields}` form is/// served; `mode` (multi-value collapse), `missing` (per-field default) and/// the `__xy_f32_fields__` sentinel (float-precision round-trip, injected by@@ -1614,7 +1613,11 @@ impl<'a> FastCtx<'a> {let fields: Vec<String> = params.get("fields").and_then(Value::as_array)- .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().map(String::from))+ .collect()+ }).unwrap_or_default();if fields.is_empty() {return Some(json!({ "doc_count": 0, "fields": [] }));@@ -2657,8 +2660,8 @@ impl<'a> FastCtx<'a> {}}}- None => {} // field absent in this segment → no terms- _ => return None, // non-keyword column for a keyword field → bail+ None => {} // field absent in this segment → no terms+ _ => return None, // non-keyword column for a keyword field → bail}}match self.idx.memtable.terms_counts_columnar(field) {diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex ad74e1cbb..d91727c21 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -4492,9 +4492,7 @@ impl Index {) {if let Some(&pos) = pos_map.get(id) {if let Some(&(start, end)) = slices.offsets.get(pos as usize) {- if let Some(slice) =- slices.bytes.get(start as usize..end as usize)- {+ if let Some(slice) = slices.bytes.get(start as usize..end as usize) {// serde_json (not simd_json): same root cause// as the KNN cache — see ffd49ac.if let Ok(doc) = serde_json::from_slice::<Value>(slice) {@@ -4710,7 +4708,10 @@ impl Index {let cache_eligible = !request.profile && request.search_after.is_none() && {static DISABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();!*DISABLED.get_or_init(|| {- matches!(std::env::var("XERJ_DISABLE_QUERY_CACHE").as_deref(), Ok("1") | Ok("true"))+ matches!(+ std::env::var("XERJ_DISABLE_QUERY_CACHE").as_deref(),+ Ok("1") | Ok("true")+ )})};let cache_key: Option<(u64, u64)> = if cache_eligible {@@ -5191,8 +5192,7 @@ impl Index {// Columnar function_score fast-path probe (borrows `query`). `Some` iff// the request is exactly `function_score { match_all, field_value_factor }`// on a plain size>0 page — see `function_score_fast_fvf`.- let fs_fast_fvf: Option<&FieldValueFactor> =- function_score_fast_fvf(query, request, size);+ let fs_fast_fvf: Option<&FieldValueFactor> = function_score_fast_fvf(query, request, size);// Determine whether we need hit *sources* at all.// - size > 0 → sources for hits output@@ -5344,7 +5344,7 @@ impl Index {.sort.iter().all(|sf| sf.is_score() || sf.is_doc_order())- && !(fs_fast_fvf.is_some() && !fs_deletes_early);+ && (fs_fast_fvf.is_none() || fs_deletes_early);let mut sort_topk: Option<SortTopK> = if field_sort_active {Some(SortTopK::new(@@ -5365,11 +5365,7 @@ impl Index {} else {request.sort.clone()};- Some(SortTopK::new(- Arc::new(keys),- materialisation_limit,- None,- ))+ Some(SortTopK::new(Arc::new(keys), materialisation_limit, None))} else {None};@@ -5409,11 +5405,8 @@ impl Index {// track_scores, function_score inners).let leaf_base_const: Option<f32> = {let score_target: &QueryNode = match peeled_fs {- Some((fs_node, _)) => match fs_node {- QueryNode::FunctionScore { query: inner, .. } => inner.as_ref(),- _ => query,- },- None => query,+ Some((QueryNode::FunctionScore { query: inner, .. }, _)) => inner.as_ref(),+ _ => query,};self.leaf_constant_score(score_target, &kw_fields, &num_fields, &bool_fields)};@@ -5456,8 +5449,7 @@ impl Index {let base = leaf_base_const.unwrap_or_else(|| score_query_against_doc(inner, src))* outer_boost;- let mut fn_score =- apply_function_score(id, src, functions, *score_mode, base);+ let mut fn_score = apply_function_score(id, src, functions, *score_mode, base);if let Some(cap) = max_boost {fn_score = fn_score.min(*cap);}@@ -5474,8 +5466,7 @@ impl Index {}}if score > 0.0 && score.is_finite() {- scored_max_bits- .fetch_max(score.to_bits(), std::sync::atomic::Ordering::Relaxed);+ scored_max_bits.fetch_max(score.to_bits(), std::sync::atomic::Ordering::Relaxed);}score};@@ -5995,7 +5986,6 @@ impl Index {let snap = self.store.snapshot();let segments_dir = self.data_dir.join("segments");-// ── Fast path: count-only shortcut ────────────────────────────────//// Ported from Elasticsearch's@@ -6215,12 +6205,9 @@ impl Index {let mut scored_fast_applied = false;if let Some(plan) = &scored_plan {if scored_fast_ready {- if let Some((hits, total)) = self.scored_columnar(- plan,- &snap.segments,- &segments_dir,- materialisation_limit,- ) {+ if let Some((hits, total)) =+ self.scored_columnar(plan, &snap.segments, &segments_dir, materialisation_limit)+ {seen_ids.clear();seen_ids.extend(hits.iter().map(|h| h.id.clone()));all_hits = hits;@@ -6478,8 +6465,7 @@ impl Index {// behaviour, matching the materialisation// fallback's failure mode).if deletes_present {- match self- .ghost_positions_for(seg_id.as_str(), meta.doc_count)+ match self.ghost_positions_for(seg_id.as_str(), meta.doc_count){Some(ghosts) => {let live = seg_hits@@ -6602,33 +6588,29 @@ impl Index {// under the read-lease fix the files are// guaranteed present, so an open error is// real corruption.- let whole_fallback: Option<Vec<Value>> =- if slices_opt.is_some() {- None- } else {- let seg_reader =- self.store.open_segment_arc(&seg_id)?;- match seg_reader.section(SectionType::Stored) {- Ok(Some(raw)) => {- match xerj_storage::stored_codec::decode_stored(- raw,- ) {- // serde_json — see ffd49ac,- // simd_json silently- // corrupts some M7- // raw-bytes payloads.- Ok(b) => serde_json::from_slice::<- Vec<Value>,- >(- &b- )- .ok(),- Err(_) => None,+ let whole_fallback: Option<Vec<Value>> = if slices_opt.is_some()+ {+ None+ } else {+ let seg_reader = self.store.open_segment_arc(&seg_id)?;+ match seg_reader.section(SectionType::Stored) {+ Ok(Some(raw)) => {+ match xerj_storage::stored_codec::decode_stored(raw)+ {+ // serde_json — see ffd49ac,+ // simd_json silently+ // corrupts some M7+ // raw-bytes payloads.+ Ok(b) => {+ serde_json::from_slice::<Vec<Value>>(&b)+ .ok()}+ Err(_) => None,}- _ => None,}- };+ _ => None,+ }+ };if slices_opt.is_some() || whole_fallback.is_some() {// Owned parsed doc for a stored position,// shared by both source layouts. The@@ -6701,10 +6683,8 @@ impl Index {if seen_ids.contains(&id) {continue;}- let source = doc- .get("_source")- .cloned()- .unwrap_or(Value::Null);+ let source =+ doc.get("_source").cloned().unwrap_or(Value::Null);seen_ids.insert(id.clone());let hit = Hit {id,@@ -7220,70 +7200,71 @@ impl Index {// keeping the batch-3 verified cell bit-exact;// * either way the loop validates the FINAL score exactly like// ES (`illegal_argument_exception` on NaN/±Inf/negative).- if let Some((fs_node, fs_outer_boost)) = peeled_fs {- if let QueryNode::FunctionScore {+ if let Some((+ QueryNode::FunctionScore {functions,score_mode,boost_mode,max_boost,..- } = fs_node- {- for (doc_idx, hit) in final_hits.iter_mut().enumerate() {- let combined = if fs_fast_applied {- // Query-level boost multiplies the BASE score- // BEFORE the boost_mode combine (Lucene bakes it- // into the subquery weight — see `score_doc`).- // The columnar gate only fires with boost == 1- // (a `Boosted` wrapper defeats it), so this is- // currently a no-op kept for order-correctness.- let query_score = hit.score * fs_outer_boost;- let mut fn_score = apply_function_score(- &hit.id,- &hit.source,- functions,- *score_mode,- query_score,- );- // ES caps the COMBINED FUNCTION score (not the- // final) at `max_boost`, before boost_mode- // composition — live-verified on ES 8.13.4:- // boost_mode=sum + inner boost 3 + max_boost 100- // scores 103, outer boost 2 + max_boost 100- // scores 200.- if let Some(cap) = max_boost {- fn_score = fn_score.min(*cap);+ },+ fs_outer_boost,+ )) = peeled_fs+ {+ for (doc_idx, hit) in final_hits.iter_mut().enumerate() {+ let combined = if fs_fast_applied {+ // Query-level boost multiplies the BASE score+ // BEFORE the boost_mode combine (Lucene bakes it+ // into the subquery weight — see `score_doc`).+ // The columnar gate only fires with boost == 1+ // (a `Boosted` wrapper defeats it), so this is+ // currently a no-op kept for order-correctness.+ let query_score = hit.score * fs_outer_boost;+ let mut fn_score = apply_function_score(+ &hit.id,+ &hit.source,+ functions,+ *score_mode,+ query_score,+ );+ // ES caps the COMBINED FUNCTION score (not the+ // final) at `max_boost`, before boost_mode+ // composition — live-verified on ES 8.13.4:+ // boost_mode=sum + inner boost 3 + max_boost 100+ // scores 103, outer boost 2 + max_boost 100+ // scores 200.+ if let Some(cap) = max_boost {+ fn_score = fn_score.min(*cap);+ }+ combine_scores(query_score, fn_score, *boost_mode)+ } else {+ // Brute scan hits already carry the fully-composed+ // final score (single application in `score_doc`).+ hit.score+ };+ // ES rejects non-finite or negative scores here with+ // `illegal_argument_exception`. Match the exact reason+ // text so the YAML test's root_cause.reason comparison+ // succeeds.+ if !combined.is_finite() || combined < 0.0 {+ let label = if combined.is_nan() {+ "NaN".to_string()+ } else if combined.is_infinite() {+ if combined > 0.0 {+ "Infinity".into()+ } else {+ "-Infinity".into()}- combine_scores(query_score, fn_score, *boost_mode)} else {- // Brute scan hits already carry the fully-composed- // final score (single application in `score_doc`).- hit.score+ format!("{combined}")};- // ES rejects non-finite or negative scores here with- // `illegal_argument_exception`. Match the exact reason- // text so the YAML test's root_cause.reason comparison- // succeeds.- if !combined.is_finite() || combined < 0.0 {- let label = if combined.is_nan() {- "NaN".to_string()- } else if combined.is_infinite() {- if combined > 0.0 {- "Infinity".into()- } else {- "-Infinity".into()- }- } else {- format!("{combined}")- };- return Err(EngineError::Common(+ return Err(EngineError::Common(xerj_common::XerjError::invalid_query(format!("function score query returned an invalid score: {label} for doc: {doc_idx}; score must be a non-negative real number")),));- }- hit.score = combined;}+ hit.score = combined;}}@@ -7962,9 +7943,8 @@ impl Index {// every match. Rescore mutates scores after the scan, so the scan// max is stale there — skip.let population_max_score: Option<f32> = if request.rescore.is_empty() {- let scan_max = f32::from_bits(- scored_max_bits.load(std::sync::atomic::Ordering::Relaxed),- );+ let scan_max =+ f32::from_bits(scored_max_bits.load(std::sync::atomic::Ordering::Relaxed));match population_max_score {Some(m) if scan_max > m => Some(scan_max),other => other,@@ -8829,6 +8809,7 @@ impl Index {/// - If the segment has no FTS data for the field at all, the/// shortcut is abandoned (return `None`) because the segment/// would otherwise undercount.+ ////// Exact match count for a `bool` that carries `should` and/or `must_not`/// clauses — the shapes the fused must/filter-intersection arm bails on./// Resolves every leaf clause to its doc-values position set per segment@@ -9362,8 +9343,8 @@ impl Index {let cols = self.dv_columns_for(&segments_dir, &meta.id)?;match cols.get(field_str) {Some(xerj_storage::doc_values::Column::Numeric(n)) => {- seg_matches = seg_matches- .saturating_add(n.range_count(lo, hi, lo_incl, hi_incl));+ seg_matches =+ seg_matches.saturating_add(n.range_count(lo, hi, lo_incl, hi_incl));}// DATE fields (e.g. `@timestamp`) are date-shaped Keyword dv// columns, not Numeric — without this arm the shortcut@@ -9380,8 +9361,12 @@ impl Index {field_str,meta.doc_count,)?;- let (slo, slo_incl, shi, shi_incl) =- shadow_range_bounds(gte.as_ref(), gt.as_ref(), lte.as_ref(), lt.as_ref())?;+ let (slo, slo_incl, shi, shi_incl) = shadow_range_bounds(+ gte.as_ref(),+ gt.as_ref(),+ lte.as_ref(),+ lt.as_ref(),+ )?;seg_matches = seg_matches.saturating_add(shadow_range_count(&shadow, slo, shi, slo_incl, shi_incl,));@@ -9546,8 +9531,8 @@ impl Index {for v in values {let f = v.as_f64()?;if seen.insert(f.to_bits()) {- seg_matches = seg_matches- .saturating_add(n.range_count(f, f, true, true));+ seg_matches =+ seg_matches.saturating_add(n.range_count(f, f, true, true));}}}@@ -9965,9 +9950,11 @@ impl Index {field,value: Value::String(term),boost,- } if kw_fields.contains(field) => {- (field, LeafConst::Keyword(term.clone()), boost.unwrap_or(1.0))- }+ } if kw_fields.contains(field) => (+ field,+ LeafConst::Keyword(term.clone()),+ boost.unwrap_or(1.0),+ ),QueryNode::Term {field,value,@@ -9997,9 +9984,11 @@ impl Index {boost,minimum_should_match: None,..- } if kw_fields.contains(field) => {- (field, LeafConst::Keyword(query.clone()), boost.unwrap_or(1.0))- }+ } if kw_fields.contains(field) => (+ field,+ LeafConst::Keyword(query.clone()),+ boost.unwrap_or(1.0),+ ),QueryNode::Match {field,query,@@ -10446,7 +10435,8 @@ impl Index {else {return None;};- k.ord_for_term(term).is_some_and(|o| k.ords[row as usize] == o)+ k.ord_for_term(term)+ .is_some_and(|o| k.ords[row as usize] == o)}ScoredLeafKind::BoolEq(v) | ScoredLeafKind::NumericEq(v) => {let Some(Column::Numeric(nc)) =@@ -14436,6 +14426,7 @@ fn infer_field_type(val: &Value) -> FieldType {/// * a conjunctive `Bool` (empty should/must_not, non-empty must+filter)/// whose every must/filter child is a plain `Term`/`Range` — memtable/// side counted via the fused `doc_values_bool_query` walk (Bool arm).+////// Every other shape makes `try_shortcut_count` return `None` — a Bool/// with a Match child fails its child check, and any should/must_not Bool/// bails on a non-empty memtable (`bool_should_mustnot_count`) — so the@@ -17158,8 +17149,7 @@ fn score_query_against_doc(q: &QueryNode, source: &Value) -> f32 {}let inner = score_query_against_doc(query, source);let doc_id = source.get("_id").and_then(Value::as_str).unwrap_or("");- let mut fn_score =- apply_function_score(doc_id, source, functions, *score_mode, inner);+ let mut fn_score = apply_function_score(doc_id, source, functions, *score_mode, inner);// `max_boost` caps the combined FUNCTION score before// boost_mode composition (ES semantics — see the post-loop).if let Some(cap) = max_boost {@@ -17720,7 +17710,11 @@ fn seg_range_positions(let Column::Numeric(n) = cols.get(field)? else {return None;};- Some(n.range_doc_ids(lo, hi, lo_incl, hi_incl).into_iter().collect())+ Some(+ n.range_doc_ids(lo, hi, lo_incl, hi_incl)+ .into_iter()+ .collect(),+ )}fn brace_walk_offsets(bytes: &[u8]) -> Vec<(u32, u32)> {@@ -18433,9 +18427,7 @@ fn compute_sort_values(// widening: ES serializes scores as Java floats (448.4), and// `448.39999_f32 as f64` prints 448.3999938964844 on the wire.let wire: f64 = score.to_string().parse().unwrap_or(score as f64);- Value::Number(- serde_json::Number::from_f64(wire).unwrap_or(serde_json::Number::from(0)),- )+ Value::Number(serde_json::Number::from_f64(wire).unwrap_or(serde_json::Number::from(0)))} else if sf.is_doc_order() || sf.field == "_id" {// `_id` (and `_doc`) is doc metadata, NOT part of `_source`, so a// plain `get_field_value` returns Null — which breaks `_id`-sorted@@ -19274,16 +19266,22 @@ fn query_node_to_fts(if tokens.is_empty() {return None;}- return Some(FtsQuery::PhrasePrefix(xerj_fts::search::PhrasePrefixQuery {- field: field.clone(),- terms: tokens.iter().map(|t| t.text.clone()).collect(),- max_expansions: *max_expansions as usize,- boost: 1.0,- }));+ return Some(FtsQuery::PhrasePrefix(+ xerj_fts::search::PhrasePrefixQuery {+ field: field.clone(),+ terms: tokens.iter().map(|t| t.text.clone()).collect(),+ max_expansions: *max_expansions as usize,+ boost: 1.0,+ },+ ));}None}- QueryNode::Prefix { field, value, boost } => {+ QueryNode::Prefix {+ field,+ value,+ boost,+ } => {// `prefix` on a KEYWORD field: whole-value, case-sensitive prefix// match over the keyword FST term dictionary — byte-identical to ES// `prefix` on a keyword field (default case-sensitive, matches the@@ -19328,7 +19326,11 @@ fn query_node_to_fts(}None}- QueryNode::Wildcard { field, value, boost } => {+ QueryNode::Wildcard {+ field,+ value,+ boost,+ } => {// `wildcard` on a KEYWORD field: expand the keyword FST term// dictionary to every term matching the pattern (`*`=0+ chars,// `?`=1 char) and score each as a term. The searcher's expansion@@ -19616,6 +19618,7 @@ enum ScoredLeafKind {/// conjunction as a peer — see `explicit_msm`)./// * dis_max: `(f32)(max + (Σ − max) · tie)` with Σ in f64/// (`DisjunctionMaxScorer`).+////// A flat f64 sum over all leaves — the pre-batch-11 code — drifts/// 1 ULP from ES on `must` + multi-`should` shapes (live-verified:/// skew corpus bool_msm_must 0x4080c786 vs ES 0x4080c785).@@ -19666,9 +19669,7 @@ impl ScoreEval<'_> {Some(o) => col.ords[row as usize] == *o,None => false,},- ScoreEval::Bool { col, val } => {- f64::from_bits(col.data[row as usize] as u64) == *val- }+ ScoreEval::Bool { col, val } => f64::from_bits(col.data[row as usize] as u64) == *val,}}}@@ -19971,8 +19972,7 @@ enum ScoredPlan {fn bm25_keyword_term_score(n: u64, total_docs: u64, boost: f32) -> f32 {// idf in f64, single cast to f32 (matches Lucene's `(float)` on the// double-precision idf expression).- let idf_f32 =- (1.0_f64 + (total_docs as f64 - n as f64 + 0.5) / (n as f64 + 0.5)).ln() as f32;+ let idf_f32 = (1.0_f64 + (total_docs as f64 - n as f64 + 0.5) / (n as f64 + 0.5)).ln() as f32;// weight = boost · (k1+1) · idf, all float32, Lucene's evaluation// order (`boost * (k1+1)` first, then `· idf` — BM25Similarity's// BM25Scorer ctor). Live-validated bit-exact for boost = 3 / 2 / 0.3@@ -20050,7 +20050,7 @@ fn scored_fast_plan(};fn boost_ok(b: &Option<f32>) -> bool {- b.map_or(true, |v| v == 1.0)+ b.is_none_or(|v| v == 1.0)}// Scoring leaves accept ANY finite non-negative boost — keyword/bool// leaves feed it into the BM25 weight (Lucene boost-in-weight, see@@ -20223,8 +20223,7 @@ fn scored_fast_plan(// Explicit integer minimum_should_match (≥1, applied to a// non-empty should list). Percentage / combination forms// and an explicit 0 keep the brute path.- let (required_should, explicit_msm): (usize, bool) = match minimum_should_match- {+ let (required_should, explicit_msm): (usize, bool) = match minimum_should_match {None => (usize::from(must.is_empty() && filter.is_empty() && !should.is_empty()),false,@@ -20286,13 +20285,11 @@ fn scored_fast_plan(positive,negative,negative_boost,- } if negative_boost.is_finite() && *negative_boost >= 0.0 => {- Some(ScoredPlan::Boosting {- positive: scoring_leaf(positive, 1.0, &fs)?,- negative: filter_leaf(negative, &fs)?,- negative_boost: *negative_boost,- })- }+ } if negative_boost.is_finite() && *negative_boost >= 0.0 => Some(ScoredPlan::Boosting {+ positive: scoring_leaf(positive, 1.0, &fs)?,+ negative: filter_leaf(negative, &fs)?,+ negative_boost: *negative_boost,+ }),QueryNode::Pinned { ids, organic } if !ids.is_empty() => {// Duplicate pinned ids would need ES's dedup semantics — bail.let mut seen: HashSet<&str> = HashSet::with_capacity(ids.len());@@ -21072,7 +21069,8 @@ mod fts_projection_tests {analyzer: None,boost: None,};- let fq = query_node_to_fts(&q, &["body".to_string()], &kw(&[])).expect("text phrase projects");+ let fq =+ query_node_to_fts(&q, &["body".to_string()], &kw(&[])).expect("text phrase projects");match fq {FtsQuery::Phrase(p) => {assert_eq!(p.field, "body");diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rsindex 740f5e5cf..4cb2dcf39 100644--- a/engine/crates/xerj-fts/src/search.rs+++ b/engine/crates/xerj-fts/src/search.rs@@ -25,6 +25,9 @@ use rayon::prelude::*;use serde::{Deserialize, Serialize};use std::sync::Arc;+/// Per-term phrase postings: `doc_id → (term_freq, positions)`.+type TermPostingsMap = std::collections::HashMap<u32, (u32, Vec<u32>)>;+// ── Scored hit ────────────────────────────────────────────────────────────────/// One scored result document.@@ -591,8 +594,7 @@ impl FtsSearcher {// implementation `.find()`-scanned each other term's FULL posting list// for every anchor doc (O(anchor_df × other_df), quadratic on common// terms like a non-stop-worded "the").- let mut term_maps: Vec<(std::collections::HashMap<u32, (u32, Vec<u32>)>, u32)> =- Vec::with_capacity(pq.terms.len());+ let mut term_maps: Vec<(TermPostingsMap, u32)> = Vec::with_capacity(pq.terms.len());for term in &pq.terms {let tp = match self.reader.lookup_term(&pq.field, term) {Some(tp) => tp,@@ -602,10 +604,9 @@ impl FtsSearcher {Some(d) => d,None => return Ok(Vec::new()),};- let mut reader =- PostingsReader::new_with_positions(post_data, tp.doc_frequency, true);- let mut map: std::collections::HashMap<u32, (u32, Vec<u32>)> =- std::collections::HashMap::with_capacity(tp.doc_frequency as usize);+ let mut reader = PostingsReader::new_with_positions(post_data, tp.doc_frequency, true);+ let mut map: TermPostingsMap =+ TermPostingsMap::with_capacity(tp.doc_frequency as usize);while let Some(p) = reader.next() {map.insert(p.doc_id, (p.term_freq, p.positions));}@@ -624,7 +625,7 @@ impl FtsSearcher {let scorer = self.make_scorer(&pq.field);let mut hits = Vec::new();- 'doc: for (&doc_id, _) in &term_maps[min_idx].0 {+ 'doc: for &doc_id in term_maps[min_idx].0.keys() {// Gather each term's positions for this doc, in TERM ORDER (raw —// no offset games; the matcher below handles adjacency + slop).let mut all_positions: Vec<&Vec<u32>> = Vec::with_capacity(pq.terms.len());@@ -1681,21 +1682,48 @@ mod tests {// Case-sensitive wildcard: "R*" matches, "r*" does not.let mut ci = WildcardQuery::new("body", "R*");ci.case_insensitive = false;- assert_eq!(searcher.search(&Query::Wildcard(ci), 10, false).unwrap().len(), 1);+ assert_eq!(+ searcher+ .search(&Query::Wildcard(ci), 10, false)+ .unwrap()+ .len(),+ 1+ );let mut cs = WildcardQuery::new("body", "r*");cs.case_insensitive = false;- assert_eq!(searcher.search(&Query::Wildcard(cs), 10, false).unwrap().len(), 0);+ assert_eq!(+ searcher+ .search(&Query::Wildcard(cs), 10, false)+ .unwrap()+ .len(),+ 0+ );// Case-insensitive (keyword-style) wildcard: "r*" DOES match.let ki = WildcardQuery::new("body", "r*"); // default case_insensitive = true- assert_eq!(searcher.search(&Query::Wildcard(ki), 10, false).unwrap().len(), 1);+ assert_eq!(+ searcher+ .search(&Query::Wildcard(ki), 10, false)+ .unwrap()+ .len(),+ 1+ );// Case-sensitive fuzzy: "Rist" (1 edit from "Rust") matches; "rist" does not.let mut fz = FuzzyQuery::new("body", "Rist", 1);fz.case_insensitive = false;- assert_eq!(searcher.search(&Query::Fuzzy(fz), 10, false).unwrap().len(), 1);+ assert_eq!(+ searcher.search(&Query::Fuzzy(fz), 10, false).unwrap().len(),+ 1+ );let mut fzl = FuzzyQuery::new("body", "rist", 1);fzl.case_insensitive = false;- assert_eq!(searcher.search(&Query::Fuzzy(fzl), 10, false).unwrap().len(), 0);+ assert_eq!(+ searcher+ .search(&Query::Fuzzy(fzl), 10, false)+ .unwrap()+ .len(),+ 0+ );}#[test]@@ -1763,7 +1791,14 @@ mod tests {assert!(w[0].score >= w[1].score);}- for cap in [0usize, 1, 2, 3, total_full as usize, total_full as usize + 5] {+ for cap in [+ 0usize,+ 1,+ 2,+ 3,+ total_full as usize,+ total_full as usize + 5,+ ] {let (bounded, total) = searcher.search_bounded(q, cap, false).unwrap();// (1) Exact total is independent of the page cap.diff --git a/engine/crates/xerj-mcp/src/main.rs b/engine/crates/xerj-mcp/src/main.rsindex c1fcd487d..2f3c2bac1 100644--- a/engine/crates/xerj-mcp/src/main.rs+++ b/engine/crates/xerj-mcp/src/main.rs@@ -390,7 +390,10 @@ async fn call_tool(ctx: &Ctx, msg: &Value) -> Value {Some(n) => n,None => return tool_text("missing tool `name`", true),};- let args = params.get("arguments").cloned().unwrap_or_else(|| json!({}));+ let args = params+ .get("arguments")+ .cloned()+ .unwrap_or_else(|| json!({}));let result = match name {"xerj_search" => build_search(&args),@@ -653,7 +656,10 @@ mod tests {.unwrap();assert_eq!(path, "/h/_search");assert_eq!(body["query"]["hybrid"]["fusion"], "rrf");- assert_eq!(body["query"]["hybrid"]["queries"].as_array().unwrap().len(), 2);+ assert_eq!(+ body["query"]["hybrid"]["queries"].as_array().unwrap().len(),+ 2+ );assert_eq!(body["size"], 10);}diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rsindex 583e89683..9e9e72dee 100644--- a/engine/crates/xerj-query/src/parser.rs+++ b/engine/crates/xerj-query/src/parser.rs@@ -1131,6 +1131,10 @@ fn try_lower_query_string(}#[derive(Debug, Clone)]+// `Range` (a field + four `Option<Value>` bounds) dwarfs the unit+// operator variants; QsTok is a short-lived per-parse token buffer, so+// boxing it would cost more indirection than the transient size saves.+#[allow(clippy::large_enum_variant)]enum QsTok {Term(String, String), // (field, value) — field empty if unqualifiedPhrase(String, String), // (field, value)diff --git a/engine/crates/xerj-storage/src/wal.rs b/engine/crates/xerj-storage/src/wal.rsindex bc12ffd6f..e7e176084 100644--- a/engine/crates/xerj-storage/src/wal.rs+++ b/engine/crates/xerj-storage/src/wal.rs@@ -785,7 +785,7 @@ impl WalReader {let dir = self.dir.clone();let iter = gens.into_iter().flat_map(move |gen| {let path = wal_path(&dir, gen);- read_wal_file(path, checkpoint.clone())+ read_wal_file(path, checkpoint)});Ok(iter)@@ -960,8 +960,8 @@ fn read_wal_file(path: PathBuf, checkpoint: Option<WalCheckpoint>) -> Vec<Result// Skip entries already covered by the checkpoint — see the// offset-bounded rule in the function docs.if let Some(c) = &checkpoint {- let positionally_covered = generation < c.generation- || (generation == c.generation && this_offset < c.offset);+ let positionally_covered =+ generation < c.generation || (generation == c.generation && this_offset < c.offset);if positionally_covered && seq_no <= c.max_seq_no {continue;}