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): collapse inner_hits members honour the default _source projection (#646)
xerj-org76b5e96861d0
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex a0a5a9b0e..6f8f87899 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -8497,6 +8497,7 @@ fn render_collapse_inner_hits(spec: Value,idx_name: &str,rest_total_hits_as_int: bool,+ strip_companions: Option<&std::collections::HashSet<String>>,) -> Value {let spec_list: Vec<Value> = match spec {Value::Array(a) => a,@@ -8615,6 +8616,18 @@ fn render_collapse_inner_hits(if let Some(src) = m.get_mut("_source").and_then(Value::as_object_mut) {src.remove("__xy_collapse_group__");src.remove("__xy_collapse_spec__");+ // #646: a member's source is stashed BEFORE the engine's+ // `_source` projection, so it still carries the passage+ // sentinels (always internal) and, under the default+ // projection, the generated embedding companions. Match the+ // top-level hit rendering: strip the sentinels unconditionally+ // and the companions when the caller passed the set.+ src.retain(|k, _| {+ !k.starts_with(xerj_query::executor::PASSAGE_METADATA_PREFIX)+ });+ if let Some(companions) = strip_companions {+ src.retain(|k, _| !companions.contains(k));+ }}let mut hit_obj = serde_json::Map::new();hit_obj.insert("_index".to_string(), Value::String(idx_name.to_string()));@@ -10866,11 +10879,12 @@ async fn search_impl(Vec::new()};// One schema read-lock per participating index, and only for a request that- // could actually consume the answer. (The collapse `inner_hits` companion- // leak under a default projection is a separate, pre-existing gap tracked as- // a follow-up; it is not driven by the pierce, so it is not populated here.)+ // could actually consume the answer: a pierce (a companion named in+ // `fields`/`docvalue_fields`) OR a collapse `inner_hits` block, whose members+ // are stashed before the #309 projection and would otherwise ship the+ // companions on the wire (#646).let mut companions_by_index: HashMap<String, HashSet<String>> = HashMap::new();- if default_source_projection && !value_bearing_names.is_empty() {+ if default_source_projection && (!value_bearing_names.is_empty() || body.collapse.is_some()) {for idx_name in &index_names {let Ok(idx) = state.engine.get_index(idx_name) else {continue;@@ -13600,6 +13614,18 @@ async fn search_impl(spec,&idx_name,params.rest_total_hits_as_int.as_deref() == Some("true"),+ // #646: under the default projection, strip the generated+ // companions from each member's `_source` — the members were+ // stashed before #309 ran. Gated on `!is_scroll_request` so a+ // collapse SCROLL stays byte-identical across pages (#623):+ // the continuation path (scroll_page_response) cannot strip+ // companions yet, so page 1 must not either — scroll+collapse+ // companion stripping is the clean remaining sub-case.+ if default_source_projection && !is_scroll_request {+ companions_by_index.get(idx_name.as_str())+ } else {+ None+ },));}@@ -20733,6 +20759,13 @@ async fn scroll_page_response(s,&h.index,rest_total_hits_as_int,+ // The scroll continuation has no companion set+ // in scope (it would need threading through+ // ScrollContext); the unconditional passage+ // sentinel strip still applies. Scroll+collapse+ // companion stripping is a scoped remaining+ // sub-case of #646.+ None,)),_ => None,}diff --git a/engine/crates/xerj-api/tests/collapse_inner_hits_no_companion_leak.rs b/engine/crates/xerj-api/tests/collapse_inner_hits_no_companion_leak.rsnew file mode 100644index 000000000..65e104a98--- /dev/null+++ b/engine/crates/xerj-api/tests/collapse_inner_hits_no_companion_leak.rs@@ -0,0 +1,133 @@+//! Issue #646 (follow-up to #310): a collapse `inner_hits` block must not ship+//! the generated embedding companions in each member's `_source` under the+//! default projection.+//!+//! The collapse machinery stashes each group member's source BEFORE the engine's+//! `_source` projection runs, so the members carry `*_vector` / `*_vector_chunks`+//! even though #309 keeps them off the top-level `_source`. The leader honours+//! #309; the `inner_hits` underneath it leaked the vectors.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;+use xerj_common::types::{EmbeddingConfig, FieldConfig, FieldType, Schema};++const DIMS: usize = 32;++async fn seeded_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);++ let mut schema = Schema::empty();+ let mut body = FieldConfig::new("body", FieldType::Text);+ body.options.dimensions = Some(DIMS);+ body.options.similarity = Some("cosine".into());+ body.embedding = Some(EmbeddingConfig {+ endpoint: None,+ model: None,+ target_field: Some("body_vector".into()),+ });+ schema.add_field(body).expect("body field");+ let mut companion = FieldConfig::new("body_vector", FieldType::Vector);+ companion.options.dimensions = Some(DIMS);+ companion.options.similarity = Some("cosine".into());+ schema.add_field(companion).expect("body_vector field");+ schema+ .add_field(FieldConfig::new("grp", FieldType::Keyword))+ .expect("grp field");++ state.engine.create_index("docs", schema).expect("create");+ let idx = state.engine.get_index("docs").expect("get index");+ // Two docs in the same collapse group so the leader has an inner_hits member.+ for id in ["1", "2"] {+ idx.index_document(+ Some(id.into()),+ json!({+ "body": format!("companion leak guard document number {id}. ").repeat(8),+ "grp": "A",+ }),+ )+ .await+ .expect("index document");+ }+ idx.refresh().await.expect("refresh");++ (xerj_api::router::build_es_compat_router(state), dir)+}++async fn post(app: &axum::Router, path: &str, body: Value) -> (StatusCode, Value) {+ let response = app+ .clone()+ .oneshot(+ Request::post(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");+ let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ (status, value)+}++/// A collapse `inner_hits` member's `_source` must omit the generated companion+/// under the default projection, exactly as the collapse leader's `_source`+/// does (#309 / #646).+#[tokio::test]+async fn collapse_inner_hits_member_source_omits_the_companion() {+ let (app, _dir) = seeded_app().await;+ let (status, response) = post(+ &app,+ "/docs/_search",+ json!({+ "query": { "match_all": {} },+ "size": 10,+ "collapse": {+ "field": "grp",+ "inner_hits": { "name": "members", "size": 10 }+ }+ }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{response}");++ let leader = &response["hits"]["hits"][0];+ // #309 already holds on the leader.+ assert!(+ !leader["_source"]+ .as_object()+ .expect("leader _source")+ .contains_key("body_vector"),+ "the collapse leader must not leak the companion (#309): {response}"+ );++ // The inner_hits members must honour the same default projection (#646).+ let members = leader["inner_hits"]["members"]["hits"]["hits"]+ .as_array()+ .expect("inner_hits members");+ assert!(+ !members.is_empty(),+ "expected inner_hits members: {response}"+ );+ for m in members {+ let src = m["_source"].as_object().expect("member _source");+ assert!(+ !src.contains_key("body_vector"),+ "#646: a collapse inner_hits member must not leak body_vector in _source: {m}"+ );+ assert!(+ !src.contains_key("body_vector_chunks"),+ "#646: a collapse inner_hits member must not leak body_vector_chunks: {m}"+ );+ }+}