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): query_string with no default_field searches every text field, bounded and deadline-aware (#130)
xerj-orga71bf7ad4651
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 12e8f8e15..833dfca8c 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -12156,6 +12156,17 @@ impl Index {// wasted work when the query is a stored-doc scan.let fts_query_probe = query_node_to_fts(query, &text_fields, &exact_fields);let needs_fts = fts_query_probe.is_some();+ // A `query_string` whose projection DECLINED still has to be+ // answered by the stored-doc scan — an over-cap `tokens × fields`+ // cross-product returns `None`, and without the scan the segment+ // would be skipped outright, dropping every match it holds.+ //+ // UNLESS it declined because the query analyses to zero tokens, in+ // which case nothing can match and the scan is pure cost. See+ // `query_string_has_no_tokens` for the measurement; hoisted out of+ // the per-segment loop below because it re-tokenises the query.+ let query_string_needs_doc_scan = matches!(query, QueryNode::QueryString { .. })+ && !query_string_has_no_tokens(query, &exact_fields);// Open the FTS reader with every field the projected query// actually touches, ON TOP of the text fields. Keyword-typed// fields have FTS side-cars too (whole-value keyword-analyzer@@ -12243,7 +12254,14 @@ impl Index {let fts_dir = segments_dir.clone();let field_refs: Vec<&str> = fts_open_fields.iter().map(|s| s.as_str()).collect();- let scan_stored = matches!(query, QueryNode::MatchAll) || is_doc_scan_query(query);+ // `QueryString` is steered by its own flag rather than added+ // to `is_doc_scan_query` (which also steers the MEMTABLE+ // branch, where `query_string` must keep its BM25 route), and+ // that flag is false for the zero-token shape so a+ // `query_string` that can match nothing costs nothing.+ let scan_stored = matches!(query, QueryNode::MatchAll)+ || query_string_needs_doc_scan+ || is_doc_scan_query(query);// Try FTS path first if we have an FTS query.let mut fts_handled = false;@@ -12308,6 +12326,20 @@ impl Index {// report 0 matches for the segment. Require every// referenced field to be present; if any is missing,// fall through to the stored-doc scan.+ //+ // HETEROGENEOUS SEGMENTS: for a pure disjunction that+ // rule is far stricter than it needs to be. A+ // field-less `query_string` projects one `should`+ // clause per (token, text field), and any field first+ // indexed after a flush is missing from every older+ // segment — so a single late field pushed EVERY older+ // segment onto the stored-doc scan. Prune the clauses+ // naming fields this segment never indexed (they can+ // only match nothing here) and keep the postings path;+ // if nothing survives, fall through as before.+ let fq =+ prune_missing_should_fields(&fq, &|f| reader.field_stats(f).is_some())+ .unwrap_or(fq);let fts_has_field = {let mut qf: Vec<String> = Vec::new();collect_fts_query_fields(&fq, &mut qf);@@ -19644,22 +19676,34 @@ impl Index {// minimum the ~3 µs JSON parse below; the read is noise).//// The interval used to be 4 096, sized for that ~3 µs/doc floor.- // A `script` query breaks that assumption: even with the Painless- // AST cached (see `painless::compile_script_cached`), *executing*- // a script dominates the per-doc cost. Measured on a release- // build: a benign 64 KiB script runs 385 µs/doc, so 4 096 docs is- // a ~1.6 s stretch in which a `timeout` cannot take effect, and- // 256 brings that to ~98 ms.+ // Two separate matcher shapes break that assumption:+ //+ // - A `script` query: even with the Painless AST cached (see+ // `painless::compile_script_cached`), *executing* a script+ // dominates the per-doc cost. Measured on a release build, a+ // benign 64 KiB script runs 385 µs/doc, so 4 096 docs is a+ // ~1.6 s stretch in which a `timeout` cannot take effect, and+ // 256 brings that to ~98 ms.+ // - A field-less `query_string` over a wide mapping: it+ // tokenises every text-bearing field of every document, so a+ // few hundred documents is already several times the+ // request's whole budget — and the scan would report+ // `timed_out: false` after blowing straight through it.//- // 256 is an improvement, not a bound. A deliberately adversarial- // script of legal size — flat, no closure calls, tripping none of- // MAX_CALL_DEPTH / MAX_CALL_COUNT / MAX_EVAL_DEPTH /- // MAX_PARSE_DEPTH / MAX_PAINLESS_STRING_LEN — was measured at- // 1.27 s/doc, which is ~325 s per poll interval. Nothing here- // bounds that, because there is no per-evaluation CPU budget; the- // poll interval only decides how often an already-cheap document- // boundary is checked. Closing that needs a real time or- // instruction budget inside `eval_painless`, tracked separately.+ // 256 bounds the overshoot to a few hundred documents for every+ // matcher shape, and 16× more clock reads on a million-doc scan is+ // still a rounding error against the parse.+ //+ // For scripts, 256 is an improvement, not a bound. A deliberately+ // adversarial script of legal size — flat, no closure calls,+ // tripping none of MAX_CALL_DEPTH / MAX_CALL_COUNT /+ // MAX_EVAL_DEPTH / MAX_PARSE_DEPTH / MAX_PAINLESS_STRING_LEN — was+ // measured at 1.27 s/doc, which is ~325 s per poll interval.+ // Nothing here bounds that, because there is no per-evaluation CPU+ // budget; the poll interval only decides how often an+ // already-cheap document boundary is checked. Closing that needs a+ // real time or instruction budget inside `eval_painless`, tracked+ // separately.if doc_pos & 0xFF == 0 {if let Some(dl) = deadline {if std::time::Instant::now() >= dl {@@ -24937,6 +24981,103 @@ fn doc_matches_query(q: &QueryNode, source: &Value) -> bool {QueryNode::SimpleQueryString { .. } => false, // Converted to Bool at parse time+ // `query_string` on the stored-doc path.+ //+ // Segments are HETEROGENEOUS: one flushed before a field first+ // appeared carries no FTS side-car for that field, and a segment+ // flushed under M5.4 may carry no side-cars at all. In both cases the+ // FTS route declines the segment and this scan is the only thing that+ // answers for its documents. Until this arm existed the catch-all+ // `_ => false` below made every one of those documents a silent+ // non-match: `hits.total` simply came back short, with nothing in the+ // response saying so. Widening the field-less projection from+ // `text_fields[0]` to every text field is what turned that decline+ // from a corner case into the common one — any field added after a+ // flush makes every older segment fail the "reader has every queried+ // field" gate.+ //+ // An OR over the analyzed query tokens, restricted to `default_field`+ // when one is given and otherwise run against the fields present in+ // the scanned source (`index.query.default_field` defaults to `"*"`).+ // Leading-underscore keys are skipped — `_id` is spliced into the+ // scanned source and would over-count.+ //+ // This is CLOSE TO, but not byte-identical to, `query_node_to_fts`'s+ // projection, and the difference is deliberate: the projection ORs+ // over schema `FieldType::Text` fields only, whereas this scan arm+ // walks every non-`_` key of the source, so a token living only in a+ // KEYWORD (or other exact string) field matches here but not on the+ // FTS route. Measured: with schema {code: Keyword, alpha: Text} and a+ // token only in `code`, a field-less `query_string` returns it via the+ // scan path. The scan arm is the more ES-correct of the two (ES's+ // `default_field: "*"` includes keyword fields), but because a+ // within-cap query takes the FTS route and an over-cap one takes the+ // scan route, the answer can differ across the `tokens × fields` cap.+ // Reconciling the two onto one field set is tracked separately; do not+ // read this as "the two routes agree".+ QueryNode::QueryString {+ query,+ default_field,+ ..+ } => {+ // This runs PER DOCUMENT over every text-bearing field, so it has+ // to be O(document tokens), not O(document tokens × query tokens):+ // hash the query's tokens once and reuse a single lowercase buffer+ // for the whole call, so scanning a document allocates nothing.+ let terms: HashSet<String> = intervals_tokenise(query).into_iter().collect();+ if terms.is_empty() {+ return false;+ }+ /// Any analyzed token of `v` (recursing through arrays/objects)+ /// equal to one of `terms`. Whole-value equality is also accepted+ /// so a keyword-typed field — whose FST holds one un-analyzed+ /// token per value — is not silently missed on this path, the+ /// same exact-or-tokenized convention the `Terms` arm above uses.+ fn any_token_hit(+ v: &Value,+ terms: &HashSet<String>,+ raw: &str,+ buf: &mut String,+ ) -> bool {+ match v {+ Value::String(s) => {+ if s.eq_ignore_ascii_case(raw) {+ return true;+ }+ for tok in s.split(|c: char| !c.is_alphanumeric()) {+ if tok.is_empty() {+ continue;+ }+ buf.clear();+ buf.extend(tok.chars().flat_map(char::to_lowercase));+ if terms.contains(buf.as_str()) {+ return true;+ }+ }+ false+ }+ Value::Array(arr) => arr.iter().any(|e| any_token_hit(e, terms, raw, buf)),+ Value::Object(obj) => obj+ .iter()+ .filter(|(k, _)| !k.starts_with('_'))+ .any(|(_, e)| any_token_hit(e, terms, raw, buf)),+ _ => false,+ }+ }+ let mut buf = String::new();+ match default_field.as_deref() {+ Some(f) if f != "*" && !f.is_empty() => get_field_value(source, f)+ .is_some_and(|v| any_token_hit(&v, &terms, query.as_str(), &mut buf)),+ _ => match source {+ Value::Object(obj) => obj+ .iter()+ .filter(|(k, _)| !k.starts_with('_'))+ .any(|(_, v)| any_token_hit(v, &terms, query.as_str(), &mut buf)),+ other => any_token_hit(other, &terms, query.as_str(), &mut buf),+ },+ }+ }+QueryNode::FunctionScore { query, .. } => doc_matches_query(query, source),// Nested: extract the array at `path`, run the inner query against each element.@@ -28203,6 +28344,55 @@ fn ip_matches_cidr(ip_str: &str, cidr: &str) -> Option<bool> {Some((ip & mask) == (network & mask))}+/// Drop the `should` clauses of a pure disjunction that name a field this+/// segment has no FTS data for, returning `None` when the shape isn't a pure+/// disjunction or when nothing survives.+///+/// Segments are heterogeneous. A field first seen after a flush has no+/// side-car in any older segment, so `field_stats` reports it missing there —+/// and the caller's "reader has EVERY queried field" gate then refuses the+/// whole segment. That gate is right for `must`/`must_not`, where a missing+/// field changes what the clause means, but it is needlessly destructive for+/// the disjunction a field-less `query_string` (or a `fields`-less+/// `multi_match`) projects to: a clause naming a field the segment never+/// indexed can only ever match nothing, so deleting it leaves the disjunction+/// semantically identical over this segment's documents while keeping the+/// whole thing on the postings path.+///+/// Deliberately narrow — only `should`-only bools whose every clause is a+/// plain `Term`, which is exactly what the field-less projection emits.+/// Anything else keeps the conservative all-fields-present gate.+fn prune_missing_should_fields(q: &FtsQuery, has_field: &dyn Fn(&str) -> bool) -> Option<FtsQuery> {+ let FtsQuery::Bool(b) = q else { return None };+ if !b.must.is_empty() || !b.must_not.is_empty() || b.min_should_match.is_some() {+ return None;+ }+ if b.should.is_empty() || !b.should.iter().all(|c| matches!(c, FtsQuery::Term(_))) {+ return None;+ }+ let kept: Vec<FtsQuery> = b+ .should+ .iter()+ .filter(|c| match c {+ FtsQuery::Term(t) => has_field(t.field.as_str()),+ _ => false,+ })+ .cloned()+ .collect();+ // Nothing survived: the segment has FTS data for none of the queried+ // fields, which is also what an FTS-less segment looks like. Let the+ // caller fall through to the stored-doc scan rather than reporting an+ // authoritative zero.+ if kept.is_empty() || kept.len() == b.should.len() {+ return None;+ }+ let mut pruned = FtsBool::new().boost(b.boost);+ for c in kept {+ pruned = pruned.should(c);+ }+ Some(FtsQuery::Bool(Box::new(pruned)))+}+/// Collect every field name referenced by an FTS query tree.////// Used to (a) extend the set of side-car fields `FtsIndexReader::open`@@ -28260,6 +28450,69 @@ fn collect_fts_query_fields(q: &FtsQuery, out: &mut Vec<String>) {}}+/// Does this `query_string` analyse to ZERO searchable tokens?+///+/// `query_node_to_fts` declines a `QueryString` (returns `None`) for two+/// reasons that are indistinguishable to the caller and demand OPPOSITE+/// handling:+///+/// * The analyzed query has no tokens at all — `"+++"`, `"---"`, anything+/// the standard analyzer reduces to nothing. The projection would be a+/// disjunction with zero clauses, which matches nothing, and the+/// stored-doc scan agrees: `doc_matches_query`'s `QueryString` arm returns+/// `false` the moment its token set is empty. The correct answer is the+/// empty result, reached WITHOUT reading a single document.+/// * The `tokens × fields` cross-product blew `MAX_QS_CROSS_PRODUCT`. The+/// query is perfectly matchable there and the stored-doc scan is the only+/// route left, so skipping the segment would drop every match it holds.+///+/// (The heterogeneous-segment case is NOT one of these: a segment missing a+/// queried field still gets a `Some` projection, and it is the per-segment+/// `fts_has_field` gate below that routes it to the scan via+/// `needs_fts && !fts_handled`. That path is untouched here.)+///+/// Collapsing both into "scan the stored section" cost a full O(corpus) walk+/// to produce an empty result. Measured by+/// `tests/query_string_default_field.rs::zero_token_query_string_does_not_scan_the_corpus`+/// — release, 20 000 documents in ONE segment, best of 5, query cache cleared+/// before every run — a zero-token `query_string` cost:+///+/// * 0.399 ms before the field-less `query_string` work,+/// * 26.412 ms with both declines collapsed into one `scan_stored`,+/// * 0.457 ms with them separated here.+///+/// The middle number is a 66× regression on a shape that returns nothing, and+/// it grows with the index: the comparator in that test — a query that really+/// does walk all 20 000 documents — cost 10.7-16.9 ms on the same runs.+///+/// Mirrors the projection's own order of operations: an `exact_fields`+/// `default_field` short-circuits to a whole-value term BEFORE any+/// tokenisation, so an un-analyzable string is still a legitimate term there+/// and this must report `false`.+fn query_string_has_no_tokens(+ q: &QueryNode,+ exact_fields: &std::collections::HashSet<String>,+) -> bool {+ let QueryNode::QueryString {+ query,+ default_field,+ ..+ } = q+ else {+ return false;+ };+ if let Some(field) = default_field.as_deref() {+ if exact_fields.contains(field) {+ return false;+ }+ }+ // No analyzer (never in practice — `standard` is always registered) is+ // treated as "cannot prove it matches nothing", keeping the scan.+ AnalyzerRegistry::default()+ .get_analyzer("standard")+ .is_some_and(|a| a.analyze(query).is_empty())+}+/// Convert a QueryNode to an FTS Query for segment search.////// `exact_fields` are the non-Text schema fields (keyword / numeric / date /@@ -28564,23 +28817,83 @@ fn query_node_to_fts(} => {// Honor top-level `query_string.boost` like the Match arm above.let b = boost.unwrap_or(1.0);- let field = default_field- .as_deref()- .or_else(|| text_fields.first().map(|s| s.as_str()))- .unwrap_or("_all");- // Keyword default field: whole-value term (keyword analyzer).- if exact_fields.contains(field) {- return Some(FtsQuery::Term(FtsTerm::boosted(field, query.as_str(), b)));- }+ // An explicit `default_field` searches exactly that one field —+ // unchanged single-field behavior, including the keyword+ // whole-value-term shortcut.+ if let Some(field) = default_field.as_deref() {+ if exact_fields.contains(field) {+ return Some(FtsQuery::Term(FtsTerm::boosted(field, query.as_str(), b)));+ }+ let registry = AnalyzerRegistry::default();+ let analyzer = registry.get_analyzer("standard")?;+ let tokens = analyzer.analyze(query);+ if tokens.is_empty() {+ return None;+ }+ let mut bool_q = FtsBool::new().boost(b);+ for token in &tokens {+ bool_q = bool_q.should(FtsQuery::Term(FtsTerm::new(field, &token.text)));+ }+ return Some(FtsQuery::Bool(Box::new(bool_q)));+ }+ // No `default_field`: real ES/OpenSearch searches every mapped+ // text field (`index.query.default_field` defaults to `"*"`).+ // This used to fall back to `text_fields.first()` — an+ // arbitrary single field picked by schema order — silently+ // missing every match in every OTHER text field. Found live: a+ // `query_string` with no field, run across a multi-index search+ // spanning indices with different schemas, undercounted matches+ // by two orders of magnitude (18 of ~14,074) because only one+ // unrelated field was ever checked.+ let fallback = ["_all".to_string()];+ let fields: &[String] = if text_fields.is_empty() {+ &fallback+ } else {+ text_fields+ };let registry = AnalyzerRegistry::default();let analyzer = registry.get_analyzer("standard")?;let tokens = analyzer.analyze(query);if tokens.is_empty() {return None;}+ // Bound the `tokens × fields` cross-product. This is the SAME+ // shape as the `more_like_this` `fields × like` blow-up capped+ // in `xerj_query::parser` (MAX_MLT_CROSS_PRODUCT), and it is+ // worse here on two counts: the product is rebuilt for EVERY+ // segment of the scan, and `FtsSearcher::execute_bool`+ // materialises a full `Vec<ScoredHit>` PER CLAUSE before+ // combining — so a wide mapping crossed with a long query+ // string is both an allocation bomb and an uninterruptible+ // unit of work on the search hot path. Widening the field-less+ // `query_string` from one field to every text field is exactly+ // what makes the second dimension attacker-reachable.+ //+ // Over the cap we do NOT narrow the field set (that is the+ // silent under-matching this arm exists to fix) and we do NOT+ // drop the query: returning `None` routes the request to the+ // stored-doc scan, which evaluates the same field-less+ // semantics per document in `doc_matches_query` and polls the+ // request deadline every 256 docs. Slower, bounded, correct.+ //+ // Only the PRODUCT is capped, unlike MLT's three limits. There+ // both dimensions come from the request body, so bounding each+ // one is meaningful; here the field count is the index's own+ // mapping, and a standalone field cap would push a perfectly+ // ordinary two-token query off the fast path on any schema with+ // a lot of text fields. 4 096 is the MLT cross-product cap and+ // also ES's default `indices.query.bool.max_clause_count` —+ // where ES rejects the query outright, we degrade to the scan.+ const MAX_QS_CROSS_PRODUCT: usize = 4_096;+ if tokens.len().saturating_mul(fields.len()) > MAX_QS_CROSS_PRODUCT {+ return None;+ }let mut bool_q = FtsBool::new().boost(b);for token in &tokens {- bool_q = bool_q.should(FtsQuery::Term(FtsTerm::new(field, &token.text)));+ for field in fields {+ bool_q =+ bool_q.should(FtsQuery::Term(FtsTerm::new(field.as_str(), &token.text)));+ }}Some(FtsQuery::Bool(Box::new(bool_q)))}@@ -31208,6 +31521,255 @@ mod fts_projection_tests {}}+ /// The two `None`s `query_node_to_fts` returns for a `QueryString` mean+ /// opposite things, and `scan_stored` has to tell them apart: zero tokens+ /// means nothing can match (skip the segment), an over-cap cross-product+ /// means the query is matchable and the stored scan is the only route.+ #[test]+ fn zero_token_query_string_is_distinguished_from_an_over_cap_one() {+ let punctuation = QueryNode::QueryString {+ query: "+++".into(),+ default_field: None,+ default_operator: None,+ boost: None,+ };+ let one_field = vec!["body".to_string()];+ assert!(+ query_node_to_fts(&punctuation, &one_field, &kw(&[])).is_none(),+ "pure punctuation projects to nothing"+ );+ assert!(+ query_string_has_no_tokens(&punctuation, &kw(&[])),+ "…and that `None` must be reported as UNMATCHABLE, not as a \+ decline that needs the stored-doc scan"+ );++ // The other `None`: a matchable query that blew the cross-product cap.+ let many_fields: Vec<String> = (0..2_000).map(|i| format!("f{i}")).collect();+ let over_cap = qs_tokens(3);+ assert!(+ query_node_to_fts(&over_cap, &many_fields, &kw(&[])).is_none(),+ "3 × 2 000 is over the cap"+ );+ assert!(+ !query_string_has_no_tokens(&over_cap, &kw(&[])),+ "an over-cap query still matches documents and MUST keep the scan"+ );++ // An ordinary query is never mistaken for unmatchable.+ assert!(!query_string_has_no_tokens(&qs_tokens(2), &kw(&[])));+ // Non-`QueryString` nodes are not this function's business.+ assert!(!query_string_has_no_tokens(&QueryNode::MatchAll, &kw(&[])));++ // Keyword `default_field`: the projection short-circuits to a+ // whole-value term BEFORE tokenising, so an un-analyzable string is a+ // legitimate term there and must NOT be called unmatchable.+ let on_keyword = QueryNode::QueryString {+ query: "+++".into(),+ default_field: Some("code".into()),+ default_operator: None,+ boost: None,+ };+ assert!(+ query_node_to_fts(&on_keyword, &one_field, &kw(&["code"])).is_some(),+ "a keyword default_field projects to a whole-value term"+ );+ assert!(!query_string_has_no_tokens(&on_keyword, &kw(&["code"])));+ // Same string on a TEXT default_field does tokenise to nothing.+ assert!(query_string_has_no_tokens(&on_keyword, &kw(&[])));+ }++ /// Regression: `query_string` with no `default_field` set (ES/OpenSearch+ /// semantics — `index.query.default_field` defaults to `"*"`, i.e.+ /// search every mapped text field) used to pick only `text_fields[0]`,+ /// an arbitrary single field chosen by schema order. Any match in every+ /// OTHER text field was silently missed. Found live: a Kibana/OSD+ /// Timelion panel's `query_string` (used to select which index's docs+ /// to count inside a `filters` aggregation) undercounted matches by two+ /// orders of magnitude because the schema's first text field happened+ /// not to be the one holding the searched value.+ #[test]+ fn query_string_with_no_default_field_searches_every_text_field() {+ let q = QueryNode::QueryString {+ query: "needle".into(),+ default_field: None,+ default_operator: None,+ boost: None,+ };+ let text_fields = vec!["agent".to_string(), "message".to_string()];+ let fq = query_node_to_fts(&q, &text_fields, &kw(&[])).expect("projects");+ match fq {+ FtsQuery::Bool(b) => {+ let fields: Vec<&str> = b+ .should+ .iter()+ .map(|s| match s {+ FtsQuery::Term(t) => t.field.as_str(),+ other => panic!("expected term, got {:?}", other),+ })+ .collect();+ assert!(+ fields.contains(&"message"),+ "must search every text field, not just the first — got {fields:?}"+ );+ assert!(fields.contains(&"agent"), "got {fields:?}");+ }+ other => panic!("expected bool, got {:?}", other),+ }+ }++ /// Build a field-less `query_string` node over `n_tokens` tokens.+ fn qs_tokens(n_tokens: usize) -> QueryNode {+ QueryNode::QueryString {+ query: (0..n_tokens)+ .map(|i| format!("tok{i} "))+ .collect::<String>(),+ default_field: None,+ default_operator: None,+ boost: None,+ }+ }++ /// BLOCKER: the field-less projection builds one `should` clause per+ /// (token × field) and `execute_bool` then materialises a full hit vector+ /// per clause, so the product must be capped exactly like the+ /// `more_like_this` `fields × like` cross-product is capped at parse time.+ /// Uncapped, 500 tokens × 80 fields is 40 000 clauses re-built for EVERY+ /// segment of the scan.+ #[test]+ fn field_less_query_string_cross_product_is_capped() {+ let text_fields: Vec<String> = (0..80).map(|i| format!("f{i}")).collect();+ assert!(+ query_node_to_fts(&qs_tokens(500), &text_fields, &kw(&[])).is_none(),+ "500 × 80 = 40 000 clauses must not be projected; the request \+ falls back to the stored-doc scan, which is deadline-polled"+ );+ // Either dimension can carry the product past the cap on its own.+ let one_field = vec!["body".to_string()];+ assert!(+ query_node_to_fts(&qs_tokens(5_000), &one_field, &kw(&[])).is_none(),+ "5 000 tokens × 1 field is still 5 000 clauses"+ );+ let many_fields: Vec<String> = (0..2_000).map(|i| format!("f{i}")).collect();+ assert!(+ query_node_to_fts(&qs_tokens(3), &many_fields, &kw(&[])).is_none(),+ "3 tokens × 2 000 fields is 6 000 clauses"+ );+ }++ /// The cap must not touch ordinary queries: a realistic mapping and a+ /// realistic query still project to the postings path, with every clause+ /// accounted for. A WIDE mapping with a short query especially — capping+ /// the field count on its own would have pushed it off the fast path.+ #[test]+ fn field_less_query_string_within_the_cap_still_projects() {+ let text_fields: Vec<String> = (0..8).map(|i| format!("f{i}")).collect();+ let fq = query_node_to_fts(&qs_tokens(20), &text_fields, &kw(&[])).expect("projects");+ match fq {+ FtsQuery::Bool(b) => assert_eq!(+ b.should.len(),+ 20 * 8,+ "every (token × field) pair is a clause"+ ),+ other => panic!("expected bool, got {other:?}"),+ }+ let wide: Vec<String> = (0..300).map(|i| format!("f{i}")).collect();+ let fq = query_node_to_fts(&qs_tokens(2), &wide, &kw(&[])).expect("wide mapping projects");+ match fq {+ FtsQuery::Bool(b) => assert_eq!(b.should.len(), 2 * 300),+ other => panic!("expected bool, got {other:?}"),+ }+ }++ /// HIGH: a segment that never indexed one of the queried fields must have+ /// only THAT clause dropped, not the whole disjunction rejected. Rejecting+ /// it sent the segment to a stored-doc scan that had no `query_string`+ /// matcher, so its documents silently vanished from `hits.total`.+ #[test]+ fn prune_drops_only_the_clauses_a_segment_cannot_serve() {+ let q = FtsQuery::Bool(Box::new(+ FtsBool::new()+ .should(FtsQuery::Term(FtsTerm::new("alpha", "needle")))+ .should(FtsQuery::Term(FtsTerm::new("beta", "needle"))),+ ));+ let pruned =+ prune_missing_should_fields(&q, &|f| f == "alpha").expect("prunes to the kept field");+ match pruned {+ FtsQuery::Bool(b) => {+ assert_eq!(b.should.len(), 1);+ match &b.should[0] {+ FtsQuery::Term(t) => assert_eq!(t.field, "alpha"),+ other => panic!("expected term, got {other:?}"),+ }+ }+ other => panic!("expected bool, got {other:?}"),+ }+ // Every field present → nothing to prune, caller keeps the original.+ assert!(prune_missing_should_fields(&q, &|_| true).is_none());+ // No field present → indistinguishable from a segment with no FTS+ // side-cars at all; the caller must fall through to the stored scan+ // rather than report an authoritative zero.+ assert!(prune_missing_should_fields(&q, &|_| false).is_none());+ // Conjunctive shapes keep the conservative all-present gate: dropping+ // a `must` clause would BROADEN the query.+ let conj = FtsQuery::Bool(Box::new(+ FtsBool::new()+ .must(FtsQuery::Term(FtsTerm::new("alpha", "needle")))+ .should(FtsQuery::Term(FtsTerm::new("beta", "needle"))),+ ));+ assert!(prune_missing_should_fields(&conj, &|f| f == "alpha").is_none());+ }++ /// HIGH: the stored-doc scan is the ONLY thing that answers for a segment+ /// the FTS route declines, and it had no `query_string` arm — every such+ /// document was a silent non-match.+ #[test]+ fn doc_scan_matches_field_less_query_string_on_any_text_field() {+ let q = QueryNode::QueryString {+ query: "needle".into(),+ default_field: None,+ default_operator: None,+ boost: None,+ };+ assert!(doc_matches_query(+ &q,+ &serde_json::json!({"alpha": "a needle in here"})+ ));+ assert!(doc_matches_query(+ &q,+ &serde_json::json!({"alpha": "nope", "beta": "needle"})+ ));+ assert!(doc_matches_query(+ &q,+ &serde_json::json!({"alpha": ["nope", "needle"]})+ ));+ assert!(!doc_matches_query(+ &q,+ &serde_json::json!({"alpha": "haystack"})+ ));+ // `_id` is spliced into the scanned source but is not a mapped text+ // field — matching it would over-count relative to the FTS route.+ assert!(!doc_matches_query(+ &q,+ &serde_json::json!({"_id": "needle", "alpha": "haystack"})+ ));+ // An explicit default_field stays single-field.+ let pinned = QueryNode::QueryString {+ query: "needle".into(),+ default_field: Some("alpha".into()),+ default_operator: None,+ boost: None,+ };+ assert!(doc_matches_query(+ &pinned,+ &serde_json::json!({"alpha": "needle"})+ ));+ assert!(!doc_matches_query(+ &pinned,+ &serde_json::json!({"beta": "needle"})+ ));+ }+/// Field collector walks every clause of a projected query.#[test]fn collect_fields_walks_bool_tree() {diff --git a/engine/crates/xerj-engine/tests/query_string_default_field.rs b/engine/crates/xerj-engine/tests/query_string_default_field.rsnew file mode 100644index 000000000..077de6038--- /dev/null+++ b/engine/crates/xerj-engine/tests/query_string_default_field.rs@@ -0,0 +1,531 @@+//! Regression tests for the field-less `query_string` projection.+//!+//! `query_string` with no `default_field` searches EVERY mapped text field+//! (ES/OpenSearch `index.query.default_field` defaults to `"*"`). Two hazards+//! come with that widening, and both are covered here:+//!+//! 1. HETEROGENEOUS SEGMENTS. Segments flushed before a field first appeared+//! carry no FTS side-car for it. The per-segment "does the reader have+//! every queried field?" gate then rejects the whole segment and the+//! stored-doc fallback had no `query_string` matcher at all — so those+//! segments silently contributed ZERO hits. Under-matching on a search+//! path surfaces nowhere, which is worse than the single-field bug it+//! replaced.+//!+//! 2. `tokens × fields` CROSS-PRODUCT. One `should` clause is built per+//! (token, field) pair and the bool executor materialises a full hit+//! vector per clause, so a wide mapping plus a long query string is an+//! unbounded, uninterruptible unit of work inside the search hot path.++use serde_json::{json, Value};+use tempfile::TempDir;+use xerj_common::config::Config;+use xerj_common::types::Schema;+use xerj_engine::Engine;+use xerj_query::ast::{QueryNode, SearchRequest};+use xerj_query::parse_request;++fn make_engine(dir: &TempDir) -> Engine {+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_str().unwrap().to_string();+ Engine::new(config).expect("engine::new")+}++/// One ingest shard and a flush threshold nothing in these tests can reach, so+/// an explicit `flush()` yields exactly ONE segment. The between-segment+/// deadline check is what bounds a multi-segment scan; a single segment is the+/// shape where the only thing standing between a clause storm and an+/// indefinitely-held worker is a poll *inside* the clause loop.+fn make_single_segment_engine(dir: &TempDir) -> Engine {+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_str().unwrap().to_string();+ config.storage.flush_size_mb = 8_192;+ config.engine.ingest_shards = 1;+ Engine::new(config).expect("engine::new")+}++fn search(query_json: Value) -> SearchRequest {+ parse_request(&json!({ "query": query_json, "size": 100 })).expect("parse_request")+}++/// A `query_string` whose text the Lucene lowerer cannot parse (here: an+/// unterminated quote) stays an opaque `QueryNode::QueryString` — the node+/// whose projection this PR changes. Anything that lowers becomes a+/// `Match`/`Bool` tree and never reaches that arm.+fn opaque_qs(text: &str) -> Value {+ json!({ "query_string": { "query": format!("\"{text}") } })+}++/// HIGH: heterogeneous segments must contribute the same hits as a+/// homogeneous corpus with the same documents.+///+/// `hetero` flushes a segment holding only `alpha` BEFORE any document+/// introduces `beta`, so that segment's FTS side-car has no `beta` field.+/// `homo` indexes the identical documents but flushes once, after `beta`+/// exists, so every segment carries both fields. The two must agree.+#[tokio::test]+async fn field_less_query_string_matches_equally_across_heterogeneous_segments() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);++ // Documents 0..5 only ever have `alpha`; 5..10 have `alpha` + `beta`.+ let docs: Vec<Value> = (0..10)+ .map(|i| {+ if i < 5 {+ json!({ "alpha": format!("needle alpha body {i}") })+ } else {+ json!({ "alpha": format!("filler body {i}"), "beta": "needle beta body" })+ }+ })+ .collect();++ engine.create_index("hetero", Schema::empty()).unwrap();+ let hetero = engine.get_index("hetero").unwrap();+ for (i, d) in docs.iter().enumerate() {+ hetero+ .index_document(Some(format!("d{i}")), d.clone())+ .await+ .unwrap();+ // Flush right after the alpha-only prefix: that segment is written+ // before `beta` is ever seen, so it has no `beta` FTS side-car.+ if i == 4 {+ hetero.flush().await.unwrap();+ }+ }+ hetero.flush().await.unwrap();++ engine.create_index("homo", Schema::empty()).unwrap();+ let homo = engine.get_index("homo").unwrap();+ // Seed `beta` first so the very first segment carries both fields.+ homo.index_document(+ Some("seed".to_string()),+ json!({ "alpha": "seed body", "beta": "seed body" }),+ )+ .await+ .unwrap();+ homo.flush().await.unwrap();+ for (i, d) in docs.iter().enumerate() {+ homo.index_document(Some(format!("d{i}")), d.clone())+ .await+ .unwrap();+ }+ homo.flush().await.unwrap();++ let q = opaque_qs("needle");+ let h = hetero.search(&search(q.clone())).await.unwrap();+ let m = homo.search(&search(q)).await.unwrap();++ assert_eq!(+ h.total.value,+ 10,+ "every document holds `needle` in some text field; heterogeneous \+ segments dropped {} of them",+ 10 - h.total.value+ );+ assert_eq!(+ h.total.value, m.total.value,+ "heterogeneous segments must match the same documents as a \+ homogeneous corpus (hetero={} homo={})",+ h.total.value, m.total.value+ );+}++/// HIGH, narrower: the same corpus queried for a token that lives ONLY in the+/// field the older segment lacks. The older segment legitimately contributes+/// nothing, but the newer one must still answer.+#[tokio::test]+async fn field_less_query_string_finds_new_field_added_after_a_flush() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("late_field", Schema::empty()).unwrap();+ let idx = engine.get_index("late_field").unwrap();++ for i in 0..5 {+ idx.index_document(Some(format!("old{i}")), json!({ "alpha": "old body" }))+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();+ for i in 0..3 {+ idx.index_document(+ Some(format!("new{i}")),+ json!({ "alpha": "new body", "beta": "zebrafish" }),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ let r = idx.search(&search(opaque_qs("zebrafish"))).await.unwrap();+ assert_eq!(+ r.total.value, 3,+ "`zebrafish` lives only in `beta`, present in 3 documents"+ );+}++/// BLOCKER: a wide mapping crossed with a long query string must not turn one+/// request into an unbounded unit of work. The request carries a short+/// timeout; it must come back inside a small multiple of that budget rather+/// than grinding through `tokens × fields` clauses.+#[tokio::test]+async fn field_less_query_string_cross_product_respects_the_request_deadline() {+ let dir = TempDir::new().unwrap();+ let engine = make_single_segment_engine(&dir);+ engine.create_index("wide", Schema::empty()).unwrap();+ let idx = engine.get_index("wide").unwrap();++ // Every field of every document carries the SAME vocabulary, so every+ // (token, field) clause the projection can build is a clause that+ // actually returns the whole corpus — the worst case, and the one an+ // attacker picks.+ const FIELDS: usize = 120;+ const TOKENS: usize = 300;+ const DOCS: usize = 600;+ let body: String = (0..TOKENS).map(|t| format!("tok{t} ")).collect::<String>();+ for d in 0..DOCS {+ let mut doc = serde_json::Map::new();+ for f in 0..FIELDS {+ doc.insert(format!("f{f}"), json!(body.clone()));+ }+ idx.index_document(Some(format!("d{d}")), Value::Object(doc))+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ // 300 tokens × 120 fields = 36 000 `should` clauses, each matching all+ // 600 documents — 21.6 M materialised hits before a single result is+ // returned, with nothing polling the request deadline in between.+ let req = parse_request(&json!({+ "query": { "query_string": { "query": format!("\"{body}") } },+ "size": 10,+ "timeout": "150ms",+ }))+ .expect("parse_request");++ let stats = idx.stats().await;+ assert_eq!(+ stats.segment_count, 1,+ "the test needs ONE segment: with several, the between-segment \+ deadline check masks an uninterruptible clause loop"+ );++ let t0 = std::time::Instant::now();+ let res = idx.search(&req).await.unwrap();+ let elapsed = t0.elapsed();+ eprintln!(+ "cross-product query: {elapsed:?}, total={} timed_out={}",+ res.total.value, res.timed_out+ );++ // Generous multiple of the 150ms budget so a loaded 2-core CI runner has+ // room, but far below the seconds an unbounded clause storm takes.+ assert!(+ elapsed < std::time::Duration::from_secs(3),+ "field-less query_string cross-product ran {elapsed:?} against a \+ 150ms deadline — the projection is unbounded and the clause loop \+ never polls the deadline"+ );+ // Whatever comes back must be self-consistent: either it finished inside+ // the budget, or it says it did not. This assertion is load-normalising —+ // a slow machine trips the deadline poll and reports `timed_out`, so only+ // a run with NO poll at all can overshoot while claiming success.+ assert!(+ res.timed_out || elapsed < std::time::Duration::from_millis(1_500),+ "a run that overran its deadline must report timed_out"+ );++ // Load-independent restatement: a budget the work provably cannot meet+ // must come back saying so.+ let impossible = parse_request(&json!({+ "query": { "query_string": { "query": format!("\"{body}") } },+ "size": 10,+ "timeout": "1ms",+ }))+ .expect("parse_request");+ let starved = idx.search(&impossible).await.unwrap();+ assert!(+ starved.timed_out,+ "a 1ms budget against a 36 000-clause cross-product must report \+ timed_out, not silently run to completion"+ );+ // Bounded must not mean silently wrong: partial results are a SUBSET.+ assert!(+ res.total.value <= DOCS as u64,+ "over-counting: {} > {DOCS}",+ res.total.value+ );++ // Same query, ample budget: bounding the cross-product must not cost+ // correctness — every document really does hold every token.+ let generous = parse_request(&json!({+ "query": { "query_string": { "query": format!("\"{body}") } },+ "size": 10,+ "timeout": "60s",+ }))+ .expect("parse_request");+ let full = idx.search(&generous).await.unwrap();+ assert!(!full.timed_out, "60s is ample for this corpus");+ assert_eq!(+ full.total.value, DOCS as u64,+ "the capped path must still find every matching document"+ );+}++/// Floor cost of `req` against `idx`, query cache cleared before every run.+///+/// `query_cache` is keyed on `(query_body_hash, dataset_version)` and holds+/// the finished `SearchResult`, so re-running an identical request otherwise+/// measures a DashMap lookup and nothing else. Without the clear an earlier+/// version of this measurement reported ~5 µs for every shape on BOTH sides of+/// the fix — one real execution followed by four cache hits.+///+/// Best-of-5: the floor is the shape's real cost, and a scheduler blip can+/// only ever make a run look SLOWER, never faster.+async fn floor_ns(idx: &std::sync::Arc<xerj_engine::Index>, req: &SearchRequest) -> (u128, u64) {+ let warm = idx.search(req).await.unwrap();+ let mut best = u128::MAX;+ for _ in 0..5 {+ idx.query_cache.clear();+ let t = std::time::Instant::now();+ let r = idx.search(req).await.unwrap();+ best = best.min(t.elapsed().as_nanos());+ assert_eq!(r.total.value, warm.total.value, "runs must agree");+ }+ (best, warm.total.value)+}++/// A `query_string` whose text the standard analyzer reduces to NOTHING —+/// pure punctuation — can match no document, on any path: the projection is a+/// disjunction with zero clauses and the stored-doc scan's `QueryString` arm+/// returns `false` the instant its token set is empty.+///+/// Routing that shape to the stored-doc scan (because "the projection+/// declined") made the query that matches nothing pay for a full O(corpus)+/// walk.+///+/// The comparator is a query on the SAME index that provably DOES take that+/// walk — `match` with `operator: and`, which `is_doc_scan_query` routes to+/// the stored section — so the assertion is machine-relative and needs no+/// absolute budget. `match_all` is deliberately NOT the comparator: it has its+/// own bounded-scan fast path and is cheaper than one full walk, which is what+/// made an earlier version of this test fail against the FIXED code.+///+/// MEASURED, release, 20 000 documents in ONE segment, best of 5, query cache+/// cleared before every run — see the commit message for the numbers.+#[tokio::test]+async fn zero_token_query_string_does_not_scan_the_corpus() {+ // `+++` survives the Lucene lowerer as an opaque `QueryString` (the+ // unterminated quote is what stops it becoming a `Match`/`Bool` tree), and+ // the standard analyzer reduces it to zero tokens. Pin the shape: if the+ // parser ever lowers it, this test stops covering the arm it names.+ let zero_token = search(opaque_qs("+++"));+ assert!(+ matches!(zero_token.query, QueryNode::QueryString { .. }),+ "the test needs an opaque QueryString node; got {:?}",+ zero_token.query+ );+ // Known stored-doc scan over the same corpus: per-token AND semantics+ // exist only on the doc-scan path, so `is_doc_scan_query` sends it there.+ let known_scan = search(json!({+ "match": { "alpha": { "query": "body text", "operator": "and" } }+ }));++ let dir = TempDir::new().unwrap();+ let engine = make_single_segment_engine(&dir);+ engine.create_index("punct", Schema::empty()).unwrap();+ let idx = engine.get_index("punct").unwrap();++ const DOCS: usize = 20_000;+ for d in 0..DOCS {+ idx.index_document(+ Some(format!("d{d}")),+ json!({ "alpha": format!("body text {d}"), "beta": "more words here" }),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();+ assert_eq!(+ idx.stats().await.segment_count,+ 1,+ "one segment, so the comparator walks exactly the documents the \+ zero-token query would have walked"+ );++ let (zero_ns, zero_total) = floor_ns(&idx, &zero_token).await;+ let (scan_ns, scan_total) = floor_ns(&idx, &known_scan).await;++ assert_eq!(zero_total, 0, "zero tokens can match nothing");+ assert_eq!(+ scan_total, DOCS as u64,+ "the comparator must really walk the corpus"+ );++ eprintln!(+ "zero-token query_string: {:.3}ms full stored scan: {:.3}ms ({DOCS} docs, 1 segment)",+ zero_ns as f64 / 1e6,+ scan_ns as f64 / 1e6+ );++ // An order of magnitude of headroom on this machine. Demanding only 4×+ // keeps the guard meaningful on a runner where the fixed per-request+ // overhead is a larger share of the total.+ assert!(+ zero_ns * 4 < scan_ns,+ "a `query_string` that matches NOTHING cost {:.3}ms against {:.3}ms \+ for a query that really does walk all {DOCS} documents — it is doing \+ the full stored-doc scan instead of returning empty",+ zero_ns as f64 / 1e6,+ scan_ns as f64 / 1e6+ );+}++/// The zero-token split must not weaken the cross-product fallback: a+/// `query_string` that declines for the OTHER reason — too many+/// `tokens × fields` clauses — still has to be answered by the stored-doc+/// scan, or every one of its matches disappears.+#[tokio::test]+async fn over_cap_query_string_still_reaches_the_stored_doc_scan() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("overcap", Schema::empty()).unwrap();+ let idx = engine.get_index("overcap").unwrap();++ // 40 fields × 200 tokens = 8 000 clauses, past MAX_QS_CROSS_PRODUCT+ // (4 096), so the projection returns `None` — the same `None` the+ // zero-token shape returns, and the one that still needs the scan.+ const FIELDS: usize = 40;+ const TOKENS: usize = 200;+ const DOCS: usize = 12;+ let body: String = (0..TOKENS).map(|t| format!("tok{t} ")).collect::<String>();+ for d in 0..DOCS {+ let mut doc = serde_json::Map::new();+ for f in 0..FIELDS {+ doc.insert(format!("f{f}"), json!(body.clone()));+ }+ idx.index_document(Some(format!("d{d}")), Value::Object(doc))+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ let r = idx.search(&search(opaque_qs(body.trim()))).await.unwrap();+ assert_eq!(+ r.total.value,+ DOCS as u64,+ "an over-cap `query_string` declines the postings path and MUST fall \+ through to the stored-doc scan; {} of {DOCS} documents were dropped",+ DOCS as u64 - r.total.value+ );+}++/// Undeclared response-value change, now pinned.+///+/// `prune_missing_should_fields` fires for ANY should-only bool of plain+/// terms, which includes an ordinary two-clause `match` disjunction — a shape+/// the field-less `query_string` work never mentions. On a heterogeneous+/// corpus that moved `max_score` (2.0986123 -> 1.3996884 as first measured);+/// `hits.total` and every per-hit `_score` were byte-identical.+///+/// The new value is the correct one, and this test is the definition rather+/// than a pinned constant: ES documents `max_score` as the highest `_score`+/// among the matching documents, so a `max_score` no returned hit can reach is+/// wrong by construction. Pre-change it came from `scored_max_bits` — the+/// brute stored-doc scorer's population max — while the hits themselves were+/// scored by the FTS postings path. Two scorers, two scales, and `max_score`+/// took the larger: the field-lacking segment was rejected by the+/// all-fields-present gate and re-scored by the brute scan, which is exactly+/// what the prune stops happening.+#[tokio::test]+async fn should_only_bool_max_score_never_exceeds_the_top_hit() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("scores", Schema::empty()).unwrap();+ let idx = engine.get_index("scores").unwrap();++ // Heterogeneous by construction: the first four documents are flushed+ // before `gamma` exists, so that segment has no `gamma` FTS side-car and+ // the disjunction's `gamma` clause is the one the prune drops.+ for i in 0..4 {+ idx.index_document(+ Some(format!("old{i}")),+ json!({ "alpha": format!("apple pie {i}") }),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();+ for i in 0..3 {+ idx.index_document(+ Some(format!("new{i}")),+ json!({ "alpha": "apple tart", "gamma": format!("apple sauce {i}") }),+ )+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ let req = search(json!({+ "bool": { "should": [+ { "match": { "alpha": "apple" } },+ { "match": { "gamma": "apple" } },+ ]}+ }));+ let r = idx.search(&req).await.unwrap();++ assert_eq!(r.total.value, 7, "every document holds `apple` somewhere");+ assert_eq!(r.hits.len(), 7, "size:100 — every hit is on the page");++ let top = r+ .hits+ .iter()+ .map(|h| h.score)+ .fold(f32::NEG_INFINITY, f32::max);+ let max_score = r.max_score.expect("a scored query reports max_score");+ let mut scores: Vec<f32> = r.hits.iter().map(|h| h.score).collect();+ scores.sort_by(|a, b| b.partial_cmp(a).unwrap());+ eprintln!(+ "total={} max_score={max_score} top_hit={top} scores={scores:?}",+ r.total.value+ );+ assert!(+ (max_score - top).abs() <= f32::EPSILON * top.abs().max(1.0),+ "max_score {max_score} is not the highest returned _score {top} — ES \+ defines max_score as the maximum `_score` of the matching documents, \+ so a value no hit can reach is unreachable by definition"+ );+ // Guard the other direction too: a max_score BELOW the top hit would be+ // just as wrong, and would be the natural regression if the population+ // max were ever narrowed to a page.+ assert!(max_score >= top, "max_score {max_score} < top hit {top}");+}++/// The cap must not change results for ordinary (within-cap) queries.+#[tokio::test]+async fn field_less_query_string_within_the_cap_is_unchanged() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("small", Schema::empty()).unwrap();+ let idx = engine.get_index("small").unwrap();++ idx.index_document(+ Some("a".into()),+ json!({"title": "alpha", "body": "needle"}),+ )+ .await+ .unwrap();+ idx.index_document(Some("b".into()), json!({"title": "needle", "body": "beta"}))+ .await+ .unwrap();+ idx.index_document(Some("c".into()), json!({"title": "gamma", "body": "delta"}))+ .await+ .unwrap();+ idx.flush().await.unwrap();++ let r = idx.search(&search(opaque_qs("needle"))).await.unwrap();+ assert_eq!(+ r.total.value, 2,+ "`needle` is in `body` of one doc and `title` of another"+ );+}diff --git a/engine/crates/xerj-fts/src/search.rs b/engine/crates/xerj-fts/src/search.rsindex c472b5381..7415d8648 100644--- a/engine/crates/xerj-fts/src/search.rs+++ b/engine/crates/xerj-fts/src/search.rs@@ -1028,24 +1028,51 @@ impl FtsSearcher {0});- // Execute all sub-queries- let must_hits: Vec<Vec<ScoredHit>> = bq- .must- .iter()- .map(|q| self.execute(q, explain))- .collect::<Result<_>>()?;-- let should_hits: Vec<Vec<ScoredHit>> = bq- .should- .iter()- .map(|q| self.execute(q, explain))- .collect::<Result<_>>()?;-- let must_not_hits: Vec<Vec<ScoredHit>> = bq- .must_not- .iter()- .map(|q| self.execute(q, explain))- .collect::<Result<_>>()?;+ // Execute all sub-queries.+ //+ // Cooperative deadline (RC4 blocker 12, extended to clause fan-out):+ // clause COUNT is a second unbounded axis alongside the term-dictionary+ // walks the expansion loops already poll. A projected disjunction is+ // one clause per (token × field) — a field-less `query_string` over a+ // wide mapping reaches tens of thousands — and each clause here+ // materialises a full `Vec<ScoredHit>` before anything is combined. The+ // engine runs the search to completion inside `block_in_place`, so the+ // outer `tokio::time::timeout` cannot interrupt it: without this poll+ // one request holds a worker for as long as the clause list takes,+ // whatever the request's own timeout said. Stopping early yields+ // partial hits, which `deadline_tripped` reports so the response says+ // `timed_out: true` (ES shard-timeout semantics).+ //+ // Partial must ALWAYS mean narrower, never broader. Abandoning a+ // `should` clause only removes disjuncts, so the surviving hits are a+ // subset of the true answer — safe. Abandoning a `must` or `must_not`+ // clause would RELAX the query and admit documents it excludes, so+ // those bail the whole bool to an empty result instead.+ let mut clauses_run: usize = 0;+ let mut run_clauses =+ |slice: &[Query], partial_ok: bool| -> Result<Option<Vec<Vec<ScoredHit>>>> {+ let mut out = Vec::with_capacity(slice.len());+ for q in slice {+ // Poll every 64 clauses: one clause is a postings decode,+ // orders of magnitude coarser than the per-term probes the+ // expansion loops poll every 1 024 of.+ if clauses_run & 63 == 0 && self.deadline_hit() {+ return Ok(if partial_ok { Some(out) } else { None });+ }+ clauses_run += 1;+ out.push(self.execute(q, explain)?);+ }+ Ok(Some(out))+ };+ let Some(must_hits) = run_clauses(&bq.must, false)? else {+ return Ok(Vec::new());+ };+ let Some(should_hits) = run_clauses(&bq.should, true)? else {+ return Ok(Vec::new());+ };+ let Some(must_not_hits) = run_clauses(&bq.must_not, false)? else {+ return Ok(Vec::new());+ };// Build must_not doc_id setlet must_not_docs: std::collections::HashSet<u32> = must_not_hits@@ -1880,6 +1907,277 @@ mod tests {);}+ /// Clause COUNT is the second unbounded axis. A projected disjunction is+ /// one clause per (token × field), so a field-less `query_string` over a+ /// wide mapping arrives here with tens of thousands of `should` clauses,+ /// each materialising a full hit vector. Pre-fix nothing in this loop+ /// polled the request deadline, so the whole list ran to completion+ /// inside `block_in_place` — one request holding a worker for as long as+ /// the clause list took, whatever its timeout said.+ #[test]+ fn bool_clause_fan_out_respects_cooperative_deadline() {+ let dir = TempDir::new().unwrap();+ let registry = Arc::new(AnalyzerRegistry::default());+ let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(®istry));+ let cfg = FieldIndexConfig {+ analyzer: "whitespace".to_owned(),+ ..Default::default()+ };+ writer.configure_field("body", cfg);+ let text: String = (0..2000)+ .map(|i| format!("term{i:05}"))+ .collect::<Vec<_>>()+ .join(" ");+ writer.add_document(0, &[("body".to_owned(), text)].into_iter().collect());+ writer.finish().unwrap();+ let reader = Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["body"]).unwrap());++ // 2 000 `should` clauses — well past the every-64 poll interval.+ let mut bq = BoolQuery::new();+ for i in 0..2000 {+ bq = bq.should(Query::Term(TermQuery::new("body", format!("term{i:05}"))));+ }+ let q = Query::Bool(Box::new(bq));++ // Unarmed searcher: every clause runs, the doc matches, flag clear.+ let searcher = FtsSearcher::new(Arc::clone(&reader), Arc::clone(®istry));+ let hits = searcher.search(&q, 10, false).unwrap();+ assert_eq!(+ hits.len(),+ 1,+ "the one doc matches via the full disjunction"+ );+ assert!(!searcher.deadline_tripped(), "no deadline → never tripped");++ // Deadline already past: the clause loop stops at its first poll,+ // returns Ok (graceful partial, not an error), and latches the trip+ // so the caller reports `timed_out: true`.+ let expired = FtsSearcher::new(Arc::clone(&reader), Arc::clone(®istry)).with_deadline(+ Some(std::time::Instant::now() - std::time::Duration::from_millis(1)),+ );+ let partial = expired.search(&q, 10, false).unwrap();+ assert!(+ expired.deadline_tripped(),+ "expired deadline must latch deadline_tripped on clause fan-out"+ );+ assert!(+ partial.len() <= 1,+ "partial results are a SUBSET, never more than the true answer"+ );+ }++ /// The poll interval of `execute_bool`'s clause loop. The two tests below+ /// depend on it: a clause list of EXACTLY this length is polled once, at+ /// its first clause, and the NEXT list is then polled at its first clause+ /// too — which is how the deadline is made to land between two lists.+ const CLAUSE_POLL_INTERVAL: usize = 64;++ /// Dictionary size for [`midlist_deadline_fixture`]. Measured on this+ /// machine, one full `term*` wildcard walk: ~38 ms release / ~341 ms+ /// debug, funding a ~19 ms / ~170 ms budget.+ const DICTIONARY_TERMS: usize = 100_000;++ /// Fixture for the "partial must never broaden" pair.+ ///+ /// Returns the segment reader, a wildcard clause expensive enough to spend+ /// a whole request budget on its own, and a budget MEASURED from that+ /// clause rather than hard-coded. Deriving it is what keeps the pair+ /// honest on a machine of any speed — a slower machine measures a slower+ /// walk and gets a proportionally larger budget, so the only absolute+ /// risk (the budget expiring before the bool's first clause poll, which+ /// would make both tests vacuous) shrinks rather than grows under load.+ /// A hard-coded 2 ms budget did expire that way once, in release, with+ /// the rest of this suite running in parallel; the precondition+ /// assertions caught it as a failure rather than a false pass.+ ///+ /// The document holds `alpha` (a hit), `beta` (an exclusion), and a+ /// 100 000-term dictionary for the wildcard to walk. That size is set by+ /// the RELEASE profile: at 20 000 terms an optimised walk is ~7 ms, which+ /// cannot fund a budget big enough to survive scheduling.+ fn midlist_deadline_fixture(+ dir: &TempDir,+ ) -> (+ Arc<FtsIndexReader>,+ Arc<AnalyzerRegistry>,+ Query,+ std::time::Duration,+ ) {+ let registry = Arc::new(AnalyzerRegistry::default());+ let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(®istry));+ let cfg = FieldIndexConfig {+ analyzer: "whitespace".to_owned(),+ ..Default::default()+ };+ writer.configure_field("body", cfg);+ let mut text = String::from("alpha beta");+ for i in 0..DICTIONARY_TERMS {+ text.push_str(&format!(" term{i:06}"));+ }+ writer.add_document(0, &[("body".to_owned(), text)].into_iter().collect());+ writer.finish().unwrap();+ let reader = Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["body"]).unwrap());++ let mut wq = WildcardQuery::new("body", "term*");+ wq.case_insensitive = false;+ let expensive = Query::Wildcard(wq);++ // Calibrate with no deadline armed, twice — the second run is warm,+ // and warm is what the timed runs will be.+ let cal = FtsSearcher::new(Arc::clone(&reader), Arc::clone(®istry));+ let _ = cal.search(&expensive, 10, false).unwrap();+ let t0 = std::time::Instant::now();+ let _ = cal.search(&expensive, 10, false).unwrap();+ let full_walk = t0.elapsed();+ assert!(!cal.deadline_tripped(), "no deadline → never tripped");++ // HALF the full walk. Below it, so the wildcard provably overruns and+ // the deadline is past when it returns; large in absolute terms, so+ // the microseconds between arming the deadline and the bool's first+ // clause poll cannot consume it.+ let budget = full_walk / 2;+ assert!(+ budget >= std::time::Duration::from_millis(10),+ "the calibration clause is too cheap to fund a budget that \+ survives scheduling (full walk {full_walk:?}); raise \+ DICTIONARY_TERMS"+ );+ (reader, registry, expensive, budget)+ }++ /// A truncated `must_not` would RELAX the query and admit documents it+ /// excludes. That clause list must bail the whole bool to empty rather+ /// than return a broader-than-asked-for set.+ ///+ /// The deadline has to expire strictly BETWEEN the `should` clauses and+ /// the `must_not` clauses, and that is the whole difficulty. An+ /// already-expired deadline cannot exercise this at all: the poll fires on+ /// the FIRST clause of the bool, so `should` truncates to nothing, the+ /// bool is empty whatever `must_not` does, and the assertion holds+ /// vacuously. An earlier version of this test did exactly that — it passed+ /// with the source change reverted AND with the hazard it is named after+ /// (`must_not` truncation made partial-ok) deliberately introduced.+ ///+ /// So the deadline is armed in the FUTURE and spent inside the `should`+ /// list by one deliberately expensive clause:+ ///+ /// * `should` holds exactly one poll interval of clauses, so the only+ /// poll inside it is at index 0, before any budget is spent. Clause 0+ /// matches the document; clause 1 burns the budget; the rest are cheap+ /// misses.+ /// * `must_not` is therefore entered with the shared clause counter at+ /// 64, its first poll fires, and the excluding clause never runs.+ ///+ /// Verified to fail on the hazard: with `run_clauses(&bq.must_not, true)`+ /// the document comes back and the final assertion trips.+ ///+ /// Both preconditions are asserted rather than assumed, so an unlucky+ /// machine makes this test FAIL LOUDLY instead of passing vacuously.+ #[test]+ fn bool_deadline_never_broadens_a_must_not() {+ let dir = TempDir::new().unwrap();+ let (reader, registry, expensive, budget) = midlist_deadline_fixture(&dir);++ let mut base = BoolQuery::new().should(Query::Term(TermQuery::new("body", "alpha")));+ base = base.should(expensive);+ for i in 2..CLAUSE_POLL_INTERVAL {+ base = base.should(Query::Term(TermQuery::new("body", format!("absent{i}"))));+ }+ assert_eq!(base.should.len(), CLAUSE_POLL_INTERVAL);++ // Precondition: the same should list, same budget, no must_not. If+ // this comes back empty the deadline fired before the should clauses+ // ran and the real assertion below would prove nothing.+ let control = FtsSearcher::new(Arc::clone(&reader), Arc::clone(®istry))+ .with_deadline(Some(std::time::Instant::now() + budget));+ let control_hits = control+ .search(&Query::Bool(Box::new(base.clone())), 10, false)+ .unwrap();+ assert_eq!(+ control_hits.len(),+ 1,+ "precondition: the should clauses must have produced the document \+ before the budget ({budget:?}) ran out"+ );++ let with_must_not = Query::Bool(Box::new(+ base.must_not(Query::Term(TermQuery::new("body", "beta"))),+ ));+ let expired = FtsSearcher::new(reader, registry)+ .with_deadline(Some(std::time::Instant::now() + budget));+ let hits = expired.search(&with_must_not, 10, false).unwrap();+ assert!(+ expired.deadline_tripped(),+ "precondition: the budget ({budget:?}) must have been spent \+ inside the clause list"+ );+ assert!(+ hits.is_empty(),+ "a must_not that could not be fully evaluated must not admit the \+ document it excludes — got {} hit(s)",+ hits.len()+ );+ }++ /// The other half of the same invariant: a truncated `must` drops+ /// conjuncts, and dropping a conjunct only ever ADMITS documents the full+ /// query rejects.+ ///+ /// Same construction, one list earlier: `must` holds one poll interval of+ /// clauses the document satisfies (clause 1 burns the budget), and the+ /// conjunct that would EXCLUDE it sits at index 64 — the first clause not+ /// reached before the poll fires. Truncating there and keeping the partial+ /// intersection returns the document; bailing returns nothing.+ ///+ /// Verified to fail on the hazard: with `run_clauses(&bq.must, true)` the+ /// document comes back and the final assertion trips.+ #[test]+ fn bool_deadline_never_broadens_a_must() {+ let dir = TempDir::new().unwrap();+ let (reader, registry, expensive, budget) = midlist_deadline_fixture(&dir);++ // Every clause here matches the one document, so the intersection is+ // non-empty right up to the clause that is never reached.+ let mut base = BoolQuery::new().must(Query::Term(TermQuery::new("body", "alpha")));+ base = base.must(expensive);+ for i in 2..CLAUSE_POLL_INTERVAL {+ base = base.must(Query::Term(TermQuery::new("body", format!("term{i:06}"))));+ }+ assert_eq!(base.must.len(), CLAUSE_POLL_INTERVAL);++ // Precondition: without the excluding conjunct the document survives,+ // so a later empty result can only come from the guard.+ let control = FtsSearcher::new(Arc::clone(&reader), Arc::clone(®istry))+ .with_deadline(Some(std::time::Instant::now() + budget));+ let control_hits = control+ .search(&Query::Bool(Box::new(base.clone())), 10, false)+ .unwrap();+ assert_eq!(+ control_hits.len(),+ 1,+ "precondition: the must clauses must have intersected to the \+ document before the budget ({budget:?}) ran out"+ );++ // `zebrafish` is in no document, so a FULL evaluation excludes doc 0.+ let with_excluding_conjunct = Query::Bool(Box::new(+ base.must(Query::Term(TermQuery::new("body", "zebrafish"))),+ ));+ let expired = FtsSearcher::new(reader, registry)+ .with_deadline(Some(std::time::Instant::now() + budget));+ let hits = expired.search(&with_excluding_conjunct, 10, false).unwrap();+ assert!(+ expired.deadline_tripped(),+ "precondition: the budget ({budget:?}) must have been spent \+ inside the clause list"+ );+ assert!(+ hits.is_empty(),+ "a must clause that could not be evaluated must not be silently \+ dropped from the conjunction — got {} hit(s)",+ hits.len()+ );+ }+#[test]fn phrase_query_nonexistent_returns_empty() {let dir = TempDir::new().unwrap();