Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(search): reject sort on an unresolvable field instead of null-stranding search_after (#437)

Vincenzo Lombardo406aa6856d0c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b7f1b4fc3..acb0ce8fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,51 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **`sort` on a field XERJ cannot resolve returned `null` on every hit
+ instead of an error** ([#437](https://github.com/xerj-org/xerj/issues/437)).
+ `compute_sort_values` special-cased `_score`, `_doc`, `_id` and the four
+ meta-fields [#420](https://github.com/xerj-org/xerj/pull/420) made
+ resolvable (`_seq_no`, `_version`, `_primary_term`, `_index`); every other
+ ES meta-field name (`_source`, `_size`, `_doc_count`, `_field_names`,
+ `_meta`, `_tier`, `_nested`, `_nested_path`, `_feature`, `_parent`,
+ `_matched_queries`) and any unmapped or misspelled field fell through to a
+ plain `_source` lookup that returned `Null` when absent. The whole result
+ set tied on `[null]`, HTTP 200, and `search_after` paging on that field
+ was stranded at page one with no error anywhere — the same
+ silently-truncated-export failure mode
+ [#198](https://github.com/xerj-org/xerj/issues/198) closes for scroll,
+ reached through `sort` instead.
+
+ A prior attempt, [#402](https://github.com/xerj-org/xerj/pull/402), tried
+ a request-level denylist of "known-unresolvable" field names and was
+ closed after independent verification refuted it: XERJ deliberately
+ accepts a metadata-named key inside a document body (`{"_seq_no": 1}`,
+ where real Elasticsearch rejects it — see #420's entry above), so whether
+ a name resolves is a property of the *corpus* being searched, not of the
+ field name, and a static list is guaranteed wrong on some corpus. #402
+ was also wired into `_search` only, leaving `_msearch`,
+ `_search/template` and `_async_search` answering the identical
+ "unresolvable" field with 200.
+
+ This fix checks the index's **schema** instead of the corpus — the same
+ thing real Elasticsearch validates — with a single gate inside the
+ engine's `search_inner`, which every search entry point funnels through
+ regardless of endpoint. A sort field that is not one of the seven
+ already-resolvable special cases and is not declared in the schema (via
+ the same recursive dotted-path resolution already used for `.keyword`
+ multi-fields and nested/object properties) is now rejected up front with
+ Elasticsearch's real error: a 400 `search_phase_execution_exception`
+ wrapping `query_shard_exception`, reason `"No mapping found for [x] in
+ order to sort on"`.
+
+ **Known gap, not closed here:** `collapse.inner_hits.sort` and
+ aggregation `top_hits.sort` implement their own sorting independently of
+ `compute_sort_values` and are not covered by this gate — an unresolvable
+ field named in either still sorts silently wrong rather than erroring.
+ Tracked as a follow-up.
+
## [1.0.0-rc.18] - 2026-08-18
### Security
diff --git a/engine/crates/xerj-api/src/error.rs b/engine/crates/xerj-api/src/error.rs
index 7955af186..e6f72735f 100644
--- a/engine/crates/xerj-api/src/error.rs
+++ b/engine/crates/xerj-api/src/error.rs
@@ -194,6 +194,12 @@ impl ApiError {
rt.to_string()
} else if reason.starts_with("failed to create query:") {
"query_shard_exception".to_string()
+ } else if reason.starts_with("No mapping found for") {
+ // #437: a sort field with no mapping is a shard-level query-
+ // build failure in real ES too, wrapped the same way as
+ // `failed to create query:` above — `query_shard_exception`
+ // in root_cause, outer wrapper unchanged.
+ "query_shard_exception".to_string()
} else if reason.starts_with("function score query returned an invalid score:") {
// ES validates function_score results and raises
// `illegal_argument_exception` with a 400 status when a
diff --git a/engine/crates/xerj-api/tests/sort_on_unresolvable_field_http.rs b/engine/crates/xerj-api/tests/sort_on_unresolvable_field_http.rs
new file mode 100644
index 000000000..bc5ecce4f
--- /dev/null
+++ b/engine/crates/xerj-api/tests/sort_on_unresolvable_field_http.rs
@@ -0,0 +1,312 @@
+//! Issue #437, from the outside: sorting on a field the engine cannot
+//! resolve must be rejected with ES's real error shape, on every HTTP entry
+//! point that accepts a `sort` clause — not just `_search`.
+//!
+//! Issue #402's request-level denylist only ever reached `search_impl`, and
+//! its own review caught `_msearch`/`_search/template`/`_async_search`
+//! answering 200 on the same "unresolvable" field name it rejected on
+//! `_search`. This suite proves the engine-level fix (a single gate inside
+//! `search_inner`, which every one of these handlers funnels through) closes
+//! that gap structurally rather than needing each endpoint wired in by hand.
+
+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, req: Request<Body>) -> (StatusCode, Value) {
+ let response = app.clone().oneshot(req).await.expect("response");
+ let status = response.status();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("body");
+ let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
+ (status, value)
+}
+
+async fn seed(app: &axum::Router, index: &str, n: u64) {
+ let mut ndjson = String::new();
+ for i in 0..n {
+ ndjson.push_str(&format!(
+ "{{\"index\":{{\"_id\":\"{i}\"}}}}\n{{\"n\":{i}}}\n"
+ ));
+ }
+ let (st, body) = send(
+ app,
+ Request::builder()
+ .method("POST")
+ .uri(format!("/{index}/_bulk"))
+ .header("content-type", "application/x-ndjson")
+ .body(Body::from(ndjson))
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "bulk {index}: {body}");
+ let (st, body) = send(
+ app,
+ Request::builder()
+ .method("POST")
+ .uri(format!("/{index}/_refresh"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "refresh {index}: {body}");
+}
+
+/// The real ES envelope: `search_phase_execution_exception`/400 wrapping
+/// `query_shard_exception` in `root_cause`, reason naming the field.
+fn assert_no_mapping_found_error(status: StatusCode, body: &Value, field: &str) {
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "sort on unresolvable field [{field}] must be a 400, not silently answered: {body}"
+ );
+ assert_eq!(
+ body["error"]["type"], "search_phase_execution_exception",
+ "wrong outer error type for [{field}]: {body}"
+ );
+ assert_eq!(
+ body["error"]["root_cause"][0]["type"], "query_shard_exception",
+ "wrong root_cause type for [{field}]: {body}"
+ );
+ let reason = body["error"]["reason"].as_str().unwrap_or_default();
+ assert!(
+ reason.contains(&format!("No mapping found for [{field}]")),
+ "reason for [{field}] doesn't name the field: {reason}"
+ );
+ assert_eq!(
+ body["status"], 400,
+ "wrong top-level status for [{field}]: {body}"
+ );
+}
+
+#[tokio::test]
+async fn search_rejects_sort_on_every_unresolvable_meta_field_and_a_typo() {
+ let (app, _dir) = app().await;
+ seed(&app, "census", 4).await;
+
+ const FIELDS: &[&str] = &[
+ "_source",
+ "_size",
+ "_doc_count",
+ "_field_names",
+ "_meta",
+ "_tier",
+ "_nested",
+ "_nested_path",
+ "_feature",
+ "_parent",
+ "_matched_queries",
+ "not_a_field_at_all",
+ ];
+ for field in FIELDS {
+ let (status, body) = send(
+ &app,
+ Request::builder()
+ .method("POST")
+ .uri("/census/_search")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({"query": {"match_all": {}}, "sort": [{*field: "asc"}]}).to_string(),
+ ))
+ .unwrap(),
+ )
+ .await;
+ assert_no_mapping_found_error(status, &body, field);
+ }
+}
+
+/// The actual user-visible harm the issue is about: `search_after` paging
+/// on an unresolvable field silently stops at page one instead of erroring.
+/// A mapped field (control) must keep walking the whole corpus.
+#[tokio::test]
+async fn search_after_is_rejected_up_front_instead_of_stranded_at_page_one() {
+ let (app, _dir) = app().await;
+ seed(&app, "strand", 6).await;
+
+ // Control: search_after on a real field walks the whole corpus.
+ let (status, page1) = send(
+ &app,
+ Request::builder()
+ .method("POST")
+ .uri("/strand/_search")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({"query": {"match_all": {}}, "size": 2, "sort": [{"n": "asc"}, {"_id": "asc"}]})
+ .to_string(),
+ ))
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "control page 1: {page1}");
+ let hits = page1["hits"]["hits"].as_array().expect("hits array");
+ assert_eq!(hits.len(), 2, "control page 1 must return a full page");
+ let cursor = hits.last().unwrap()["sort"].clone();
+ let (status, page2) = send(
+ &app,
+ Request::builder()
+ .method("POST")
+ .uri("/strand/_search")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({
+ "query": {"match_all": {}}, "size": 2,
+ "sort": [{"n": "asc"}, {"_id": "asc"}],
+ "search_after": cursor,
+ })
+ .to_string(),
+ ))
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "control page 2: {page2}");
+ assert_eq!(
+ page2["hits"]["hits"].as_array().map(Vec::len),
+ Some(2),
+ "control search_after must advance past page 1, not repeat it: {page2}"
+ );
+
+ // The bug: search_after on an unresolvable field, pre-fix, answered 200
+ // with every hit's sort value null and page 2 identical to page 1
+ // (stranded). Post-fix it must be refused up front.
+ let (status, body) = send(
+ &app,
+ Request::builder()
+ .method("POST")
+ .uri("/strand/_search")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({"query": {"match_all": {}}, "size": 2, "sort": [{"_tier": "asc"}]})
+ .to_string(),
+ ))
+ .unwrap(),
+ )
+ .await;
+ assert_no_mapping_found_error(status, &body, "_tier");
+}
+
+/// #402's own review caught this exact gap: the denylist reached `_search`
+/// but not `_msearch`. Prove the single engine-level gate closes it without
+/// per-endpoint wiring.
+#[tokio::test]
+async fn msearch_rejects_sort_on_an_unresolvable_field_too() {
+ let (app, _dir) = app().await;
+ seed(&app, "mscensus", 4).await;
+
+ let ndjson = format!(
+ "{}\n{}\n",
+ json!({"index": "mscensus"}),
+ json!({"query": {"match_all": {}}, "sort": [{"_meta": "asc"}]})
+ );
+ let (status, body) = send(
+ &app,
+ Request::builder()
+ .method("POST")
+ .uri("/_msearch")
+ .header("content-type", "application/x-ndjson")
+ .body(Body::from(ndjson))
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "msearch envelope itself is always 200: {body}"
+ );
+ let responses = body["responses"].as_array().expect("responses array");
+ assert_eq!(responses.len(), 1);
+ assert_no_mapping_found_error(StatusCode::BAD_REQUEST, &responses[0], "_meta");
+}
+
+/// Same gap, `_search/template`.
+#[tokio::test]
+async fn search_template_rejects_sort_on_an_unresolvable_field_too() {
+ let (app, _dir) = app().await;
+ seed(&app, "tplcensus", 4).await;
+
+ let (status, body) = send(
+ &app,
+ Request::builder()
+ .method("POST")
+ .uri("/tplcensus/_search/template")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({
+ "source": {"query": {"match_all": {}}, "sort": [{"_field_names": "asc"}]},
+ "params": {},
+ })
+ .to_string(),
+ ))
+ .unwrap(),
+ )
+ .await;
+ assert_no_mapping_found_error(status, &body, "_field_names");
+}
+
+/// Positive control: a `.keyword` multi-field and a nested/object property
+/// must keep sorting correctly — the schema check uses the same recursive
+/// dotted-path resolution `compute_sort_values` already relies on for
+/// `.keyword`, not a flat exact-match lookup that would false-reject both.
+#[tokio::test]
+async fn sort_on_a_keyword_multi_field_and_a_nested_property_still_works() {
+ let (app, _dir) = app().await;
+ let (st, body) = send(
+ &app,
+ Request::builder()
+ .method("POST")
+ .uri("/nested_ok/_bulk")
+ .header("content-type", "application/x-ndjson")
+ .body(Body::from(
+ "{\"index\":{\"_id\":\"1\"}}\n\
+ {\"title\":\"b\",\"user\":{\"name\":\"z\"}}\n\
+ {\"index\":{\"_id\":\"2\"}}\n\
+ {\"title\":\"a\",\"user\":{\"name\":\"y\"}}\n",
+ ))
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "bulk: {body}");
+ let (st, body) = send(
+ &app,
+ Request::builder()
+ .method("POST")
+ .uri("/nested_ok/_refresh")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "refresh: {body}");
+
+ for field in ["title.keyword", "user.name"] {
+ let (status, body) = send(
+ &app,
+ Request::builder()
+ .method("POST")
+ .uri("/nested_ok/_search")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({"query": {"match_all": {}}, "sort": [{field: "asc"}]}).to_string(),
+ ))
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "sort on [{field}] must work: {body}"
+ );
+ assert_eq!(body["hits"]["hits"].as_array().map(Vec::len), Some(2));
+ }
+}
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 4c72dea51..faddbe226 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -13828,6 +13828,39 @@ impl Index {
),
)));
}
+ // #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
+ // in `compute_sort_values` and silently returned `null` on
+ // every hit — a full-corpus tie that strands `search_after` at
+ // page one, HTTP 200, indistinguishable from a correct run.
+ // #402 tried to catch this with a request-level allowlist of
+ // "known-unresolvable" names and was refuted: xerj permits a
+ // metadata-named `_source` key (`{"_seq_no": 1}`), so whether a
+ // name resolves is a property of the CORPUS, not of the field
+ // name — a static list is guaranteed wrong on some corpus. The
+ // schema is the stable thing to check instead, matching what
+ // real ES actually validates. Bypass set kept in lockstep with
+ // `compute_sort_values`'s own special cases (`_score`/`_doc`/
+ // `_id`/`is_meta_sort_field`) — anything else must be declared,
+ // via the same recursive dotted-path walk `declared_field`
+ // already does for `.keyword` multi-fields and nested/object
+ // properties (unlike `Schema::has_field`, which is flat/exact
+ // match only and would false-reject both).
+ for sf in &request.sort {
+ if sf.is_score()
+ || sf.is_doc_order()
+ || sf.field == "_id"
+ || is_meta_sort_field(&sf.field)
+ {
+ continue;
+ }
+ if declared_field(&schema.schema, &sf.field).is_none() {
+ return Err(EngineError::Common(xerj_common::XerjError::invalid_query(
+ format!("No mapping found for [{}] in order to sort on", sf.field),
+ )));
+ }
+ }
// #328's query half, and it rides the same guard for the same
// reason: a `dense_vector` has no term dictionary to consult, so a
// lexical clause naming one is lowered to `match_none` HERE,
diff --git a/engine/crates/xerj-engine/tests/sort_on_unresolvable_field.rs b/engine/crates/xerj-engine/tests/sort_on_unresolvable_field.rs
new file mode 100644
index 000000000..e04ac4513
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/sort_on_unresolvable_field.rs
@@ -0,0 +1,167 @@
+//! Regression test for #437 — sorting on a field this engine cannot resolve
+//! (any ES meta-field name besides `_score`/`_doc`/`_id` and the four #420
+//! made resolvable, or an unmapped/misspelled field) must be REJECTED, not
+//! silently answered with `null` on every hit.
+//!
+//! Before this fix, `compute_sort_values` sent every one of these fields to
+//! a plain `get_field_value(source, field)` lookup, which returns `Null`
+//! when the field is absent — the whole result set ties on `[null]`, HTTP
+//! 200, and `search_after` paging on that field is stranded at page one
+//! with no error anywhere.
+//!
+//! Issue #402 tried to catch this with a request-level denylist of
+//! "known-unresolvable" field names and was refuted: xerj deliberately
+//! permits a metadata-named key inside `_source` (`{"_seq_no": 1}` is a
+//! valid document body, unlike real ES), so whether a name resolves depends
+//! on the CORPUS, not the field name — a static list is guaranteed wrong on
+//! some corpus. This fix checks the SCHEMA instead, which is the stable
+//! thing real ES itself validates (`No mapping found for [x] in order to
+//! sort on`).
+
+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::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")
+}
+
+fn sorted_req(field: &str, size: usize) -> xerj_query::ast::SearchRequest {
+ parse_request(&json!({
+ "query": {"match_all": {}},
+ "size": size,
+ "sort": [{field: "asc"}],
+ }))
+ .expect("parse_request")
+}
+
+fn reason_of(err: &xerj_engine::EngineError) -> String {
+ match err {
+ xerj_engine::EngineError::Common(xerj_common::XerjError::InvalidQuery { reason }) => {
+ reason.clone()
+ }
+ other => panic!("expected EngineError::Common(InvalidQuery), got: {other:?}"),
+ }
+}
+
+/// #402's own under-inclusion review is the ready-made census: every ES
+/// meta-field name besides the ones already handled (`_score`, `_doc`,
+/// `_id`, `_seq_no`, `_version`, `_primary_term`, `_index`), plus an
+/// arbitrary unmapped/misspelled field.
+const UNRESOLVABLE_FIELDS: &[&str] = &[
+ "_source",
+ "_size",
+ "_doc_count",
+ "_field_names",
+ "_meta",
+ "_tier",
+ "_nested",
+ "_nested_path",
+ "_feature",
+ "_parent",
+ "_matched_queries",
+ "not_a_field_at_all",
+];
+
+#[tokio::test]
+async fn sort_on_an_unresolvable_field_is_rejected_not_stranded() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine
+ .create_index("unresolvable", Schema::empty())
+ .unwrap();
+ let idx = engine.get_index("unresolvable").unwrap();
+ for i in 0..6u64 {
+ idx.index_document(Some(format!("d{i}")), json!({ "n": i }))
+ .await
+ .unwrap();
+ }
+
+ for field in UNRESOLVABLE_FIELDS {
+ let result = idx.search(&sorted_req(field, 2)).await;
+ let err = result.err().unwrap_or_else(|| {
+ panic!(
+ "sort on [{field}] must be rejected — the pre-fix behavior was HTTP 200 \
+ with every hit's sort value silently null, stranding search_after at \
+ page one (#437)"
+ )
+ });
+ let reason = reason_of(&err);
+ assert!(
+ reason.contains(&format!("No mapping found for [{field}]")),
+ "sort on [{field}] was rejected, but the reason doesn't name it: {reason}"
+ );
+ }
+}
+
+/// Control: sorting on a genuinely mapped field, or one of the seven
+/// already-handled special cases, must keep working — this fix must not
+/// turn every sort into a rejection.
+#[tokio::test]
+async fn sort_on_a_resolvable_field_still_works() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("resolvable", Schema::empty()).unwrap();
+ let idx = engine.get_index("resolvable").unwrap();
+ for i in 0..6u64 {
+ idx.index_document(Some(format!("d{i}")), json!({ "n": i }))
+ .await
+ .unwrap();
+ }
+
+ // A dynamically-mapped ordinary field.
+ let res = idx.search(&sorted_req("n", 10)).await.expect("sort on n");
+ assert_eq!(res.hits.len(), 6);
+ for hit in &res.hits {
+ assert_ne!(hit.sort.first(), Some(&Value::Null), "n must not sort null");
+ }
+
+ // The already-handled special cases must still bypass the schema check
+ // entirely (they're resolved from the hit/engine metadata, never from
+ // `_source`, so they're never "in the schema" to begin with).
+ for field in [
+ "_score",
+ "_doc",
+ "_id",
+ "_seq_no",
+ "_version",
+ "_primary_term",
+ "_index",
+ ] {
+ idx.search(&sorted_req(field, 10))
+ .await
+ .unwrap_or_else(|e| panic!("sort on [{field}] must still work: {e}"));
+ }
+}
+
+/// A dynamically-mapped `.keyword` multi-field, and a nested/object
+/// property, must resolve via the schema too — proving the fix uses
+/// `declared_field`'s recursive dotted-path walk, not a flat exact-match
+/// lookup that would false-reject both.
+#[tokio::test]
+async fn sort_on_a_keyword_multi_field_and_a_nested_property_works() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine.create_index("nested_sort", Schema::empty()).unwrap();
+ let idx = engine.get_index("nested_sort").unwrap();
+ for i in 0..4u64 {
+ idx.index_document(
+ Some(format!("d{i}")),
+ json!({ "title": format!("t{i}"), "user": { "name": format!("u{i}") } }),
+ )
+ .await
+ .unwrap();
+ }
+
+ idx.search(&sorted_req("title.keyword", 10))
+ .await
+ .expect("sort on a dynamic .keyword multi-field must work");
+ idx.search(&sorted_req("user.name", 10))
+ .await
+ .expect("sort on a nested/object property must work");
+}