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(api): _validate/query consults the mapping, matching _search (#1284, #204) (#2263)
ordinary beingf88a16abd3f0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7450ae79b..27fdbd1bb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,6 +30,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0unrecorded with the journal kept, instead of a ledger that names no build([#2239](https://github.com/xerj-org/xerj/issues/2239)).+- `_validate/query` now asks every resolved index the same buildability+ question `_search` does: a query naming a field that is neither indexed nor+ has doc values, or a non-numeric value against a numeric field, reports+ `valid: false` (with `error`/`explanations`) instead of claiming a body+ `_search` rejects is valid. The parse-only answer is kept for a selector+ that resolves to no index.+- A `semantic` query on a `semantic_text` field returns `highlight` fragmentswhen the request asks for them (#1947). The fragments are the field'sbest-scoring chunks for the query embedding, in score order, limited bydiff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex a9f3f2d97..1fab49078 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -19498,7 +19498,7 @@ pub struct ValidateQueryParams {}pub async fn validate_query(- State(_state): State<AppState>,+ State(state): State<AppState>,Path(index): Path<String>,Query(params): Query<ValidateQueryParams>,body: OptionalJson<Value>,@@ -19520,17 +19520,63 @@ pub async fn validate_query(match xerj_query::parse_request(&query_doc) {Ok(req) => {+ // Parsing is only half the answer: `_search` also rewrites aliases,+ // lowers keyword full-text to term, and rejects unsearchable fields+ // and non-numeric values against numeric fields while it builds the+ // query. Ask every resolved index the same question so this+ // endpoint cannot report `valid: true` for a body `_search` refuses+ // (the "GAP 5" this endpoint used to carry).+ let targets = resolve_index_selector(&state, &index).await;+ let mut successful = 0u64;+ let mut first_error: Option<String> = None;+ let mut explanations = Vec::new();+ for name in &targets {+ let outcome = match state.engine.get_index(name) {+ // A target the selector named but the engine does not hold+ // stays on the parse-only answer, as before.+ Ok(idx) => idx+ .validate_query(&req.query)+ .await+ .map_err(|e| e.to_string()),+ Err(_) => Ok(()),+ };+ match outcome {+ Ok(()) => {+ successful += 1;+ if explain {+ explanations.push(json!({+ "index": name,+ "valid": true,+ "explanation": format!("{:?}", req.query),+ }));+ }+ }+ Err(error) => {+ if first_error.is_none() {+ first_error = Some(error.clone());+ }+ if explain {+ explanations.push(json!({+ "index": name,+ "valid": false,+ "error": error,+ }));+ }+ }+ }+ }+ let total = targets.len() as u64;+ let failed = total.saturating_sub(successful);let mut resp = json!({- "_shards": { "total": 1, "successful": 1, "failed": 0 },- "valid": true,+ "_shards": { "total": total, "successful": successful, "failed": failed },+ "valid": failed == 0,"_index": index,});+ if let Some(error) = first_error {+ resp["error"] = json!(error);+ }if explain {- resp["explanations"] = json!([{- "index": index,- "valid": true,- "explanation": format!("{:?}", req.query),- }]);+ resp["explanations"] = json!(explanations);}Json(resp).into_response()}diff --git a/engine/crates/xerj-api/tests/index_false_is_honoured.rs b/engine/crates/xerj-api/tests/index_false_is_honoured.rsindex 32e59f6fd..783aec107 100644--- a/engine/crates/xerj-api/tests/index_false_is_honoured.rs+++ b/engine/crates/xerj-api/tests/index_false_is_honoured.rs@@ -681,10 +681,9 @@ async fn documented_gaps_are_still_open_and_still_documented() {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.+ // GAP 5 CLOSED — `_validate/query` now asks every resolved index the same+ // buildability question `_search` asks, so it no longer says a query+ // `_search` refuses is valid.let (status, body) = json_req(&app,"POST",@@ -692,12 +691,40 @@ async fn documented_gaps_are_still_open_and_still_documented() {json!({ "query": { "match": { "note": "pelicans" } } }),).await;- assert_eq!(status, StatusCode::OK, "GAP 5 changed: {body}");+ assert_eq!(status, StatusCode::OK, "{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}"+ Some(false),+ "GAP 5 closed: {body}"+ );+ let reason = body+ .get("error")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ reason.contains("Cannot search on field [note]"),+ "got {reason:?}: {body}"+ );++ // `explain=true` reports the refusal per index instead of one top-level+ // sentence.+ let (status, body) = json_req(+ &app,+ "POST",+ "/t/_validate/query?explain=true",+ json!({ "query": { "match": { "note": "pelicans" } } }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["valid"], false, "{body}");+ assert_eq!(body["explanations"][0]["index"], "t");+ assert_eq!(body["explanations"][0]["valid"], false);+ assert!(+ body["explanations"][0]["error"]+ .as_str()+ .unwrap_or_default()+ .contains("Cannot search on field [note]"),+ "{body}");}diff --git a/engine/crates/xerj-api/tests/validate_query_matches_search.rs b/engine/crates/xerj-api/tests/validate_query_matches_search.rsnew file mode 100644index 000000000..68784711e--- /dev/null+++ b/engine/crates/xerj-api/tests/validate_query_matches_search.rs@@ -0,0 +1,163 @@+//! `_validate/query` must answer the same "will this build?" question as+//! `_search`.+//!+//! It used to parse the body and never open the index, so a query naming an+//! unsearchable field or a non-numeric value on a numeric field was reported+//! `valid: true` and then 400ed at search time (the "GAP 5" recorded in+//! `index_false_is_honoured.rs`). Both surfaces now call+//! `Index::validate_query`, which runs the same+//! `check_buildable_query` the search path builds with: alias and+//! keyword-full-text rewrites, then the unsearchable-field (#204) and+//! non-numeric-value (#1284) checks.+//!+//! Elasticsearch is referenced for semantics only. It is AGPL-3.0/SSPL-1.0/+//! Elastic-2.0 licensed and no code from it is reproduced here.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++async fn app() -> (axum::Router, tempfile::TempDir) {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ (xerj_api::router::build_es_compat_router(state), dir)+}++async fn json_req(+ app: &axum::Router,+ method: &str,+ path: &str,+ body: Value,+) -> (StatusCode, Value) {+ let response = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request"),+ )+ .await+ .expect("response");+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .expect("body");+ (+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ )+}++async fn validate(app: &axum::Router, query: Value) -> (StatusCode, Value) {+ json_req(+ app,+ "POST",+ "/vq/_validate/query",+ json!({ "query": query }),+ )+ .await+}++/// The refusal sentence from either response shape: a validate body carries+/// `error` as a string, a search body carries `error.root_cause[0].reason`.+fn refusal(body: &Value) -> &str {+ body.pointer("/error/root_cause/0/reason")+ .and_then(Value::as_str)+ .or_else(|| body.get("error").and_then(Value::as_str))+ .unwrap_or_default()+}++#[tokio::test]+async fn validate_query_matches_search_for_schema_refusals() {+ let (app, _dir) = app().await;+ let (status, body) = json_req(+ &app,+ "PUT",+ "/vq",+ json!({+ "mappings": { "properties": {+ "n": { "type": "integer" },+ "note": { "type": "text", "index": false },+ "body": { "type": "text" }+ }}+ }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let (status, body) = json_req(+ &app,+ "PUT",+ "/vq/_doc/1",+ json!({"n": 1, "body": "pelicans", "note": "hidden"}),+ )+ .await;+ assert!(status.is_success(), "{body}");++ for (name, query, needle) in [+ (+ "term on an integer with a string",+ json!({"term": {"n": "abc"}}),+ "For input string",+ ),+ (+ "range on an integer with a string bound",+ json!({"range": {"n": {"gte": "abc"}}}),+ "For input string",+ ),+ (+ "match on an unsearchable text field",+ json!({"match": {"note": "pelicans"}}),+ "Cannot search on field [note]",+ ),+ ] {+ let (status, body) = validate(&app, query.clone()).await;+ assert_eq!(status, StatusCode::OK, "{name}: {body}");+ assert_eq!(body["valid"].as_bool(), Some(false), "{name}: {body}");+ assert!(refusal(&body).contains(needle), "{name}: {body}");++ let (status, body) = json_req(&app, "POST", "/vq/_search", json!({ "query": query })).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{name}: {body}");+ assert!(refusal(&body).contains(needle), "{name} search: {body}");+ }++ for query in [+ json!({"term": {"n": 1}}),+ json!({"match": {"body": "pelicans"}}),+ ] {+ let (status, body) = validate(&app, query.clone()).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["valid"].as_bool(), Some(true), "{body}");+ let (status, body) = json_req(&app, "POST", "/vq/_search", json!({ "query": query })).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ }++ // `explain=true` names the refusing index instead of one top-level+ // sentence, so a mixed multi-index validation is actionable.+ let (status, body) = json_req(+ &app,+ "POST",+ "/vq/_validate/query?explain=true",+ json!({"query": {"term": {"n": "abc"}}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["valid"].as_bool(), Some(false), "{body}");+ assert_eq!(body["explanations"][0]["index"], "vq");+ assert_eq!(body["explanations"][0]["valid"].as_bool(), Some(false));+ assert!(+ body["explanations"][0]["error"]+ .as_str()+ .unwrap_or_default()+ .contains("For input string"),+ "{body}"+ );+}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex c9fd8ba59..ec03572ea 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -20929,6 +20929,19 @@ impl Index {}}+ /// Validate a query exactly as [`Index::search`] will build it, without+ /// executing it. One definition of "buildable": the alias and+ /// keyword-full-text rewrites, then the unsearchable-field (#204) and+ /// non-numeric-value (#1284) checks. `_validate/query` uses this so its+ /// `valid` flag cannot disagree with `_search` on the same body.+ pub async fn validate_query(+ &self,+ query: &QueryNode,+ ) -> std::result::Result<(), xerj_common::XerjError> {+ let schema = self.schema.read().await;+ check_buildable_query(query, &schema.schema).map(|_| ())+ }+/// Inner search implementation (without timeout wrapper).async fn search_inner(&self,@@ -21053,26 +21066,11 @@ impl Index {// from `_source` (#204 — accepted means honoured).let resolved_query = {let schema = self.schema.read().await;- let resolved = rewrite_keyword_full_text_to_term(- &rewrite_query_aliases(&request.query, &schema.schema),- &schema.schema,- );- if let Some(field) = unsearchable_query_field(&resolved, &schema.schema) {- return Err(EngineError::Common(xerj_common::XerjError::invalid_query(- format!(- "failed to create query: Cannot search on field [{field}] \- since it is not indexed nor has doc values."- ),- )));- }- // #1284: a non-numeric value against a numeric field is a query- // that cannot be built, and ES fails it (`query_shard_exception` /- // `number_format_exception`) rather than answering a 0-hit.- if let Some(value) = non_numeric_term_value(&resolved, &schema.schema) {- return Err(EngineError::Common(xerj_common::XerjError::invalid_query(- format!("failed to create query: For input string: \"{value}\""),- )));- }+ // One definition of "buildable" (alias/keyword rewrites + the+ // unsearchable-field and #1284 numeric checks), shared with+ // `_validate/query`; see `check_buildable_query`.+ let resolved = check_buildable_query(&request.query, &schema.schema)+ .map_err(EngineError::Common)?;// #437: a sort field this engine cannot resolve (any of 11 ES// meta-field names besides the ones handled below, or an// unmapped/misspelled field) fell through to `_source` lookup@@ -43235,6 +43233,37 @@ fn has_analyzed_text_term_leaf(q: &QueryNode, schema: &Schema) -> bool {/// The first field in `q` that the mapping has made completely unsearchable.///+/// The schema checks that make a query unbuildable, shared by `search` and+/// `_validate/query`. Applies the same two rewrites execution does (field+/// aliases, then keyword full-text → term) before checking:+///+/// - a field declared `"index": false` with no doc values has neither postings+/// nor a column to scan, so ES rejects the query (#204);+/// - a non-numeric value against a numeric field cannot be built (#1284).+///+/// Returns the rewritten tree `search` should execute, or the same error+/// `_search` would return. `_validate/query` calls this through+/// [`Index::validate_query`]; before that it answered from the parse alone and+/// reported `valid: true` for a body `_search` refused.+fn check_buildable_query(+ query: &QueryNode,+ schema: &Schema,+) -> std::result::Result<QueryNode, xerj_common::XerjError> {+ let resolved = rewrite_keyword_full_text_to_term(&rewrite_query_aliases(query, schema), schema);+ if let Some(field) = unsearchable_query_field(&resolved, schema) {+ return Err(xerj_common::XerjError::invalid_query(format!(+ "failed to create query: Cannot search on field [{field}] \+ since it is not indexed nor has doc values."+ )));+ }+ if let Some(value) = non_numeric_term_value(&resolved, schema) {+ return Err(xerj_common::XerjError::invalid_query(format!(+ "failed to create query: For input string: \"{value}\""+ )));+ }+ Ok(resolved)+}+/// A field is unsearchable when its mapping declares BOTH `"index": false`/// (no postings) and no doc values (nothing to scan instead) — for example/// `{"type": "text", "index": false}`, since `text` has no doc values by@@ -43310,12 +43339,9 @@ fn has_analyzed_text_term_leaf(q: &QueryNode, schema: &Schema) -> bool {/// which it raises whether or not `index: false` was declared — a wider/// divergence than this change, and one this error message would misreport.///-/// And one surface never reaches this function at all: `_validate/query`-/// (`xerj-api/src/es_compat.rs::validate_query`) answers from the parse alone-/// and never opens the index, so it still reports `{"valid": true}` for a body-/// `_search` refuses. That is its behaviour on `main` too — this change did-/// not alter it — but it now disagrees with `_search`, so it is written down-/// here and in the CHANGELOG instead of being left to surprise someone.+/// `_validate/query` reaches this check through [`check_buildable_query`]+/// (via `Index::validate_query`), so its `valid` flag is the same answer+/// `_search` gives for the same body.fn unsearchable_query_field(q: &QueryNode, schema: &Schema) -> Option<String> {let check = |field: &str| -> Option<String> {let fc = declared_field(schema, field)?;