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): 400 a single top-level knn on an unanswerable field, not silent empty 200 (#498)

xerj-org1eda875d303d
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index c2fccb717..0179b001d 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -39941,12 +39941,13 @@ mod script_guard_symmetry_tests {
}
/// Why top-level `knn` is not a `GuardedField`: `_msearch` never executes
- /// it, so a script parked there reaches no executor. The discriminator is
- /// a `knn.filter` that matches nothing — `_search` honours it and returns
- /// zero hits, `_msearch` ignores the whole clause and returns the doc.
- ///
- /// If this ever starts failing because `_msearch` grew knn support, that
- /// path gained a script sink and `knn` must become a guarded field.
+ /// it, so a script parked there reaches no executor. The discriminator is a
+ /// `knn` naming the field `vec`, which the seed index does not have: since
+ /// #498 `_search` EXECUTES the clause and rejects the unanswerable field
+ /// with a `400`, while `_msearch` ignores the whole clause and returns the
+ /// doc (`200`, one hit). If `_msearch` ever grew knn support it would 400
+ /// here too — that path would have gained a script sink and `knn` must
+ /// become a guarded field.
#[tokio::test]
async fn msearch_does_not_execute_top_level_knn() {
let state = test_state();
@@ -39968,12 +39969,18 @@ mod script_guard_symmetry_tests {
"`_msearch` must be ignoring the knn clause entirely: {msearch_item}"
);
+ // `_search` executes the knn, so it validates the field — `vec` is
+ // absent from the mapping and carries no vectors, which is a 400 since
+ // #498 (a silent empty 200 hid "this index cannot do vector search").
let (search_status, search_body) = search_verdict(state, &body).await;
- assert_eq!(search_status, 200, "{search_body}");
- assert_eq!(
- search_body["hits"]["total"]["value"],
- json!(0),
- "`_search` must be executing the knn filter: {search_body}"
+ assert_eq!(search_status, 400, "{search_body}");
+ assert!(
+ search_body
+ .pointer("/error/reason")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .contains("vec"),
+ "the 400 must name the unanswerable field: {search_body}"
);
}
}
diff --git a/engine/crates/xerj-api/tests/knn_on_missing_field_400s.rs b/engine/crates/xerj-api/tests/knn_on_missing_field_400s.rs
new file mode 100644
index 000000000..9d73f921b
--- /dev/null
+++ b/engine/crates/xerj-api/tests/knn_on_missing_field_400s.rs
@@ -0,0 +1,168 @@
+//! A `knn` (or `semantic`) clause naming a field the index cannot answer must
+//! fail loudly with a `400`, not return a silent, successful empty result —
+//! issue #498.
+//!
+//! `refsym`, XERJ's own reference-coding corpus, has no `dense_vector` field, so
+//! `knn: {field: "embedding", ...}` had nothing to run against and came back
+//! `200` with `hits.total = 0` and `error: null`. An agent cannot tell "nothing
+//! matched" from "this index does not do vector search," so it concludes the
+//! code does not exist — the exact silent-false-negative the vector/semantic
+//! badges are supposed to prevent.
+//!
+//! Elasticsearch answers a `knn` against a missing or wrongly-typed field with
+//! `400 illegal_argument_exception` naming the field. XERJ must do the same.
+//!
+//! The companion `knn_on_declared_but_empty_vector_field_is_empty_200` locks the
+//! distinction that sank the first attempt (#529): a field that IS a
+//! `dense_vector` but currently holds no vectors is a real empty result, not an
+//! error — the 400 must key on "the field cannot answer a vector query," not on
+//! "the field has no data yet."
+//!
+//! Elasticsearch is referenced for wire semantics only; 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),
+ )
+}
+
+/// The #498 bug: `knn` on a field that is absent from a non-vector index must be
+/// a `400`, not a silent empty `200`.
+#[tokio::test]
+async fn knn_on_absent_field_is_400_not_silent_empty() {
+ let (app, _dir) = app().await;
+
+ // An index whose mapping has NO dense_vector field (mirrors refsym).
+ let (status, body) = json_req(
+ &app,
+ "PUT",
+ "/codes",
+ json!({ "mappings": { "properties": {
+ "name": { "type": "text" },
+ "code": { "type": "keyword" }
+ } } }),
+ )
+ .await;
+ assert!(status.is_success(), "create index: {status} {body}");
+
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ "/codes/_doc/1",
+ json!({ "name": "sniff content type", "code": "fn sniff() {}" }),
+ )
+ .await;
+ assert!(status.is_success(), "index doc: {status} {body}");
+ let (_s, _b) = json_req(&app, "POST", "/codes/_refresh", json!({})).await;
+
+ // knn against a field that does not exist in the mapping.
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ "/codes/_search",
+ json!({ "knn": {
+ "field": "embedding",
+ "query_vector": [0.1, 0.2, 0.3],
+ "k": 5,
+ "num_candidates": 50
+ } }),
+ )
+ .await;
+
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "knn on an absent field must be 400, not a silent empty 200 (#498): got {status} {body}"
+ );
+ let reason = body
+ .pointer("/error/reason")
+ .and_then(Value::as_str)
+ .unwrap_or("");
+ assert!(
+ reason.contains("embedding"),
+ "the 400 must name the field: {body}"
+ );
+}
+
+/// The invariant #529 broke: a field that IS a `dense_vector` but currently
+/// holds no vectors returns an empty `200`, NOT a 400. "Cannot answer a vector
+/// query" is a mapping/execution fact, not "has no data yet."
+#[tokio::test]
+async fn knn_on_declared_but_empty_vector_field_is_empty_200() {
+ let (app, _dir) = app().await;
+
+ let (status, body) = json_req(
+ &app,
+ "PUT",
+ "/vecs",
+ json!({ "mappings": { "properties": {
+ "v": { "type": "dense_vector", "dims": 3 }
+ } } }),
+ )
+ .await;
+ assert!(status.is_success(), "create vector index: {status} {body}");
+ // Deliberately index NO documents — the field exists and is vector-typed,
+ // it simply has nothing to match.
+
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ "/vecs/_search",
+ json!({ "knn": {
+ "field": "v",
+ "query_vector": [0.1, 0.2, 0.3],
+ "k": 5,
+ "num_candidates": 50
+ } }),
+ )
+ .await;
+
+ assert!(
+ status.is_success(),
+ "knn on a declared-but-empty dense_vector field is a real empty result, not an error (#498/#529 guard): {status} {body}"
+ );
+ let total = body
+ .pointer("/hits/total/value")
+ .and_then(Value::as_u64)
+ .unwrap_or(u64::MAX);
+ assert_eq!(total, 0, "expected an empty result set: {body}");
+}
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index c247e6918..3c7ac669b 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -11287,6 +11287,72 @@ impl Index {
Ok(result)
}
+ /// True iff at least one indexed document carries a numeric-array vector at
+ /// `field` — the execution-truth signal that a field CAN answer a vector
+ /// query even when it was never declared `dense_vector`. This is the case a
+ /// schema-only (or `hnsw_field`) check gets wrong: a field seeded with, say,
+ /// 256 undeclared vectors is below `HNSW_MIN_DOCS`, so no graph exists and
+ /// `hnsw_field` is `None`, yet the field is fully brute-force answerable
+ /// (#498/#529). Early-exits on the first hit and is only invoked on an empty
+ /// knn result, so it never runs on the hot path.
+ async fn index_has_any_vector_at(&self, field: &str) -> bool {
+ for (_id, source) in self.memtable.all_docs_with_sources() {
+ if extract_numeric_vector(&source, field).is_some() {
+ return true;
+ }
+ }
+ let snap = self.store.snapshot();
+ for meta in snap.segments.iter() {
+ if let Some(docs) = self.stored_values_for_async(&meta.id).await {
+ for doc in docs.iter() {
+ let src = doc.get("_source").unwrap_or(doc);
+ if extract_numeric_vector(src, field).is_some() {
+ return true;
+ }
+ }
+ }
+ }
+ false
+ }
+
+ /// #498: reject a `knn`/`semantic` clause naming a field the index cannot
+ /// answer with a `400`, instead of the silent empty `200` it used to return.
+ /// "Cannot answer" is execution truth: the field is neither declared
+ /// `dense_vector`/`semantic_text` NOR does any indexed document carry a
+ /// vector for it. A declared-but-empty vector field, and an undeclared field
+ /// that nonetheless holds indexed vectors, both legitimately return an empty
+ /// result — only a genuinely non-vector field is rejected (the distinction
+ /// #529's mapping-only gate got wrong). Called only on an empty, non-timed-
+ /// out result, so the extra scan never touches the hot path.
+ async fn reject_unanswerable_knn_field(&self, field: &str) -> Result<()> {
+ {
+ let schema = self.schema.read().await;
+ if collect_dense_vector_fields(&schema.schema)
+ .iter()
+ .any(|f| f == field)
+ {
+ return Ok(());
+ }
+ if schema
+ .schema
+ .field(field)
+ .is_some_and(|fc| fc.embedding.is_some())
+ {
+ return Ok(());
+ }
+ }
+ if self.index_has_any_vector_at(field).await {
+ return Ok(());
+ }
+ Err(EngineError::Common(xerj_common::XerjError::invalid_query(
+ format!(
+ "[knn] query field [{field}] is not a vector field: it is absent from the \
+ mapping and carries no indexed vector data. Map it as [dense_vector] (or \
+ [semantic_text]) before running vector search."
+ ),
+ )))
+ }
+
/// Brute-force nested KNN: score each parent by the best (max)
/// similarity among its `<nested_path>` array elements.
///
@@ -13984,39 +14050,50 @@ impl Index {
// SET can differ slightly from exact; aggregations over that set
// must be exact (analytics counts, not ranked hits), so we do not
// let ANN approximation leak into agg buckets.
- if filter_opt.is_none()
+ let plain = filter_opt.is_none()
&& boost.is_none()
&& min_similarity.is_none()
- && request.aggs.is_none()
- {
- if let Some(result) = self
- .run_knn_hnsw(
+ && request.aggs.is_none();
+ let hnsw = if plain {
+ self.run_knn_hnsw(
+ request,
+ search_deadline,
+ &field,
+ &query_vec,
+ k,
+ num_candidates,
+ &similarity,
+ )
+ .await
+ } else {
+ None
+ };
+ let result = match hnsw {
+ Some(result) => result,
+ None => {
+ self.run_knn_brute_force_with_deadline(
request,
search_deadline,
&field,
&query_vec,
k,
- num_candidates,
+ filter_opt,
&similarity,
+ boost,
+ min_similarity,
)
- .await
- {
- return Ok(result);
+ .await?
}
- }
- return self
- .run_knn_brute_force_with_deadline(
- request,
- search_deadline,
- &field,
- &query_vec,
- k,
- filter_opt,
- &similarity,
- boost,
- min_similarity,
- )
- .await;
+ };
+ // #498: a knn naming a field the index cannot answer must fail with a
+ // 400, not return a silent empty 200. Checked only on a genuinely
+ // empty, non-timed-out result, so the hot path is untouched and a
+ // declared-but-empty (or indexed-but-undeclared) vector field still
+ // returns its real empty result.
+ if result.hits.is_empty() && !result.timed_out {
+ self.reject_unanswerable_knn_field(&field).await?;
+ }
+ return Ok(result);
}
// PURE multi-KNN (the ES `knn: [...]` array form): every clause runs
// its own exact top-k, scores are SUMMED for docs found by more than