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(search): preserve passage provenance across response shapes
buger6cf2c556de19
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex c3c5f3147..d6234e1cc 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -29,6 +29,15 @@ use crate::{state::AppState,};+fn passage_fields(hit: &xerj_query::executor::Hit) -> Option<HashMap<String, Value>> {+ let passage = hit.passage.as_ref()?;+ let value = serde_json::to_value(passage).ok()?;+ Some(HashMap::from([(+ xerj_query::executor::PASSAGE_RESPONSE_FIELD.to_string(),+ Value::Array(vec![value]),+ )]))+}+// ─────────────────────────────────────────────────────────────────────────────// GET / — cluster info// ─────────────────────────────────────────────────────────────────────────────@@ -4633,6 +4642,12 @@ fn build_search_request(if let Some(ref tth) = body.track_total_hits {query_body["track_total_hits"] = tth.clone();}+ // Preserve every accepted ES `fields` wire shape. The query parser+ // normalizes scalar, string-array, and `{field: ...}` entries into names+ // used by engine-owned pseudo-fields such as `_passage`.+ if let Some(ref fields) = body.fields {+ query_body["fields"] = fields.clone();+ }let mut req = parse_request(&query_body).map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))?;@@ -4739,22 +4754,6 @@ fn build_search_request(// handler's fields-building closure and merged into the hit's `fields`.req.script_fields = body.script_fields.clone();- // Forward fields request.- if let Some(fields_val) = &body.fields {- match fields_val {- Value::Array(arr) => {- req.fields = arr- .iter()- .filter_map(|v| v.as_str().map(String::from))- .collect();- }- Value::String(s) => {- req.fields = vec![s.clone()];- }- _ => {}- }- }-// track_total_hits is already forwarded via the JSON blob above.// Parse search_after cursor.@@ -15036,7 +15035,7 @@ pub async fn search_with_scroll(} else {Some(h.source.clone())},- fields: None,+ fields: passage_fields(h),sort: if h.sort.is_empty() {None} else {@@ -15090,12 +15089,18 @@ pub async fn search_with_scroll("hits": {"total": { "value": total_count, "relation": "eq" },"max_score": first_page.first().and_then(|h| h.score),- "hits": first_page.iter().map(|h| json!({- "_index": h.index,- "_id": h.id,- "_score": h.score,- "_source": h.source,- })).collect::<Vec<_>>()+ "hits": first_page.iter().map(|h| {+ let mut hit = json!({+ "_index": h.index,+ "_id": h.id,+ "_score": h.score,+ "_source": h.source,+ });+ if let Some(fields) = &h.fields {+ hit["fields"] = serde_json::to_value(fields).unwrap_or(Value::Null);+ }+ hit+ }).collect::<Vec<_>>()}});return Json(resp).into_response();@@ -15120,7 +15125,7 @@ pub async fn search_with_scroll(} else {Some(h.source.clone())},- fields: None,+ fields: passage_fields(h),sort: if h.sort.is_empty() {None} else {@@ -15257,7 +15262,7 @@ pub async fn next_scroll(} else {Some(h.source.clone())},- fields: None,+ fields: passage_fields(h),sort: if h.sort.is_empty() {None} else {@@ -15311,6 +15316,12 @@ pub async fn next_scroll(if let Some(sort) = &h.sort {o.insert("sort".to_string(), Value::Array(sort.clone()));}+ if let Some(fields) = &h.fields {+ o.insert(+ "fields".to_string(),+ serde_json::to_value(fields).unwrap_or(Value::Null),+ );+ }Value::Object(o)}).collect::<Vec<_>>()}@@ -15326,6 +15337,153 @@ pub async fn next_scroll(}}+#[cfg(test)]+mod passage_scroll_tests {+ use super::*;+ use axum::{body::Body, http::Request};+ use std::time::{Duration, Instant};+ use tower::ServiceExt;+ use xerj_query::executor::{Hit, PassageMatch};++ fn test_state() -> AppState {+ let dir = tempfile::tempdir().expect("tempdir").keep();+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.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");+ AppState::new(config, engine, metrics)+ }++ fn passage_hit(id: &str, ordinal: u32) -> Hit {+ Hit {+ id: id.to_string(),+ score: 1.0,+ source: json!({"company": "ACME"}),+ sort: Vec::new(),+ explain: None,+ highlight: None,+ matched_queries: Vec::new(),+ passage: Some(PassageMatch {+ field: "content".into(),+ ordinal,+ start_offset: 0,+ end_offset: 8,+ text: "evidence".into(),+ page: Some(u64::from(ordinal) + 1),+ }),+ }+ }++ #[tokio::test]+ async fn scroll_continuation_preserves_opted_in_passage_fields() {+ let state = test_state();+ let scroll_id = Uuid::new_v4().to_string();+ let now = Instant::now();+ state.engine.scrolls.insert(+ scroll_id.clone(),+ xerj_engine::engine::ScrollContext {+ index: "reports".into(),+ hits: vec![passage_hit("page-1", 0), passage_hit("page-2", 1)],+ position: 1,+ page_size: 1,+ created: now,+ keep_alive: Duration::from_secs(60),+ expires_at: now + Duration::from_secs(60),+ },+ );+ let app = crate::router::build_es_compat_router(state);+ let response = app+ .oneshot(+ Request::post("/_search/scroll")+ .header("content-type", "application/json")+ .body(Body::from(json!({"scroll_id": scroll_id}).to_string()))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let body: Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(body["hits"]["hits"][0]["_id"], "page-2");+ assert_eq!(+ body["hits"]["hits"][0]["fields"]["_passage"][0]["ordinal"],+ 1+ );+ assert_eq!(body["hits"]["hits"][0]["fields"]["_passage"][0]["page"], 2);+ }++ #[tokio::test]+ async fn passage_field_scalar_array_and_object_forms_reach_the_engine() {+ let state = test_state();+ let mut schema = Schema::empty();+ let mut content = FieldConfig::new("content", FieldType::Text);+ content.options.dimensions = Some(32);+ content.embedding = Some(xerj_common::types::EmbeddingConfig {+ endpoint: None,+ model: None,+ target_field: Some("embedding".into()),+ });+ schema.fields.push(content);+ state.engine.create_index("passage-fields", schema).unwrap();+ let index = state.engine.get_index("passage-fields").unwrap();+ index+ .index_document(+ Some("report-page".into()),+ json!({+ "content": format!(+ "{} quarterly zephyr liquidity evidence {}",+ "operating narrative ".repeat(50),+ "tax footnote ".repeat(50)+ ),+ "page": 7+ }),+ )+ .await+ .unwrap();+ index.refresh().await.unwrap();+ let app = crate::router::build_es_compat_router(state);++ for fields in [+ json!("_passage"),+ json!(["_passage"]),+ json!([{"field": "_passage"}]),+ ] {+ let response = app+ .clone()+ .oneshot(+ Request::post("/passage-fields/_search")+ .header("content-type", "application/json")+ .body(Body::from(+ json!({+ "fields": fields,+ "query": {"semantic": {+ "field": "content",+ "query": "quarterly zephyr liquidity evidence",+ "k": 1+ }}+ })+ .to_string(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let body: Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(+ body["hits"]["hits"][0]["fields"]["_passage"][0]["page"], 7,+ "fields form {fields} did not propagate: {body}"+ );+ }+ }+}+#[derive(Debug, Deserialize, Default)]pub struct ClearScrollBody {#[serde(default)]diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 8fee71735..e0019ba00 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -8725,6 +8725,16 @@ impl Index {// exact brute-force scan below. Filtered knn stays exact brute// force with a pre-filter, where `num_candidates` (the ANN fan-out)// has no effect.+ if passage_requested(request)+ && (peel_multi_knn_query(query).is_some() || peel_hybrid_query(query).is_some())+ {+ return Err(EngineError::Common(xerj_common::XerjError::invalid_query(+ "`fields: [\"_passage\"]` requires one semantic or kNN clause; \+ multi-kNN and hybrid queries combine independent score contributions, \+ so they do not have one unambiguous winning passage; request `_passage` \+ only with a single semantic/kNN clause, or omit `_passage` for fusion",+ )));+ }if let Some(peeled) = peel_knn_query(query) {let PeeledKnn {field,diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rsindex 6ee45b0c9..9a332d746 100644--- a/engine/crates/xerj-engine/tests/integration.rs+++ b/engine/crates/xerj-engine/tests/integration.rs@@ -321,6 +321,82 @@ async fn reserved_passage_metadata_input_is_rejected() {assert!(idx.get_document("spoof").await.unwrap().is_none());}+#[tokio::test]+async fn passage_provenance_rejects_ambiguous_multi_vector_composition_in_any_order() {+ use xerj_query::ast::{FusionStrategy, WeightedQuery};++ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine+ .create_index("passage-composition", Schema::empty())+ .unwrap();+ let idx = engine.get_index("passage-composition").unwrap();++ let knn_a = QueryNode::Knn {+ field: "embedding_a".into(),+ vector: vec![1.0, 0.0],+ k: 10,+ num_candidates: None,+ filter: None,+ boost: None,+ similarity: None,+ };+ let knn_b = QueryNode::Knn {+ field: "embedding_b".into(),+ vector: vec![0.0, 1.0],+ k: 10,+ num_candidates: None,+ filter: None,+ boost: None,+ similarity: None,+ };++ for should in [+ vec![knn_a.clone(), knn_b.clone()],+ vec![knn_b.clone(), knn_a.clone()],+ ] {+ let request = SearchRequest {+ query: QueryNode::Bool {+ must: Vec::new(),+ should,+ filter: Vec::new(),+ must_not: Vec::new(),+ minimum_should_match: None,+ },+ fields: vec!["_passage".into()],+ ..SearchRequest::default()+ };+ let error = idx.search(&request).await.unwrap_err().to_string();+ assert!(error.contains("one unambiguous winning passage"), "{error}");+ }++ let semantic = QueryNode::SemanticSearch {+ field: "content".into(),+ text: "quarterly evidence".into(),+ k: 10,+ filter: None,+ boost: None,+ };+ for queries in [+ vec![semantic.clone(), QueryNode::MatchAll],+ vec![QueryNode::MatchAll, semantic.clone()],+ ] {+ let request = SearchRequest {+ query: QueryNode::Hybrid {+ queries: queries+ .into_iter()+ .map(|query| WeightedQuery { query, weight: 1.0 })+ .collect(),+ fusion: FusionStrategy::Rrf { k: 60 },+ },+ fields: vec!["_passage".into()],+ ..SearchRequest::default()+ };+ let error = idx.search(&request).await.unwrap_err().to_string();+ assert!(error.contains("one unambiguous winning passage"), "{error}");+ }+}+fn make_search(query_json: Value) -> SearchRequest {parse_request(&json!({ "query": query_json, "size": 100 })).expect("parse_request")}diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rsindex 7f1ee9d1d..1d0d0e8e3 100644--- a/engine/crates/xerj-query/src/parser.rs+++ b/engine/crates/xerj-query/src/parser.rs@@ -210,12 +210,19 @@ pub fn parse_request(body: &Value) -> Result<SearchRequest> {let script_fields = obj.get("script_fields").cloned();// fields — stored/doc-value fields to return alongside _source.+ let parse_field = |value: &Value| {+ value.as_str().map(String::from).or_else(|| {+ value+ .as_object()+ .and_then(|object| object.get("field"))+ .and_then(Value::as_str)+ .map(String::from)+ })+ };let fields: Vec<String> = match obj.get("fields") {- Some(Value::Array(arr)) => arr- .iter()- .filter_map(|v| v.as_str().map(String::from))- .collect(),- _ => Vec::new(),+ Some(Value::Array(arr)) => arr.iter().filter_map(parse_field).collect(),+ Some(value) => parse_field(value).into_iter().collect(),+ None => Vec::new(),};// profile — include timing breakdown@@ -5050,4 +5057,21 @@ mod tests {})).is_err());}++ #[test]+ fn fields_accept_scalar_array_and_object_forms() {+ for (body, expected) in [+ (json!({"fields": "_passage"}), vec!["_passage"]),+ (+ json!({"fields": ["company", "_passage"]}),+ vec!["company", "_passage"],+ ),+ (+ json!({"fields": [{"field": "_passage", "format": "ignored"}]}),+ vec!["_passage"],+ ),+ ] {+ assert_eq!(parse_request(&body).unwrap().fields, expected);+ }+ }}