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(es-compat): report the index:false rejection on the three surfaces that still swallowed it

xerj-org567550db20a5
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 552788657..e00f394d7 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -15401,6 +15401,19 @@ pub async fn refresh_index(
// GET /{index}/_count
// ─────────────────────────────────────────────────────────────────────────────
+/// One entry of `_count`'s `_shards.failures`, in ES's shape. `rendered` is the
+/// `ApiError` body for the failure; the per-index entry carries the
+/// *shard-level* exception (`query_shard_exception`) rather than the
+/// `search_phase_execution_exception` wrapper the top-level error uses.
+fn count_shard_failure(index: &str, rendered: &Value) -> Value {
+ let reason = rendered
+ .pointer("/error/root_cause/0")
+ .or_else(|| rendered.pointer("/error"))
+ .cloned()
+ .unwrap_or_else(|| json!({ "type": "exception", "reason": "search failed" }));
+ json!({ "shard": 0, "index": index, "reason": reason })
+}
+
pub async fn count_docs_global(
State(state): State<AppState>,
Query(params): Query<CountParams>,
@@ -15449,7 +15462,28 @@ pub async fn count_docs(
.and_then(|b| b.get("query"))
.map(|q| !q.is_null())
.unwrap_or(false);
+ // A refused query is not a zero. This loop used to run the search under
+ // `if let Ok(..)` with no else, so an index whose mapping refuses the
+ // query — a `match` on an `"index": false` field, say — contributed
+ // nothing to `total` and the response still published
+ // `"successful": <all>, "failed": 0`: a confident wrong count on the
+ // shapes most callers actually write (`logs-*`, a comma list, and
+ // `POST /_count`, which routes here through `_all`).
+ //
+ // The failure is now reported per index, and the HTTP status follows
+ // ES's own rule for a broadcast action: the failure status is returned
+ // only when NO shard succeeded, and otherwise the response is a 200
+ // carrying the partial count with the failures visible in `_shards`
+ // (`server/src/main/java/org/elasticsearch/rest/RestStatus.java:548-566`
+ // — read for semantics only; ES is AGPL-3.0/SSPL-1.0/Elastic-2.0 and
+ // no code from it is reproduced here). So a single-index `_count`, and
+ // a `logs-*` whose indices all share the offending mapping, both 400
+ // exactly as `_search` does, while a mixed selector answers what it
+ // could count and says out loud what it could not.
let mut total: u64 = 0;
+ let mut successful: u64 = 0;
+ let mut shard_failures: Vec<Value> = Vec::new();
+ let mut first_error: Option<Value> = None;
for ix_name in &wanted {
let Ok(idx) = state.engine.get_index(ix_name) else {
continue;
@@ -15466,8 +15500,17 @@ pub async fn count_docs(
// object and rejects it).
resolve_terms_lookups(&mut query_val, &state).await;
let search_body = json!({ "query": query_val, "size": 0, "from": 0 });
- if let Ok(req) = xerj_query::parse_request(&search_body) {
- if let Ok(result) = idx.search(&req).await {
+ // A body that does not parse is not per-index: it is the same
+ // 400 the single-index arm returns, for the same reason.
+ let req = match xerj_query::parse_request(&search_body) {
+ Ok(r) => r,
+ Err(e) => {
+ let ze = xerj_common::XerjError::invalid_query(e.to_string());
+ return ApiError::new(ze).into_response();
+ }
+ };
+ match idx.search(&req).await {
+ Ok(result) => {
// A script resource limit in the filter (terms_set's
// `minimum_should_match` script, say) makes matching
// fail-closed, so the count under-reports with nothing
@@ -15476,16 +15519,45 @@ pub async fn count_docs(
return script_limit_response(reason);
}
total += result.total.value;
+ successful += 1;
+ }
+ Err(e) => {
+ let rendered = ApiError::new(xerj_common::XerjError::from(e)).into_value();
+ shard_failures.push(count_shard_failure(ix_name, &rendered));
+ if first_error.is_none() {
+ first_error = Some(rendered);
+ }
}
}
} else {
total += idx.stats().await.doc_count;
+ successful += 1;
+ }
+ }
+ // Nothing answered and something refused: the count IS the error, and
+ // it is returned with the same body and status the single-index form
+ // would have produced.
+ if successful == 0 && !shard_failures.is_empty() {
+ if let Some(rendered) = first_error {
+ let code = rendered
+ .get("status")
+ .and_then(Value::as_u64)
+ .and_then(|c| StatusCode::from_u16(c as u16).ok())
+ .unwrap_or(StatusCode::BAD_REQUEST);
+ return (code, Json(rendered)).into_response();
}
}
+ // `total` is what was actually attempted, so the three numbers add up:
+ // a name in a comma list that resolves to no index is skipped here (as
+ // it always was) rather than counted as a shard that succeeded.
+ let failed = shard_failures.len() as u64;
let mut body_out = json!({
"count": total,
- "_shards": { "total": wanted.len() as u64, "successful": wanted.len() as u64, "skipped": 0, "failed": 0 }
+ "_shards": { "total": successful + failed, "successful": successful, "skipped": 0, "failed": failed }
});
+ if !shard_failures.is_empty() {
+ body_out["_shards"]["failures"] = Value::Array(shard_failures);
+ }
if let Some(ref fp) = params.filter_path {
if !fp.is_empty() {
let paths: Vec<&str> = fp.split(',').map(str::trim).collect();
@@ -25368,10 +25440,27 @@ async fn msearch_template_impl(
let mut merged_hits: Vec<Value> = Vec::new();
let mut total_count: u64 = 0;
let mut script_failure: Option<String> = None;
+ let mut search_error: Option<xerj_common::XerjError> = None;
+ // Both arms below used to be `if let Ok(..)` with no else, so a
+ // missing index or a query the engine refused produced
+ // `{"_shards":{"successful":1,"failed":0},"hits":{"total":0}}` — a
+ // sub-response positively asserting the shard succeeded and found
+ // nothing. `_msearch` carries the same errors as a per-response
+ // envelope (`ApiError::into_value`, which keeps the exact body and
+ // status the single-request `_search` would have returned); the
+ // template form now does the same, and the sibling sub-requests in the
+ // batch are unaffected either way.
for idx_name in &index_names {
- if let Ok(idx) = state.engine.get_index(idx_name) {
- if let Ok(result) = idx.search(&search_req).await {
+ let idx = match state.engine.get_index(idx_name) {
+ Ok(i) => i,
+ Err(e) => {
+ search_error = Some(xerj_common::XerjError::from(e));
+ break;
+ }
+ };
+ match idx.search(&search_req).await {
+ Ok(result) => {
if let Some(reason) = result.script_failure {
script_failure = Some(reason);
break;
@@ -25391,6 +25480,10 @@ async fn msearch_template_impl(
}));
}
}
+ Err(e) => {
+ search_error = Some(xerj_common::XerjError::from(e));
+ break;
+ }
}
}
@@ -25401,6 +25494,11 @@ async fn msearch_template_impl(
continue;
}
+ if let Some(err) = search_error {
+ responses.push(ApiError::new(err).into_value());
+ continue;
+ }
+
let took_ms = started.elapsed().as_millis() as u64;
responses.push(json!({
"took": took_ms,
@@ -30134,6 +30232,25 @@ pub async fn rank_eval(
let mut failures = serde_json::Map::new();
+ // A request `_rank_eval` cannot run is recorded in `failures`, never
+ // dropped. The three arms below used to be `Err(_) => continue`, so a
+ // refused request vanished from `details` AND from `failures` while
+ // `metric_score` was still published — the batch silently shrank and the
+ // mean was taken over the survivors, on the one endpoint whose entire
+ // purpose is measuring relevance quality. `failures` is the channel ES
+ // provides for exactly this (the `script_failure` arm further down already
+ // used it); a faulted request contributes nothing to `metric_score`, and a
+ // caller can now see that it did not.
+ let record_failure =
+ |failures: &mut serde_json::Map<String, Value>, id: &str, err: xerj_common::XerjError| {
+ let detail = ApiError::new(err)
+ .into_value()
+ .get("error")
+ .cloned()
+ .unwrap_or_else(|| json!({ "type": "exception", "reason": "request failed" }));
+ failures.insert(id.to_string(), detail);
+ };
+
for req_spec in &body.requests {
let query_val = req_spec
.request
@@ -30149,17 +30266,30 @@ pub async fn rank_eval(
let search_req =
match xerj_query::parse_request(&json!({"query": query_val, "size": size.max(k)})) {
Ok(r) => r,
- Err(_) => continue,
+ Err(e) => {
+ record_failure(
+ &mut failures,
+ &req_spec.id,
+ xerj_common::XerjError::invalid_query(e.to_string()),
+ );
+ continue;
+ }
};
let idx = match state.engine.get_index(&index) {
Ok(i) => i,
- Err(_) => continue,
+ Err(e) => {
+ record_failure(&mut failures, &req_spec.id, xerj_common::XerjError::from(e));
+ continue;
+ }
};
let result = match idx.search(&search_req).await {
Ok(r) => r,
- Err(_) => continue,
+ Err(e) => {
+ record_failure(&mut failures, &req_spec.id, xerj_common::XerjError::from(e));
+ continue;
+ }
};
// A Painless resource limit tripped while scoring or matching this
// request. `_rank_eval` exists to *measure relevance quality*, so a
diff --git a/engine/crates/xerj-api/tests/index_false_is_honoured.rs b/engine/crates/xerj-api/tests/index_false_is_honoured.rs
index 20ed82aaa..569ca1217 100644
--- a/engine/crates/xerj-api/tests/index_false_is_honoured.rs
+++ b/engine/crates/xerj-api/tests/index_false_is_honoured.rs
@@ -585,16 +585,120 @@ async fn documented_gaps_are_still_open_and_still_documented() {
.await;
assert_eq!(status, StatusCode::OK, "GAP 1 (sort half) changed: {body}");
+ // A token that exists ONLY in the unsearchable field. The gaps below are
+ // about matching *through* `note`, so probing them with a word that also
+ // lives in `body` would pass whether or not the gap were open.
+ let (status, body) = json_req(
+ &app,
+ "PUT",
+ "/t/_doc/2?refresh=true",
+ json!({ "note": "zzquagga sighting", "body": "nothing to see here" }),
+ )
+ .await;
+ assert!(status.is_success(), "index doc 2 failed: {status} {body}");
+
// GAP 2 — the FIELD-LESS arms of the stored-document scan are schema-free
// and walk every `_source` key, so a token living only in an unsearchable
// field still matches when NO field is named.
for query in [
- json!({ "query_string": { "query": "pelicans" } }),
- json!({ "more_like_this": { "like": ["pelicans"], "min_term_freq": 1, "max_query_terms": 5 } }),
+ json!({ "query_string": { "query": "zzquagga" } }),
+ json!({ "more_like_this": { "like": ["zzquagga"], "min_term_freq": 1, "max_query_terms": 5 } }),
] {
let (status, body) = search(&app, query.clone()).await;
assert_eq!(status, StatusCode::OK, "GAP 2 changed for {query}: {body}");
}
+ let (_, body) = search(&app, json!({ "query_string": { "query": "zzquagga" } })).await;
+ assert_eq!(
+ body.pointer("/hits/total/value").and_then(Value::as_u64),
+ Some(1),
+ "GAP 2 changed — the field-less scan no longer reaches `note`, \
+ update the CHANGELOG: {body}"
+ );
+
+ // GAP 3 — GAP 2 reached through a WILDCARD `fields` spec. A pattern is
+ // never an error (that half is ES's rule and is deliberate), but in
+ // `query_string` / `simple_query_string` a pattern lowers to the same
+ // field-less `"*"` placeholder as GAP 2, so it is answered by the
+ // schema-free scan and still matches through `note`. Identical on `main`:
+ // this change neither introduced nor closed it, and the CHANGELOG says so
+ // instead of claiming a pattern is "answered over the searchable fields".
+ for query in [
+ json!({ "simple_query_string": { "query": "zzquagga", "fields": ["*"] } }),
+ json!({ "query_string": { "query": "zzquagga", "fields": ["*"] } }),
+ ] {
+ let (status, body) = search(&app, query.clone()).await;
+ assert_eq!(status, StatusCode::OK, "GAP 3 changed for {query}: {body}");
+ assert_eq!(
+ body.pointer("/hits/total/value").and_then(Value::as_u64),
+ Some(1),
+ "GAP 3 changed for {query} — the wildcard form no longer reaches \
+ the field-less scan, update the CHANGELOG: {body}"
+ );
+ }
+
+ // `multi_match` with a pattern is the counter-example that keeps the
+ // sentence honest: it stays a `MultiMatch` node and is answered by the FTS
+ // projection, which DOES apply ES's `isSearchable()` rule — so it finds
+ // nothing in `note`. The gap is the field-less scan, not "patterns".
+ let (status, body) = search(
+ &app,
+ json!({ "multi_match": { "query": "zzquagga", "fields": ["*", "body"] } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(
+ body.pointer("/hits/total/value").and_then(Value::as_u64),
+ Some(0),
+ "multi_match's pattern expansion must not reach an unsearchable field: {body}"
+ );
+
+ // GAP 4 — the opaque `query_string` fallback. A query string the parser
+ // declines to lower (here: an unterminated quote) keeps the whole string
+ // for the FTS path, and that node has nowhere to put a multi-element
+ // `fields` list, so the list is not applied and not checked. A ONE-element
+ // list is carried across as `default_field` and therefore is checked —
+ // asserted below, because that half is the part that works.
+ let (status, body) = search(
+ &app,
+ json!({ "query_string": { "query": "\"zzquagga", "fields": ["note", "body"] } }),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "GAP 4 changed — the opaque query_string fallback now honours a \
+ multi-field `fields` list, update the CHANGELOG: {body}"
+ );
+ let (status, body) = search(
+ &app,
+ json!({ "query_string": { "query": "\"zzquagga", "fields": ["note"] } }),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "a one-element `fields` must still reach the check on the opaque \
+ fallback: {body}"
+ );
+
+ // GAP 5 — `_validate/query` never opens the index, so it answers on the
+ // parse alone and says a query `_search` refuses is valid. Pre-existing
+ // and identical on `main`, but it now disagrees with `_search` on the same
+ // body, so it is stated rather than left for a user to trip over.
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ "/t/_validate/query",
+ json!({ "query": { "match": { "note": "pelicans" } } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "GAP 5 changed: {body}");
+ assert_eq!(
+ body.get("valid").and_then(Value::as_bool),
+ Some(true),
+ "GAP 5 changed — `_validate/query` now consults the mapping, \
+ update the CHANGELOG: {body}"
+ );
}
/// `more_like_this` needs no arm of its own: with an explicit `fields` list the
@@ -642,3 +746,349 @@ async fn a_named_more_like_this_field_inherits_the_check() {
"{body}"
);
}
+
+/// A second, ordinary index so the multi-index selectors have something real
+/// to sum. `t2` maps `body` only — it has no unsearchable field at all, which
+/// is the point: the rejection must come from `t`'s mapping and must not be
+/// hidden by a sibling index answering normally.
+async fn add_plain_sibling(app: &axum::Router) {
+ let (status, body) = json_req(
+ app,
+ "PUT",
+ "/t2",
+ json!({ "mappings": { "properties": { "body": { "type": "text" } } } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "create t2 failed: {body}");
+
+ let (status, body) = json_req(
+ app,
+ "PUT",
+ "/t2/_doc/1?refresh=true",
+ json!({ "body": "another memo about pelicans" }),
+ )
+ .await;
+ assert!(status.is_success(), "index into t2 failed: {status} {body}");
+}
+
+/// A second index that shares `t`'s unsearchable mapping, so a multi-index
+/// selector can be built in which *every* participating index refuses.
+async fn add_unsearchable_sibling(app: &axum::Router) {
+ let (status, body) = json_req(
+ app,
+ "PUT",
+ "/t3",
+ json!({
+ "mappings": { "properties": {
+ "note": { "type": "text", "index": false },
+ "body": { "type": "text" }
+ } }
+ }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "create t3 failed: {body}");
+
+ let (status, body) = json_req(
+ app,
+ "PUT",
+ "/t3/_doc/1?refresh=true",
+ json!({ "note": "third memo about pelicans", "body": "third memo about pelicans" }),
+ )
+ .await;
+ assert!(status.is_success(), "index into t3 failed: {status} {body}");
+}
+
+/// The multi-index `_count` selectors must report the refusal, never absorb it.
+///
+/// `count_docs` has two arms, and only the single-index arm propagated. The
+/// wildcard / comma-list / `_all` arm ran the search under `if let Ok(..)`
+/// with no else, so a refused index contributed nothing to the total and the
+/// response still published `"successful": 2, "failed": 0` —
+/// `{"count":0,"_shards":{"total":2,"successful":2,"failed":0}}`, a confident
+/// wrong number. `POST /_count` routes through `_all`, so the cluster-wide
+/// count endpoint took that arm, as does the `logs-*` shape almost every real
+/// caller writes.
+///
+/// The status follows ES's broadcast rule rather than "always 400": the
+/// failure status is returned only when NO index answered
+/// (`RestStatus.java:548-566`, semantics only), and otherwise the partial
+/// count comes back as a 200 with the failure visible in `_shards.failures`.
+#[tokio::test]
+async fn every_count_selector_reports_the_rejection() {
+ let (app, _dir) = app_with_mapping().await;
+ add_plain_sibling(&app).await;
+
+ // Control first: the same selectors answer the *searchable* field, and
+ // answer it with both indices counted. Without this the assertions below
+ // would also be satisfied by a route that simply never runs.
+ for path in ["/t*/_count", "/t,t2/_count", "/_all/_count", "/_count"] {
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ path,
+ json!({ "query": { "match": { "body": "pelicans" } } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{path} control: {body}");
+ assert_eq!(
+ body.get("count").and_then(Value::as_u64),
+ Some(2),
+ "{path} control must count both indices: {body}"
+ );
+ assert_eq!(
+ body.pointer("/_shards/failed").and_then(Value::as_u64),
+ Some(0),
+ "{path} control: {body}"
+ );
+ }
+
+ // `t` refuses, `t2` answers: a 200 whose `_shards` says one index failed,
+ // with the shard-level exception attached. The count is partial and says
+ // so — the bug was that it was partial and claimed to be complete.
+ for path in ["/t*/_count", "/t,t2/_count", "/_all/_count", "/_count"] {
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ path,
+ json!({ "query": { "match": { "note": "pelicans" } } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{path}: {body}");
+ assert_eq!(
+ body.pointer("/_shards/failed").and_then(Value::as_u64),
+ Some(1),
+ "{path} must not report a clean run: {body}"
+ );
+ assert_eq!(
+ body.pointer("/_shards/successful").and_then(Value::as_u64),
+ Some(1),
+ "{path}: {body}"
+ );
+ assert_eq!(
+ body.pointer("/_shards/failures/0/index")
+ .and_then(Value::as_str),
+ Some("t"),
+ "{path}: {body}"
+ );
+ assert_eq!(
+ body.pointer("/_shards/failures/0/reason/type")
+ .and_then(Value::as_str),
+ Some("query_shard_exception"),
+ "{path}: {body}"
+ );
+ }
+
+ // …and when every selected index refuses, the count IS the error: the same
+ // 400 envelope the single-index form returns, with no count published.
+ add_unsearchable_sibling(&app).await;
+ for path in ["/t,t3/_count", "/t3/_count"] {
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ path,
+ json!({ "query": { "match": { "note": "pelicans" } } }),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "{path} must refuse, not answer 0: {body}"
+ );
+ assert_eq!(
+ body.pointer("/error/root_cause/0/type")
+ .and_then(Value::as_str),
+ Some("query_shard_exception"),
+ "{path}: {body}"
+ );
+ assert!(
+ body.get("count").is_none(),
+ "{path} published a count for a query no index ran: {body}"
+ );
+ }
+}
+
+/// `_msearch/template` renders the rejection instead of an empty success.
+///
+/// Its per-index loop was `if let Ok(idx)` / `if let Ok(result)` with no else,
+/// so a refused query produced `{"_shards":{"successful":1,"failed":0},
+/// "hits":{"total":{"value":0},"hits":[]}}` — a sub-response positively
+/// asserting the shard ran and found nothing. It now carries the same
+/// per-response envelope `_msearch` does.
+#[tokio::test]
+async fn msearch_template_reports_the_rejection_instead_of_zero_hits() {
+ let (app, _dir) = app_with_mapping().await;
+
+ let body_ndjson = concat!(
+ "{\"index\":\"t\"}\n",
+ "{\"source\":\"{\\\"query\\\":{\\\"match\\\":{\\\"note\\\":\\\"pelicans\\\"}}}\",\"params\":{}}\n",
+ "{\"index\":\"t\"}\n",
+ "{\"source\":\"{\\\"query\\\":{\\\"match\\\":{\\\"body\\\":\\\"pelicans\\\"}}}\",\"params\":{}}\n"
+ );
+ let (status, body) = ndjson_req(&app, "/_msearch/template", body_ndjson).await;
+ assert_eq!(status, StatusCode::OK, "envelope is 200: {body}");
+
+ assert_eq!(
+ body.pointer("/responses/0/status").and_then(Value::as_u64),
+ Some(400),
+ "refused sub-request must be a 400, not an empty 200: {body}"
+ );
+ assert_eq!(
+ body.pointer("/responses/0/error/root_cause/0/type")
+ .and_then(Value::as_str),
+ Some("query_shard_exception"),
+ "{body}"
+ );
+ assert!(
+ body.pointer("/responses/0/hits").is_none(),
+ "a refused sub-request must not also publish a hit list: {body}"
+ );
+
+ // The sibling template in the same batch keeps its answer.
+ assert_eq!(
+ body.pointer("/responses/1/hits/total/value")
+ .and_then(Value::as_u64),
+ Some(1),
+ "{body}"
+ );
+}
+
+/// `_rank_eval` records a refused request in `failures` instead of dropping it.
+///
+/// The three `Err(_) => continue` arms took the request out of `details` *and*
+/// out of `failures` while still publishing `metric_score` — so a relevance
+/// gate read a clean score over a batch that had silently shrunk. `failures`
+/// is the channel ES provides, and the neighbouring `script_failure` arm was
+/// already using it.
+#[tokio::test]
+async fn rank_eval_records_a_refused_request_in_failures() {
+ let (app, _dir) = app_with_mapping().await;
+
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ "/t/_rank_eval",
+ json!({
+ "requests": [
+ {
+ "id": "good",
+ "request": { "query": { "match": { "body": "pelicans" } } },
+ "ratings": [ { "_index": "t", "_id": "1", "rating": 1 } ]
+ },
+ {
+ "id": "bad",
+ "request": { "query": { "match": { "note": "pelicans" } } },
+ "ratings": [ { "_index": "t", "_id": "1", "rating": 1 } ]
+ }
+ ],
+ "metric": { "precision": { "k": 10 } }
+ }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+
+ assert!(
+ body.pointer("/details/good").is_some(),
+ "the answerable request keeps its details: {body}"
+ );
+ assert!(
+ body.pointer("/details/bad").is_none(),
+ "a refused request must not appear in details: {body}"
+ );
+ assert!(
+ body.pointer("/failures/bad").is_some(),
+ "a refused request must appear in failures, not vanish: {body}"
+ );
+ assert_eq!(
+ body.pointer("/failures/bad/root_cause/0/type")
+ .and_then(Value::as_str),
+ Some("query_shard_exception"),
+ "{body}"
+ );
+}
+
+/// `query_string`'s `fields` array is read, and a named unsearchable field in
+/// it is rejected exactly like `default_field`.
+///
+/// `parse_query_string` never looked at `fields`, so the key was accepted and
+/// ignored: the query ran over every field. Once `index: false` became a real
+/// rejection that also made two spellings of one request disagree —
+/// `{"default_field":"note"}` answered 400 while `{"fields":["note"]}`
+/// answered 200 with a hit *through* the unsearchable field.
+#[tokio::test]
+async fn query_string_fields_are_read_and_a_named_unsearchable_field_is_rejected() {
+ let (app, _dir) = app_with_mapping().await;
+
+ for fields in [json!(["note"]), json!(["note", "body"]), json!(["note^3"])] {
+ let query = json!({ "query_string": { "query": "pelicans", "fields": fields } });
+ let (status, body) = search(&app, query.clone()).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{query} → {body}");
+ let reason = body
+ .pointer("/error/root_cause/0/reason")
+ .and_then(Value::as_str)
+ .unwrap_or_default();
+ assert!(
+ reason.contains("Cannot search on field [note]"),
+ "got {reason:?}: {body}"
+ );
+ }
+
+ // The searchable field still answers, so the rejection above is the
+ // mapping talking and not `fields` having broken the query type.
+ let (status, body) = search(
+ &app,
+ json!({ "query_string": { "query": "pelicans", "fields": ["body"] } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(
+ body.pointer("/hits/total/value").and_then(Value::as_u64),
+ Some(1),
+ "{body}"
+ );
+
+ // And a pattern spec is never an error, as for the other multi-field types.
+ let (status, body) = search(
+ &app,
+ json!({ "query_string": { "query": "pelicans", "fields": ["*"] } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+}
+
+/// `_delete_by_query` refuses rather than reporting a clean zero-deletion run.
+///
+/// A write endpoint that answers `{"deleted": 0, "failures": []}` for a query
+/// it never ran is the worst shape of this bug: the caller reads it as "there
+/// was nothing to delete". Listed in the CHANGELOG, so asserted here.
+#[tokio::test]
+async fn delete_by_query_refuses_and_leaves_the_document() {
+ let (app, _dir) = app_with_mapping().await;
+
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ "/t/_delete_by_query",
+ json!({ "query": { "match": { "note": "pelicans" } } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+ assert_eq!(
+ body.pointer("/error/root_cause/0/type")
+ .and_then(Value::as_str),
+ Some("query_shard_exception"),
+ "{body}"
+ );
+ assert!(
+ body.get("deleted").is_none(),
+ "a refused delete must not publish a deletion count: {body}"
+ );
+
+ // …and the document is still there.
+ let (status, body) = get(&app, "/t/_doc/1").await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(
+ body.pointer("/_source/note").and_then(Value::as_str),
+ Some("confidential memo about pelicans"),
+ "{body}"
+ );
+}
diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rs
index 7a6200035..87af3443e 100644
--- a/engine/crates/xerj-query/src/parser.rs
+++ b/engine/crates/xerj-query/src/parser.rs
@@ -1173,10 +1173,28 @@ fn parse_query_string(params: &Value) -> Result<QueryNode> {
MAX_QUERY_STRING_LEN
)));
}
- let default_field = obj
+ let mut default_field = obj
.get("default_field")
.and_then(|v| v.as_str())
.map(str::to_string);
+ // `fields` was accepted and ignored: the key never reached this parser, so
+ // `query_string {"query":"x","fields":["title"]}` searched every field —
+ // and, once `index: false` became a real rejection, disagreed with
+ // `{"default_field":"title"}`, which is the same request written the other
+ // way. It is now read and used, the way `simple_query_string` already used
+ // its own `fields` list: an unqualified clause is searched over exactly
+ // these fields (a `^boost` suffix is honoured), while a `field:value`
+ // clause inside the string keeps naming its own field, as in ES.
+ let fields: Vec<String> = obj
+ .get("fields")
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(Value::as_str)
+ .map(str::to_string)
+ .collect()
+ })
+ .unwrap_or_default();
let default_operator = parse_bool_operator(obj.get("default_operator")).ok();
let boost = obj.get("boost").and_then(|v| v.as_f64()).map(|b| b as f32);
@@ -1185,9 +1203,14 @@ fn parse_query_string(params: &Value) -> Result<QueryNode> {
// QueryString node if lowering isn't possible (the FTS path still
// tokenizes it) — but malformed range syntax is a hard parse error,
// never a silent term-match fallback.
- if let Some(lowered) =
- try_lower_query_string(&query, default_field.as_deref(), default_operator)?
- {
+ if let Some(lowered) = try_lower_query_string(
+ &query,
+ QsFields {
+ default_field: default_field.as_deref(),
+ fields: &fields,
+ },
+ default_operator,
+ )? {
return Ok(match boost {
Some(b) if b != 1.0 => QueryNode::Boosted {
boost: b,
@@ -1197,6 +1220,16 @@ fn parse_query_string(params: &Value) -> Result<QueryNode> {
});
}
+ // Lowering declined (a string this tokenizer cannot handle, e.g. an
+ // unterminated quote): the opaque node hands the whole string to the FTS
+ // path. A one-element `fields` list means exactly what `default_field`
+ // means, so it is carried across rather than dropped. A multi-element list
+ // has no representation on this node — that residue is stated as a known
+ // gap in the CHANGELOG rather than papered over.
+ if default_field.is_none() && fields.len() == 1 {
+ default_field = Some(qs_split_boost(&fields[0]).0);
+ }
+
Ok(QueryNode::QueryString {
query,
default_field,
@@ -1205,11 +1238,89 @@ fn parse_query_string(params: &Value) -> Result<QueryNode> {
})
}
+/// Split a `fields` entry into its field name and optional `^boost`.
+///
+/// `"title^3"` → `("title", Some(3.0))`, `"title"` → `("title", None)`. A
+/// malformed suffix (`"title^x"`) keeps the whole spec as the name, which is
+/// what ES's field-spec parser does with an unparseable boost.
+fn qs_split_boost(spec: &str) -> (String, Option<f32>) {
+ match spec.rsplit_once('^') {
+ Some((name, b)) if !name.is_empty() => match b.parse::<f32>() {
+ Ok(b) if b.is_finite() => (name.to_string(), Some(b)),
+ _ => (spec.to_string(), None),
+ },
+ _ => (spec.to_string(), None),
+ }
+}
+
+/// Where a clause that named no field of its own is searched.
+///
+/// `query_string` has two ways to say this and ES treats them as the same
+/// thing: `default_field` (one field) and `fields` (a list, `^boost` allowed).
+/// An empty `fields` with no `default_field` keeps the historical `"*"`
+/// placeholder, which downstream means the field-less scan.
+#[derive(Clone, Copy)]
+struct QsFields<'a> {
+ default_field: Option<&'a str>,
+ fields: &'a [String],
+}
+
+impl QsFields<'_> {
+ /// The (field, boost) targets for an unqualified clause.
+ fn targets(&self) -> Vec<(String, Option<f32>)> {
+ if self.fields.is_empty() {
+ return vec![(self.default_field.unwrap_or("*").to_string(), None)];
+ }
+ self.fields.iter().map(|s| qs_split_boost(s)).collect()
+ }
+
+ /// Whether an unqualified *range* has a concrete field to land on. A
+ /// range needs one real field name; `"*"` is not one.
+ fn has_concrete_target(&self) -> bool {
+ if self.fields.is_empty() {
+ return matches!(self.default_field, Some(df) if !df.is_empty() && df != "*");
+ }
+ self.fields
+ .iter()
+ .any(|s| !s.is_empty() && !qs_split_boost(s).0.contains('*'))
+ }
+}
+
+/// The (field, boost) targets one query-string clause resolves to.
+///
+/// `explicit` is the `field:` prefix the clause carried, if any: ES keeps an
+/// explicitly named field whatever `fields` / `default_field` say, and only an
+/// unqualified clause fans out over them.
+fn qs_targets(explicit: &str, ctx: QsFields<'_>) -> Vec<(String, Option<f32>)> {
+ if explicit.is_empty() {
+ ctx.targets()
+ } else {
+ vec![(explicit.to_string(), None)]
+ }
+}
+
+/// Combine the per-field copies of one unqualified clause.
+///
+/// One target stays a bare leaf (the shape every existing query_string test
+/// pins); several become a `dis_max`, which is how ES combines a
+/// `query_string` over multiple fields — best field wins, no tie-breaker.
+fn qs_combine(mut nodes: Vec<QueryNode>) -> Option<QueryNode> {
+ match nodes.len() {
+ 0 => None,
+ 1 => nodes.pop(),
+ _ => Some(QueryNode::DisMax {
+ queries: nodes,
+ tie_breaker: 0.0,
+ }),
+ }
+}
+
/// Lower a Lucene-style query string into a QueryNode::Bool tree.
///
/// Supports:
/// - `field:value` → Match on that field
-/// - `value` → Match on default_field (if provided) else MultiMatch on all
+/// - `value` → Match on `default_field` / each entry of `fields` (a `dis_max`
+/// when there is more than one), else the `"*"` field-less placeholder
/// - `A OR B` → Bool.should
/// - `A AND B` → Bool.must
/// - `+A` must, `-A` must_not
@@ -1224,7 +1335,7 @@ fn parse_query_string(params: &Value) -> Result<QueryNode> {
/// ranges must never silently degrade to a term match.
fn try_lower_query_string(
q: &str,
- default_field: Option<&str>,
+ ctx: QsFields<'_>,
default_op: Option<BoolOperator>,
) -> Result<Option<QueryNode>> {
let Some(tokens) = tokenize_query_string(q)? else {
@@ -1234,14 +1345,13 @@ fn try_lower_query_string(
return Ok(None);
}
// Range clauses must target a concrete field: resolve unqualified
- // ranges against default_field up-front so `>10` with no usable
- // default errors instead of degrading to a term match.
+ // ranges against default_field / fields up-front so `>10` with no usable
+ // target errors instead of degrading to a term match.
let mut has_range = false;
for t in &tokens {
if let QsTok::Range { field, .. } = t {
has_range = true;
- if field.is_empty() && !matches!(default_field, Some(df) if !df.is_empty() && df != "*")
- {
+ if field.is_empty() && !ctx.has_concrete_target() {
return Err(qerr(
"query_string range requires an explicit field (e.g. `price:>10`) or a non-wildcard default_field",
));
@@ -1249,7 +1359,7 @@ fn try_lower_query_string(
}
}
let mut pos = 0;
- let parsed = parse_qs_or(&tokens, &mut pos, default_field, default_op);
+ let parsed = parse_qs_or(&tokens, &mut pos, ctx, default_op);
match parsed {
Some(node) if pos == tokens.len() => Ok(Some(node)),
_ if has_range => Err(qerr(format!(
@@ -1584,14 +1694,14 @@ fn tokenize_query_string(q: &str) -> Result<Option<Vec<QsTok>>> {
fn parse_qs_or(
toks: &[QsTok],
pos: &mut usize,
- default_field: Option<&str>,
+ ctx: QsFields<'_>,
default_op: Option<BoolOperator>,
) -> Option<QueryNode> {
- let mut left = parse_qs_and(toks, pos, default_field, default_op)?;
+ let mut left = parse_qs_and(toks, pos, ctx, default_op)?;
// `A OR B` — explicit OR operator.
while *pos < toks.len() && matches!(toks[*pos], QsTok::Or) {
*pos += 1;
- let right = parse_qs_and(toks, pos, default_field, default_op)?;
+ let right = parse_qs_and(toks, pos, ctx, default_op)?;
left = QueryNode::Bool {
must: vec![],
must_not: vec![],
@@ -1607,7 +1717,7 @@ fn parse_qs_or(
let implicit_or = matches!(default_op, None | Some(BoolOperator::Or));
if implicit_or {
while *pos < toks.len() && !matches!(toks[*pos], QsTok::RParen | QsTok::Or | QsTok::And) {
- let right = parse_qs_and(toks, pos, default_field, default_op)?;
+ let right = parse_qs_and(toks, pos, ctx, default_op)?;
left = QueryNode::Bool {
must: vec![],
must_not: vec![],
@@ -1623,7 +1733,7 @@ fn parse_qs_or(
fn parse_qs_and(
toks: &[QsTok],
pos: &mut usize,
- default_field: Option<&str>,
+ ctx: QsFields<'_>,
default_op: Option<BoolOperator>,
) -> Option<QueryNode> {
let mut clauses: Vec<QueryNode> = Vec::new();
@@ -1644,7 +1754,7 @@ fn parse_qs_and(
_ => break,
}
}
- let node = parse_qs_unary(toks, pos, default_field)?;
+ let node = parse_qs_unary(toks, pos, ctx)?;
if force_not {
not_clauses.push(node);
} else {
@@ -1694,11 +1804,7 @@ fn parse_qs_and(
Some(node)
}
-fn parse_qs_unary(
- toks: &[QsTok],
- pos: &mut usize,
- default_field: Option<&str>,
-) -> Option<QueryNode> {
+fn parse_qs_unary(toks: &[QsTok], pos: &mut usize, ctx: QsFields<'_>) -> Option<QueryNode> {
if *pos >= toks.len() {
return None;
}
@@ -1716,7 +1822,7 @@ fn parse_qs_unary(
// opaque `QueryNode::QueryString` path (iterative tokenizer, no
// recursion). The guard decrements on drop when this arm returns.
let _depth_guard = DepthGuard::enter().ok()?;
- let n = parse_qs_or(toks, pos, default_field, None)?;
+ let n = parse_qs_or(toks, pos, ctx, None)?;
if *pos >= toks.len() || !matches!(toks[*pos], QsTok::RParen) {
return None;
}
@@ -1725,11 +1831,10 @@ fn parse_qs_unary(
}
QsTok::Term(field, value) => {
*pos += 1;
- let f = if field.is_empty() {
- default_field.unwrap_or("*").to_string()
- } else {
- field
- };
+ // A clause that named its own field keeps it; one that did not is
+ // searched over every target `default_field` / `fields` supplies,
+ // combined by `qs_combine`.
+ let targets = qs_targets(&field, ctx);
// A bare term containing `*` or `?` is a Lucene wildcard —
// emit a Wildcard query so `q=shor*` / `q=te?t` match text
// tokens with the expected substitution semantics.
@@ -1750,36 +1855,47 @@ fn parse_qs_unary(
// `model:claude-* AND status:ok` → 1.0 + BM25(status:ok).
// `constant_score: true` also admits the keyword shape to
// the columnar Filtered plan (seq-ascending → ES tie order).
- return Some(QueryNode::Wildcard {
- field: f,
- value: value.to_lowercase(),
- boost: None,
- constant_score: true,
- });
+ let lowered = value.to_lowercase();
+ return qs_combine(
+ targets
+ .into_iter()
+ .map(|(f, boost)| QueryNode::Wildcard {
+ field: f,
+ value: lowered.clone(),
+ boost,
+ constant_score: true,
+ })
+ .collect(),
+ );
}
- Some(QueryNode::Match {
- field: f,
- query: value,
- operator: BoolOperator::Or,
- analyzer: None,
- boost: None,
- minimum_should_match: None,
- })
+ qs_combine(
+ targets
+ .into_iter()
+ .map(|(f, boost)| QueryNode::Match {
+ field: f,
+ query: value.clone(),
+ operator: BoolOperator::Or,
+ analyzer: None,
+ boost,
+ minimum_should_match: None,
+ })
+ .collect(),
+ )
}
QsTok::Phrase(field, value) => {
*pos += 1;
- let f = if field.is_empty() {
- default_field.unwrap_or("*").to_string()
- } else {
- field
- };
- Some(QueryNode::MatchPhrase {
- field: f,
- query: value,
- slop: 0,
- analyzer: None,
- boost: None,
- })
+ qs_combine(
+ qs_targets(&field, ctx)
+ .into_iter()
+ .map(|(f, boost)| QueryNode::MatchPhrase {
+ field: f,
+ query: value.clone(),
+ slop: 0,
+ analyzer: None,
+ boost,
+ })
+ .collect(),
+ )
}
QsTok::Range {
field,
@@ -1789,21 +1905,27 @@ fn parse_qs_unary(
lte,
} => {
*pos += 1;
- // Unqualified ranges with no usable default_field were already
- // rejected in try_lower_query_string.
- let f = if field.is_empty() {
- default_field.unwrap_or("*").to_string()
- } else {
- field
- };
- Some(QueryNode::Range {
- field: f,
- gte,
- gt,
- lte,
- lt,
- boost: None,
- })
+ // Unqualified ranges with no usable target were already rejected
+ // in try_lower_query_string. A pattern entry in `fields` has no
+ // meaning for a range, so those targets are dropped here rather
+ // than turned into a `Range` on the literal field name `"*"`.
+ let targets: Vec<(String, Option<f32>)> = qs_targets(&field, ctx)
+ .into_iter()
+ .filter(|(f, _)| !field.is_empty() || !f.contains('*'))
+ .collect();
+ qs_combine(
+ targets
+ .into_iter()
+ .map(|(f, boost)| QueryNode::Range {
+ field: f,
+ gte: gte.clone(),
+ gt: gt.clone(),
+ lte: lte.clone(),
+ lt: lt.clone(),
+ boost,
+ })
+ .collect(),
+ )
}
_ => None,
}
@@ -4731,6 +4853,70 @@ mod tests {
assert_eq!(lte, Some(json!(5)));
}
+ /// `query_string`'s `fields` was accepted and ignored — the key never
+ /// reached this parser, so the query ran over every field regardless. It
+ /// now selects the targets for an unqualified clause, the same way
+ /// `simple_query_string`'s `fields` already did.
+ #[test]
+ fn test_query_string_fields_select_the_unqualified_targets() {
+ // One field is exactly `default_field`.
+ match q(json!({"query_string": {"query": "hello", "fields": ["title"]}})) {
+ QueryNode::Match { field, query, .. } => {
+ assert_eq!(field, "title");
+ assert_eq!(query, "hello");
+ }
+ other => panic!("expected Match on title, got {other:?}"),
+ }
+
+ // Several become a dis_max over one leaf per field, and `^boost` on a
+ // spec lands on that leaf.
+ match q(json!({"query_string": {"query": "hello", "fields": ["title^3", "body"]}})) {
+ QueryNode::DisMax { queries, .. } => {
+ assert_eq!(queries.len(), 2);
+ match &queries[0] {
+ QueryNode::Match { field, boost, .. } => {
+ assert_eq!(field, "title");
+ assert_eq!(*boost, Some(3.0));
+ }
+ other => panic!("expected boosted Match on title, got {other:?}"),
+ }
+ match &queries[1] {
+ QueryNode::Match { field, boost, .. } => {
+ assert_eq!(field, "body");
+ assert_eq!(*boost, None);
+ }
+ other => panic!("expected Match on body, got {other:?}"),
+ }
+ }
+ other => panic!("expected DisMax, got {other:?}"),
+ }
+
+ // A clause that names its own field keeps it: `fields` only supplies
+ // the target for clauses that named none, as in ES.
+ match q(json!({"query_string": {"query": "body:hello", "fields": ["title"]}})) {
+ QueryNode::Match { field, .. } => assert_eq!(field, "body"),
+ other => panic!("expected Match on body, got {other:?}"),
+ }
+
+ // With no `fields` and no `default_field` nothing changes: the
+ // field-less `"*"` placeholder is still what an unqualified clause
+ // resolves to.
+ match qs("hello") {
+ QueryNode::Match { field, .. } => assert_eq!(field, "*"),
+ other => panic!("expected Match on *, got {other:?}"),
+ }
+
+ // An unqualified range now resolves against `fields` too, instead of
+ // erroring for want of a `default_field`.
+ match q(json!({"query_string": {"query": ">10", "fields": ["n"]}})) {
+ QueryNode::Range { field, gt, .. } => {
+ assert_eq!(field, "n");
+ assert_eq!(gt, Some(json!(10)));
+ }
+ other => panic!("expected Range on n, got {other:?}"),
+ }
+ }
+
#[test]
fn test_query_string_range_inclusive_brackets() {
let (field, gt, gte, lt, lte) = expect_range(qs("n:[2 TO 5]"));