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(engine): non-numeric term/terms/range value on a numeric field is a 400 (#1284, part 1)

Vincenzo Lombardodb0e74c37903
diff --git a/engine/crates/xerj-api/tests/non_numeric_value_on_numeric_field_400s.rs b/engine/crates/xerj-api/tests/non_numeric_value_on_numeric_field_400s.rs
new file mode 100644
index 000000000..f68d83364
--- /dev/null
+++ b/engine/crates/xerj-api/tests/non_numeric_value_on_numeric_field_400s.rs
@@ -0,0 +1,156 @@
+//! Issue #1284 (term-level part): a string that is not a number, sent by a
+//! `term` / `terms` / `range` clause to a numeric field, is a query ES cannot
+//! build. ES 8.13.4 answers 400 with root cause `failed to create query: For
+//! input string: "abc"` (`query_shard_exception` / `number_format_exception`).
+//! XERJ answered 200 with 0 hits, so a type error looked like an empty result.
+//!
+//! Elasticsearch is referenced for wire semantics only; no ES code 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 send(
+ app: &axum::Router,
+ method: &str,
+ path: &str,
+ ctype: &str,
+ body: String,
+) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(path);
+ if !body.is_empty() {
+ req = req.header("content-type", ctype);
+ }
+ let response = app
+ .clone()
+ .oneshot(req.body(Body::from(body)).unwrap())
+ .await
+ .unwrap();
+ let status = response.status();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (
+ status,
+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),
+ )
+}
+
+async fn seeded() -> (axum::Router, tempfile::TempDir) {
+ let (app, dir) = app().await;
+ let (st, body) = send(
+ &app,
+ "PUT",
+ "/t84",
+ "application/json",
+ json!({"mappings": {"properties": {
+ "bytes": {"type": "long"},
+ "ms": {"type": "float"},
+ "h": {"type": "keyword"},
+ "msg": {"type": "text"}
+ }}})
+ .to_string(),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "create index: {body}");
+ let (st, body) = send(
+ &app,
+ "PUT",
+ "/t84/_doc/1?refresh=true",
+ "application/json",
+ json!({"bytes": 1, "ms": 1.5, "h": "a", "msg": "hello"}).to_string(),
+ )
+ .await;
+ assert_eq!(st, StatusCode::CREATED, "index doc: {body}");
+ (app, dir)
+}
+
+async fn count(app: &axum::Router, query: Value) -> (StatusCode, Value) {
+ send(
+ app,
+ "POST",
+ "/t84/_count",
+ "application/json",
+ json!({ "query": query }).to_string(),
+ )
+ .await
+}
+
+/// Every shape here returned 400 on ES 8.13.4 with this exact reason.
+#[tokio::test]
+async fn non_numeric_term_level_values_are_a_400() {
+ let (app, _dir) = seeded().await;
+ for query in [
+ json!({"term": {"bytes": "abc"}}),
+ json!({"term": {"bytes": {"value": "abc"}}}),
+ json!({"terms": {"bytes": ["1", "abc"]}}),
+ json!({"range": {"bytes": {"gte": "abc"}}}),
+ json!({"term": {"ms": "abc"}}),
+ json!({"bool": {"filter": [{"term": {"bytes": "abc"}}]}}),
+ ] {
+ for path in ["/t84/_count", "/t84/_search"] {
+ let (st, resp) = send(
+ &app,
+ "POST",
+ path,
+ "application/json",
+ json!({ "query": query }).to_string(),
+ )
+ .await;
+ assert_eq!(st, StatusCode::BAD_REQUEST, "{path} {query}: {resp}");
+ assert!(
+ resp.to_string()
+ .contains(r#"failed to create query: For input string: \"abc\""#),
+ "{path} {query}: reason must name the bad value: {resp}"
+ );
+ }
+ }
+}
+
+/// Valid queries that ES answers 200 must keep answering 200.
+#[tokio::test]
+async fn numeric_strings_and_non_numeric_fields_stay_valid() {
+ let (app, _dir) = seeded().await;
+ for (query, hits) in [
+ (json!({"term": {"bytes": "1"}}), 1),
+ (json!({"term": {"bytes": 1}}), 1),
+ // ES: a decimal against a long is a valid query that matches nothing.
+ (json!({"term": {"bytes": "1.5"}}), 0),
+ (json!({"range": {"bytes": {"gte": "0", "lte": "5"}}}), 1),
+ (json!({"term": {"h": "abc"}}), 0),
+ // `query_string` without `lenient`: 200 on ES 8.13.4 too.
+ (json!({"query_string": {"query": "bytes:abc"}}), 0),
+ ] {
+ let (st, resp) = count(&app, query.clone()).await;
+ assert_eq!(st, StatusCode::OK, "{query}: {resp}");
+ assert_eq!(resp["count"], json!(hits), "{query}: {resp}");
+ }
+}
+
+/// `_msearch` fails only the offending item.
+#[tokio::test]
+async fn non_numeric_value_fails_only_that_msearch_item() {
+ let (app, _dir) = seeded().await;
+ let ndjson = "{\"index\":\"t84\"}\n{\"query\":{\"term\":{\"bytes\":\"abc\"}}}\n\
+ {\"index\":\"t84\"}\n{\"query\":{\"term\":{\"bytes\":\"1\"}}}\n"
+ .to_string();
+ let (st, resp) = send(&app, "POST", "/_msearch", "application/x-ndjson", ndjson).await;
+ assert_eq!(st, StatusCode::OK, "{resp}");
+ let items = resp["responses"].as_array().expect("responses");
+ assert_eq!(items[0]["status"], 400, "bad item: {resp}");
+ assert_eq!(items[1]["status"], 200, "good item still runs: {resp}");
+ assert_eq!(items[1]["hits"]["total"]["value"], 1, "{resp}");
+}
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index a61f96e5b..669e6b127 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -20203,6 +20203,14 @@ impl Index {
),
)));
}
+ // #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}\""),
+ )));
+ }
// #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
@@ -41254,6 +41262,70 @@ fn unsearchable_query_field(q: &QueryNode, schema: &Schema) -> Option<String> {
}
}
+/// The first string value a `term` / `terms` / `range` clause sends to a
+/// numeric (`long` / `double`) field that does not parse as a number (#1284).
+///
+/// ES 8.13.4 answers every one of these with a 400 whose root cause reads
+/// `failed to create query: For input string: "abc"`, top-level or under
+/// `bool.filter`; XERJ answered a silent 0-hit 200, so a type error in a
+/// dashboard query looked like an empty result. These clause types have no
+/// `lenient` option in ES, so there is nothing to honour here. A decimal
+/// against a `long` (`"1.5"`) is a valid query that matches nothing on ES, so
+/// only an unparseable string is rejected. `match` / `multi_match` /
+/// `query_string` are left alone: they DO take `lenient`, which the AST does
+/// not carry yet.
+fn non_numeric_term_value(q: &QueryNode, schema: &Schema) -> Option<String> {
+ let numeric = |field: &str| {
+ declared_field(schema, field)
+ .is_some_and(|fc| matches!(fc.field_type, FieldType::Long | FieldType::Double))
+ };
+ let bad = |v: &serde_json::Value| -> Option<String> {
+ let s = v.as_str()?;
+ s.trim().parse::<f64>().is_err().then(|| s.to_string())
+ };
+ match q {
+ QueryNode::Term { field, value, .. } if numeric(field) => bad(value),
+ QueryNode::Terms { field, values, .. } if numeric(field) => values.iter().find_map(bad),
+ QueryNode::Range {
+ field,
+ gte,
+ gt,
+ lte,
+ lt,
+ ..
+ } if numeric(field) => [gte, gt, lte, lt].into_iter().flatten().find_map(bad),
+ QueryNode::Bool {
+ must,
+ should,
+ must_not,
+ filter,
+ ..
+ } => must
+ .iter()
+ .chain(should)
+ .chain(must_not)
+ .chain(filter)
+ .find_map(|c| non_numeric_term_value(c, schema)),
+ QueryNode::Constant { query, .. }
+ | QueryNode::Boosted { query, .. }
+ | QueryNode::Named { query, .. }
+ | QueryNode::Nested { query, .. }
+ | QueryNode::FunctionScore { query, .. } => non_numeric_term_value(query, schema),
+ QueryNode::Pinned { organic, .. } => non_numeric_term_value(organic, schema),
+ QueryNode::Boosting {
+ positive, negative, ..
+ } => non_numeric_term_value(positive, schema)
+ .or_else(|| non_numeric_term_value(negative, schema)),
+ QueryNode::DisMax { queries, .. } => queries
+ .iter()
+ .find_map(|c| non_numeric_term_value(c, schema)),
+ QueryNode::Knn { filter, .. } | QueryNode::SemanticSearch { filter, .. } => filter
+ .as_ref()
+ .and_then(|f| non_numeric_term_value(f, schema)),
+ _ => None,
+ }
+}
+
/// Lower every LEXICAL clause that names a lexically typeless field to
/// `QueryNode::MatchNone` — the query half of #328.
///
diff --git a/engine/tests/es-compat-yaml/yaml/search/720_non_numeric_term_value.yml b/engine/tests/es-compat-yaml/yaml/search/720_non_numeric_term_value.yml
new file mode 100644
index 000000000..4d18dea74
--- /dev/null
+++ b/engine/tests/es-compat-yaml/yaml/search/720_non_numeric_term_value.yml
@@ -0,0 +1,49 @@
+setup:
+ - do:
+ indices.create:
+ index: non_numeric_term
+ body:
+ mappings:
+ properties:
+ bytes:
+ type: long
+ h:
+ type: keyword
+ - do:
+ bulk:
+ refresh: true
+ body:
+ - '{"index": {"_index": "non_numeric_term", "_id": "1"}}'
+ - '{"bytes": 1, "h": "a"}'
+
+---
+"non-numeric term-level value on a numeric field is a 400 (#1284)":
+ - do:
+ catch: bad_request
+ search:
+ index: non_numeric_term
+ body: { query: { term: { bytes: "abc" } } }
+ # This runner records a `catch` response without checking its status, so
+ # the 400 is asserted on the body (`status` is in ES's error envelope).
+ - match: { status: 400 }
+
+ - do:
+ catch: bad_request
+ search:
+ index: non_numeric_term
+ body: { query: { bool: { filter: [ { range: { bytes: { gte: "abc" } } } ] } } }
+ - match: { status: 400 }
+
+---
+"numeric strings and non-numeric fields stay valid (#1284)":
+ - do:
+ search:
+ index: non_numeric_term
+ body: { query: { term: { bytes: "1" } } }
+ - match: { hits.total.value: 1 }
+
+ - do:
+ search:
+ index: non_numeric_term
+ body: { query: { term: { h: "abc" } } }
+ - match: { hits.total.value: 0 }