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(mcp): split an oversized batch _msearch instead of failing every item (#2697)
Cristian Groza406bc9186e4d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 823107650..ac831cd35 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- `xerj_batch_search` (and `xerj batch-search`): a batch whose combined `_msearch` response passes the 32 MiB cap no longer fails every item. The request is retried in halves, and only an item whose own response is over the cap fails, with `response_too_large`. (#2694)- `xerj autoindex` and `xerj autoindex map`: when the node is unreachable at a `localhost` URL, the error now also suggests the same URL with `127.0.0.1`, since the node binds the IPv4 loopback by default and `localhost` can resolve to `::1` first (seen on Windows). (#2688)- The node binds its ES-compat and REST listeners before it opens itsindices, and on plain-HTTP ports answers every request withdiff --git a/engine/crates/xerj-mcp/src/batch.rs b/engine/crates/xerj-mcp/src/batch.rsindex a153b9cec..8fd3314d1 100644--- a/engine/crates/xerj-mcp/src/batch.rs+++ b/engine/crates/xerj-mcp/src/batch.rs@@ -10,7 +10,7 @@ const MAX_RESPONSE_BYTES: usize = 32 * 1024 * 1024;pub(crate) fn spec() -> Value {json!({"name":"xerj_batch_search",- "description": "Search 1..50 IDs or questions in one call, in input order. Shares the CLI xerj batch-search adapter. Each result has its zero-based position, optional caller key, and status hits, abstain (only a complete empty search), or error. Hits carry citations: index/id plus file/line or record locator when available. This retrieves evidence, not generated answers or calibrated confidence. Use identifier plus an explicitly keyword-mapped field for exact IDs; query takes plain text or an ES query clause. One bad item never discards its siblings; identical inputs remain separate. Uses one _msearch request, plus at most one mapping read. Omitted or null max_tokens defaults to 8000 UAX #29 words and caps the entire successful JSON response using StandardTokenizer UAX #29 words, not BPE. Budgeting removes raw hit bodies, then extra hits, retaining each item's status and at least one citation per matched item. If that minimum cannot fit, returns an actionable tool error, never truncated JSON or a false abstention. Errors are not truncated.",+ "description": "Search 1..50 IDs or questions in one call, in input order. Shares the CLI xerj batch-search adapter. Each result has its zero-based position, optional caller key, and status hits, abstain (only a complete empty search), or error. Hits carry citations: index/id plus file/line or record locator when available. This retrieves evidence, not generated answers or calibrated confidence. Use identifier plus an explicitly keyword-mapped field for exact IDs; query takes plain text or an ES query clause. One bad item never discards its siblings; identical inputs remain separate. Uses one _msearch request, plus at most one mapping read; a response over 32 MiB is retried in halves, and an item still over it alone fails alone. Omitted or null max_tokens defaults to 8000 UAX #29 words and caps the entire successful JSON response using StandardTokenizer UAX #29 words, not BPE. Budgeting removes raw hit bodies, then extra hits, retaining each item's status and at least one citation per matched item. If that minimum cannot fit, returns an actionable tool error, never truncated JSON or a false abstention. Errors are not truncated.","inputSchema":{"type":"object", "additionalProperties":false,"properties":{@@ -281,7 +281,53 @@ fn item_result(base}-async fn msearch(ctx: &Ctx, ndjson: String) -> Result<Vec<Value>, String> {+/// Why one `_msearch` round trip failed. Only an oversized body is worth+/// retrying smaller; every other failure belongs to the whole request.+enum MsearchError {+ TooLarge,+ Failed(String),+}++/// #2694 — one search per entry (its header and body lines), answered in+/// entry order. A response past [`MAX_RESPONSE_BYTES`] is retried as two+/// halves, so large records cost the items that carry them, not the batch;+/// an entry still too large on its own fails alone. Any other failure fails+/// the whole call, as a single `_msearch` always did.+async fn msearch_split(+ ctx: &Ctx,+ entries: &[String],+) -> Result<Vec<Result<Value, String>>, String> {+ let mut out: Vec<Option<Result<Value, String>>> = vec![None; entries.len()];+ let mut ranges = vec![(0, entries.len())];+ while let Some((start, end)) = ranges.pop() {+ match msearch(ctx, entries[start..end].concat()).await {+ Ok(responses) if responses.len() == end - start => {+ for (slot, response) in out[start..end].iter_mut().zip(responses) {+ *slot = Some(Ok(response));+ }+ }+ Ok(_) => return Err("batch endpoint returned the wrong number of responses; item correspondence cannot be trusted".into()),+ Err(MsearchError::TooLarge) if end - start > 1 => {+ let mid = start + (end - start) / 2;+ // Popped last-in first: the lower half runs first.+ ranges.push((mid, end));+ ranges.push((start, mid));+ }+ Err(MsearchError::TooLarge) => {+ out[start] = Some(Err(+ "this item's search response alone exceeds 32 MiB; lower size or narrow the query".into(),+ ));+ }+ Err(MsearchError::Failed(e)) => return Err(e),+ }+ }+ Ok(out+ .into_iter()+ .map(|slot| slot.expect("every range is answered or split"))+ .collect())+}++async fn msearch(ctx: &Ctx, ndjson: String) -> Result<Vec<Value>, MsearchError> {let url = format!("{}/_msearch", ctx.base_url);let mut req = ctx.client@@ -291,15 +337,18 @@ async fn msearch(ctx: &Ctx, ndjson: String) -> Result<Vec<Value>, String> {if let Some(auth) = &ctx.auth {req = req.header("Authorization", auth);}- let mut resp = req- .send()- .await- .map_err(|e| crate::transport_failure_text(&ctx.base_url, &url, &e))?;+ let mut resp = req.send().await.map_err(|e| {+ MsearchError::Failed(crate::transport_failure_text(&ctx.base_url, &url, &e))+ })?;let status = resp.status();let mut bytes = Vec::new();- while let Some(chunk) = resp.chunk().await.map_err(|e| crate::error_detail(&e))? {+ while let Some(chunk) = resp+ .chunk()+ .await+ .map_err(|e| MsearchError::Failed(crate::error_detail(&e)))?+ {if bytes.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {- return Err("batch response exceeds 32 MiB; reduce size or split the batch".into());+ return Err(MsearchError::TooLarge);}bytes.extend_from_slice(&chunk);}@@ -308,17 +357,19 @@ async fn msearch(ctx: &Ctx, ndjson: String) -> Result<Vec<Value>, String> {if let Some(proxied) =crate::proxy_status_failure(&ctx.base_url, &url, status.as_u16(), &body){- return Err(proxied);+ return Err(MsearchError::Failed(proxied));}- return Err(format!("batch endpoint returned HTTP {status}: {body}"));+ return Err(MsearchError::Failed(format!(+ "batch endpoint returned HTTP {status}: {body}"+ )));}- let response: Value =- serde_json::from_slice(&bytes).map_err(|_| "batch endpoint returned invalid JSON")?;+ let response: Value = serde_json::from_slice(&bytes)+ .map_err(|_| MsearchError::Failed("batch endpoint returned invalid JSON".into()))?;response.get("responses").and_then(Value::as_array).cloned()- .ok_or_else(|| "batch endpoint returned no responses array".into())+ .ok_or_else(|| MsearchError::Failed("batch endpoint returned no responses array".into()))}/// Never discard an item's outcome to meet a budget. At least one citation@@ -418,17 +469,14 @@ pub(crate) async fn execute(ctx: &Ctx, args: &Value) -> Result<String, String> {.collect();let mut pending = Vec::new();let mut batch_error = None;- let mut ndjson = String::new();+ let mut entries = Vec::new();for (i, item) in items.iter().enumerate() {let built = validation[i].clone().and_then(|()| item_body(item, &index, size, mapping.as_ref()));match built {Ok(body) => {- ndjson.push_str(&json!({"index":index}).to_string());- ndjson.push('\n');- ndjson.push_str(&body.to_string());- ndjson.push('\n');+ entries.push(format!("{}\n{}\n", json!({"index":index}), body));pending.push(i);}Err(message) => {@@ -440,23 +488,25 @@ pub(crate) async fn execute(ctx: &Ctx, args: &Value) -> Result<String, String> {}}if !pending.is_empty() {- match msearch(ctx, ndjson).await {- Ok(responses) if responses.len() == pending.len() => {+ match msearch_split(ctx, &entries).await {+ Ok(responses) => {for (i, response) in pending.into_iter().zip(responses) {- results[i] = item_result(- results[i].clone(),- response,- &items[i],- size,- mapping.as_ref(),- );+ results[i] = match response {+ Ok(response) => item_result(+ results[i].clone(),+ response,+ &items[i],+ size,+ mapping.as_ref(),+ ),+ Err(message) => failed(+ results[i].clone(),+ json!({"reason":"response_too_large","message":message}),+ ),+ };}}- other => {- let message = match other {- Ok(_) => "batch endpoint returned the wrong number of responses; item correspondence cannot be trusted".to_string(),- Err(e) => e,- };+ Err(message) => {for i in pending {results[i] = failed(results[i].clone(),diff --git a/engine/crates/xerj-mcp/tests/batch_search.rs b/engine/crates/xerj-mcp/tests/batch_search.rsindex dd91390bb..891fedc37 100644--- a/engine/crates/xerj-mcp/tests/batch_search.rs+++ b/engine/crates/xerj-mcp/tests/batch_search.rs@@ -401,3 +401,71 @@ async fn binding_budget_counts_omitted_hits_and_keeps_the_first_citation() {<= limit);}++/// #2694: a batch whose combined `_msearch` body passes the 32 MiB cap is+/// retried in halves, so the small items still answer and only an item whose+/// own response is over the cap fails, alone.+#[tokio::test]+async fn an_oversized_msearch_is_split_and_only_the_oversized_item_fails() {+ let requests = Arc::new(Mutex::new(Vec::<usize>::new()));+ let seen = requests.clone();+ let app = Router::new().route(+ "/_msearch",+ axum::routing::post(move |text: String| {+ let lines: Vec<&str> = text.lines().collect();+ seen.lock().unwrap().push(lines.len() / 2);+ let responses: Vec<Value> = lines+ .chunks(2)+ .map(|pair| {+ // 20 MiB fits alone and two do not; 40 MiB never fits.+ let mib = if pair[1].contains("huge") {+ 40+ } else if pair[1].contains("big") {+ 20+ } else {+ 0+ };+ json!({"hits":{"total":{"value":1,"relation":"eq"},"hits":[{+ "_index":"docs","_id":format!("r{}", pair[1].len()),+ "_source":{"ax_path":"src/a.rs","body":"x".repeat(mib << 20)}}]}})+ })+ .collect();+ async move { Json(json!({ "responses": responses })) }+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let result = body(+ &call(+ &url,+ json!({"index":"docs","queries":[+ {"query":{"match":{"body":"small one"}}},+ {"query":{"match":{"body":"big one"}}},+ {"query":{"match":{"body":"big two"}}},+ {"query":{"match":{"body":"huge"}}},+ {"query":{"match":{"body":"small two"}}}+ ]}),+ )+ .await,+ );+ assert!(result.get("batch_error").is_none(), "{result}");+ let items = result["results"].as_array().unwrap();+ assert_eq!(items.len(), 5);+ for (i, item) in items.iter().enumerate() {+ assert_eq!(item["position"], i);+ if i == 3 {+ assert_eq!(item["status"], "error");+ assert_eq!(item["error"]["reason"], "response_too_large");+ } else {+ assert_eq!(item["status"], "hits", "item {i}");+ assert_eq!(item["hits"][0]["citation"]["ax_path"], "src/a.rs");+ }+ }+ // One whole try, then halves until each request fits.+ let sizes = requests.lock().unwrap().clone();+ assert_eq!(sizes[0], 5, "{sizes:?}");+ assert!(sizes.len() > 1, "{sizes:?}");+ server.abort();+ let _ = server.await;+}diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.jsonindex 6b832de6f..cd3375804 100644--- a/landing/docs/agents/schemas/mcp-tools.json+++ b/landing/docs/agents/schemas/mcp-tools.json@@ -48,7 +48,7 @@},{"name": "xerj_batch_search",- "description": "Search 1..50 IDs or questions in one call, in input order. Shares the CLI xerj batch-search adapter. Each result has its zero-based position, optional caller key, and status hits, abstain (only a complete empty search), or error. Hits carry citations: index/id plus file/line or record locator when available. This retrieves evidence, not generated answers or calibrated confidence. Use identifier plus an explicitly keyword-mapped field for exact IDs; query takes plain text or an ES query clause. One bad item never discards its siblings; identical inputs remain separate. Uses one _msearch request, plus at most one mapping read. Omitted or null max_tokens defaults to 8000 UAX #29 words and caps the entire successful JSON response using StandardTokenizer UAX #29 words, not BPE. Budgeting removes raw hit bodies, then extra hits, retaining each item's status and at least one citation per matched item. If that minimum cannot fit, returns an actionable tool error, never truncated JSON or a false abstention. Errors are not truncated.",+ "description": "Search 1..50 IDs or questions in one call, in input order. Shares the CLI xerj batch-search adapter. Each result has its zero-based position, optional caller key, and status hits, abstain (only a complete empty search), or error. Hits carry citations: index/id plus file/line or record locator when available. This retrieves evidence, not generated answers or calibrated confidence. Use identifier plus an explicitly keyword-mapped field for exact IDs; query takes plain text or an ES query clause. One bad item never discards its siblings; identical inputs remain separate. Uses one _msearch request, plus at most one mapping read; a response over 32 MiB is retried in halves, and an item still over it alone fails alone. Omitted or null max_tokens defaults to 8000 UAX #29 words and caps the entire successful JSON response using StandardTokenizer UAX #29 words, not BPE. Budgeting removes raw hit bodies, then extra hits, retaining each item's status and at least one citation per matched item. If that minimum cannot fit, returns an actionable tool error, never truncated JSON or a false abstention. Errors are not truncated.","inputSchema": {"type": "object","additionalProperties": false,