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
fix(engine): preserve #191 total tie order on dynamic-text and keyword term queries
Christian M. Todie1e885489d615
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 6d720289f..7afc7d034 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -20901,6 +20901,37 @@ impl Index {}(tf, ef, kw, num, bf)};+ // #1359: `query_node_to_fts_projected` projects a `QueryNode::Term` on a+ // `FieldType::Keyword` field into `FtsQuery::Term` so a `bool` or+ // `dis_max` combining a text clause and a keyword `term` clause does+ // not `?`-abort FTS projection on the keyword child. A standalone+ // top-level `term` on a keyword field, however, is served by+ // `scored_columnar` when `mem_doc_count == 0` and by the doc-values+ // prefilter + stored scan (where memtable `DocValuesHits` and segment+ // `score_doc` both assign constant score `1.0`) when `mem_doc_count > 0`+ // or columnar bails. Routing a top-level keyword `term` into segment FTS+ // gave segment hits BM25 (~0.00147) while memtable `DocValuesHits` gave+ // `1.0` — so `seg_can_enter` rejected every flushed segment against a+ // full memtable collector (`size:1` returned `mem000` over `seg0000`)+ // and `query_needs_fts` flipped true on a `term`-on-keyword query.+ let empty_kw_fields: std::collections::HashSet<String> = std::collections::HashSet::new();+ let fts_kw_fields: &std::collections::HashSet<String> = {+ let mut q = query;+ loop {+ match q {+ QueryNode::Constant { query, .. }+ | QueryNode::Boosted { query, .. }+ | QueryNode::Named { query, .. } => q = query,+ other => {+ break if matches!(other, QueryNode::Term { .. }) {+ &empty_kw_fields+ } else {+ &kw_fields+ };+ }+ }+ }+ };// ── B3: peeled function_score for the brute path ──────────────────// The single scoring clause of the request when it is a (wrapped)@@ -21437,7 +21468,7 @@ impl Index {query,&text_fields,&exact_fields,- &kw_fields,+ fts_kw_fields,mem_doc_count,pinned_probe,)@@ -22194,7 +22225,7 @@ impl Index {query,&text_fields,&exact_fields,- &kw_fields,+ fts_kw_fields,self.segment_analyzer_binding(),pinned_probe,)@@ -22441,7 +22472,7 @@ impl Index {query,&text_fields,&exact_fields,- &kw_fields,+ fts_kw_fields,self.segment_analyzer_binding(),pinned_probe,);@@ -22457,7 +22488,7 @@ impl Index {query,&text_fields,&exact_fields,- &kw_fields,+ fts_kw_fields,self.segment_analyzer_binding(),pinned_probe,);@@ -22612,17 +22643,19 @@ impl Index {let seg_id = meta.id.clone();let fts_dir = segments_dir.clone();- // #191 — on the count-authoritative stored-scan path each- // segment gets its OWN `materialisation_limit` of headroom:- // `scan_stored_section_into` stops at- // `all_hits.len() >= limit`, so a collector already filled by- // an earlier segment would let a genuinely competitive segment- // contribute nothing. Positions inside a segment ARE `seq_no`- // order (`drain_for_flush` and the merge both sort by- // `seq_no`), so this segment's first `cap` matches are its own- // `cap` best; the merge below then re-selects the global best- // `cap`. Peak is 2×cap, trimmed at the bottom of the loop.- let scan_limit = if count_authoritative && !count_only && sort_topk.is_none() {+ // #191 / #1359 — on the stored-scan path each segment gets its+ // OWN `materialisation_limit` of headroom, whether or not+ // `count_authoritative` is set: `scan_stored_section_into` stops+ // materialising hits at `all_hits.len() >= limit` (continuing to+ // tally `total_count` when `!count_authoritative`), so a+ // collector already filled by an earlier segment or the memtable+ // would otherwise let a genuinely competitive segment contribute+ // zero hits. Positions inside a segment ARE `seq_no` order+ // (`drain_for_flush` and the merge both sort by `seq_no`), so+ // this segment's first `cap` matches are its own `cap` best; the+ // merge below then re-selects the global best `cap`. Peak is+ // 2×cap, trimmed at the bottom of the loop.+ let scan_limit = if !count_only && sort_topk.is_none() {all_hits.len().saturating_add(materialisation_limit)} else {materialisation_limit@@ -22683,7 +22716,7 @@ impl Index {query,&text_fields,&exact_fields,- &kw_fields,+ fts_kw_fields,self.segment_analyzer_binding(),pinned_positions.as_ref()@@ -24069,7 +24102,7 @@ impl Index {// Trimmed hits stay in `seen_ids`: the cap-th key only ever// improves, so a document that lost the trim can never become// competitive again.- if count_authoritative+ if !fts_handled&& !count_only&& sort_topk.is_none()&& all_hits.len() != hits_before_segmentdiff --git a/engine/crates/xerj-engine/tests/tied_score_page_order.rs b/engine/crates/xerj-engine/tests/tied_score_page_order.rsindex 92bf1d850..3d402815d 100644--- a/engine/crates/xerj-engine/tests/tied_score_page_order.rs+++ b/engine/crates/xerj-engine/tests/tied_score_page_order.rs@@ -36,7 +36,7 @@use serde_json::{json, Value};use tempfile::TempDir;use xerj_common::config::Config;-use xerj_common::types::Schema;+use xerj_common::types::{FieldConfig, FieldType, Schema};use xerj_engine::Engine;use xerj_query::parse_request;@@ -46,6 +46,19 @@ fn make_engine(dir: &TempDir) -> Engine {Engine::new(config).expect("engine::new")}+/// `kw` is an explicit `FieldType::Keyword` (`doc_values: true`); `body` and+/// `kind` remain dynamically mapped as `FieldType::Text` (`doc_values: false`+/// since #1329), so `term` on `kind` exercises the non-authoritative stored+/// scan while `term` on `kw` exercises the keyword doc-values / columnar routes+/// (#1359).+fn tied_schema() -> Schema {+ let mut schema = Schema::empty();+ schema+ .fields+ .push(FieldConfig::new("kw", FieldType::Keyword));+ schema+}+fn req(from: usize, size: usize, q: &Value) -> xerj_query::ast::SearchRequest {parse_request(&json!({"from": from, "size": size, "query": q})).expect("parse_request")}@@ -63,6 +76,7 @@ async fn tied_corpus(idx: &std::sync::Arc<xerj_engine::index::Index>) -> Vec<Strjson!({"body": "listpack encoding for small collections","kind": "same",+ "kw": "same",}),).await@@ -82,18 +96,20 @@ fn page_ids(hits: &[xerj_query::Hit]) -> Vec<String> {async fn tied_scores_bounded_pages_are_prefixes_of_the_full_page() {let dir = TempDir::new().unwrap();let engine = make_engine(&dir);- engine.create_index("tie", Schema::empty()).unwrap();+ engine.create_index("tie", tied_schema()).unwrap();let idx = engine.get_index("tie").unwrap();let inserted = tied_corpus(&idx).await;// Each shape exercises a different collector:// match → scored FTS admission walk (`page_worst`)- // term → count-authoritative stored scan (`scan_page_worst`)+ // term → non-authoritative dynamic-text stored scan (#1359)+ // term_keyword → keyword columnar / doc-values prefiltered scan (#1359)// match_all → columnar top-k// constant_score → columnar top-k with the wrapper's constant scorefor (label, q) in [("match", json!({"match": {"body": "listpack"}})),("term", json!({"term": {"kind": "same"}})),+ ("term_keyword", json!({"term": {"kw": "same"}})),("match_all", json!({"match_all": {}})),("constant_score",@@ -250,7 +266,7 @@ async fn tie_straddling_a_page_boundary_resolves_the_same_way_at_every_size() {async fn tied_scores_page_the_same_way_with_an_unflushed_memtable() {let dir = TempDir::new().unwrap();let engine = make_engine(&dir);- engine.create_index("mixed", Schema::empty()).unwrap();+ engine.create_index("mixed", tied_schema()).unwrap();let idx = engine.get_index("mixed").unwrap();let mut inserted = Vec::new();@@ -259,7 +275,7 @@ async fn tied_scores_page_the_same_way_with_an_unflushed_memtable() {let id = format!("seg{batch}{i:03}");idx.index_document(Some(id.clone()),- json!({"body": "listpack encoding", "kind": "same"}),+ json!({"body": "listpack encoding", "kind": "same", "kw": "same"}),).await.unwrap();@@ -274,7 +290,7 @@ async fn tied_scores_page_the_same_way_with_an_unflushed_memtable() {let id = format!("mem{i:03}");idx.index_document(Some(id.clone()),- json!({"body": "listpack encoding", "kind": "same"}),+ json!({"body": "listpack encoding", "kind": "same", "kw": "same"}),).await.unwrap();@@ -285,6 +301,7 @@ async fn tied_scores_page_the_same_way_with_an_unflushed_memtable() {for (label, q) in [("match", json!({"match": {"body": "listpack"}})),("term", json!({"term": {"kind": "same"}})),+ ("term_keyword", json!({"term": {"kw": "same"}})),("match_all", json!({"match_all": {}})),("constant_score",@@ -343,7 +360,7 @@ async fn tied_scores_page_the_same_way_with_an_unflushed_memtable() {async fn tied_scores_page_the_same_way_with_no_flush_at_all() {let dir = TempDir::new().unwrap();let engine = make_engine(&dir);- engine.create_index("memonly", Schema::empty()).unwrap();+ engine.create_index("memonly", tied_schema()).unwrap();let idx = engine.get_index("memonly").unwrap();// Comfortably past the 256-hit floor. `size:300` implies a 400-hit cap@@ -355,7 +372,7 @@ async fn tied_scores_page_the_same_way_with_no_flush_at_all() {let id = format!("m{i:04}");idx.index_document(Some(id.clone()),- json!({"body": "listpack encoding", "kind": "same"}),+ json!({"body": "listpack encoding", "kind": "same", "kw": "same"}),).await.unwrap();@@ -365,6 +382,7 @@ async fn tied_scores_page_the_same_way_with_no_flush_at_all() {for (label, q) in [("match", json!({"match": {"body": "listpack"}})),("term", json!({"term": {"kind": "same"}})),+ ("term_keyword", json!({"term": {"kw": "same"}})),("match_all", json!({"match_all": {}})),("constant_score",