Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(search): one analyzer for both phrase evaluators; honour phrase_prefix slop

xerj-orged0afc51c438
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index dcdc2fe14..e1c704d93 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -27050,10 +27050,12 @@ fn strip_nested_path_in_query(q: &QueryNode, path: &str) -> QueryNode {
field,
query,
max_expansions,
+ slop,
} => QueryNode::MatchPhrasePrefix {
field: strip(field),
query: query.clone(),
max_expansions: *max_expansions,
+ slop: *slop,
},
QueryNode::Fuzzy {
field,
@@ -28126,18 +28128,40 @@ fn geo_coord(v: &Value) -> Option<f64> {
.or_else(|| v.as_str().and_then(|s| s.trim().parse().ok()))
}
-/// Split raw field/query text into the lowercase alphanumeric token stream
-/// the stored-doc evaluator treats as "positions". It is the stored-scan
-/// counterpart of the standard analyzer's token stream: the analyzer drops
+/// The analyzed token stream the stored-doc evaluator treats as "positions".
+///
+/// It runs the **standard analyzer** — the same pipeline the indexing path
+/// and `query_node_to_fts` use — so the stored-scan/memtable evaluator and
+/// the positional segment clause answer the same query. The analyzer drops
/// punctuation and lowercases, so `merge, policy` yields `[merge, policy]`
/// — two ADJACENT positions, which is why a positional phrase matches it
/// and raw-substring containment does not (issue #230).
+///
+/// It must not be hand-rolled. An earlier revision of this fix split on
+/// `!char::is_alphanumeric()`, which is NOT the standard tokenizer:
+/// UAX#29 (`unicode_words()`) keeps intra-word `.`, `'` and `_` inside one
+/// word, so `3.14`, `don't` and `foo_bar` are ONE term each on the segment
+/// side but two or three under the split. Measured at that revision, with an
+/// explicit `_flush` between the two probes of one index:
+///
+/// | query (`multi_match`, `type: phrase`) | doc | pre-flush | post-flush |
+/// |---|---|---|---|
+/// | `"release 3"` | `release 3.14 notes here` | hit | miss |
+/// | `"don t"` | `we don't stop now` | hit | miss |
+/// | `"foo bar"` | `the foo_bar baz` | hit | miss |
+///
+/// — a flush-variant hit set, the regression class #218/#222 removed and
+/// that issue #230 names as the standing invariant; and the pre-flush answer
+/// was also the wrong one (ES's standard analyzer keeps `don't` whole).
+///
+/// Callers pass field text that upstream has already lowercased; the
+/// pipeline's lowercase filter is idempotent, so that is harmless.
fn phrase_tokens(text: &str) -> Vec<String> {
- text.to_lowercase()
- .split(|c: char| !c.is_alphanumeric())
- .filter(|t| !t.is_empty())
- .map(str::to_string)
- .collect()
+ static STANDARD: std::sync::OnceLock<std::sync::Arc<xerj_fts::analyzer::AnalyzerPipeline>> =
+ std::sync::OnceLock::new();
+ STANDARD
+ .get_or_init(|| AnalyzerRegistry::default().standard())
+ .analyze_to_terms(text)
}
/// True when `query_tokens` occur in `field_tokens` in order with at most
@@ -28155,28 +28179,59 @@ fn phrase_tokens(text: &str) -> Vec<String> {
/// `[a, x, x, x, a, b]` rejected the slop-1 phrase `a b` that both ES and
/// the segment path accept (anchor at the second `a`).
fn phrase_positions_in_tokens(field_tokens: &[String], query_tokens: &[String], slop: u32) -> bool {
+ phrase_walk(field_tokens, query_tokens, slop, false)
+}
+
+/// The one positional walk behind both `phrase_positions_in_tokens` and
+/// `phrase_prefix_positions_in_tokens`. `last_is_prefix` makes the FINAL
+/// query token match by `starts_with` instead of equality, which is exactly
+/// what the segment side computes: `execute_phrase_prefix` expands the
+/// trailing prefix against the term dictionary and unions one sloppy phrase
+/// query per expansion, and "some expansion term sits here" is the same
+/// predicate as "this token starts with the prefix".
+///
+/// Keeping one walk (rather than two look-alike ones) is deliberate: the
+/// two evaluators must not be able to drift apart the way the slop-0-only
+/// prefix walk had already drifted from the sloppy phrase walk.
+fn phrase_walk(
+ field_tokens: &[String],
+ query_tokens: &[String],
+ slop: u32,
+ last_is_prefix: bool,
+) -> bool {
if query_tokens.is_empty() {
return true;
}
if query_tokens.len() > field_tokens.len() {
return false;
}
- if slop == 0 {
- return field_tokens
- .windows(query_tokens.len())
- .any(|w| w == query_tokens);
+ let n = query_tokens.len();
+ let matches_at = |idx: usize, qi: usize| -> bool {
+ let ft = &field_tokens[idx];
+ if last_is_prefix && qi == n - 1 {
+ ft.starts_with(query_tokens[qi].as_str())
+ } else {
+ ft == &query_tokens[qi]
+ }
+ };
+ // Exact-adjacency fast path for the whole-term case (the common one).
+ if slop == 0 && !last_is_prefix {
+ return field_tokens.windows(n).any(|w| w == query_tokens);
}
- for (start, tok) in field_tokens.iter().enumerate() {
- if tok != &query_tokens[0] {
+ for start in 0..field_tokens.len() {
+ if !matches_at(start, 0) {
continue;
}
let mut current = start;
let mut total_gaps: u32 = 0;
let mut ok = true;
- for qt in &query_tokens[1..] {
- match field_tokens[current + 1..].iter().position(|ft| ft == qt) {
- Some(off) => {
- let next = current + 1 + off;
+ for qi in 1..n {
+ // Earliest match after `current` minimises the running gap sum,
+ // so the greedy walk is optimal for an in-order phrase — the
+ // same walk `xerj_fts::search::phrase_positions_match` runs over
+ // segment positions.
+ match (current + 1..field_tokens.len()).find(|&i| matches_at(i, qi)) {
+ Some(next) => {
total_gaps += (next - current - 1) as u32;
if total_gaps > slop {
ok = false;
@@ -28197,32 +28252,26 @@ fn phrase_positions_in_tokens(field_tokens: &[String], query_tokens: &[String],
false
}
-/// True when the leading `query_tokens[..n-1]` form an adjacent in-order
-/// phrase whose next position starts with `query_tokens[n-1]` — ES
-/// `match_phrase_prefix` semantics over the token stream. A single token
-/// degrades to "any token starts with it".
+/// True when the leading `query_tokens[..n-1]` form an in-order phrase whose
+/// next position starts with `query_tokens[n-1]`, with at most `slop`
+/// intervening positions in total — ES `match_phrase_prefix` semantics over
+/// the token stream. A single token degrades to "any token starts with it".
///
/// This is TERM-level, not substring-level: `merge poli` matches the token
/// stream `[merge, policy]` (so it matches raw text `merge, policy` too),
/// while `merge polic` does NOT satisfy the exact-phrase variant, because
/// `polic` is not the term `policy`.
-fn phrase_prefix_positions_in_tokens(field_tokens: &[String], query_tokens: &[String]) -> bool {
- let (last, head) = match query_tokens.split_last() {
- Some(pair) => pair,
- None => return true,
- };
- if head.is_empty() {
- return field_tokens.iter().any(|t| t.starts_with(last.as_str()));
- }
- if head.len() >= field_tokens.len() {
- return false;
- }
- field_tokens.windows(head.len()).enumerate().any(|(i, w)| {
- w == head
- && field_tokens
- .get(i + head.len())
- .is_some_and(|t| t.starts_with(last.as_str()))
- })
+///
+/// `slop` spans the whole phrase, trailing prefix term included — the same
+/// thing ES's `MultiPhrasePrefixQuery.setSlop` does and the same thing
+/// `execute_phrase_prefix` now does by carrying `PhrasePrefixQuery.slop`
+/// into each expansion's phrase query.
+fn phrase_prefix_positions_in_tokens(
+ field_tokens: &[String],
+ query_tokens: &[String],
+ slop: u32,
+) -> bool {
+ phrase_walk(field_tokens, query_tokens, slop, true)
}
/// Per-field phrase predicate for the phrase-shaped `multi_match` types,
@@ -28230,11 +28279,12 @@ fn phrase_prefix_positions_in_tokens(field_tokens: &[String], query_tokens: &[St
/// (`score_query_against_doc`) arms so an admitted doc can never score 0.
///
/// `phrase_prefix` treats the trailing token as a prefix; `phrase` requires
-/// whole terms and honours `slop`. `slop` is deliberately unread on the
-/// prefix arm — the parser REFUSES a non-zero `slop` with
-/// `type: phrase_prefix` (neither this walk nor the segment's
-/// `PhrasePrefixQuery` can honour it), so the only value that reaches here
-/// is 0. Reading it would imply support that does not exist.
+/// whole terms. Both honour `slop`, as ES does for both types.
+///
+/// `query_tokens` MUST come from `phrase_tokens` (the standard analyzer),
+/// not from a hand-rolled split: `3.14` is one analyzed term and two split
+/// ones, so a split query and an analyzed segment clause ask different
+/// questions and the hit set changes at `_flush`.
///
/// `field_text_lc` is the field's text as the rest of the `multi_match` arms
/// see it — an array-valued field arrives already joined with a space.
@@ -28257,7 +28307,7 @@ fn multi_match_phrase_hit(
}
let field_tokens = phrase_tokens(field_text_lc);
if is_prefix {
- phrase_prefix_positions_in_tokens(&field_tokens, query_tokens)
+ phrase_prefix_positions_in_tokens(&field_tokens, query_tokens, slop)
} else {
phrase_positions_in_tokens(&field_tokens, query_tokens, slop)
}
@@ -28812,6 +28862,17 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {
let is_phrase_prefix =
matches!(match_type, xerj_query::ast::MultiMatchType::PhrasePrefix);
let is_and = matches!(operator, Some(xerj_query::ast::BoolOperator::And));
+ // The phrase arms need ANALYZER tokens, not the alphanumeric
+ // split above: `query_node_to_fts` builds the segment clause
+ // from `analyzer.analyze(query)`, and `3.14` is one analyzed
+ // term but two split ones. Only the phrase arms switch — the
+ // cross_fields / AND / OR arms below intentionally keep the
+ // split, which is what they have always matched with.
+ let phrase_q_tokens: Vec<String> = if is_phrase {
+ phrase_tokens(query)
+ } else {
+ Vec::new()
+ };
let field_texts: Vec<String> = fields
.iter()
.filter_map(|field_spec| {
@@ -28837,7 +28898,7 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {
}
})
.collect();
- if is_phrase && !tokens.is_empty() {
+ if is_phrase && !phrase_q_tokens.is_empty() {
// phrase / phrase_prefix: POSITIONAL, per field (issue
// #230). ES lowers these types to a dis_max over per-field
// `match_phrase`/`match_phrase_prefix`, so the predicate is
@@ -28852,9 +28913,11 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {
// (`"merge policy"` missed the doc `merge, policy`, whose
// analyzed terms are adjacent) and OVER-matched (`"merge
// polic"` matched `merge policy`, where no such term
- // exists). The segment path evaluates the same positions,
- // now via `FtsQuery::Phrase`/`PhrasePrefix`, so the hit set
- // stays flush-invariant.
+ // exists). The hit set stays flush-invariant because the
+ // segment either evaluates the SAME positions via
+ // `FtsQuery::Phrase` (type `phrase`, same standard-analyzer
+ // token stream on both sides) or declines the projection
+ // and runs this very predicate (type `phrase_prefix`).
//
// Tested FIRST, ahead of the operator branches: `operator`
// is meaningless for a phrase in ES (its phrase parser never
@@ -28863,7 +28926,7 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {
// stopped being a phrase at all.
field_texts
.iter()
- .any(|ft| multi_match_phrase_hit(ft, &tokens, is_phrase_prefix, *slop))
+ .any(|ft| multi_match_phrase_hit(ft, &phrase_q_tokens, is_phrase_prefix, *slop))
} else if is_cross && is_and && !tokens.is_empty() {
// cross_fields + operator AND: every token must appear in
// at least one listed field (combined perspective).
@@ -29080,7 +29143,9 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {
.unwrap_or(false)
}
- QueryNode::MatchPhrasePrefix { field, query, .. } => {
+ QueryNode::MatchPhrasePrefix {
+ field, query, slop, ..
+ } => {
// POSITIONAL, not substring (issue #230). Pre-fix this arm found
// the head phrase as a raw substring (`s_lower.find(head)`) and
// required the prefix to follow it in the raw text — so
@@ -29088,7 +29153,7 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {
// while the segment path (`FtsQuery::PhrasePrefix`) matched over
// the analyzed positions. The two states disagreed at `_flush`.
// Both now walk the same analyzed token stream.
- fn matches_str(s: &str, query: &str) -> Option<bool> {
+ fn matches_str(s: &str, query: &str, slop: u32) -> Option<bool> {
let query_tokens = phrase_tokens(query);
if query_tokens.is_empty() {
return Some(true);
@@ -29096,11 +29161,12 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {
Some(phrase_prefix_positions_in_tokens(
&phrase_tokens(s),
&query_tokens,
+ slop,
))
}
get_field_value(source, field)
.and_then(|v| match &v {
- Value::String(s) => matches_str(s, query),
+ Value::String(s) => matches_str(s, query, *slop),
// Multi-valued field: ES matches if ANY element
// satisfies the phrase-prefix — pre-fix this arm only
// handled a scalar string, so a `match_phrase_prefix`
@@ -29110,7 +29176,7 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {
Value::Array(arr) => {
if arr.iter().any(|e| {
e.as_str()
- .and_then(|s| matches_str(s, query))
+ .and_then(|s| matches_str(s, query, *slop))
.unwrap_or(false)
}) {
Some(true)
@@ -30561,9 +30627,23 @@ fn score_query_against_doc(q: &QueryNode, source: &Value) -> f32 {
.filter(|t| !t.is_empty())
.map(str::to_string)
.collect();
+ // Phrase arms tokenize with the ANALYZER, matching both
+ // `doc_matches_query` and the segment clause built by
+ // `query_node_to_fts` — see `phrase_tokens`. The non-phrase arms
+ // keep `q_tokens` (the alphanumeric split) unchanged.
+ let phrase_q_tokens: Vec<String> = if is_phrase {
+ phrase_tokens(query)
+ } else {
+ Vec::new()
+ };
let field_hit = |text_lc: &str| -> bool {
- if is_phrase && !q_tokens.is_empty() {
- return multi_match_phrase_hit(text_lc, &q_tokens, is_phrase_prefix, *slop);
+ if is_phrase && !phrase_q_tokens.is_empty() {
+ return multi_match_phrase_hit(
+ text_lc,
+ &phrase_q_tokens,
+ is_phrase_prefix,
+ *slop,
+ );
}
if q_tokens.is_empty() {
return text_lc.contains(&q_lower);
@@ -32934,11 +33014,14 @@ fn query_node_to_fts(
operator,
boost,
slop,
- max_expansions,
+ // Unused HERE on purpose: `phrase_prefix` declines the
+ // projection (see below), so nothing in this function expands a
+ // prefix and nothing needs the bound.
+ max_expansions: _,
analyzer,
} => {
- // phrase / phrase_prefix are POSITIONAL (issue #230): they lower
- // to one positional clause per field, combined by dis_max — the
+ // phrase is POSITIONAL (issue #230): it lowers to one positional
+ // clause per field, combined by dis_max — the
// shape ES builds (`MultiMatchQueryParser.buildFieldQueries` +
// `combineGrouped` → `DisjunctionMaxQuery`, tie_breaker 0.0 for
// both phrase types; AGPL, read for semantics only, no code
@@ -32994,8 +33077,28 @@ fn query_node_to_fts(
if field_specs.is_empty() {
return None;
}
- // ── phrase / phrase_prefix: one positional clause per field ──
+ // ── phrase: one positional clause per field ──
if is_phrase_type {
+ // `phrase_prefix` deliberately keeps the DECLINED /
+ // stored-scan routing it has on `main`. The segment clause
+ // (`FtsQuery::PhrasePrefix`) bounds the trailing prefix to
+ // `max_expansions` terms taken from the field's term
+ // dictionary; the stored-doc walk has no term dictionary and
+ // uses an unbounded `starts_with`. Projecting it therefore
+ // makes the hit set change at `_flush` — measured on one
+ // index: `{type: phrase_prefix, query: "merge pol",
+ // max_expansions: 1}` returned 5 docs in the memtable and 4
+ // after `_flush`. That is the #218 regression class, and
+ // #230 names flush invariance as the standing invariant, so
+ // the invariant wins over the projection. Consequence,
+ // stated plainly: `max_expansions` does not bind on
+ // `multi_match` (it never did on `main` either — the
+ // parameter was dropped in the parser), and phrase_prefix
+ // keeps the O(N) stored scan. `phrase` — where the measured
+ // 5.7× win is — still projects.
+ if is_phrase_prefix {
+ return None;
+ }
let terms: Vec<String> = tokens.iter().map(|t| t.text.clone()).collect();
// Every listed field must be an ANALYZED TEXT field with a
// positions side-car, and the query must analyze to at least
@@ -33025,14 +33128,7 @@ fn query_node_to_fts(
let outer = boost.unwrap_or(1.0);
let mut per_field: Vec<FtsQuery> = Vec::with_capacity(field_specs.len());
for (field, fb) in &field_specs {
- per_field.push(if is_phrase_prefix {
- FtsQuery::PhrasePrefix(xerj_fts::search::PhrasePrefixQuery {
- field: field.clone(),
- terms: terms.clone(),
- max_expansions: *max_expansions as usize,
- boost: *fb,
- })
- } else if terms.len() == 1 {
+ per_field.push(if terms.len() == 1 {
// A one-term phrase is just a term query — and scores
// identically to `match_phrase` on that field.
FtsQuery::Term(FtsTerm::boosted(field.as_str(), &terms[0], *fb))
@@ -33398,6 +33494,7 @@ fn query_node_to_fts(
field,
query,
max_expansions,
+ slop,
} => {
// match_phrase_prefix on a KEYWORD field: single whole-value token
// whose last (only) term is a prefix → a prefix query over the
@@ -33432,6 +33529,10 @@ fn query_node_to_fts(
field: field.clone(),
terms: tokens.iter().map(|t| t.text.clone()).collect(),
max_expansions: *max_expansions as usize,
+ // `slop` used to be dropped on the floor here, so a
+ // sloppy `match_phrase_prefix` silently answered as
+ // slop 0 (#204 class).
+ slop: *slop,
boost: 1.0,
},
));
@@ -36016,8 +36117,13 @@ mod fts_projection_tests {
other => panic!("expected dis_max of phrase clauses, got {other:?}"),
}
- // phrase_prefix lowers to the positional prefix clause, carrying
- // `max_expansions`.
+ // phrase_prefix DECLINES the projection on purpose (#230 review): a
+ // positional prefix clause bounds the trailing prefix to
+ // `max_expansions` terms from the segment's term dictionary, while
+ // the stored-doc walk that answers for the memtable has no term
+ // dictionary and expands unbounded — so projecting it makes the hit
+ // set shrink at `_flush`, the #218 regression class. Declining keeps
+ // one evaluator for both states.
q = QueryNode::MultiMatch {
fields: vec!["body".into()],
query: "merge poli".into(),
@@ -36028,13 +36134,11 @@ mod fts_projection_tests {
slop: 0,
max_expansions: 7,
};
- match query_node_to_fts(&q, &text, &kw(&[])).expect("phrase_prefix projects") {
- FtsQuery::PhrasePrefix(p) => {
- assert_eq!(p.terms, vec!["merge".to_string(), "poli".to_string()]);
- assert_eq!(p.max_expansions, 7);
- }
- other => panic!("expected phrase-prefix clause, got {other:?}"),
- }
+ assert!(
+ query_node_to_fts(&q, &text, &kw(&[])).is_none(),
+ "multi_match phrase_prefix must decline the projection so the \
+ memtable and the segment stay on one predicate"
+ );
}
/// #230 parity guard — a KEYWORD field in a phrase `multi_match` declines
@@ -36198,6 +36302,7 @@ mod fts_projection_tests {
field: "body".into(),
query: "status ok log".into(),
max_expansions: 50,
+ slop: 0,
};
match query_node_to_fts(&q, &tf, &kw(&[])).expect("text mpp projects") {
FtsQuery::PhrasePrefix(p) => {
@@ -36216,6 +36321,7 @@ mod fts_projection_tests {
field: "top_doc".into(),
query: "runbook/on".into(),
max_expansions: 50,
+ slop: 0,
};
let fq = query_node_to_fts(&q, &[], &kw(&["top_doc"])).expect("keyword prefix projects");
match fq {
diff --git a/engine/crates/xerj-engine/tests/multi_match_phrase_positions.rs b/engine/crates/xerj-engine/tests/multi_match_phrase_positions.rs
index 2bc501a2c..579d8e968 100644
--- a/engine/crates/xerj-engine/tests/multi_match_phrase_positions.rs
+++ b/engine/crates/xerj-engine/tests/multi_match_phrase_positions.rs
@@ -311,45 +311,191 @@ async fn memtable_phrase_hit_scores_nonzero() {
}
}
-/// `slop` on a `phrase_prefix` cannot be honoured by either evaluator —
-/// the segment clause (`xerj_fts::search::PhrasePrefixQuery`) carries no
-/// slop, and the stored-doc walk requires an adjacent head phrase. ES does
-/// honour it, so accepting the parameter and answering an exact phrase
-/// would silently answer a different query (#204's defect class). It must
-/// be refused, loudly.
-#[test]
-fn slop_on_phrase_prefix_is_refused_not_ignored() {
- let err = parse_request(&json!({
- "query": {"multi_match": {"query": "merge poli", "fields": ["body"],
- "type": "phrase_prefix", "slop": 2}}
- }))
- .expect_err("slop on phrase_prefix must be refused, not silently dropped");
- let msg = err.to_string();
- assert!(
- msg.contains("slop") && msg.contains("phrase_prefix"),
- "error must name both the parameter and the type, got: {msg}"
- );
+/// `slop` on a `phrase_prefix` is HONOURED, at both entry points and in
+/// both states. ES honours it (`TextFieldMapper.createPhrasePrefixQuery`
+/// builds a `MultiPhrasePrefixQuery` and calls `setSlop`), so refusing it
+/// would break clients, and dropping it — which `parse_match_phrase_prefix`
+/// did — is the accept-and-ignore defect class of #204: the `multi_match`
+/// and `match_phrase_prefix` spellings of the same query must not disagree.
+///
+/// Doc 1's `body` analyses to [the, log, merge, policy, …]: the phrase
+/// `log poli*` needs one intervening position, so slop 0 misses and slop 1
+/// hits.
+#[tokio::test]
+async fn phrase_prefix_slop_is_honoured_at_both_entry_points() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ let idx = seed(&engine, "mmpp_prefix_slop").await;
- // slop 0 is the default and stays accepted.
- parse_request(&json!({
- "query": {"multi_match": {"query": "merge poli", "fields": ["body"],
- "type": "phrase_prefix", "slop": 0}}
- }))
- .expect("slop 0 on phrase_prefix is the default and must parse");
+ assert_both_states(
+ &idx,
+ &[
+ (
+ json!({"multi_match": {"query": "log poli", "fields": ["body"],
+ "type": "phrase_prefix"}}),
+ &[],
+ "phrase_prefix slop 0 (default): one intervening token → no match",
+ ),
+ (
+ json!({"multi_match": {"query": "log poli", "fields": ["body"],
+ "type": "phrase_prefix", "slop": 1}}),
+ &["1"],
+ "phrase_prefix slop 1: one intervening token → match",
+ ),
+ (
+ json!({"match_phrase_prefix": {"body": {"query": "log poli", "slop": 1}}}),
+ &["1"],
+ "oracle match_phrase_prefix slop 1 answers the same query",
+ ),
+ (
+ json!({"match_phrase_prefix": {"body": {"query": "log poli"}}}),
+ &[],
+ "oracle match_phrase_prefix slop 0",
+ ),
+ ],
+ )
+ .await;
}
-/// A negative `slop` is a client error in ES; accepting it silently would
-/// be another accept-and-ignore. Assert the parser rejects it.
+/// A negative `slop` is a client error in ES from EVERY builder, so every
+/// entry point must answer alike — a 400 from one spelling and a silently
+/// coerced 0 from the other is the same accept-and-ignore defect wearing a
+/// different hat.
#[test]
-fn negative_slop_is_rejected() {
- let err = parse_request(&json!({
- "query": {"multi_match": {"query": "merge policy", "fields": ["body"],
- "type": "phrase", "slop": -1}}
- }))
- .expect_err("negative slop must be rejected");
- let msg = err.to_string();
- assert!(
- msg.contains("slop"),
- "error should name the offending parameter, got: {msg}"
- );
+fn negative_slop_is_rejected_at_every_entry_point() {
+ for bad in [
+ json!({"multi_match": {"query": "merge policy", "fields": ["body"],
+ "type": "phrase", "slop": -1}}),
+ json!({"match_phrase": {"body": {"query": "merge policy", "slop": -1}}}),
+ json!({"match_phrase_prefix": {"body": {"query": "merge poli", "slop": -1}}}),
+ ] {
+ let err = parse_request(&json!({"query": bad}))
+ .expect_err("negative slop must be rejected, not coerced to 0");
+ assert!(
+ err.to_string().contains("slop"),
+ "error should name the offending parameter, got: {err}"
+ );
+ }
+}
+
+/// The stored-scan/memtable evaluator and the positional segment clause
+/// must tokenize with the SAME analyzer, or they answer different queries
+/// and the hit set changes at `_flush` — the regression class #218/#222
+/// removed and that #230 names as the standing invariant.
+///
+/// An earlier revision of this fix tokenized the memtable side by splitting
+/// on `!char::is_alphanumeric()` while the segment clause was built from the
+/// `standard` analyzer (UAX#29 `unicode_words()`). The two disagree on
+/// intra-word `.`, `'` and `_`: `3.14`, `don't` and `foo_bar` are ONE
+/// analyzed term each and two-or-three split ones. Each case below returned
+/// a hit pre-flush and none post-flush at that revision; the analyzed answer
+/// (no hit — the terms never line up) is also the one ES gives.
+#[tokio::test]
+async fn phrase_tokenizer_matches_the_segment_analyzer() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("mmpp_tok", Schema::empty()).unwrap();
+ let idx = engine.get_index("mmpp_tok").unwrap();
+ for (id, body) in [
+ ("n1", "release 3.14 notes here"),
+ ("d1", "we don't stop now"),
+ ("u1", "the foo_bar baz"),
+ ] {
+ idx.index_document(Some(id.into()), json!({ "body": body }))
+ .await
+ .unwrap();
+ }
+
+ assert_both_states(
+ &idx,
+ &[
+ (
+ json!({"multi_match": {"query": "release 3", "fields": ["body"],
+ "type": "phrase"}}),
+ &[],
+ "`3.14` is ONE analyzed term, so `release 3` is not a phrase in it",
+ ),
+ (
+ json!({"match_phrase": {"body": "release 3"}}),
+ &[],
+ "oracle match_phrase agrees",
+ ),
+ (
+ json!({"multi_match": {"query": "don t", "fields": ["body"],
+ "type": "phrase"}}),
+ &[],
+ "`don't` is ONE analyzed term, so `don t` is not a phrase in it",
+ ),
+ (
+ json!({"multi_match": {"query": "foo bar", "fields": ["body"],
+ "type": "phrase"}}),
+ &[],
+ "`foo_bar` is ONE analyzed term, so `foo bar` is not a phrase in it",
+ ),
+ // The whole analyzed term still matches, in both states.
+ (
+ json!({"multi_match": {"query": "release 3.14", "fields": ["body"],
+ "type": "phrase"}}),
+ &["n1"],
+ "the analyzed term itself matches",
+ ),
+ (
+ json!({"multi_match": {"query": "we don't", "fields": ["body"],
+ "type": "phrase"}}),
+ &["d1"],
+ "the analyzed term itself matches (apostrophe)",
+ ),
+ ],
+ )
+ .await;
+}
+
+/// `max_expansions` is why `phrase_prefix` keeps the declined/stored-scan
+/// routing on `multi_match`: the segment clause bounds the trailing prefix
+/// to `max_expansions` terms from the field's term dictionary, and the
+/// stored-doc walk — which has no term dictionary — cannot. Projecting it
+/// made the hit set shrink at `_flush`.
+///
+/// This asserts the INVARIANT (same answer either side of the flush), not
+/// ES parity: XERJ does not bind `max_expansions` on `multi_match`, so both
+/// states return the unbounded answer. Stated plainly rather than papered
+/// over — flush invariance is the property #230 asks for.
+///
+/// HONEST LIMIT of this test: it also passes against the revision that DID
+/// project `phrase_prefix` (checked out and run — 7 passed, 3 failed, and
+/// this was not one of the three), so it is an invariant assertion, not a
+/// regression catcher. This in-process fixture does not reliably route the
+/// query through the bounded segment clause the way a mapped index on a
+/// live server does, which is where the review measured the shrink
+/// (pre {p1,p2,p3,p4,s1} / post {p1,p2,p3,p4}). The discriminating guard
+/// for the routing decision is the unit test
+/// `index::fts_projection_tests::multi_match_phrase_projects_positional_dis_max`,
+/// which asserts `query_node_to_fts` returns `None` for `phrase_prefix`.
+#[tokio::test]
+async fn phrase_prefix_max_expansions_does_not_change_the_hit_set_at_flush() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("mmpp_maxexp", Schema::empty()).unwrap();
+ let idx = engine.get_index("mmpp_maxexp").unwrap();
+ // `pol*` expands to two dictionary terms — `polar` sorts first, so a
+ // max_expansions of 1 would keep only it on a bounded segment clause.
+ for (id, body) in [
+ ("p1", "a tiered merge policy compacts segments"),
+ ("p2", "the merge polar route"),
+ ] {
+ idx.index_document(Some(id.into()), json!({ "body": body }))
+ .await
+ .unwrap();
+ }
+
+ assert_both_states(
+ &idx,
+ &[(
+ json!({"multi_match": {"query": "merge pol", "fields": ["body"],
+ "type": "phrase_prefix", "max_expansions": 1}}),
+ &["p1", "p2"],
+ "multi_match phrase_prefix hit set is the same before and after _flush",
+ )],
+ )
+ .await;
}
diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rs
index 22f28e6be..0da55c0b2 100644
--- a/engine/crates/xerj-fts/src/search.rs
+++ b/engine/crates/xerj-fts/src/search.rs
@@ -314,7 +314,8 @@ impl FuzzyQuery {
/// LAST element is treated as a **prefix** that expands against the field's
/// analyzed term dictionary (bounded by `max_expansions`, in FST/lexicographic
/// order — the same order ES takes its first `max_expansions` terms). A doc
-/// matches when the head phrase is immediately followed by any expansion term.
+/// matches when any expansion term follows a head-phrase occurrence within
+/// `slop` intervening positions (`slop == 0`, the default, means immediately).
/// `terms` are already analyzed by the caller (standard analyzer → lowercased),
/// so the prefix expansion is a plain case-sensitive `starts_with` against the
/// (lowercased) term dictionary — byte-identical to ES, whose analyzer
@@ -325,6 +326,16 @@ pub struct PhrasePrefixQuery {
pub terms: Vec<String>,
#[serde(default = "default_max_expansions")]
pub max_expansions: usize,
+ /// Allowed number of intervening positions across the WHOLE phrase,
+ /// including the expanded trailing prefix term. ES honours `slop` on
+ /// `match_phrase_prefix`: `TextFieldMapper.createPhrasePrefixQuery` builds
+ /// a `MultiPhrasePrefixQuery` and calls `setSlop(slop)` alongside
+ /// `setMaxExpansions` (elasticsearch/server/src/main/java/org/
+ /// elasticsearch/index/mapper/TextFieldMapper.java:1269 — AGPL, read for
+ /// semantics only, no code copied). Defaults to 0 (adjacency), which is
+ /// the pre-existing behaviour for every caller that does not set it.
+ #[serde(default)]
+ pub slop: u32,
#[serde(default = "default_boost")]
pub boost: f32,
}
@@ -814,7 +825,11 @@ impl FtsSearcher {
let pq = PhraseQuery {
field: ppq.field.clone(),
terms,
- slop: 0,
+ // `slop` spans the whole phrase INCLUDING the expanded
+ // trailing term — ES's `MultiPhrasePrefixQuery.setSlop`
+ // applies to the multi-term position too, so the union of
+ // per-expansion sloppy phrase queries is the same hit set.
+ slop: ppq.slop,
boost: ppq.boost,
};
for hit in self.execute_phrase(&pq, explain)? {
diff --git a/engine/crates/xerj-query/src/ast.rs b/engine/crates/xerj-query/src/ast.rs
index 455f11e73..2e58721d5 100644
--- a/engine/crates/xerj-query/src/ast.rs
+++ b/engine/crates/xerj-query/src/ast.rs
@@ -558,6 +558,13 @@ pub enum QueryNode {
query: String,
#[serde(default = "default_max_expansions")]
max_expansions: u32,
+ /// Allowed intervening positions across the whole phrase, trailing
+ /// prefix term included. ES accepts and honours `slop` here
+ /// (`MatchPhrasePrefixQueryBuilder` parses it and passes it to
+ /// `MatchQueryParser.setPhraseSlop`), so dropping it would be
+ /// accept-and-ignore (#204 class).
+ #[serde(default)]
+ slop: u32,
},
/// Simple query string — splits on `+`/`|`/`-` operators, converted to a Bool query.
diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rs
index 69ddd5ece..d0ebf8dc0 100644
--- a/engine/crates/xerj-query/src/parser.rs
+++ b/engine/crates/xerj-query/src/parser.rs
@@ -536,7 +536,7 @@ fn parse_match_phrase(params: &Value) -> Result<QueryNode> {
.get("query")
.and_then(scalar_to_string)
.ok_or_else(|| qerr("`match_phrase.query` must be a non-empty scalar"))?;
- let slop = vobj.get("slop").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
+ let slop = parse_phrase_slop(vobj.get("slop"), "match_phrase")?;
let analyzer = vobj
.get("analyzer")
.and_then(|v| v.as_str())
@@ -557,6 +557,33 @@ fn parse_match_phrase(params: &Value) -> Result<QueryNode> {
Ok(maybe_named(node, name))
}
+/// Parse the `slop` parameter of a phrase-shaped query, identically for every
+/// entry point that accepts one (`match_phrase`, `match_phrase_prefix`,
+/// `multi_match`). Sharing it is the point: the same JSON value must produce
+/// the same answer whichever query wraps it, or a client gets a 400 from one
+/// form and a silently different answer from the semantically identical other
+/// form.
+///
+/// ES rejects a negative slop from every builder
+/// (`MatchPhraseQueryBuilder.slop` / `MatchPhrasePrefixQueryBuilder.slop:103`
+/// / `MultiMatchQueryBuilder.slop:350` all throw "No negative slop allowed";
+/// AGPL, read for semantics only). `u32::try_from` rather than `as u32`
+/// because a wrapping cast turns an out-of-range slop into a small honoured
+/// one — a silently wrong answer, which is worse than a 400.
+fn parse_phrase_slop(v: Option<&Value>, ctx: &str) -> Result<u32> {
+ match v {
+ None | Some(Value::Null) => Ok(0),
+ Some(v) => match v
+ .as_i64()
+ .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
+ {
+ Some(n) if n < 0 => invalid(format!("`{ctx}.slop` must not be negative")),
+ Some(n) => u32::try_from(n).map_err(|_| qerr(format!("`{ctx}.slop` is out of range"))),
+ None => invalid(format!("`{ctx}.slop` must be an integer")),
+ },
+ }
+}
+
/// ES `combined_fields` query — introduced in 7.13, treats N text fields as a
/// single virtual field for term-frequency scoring. Our approximation routes
/// it to `multi_match` with `type: "cross_fields"`, which is the closest
@@ -608,22 +635,7 @@ fn parse_multi_match(params: &Value) -> Result<QueryNode> {
// and reject the values ES rejects instead of quietly mis-answering.
// ES: negative slop and non-positive max_expansions are 400s, and
// `slop` is not allowed with `type: bool_prefix`.
- // `u32::try_from` rather than `as u32`: a wrapping cast would turn an
- // out-of-range slop into a small honoured one — a silently wrong answer.
- let slop: u32 = match obj.get("slop") {
- None | Some(Value::Null) => 0,
- Some(v) => match v
- .as_i64()
- .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
- {
- Some(n) if n < 0 => return invalid("`multi_match.slop` must not be negative"),
- Some(n) => match u32::try_from(n) {
- Ok(s) => s,
- Err(_) => return invalid("`multi_match.slop` is out of range"),
- },
- None => return invalid("`multi_match.slop` must be an integer"),
- },
- };
+ let slop: u32 = parse_phrase_slop(obj.get("slop"), "multi_match")?;
let max_expansions: u32 = match obj.get("max_expansions") {
None | Some(Value::Null) => 50,
Some(v) => match v
@@ -644,20 +656,19 @@ fn parse_multi_match(params: &Value) -> Result<QueryNode> {
// fail, so this arm passed while XERJ silently ignored `slop`.
return invalid("[slop] not allowed for type [bool_prefix]");
}
- if slop != 0 && type_str == "phrase_prefix" {
- // FAIL LOUDLY rather than accept-and-ignore (#204). XERJ evaluates a
- // `phrase_prefix` as an ADJACENT head phrase plus a trailing prefix
- // term, in both the positional segment clause
- // (`xerj_fts::search::PhrasePrefixQuery`, which carries no slop) and
- // the stored-doc walk. ES does honour slop here, so silently
- // dropping it would answer a different query than the one asked —
- // exactly the class of defect this fix exists to remove.
- return invalid(
- "`multi_match.slop` is not supported for type [phrase_prefix]: xerj matches a \
- phrase_prefix as an adjacent phrase plus a trailing prefix term. Remove [slop], \
- or use type [phrase]",
- );
- }
+ // `slop` with `type: phrase_prefix` is ACCEPTED and HONOURED, because ES
+ // honours it: `MultiMatchQueryBuilder` rejects slop only for
+ // `bool_prefix` (…/index/query/MultiMatchQueryBuilder.java:673) and
+ // `TextFieldMapper.createPhrasePrefixQuery` calls
+ // `MultiPhrasePrefixQuery.setSlop(slop)` (…/index/mapper/
+ // TextFieldMapper.java:1269 — AGPL, read for semantics only). Both XERJ
+ // evaluators now carry it: `PhrasePrefixQuery.slop` on the segment side
+ // and the sloppy prefix walk in the stored-doc scan. Refusing it here
+ // would have been a wire-compat break on a query ES answers, and would
+ // have left the semantically identical single-field
+ // `{"match_phrase_prefix": {"f": {"query": …, "slop": N}}}` — which
+ // `parse_match_phrase_prefix` accepts — answering a different query.
+ //
// `slop` on the FIELD-CENTRIC types (best_fields / most_fields /
// cross_fields) is accepted and unused, which is also what ES does:
// those types lower to a BOOLEAN match query, and only the PHRASE and
@@ -1981,6 +1992,7 @@ fn parse_match_phrase_prefix(params: &Value) -> Result<QueryNode> {
field,
query,
max_expansions: 50,
+ slop: 0,
});
}
@@ -2000,11 +2012,21 @@ fn parse_match_phrase_prefix(params: &Value) -> Result<QueryNode> {
.get("max_expansions")
.and_then(Value::as_u64)
.unwrap_or(50) as u32;
+ // `slop` used to be read nowhere here, so
+ // `{"match_phrase_prefix": {"f": {"query": …, "slop": 2}}}` was accepted
+ // and answered as slop 0 — accept-and-ignore (#204 class), and a silent
+ // disagreement with the `multi_match` form of the same query. ES parses
+ // and honours it (`MatchPhrasePrefixQueryBuilder.fromXContent` →
+ // `MatchQueryParser.setPhraseSlop`), and both XERJ evaluators now carry
+ // it: `PhrasePrefixQuery.slop` on segments, the sloppy prefix walk in
+ // the stored-doc scan.
+ let slop = parse_phrase_slop(inner.get("slop"), "match_phrase_prefix")?;
Ok(QueryNode::MatchPhrasePrefix {
field,
query,
max_expansions,
+ slop,
})
}
@@ -4466,12 +4488,16 @@ mod tests {
"type": "phrase", "slop": 4294967296i64}}),
json!({"multi_match": {"query": "a b", "fields": ["body"],
"type": "phrase_prefix", "max_expansions": 0}}),
+ // ES rejects slop for bool_prefix ONLY
+ // (MultiMatchQueryBuilder.java:673).
json!({"multi_match": {"query": "a b", "fields": ["body"],
"type": "bool_prefix", "slop": 2}}),
- // Accepted-and-ignored is the defect class of #204: xerj cannot
- // honour slop on a phrase_prefix, so it must refuse it.
- json!({"multi_match": {"query": "a b", "fields": ["body"],
- "type": "phrase_prefix", "slop": 2}}),
+ // The same values are rejected on the single-field phrase
+ // entry points — one JSON value, one answer, whichever query
+ // wraps it.
+ json!({"match_phrase": {"body": {"query": "a b", "slop": -1}}}),
+ json!({"match_phrase_prefix": {"body": {"query": "a b", "slop": -1}}}),
+ json!({"match_phrase_prefix": {"body": {"query": "a b", "slop": 4294967296i64}}}),
] {
assert!(
parse_query(&bad).is_err(),
@@ -4480,6 +4506,43 @@ mod tests {
}
}
+ /// `slop` + `type: phrase_prefix` is ACCEPTED and carried, at BOTH
+ /// entry points. ES honours it (`MultiMatchQueryBuilder` rejects slop
+ /// only for `bool_prefix`; `TextFieldMapper.createPhrasePrefixQuery`
+ /// calls `MultiPhrasePrefixQuery.setSlop`), so refusing it would be a
+ /// wire-compat break — and dropping it, as `parse_match_phrase_prefix`
+ /// used to, is the accept-and-ignore defect class of #204.
+ #[test]
+ fn test_phrase_prefix_slop_is_carried_at_both_entry_points() {
+ let node = q(json!({
+ "multi_match": {"query": "quick fo", "fields": ["body"],
+ "type": "phrase_prefix", "slop": 2}
+ }));
+ assert!(
+ matches!(
+ node,
+ QueryNode::MultiMatch {
+ match_type: MultiMatchType::PhrasePrefix,
+ slop: 2,
+ ..
+ }
+ ),
+ "multi_match phrase_prefix must carry slop, got {node:?}"
+ );
+
+ let node = q(json!({
+ "match_phrase_prefix": {"body": {"query": "quick fo", "slop": 2}}
+ }));
+ assert!(
+ matches!(node, QueryNode::MatchPhrasePrefix { slop: 2, .. }),
+ "match_phrase_prefix must carry slop, got {node:?}"
+ );
+
+ // Absent slop is 0 at both entry points.
+ let node = q(json!({"match_phrase_prefix": {"body": "quick fo"}}));
+ assert!(matches!(node, QueryNode::MatchPhrasePrefix { slop: 0, .. }));
+ }
+
// ── term ──────────────────────────────────────────────────────────────────
#[test]
diff --git a/engine/crates/xerj-query/src/planner.rs b/engine/crates/xerj-query/src/planner.rs
index 0c39f727a..567e6177f 100644
--- a/engine/crates/xerj-query/src/planner.rs
+++ b/engine/crates/xerj-query/src/planner.rs
@@ -506,14 +506,16 @@ fn plan_node(query: QueryNode, schema: &Schema) -> ExecutionPlan {
QueryNode::Intervals { field, .. } => ExecutionPlan::ExistsScan { field },
// MatchPhrasePrefix: treat as a phrase search on the given field.
- QueryNode::MatchPhrasePrefix { field, query, .. } => {
+ QueryNode::MatchPhrasePrefix {
+ field, query, slop, ..
+ } => {
let tokens: Vec<String> = query.split_whitespace().map(str::to_string).collect();
ExecutionPlan::FtsSearch {
field,
tokens,
require_all: true,
phrase: true,
- slop: 0,
+ slop,
cost: 10.0,
}
}