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(api): scroll continuation matches first-page _source suppression (#637)

xerj-orga78cac233b01
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 6f8f87899..3c249d5ed 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -8726,6 +8726,29 @@ fn render_collapse_inner_hits(
Value::Object(combined)
}
+/// Whether the index mapping sets `_source.enabled: false`. ES suppresses
+/// `_source` in the response for such an index; xerj keeps the underlying
+/// source available internally (fields/highlight/_ignored extraction) and makes
+/// the suppression a response-time decision. Mirrors the per-hit check in
+/// `search_impl`'s render, extracted so scroll-open can capture the SAME
+/// decision into `ScrollContext::source_disabled` and continuation pages stay in
+/// parity with the first page (#637).
+fn mapping_source_disabled(state: &AppState, index: &str) -> bool {
+ state
+ .engine
+ .index_mappings
+ .get(index)
+ .and_then(|m| {
+ m.get("mappings")
+ .and_then(|mm| mm.get("_source"))
+ .or_else(|| m.get("_source"))
+ .cloned()
+ })
+ .and_then(|src| src.get("enabled").and_then(Value::as_bool))
+ .map(|b| !b)
+ .unwrap_or(false)
+}
+
async fn search_impl(
state: AppState,
index: String,
@@ -11958,19 +11981,7 @@ async fn search_impl(
// extraction, so the suppression is a response-time
// decision not a data-layer decision.
let source_body_disabled = matches!(body.source, Some(Value::Bool(false)));
- let source_mapping_disabled = state
- .engine
- .index_mappings
- .get(idx_name.as_str())
- .and_then(|m| {
- m.get("mappings")
- .and_then(|mm| mm.get("_source"))
- .or_else(|| m.get("_source"))
- .cloned()
- })
- .and_then(|src| src.get("enabled").and_then(Value::as_bool))
- .map(|b| !b)
- .unwrap_or(false);
+ let source_mapping_disabled = mapping_source_disabled(&state, idx_name.as_str());
// `stored_fields` implicitly suppressing `_source` (unless the
// list literally contains `"_source"`) is only a DEFAULT for
// when the caller left `_source` unspecified. When the request
@@ -14620,6 +14631,21 @@ async fn search_impl(
.min(sc_cfg.scroll_max_keep_alive_secs);
let keep_alive = std::time::Duration::from_secs(keep_alive_secs);
let now = Instant::now();
+ // #637: capture the FULL first-page `_source` suppression decision, not
+ // just request-level `_source: false`. search_impl's own render above
+ // also omits `_source` when `stored_fields` implies it (and the request
+ // left `_source` unspecified) or the mapping sets `_source.enabled:
+ // false`. Both are request/index-level (constant across the snapshot),
+ // so a single captured boolean keeps continuation pages in parity with
+ // this first page. The remaining per-hit null-source case is already
+ // handled directly in `scroll_page_response`. (The
+ // `/:index/_search_scroll` route's own first page does not suppress these
+ // cases, so its capture site is intentionally left as request-level only
+ // — matching ITS render.) Computed before the struct literal moves
+ // `scroll_index` into `ctx.index`.
+ let scroll_source_disabled = matches!(body.source, Some(Value::Bool(false)))
+ || (suppress_source_for_stored && body.source.is_none())
+ || mapping_source_disabled(&state, &scroll_index);
let ctx = xerj_engine::engine::ScrollContext {
index: scroll_index,
hits: snapshot,
@@ -14630,7 +14656,7 @@ async fn search_impl(
// first page's own `_seq_no`/`_version` emission above.
seq_no_primary_term: emit_seq_no,
version: emit_version,
- source_disabled: matches!(body.source, Some(Value::Bool(false))),
+ source_disabled: scroll_source_disabled,
created: now,
keep_alive,
expires_at: now + keep_alive,
diff --git a/engine/crates/xerj-api/tests/scroll_source_suppression_parity.rs b/engine/crates/xerj-api/tests/scroll_source_suppression_parity.rs
new file mode 100644
index 000000000..d322f1f55
--- /dev/null
+++ b/engine/crates/xerj-api/tests/scroll_source_suppression_parity.rs
@@ -0,0 +1,168 @@
+//! Issue #637 (follow-up to #624): a `_search?scroll=` continuation page must
+//! suppress `_source` in the SAME cases the first page (`search_impl`) does, not
+//! only for a request-level `_source: false`.
+//!
+//! #624 added `ScrollContext::source_disabled`, but captured it from
+//! `matches!(body.source, Some(Value::Bool(false)))` ONLY. The first page omits
+//! `_source` in three more cases:
+//! - mapping `_source.enabled: false`,
+//! - `stored_fields` implying suppression when `_source` is unspecified,
+//! - a null/absent stored source (this one is already per-hit on the
+//! continuation, so it is not a divergence).
+//!
+//! For the first two, a scroll opened against them omitted `_source` on the
+//! first page but EMITTED it on every continuation page — a first-page/
+//! continuation divergence. These tests pin the parity.
+
+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 call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(path);
+ let body = if body.is_null() {
+ Body::empty()
+ } else {
+ req = req.header("content-type", "application/json");
+ Body::from(body.to_string())
+ };
+ let response = app.clone().oneshot(req.body(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 seed(app: &axum::Router, index: &str, mappings: Value) {
+ let (st, body) = call(app, "PUT", &format!("/{index}"), mappings).await;
+ assert_eq!(st, StatusCode::OK, "create {index}: {body}");
+ for (id, v) in [("d0", 10), ("d1", 11), ("d2", 12), ("d3", 13)] {
+ let (st, _) = call(
+ app,
+ "POST",
+ &format!("/{index}/_doc/{id}"),
+ json!({"grp": "g", "v": v}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::CREATED, "index {id}");
+ }
+ let _ = call(app, "POST", &format!("/{index}/_refresh"), Value::Null).await;
+}
+
+/// mapping `_source.enabled: false`: the first page omits `_source`; the
+/// continuation must too (fails before the fix — the continuation emitted it).
+#[tokio::test]
+async fn scroll_continuation_omits_source_under_mapping_source_disabled() {
+ let (app, _dir) = app().await;
+ seed(
+ &app,
+ "docs",
+ json!({"mappings": {
+ "_source": {"enabled": false},
+ "properties": {"grp": {"type": "keyword"}, "v": {"type": "long"}}
+ }}),
+ )
+ .await;
+
+ // Scroll, size 1, sorted v asc → first page 1 hit, continuation pages follow.
+ let (st, first) = call(
+ &app,
+ "POST",
+ "/docs/_search?scroll=5m",
+ json!({"query": {"match_all": {}}, "size": 1, "sort": [{"v": "asc"}]}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "scroll start: {first}");
+ // Baseline: mapping `_source.enabled:false` already omits `_source` on the
+ // FIRST page (search_impl). If this ever regresses the divergence premise is
+ // moot — assert it so the test stays honest.
+ assert!(
+ first["hits"]["hits"][0].get("_source").is_none(),
+ "#637 premise: mapping _source.enabled:false omits _source on the first page: {first}"
+ );
+ let sid = first["_scroll_id"].as_str().expect("scroll id").to_string();
+
+ let (st, page2) = call(
+ &app,
+ "POST",
+ "/_search/scroll",
+ json!({"scroll": "5m", "scroll_id": sid}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "continuation: {page2}");
+ let hit = &page2["hits"]["hits"][0];
+ assert!(
+ hit.get("_id").is_some(),
+ "#637: continuation should still return a hit: {page2}"
+ );
+ assert!(
+ hit.get("_source").is_none(),
+ "#637: scroll continuation must omit _source when the mapping sets \
+ _source.enabled:false (first-page parity), got: {hit}"
+ );
+}
+
+/// `stored_fields` without an explicit `_source`: the first page omits `_source`;
+/// the continuation must too (fails before the fix).
+#[tokio::test]
+async fn scroll_continuation_omits_source_under_stored_fields() {
+ let (app, _dir) = app().await;
+ seed(
+ &app,
+ "docs",
+ json!({"mappings": {
+ "properties": {"grp": {"type": "keyword"}, "v": {"type": "long"}}
+ }}),
+ )
+ .await;
+
+ let (st, first) = call(
+ &app,
+ "POST",
+ "/docs/_search?scroll=5m",
+ json!({
+ "query": {"match_all": {}},
+ "size": 1,
+ "sort": [{"v": "asc"}],
+ "stored_fields": ["grp"]
+ }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "scroll start: {first}");
+ assert!(
+ first["hits"]["hits"][0].get("_source").is_none(),
+ "#637 premise: stored_fields (no _source) omits _source on the first page: {first}"
+ );
+ let sid = first["_scroll_id"].as_str().expect("scroll id").to_string();
+
+ let (st, page2) = call(
+ &app,
+ "POST",
+ "/_search/scroll",
+ json!({"scroll": "5m", "scroll_id": sid}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "continuation: {page2}");
+ let hit = &page2["hits"]["hits"][0];
+ assert!(
+ hit.get("_source").is_none(),
+ "#637: scroll continuation must omit _source when the opening request set \
+ stored_fields without _source (first-page parity), got: {hit}"
+ );
+}