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 helper thread cannot be created (#1122) (#2226)
xerj-org3a0fd82abd42
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e8675d25b..061baf267 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- A best-effort helper thread that cannot be created no longer aborts the+ process. On Unix those threads are started with `pthread_create` and do not+ map an alternate signal stack, so the allocation failure that used to panic+ inside the child (`failed to allocate an alternative stack`, os error 12)+ comes back as an error. Drain-free drops the generation on the caller; pool+ work runs inline; WAL fsync, background merge, and the ingest-memory trace+ skip the thread and retry or stay off; share-tunnel and ONNX init fail that+ startup step. Each site logs once. `panic = "abort"` is unchanged+ ([#1122](https://github.com/xerj-org/xerj/issues/1122)).+- `xerj corpus add <name> <local-path>` copies the checkout's root`.xerjignore` into the clone when that file is untracked or has uncommittededits. `git clone` only checks out committed files, so the ignore file wasdiff --git a/engine/crates/xerj-ai/src/embedder.rs b/engine/crates/xerj-ai/src/embedder.rsindex 29c51c0e9..3f8c8c1dc 100644--- a/engine/crates/xerj-ai/src/embedder.rs+++ b/engine/crates/xerj-ai/src/embedder.rs@@ -85,54 +85,58 @@ impl<T: Send + Sync + 'static> CancellationSafeInit<T> {let worker_name = thread_name.clone();let started = std::time::Instant::now();tracing::info!(%thread_name, "ONNX lazy initialization scheduled");- let spawn = std::thread::Builder::new()- .name(thread_name.clone())- .spawn(move || {- let mut completion = InitCompletionGuard {- shared: std::sync::Arc::clone(&shared),- armed: true,- };- let result =- std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match load() {- Ok(value) => Ok(std::sync::Arc::new(value)),- Err(error) => Err(std::sync::Arc::<str>::from(format!("{error:#}"))),- }))- .unwrap_or_else(|payload| {- let detail = if let Some(message) = payload.downcast_ref::<&str>() {- (*message).to_string()- } else if let Some(message) = payload.downcast_ref::<String>() {- message.clone()- } else {- "non-string panic payload".to_string()- };- Err(std::sync::Arc::<str>::from(format!(- "ONNX initialization loader panicked: {detail}"- )))- });- let elapsed_ms = started.elapsed().as_millis();- let _ = shared.result.set(result);- shared.notify.notify_waiters();- completion.armed = false;-- let published = shared- .result- .get()- .expect("initialization result was just published");- match published {- Ok(_) => tracing::info!(- thread_name = %worker_name,- elapsed_ms,- "ONNX lazy initialization completed"- ),- Err(error) => tracing::error!(- thread_name = %worker_name,- elapsed_ms,- %error,- "ONNX lazy initialization failed"- ),- }- });- if let Err(error) = spawn {+ // #1122: Builder::spawn panics in the child when the alternate+ // signal stack cannot be mapped (`panic = "abort"` kills the+ // node). A failed spawn publishes the error on the same path+ // an `Err` from pthread_create already took.+ let spawn = xerj_common::thread_spawn::try_spawn_unguarded(&thread_name, move || {+ let mut completion = InitCompletionGuard {+ shared: std::sync::Arc::clone(&shared),+ armed: true,+ };+ let result =+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match load() {+ Ok(value) => Ok(std::sync::Arc::new(value)),+ Err(error) => Err(std::sync::Arc::<str>::from(format!("{error:#}"))),+ }))+ .unwrap_or_else(|payload| {+ let detail = if let Some(message) = payload.downcast_ref::<&str>() {+ (*message).to_string()+ } else if let Some(message) = payload.downcast_ref::<String>() {+ message.clone()+ } else {+ "non-string panic payload".to_string()+ };+ Err(std::sync::Arc::<str>::from(format!(+ "ONNX initialization loader panicked: {detail}"+ )))+ });+ let elapsed_ms = started.elapsed().as_millis();+ let _ = shared.result.set(result);+ shared.notify.notify_waiters();+ completion.armed = false;++ let published = shared+ .result+ .get()+ .expect("initialization result was just published");+ match published {+ Ok(_) => tracing::info!(+ thread_name = %worker_name,+ elapsed_ms,+ "ONNX lazy initialization completed"+ ),+ Err(error) => tracing::error!(+ thread_name = %worker_name,+ elapsed_ms,+ %error,+ "ONNX lazy initialization failed"+ ),+ }+ });+ if let Err(failure) = spawn {+ let error = failure.error;+ drop(failure.job);let error = std::sync::Arc::<str>::from(format!("spawn ONNX initialization thread {thread_name}: {error}"));diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rsindex c3ac48892..922500907 100644--- a/engine/crates/xerj-common/src/lib.rs+++ b/engine/crates/xerj-common/src/lib.rs@@ -33,8 +33,10 @@//! - [`xccode`] — the reference-coding semantics shared by `xerj code`,//! `xerj corpus`, and the `xerj_code_search` MCP tool (issue #977)//! - [`thread_spawn`] — spawning helper threads without aborting the node-//! on a failed spawn (#1122): the closure comes back, plus a process-wide-//! memory spawn gate+//! on a failed spawn (#1122): Unix threads are created with `pthread_create`+//! so a signal-stack allocation failure is an error instead of a panic in+//! the child, the closure comes back, and a process-wide memory spawn gate+//! skips best-effort spawns once the breaker is engaged//! - [`hub`] — Corpus Hub v2 shared types: the catalogue, pack manifest,//! definition record, and the [`hub::Answer`] every surface renders (#1374)diff --git a/engine/crates/xerj-common/src/thread_spawn.rs b/engine/crates/xerj-common/src/thread_spawn.rsindex e4435e893..4450ab56b 100644--- a/engine/crates/xerj-common/src/thread_spawn.rs+++ b/engine/crates/xerj-common/src/thread_spawn.rs@@ -1,29 +1,45 @@//! Spawning helper threads without taking the node down (#1122).//!-//! The shipped release profile is `panic = "abort"`, so every way a thread-//! spawn can panic is a whole-node outage:+//! The shipped release profile is `panic = "abort"`, so a panic on any thread+//! is a whole-node outage. Two different failures look the same from the+//! outside://!-//! * `std::thread::spawn` is `Builder::spawn(..).expect(..)` — an `EAGAIN`-//! from `pthread_create` (thread or memory limit) aborts the process;-//! * `Builder::spawn` returns that `Err`, but std then **panics inside the-//! new thread** when it cannot mmap the thread's alternate signal stack-//! under memory exhaustion — a failure the caller can never observe.+//! * `std::thread::spawn` is `Builder::spawn(..).expect(..)`. An `EAGAIN`+//! from `pthread_create` (thread or memory limit) aborts the process.+//! `Builder::spawn` itself returns that `Err`.+//! * On Unix, `Builder::spawn` then **panics inside the new thread** when it+//! cannot mmap the alternate signal stack (`failed to allocate an+//! alternative stack: os error 12`). The parent already observed `Ok`.+//! With `panic = "abort"` that child panic is not catchable.//!-//! The first is handled by returning the error, and — because-//! `Builder::spawn` consumes and drops the closure on failure — by handing-//! the closure *back* in [`SpawnFailure::job`], so the caller can run it-//! inline, retry, or drop it deliberately. The second can only be avoided by-//! not spawning while memory is exhausted: a process-wide spawn gate (the-//! engine installs its governor's RSS-watermark check through-//! [`install_spawn_gate`]) refuses the spawn up front, with the same-//! hand-back.+//! [`StdSpawn`] does not use `std::thread::Builder` on Unix. It calls+//! `pthread_create` directly and runs the job on that thread, so a stack+//! that cannot be reserved comes back as [`SpawnFailure`] and the child+//! never executes std's signal-stack setup. Windows has no alternate-stack+//! mmap; `CreateThread` failure is already an `Err` from `Builder::spawn`.+//! The global allocator aborting on its own (`memory allocation of N bytes+//! failed`) is a different failure and is not what this module handles.//!-//! The actual spawn goes through the [`Spawn`] trait so the failure paths are-//! unit-testable without exhausting a real machine.+//! Because `Builder::spawn` / a failed `pthread_create` drops the closure,+//! the closure is handed *back* in [`SpawnFailure::job`] so the caller can+//! run it inline, retry, or drop it. Dropping it is the right degrade for+//! an infinite worker loop; running it is the right degrade for a finite+//! job such as freeing a memtable generation.+//!+//! [`try_spawn`] also consults a process-wide spawn gate (the engine+//! installs its governor's RSS-watermark check through+//! [`install_spawn_gate`]). That gate is a backstop: once the breaker is+//! already engaged, a best-effort spawn is not attempted at all. It is not+//! a substitute for the non-panicking spawn. Threads that must be tried+//! even above the watermark (the governor itself, WAL fsync) use+//! [`try_spawn_unguarded`] and still get an `Err` instead of an abort.+//!+//! The actual spawn goes through the [`Spawn`] trait so the failure paths+//! are unit-testable without exhausting a real machine.use std::io;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex, OnceLock};-use std::thread::JoinHandle;use std::time::Duration;/// A process-wide "is it safe to spawn a thread right now?" predicate.@@ -52,18 +68,125 @@ pub type BoxedJob = Box<dyn FnOnce() + Send + 'static>;/// inject a spawner that fails.pub trait Spawn {/// Start `job` on a new thread called `name`.- fn spawn(&self, name: &str, job: BoxedJob) -> io::Result<JoinHandle<()>>;+ ///+ /// Failure to create the thread, including a failure while reserving its+ /// stack, is an `Err`. This must not panic: with `panic = "abort"` a+ /// panic here, or in the new thread before `job` runs, kills the process.+ fn spawn(&self, name: &str, job: BoxedJob) -> io::Result<SpawnedThread>;}-/// `std::thread::Builder` with a thread name.+/// `pthread_create` on Unix, `std::thread::Builder` elsewhere.+///+/// Unix does not go through `std::thread`. That path panics in the child+/// when the alternate signal stack cannot be mapped, after the parent has+/// already been told the thread exists (#1122).#[derive(Debug, Clone, Copy, Default)]pub struct StdSpawn;impl Spawn for StdSpawn {- fn spawn(&self, name: &str, job: BoxedJob) -> io::Result<JoinHandle<()>> {- std::thread::Builder::new()- .name(name.to_string())- .spawn(job)+ fn spawn(&self, name: &str, job: BoxedJob) -> io::Result<SpawnedThread> {+ #[cfg(unix)]+ {+ // The OS name is applied on the new thread by the wrapper+ // `try_spawn_with` builds, before `job` runs. `std::thread`+ // would do that itself and then panic if the signal stack+ // cannot be mapped.+ let _ = name;+ spawn_pthread(job)+ }+ #[cfg(not(unix))]+ {+ spawn_std(name, job)+ }+ }+}++/// A thread started by [`Spawn::spawn`]. Dropping it detaches; [`join`](Self::join)+/// waits. There is no `std::thread::JoinHandle` on Unix because that type+/// only exists for threads std started, and those are the ones that panic+/// while mapping a signal stack.+pub struct SpawnedThread {+ inner: SpawnedInner,+}++impl std::fmt::Debug for SpawnedThread {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("SpawnedThread { .. }")+ }+}++enum SpawnedInner {+ #[cfg(unix)]+ Raw {+ thread: libc::pthread_t,+ joined: bool,+ },+ #[cfg(not(unix))]+ Std(Option<std::thread::JoinHandle<()>>),+ /// Spawn was refused or failed and the caller still needs a handle that+ /// `join`s immediately (a background loop that never started).+ Inert,+}++impl SpawnedThread {+ /// A handle for a thread that was never started. [`join`](Self::join)+ /// returns immediately.+ pub fn inert() -> Self {+ Self {+ inner: SpawnedInner::Inert,+ }+ }++ /// Wait for the thread to finish.+ ///+ /// A panic inside the job aborts the process on the release profile+ /// (`panic = "abort"`). On unwind builds the panic is caught at the+ /// `extern "C"` boundary so it cannot unwind into C; `join` then+ /// returns `Ok` and the panic hook has already printed it. Callers+ /// that detach (the normal best-effort path) do not observe it.+ pub fn join(mut self) -> std::thread::Result<()> {+ self.join_inner()+ }++ fn join_inner(&mut self) -> std::thread::Result<()> {+ match &mut self.inner {+ #[cfg(unix)]+ SpawnedInner::Raw { thread, joined } => {+ if !*joined {+ *joined = true;+ // SAFETY: `thread` came from a successful pthread_create+ // in this process, and this is the only join or detach.+ let rc = unsafe { libc::pthread_join(*thread, std::ptr::null_mut()) };+ if rc != 0 {+ return Err(Box::new(io::Error::from_raw_os_error(rc)));+ }+ }+ Ok(())+ }+ #[cfg(not(unix))]+ SpawnedInner::Std(handle) => match handle.take() {+ Some(handle) => handle.join(),+ None => Ok(()),+ },+ SpawnedInner::Inert => Ok(()),+ }+ }+}++impl Drop for SpawnedThread {+ fn drop(&mut self) {+ #[cfg(unix)]+ if let SpawnedInner::Raw { thread, joined } = &mut self.inner {+ if !*joined {+ *joined = true;+ // SAFETY: `thread` came from a successful pthread_create in+ // this process, and join has not been called. Detach is what+ // dropping a `JoinHandle` does for a std thread.+ unsafe {+ libc::pthread_detach(*thread);+ }+ }+ }}}@@ -93,26 +216,53 @@ impl<F> std::fmt::Display for SpawnFailure<F> {}}+/// Log one degradation for `once`. Hot paths (every memtable publish, every+/// pool call) must not emit a line per failed attempt. Returns whether this+/// call logged.+pub fn warn_best_effort_degraded(once: &AtomicBool, name: &str, error: &io::Error) -> bool {+ if once.swap(true, Ordering::Relaxed) {+ return false;+ }+ tracing::warn!(+ thread = name,+ error = %error,+ "best-effort helper thread was not started; degrading instead of aborting the process (#1122)"+ );+ true+}+/// The error a gate refusal carries.fn gate_refused(name: &str) -> io::Error {io::Error::new(io::ErrorKind::OutOfMemory,format!("not spawning thread {name}: memory is at the governor watermark, \- and a spawn under memory exhaustion aborts the process (#1122)"+ so this best-effort spawn is skipped (#1122)"),)}/// Spawn a named thread, honouring the process-wide spawn gate. Never/// panics on spawn failure; see [`SpawnFailure`].-pub fn try_spawn<F>(name: &str, f: F) -> Result<JoinHandle<()>, SpawnFailure<F>>+pub fn try_spawn<F>(name: &str, f: F) -> Result<SpawnedThread, SpawnFailure<F>>whereF: FnOnce() + Send + 'static,{try_spawn_with(&StdSpawn, spawn_allowed(), name, f)}+/// [`try_spawn`] without the watermark gate.+///+/// For threads that should still be attempted when RSS is already high+/// (the governor, a WAL fsync worker). A real OS failure is still an+/// `Err` with the job handed back — it does not abort.+pub fn try_spawn_unguarded<F>(name: &str, f: F) -> Result<SpawnedThread, SpawnFailure<F>>+where+ F: FnOnce() + Send + 'static,+{+ try_spawn_with(&StdSpawn, true, name, f)+}+/// [`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>(@@ -120,7 +270,7 @@ pub fn try_spawn_with<S, F>(allowed: bool,name: &str,f: F,-) -> Result<JoinHandle<()>, SpawnFailure<F>>+) -> Result<SpawnedThread, SpawnFailure<F>>whereS: Spawn + ?Sized,F: FnOnce() + Send + 'static,@@ -136,7 +286,14 @@ where// though the spawner dropped the boxed wrapper.let slot = Arc::new(Mutex::new(Some(f)));let thread_slot = Arc::clone(&slot);+ #[cfg(unix)]+ let comm = os_comm_name(name);let wrapper: BoxedJob = Box::new(move || {+ // Before the caller's job, so a panic in the job still shows the+ // OS thread name. std would have set this and then mmap'd a signal+ // stack; that mmap is the panic #1122 hit.+ #[cfg(unix)]+ set_os_name(&comm);let job = thread_slot.lock().unwrap_or_else(|poisoned| poisoned.into_inner())@@ -167,7 +324,7 @@ pub fn spawn_with_retry<F>(attempts: u32,backoff: Duration,f: F,-) -> Result<JoinHandle<()>, SpawnFailure<F>>+) -> Result<SpawnedThread, SpawnFailure<F>>whereF: FnOnce() + Send + 'static,{@@ -182,7 +339,7 @@ pub fn spawn_with_retry_using<S, G, F>(attempts: u32,backoff: Duration,f: F,-) -> Result<JoinHandle<()>, SpawnFailure<F>>+) -> Result<SpawnedThread, SpawnFailure<F>>whereS: Spawn + ?Sized,G: Fn() -> bool,@@ -214,10 +371,159 @@ where}}+/// Linux `TASK_COMM_LEN`, including the trailing NUL. `std::thread` truncates+/// to the same width for the OS name; the full name still goes in our logs.+#[cfg(unix)]+fn os_comm_name(name: &str) -> [u8; 16] {+ let mut buf = [0u8; 16];+ let bytes = if name.is_empty() {+ b"xerj".as_slice()+ } else {+ name.as_bytes()+ };+ let n = bytes.len().min(15);+ buf[..n].copy_from_slice(&bytes[..n]);+ buf+}++#[cfg(unix)]+fn set_os_name(bytes: &[u8; 16]) {+ #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]+ {+ // SAFETY: `bytes` is NUL-terminated (index 15 is never written) and+ // the C string is only read for the duration of the setname call.+ let name = unsafe { std::ffi::CStr::from_ptr(bytes.as_ptr().cast()) };+ #[cfg(any(target_os = "linux", target_os = "android"))]+ unsafe {+ // SAFETY: `name` is a NUL-terminated C string. Setting the+ // calling thread's name cannot fail the spawn.+ let _ = libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());+ }+ #[cfg(target_os = "macos")]+ unsafe {+ // SAFETY: same as Linux, but Darwin's setter only names the+ // calling thread and takes no `pthread_t`.+ let _ = libc::pthread_setname_np(name.as_ptr());+ }+ }+ #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "macos")))]+ {+ let _ = bytes;+ }+}++/// Same default std uses for a spawned thread (`2 MiB` on Tier-1). A larger+/// stack would reserve more address space than the path this replaces,+/// which is the opposite of what a memory-pressure spawn should do.+#[cfg(unix)]+const HELPER_STACK_BYTES: usize = 2 * 1024 * 1024;++#[cfg(unix)]+struct AttrGuard(libc::pthread_attr_t);++#[cfg(unix)]+impl Drop for AttrGuard {+ fn drop(&mut self) {+ // SAFETY: the guard is built only after `pthread_attr_init` returned+ // 0, and nothing else destroys this attribute.+ unsafe {+ libc::pthread_attr_destroy(&mut self.0);+ }+ }+}++#[cfg(unix)]+fn spawn_pthread(job: BoxedJob) -> 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+ // fails, the global allocator aborts — that is every Rust allocation,+ // not the signal-stack panic this function exists to avoid.+ let job = Box::new(job);+ let job_ptr = Box::into_raw(job);++ let mut attr = std::mem::MaybeUninit::<libc::pthread_attr_t>::uninit();+ // SAFETY: `attr` is a valid out-pointer for pthread_attr_init.+ let rc = unsafe { libc::pthread_attr_init(attr.as_mut_ptr()) };+ if rc != 0 {+ // SAFETY: the new thread was not created, so it did not take the box.+ drop(unsafe { Box::from_raw(job_ptr) });+ return Err(io::Error::from_raw_os_error(rc));+ }+ // SAFETY: pthread_attr_init returned 0, so the attribute is initialized.+ let mut attr = AttrGuard(unsafe { attr.assume_init() });+ // 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 mut thread = std::mem::MaybeUninit::<libc::pthread_t>::uninit();+ // SAFETY: `attr` is initialized; `thread_main` has the C ABI and frees+ // `job_ptr` exactly once. On failure the thread did not start and the+ // pointer is freed below.+ let rc = unsafe {+ libc::pthread_create(+ thread.as_mut_ptr(),+ &attr.0,+ thread_main,+ job_ptr.cast::<libc::c_void>(),+ )+ };+ drop(attr);+ if rc != 0 {+ // SAFETY: pthread_create failed, so `thread_main` will not run.+ drop(unsafe { Box::from_raw(job_ptr) });+ return Err(io::Error::from_raw_os_error(rc));+ }+ // SAFETY: pthread_create returned 0, so `thread` was written.+ let thread = unsafe { thread.assume_init() };+ Ok(SpawnedThread {+ inner: SpawnedInner::Raw {+ thread,+ joined: false,+ },+ })+}++#[cfg(unix)]+extern "C" fn thread_main(ptr: *mut libc::c_void) -> *mut libc::c_void {+ // SAFETY: the parent leaked this box into pthread_create, and this+ // thread is the unique consumer. The closure is `Send`.+ let job = unsafe { Box::from_raw(ptr.cast::<BoxedJob>()) };+ run_job(*job);+ std::ptr::null_mut()+}++#[cfg(unix)]+fn run_job(job: BoxedJob) {+ // Unwinding out of `extern "C"` is undefined. Release builds abort+ // inside the job (`panic = "abort"`) and never reach the catch.+ // Unwind builds (tests) catch so a panicked helper cannot cross the+ // C boundary; the panic hook has already printed.+ #[cfg(panic = "unwind")]+ let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job));+ #[cfg(not(panic = "unwind"))]+ job();+}++#[cfg(not(unix))]+fn spawn_std(name: &str, job: BoxedJob) -> 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)?;+ Ok(SpawnedThread {+ inner: SpawnedInner::Std(Some(handle)),+ })+}+#[cfg(test)]mod tests {use super::*;- use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};+ use std::sync::atomic::{AtomicU32, AtomicUsize};/// Fails the first `fail_first` spawns with EAGAIN, then spawns for real.struct FlakySpawn {@@ -235,7 +541,7 @@ mod tests {}impl Spawn for FlakySpawn {- fn spawn(&self, name: &str, job: BoxedJob) -> io::Result<JoinHandle<()>> {+ fn spawn(&self, name: &str, job: BoxedJob) -> io::Result<SpawnedThread> {let call = self.calls.fetch_add(1, Ordering::SeqCst);if call < self.fail_first {drop(job); // exactly what Builder::spawn does on failure@@ -245,6 +551,19 @@ mod tests {}}+ /// Models the failure std reports only by panicking in the child:+ /// the alternate-signal-stack mmap returns ENOMEM (os error 12).+ /// The production spawner must surface that as `Err` with the job+ /// handed back, so the caller can drop it inline and keep running.+ struct SigaltstackEnomem;++ impl Spawn for SigaltstackEnomem {+ fn spawn(&self, _name: &str, job: BoxedJob) -> io::Result<SpawnedThread> {+ drop(job);+ Err(io::Error::from_raw_os_error(12))+ }+ }+#[test]fn a_failed_spawn_returns_the_job_instead_of_panicking() {let ran = Arc::new(AtomicUsize::new(0));@@ -260,6 +579,26 @@ mod tests {assert_eq!(ran.load(Ordering::SeqCst), 1);}+ #[test]+ fn an_enomem_setup_failure_returns_the_job_instead_of_panicking() {+ let ran = Arc::new(AtomicUsize::new(0));+ let job_ran = Arc::clone(&ran);+ let failure = try_spawn_with(&SigaltstackEnomem, true, "xerj-drain-free", move || {+ job_ran.fetch_add(1, Ordering::SeqCst);+ })+ .expect_err("setup failure is an Err, not a panic");+ assert_eq!(failure.error.raw_os_error(), Some(12));+ assert_eq!(+ ran.load(Ordering::SeqCst),+ 0,+ "the job did not run on a thread"+ );+ // Drain-free drops the job (the capture's destructors free the+ // memtable). Pools run it inline. Either degrade keeps the process up.+ (failure.job.expect("job handed back"))();+ assert_eq!(ran.load(Ordering::SeqCst), 1);+ }+#[test]fn a_closed_gate_refuses_without_calling_the_spawner() {let spawner = FlakySpawn::new(0);@@ -273,8 +612,7 @@ mod tests {fn a_successful_spawn_runs_the_job_once_on_the_named_thread() {let (tx, rx) = std::sync::mpsc::channel();let handle = try_spawn_with(&StdSpawn, true, "xerj-t1122", move || {- let name = std::thread::current().name().map(str::to_string);- tx.send(name).unwrap();+ tx.send(helper_thread_name()).unwrap();}).expect("spawn");handle.join().unwrap();@@ -282,6 +620,67 @@ mod tests {assert!(rx.try_recv().is_err(), "ran exactly once");}+ #[cfg(unix)]+ #[test]+ fn a_spawned_helper_does_not_install_an_alternate_signal_stack() {+ // #1122: std::thread::Builder's child calls+ // `stack_overflow::Handler::new`, which mmap's an alternate signal+ // stack and panics on ENOMEM. The parent has already been returned+ // `Ok`, and `panic = "abort"` turns that into SIGABRT. A helper+ // thread must not install that stack, so the failure mode cannot+ // happen. A std thread in this process does install one (the test+ // binary left SIGSEGV at SIG_DFL, so std's handler is active); this+ // assertion is false for `Builder::spawn`.+ let (tx, rx) = std::sync::mpsc::channel();+ let handle = try_spawn_with(&StdSpawn, true, "xerj-drain-free", move || {+ tx.send(alternate_signal_stack_flags()).unwrap();+ })+ .expect("spawn");+ handle.join().unwrap();+ let (rc, flags) = rx.recv().unwrap();+ assert_eq!(rc, 0, "sigaltstack query failed");+ assert_ne!(+ flags & libc::SS_DISABLE,+ 0,+ "helper installed an alternate signal stack; an ENOMEM mmap of it \+ panics inside the child and aborts the process (#1122)"+ );++ // The same process's std threads do install one. If they did not,+ // this test would pass for `Builder::spawn` too and would not be a+ // regression test for the panic.+ let (std_rc, std_flags) = std::thread::spawn(alternate_signal_stack_flags)+ .join()+ .unwrap();+ assert_eq!(std_rc, 0, "sigaltstack query failed on a std thread");+ assert_eq!(+ std_flags & libc::SS_DISABLE,+ 0,+ "std::thread did not install an alternate signal stack in this \+ process, so the assertion above cannot tell the two spawners apart"+ );+ }++ #[test]+ fn dropping_the_handle_detaches_and_the_job_still_runs() {+ let (tx, rx) = std::sync::mpsc::channel();+ let handle = try_spawn_with(&StdSpawn, true, "xerj-t1122", move || {+ tx.send(()).unwrap();+ })+ .expect("spawn");+ drop(handle);+ rx.recv_timeout(Duration::from_secs(2))+ .expect("detached thread ran the job");+ }++ #[test]+ fn degradation_is_logged_once_per_flag() {+ let once = AtomicBool::new(false);+ let error = io::Error::from_raw_os_error(12);+ assert!(warn_best_effort_degraded(&once, "xerj-drain-free", &error));+ assert!(!warn_best_effort_degraded(&once, "xerj-drain-free", &error));+ }+#[test]fn retry_rides_out_transient_failures() {let spawner = FlakySpawn::new(2);@@ -336,4 +735,37 @@ mod tests {assert_eq!(gate_calls.load(Ordering::SeqCst), 2);assert_eq!(spawner.calls.load(Ordering::SeqCst), 1);}++ /// `(rc, ss_flags)` from `sigaltstack`. `SS_DISABLE` set means the+ /// thread has no alternate signal stack — the mapping `std::thread`+ /// panics on if it cannot be created.+ #[cfg(unix)]+ fn alternate_signal_stack_flags() -> (libc::c_int, libc::c_int) {+ let mut stack = unsafe { std::mem::zeroed::<libc::stack_t>() };+ // SAFETY: a null current-stack pointer only reads the calling+ // thread's alternate signal stack into `stack`.+ let rc = unsafe { libc::sigaltstack(std::ptr::null(), &mut stack) };+ (rc, stack.ss_flags)+ }++ fn helper_thread_name() -> Option<String> {+ #[cfg(any(target_os = "linux", target_os = "macos"))]+ {+ let mut buf = [0u8; 64];+ // SAFETY: `buf` is writable for `buf.len()` bytes and is+ // NUL-terminated by pthread_getname_np on success.+ let rc = unsafe {+ libc::pthread_getname_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len())+ };+ if rc != 0 {+ return None;+ }+ let end = buf.iter().position(|byte| *byte == 0).unwrap_or(buf.len());+ String::from_utf8(buf[..end].to_vec()).ok()+ }+ #[cfg(not(any(target_os = "linux", target_os = "macos")))]+ {+ std::thread::current().name().map(str::to_owned)+ }+ }}diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex af70af5d1..27883c2bd 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -5376,7 +5376,7 @@ mod governor_thread_spawn_tests {&self,_name: &str,_job: BoxedJob,- ) -> std::io::Result<std::thread::JoinHandle<()>> {+ ) -> std::io::Result<xerj_common::thread_spawn::SpawnedThread> {Err(std::io::Error::from_raw_os_error(libc::EAGAIN))}}diff --git a/engine/crates/xerj-engine/src/governor.rs b/engine/crates/xerj-engine/src/governor.rsindex 3d89b8e70..26b73fb9e 100644--- a/engine/crates/xerj-engine/src/governor.rs+++ b/engine/crates/xerj-engine/src/governor.rs@@ -190,14 +190,16 @@ impl ResourceGovernor {self.memory_tripped.load(Ordering::Relaxed)}- /// Whether it is safe to spawn a helper thread right now (#1122).+ /// Whether it is safe to spawn a best-effort helper thread right now (#1122).///- /// `std::thread::Builder::spawn` **panics** — it does not return `Err` —- /// when the new thread's alternate signal stack cannot be mmap'd under- /// memory exhaustion, and the shipped profile is `panic = "abort"`, so one- /// ENOMEM at spawn time aborts the whole node. Callers on flush/publish- /// paths that have an inline fallback must check this and take the- /// fallback instead of spawning.+ /// `std::thread::Builder::spawn` panics inside the new thread when the+ /// alternate signal stack cannot be mmap'd, and the shipped profile is+ /// `panic = "abort"`, so that panic aborts the node. The engine's helper+ /// spawner does not use that path (a failed `pthread_create` is an+ /// `Err`), and this gate skips the attempt entirely once the breaker is+ /// engaged so a flush storm does not keep reserving stacks. Callers on+ /// flush/publish paths that have an inline fallback must check this and+ /// take the fallback instead of spawning.////// Reads the *live* RSS (`current_rss_bytes`), not the sampler's last/// value, so an RSS spike between samples cannot sneak a spawn through;diff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rsindex dee45dc2f..1115db6e4 100644--- a/engine/crates/xerj-engine/src/lib.rs+++ b/engine/crates/xerj-engine/src/lib.rs@@ -93,7 +93,11 @@ pub fn engine_metrics() -> Option<&'static std::sync::Arc<xerj_common::metrics::// A pool that cannot be started does not abort the process (#1122). Release// builds are `panic = "abort"`, and the old `.build().expect(..)` turned an// `EAGAIN` from `pthread_create` into a dead node at the moment the machine-// was already out of threads. The call runs on the calling thread instead,+// was already out of threads. Workers are started with+// `pools::safe_rayon_spawn` rather than `std::thread::Builder`: std panics+// inside the new thread when its alternate signal stack cannot be mapped,+// after `build()` has already been told the thread exists, so the `Err`+// fallback never got to run. The call runs on the calling thread instead,// and the next call tries to start the pool again.static INGEST_POOL: std::sync::OnceLock<rayon::ThreadPool> = std::sync::OnceLock::new();@@ -124,6 +128,7 @@ pub(crate) fn ingest_pool() -> pools::PoolCall {rayon::ThreadPoolBuilder::new().num_threads(threads.max(1)).thread_name(|i| format!("xerj-ingest-{i}"))+ .spawn_handler(crate::pools::safe_rayon_spawn)// nice(5): bulk parse/analyze/insert are request-latency// sensitive for the WRITER, but under mixed load they were// the biggest nice(0) CPU block competing head-to-head with@@ -173,6 +178,7 @@ pub(crate) fn background_pool() -> pools::PoolCall {rayon::ThreadPoolBuilder::new().num_threads(threads.max(1)).thread_name(|i| format!("xerj-bg-{i}"))+ .spawn_handler(crate::pools::safe_rayon_spawn).start_handler(|_| {xerj_common::resource::deprioritize_current_thread(xerj_common::resource::Deprioritize::Background,@@ -215,6 +221,7 @@ pub(crate) fn merge_pool() -> pools::PoolCall {rayon::ThreadPoolBuilder::new().num_threads(threads.max(1)).thread_name(|i| format!("xerj-merge-{i}"))+ .spawn_handler(crate::pools::safe_rayon_spawn).start_handler(|_| {xerj_common::resource::deprioritize_current_thread(xerj_common::resource::Deprioritize::Maintenance,diff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rsindex ba8a97bca..f945853dd 100644--- a/engine/crates/xerj-engine/src/memtable.rs+++ b/engine/crates/xerj-engine/src/memtable.rs@@ -6,7 +6,7 @@//! store for O(N) term/range/agg queries without JSON parsing per document.use std::collections::HashMap;-use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::Arc;use std::sync::OnceLock;@@ -2826,18 +2826,25 @@ impl FrozenClaim {)});// Free the dead generations off the publish critical path. If- // thread spawn fails the Arcs drop inline: same correctness, we- // only lose the async-free optimisation. #1122: std PANICS when- // the new thread's alternate signal stack cannot be allocated, and- // the shipped profile is panic=abort, so under memory pressure the- // spawn is not attempted at all — the Arcs drop inline right here,- // on the same fallback path the comment always intended.- // `try_spawn` consults the governor's spawn gate (installed by- // `governor::init`) and hands the job back on a refusal or a failed- // spawn; dropping the returned job frees the Arcs inline.+ // the thread cannot be created — the governor watermark is already+ // engaged, `pthread_create` fails, or (the #1122 failure) the new+ // thread's stack cannot be reserved — the Arcs drop inline: same+ // correctness, we only lose the async-free optimisation. The spawn+ // itself must not panic: std panics *inside* the child when its+ // alternate signal stack cannot be mapped, and the release profile+ // is panic=abort, so that one allocation used to kill the node.+ // `try_spawn` uses a non-panicking spawn and hands the job back;+ // dropping the job frees the Arcs on this thread. Logged once so a+ // flush storm under pressure does not emit a line per generation.+ static DRAIN_FREE_DEGRADED: AtomicBool = AtomicBool::new(false);if let Err(failure) =xerj_common::thread_spawn::try_spawn("xerj-drain-free", move || drop(dead)){+ xerj_common::thread_spawn::warn_best_effort_degraded(+ &DRAIN_FREE_DEGRADED,+ "xerj-drain-free",+ &failure.error,+ );drop(failure.job);}guarddiff --git a/engine/crates/xerj-engine/src/pools.rs b/engine/crates/xerj-engine/src/pools.rsindex f968a72f8..37345d7f4 100644--- a/engine/crates/xerj-engine/src/pools.rs+++ b/engine/crates/xerj-engine/src/pools.rs@@ -16,6 +16,7 @@//! unchanged; what changes is that the knobs now do what they say.use std::cell::RefCell;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Mutex, OnceLock};use rayon::{ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder};@@ -120,6 +121,7 @@ fn install_search_pool(threads: usize) {if let Err(err) = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("xerj-search-{i}"))+ .spawn_handler(safe_rayon_spawn).build_global(){let actual = rayon::current_num_threads();@@ -211,9 +213,11 @@ pub(crate) fn spawn_or_inline(None => match xerj_common::thread_spawn::try_spawn(label, op) {Ok(_) => {}Err(failure) => {- tracing::error!(- "could not spawn a {label} worker ({}); running it on the calling thread (#1122)",- failure.error+ static LOGGED: AtomicBool = AtomicBool::new(false);+ xerj_common::thread_spawn::warn_best_effort_degraded(+ &LOGGED,+ label,+ &failure.error,);if let Some(job) = failure.job {job();@@ -244,33 +248,71 @@ fn ensure_pool<'a>(let width = threads.max(1);let pool = match build(width) {Ok(pool) => pool,- Err(err) if width > 1 => {- tracing::error!(- "could not start the {label} pool with {width} threads ({err}); \- retrying with one thread (#1122)"- );- match build(1) {- Ok(pool) => pool,- Err(err) => {- tracing::error!(- "could not start the {label} pool ({err}); \+ Err(err) if width > 1 => match build(1) {+ Ok(pool) => {+ log_pool_degraded_once(|| {+ format!(+ "could not start the {label} pool with {width} threads ({err}); \+ using one thread (#1122)"+ )+ });+ pool+ }+ Err(retry) => {+ log_pool_degraded_once(|| {+ format!(+ "could not start the {label} pool ({err}; one-thread retry: {retry}); \this call runs on the calling thread (#1122)"- );- return None;- }+ )+ });+ return None;}- }+ },Err(err) => {- tracing::error!(- "could not start the {label} pool ({err}); \- this call runs on the calling thread (#1122)"- );+ log_pool_degraded_once(|| {+ format!(+ "could not start the {label} pool ({err}); \+ this call runs on the calling thread (#1122)"+ )+ });return None;}};Some(slot.get_or_init(|| pool))}+/// One line per process. A pool that cannot start is retried on the next+/// call; logging every call floods the node that is already out of threads.+fn log_pool_degraded_once(message: impl FnOnce() -> String) {+ static LOGGED: AtomicBool = AtomicBool::new(false);+ if LOGGED.swap(true, Ordering::Relaxed) {+ return;+ }+ tracing::error!("{}", message());+}++/// Rayon worker spawn that cannot abort the process (#1122).+///+/// Rayon's default handler is `std::thread::Builder::spawn`. That returns+/// `Ok` before the child maps its alternate signal stack, and the mmap+/// failure panics in the child. `panic = "abort"` then kills the node+/// during pool build, so the `Err` fallback in [`ensure_pool`] never runs.+/// This handler uses the same non-panicking spawn as the other best-effort+/// threads. The watermark gate is not consulted: these pools are built once+/// and a soft RSS watermark must not refuse them the way it refuses a+/// drain-free thread. A real `pthread_create` failure is an `Err`, which+/// fails the build and lets the caller run inline.+pub(crate) fn safe_rayon_spawn(thread: rayon::ThreadBuilder) -> std::io::Result<()> {+ let name = thread.name().unwrap_or("xerj-rayon").to_owned();+ match xerj_common::thread_spawn::try_spawn_unguarded(&name, move || thread.run()) {+ Ok(_detached) => Ok(()),+ Err(failure) => {+ drop(failure.job);+ Err(failure.error)+ }+ }+}+/// Run `op`, and every `par_iter` inside it, on the calling thread.////// Calling `op()` directly would not do that: a `par_iter` on a thread that@@ -415,4 +457,23 @@ mod tests {assert!(ran.is_ok(), "the spawned job must run");assert!(slot.get().is_none());}++ /// #1122: production pools spawn workers through `safe_rayon_spawn`,+ /// not `std::thread::Builder`. The work has to actually run — a spawn+ /// handler that detaches wrong, or that never calls `ThreadBuilder::run`,+ /// would hang `install` or drop the job.+ #[test]+ fn the_safe_rayon_spawner_runs_pool_work() {+ let pool = ThreadPoolBuilder::new()+ .num_threads(2)+ .thread_name(|i| format!("xerj-t1122-{i}"))+ .spawn_handler(super::safe_rayon_spawn)+ .build()+ .expect("safe spawner starts a pool");+ let sum = pool.install(|| {+ use rayon::prelude::*;+ (0..64u32).into_par_iter().sum::<u32>()+ });+ assert_eq!(sum, (0..64u32).sum::<u32>());+ }}diff --git a/engine/crates/xerj-server/src/debug_profiling.rs b/engine/crates/xerj-server/src/debug_profiling.rsindex 03b693b8a..30b47804f 100644--- a/engine/crates/xerj-server/src/debug_profiling.rs+++ b/engine/crates/xerj-server/src/debug_profiling.rs@@ -14,8 +14,8 @@ use std::io::{self, Write};use std::os::unix::fs::OpenOptionsExt;use std::path::{Path, PathBuf};use std::sync::{Arc, Condvar, Mutex};-use std::thread::JoinHandle;use std::time::Duration;+use xerj_common::thread_spawn::SpawnedThread;use anyhow::{anyhow, Context, Result};use pprof::protos::Message;@@ -120,7 +120,7 @@ fn parse_duration(name: &str, value: Option<&str>) -> Result<Option<u64>> {}pub struct ProfileRuntime {- workers: Vec<JoinHandle<()>>,+ workers: Vec<SpawnedThread>,stop: Arc<(Mutex<bool>, Condvar)>,lock_path: Option<PathBuf>,_lock: File,@@ -150,6 +150,21 @@ pub fn spawn() -> Result<Option<ProfileRuntime>> {spawn_configured(config).map(Some)}+/// #1122: `std::thread::Builder::spawn` panics inside the child when the+/// alternate signal stack cannot be mapped, and the release profile is+/// `panic = "abort"`. A profile worker that cannot be created fails this+/// startup step with an error instead of aborting the process.+fn spawn_profile_thread<F>(name: &'static str, job: F) -> Result<SpawnedThread>+where+ F: FnOnce() + Send + 'static,+{+ xerj_common::thread_spawn::try_spawn_unguarded(name, job).map_err(|failure| {+ let error = failure.error;+ drop(failure.job);+ anyhow!("spawn {name} worker: {error}")+ })+}+fn spawn_configured(config: Config) -> Result<ProfileRuntime> {let lock_path = config.output_dir.join(".xerj-debug-profile.lock");let lock = OpenOptions::new()@@ -175,39 +190,34 @@ fn spawn_configured(config: Config) -> Result<ProfileRuntime> {let stop = Arc::clone(&runtime.stop);let frequency = config.cpu_hz;let delay = config.delay_seconds;- runtime.workers.push(- std::thread::Builder::new()- .name("xerj-debug-cpu-profile".into())- .spawn(move || {- if wait_for_duration_or_stop(&stop, Duration::from_secs(delay)) {- return;- }- if let Err(error) = capture_cpu(&directory, seconds, frequency, &stop) {- write_profile_error(&directory, "cpu", &error);- tracing::error!(%error, "CPU profile capture failed");- }- })- .context("spawn CPU profile worker")?,- );+ runtime+ .workers+ .push(spawn_profile_thread("xerj-debug-cpu-profile", move || {+ if wait_for_duration_or_stop(&stop, Duration::from_secs(delay)) {+ return;+ }+ if let Err(error) = capture_cpu(&directory, seconds, frequency, &stop) {+ write_profile_error(&directory, "cpu", &error);+ tracing::error!(%error, "CPU profile capture failed");+ }+ })?);}if let Some(seconds) = config.heap_seconds {let directory = config.output_dir.clone();let stop = Arc::clone(&runtime.stop);let delay = config.delay_seconds;- runtime.workers.push(- std::thread::Builder::new()- .name("xerj-debug-heap-profile".into())- .spawn(move || {- if wait_for_duration_or_stop(&stop, Duration::from_secs(delay)) {- return;- }- if let Err(error) = capture_heap(&directory, seconds, &stop) {- write_profile_error(&directory, "heap", &error);- tracing::error!(%error, "heap profile capture failed");- }- })- .context("spawn heap profile worker")?,- );+ runtime.workers.push(spawn_profile_thread(+ "xerj-debug-heap-profile",+ move || {+ if wait_for_duration_or_stop(&stop, Duration::from_secs(delay)) {+ return;+ }+ if let Err(error) = capture_heap(&directory, seconds, &stop) {+ write_profile_error(&directory, "heap", &error);+ tracing::error!(%error, "heap profile capture failed");+ }+ },+ )?);}Ok(runtime)}diff --git a/engine/crates/xerj-server/src/ingest_memory_trace.rs b/engine/crates/xerj-server/src/ingest_memory_trace.rsindex 3c9f3d7e8..ad9c33256 100644--- a/engine/crates/xerj-server/src/ingest_memory_trace.rs+++ b/engine/crates/xerj-server/src/ingest_memory_trace.rs@@ -1,8 +1,8 @@use std::io::Write;use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::{mpsc, Arc, Condvar, Mutex, Weak};-use std::thread::JoinHandle;use std::time::Duration;+use xerj_common::thread_spawn::SpawnedThread;use xerj_engine::ingest_memory::{self, AllocatorSnapshot, EventKind, ProcessSnapshot, TraceMode, LEDGER,@@ -14,8 +14,8 @@ const CHANNEL_CAPACITY: usize = 256;pub struct TraceRuntime {stop: Arc<AtomicBool>,wake: Arc<(Mutex<()>, Condvar)>,- sampler: Option<JoinHandle<()>>,- writer: Option<JoinHandle<()>>,+ sampler: Option<SpawnedThread>,+ writer: Option<SpawnedThread>,dropped: Arc<AtomicU64>,}@@ -62,20 +62,29 @@ pub fn spawn(engine: &Arc<Engine>) -> Option<TraceRuntime> {let stop = Arc::new(AtomicBool::new(false));let dropped = Arc::new(AtomicU64::new(0));let writer_dropped = Arc::clone(&dropped);- let writer = std::thread::Builder::new()- .name("xerj-ingest-memory-writer".into())- .spawn(move || writer_loop(rx, writer_dropped))- .map_err(|error| trace_spawn_failed("writer", &error))- .ok()?;+ // #1122: Builder::spawn panics in the child when the alternate signal+ // stack cannot be mapped. This trace is diagnostics; a failed spawn+ // disables it instead of aborting the node (`panic = "abort"`).+ let writer = match xerj_common::thread_spawn::try_spawn_unguarded(+ "xerj-ingest-memory-writer",+ move || writer_loop(rx, writer_dropped),+ ) {+ Ok(handle) => handle,+ Err(failure) => {+ trace_spawn_failed("writer", &failure.error);+ drop(failure.job);+ return None;+ }+ };let weak = Arc::downgrade(engine);let sampler_stop = Arc::clone(&stop);let wake = Arc::new((Mutex::new(()), Condvar::new()));let sampler_wake = Arc::clone(&wake);let sampler_dropped = Arc::clone(&dropped);- let sampler = std::thread::Builder::new()- .name("xerj-ingest-memory-sampler".into())- .spawn(move || {+ let sampler = match xerj_common::thread_spawn::try_spawn_unguarded(+ "xerj-ingest-memory-sampler",+ move || {send_snapshot(&tx, &sampler_dropped, EventKind::TraceStart, false);sample_loop(weak,@@ -85,11 +94,17 @@ pub fn spawn(engine: &Arc<Engine>) -> Option<TraceRuntime> {sampler_dropped,Duration::from_millis(config.sample_ms),);- })+ },+ ) {+ Ok(handle) => handle,// The writer exits on its own: the sender it reads from was moved// into the closure the failed spawn just dropped.- .map_err(|error| trace_spawn_failed("sampler", &error))- .ok()?;+ Err(failure) => {+ trace_spawn_failed("sampler", &failure.error);+ drop(failure.job);+ return None;+ }+ };Some(TraceRuntime {stop,diff --git a/engine/crates/xerj-server/src/share.rs b/engine/crates/xerj-server/src/share.rsindex 6adafed36..0295fde6c 100644--- a/engine/crates/xerj-server/src/share.rs+++ b/engine/crates/xerj-server/src/share.rs@@ -1468,15 +1468,19 @@ impl Tunnel {readers.push(spawn_reader(pipe, tx.clone(), tunnel.log.clone()).map_err(spawn_failed)?);}// When both pipes close, the process is gone.- std::thread::Builder::new()- .name("xerj-share-tunnel-wait".into())- .spawn(move || {- for r in readers {- let _ = r.join();- }- let _ = tx.send(TunnelEvent::Exited);- })- .map_err(spawn_failed)?;+ // #1122: Builder::spawn panics in the child on a signal-stack ENOMEM.+ // A failed spawn fails the open (local link) instead of aborting.+ xerj_common::thread_spawn::try_spawn_unguarded("xerj-share-tunnel-wait", move || {+ for r in readers {+ let _ = r.join();+ }+ let _ = tx.send(TunnelEvent::Exited);+ })+ .map_err(|failure| {+ let error = failure.error;+ drop(failure.job);+ spawn_failed(error)+ })?;let deadline = std::time::Instant::now() + TUNNEL_URL_TIMEOUT;loop {if let Some(why) = interrupts.fired() {@@ -1577,26 +1581,31 @@ fn spawn_reader<R: std::io::Read + Send + 'static>(pipe: R,tx: mpsc::Sender<TunnelEvent>,log: TunnelLog,-) -> std::io::Result<std::thread::JoinHandle<()>> {- std::thread::Builder::new()- .name("xerj-share-tunnel-log".into())- .spawn(move || {- let mut sent_url = false;- for line in BufReader::new(pipe).lines() {- let Ok(line) = line else { break };- remember_tunnel_line(&log, &line);- if !sent_url {- if let Some(u) = parse_tunnel_url(&line) {- sent_url = true;- let _ = tx.send(TunnelEvent::Url(u));- continue;- }- }- if tunnel_line_means_connected(&line) {- let _ = tx.send(TunnelEvent::Connected);+) -> std::io::Result<xerj_common::thread_spawn::SpawnedThread> {+ // #1122: a signal-stack allocation failure must come back as `Err`,+ // not as a panic in the child (`panic = "abort"` kills the process).+ xerj_common::thread_spawn::try_spawn_unguarded("xerj-share-tunnel-log", move || {+ let mut sent_url = false;+ for line in BufReader::new(pipe).lines() {+ let Ok(line) = line else { break };+ remember_tunnel_line(&log, &line);+ if !sent_url {+ if let Some(u) = parse_tunnel_url(&line) {+ sent_url = true;+ let _ = tx.send(TunnelEvent::Url(u));+ continue;}}- })+ if tunnel_line_means_connected(&line) {+ let _ = tx.send(TunnelEvent::Connected);+ }+ }+ })+ .map_err(|failure| {+ let error = failure.error;+ drop(failure.job);+ error+ })}/// Keep `line` as one of the last [`TUNNEL_LOG_LINES`]; long lines are cut.diff --git a/engine/crates/xerj-storage/src/merge.rs b/engine/crates/xerj-storage/src/merge.rsindex 628bc5a6c..3b12be451 100644--- a/engine/crates/xerj-storage/src/merge.rs+++ b/engine/crates/xerj-storage/src/merge.rs@@ -412,47 +412,67 @@ impl MergeExecutor {/// Spawn a background thread that periodically checks for merge candidates.////// The thread runs until [`MergeExecutor::shutdown`] is called. Returns a- /// handle that can be joined on shutdown.- pub fn spawn_background<P>(self: Arc<Self>, policy: Arc<P>) -> std::thread::JoinHandle<()>+ /// handle that can be joined on shutdown. If the thread cannot be created+ /// (#1122) the handle is inert — `join` returns immediately — and merges+ /// are not scheduled until the next successful spawn. The loop is not run+ /// inline: it does not return until shutdown.+ pub fn spawn_background<P>(+ self: Arc<Self>,+ policy: Arc<P>,+ ) -> xerj_common::thread_spawn::SpawnedThreadwhereP: MergePolicy,{let shutdown = Arc::clone(&self.shutdown);let interval = Duration::from_millis(self.config.check_interval_ms);- std::thread::Builder::new()- .name("xerj-merge".to_string())- .spawn(move || {- info!("merge background thread started");- while !shutdown.load(Ordering::Relaxed) {- std::thread::sleep(interval);+ // #1122: `.expect` on `std::thread::Builder::spawn` aborts the process+ // both when `pthread_create` returns an error and when the child+ // panics mapping its alternate signal stack (`panic = "abort"`).+ // Background merges are maintenance; failing to start the thread+ // skips them instead of taking the node down.+ match xerj_common::thread_spawn::try_spawn_unguarded("xerj-merge", move || {+ info!("merge background thread started");+ while !shutdown.load(Ordering::Relaxed) {+ std::thread::sleep(interval);++ if shutdown.load(Ordering::Relaxed) {+ break;+ }++ let snap = self.store.snapshot();+ let candidates = policy.select_merges(&snap.segments);+ drop(snap); // release guard before I/O++ if candidates.is_empty() {+ debug!("no merge candidates");+ continue;+ }+ for batch in candidates {if shutdown.load(Ordering::Relaxed) {break;}-- let snap = self.store.snapshot();- let candidates = policy.select_merges(&snap.segments);- drop(snap); // release guard before I/O-- if candidates.is_empty() {- debug!("no merge candidates");- continue;- }-- for batch in candidates {- if shutdown.load(Ordering::Relaxed) {- break;- }- match self.execute_merge(&batch) {- Ok(meta) => info!(merged_id = meta.id, "background merge completed"),- Err(e) => warn!("background merge failed: {e}"),- }+ match self.execute_merge(&batch) {+ Ok(meta) => info!(merged_id = meta.id, "background merge completed"),+ Err(e) => warn!("background merge failed: {e}"),}}- info!("merge background thread stopped");- })- .expect("failed to spawn merge thread")+ }+ info!("merge background thread stopped");+ }) {+ Ok(handle) => handle,+ Err(failure) => {+ static LOGGED: AtomicBool = AtomicBool::new(false);+ xerj_common::thread_spawn::warn_best_effort_degraded(+ &LOGGED,+ "xerj-merge",+ &failure.error,+ );+ drop(failure.job);+ xerj_common::thread_spawn::SpawnedThread::inert()+ }+ }}/// Signal the background thread to stop at the next check.diff --git a/engine/crates/xerj-storage/src/wal_fsync.rs b/engine/crates/xerj-storage/src/wal_fsync.rsindex 245745e39..235214707 100644--- a/engine/crates/xerj-storage/src/wal_fsync.rs+++ b/engine/crates/xerj-storage/src/wal_fsync.rs@@ -242,17 +242,30 @@ impl WalFsyncScheduler {}let mut spawned = 0usize;for _ in st.workers..want {- match std::thread::Builder::new()- .name("xerj-wal-fsync".into())- .spawn(move || self.worker_loop())- {- Ok(_) => spawned += 1,- Err(e) => {- // Retried on the next arm; if none ever succeeds the- // shard still gets fsynced by flush / rotate / shutdown,- // exactly as it would have when the old per-index thread- // failed to spawn.- warn!("could not start WAL fsync worker: {e}");+ // #1122: `std::thread::Builder::spawn` panics inside the child+ // when the alternate signal stack cannot be mapped, and the+ // release profile is panic=abort. `try_spawn_unguarded` returns+ // that failure as `Err` (the watermark gate is not consulted:+ // this thread is what bounds the durability window, and a soft+ // RSS watermark must not refuse it). The worker loop is+ // infinite, so the job is dropped rather than run inline; the+ // shard is still fsynced by flush / rotate / shutdown, and the+ // next arm retries. Logged once so a write storm does not emit+ // a line per attempt.+ match xerj_common::thread_spawn::try_spawn_unguarded("xerj-wal-fsync", move || {+ self.worker_loop()+ }) {+ Ok(_detached) => spawned += 1,+ Err(failure) => {+ static LOGGED: AtomicBool = AtomicBool::new(false);+ xerj_common::thread_spawn::warn_best_effort_degraded(+ &LOGGED,+ "xerj-wal-fsync",+ &failure.error,+ );+ // The closure only captures `&self` (Copy). Ignoring it+ // skips the infinite worker loop; flush still fsyncs.+ let _ = failure.job;break;}}