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(server): pin prod tokio worker stack to 4 MiB; correct the Painless headroom doc (#136)
xerj-org3f1134cc9184
diff --git a/engine/crates/xerj-engine/src/painless.rs b/engine/crates/xerj-engine/src/painless.rsindex 37835aee5..0958d9ea8 100644--- a/engine/crates/xerj-engine/src/painless.rs+++ b/engine/crates/xerj-engine/src/painless.rs@@ -493,7 +493,7 @@ pub(crate) const EVAL_TOO_DEEP_MSG: &str =/// stack frames to abort the process even in a release build. Kept small/// and independent of the expression budget.///-/// **32 is not a guess and must not be raised.** Measured in a release build+/// **32 is measured, not a guess.** Measured in a release build/// by probing the stack address at each call level (`stackprobe` feature,/// `measure_stack_per_call_level`), with the recursive call placed *inside*/// the closure body's nested blocks so every call level also pays that@@ -506,14 +506,35 @@ pub(crate) const EVAL_TOO_DEEP_MSG: &str =/// | 50 | 23,440 | 710 KiB |/// | 90 (parser max) | 40,720 | 1.20 MiB |///-/// The adversarial worst case already consumes 1.20 MiB (1,262,320 bytes) of-/// the 2 MiB tokio worker stack, leaving ~0.8 MiB for the axum/search/-/// segment-scan frames underneath it. Doubling the ceiling would overflow, so-/// #97's "just raise it" option is not available. The cost per level is-/// `O(MAX_PARSE_DEPTH)` because a closure body's statement nesting is not-/// charged against any shared budget — lifting this ceiling safely requires-/// charging body nesting against a single stack budget, not a bigger number-/// here.+/// The adversarial worst case consumes a measured 1.20 MiB (1,262,320 bytes).+/// That figure is intrinsic to this depth ceiling and does not change with the+/// worker-thread stack size — only what fits *underneath* the evaluator does.+/// The frames underneath have grown: axum accept/route, the two-layer+/// authorization middleware (#79), the `_*_by_query` handler, the search entry+/// and the segment scan all sit below this evaluator on the same stack. The+/// earlier "~0.8 MiB underneath" note was against the stock 2 MiB tokio worker+/// stack (2,097,152 − 1,262,320 = 834,832 bytes ≈ 0.80 MiB) and did NOT account+/// for the authz layer now living in that space. The server therefore pins the+/// worker stack to 4 MiB explicitly (`RT_THREAD_STACK_SIZE` in `xerj-server`'s+/// `main.rs`), which leaves ~2.80 MiB under this worst case+/// (4,194,304 − 1,262,320 = 2,931,984 bytes) — comfortably enough for the+/// middleware and handler frames.+///+/// HONEST NOTE ON THE 2.80 MiB: it is arithmetic against the new 4 MiB budget+/// using the *unchanged* measured 1.20 MiB evaluator cost. The stackprobe+/// instrumentation measures only this evaluator's per-level cost (unchanged+/// here — `MAX_CALL_DEPTH` and the per-frame size are untouched); it does not+/// measure the axum/authz/handler frames underneath, so their exact byte cost+/// was NOT re-instrumented. The authz layer's contribution is a small fixed+/// addition to the "underneath" side and is approximate, but it is well within+/// the enlarged headroom.+///+/// Raising this ceiling is still not a free "just raise it" (see #97), even+/// with the larger stack: the cost per level is `O(MAX_PARSE_DEPTH)` — up to+/// ~40 KiB per level in the worst case — because a closure body's statement+/// nesting is not charged against any shared budget, so the budget is consumed+/// quickly. Lifting this ceiling safely requires charging body nesting against+/// a single stack budget, not a bigger number here (and not a bigger stack).////// Reproduce with:/// `cargo test --release -p xerj-engine --lib --features stackprobe -- \diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 0ad6ab8b7..baf98e0ab 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -1436,13 +1436,110 @@ fn main() -> Result<()> {.and_then(|v| v.parse::<usize>().ok()).filter(|&n| n > 0).unwrap_or_else(|| (cores * 8).clamp(64, 512));- let rt = tokio::runtime::Builder::new_multi_thread()+ let rt = build_runtime(worker_threads)?;+ rt.block_on(async_main())+}++/// Explicit worker-thread stack size for the production Tokio runtime.+///+/// Tokio's default is 2 MiB. We pin 4 MiB deliberately so the deepest+/// legitimate-but-adversarial request rides on documented headroom rather than+/// on the default staying ahead of demand. The budget on ONE worker stack,+/// deepest frame first:+///+/// * The Painless script evaluator's own worst case — a self-application+/// closure recursed to `MAX_CALL_DEPTH` (32) with every body at the parser's+/// maximum block nesting — consumes a *measured* ~1.20 MiB (1,262,320 bytes);+/// see `xerj_engine`'s `painless::MAX_CALL_DEPTH` stackprobe table. That+/// figure is intrinsic to the depth ceiling and does NOT shrink with a+/// bigger stack.+/// * Underneath the evaluator sits everything that carried the request there:+/// the axum accept/route frames, the two-layer authorization middleware+/// (#79), the `_*_by_query` handler, the search entry, `block_in_place`, and+/// the segment scan.+///+/// At the old 2 MiB default the worst case left only ~0.8 MiB+/// (2,097,152 − 1,262,320 = 834,832 bytes) for that whole "underneath" stack,+/// and the authz layer now competes for it. At 4 MiB the headroom is ~2.80 MiB+/// (4,194,304 − 1,262,320 = 2,931,984 bytes), which absorbs the middleware and+/// handler frames with a comfortable margin. Idle workers park in `epoll_wait`+/// and only reserve *virtual* address space for the stack, so the larger size+/// costs nothing at low concurrency.+const RT_THREAD_STACK_SIZE: usize = 4 * 1024 * 1024;++/// Compile-time guardrails on the stack budget above. Enforced in the real+/// build (not only under `cfg(test)`), so a future edit that drops the stack+/// back to the tokio default, or that lets the "underneath" headroom fall+/// below the axum + authz + by-query + search frames, fails to compile.+const _: () = {+ // Measured Painless closure-recursion worst case at `MAX_CALL_DEPTH`, from+ // painless.rs's stackprobe table (40,720 B/level × 31 increments). Kept in+ // sync with `xerj_engine::painless::MAX_CALL_DEPTH`'s documented figure.+ const PAINLESS_WORST_CASE: usize = 1_262_320;+ // Must be explicitly raised off tokio's 2 MiB default.+ assert!(RT_THREAD_STACK_SIZE >= 4 * 1024 * 1024);+ // Must leave > 1 MiB under the evaluator worst case for the frames beneath+ // it (axum + authz middleware + by-query handler + search + segment scan).+ assert!(RT_THREAD_STACK_SIZE - PAINLESS_WORST_CASE > 1024 * 1024);+};++/// Build the production multi-threaded Tokio runtime with the deliberate worker+/// count and [`RT_THREAD_STACK_SIZE`]. Factored out of `main` so the exact+/// builder configuration the server boots with is exercised by a test.+fn build_runtime(worker_threads: usize) -> Result<tokio::runtime::Runtime> {+ tokio::runtime::Builder::new_multi_thread().enable_all().worker_threads(worker_threads)+ .thread_stack_size(RT_THREAD_STACK_SIZE).thread_name("xerj-rt").build()- .context("build tokio runtime")?;- rt.block_on(async_main())+ .context("build tokio runtime")+}++#[cfg(test)]+mod runtime_tests {+ use super::build_runtime;++ #[test]+ fn runtime_builds_and_boots() {+ // The exact builder config `main` uses must construct and run a task on+ // a 4 MiB-stack worker — this is the boot smoke test for the setting.+ let rt = build_runtime(2).expect("prod runtime builds");+ assert_eq!(rt.block_on(async { 40 + 2 }), 42);+ }++ #[test]+ fn worker_stack_actually_exceeds_the_2mib_default() {+ // The boot test above passes even if `.thread_stack_size` is reverted,+ // because a default-stack runtime still boots. This one exercises the+ // WIRING: a worker task uses a ~3 MiB stack frame, which fits under+ // RT_THREAD_STACK_SIZE (4 MiB) but overflows tokio's 2 MiB default.+ // Reverting the `.thread_stack_size` line makes this abort the process+ // with a stack overflow rather than fail an assertion — a hard failure+ // either way, which is the point: the setting is load-bearing.+ //+ // `spawn` (not `block_on`) so the frame lands on a WORKER thread, the+ // one the setting sizes; `block_on` runs on the calling test thread.+ const FRAME: usize = 3 * 1024 * 1024;+ let rt = build_runtime(2).expect("prod runtime builds");+ let sum = rt.block_on(async {+ tokio::spawn(async {+ // A big stack array forces the worker frame past 2 MiB. `black_box`+ // + a real read keep the optimiser from eliding it.+ let mut buf = [0u8; FRAME];+ for (i, b) in buf.iter_mut().enumerate() {+ *b = (i & 0xff) as u8;+ }+ std::hint::black_box(&buf);+ buf.iter().map(|&b| b as u64).sum::<u64>()+ })+ .await+ .expect("worker task completed without overflowing its stack")+ });+ // 256 repetitions of 0..=255 across 3 MiB: each full 0..255 block sums+ // to 32640; assert it ran rather than pinning the exact total.+ assert!(sum > 0, "the stack-heavy worker task actually executed");+ }}async fn async_main() -> Result<()> {