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(engine): degrade when a shard thread or merge buffer cannot be allocated (#1122) (#2315)
xerj-org3f9f9381d76b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eaabf02d1..aa1d9d309 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -82,6 +82,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0back into that map. Explicit `?pipeline=` was already unaffected([#2294](https://github.com/xerj-org/xerj/issues/2294)).+- The node no longer aborts when a helper thread or a merge buffer cannot+ be allocated (#1122). An in-process shard call starts its 8 MiB thread+ with `pthread_create` and, if the OS refuses, returns+ `could not start the shard call` without running the handler.+ `PUT /{index}/_doc/{id}` and `PUT /{index}/_create/{id}` refuse a body+ over the 8 MiB document ceiling before parsing it, the same way+ `POST /{index}/_doc` already did. A merge that cannot reserve its output+ buffer, document map, or the next survivor keeps the input segments and+ stays up. PDF and `.xls` output readers, the autoindex progress ticker,+ and the finalize-verify search use the same fallible spawn: a refusal+ fails that file, skips the ticker, or runs the search on the calling+ thread.+- `xerj autoindex` no longer aborts the node on one large JSON file (#1122).A bulk whose analysis would cross the memory watermark is rejected withHTTP 429 before the documents are parsed, so several in-flight bulks cannotdiff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex f1468b268..cc56d5e8f 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -3941,6 +3941,34 @@ fn resolve_effective_pipeline(}}+/// Parse one indexed document from raw bytes.+///+/// The size check runs before `serde_json`. `PUT /{index}/_doc/{id}` used+/// to take `Json<Value>`, which builds the DOM inside axum before the+/// handler runs. A body between the 8 MiB document ceiling and+/// `limits.max_body_bytes` (100 MiB) was parsed, then refused, and the+/// parse itself is what aborted the node under a memory cap (#1122).+/// Bytes that are not valid JSON and are also over the ceiling report the+/// size refusal, not a parse error — that is how a test can see the check+/// ran first.+pub(crate) fn parse_indexed_document_body(body: &[u8]) -> Result<Value, xerj_common::XerjError> {+ if xerj_common::document_limit::indexed_document_too_large(body.len()) {+ return Err(xerj_common::XerjError::invalid_document_json(+ xerj_common::document_limit::indexed_document_refusal(body.len()),+ ));+ }+ serde_json::from_slice(body)+ .map_err(|e| xerj_common::XerjError::invalid_query(format!("invalid JSON body: {e}")))+}++/// Serialize a document the in-process callers already hold as a [`Value`]+/// into the raw body [`index_doc`] parses. Those callers (brain edges,+/// agent memory) are small; the HTTP routes pass the request bytes through+/// unchanged.+pub(crate) fn document_body(doc: &Value) -> bytes::Bytes {+ bytes::Bytes::from(serde_json::to_vec(doc).unwrap_or_else(|_| Vec::from(&b"{}"[..])))+}+/// Fast path for `POST /{index}/_doc`: receives raw bytes to skip the axum/// JSON extractor's extra validation pass and parse directly with simd_json //// serde_json. No schema validation is performed here; the engine layer handles@@ -3951,22 +3979,9 @@ pub async fn index_doc_auto(Query(params): Query<IndexDocAutoParams>,body: bytes::Bytes,) -> impl IntoResponse {- if xerj_common::document_limit::indexed_document_too_large(body.len()) {- return ApiError::new(xerj_common::XerjError::invalid_document_json(- xerj_common::document_limit::indexed_document_refusal(body.len()),- ))- .into_response();- }- // Parse the raw body directly — avoids the axum Json extractor's extra- // content-type enforcement and serde_json::from_str double-pass.- let doc: Value = match serde_json::from_slice(&body) {+ let doc = match parse_indexed_document_body(&body) {Ok(v) => v,- Err(e) => {- return ApiError::new(xerj_common::XerjError::invalid_query(format!(- "invalid JSON body: {e}"- )))- .into_response();- }+ Err(e) => return ApiError::new(e).into_response(),};let doc = apply_ignore_malformed(&state, &index, doc);@@ -4115,8 +4130,13 @@ pub async fn index_doc(State(state): State<AppState>,Path((index, id)): Path<(String, String)>,Query(params): Query<IndexDocParams>,- Json(doc): Json<Value>,+ body: bytes::Bytes,) -> impl IntoResponse {+ // Size check before the DOM exists. See [`parse_indexed_document_body`].+ let doc = match parse_indexed_document_body(&body) {+ Ok(v) => v,+ Err(e) => return ApiError::new(e).into_response(),+ };// Apply ignore_malformed validation — remove malformed values and add// field names to _ignored[] per the index mapping. No-op when the index// has no mapping yet.@@ -4321,8 +4341,12 @@ pub async fn create_doc(State(state): State<AppState>,Path((index, id)): Path<(String, String)>,Query(params): Query<CreateDocParams>,- Json(doc): Json<Value>,+ body: bytes::Bytes,) -> impl IntoResponse {+ let doc = match parse_indexed_document_body(&body) {+ Ok(v) => v,+ Err(e) => return ApiError::new(e).into_response(),+ };// Execute ingest pipeline if one is specified (explicit `?pipeline=`) or// resolved from the index's `index.default_pipeline` setting.let effective_pipeline = resolve_effective_pipeline(&state, &index, params.pipeline.as_deref());@@ -4396,6 +4420,87 @@ pub async fn create_doc(}}+#[cfg(test)]+mod oversized_single_doc {+ use super::*;+ use axum::body::{to_bytes, Body};+ use axum::http::Request;+ use tower::ServiceExt;+ use xerj_common::config::{Config, WalSync};+ use xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES;+ use xerj_common::metrics::Metrics;+ use xerj_engine::Engine;++ fn test_state() -> AppState {+ let dir = tempfile::tempdir().expect("tempdir").keep();+ let mut config = Config::default();+ config.server.data_dir = dir.to_string_lossy().into_owned();+ config.storage.wal_sync = WalSync::Async;+ let metrics = Metrics::new().expect("metrics");+ let engine = Engine::new(config.clone()).expect("engine");+ AppState::new(config, engine, metrics)+ }++ #[test]+ fn an_oversized_body_is_refused_before_it_is_parsed() {+ let body = vec![b'x'; MAX_INDEXED_DOCUMENT_BYTES + 1];+ let err = parse_indexed_document_body(&body).unwrap_err();+ let text = err.to_string();+ assert!(+ text.contains(&MAX_INDEXED_DOCUMENT_BYTES.to_string()),+ "{text}"+ );+ assert!(text.contains("not indexed"), "{text}");+ assert!(+ !text.contains("invalid JSON"),+ "the size check must run before parse: {text}"+ );+ let small = parse_indexed_document_body(br#"{"name":"ada"}"#).unwrap();+ assert_eq!(small["name"], "ada");+ }++ #[tokio::test]+ async fn put_and_create_refuse_an_oversized_body_and_a_small_put_indexes() {+ let app = crate::router::build_es_compat_router(test_state());+ let body = vec![b'x'; MAX_INDEXED_DOCUMENT_BYTES + 1];+ for path in ["/oversize/_doc/1", "/oversize/_create/1"] {+ let response = app+ .clone()+ .oneshot(+ Request::put(path)+ .header("content-type", "application/json")+ .body(Body::from(body.clone()))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{path}");+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ let text = String::from_utf8(bytes.to_vec()).unwrap();+ assert!(+ text.contains(&MAX_INDEXED_DOCUMENT_BYTES.to_string()),+ "{path}: {text}"+ );+ assert!(text.contains("not indexed"), "{path}: {text}");+ assert!(+ !text.contains("invalid JSON"),+ "{path} parsed before the size check: {text}"+ );+ }++ let response = app+ .oneshot(+ Request::put("/oversize/_doc/ok")+ .header("content-type", "application/json")+ .body(Body::from(r#"{"name":"ada"}"#))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::CREATED);+ }+}+// ─────────────────────────────────────────────────────────────────────────────// GET /{index}/_doc/{id}?_source_includes=f1,f2&_source_excludes=f3// ─────────────────────────────────────────────────────────────────────────────diff --git a/engine/crates/xerj-api/src/graph_api.rs b/engine/crates/xerj-api/src/graph_api.rsindex 10bf1819d..b5ddb0697 100644--- a/engine/crates/xerj-api/src/graph_api.rs+++ b/engine/crates/xerj-api/src/graph_api.rs@@ -366,7 +366,7 @@ async fn ensure_edges_index(state: &AppState, brain: &str, index: &str) -> ResulState(state.clone()),Path((index.to_string(), BRAIN_META_ID.to_string())),Query(params),- Json(meta),+ es_compat::document_body(&meta),).await.into_response();@@ -557,7 +557,7 @@ pub async fn link(State(state.clone()),Path((index.clone(), id.clone())),Query(IndexDocParams::default()),- Json(doc.clone()),+ es_compat::document_body(&doc),).await.into_response();@@ -674,7 +674,7 @@ pub async fn unlink(State(state.clone()),Path((index, edge_id.clone())),Query(IndexDocParams::default()),- Json(doc),+ es_compat::document_body(&doc),).await.into_response();@@ -2121,7 +2121,7 @@ mod tests {State(state.clone()),Path((".xerj-memory-notes".to_string(), id.to_string())),Query(IndexDocParams::default()),- Json(doc),+ es_compat::document_body(&doc),).await.into_response();diff --git a/engine/crates/xerj-api/src/memory_api.rs b/engine/crates/xerj-api/src/memory_api.rsindex ef5bd28a7..0b15d01e2 100644--- a/engine/crates/xerj-api/src/memory_api.rs+++ b/engine/crates/xerj-api/src/memory_api.rs@@ -462,7 +462,7 @@ pub async fn store(State(state.clone()),Path((index.clone(), id.clone())),axum::extract::Query(IndexDocParams::default()),- Json(doc),+ es_compat::document_body(&doc),).await.into_response();diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rsindex 52e6c85c9..c0b4ff57e 100644--- a/engine/crates/xerj-autoindex/src/esclient.rs+++ b/engine/crates/xerj-autoindex/src/esclient.rs@@ -2354,12 +2354,24 @@ impl Es {let es = self.clone();let index_owned = index.to_owned();let body = body.clone();- std::thread::Builder::new()- .name("xerj-verify-search".to_owned())- .spawn(move || {+ // #1122: `Builder::spawn` panics in the child on a failed signal-stack+ // mmap after returning `Ok`. A failed `try_spawn` runs the search on+ // this thread instead: the parallel HEAD probe is the optimization,+ // and the process stays up.+ if let Err(failure) =+ xerj_common::thread_spawn::try_spawn("xerj-verify-search", move || {let _ = tx.send(es.search(&index_owned, &body));})- .context("spawn finalize-verify search")?;+ {+ if let Some(job) = failure.job {+ job();+ } else {+ anyhow::bail!(+ "could not start finalize-verify search for {index}: {}; the process stayed up",+ failure.error+ );+ }+ }loop {match rx.recv_timeout(Self::VERIFY_INDEX_POLL) {Ok(Ok(value)) => return Ok(value),diff --git a/engine/crates/xerj-autoindex/src/extract/pdf.rs b/engine/crates/xerj-autoindex/src/extract/pdf.rsindex 10b717f27..ea6b17966 100644--- a/engine/crates/xerj-autoindex/src/extract/pdf.rs+++ b/engine/crates/xerj-autoindex/src/extract/pdf.rs@@ -967,41 +967,41 @@ fn spawn_worker(path: &Path) -> Result<WorkerResponse> {// so one failed spawn here used to abort the whole run. A failed spawn// now stops the worker and fails this one file, like any other worker// start-up failure.- let out_reader = match std::thread::Builder::new()- .name("xerj-pdf-stdout".into())- .spawn(move || {+ let out_reader =+ match xerj_common::thread_spawn::try_spawn_returning("xerj-pdf-stdout", move || {let _closed = out_closed;read_capped(stdout, MAX_WORKER_OUTPUT)}) {- Ok(reader) => reader,- Err(error) => {- terminate_worker_tree(&mut child);- return Err(error).with_context(|| {- format!(- "could not start the PDF parser's output reader for {}",- path.display()- )- });- }- };- let err_reader = match std::thread::Builder::new()- .name("xerj-pdf-stderr".into())- .spawn(move || {+ Ok(reader) => reader,+ Err(failure) => {+ drop(failure.job);+ terminate_worker_tree(&mut child);+ return Err(failure.error).with_context(|| {+ format!(+ "could not start the PDF parser's output reader for {}",+ path.display()+ )+ });+ }+ };+ let err_reader =+ match xerj_common::thread_spawn::try_spawn_returning("xerj-pdf-stderr", move || {let _closed = err_closed;read_capped(stderr, MAX_WORKER_STDERR as usize)}) {- Ok(reader) => reader,- Err(error) => {- terminate_worker_tree(&mut child);- let _ = out_reader.join();- return Err(error).with_context(|| {- format!(- "could not start the PDF parser's error reader for {}",- path.display()- )- });- }- };+ Ok(reader) => reader,+ Err(failure) => {+ drop(failure.job);+ terminate_worker_tree(&mut child);+ let _ = out_reader.join();+ return Err(failure.error).with_context(|| {+ format!(+ "could not start the PDF parser's error reader for {}",+ path.display()+ )+ });+ }+ };let started = Instant::now();let timeout = Duration::from_secs(WORKER_TIMEOUT_SECS.load(Ordering::Relaxed));diff --git a/engine/crates/xerj-autoindex/src/extract/xls.rs b/engine/crates/xerj-autoindex/src/extract/xls.rsindex aa787c51e..9aa40c542 100644--- a/engine/crates/xerj-autoindex/src/extract/xls.rs+++ b/engine/crates/xerj-autoindex/src/extract/xls.rs@@ -362,22 +362,23 @@ fn run_worker(// #1122: `std::thread::spawn` panics when a thread cannot be created and// release builds are panic=abort; a failed spawn stops the worker and// fails this one file instead of aborting the run.- let reader = match std::thread::Builder::new()- .name("xerj-xls-stdout".into())- .spawn(move || read_capped(stdout, MAX_WORKER_OUTPUT))- {- Ok(reader) => reader,- Err(error) => {- kill_group(pid);- let _ = child.wait();- return Err(error).with_context(|| {- format!(- "could not start the .xls reader's output thread for {}",- path.display()- )- });- }- };+ let reader =+ match xerj_common::thread_spawn::try_spawn_returning("xerj-xls-stdout", move || {+ read_capped(stdout, MAX_WORKER_OUTPUT)+ }) {+ Ok(reader) => reader,+ Err(failure) => {+ drop(failure.job);+ kill_group(pid);+ let _ = child.wait();+ return Err(failure.error).with_context(|| {+ format!(+ "could not start the .xls reader's output thread for {}",+ path.display()+ )+ });+ }+ };let started = std::time::Instant::now();let status = loop {diff --git a/engine/crates/xerj-autoindex/src/progress.rs b/engine/crates/xerj-autoindex/src/progress.rsindex 41b6ebc33..a47d628d4 100644--- a/engine/crates/xerj-autoindex/src/progress.rs+++ b/engine/crates/xerj-autoindex/src/progress.rs@@ -948,42 +948,44 @@ impl Progress {}let progress = Arc::clone(self);let interval = self.interval;- let handle = std::thread::Builder::new()- .name("autoindex-progress".into())- .spawn(move || {- // Hold the guard across the loop and test the flag BEFORE- // waiting. A condvar notification reaches only threads already- // parked in `wait`, so a `stop()` that lands while this thread- // is anywhere else — above all before its very first wait — is- // delivered to nobody and is gone. Re-checking the predicate- // under the lock is what makes it impossible to miss: the flag- // is set under the same mutex, so either we see it here or we- // are already parked and the notify wakes us.- //- // Getting this wrong is not a latency detail. `Ticker::drop`- // joins this thread, so a lost stop turns every early exit —- // `es.ping()` refused, `no-files`, a small `--dry-run` — into a- // full `--progress-interval` of silence AFTER the terminal line- // has printed, and `--progress-interval 3600` makes that an- // hour.- let mut stopped = progress.stopped.lock().unwrap();- while !*stopped {- let (guard, _timeout) = progress- .wake- .wait_timeout(stopped, interval)- .expect("progress ticker mutex poisoned");- stopped = guard;- if *stopped {- break;- }- // Never emit while holding `stopped`: `stop()` would block- // behind a write to a slow pipe.- drop(stopped);- progress.emit();- stopped = progress.stopped.lock().unwrap();+ // #1122: `Builder::spawn` returns `Ok` and then panics in the child+ // when the alternate signal stack cannot be mapped. `.ok()` only+ // sees the `Err` from `pthread_create`. `try_spawn` does not install+ // that stack, so a refusal is a missing ticker, not a dead process.+ let handle = xerj_common::thread_spawn::try_spawn("autoindex-progress", move || {+ // Hold the guard across the loop and test the flag BEFORE+ // waiting. A condvar notification reaches only threads already+ // parked in `wait`, so a `stop()` that lands while this thread+ // is anywhere else — above all before its very first wait — is+ // delivered to nobody and is gone. Re-checking the predicate+ // under the lock is what makes it impossible to miss: the flag+ // is set under the same mutex, so either we see it here or we+ // are already parked and the notify wakes us.+ //+ // Getting this wrong is not a latency detail. `Ticker::drop`+ // joins this thread, so a lost stop turns every early exit —+ // `es.ping()` refused, `no-files`, a small `--dry-run` — into a+ // full `--progress-interval` of silence AFTER the terminal line+ // has printed, and `--progress-interval 3600` makes that an+ // hour.+ let mut stopped = progress.stopped.lock().unwrap();+ while !*stopped {+ let (guard, _timeout) = progress+ .wake+ .wait_timeout(stopped, interval)+ .expect("progress ticker mutex poisoned");+ stopped = guard;+ if *stopped {+ break;}- })- .ok();+ // Never emit while holding `stopped`: `stop()` would block+ // behind a write to a slow pipe.+ drop(stopped);+ progress.emit();+ stopped = progress.stopped.lock().unwrap();+ }+ })+ .ok();Ticker {progress: Arc::clone(self),handle,@@ -1063,7 +1065,7 @@ impl Drop for WatchGuard<'_> {/// called `finish` — closes the stream with an honest `ok=false` line.pub struct Ticker {progress: Arc<Progress>,- handle: Option<std::thread::JoinHandle<()>>,+ handle: Option<xerj_common::thread_spawn::SpawnedThread>,}impl Drop for Ticker {diff --git a/engine/crates/xerj-cluster/src/shard.rs b/engine/crates/xerj-cluster/src/shard.rsindex 7606749cd..9eff4d724 100644--- a/engine/crates/xerj-cluster/src/shard.rs+++ b/engine/crates/xerj-cluster/src/shard.rs@@ -318,6 +318,29 @@ impl MemoryShardDir {}}+/// Stack reserved for one in-process shard call. Smaller than this overflows+/// `search_impl`'s future; `std::thread` at this size is the sigaltstack+/// abort #1122 hit.+const SHARD_CALL_STACK_BYTES: usize = 8 * 1024 * 1024;++/// Map a spawn that did not happen into the error the HTTP caller sees.+///+/// The job is dropped. Running it on the caller's stack is the overflow+/// this thread exists to avoid, and dropping it does not write the document.+pub(crate) fn map_shard_spawn_failure<F>(+ to: &str,+ failure: xerj_common::thread_spawn::SpawnFailure<F>,+) -> ShardError {+ let error = failure.error;+ drop(failure.job);+ ShardError::Unavailable {+ to: to.to_string(),+ reason: format!(+ "could not start the shard call: {error}; the node stayed up and this call was not run"+ ),+ }+}+/// In-process [`ShardRpc`]. A call runs the target's handler on a fresh/// stack and waits for it.///@@ -328,6 +351,12 @@ impl MemoryShardDir {/// index-visibility guard is intentionally not carried across: a TCP handler/// has none, and an absent guard is how cluster-internal replica stores stay/// reachable.+///+/// The thread is 8 MiB and is started with [`xerj_common::thread_spawn`], not+/// `std::thread::Builder`. Builder returns `Ok` and then panics in the child+/// when the alternate signal stack cannot be mapped; with `panic = "abort"`+/// that kills the node (#1122). A failed spawn answers the caller and does+/// not run the handler on this stack.pub struct MemoryShardRpc {node_id: String,dir: Arc<MemoryShardDir>,@@ -355,21 +384,25 @@ impl ShardRpc for MemoryShardRpc {let runtime = tokio::runtime::Handle::current();let (tx, rx) = tokio::sync::oneshot::channel();let target = to.to_string();- std::thread::Builder::new()- .name("xerj-shard".into())- .stack_size(8 * 1024 * 1024)- .spawn(move || {+ let handle = match xerj_common::thread_spawn::try_spawn_stack(+ "xerj-shard",+ SHARD_CALL_STACK_BYTES,+ move || {let result = runtime.block_on(handler.handle(op));let _ = tx.send(result);- })- .map_err(|err| ShardError::Unavailable {- to: target.clone(),- reason: format!("could not start the shard call: {err}"),- })?;- rx.await.map_err(|_| ShardError::Unavailable {+ },+ ) {+ Ok(handle) => handle,+ Err(failure) => return Err(map_shard_spawn_failure(&target, failure)),+ };+ let received = rx.await.map_err(|_| ShardError::Unavailable {to: target,reason: "shard call stopped before answering".to_string(),- })+ });+ // Reap the helper. It has already sent (or dropped the sender);+ // join does not run the handler again.+ drop(handle);+ received}fn set_handler(&self, handler: Arc<dyn ShardHandler>) {@@ -459,4 +492,81 @@ mod tests {}]);}++ /// #1122: `std::thread::Builder::spawn` panics in the child when the+ /// alternate signal stack cannot be mapped (os error 12), after the+ /// parent has been told the thread exists. The shard call must surface+ /// that as [`ShardError`] and must not run the handler.+ #[test]+ fn a_shard_call_that_cannot_spawn_is_an_error_and_does_not_run() {+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::Arc;+ use xerj_common::thread_spawn::{try_spawn_with, Spawn, SpawnedThread};++ struct Refuse;++ impl Spawn for Refuse {+ fn spawn(+ &self,+ _name: &str,+ job: xerj_common::thread_spawn::BoxedJob,+ ) -> std::io::Result<SpawnedThread> {+ drop(job);+ Err(std::io::Error::from_raw_os_error(12))+ }+ }++ let ran = Arc::new(AtomicBool::new(false));+ let job_ran = Arc::clone(&ran);+ let failure = try_spawn_with(&Refuse, true, "xerj-shard", move || {+ job_ran.store(true, Ordering::SeqCst);+ })+ .expect_err("spawn refused");+ let err = super::map_shard_spawn_failure("n2", failure);+ assert!(+ !ran.load(Ordering::SeqCst),+ "handler ran after a failed spawn"+ );+ let text = err.to_string();+ assert!(text.contains("n2"), "{text}");+ assert!(text.contains("could not start the shard call"), "{text}");+ assert!(text.contains("stayed up"), "{text}");+ assert!(+ text.contains("12") || text.contains("Cannot allocate memory"),+ "{text}"+ );+ }++ struct EchoHandler;++ #[async_trait::async_trait]+ impl ShardHandler for EchoHandler {+ async fn handle(&self, op: ShardOp) -> ShardResult {+ ShardResult::http(200, format!("{op:?}"))+ }+ }++ #[tokio::test]+ async fn an_in_process_shard_call_runs_the_handler_on_the_helper_stack() {+ let dir = MemoryShardDir::new();+ let rpc = MemoryShardRpc::new("n1", Arc::clone(&dir));+ rpc.set_handler(Arc::new(EchoHandler));+ let result = rpc+ .call(+ "n1",+ ShardOp::GetDoc {+ index: "orders".into(),+ id: "1".into(),+ source: None,+ source_includes: None,+ source_excludes: None,+ replica: false,+ shard: 0,+ },+ )+ .await+ .expect("spawn and call");+ assert_eq!(result.status, 200);+ assert!(result.body.contains("orders"), "{}", result.body);+ }}diff --git a/engine/crates/xerj-common/src/thread_spawn.rs b/engine/crates/xerj-common/src/thread_spawn.rsindex 4450ab56b..5d87e38bd 100644--- a/engine/crates/xerj-common/src/thread_spawn.rs+++ b/engine/crates/xerj-common/src/thread_spawn.rs@@ -96,7 +96,32 @@ impl Spawn for StdSpawn {}#[cfg(not(unix))]{- spawn_std(name, job)+ spawn_std(name, job, None)+ }+ }+}++/// [`StdSpawn`] with an explicit stack reservation.+///+/// The in-process shard call needs 8 MiB: a search future overflows the+/// 2 MiB helper stack. On Unix this still uses `pthread_create`, so a+/// stack the OS will not reserve is an `Err` instead of a panic inside+/// the child after `Builder::spawn` has already returned `Ok` (#1122).+#[derive(Debug, Clone, Copy)]+pub struct StackSpawn {+ pub stack_bytes: usize,+}++impl Spawn for StackSpawn {+ fn spawn(&self, name: &str, job: BoxedJob) -> io::Result<SpawnedThread> {+ #[cfg(unix)]+ {+ let _ = name;+ spawn_pthread_with_stack(job, self.stack_bytes)+ }+ #[cfg(not(unix))]+ {+ spawn_std(name, job, Some(self.stack_bytes))}}}@@ -263,6 +288,107 @@ wheretry_spawn_with(&StdSpawn, true, name, f)}+/// [`try_spawn`] with an explicit stack size.+///+/// Used by the in-process shard call, whose handler does not fit on the+/// 2 MiB helper stack. A refused or failed spawn returns the job; the+/// caller must not run that job on its own stack (that is the overflow+/// the extra stack exists to avoid). Drop it and answer the client.+pub fn try_spawn_stack<F>(+ name: &str,+ stack_bytes: usize,+ f: F,+) -> Result<SpawnedThread, SpawnFailure<F>>+where+ F: FnOnce() + Send + 'static,+{+ try_spawn_with(&StackSpawn { stack_bytes }, spawn_allowed(), name, f)+}++/// A thread whose job returns a value.+///+/// [`Spawn`] jobs return `()`. Callers that need the result (a pipe+/// reader) send it through a channel. [`join`](Self::join) waits for the+/// thread and then for that value.+pub struct JoinedThread<T> {+ handle: SpawnedThread,+ rx: std::sync::mpsc::Receiver<T>,+}++impl<T> std::fmt::Debug for JoinedThread<T> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("JoinedThread").finish_non_exhaustive()+ }+}++impl<T> JoinedThread<T> {+ /// Wait for the job to finish and return its value.+ ///+ /// `Err` means the thread ended without sending a value (it panicked+ /// on an unwind build, where the panic is caught at the `extern "C"`+ /// boundary). On the release profile a panic aborts the process before+ /// this returns.+ pub fn join(self) -> std::thread::Result<T> {+ self.handle.join()?;+ self.rx.recv().map_err(|_| {+ Box::new(io::Error::other("helper thread ended without a result"))+ as Box<dyn std::any::Any + Send>+ })+ }+}++/// [`try_spawn`] for a job that returns `T`.+///+/// Failure hands `f` back unrun, the same contract as [`try_spawn`]. The+/// success path is one extra channel send of `T` after the job returns.+pub fn try_spawn_returning<T, F>(name: &str, f: F) -> Result<JoinedThread<T>, SpawnFailure<F>>+where+ T: Send + 'static,+ F: FnOnce() -> T + Send + 'static,+{+ try_spawn_returning_with(&StdSpawn, spawn_allowed(), name, f)+}++/// [`try_spawn_returning`] with an explicit spawner and gate verdict.+pub fn try_spawn_returning_with<S, T, F>(+ spawner: &S,+ allowed: bool,+ name: &str,+ f: F,+) -> Result<JoinedThread<T>, SpawnFailure<F>>+where+ S: Spawn + ?Sized,+ T: Send + 'static,+ F: FnOnce() -> T + Send + 'static,+{+ let (tx, rx) = std::sync::mpsc::channel();+ let slot = Arc::new(Mutex::new(Some(f)));+ let thread_slot = Arc::clone(&slot);+ match try_spawn_with(spawner, allowed, name, move || {+ let job = thread_slot+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .take();+ if let Some(job) = job {+ let _ = tx.send(job());+ }+ }) {+ Ok(handle) => Ok(JoinedThread { handle, rx }),+ Err(failure) => {+ // The wrapper did not run, so `f` is still in the slot.+ drop(failure.job);+ let job = slot+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .take();+ Err(SpawnFailure {+ error: failure.error,+ job,+ })+ }+ }+}+/// [`try_spawn`] with an explicit spawner and gate verdict (for tests and/// callers that already sampled the gate).pub fn try_spawn_with<S, F>(@@ -434,6 +560,11 @@ impl Drop for AttrGuard {#[cfg(unix)]fn spawn_pthread(job: BoxedJob) -> io::Result<SpawnedThread> {+ spawn_pthread_with_stack(job, HELPER_STACK_BYTES)+}++#[cfg(unix)]+fn spawn_pthread_with_stack(job: BoxedJob, stack_bytes: usize) -> io::Result<SpawnedThread> {// A second box so the fat pointer of `dyn FnOnce` survives the trip// through `pthread_create`'s thin `void*`. This is the same shape std// uses. The allocation is the caller's job box plus this one; if it@@ -455,7 +586,7 @@ fn spawn_pthread(job: BoxedJob) -> io::Result<SpawnedThread> {// SAFETY: `attr` is initialized. Failure leaves the platform default// stack; pthread_create still returns an error if that cannot be reserved.unsafe {- let _ = libc::pthread_attr_setstacksize(&mut attr.0, HELPER_STACK_BYTES);+ let _ = libc::pthread_attr_setstacksize(&mut attr.0, stack_bytes);}let mut thread = std::mem::MaybeUninit::<libc::pthread_t>::uninit();@@ -508,13 +639,15 @@ fn run_job(job: BoxedJob) {}#[cfg(not(unix))]-fn spawn_std(name: &str, job: BoxedJob) -> io::Result<SpawnedThread> {+fn spawn_std(name: &str, job: BoxedJob, stack_bytes: Option<usize>) -> io::Result<SpawnedThread> {// Windows (and any other non-Unix target) has no sigaltstack mmap.// `CreateThread` failure is an `Err` from `Builder::spawn`, which is// the degrade path. A global-allocator abort is out of scope here.- let handle = std::thread::Builder::new()- .name(name.to_owned())- .spawn(job)?;+ let mut builder = std::thread::Builder::new().name(name.to_owned());+ if let Some(stack_bytes) = stack_bytes {+ builder = builder.stack_size(stack_bytes);+ }+ let handle = builder.spawn(job)?;Ok(SpawnedThread {inner: SpawnedInner::Std(Some(handle)),})@@ -661,6 +794,60 @@ mod tests {);}+ /// The in-process shard call reserves 8 MiB. That reservation must not+ /// go through `std::thread::Builder`: the child's sigaltstack mmap is+ /// what aborted the node, and an 8 MiB stack is a larger mmap than the+ /// 2 MiB helper.+ #[cfg(unix)]+ #[test]+ fn an_eight_mebibyte_stack_does_not_install_an_alternate_signal_stack() {+ let (tx, rx) = std::sync::mpsc::channel();+ let handle = try_spawn_with(+ &StackSpawn {+ stack_bytes: 8 * 1024 * 1024,+ },+ true,+ "xerj-shard",+ move || {+ tx.send(alternate_signal_stack_flags()).unwrap();+ },+ )+ .expect("8 MiB stack spawn");+ handle.join().unwrap();+ let (rc, flags) = rx.recv().unwrap();+ assert_eq!(rc, 0, "sigaltstack query failed");+ assert_ne!(+ flags & libc::SS_DISABLE,+ 0,+ "shard helper installed an alternate signal stack"+ );+ }++ #[test]+ fn a_returning_spawn_yields_the_value_and_a_failure_returns_the_job() {+ let handle = try_spawn_returning("xerj-t1122-ret", || 7u32).expect("spawn");+ assert_eq!(handle.join().expect("join"), 7);++ let ran = Arc::new(AtomicUsize::new(0));+ let job_ran = Arc::clone(&ran);+ let failure = try_spawn_returning_with(&FlakySpawn::new(1), true, "xerj-pdf-stdout", {+ let job_ran = Arc::clone(&job_ran);+ move || {+ job_ran.fetch_add(1, Ordering::SeqCst);+ 9u32+ }+ })+ .expect_err("spawner fails");+ assert_eq!(failure.error.raw_os_error(), Some(libc::EAGAIN));+ assert_eq!(+ ran.load(Ordering::SeqCst),+ 0,+ "the job did not run on a thread"+ );+ assert_eq!((failure.job.expect("job handed back"))(), 9);+ assert_eq!(ran.load(Ordering::SeqCst), 1);+ }+#[test]fn dropping_the_handle_detaches_and_the_job_still_runs() {let (tx, rx) = std::sync::mpsc::channel();diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex f9b1d8d2a..0248ee6d1 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -11125,9 +11125,10 @@ impl Index {// Process-wide admission: disk flood-stage block (item 3) + parent// memory circuit breaker (item 1). Fires before any per-index work.self.governor_write_gate()?;- // Already-parsed bodies (PUT `/_doc/{id}` builds a `Value` in the- // extractor) still have to be refused before semantic embedding and- // `analyze_doc`. Bulk NDJSON is refused on the raw bytes earlier.+ // Bodies that arrived already parsed (in-process callers, a pipeline+ // rewrite) still have to be refused before semantic embedding and+ // `analyze_doc`. HTTP `PUT`/`POST /_doc` and bulk NDJSON are refused+ // on the raw bytes earlier.if let Some(seen) =xerj_common::document_limit::json_value_exceeds_indexed_document_limit(&source){@@ -13678,8 +13679,27 @@ impl Index {let mut min_seq = u64::MAX;let mut max_seq = 0u64;- let mut merged_json_buf: Vec<u8> = Vec::with_capacity(60 * 1024 * 1024);- merged_json_buf.push(b'[');+ // #1122: `Vec::with_capacity(60 MiB)` aborts the process+ // when the allocator refuses (`memory allocation of N+ // bytes failed`, no panic line). `try_reserve` of the+ // same 60 MiB keeps the success path and turns a refusal+ // into an aborted batch. Inputs stay on disk.+ let mut merged_json_buf: Vec<u8> = Vec::new();+ if let Err(error) = crate::merge_reserve::reserve_merge_output_buffer(+ &mut merged_json_buf,+ crate::merge_reserve::MERGE_OUTPUT_RESERVE_BYTES,+ ) {+ tracing::error!("{error}");+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }+ if let Err(error) =+ crate::merge_reserve::extend_merge_output(&mut merged_json_buf, b"[")+ {+ tracing::error!("{error}");+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }let mut first_doc = true;let mut live_doc_count: u64 = 0;@@ -13903,8 +13923,21 @@ impl Index {// The FTS/doc-values ordinal space of a segment is the// order of its stored documents, so the map is exactly as- // long as this vector.- doc_maps[source_index] = vec![None; raw_docs.len()];+ // long as this vector. `vec![None; n]` aborts if that+ // allocation is refused (#1122); `try_reserve` does not.+ let mut ordinals = Vec::new();+ if ordinals.try_reserve(raw_docs.len()).is_err() {+ tracing::error!(+ ?seg_path,+ docs = raw_docs.len(),+ "merge aborted: not enough memory to reserve the document map; \+ input segments were preserved and the node stayed up"+ );+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }+ ordinals.resize(raw_docs.len(), None);+ doc_maps[source_index] = ordinals;for (source_ordinal, raw) in raw_docs.iter().enumerate() {let raw_str = raw.get();let id_seq: IdSeq = match serde_json::from_str(raw_str) {@@ -13934,14 +13967,23 @@ impl Index {}// Survives — hold (seq, id, raw) for the global- // _seq_no-ordered build below.- survivors.push((- id_seq.seq_no,- id_seq.id.to_string(),- raw_str.to_string(),- source_index as u32,- source_ordinal as u32,- ));+ // _seq_no-ordered build below. Growth is fallible:+ // `push` aborts the process when the allocator+ // refuses (#1122).+ if let Err(error) = crate::merge_reserve::try_push_merge(+ &mut survivors,+ (+ id_seq.seq_no,+ id_seq.id.to_string(),+ raw_str.to_string(),+ source_index as u32,+ source_ordinal as u32,+ ),+ ) {+ tracing::error!("{error}");+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }survivor_bytes = survivor_bytes.saturating_add(raw_str.len()+ id_seq.id.len()@@ -13971,14 +14013,35 @@ impl Index {let mut fts_input_bytes: usize = 0;for (seq_no, id_str, raw_str, source_index, source_ordinal) in survivors {if !first_doc {- merged_json_buf.push(b',');+ if let Err(error) = crate::merge_reserve::extend_merge_output(+ &mut merged_json_buf,+ b",",+ ) {+ tracing::error!("{error}");+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }}first_doc = false;- merged_json_buf.extend_from_slice(raw_str.as_bytes());+ if let Err(error) = crate::merge_reserve::extend_merge_output(+ &mut merged_json_buf,+ raw_str.as_bytes(),+ ) {+ tracing::error!("{error}");+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }live_doc_count += 1;// The .ids side-car must cover every stored doc// (alignment invariant, see above).- ids_pairs.push((seq_no, id_str.clone()));+ if let Err(error) = crate::merge_reserve::try_push_merge(+ &mut ids_pairs,+ (seq_no, id_str.clone()),+ ) {+ tracing::error!("{error}");+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }// Per-doc Value parse for FTS / DV builders.//@@ -14024,7 +14087,13 @@ impl Index {doc_value.get("_source").unwrap_or(&Value::Null),));}- fts_input.push((id_str, fields, source));+ if let Err(error) =+ crate::merge_reserve::try_push_merge(&mut fts_input, (id_str, fields, source))+ {+ tracing::error!("{error}");+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }// Sampled checkpoints every 8192 drained docs: the// survivor set shrinks as `merged_json_buf` and// `fts_input` grow, so the crossover IS the batch's@@ -14050,7 +14119,13 @@ impl Index {if live_doc_count == 0 {return None;}- merged_json_buf.push(b']');+ if let Err(error) =+ crate::merge_reserve::extend_merge_output(&mut merged_json_buf, b"]")+ {+ tracing::error!("{error}");+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }crate::ingest_memory::observe_checkpoint(crate::ingest_memory::Category::MergeJsonBuffer,merged_json_buf.len(),@@ -14762,9 +14837,10 @@ impl Index {return Err(EngineError::Common(xerj_common::XerjError::internal(format!("merge pass aborted {failed} batch(es): an input segment could not \- be fully read or the output could not be written; input segments \- were preserved (no documents dropped, {merged_batches} other \- batch(es) merged)"+ be fully read, the output could not be written, or there was not \+ enough memory to build the merged segment; input segments \+ were preserved (no documents dropped, the node stayed up, \+ {merged_batches} other batch(es) merged)"),)));}diff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rsindex ddeaabc43..bde8b93c3 100644--- a/engine/crates/xerj-engine/src/lib.rs+++ b/engine/crates/xerj-engine/src/lib.rs@@ -30,6 +30,7 @@ pub mod index_guard;pub mod ingest_memory;pub mod lifecycle;pub mod memtable;+mod merge_reserve;mod node_lock;pub mod painless;pub mod pools;diff --git a/engine/crates/xerj-engine/src/merge_reserve.rs b/engine/crates/xerj-engine/src/merge_reserve.rsnew file mode 100644index 000000000..f8b4f580f--- /dev/null+++ b/engine/crates/xerj-engine/src/merge_reserve.rs@@ -0,0 +1,92 @@+//! Fallible reserves for one merge batch (#1122).+//!+//! `Vec::with_capacity` and `Vec::push` abort the process when the+//! allocator refuses (`memory allocation of N bytes failed`, then+//! `abort`). That message is not a Rust panic, so a merge that hits it+//! ends the log mid-INFO and the node is gone. These helpers use+//! `try_reserve`. On the success path the same bytes are reserved; on+//! failure the caller keeps the input segments and the process stays up.++use std::collections::TryReserveError;++/// Bytes reserved up front for one merge's concatenated stored JSON.+///+/// This is the capacity the merge used to request with `with_capacity`.+/// It stays the same so a merge that fits does not grow the buffer in+/// smaller steps.+pub const MERGE_OUTPUT_RESERVE_BYTES: usize = 60 * 1024 * 1024;++fn refused(bytes: usize, err: TryReserveError) -> String {+ format!(+ "merge aborted: not enough memory to reserve {bytes} bytes ({err}); \+ input segments were preserved and the node stayed up"+ )+}++/// Reserve `bytes` on `buf`. Does not abort when the allocator refuses.+pub fn reserve_merge_output_buffer(buf: &mut Vec<u8>, bytes: usize) -> Result<(), String> {+ buf.try_reserve(bytes).map_err(|err| refused(bytes, err))+}++/// Append `extra`, reserving first. An empty slice does not reserve.+pub fn extend_merge_output(buf: &mut Vec<u8>, extra: &[u8]) -> Result<(), String> {+ if extra.is_empty() {+ return Ok(());+ }+ buf.try_reserve(extra.len())+ .map_err(|err| refused(extra.len(), err))?;+ buf.extend_from_slice(extra);+ Ok(())+}++/// Push `value`, growing with `try_reserve` when the vec is full.+///+/// When `len < capacity` this is one comparison and a [`Vec::push`] that+/// does not allocate, the same as a push into a pre-reserved vec.+pub fn try_push_merge<T>(vec: &mut Vec<T>, value: T) -> Result<(), String> {+ if vec.len() == vec.capacity() {+ vec.try_reserve(1).map_err(|err| refused(1, err))?;+ }+ vec.push(value);+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_up_front_reserve_is_the_old_sixty_mebibyte_capacity() {+ assert_eq!(MERGE_OUTPUT_RESERVE_BYTES, 60 * 1024 * 1024);+ }++ #[test]+ fn a_reserve_the_allocator_refuses_is_an_error_and_leaves_the_buffer() {+ let mut buf = Vec::<u8>::new();+ buf.extend_from_slice(b"[");+ let err = reserve_merge_output_buffer(&mut buf, usize::MAX).unwrap_err();+ assert!(err.contains("not enough memory"), "{err}");+ assert!(err.contains("node stayed up"), "{err}");+ assert!(err.contains(&usize::MAX.to_string()), "{err}");+ assert_eq!(buf, b"[", "a refused reserve must not clear what was kept");+ }++ #[test]+ fn a_reserve_that_fits_is_the_same_capacity_with_capacity_would_take() {+ let mut buf = Vec::<u8>::new();+ reserve_merge_output_buffer(&mut buf, 64).unwrap();+ assert!(buf.capacity() >= 64);+ extend_merge_output(&mut buf, b"[").unwrap();+ extend_merge_output(&mut buf, b"").unwrap();+ assert_eq!(buf, b"[");+ }++ #[test]+ fn a_merge_vec_grows_without_aborting_and_keeps_order() {+ let mut docs = Vec::<u32>::new();+ try_push_merge(&mut docs, 1).unwrap();+ try_push_merge(&mut docs, 2).unwrap();+ try_push_merge(&mut docs, 3).unwrap();+ assert_eq!(docs, vec![1, 2, 3]);+ }+}