Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(resource): one documented core/memory policy — live worker knobs, a bounded phase A, and a governor that can see macOS

xerj-orgf0961f4e65f8
diff --git a/demo/usecases/autoindex/RECIPE_DRAFT.md b/demo/usecases/autoindex/RECIPE_DRAFT.md
index fcc53adf2..26e59962a 100644
--- a/demo/usecases/autoindex/RECIPE_DRAFT.md
+++ b/demo/usecases/autoindex/RECIPE_DRAFT.md
@@ -222,7 +222,8 @@ curl localhost:9200/ax-*/_search -H 'Content-Type: application/json' \
```
Useful knobs (all optional): `--url` for a remote endpoint, `--workers N`
-(default min(cores, 8)), `--prefix` to namespace the indices (default `ax`),
+(default: every core, reduced when the memory safe zone cannot pay for that
+many in-flight bulk buffers; bounds both the scan and the indexing phase), `--prefix` to namespace the indices (default `ax`),
`--no-semantic` for pure BM25+keyword without vector fields, `--dry-run` to
print the inferred plan without indexing anything, `--follow-symlinks`
(loop-safe), `--sample N` records per file for inference (default 500).
diff --git a/docs/recipes/zero-config-indexing.md b/docs/recipes/zero-config-indexing.md
index 2a182068a..bd8117010 100644
--- a/docs/recipes/zero-config-indexing.md
+++ b/docs/recipes/zero-config-indexing.md
@@ -246,7 +246,8 @@ curl localhost:9200/ax-*/_search -H 'Content-Type: application/json' \
```
Useful knobs (all optional): `--url` for a non-default endpoint, `--workers N`
-(default min(cores, 8)), `--prefix` to namespace the indices (default `ax`),
+(default: every core, reduced when the memory safe zone cannot pay for that
+many in-flight bulk buffers; bounds both the scan and the indexing phase), `--prefix` to namespace the indices (default `ax`),
`--no-semantic` for pure BM25+keyword without vector fields, `--dry-run` to
print the inferred plan without indexing anything, `--follow-symlinks`
(loop-safe), `--sample N` records per file for inference (default 500).
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index 9f38df4ca..0c98c057d 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -6464,6 +6464,7 @@ dependencies = [
"tree-sitter-rust",
"tree-sitter-typescript",
"walkdir",
+ "xerj-common",
"xxhash-rust",
"zip 2.4.2",
]
@@ -6501,6 +6502,7 @@ dependencies = [
"byteorder",
"bytes",
"chrono",
+ "libc",
"prometheus",
"serde",
"serde_json",
diff --git a/engine/crates/xerj-autoindex/Cargo.toml b/engine/crates/xerj-autoindex/Cargo.toml
index 55283c9e9..f2784edf6 100644
--- a/engine/crates/xerj-autoindex/Cargo.toml
+++ b/engine/crates/xerj-autoindex/Cargo.toml
@@ -7,6 +7,9 @@ authors.workspace = true
description = "xerj autoindex — point it at any folder and make the contents AI-searchable with zero configuration"
[dependencies]
+# The machine-resource policy (cores, memory safe zone, thread priority) is
+# shared with the server: one policy, one place (#240).
+xerj-common = { path = "../xerj-common" }
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index ee81b6a7b..9af0f748b 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -2,13 +2,24 @@
use std::path::PathBuf;
+/// Largest `--bulk-mb` accepted. Past this a single bulk body stops being a
+/// unit of work and starts being a memory incident on the server.
+pub const MAX_BULK_MB: usize = 24;
+
#[derive(Debug, Clone)]
pub struct IndexCfg {
pub root: PathBuf,
pub url: String,
pub api_key: Option<String>,
+ /// Phase-B index workers (concurrent bulk senders).
pub workers: usize,
+ /// Phase-A scan pool width (content hashing, sniffing, sampling). Both come
+ /// from `--workers`; they differ only when the memory safe zone cannot pay
+ /// for as many in-flight bulk buffers as the machine has cores.
+ pub scan_workers: usize,
pub pdf_workers: usize,
+ /// What the machine forced on this run, printed once at start-up.
+ pub resource_notes: Vec<String>,
pub pdf_timeout_secs: u64,
pub bulk_mb: usize,
pub bulk_timeout_secs: u64,
@@ -65,8 +76,12 @@ pub fn print_help() {
OPTIONS:\n\
--url <U> ES-compat endpoint (default http://localhost:9200)\n\
--api-key <K> Authorization header (or env XERJ_API_KEY)\n\
- --workers <N> extract workers (default min(cores,8))\n\
- --pdf-workers <N> concurrent PDF parser processes (default min(cores,4); max 4)\n\
+ --workers <N> workers for BOTH phases — content hashing/sniffing and\n\
+ indexing (default: every core, reduced if the memory\n\
+ safe zone cannot pay for that many bulk buffers;\n\
+ valid range 1..=1024)\n\
+ --pdf-workers <N> concurrent PDF parser processes (default min(cores,4); max 4,\n\
+ reduced further on a machine with little free memory)\n\
--pdf-timeout-secs <N> per-PDF parser timeout (default 120; max 3600)\n\
--bulk-mb <N> bulk cut size in MB (default 8)\n\
--bulk-timeout-secs <N>\n\
@@ -121,14 +136,11 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
let mut url = "http://localhost:9200".to_string();
let mut api_key = std::env::var("XERJ_API_KEY").ok().filter(|s| !s.is_empty());
- let mut workers = std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(8)
- .min(8);
- let mut pdf_workers = std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(4)
- .min(4);
+ // Worker counts are decided by `crate::resources::plan` once every flag is
+ // known, because the answer depends on --bulk-mb and on the machine. `None`
+ // here means "the user did not ask for a number".
+ let mut workers: Option<usize> = None;
+ let mut pdf_workers: Option<usize> = None;
let mut pdf_timeout_secs = 120u64;
let mut bulk_mb = 8usize;
let mut bulk_timeout_secs = 300u64;
@@ -152,17 +164,29 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
"--url" => url = it.next().ok_or("--url needs a value")?,
"--api-key" => api_key = it.next(),
"--workers" => {
- workers = it
- .next()
- .and_then(|s| s.parse().ok())
- .ok_or("--workers needs a number")?
+ // Refused, not clamped: `--workers 0` used to become 1 and
+ // `--workers 100000` was taken at face value, both without a
+ // word to the user (#204's class).
+ workers = Some(
+ it.next()
+ .and_then(|s| s.parse().ok())
+ .filter(|n| (1..=crate::resources::MAX_WORKERS).contains(n))
+ .ok_or(format!(
+ "--workers needs a number from 1 to {}",
+ crate::resources::MAX_WORKERS
+ ))?,
+ )
}
"--pdf-workers" => {
- pdf_workers = it
- .next()
- .and_then(|s| s.parse().ok())
- .filter(|n| (1..=4).contains(n))
- .ok_or("--pdf-workers needs a number from 1 to 4")?
+ pdf_workers = Some(
+ it.next()
+ .and_then(|s| s.parse().ok())
+ .filter(|n| (1..=crate::resources::MAX_PDF_WORKERS).contains(n))
+ .ok_or(format!(
+ "--pdf-workers needs a number from 1 to {}",
+ crate::resources::MAX_PDF_WORKERS
+ ))?,
+ )
}
"--pdf-timeout-secs" => {
pdf_timeout_secs = it
@@ -172,10 +196,14 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
.ok_or("--pdf-timeout-secs needs a number from 1 to 3600")?
}
"--bulk-mb" => {
+ // Was silently clamped into 1..=24 at the end of parsing, so
+ // `--bulk-mb 512` ran at 24 and `--bulk-mb 0` at 1, in both
+ // cases without telling anyone.
bulk_mb = it
.next()
.and_then(|s| s.parse().ok())
- .ok_or("--bulk-mb needs a number")?
+ .filter(|n| (1..=MAX_BULK_MB).contains(n))
+ .ok_or(format!("--bulk-mb needs a number from 1 to {MAX_BULK_MB}"))?
}
"--bulk-timeout-secs" => {
bulk_timeout_explicit = true;
@@ -257,28 +285,33 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
prefix,
state_dir,
})),
- (None, Some(root)) => Ok(Cmd::Index(IndexCfg {
- root,
- url,
- api_key,
- workers: workers.max(1),
- pdf_workers,
- pdf_timeout_secs,
- bulk_mb: bulk_mb.clamp(1, 24),
- bulk_timeout_secs,
- prefix,
- state_dir,
- fresh,
- follow_symlinks,
- max_file_gb,
- sample: sample.max(50),
- no_semantic,
- brain,
- no_graph,
- dry_run,
- json,
- quiet,
- })),
+ (None, Some(root)) => {
+ let plan = crate::resources::plan(workers, pdf_workers, bulk_mb);
+ Ok(Cmd::Index(IndexCfg {
+ root,
+ url,
+ api_key,
+ workers: plan.index_workers,
+ scan_workers: plan.scan_threads,
+ pdf_workers: plan.pdf_workers,
+ resource_notes: plan.notes,
+ pdf_timeout_secs,
+ bulk_mb,
+ bulk_timeout_secs,
+ prefix,
+ state_dir,
+ fresh,
+ follow_symlinks,
+ max_file_gb,
+ sample: sample.max(50),
+ no_semantic,
+ brain,
+ no_graph,
+ dry_run,
+ json,
+ quiet,
+ }))
+ }
_ => Ok(Cmd::Help),
}
}
@@ -294,6 +327,38 @@ mod tests {
}
}
+ fn err(args: &[&str]) -> String {
+ parse(args.iter().map(|s| s.to_string()).collect()).expect_err("must be refused")
+ }
+
+ /// #240 §1/§2: `--workers` capped itself at 8 for no recorded reason and
+ /// governed only phase B. It now governs both phases and defaults to the
+ /// machine.
+ #[test]
+ fn workers_defaults_to_the_machine_and_governs_both_phases() {
+ let cfg = index(&["data"]);
+ let cores = xerj_common::resource::cores();
+ assert_eq!(cfg.scan_workers, cores, "phase A gets the whole machine");
+ assert!(cfg.workers <= cores && cfg.workers >= 1);
+ let asked = index(&["data", "--workers", "3"]);
+ assert_eq!(asked.scan_workers, 3, "--workers must bound phase A");
+ assert_eq!(asked.workers, 3, "--workers must bound phase B");
+ }
+
+ /// An unusable count is a typo. Clamping it silently is the
+ /// accepted-and-ignored class this repo keeps re-finding (#204).
+ #[test]
+ fn unusable_worker_and_bulk_values_are_refused_not_clamped() {
+ assert!(err(&["data", "--workers", "0"]).contains("--workers needs a number from 1 to"));
+ assert!(err(&["data", "--workers", "99999"]).contains("--workers"));
+ assert!(err(&["data", "--workers", "eight"]).contains("--workers"));
+ assert!(err(&["data", "--pdf-workers", "8"]).contains("--pdf-workers"));
+ // `--bulk-mb 0` used to become 1 and `--bulk-mb 512` used to become 24.
+ assert!(err(&["data", "--bulk-mb", "0"]).contains("--bulk-mb needs a number from 1 to 24"));
+ assert!(err(&["data", "--bulk-mb", "512"]).contains("--bulk-mb"));
+ assert_eq!(index(&["data", "--bulk-mb", "24"]).bulk_mb, 24);
+ }
+
#[test]
fn bulk_timeout_defaults_to_300_seconds() {
assert_eq!(index(&["data"]).bulk_timeout_secs, 300);
diff --git a/engine/crates/xerj-autoindex/src/content.rs b/engine/crates/xerj-autoindex/src/content.rs
index 4f865b47a..9793b7c13 100644
--- a/engine/crates/xerj-autoindex/src/content.rs
+++ b/engine/crates/xerj-autoindex/src/content.rs
@@ -19,15 +19,47 @@ pub struct Inventory {
pub duplicates: Vec<DuplicateFile>,
}
+/// Test-only witness: which pool the digest phase actually ran on. Phase A is
+/// where `--workers` was silently disconnected (#240), and the pool a task
+/// lands on is only observable from inside the task.
+#[cfg(test)]
+pub(crate) static OBSERVED_DIGEST_POOL_THREADS: std::sync::atomic::AtomicUsize =
+ std::sync::atomic::AtomicUsize::new(0);
+
+/// Set when any digest ran on a thread that is not one of the scan pool's.
+#[cfg(test)]
+pub(crate) static DIGEST_RAN_OFF_THE_SCAN_POOL: std::sync::atomic::AtomicBool =
+ std::sync::atomic::AtomicBool::new(false);
+
/// Hash each file once, group equal digests, then byte-verify only digest peers.
///
/// This is linear in corpus bytes for adversarial common-prefix inputs rather
/// than pairwise O(n² × file_size).
pub fn resolve(files: Vec<FileEntry>) -> Result<Inventory> {
- let digests: Vec<Result<String>> = files
- .par_iter()
- .map(|file| full_digest(&file.path, file.size))
- .collect();
+ // Phase A belongs to the run's scan pool, not to rayon's global pool:
+ // `--workers` has to bound the CPU-bound phase to mean anything (#240 §2).
+ let digests: Vec<Result<String>> = crate::pool::install(|| {
+ files
+ .par_iter()
+ .map(|file| {
+ #[cfg(test)]
+ {
+ OBSERVED_DIGEST_POOL_THREADS.fetch_max(
+ rayon::current_num_threads(),
+ std::sync::atomic::Ordering::Relaxed,
+ );
+ let on_scan_pool = std::thread::current()
+ .name()
+ .is_some_and(|n| n.starts_with("xerj-scan-"));
+ if !on_scan_pool {
+ DIGEST_RAN_OFF_THE_SCAN_POOL
+ .store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+ }
+ full_digest(&file.path, file.size)
+ })
+ .collect()
+ });
let digests: Vec<String> = digests.into_iter().collect::<Result<_>>()?;
resolve_with_digests(files, digests)
}
@@ -182,6 +214,31 @@ mod tests {
use super::*;
use std::fs;
+ /// #240 §2: the digest phase ran on rayon's default global pool — every
+ /// core on the machine — so `--workers` never bounded it. It must run on
+ /// the run's own scan pool, whose width the CLI sets.
+ #[test]
+ fn the_digest_phase_runs_on_the_runs_scan_pool() {
+ let dir = tempfile::tempdir().unwrap();
+ for i in 0..32 {
+ fs::write(dir.path().join(format!("f{i}.txt")), format!("body {i}\n")).unwrap();
+ }
+ OBSERVED_DIGEST_POOL_THREADS.store(0, std::sync::atomic::Ordering::Relaxed);
+ DIGEST_RAN_OFF_THE_SCAN_POOL.store(false, std::sync::atomic::Ordering::Relaxed);
+
+ resolve(crate::walk::walk(dir.path(), false).unwrap()).unwrap();
+
+ assert!(
+ !DIGEST_RAN_OFF_THE_SCAN_POOL.load(std::sync::atomic::Ordering::Relaxed),
+ "phase A must not run on rayon's global pool"
+ );
+ assert_eq!(
+ OBSERVED_DIGEST_POOL_THREADS.load(std::sync::atomic::Ordering::Relaxed),
+ crate::pool::scan_pool().current_num_threads(),
+ "the digest phase must see exactly the scan pool the run configured"
+ );
+ }
+
#[test]
fn identical_paths_become_one_content_file_and_an_alias() {
let dir = tempfile::tempdir().unwrap();
diff --git a/engine/crates/xerj-autoindex/src/detect/e2e.rs b/engine/crates/xerj-autoindex/src/detect/e2e.rs
index 7e76b671b..72c9446ae 100644
--- a/engine/crates/xerj-autoindex/src/detect/e2e.rs
+++ b/engine/crates/xerj-autoindex/src/detect/e2e.rs
@@ -257,7 +257,9 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {
url: url.to_owned(),
api_key: None,
workers: 1,
+ scan_workers: 1,
pdf_workers: 1,
+ resource_notes: Vec::new(),
pdf_timeout_secs: 30,
bulk_mb: 8,
bulk_timeout_secs: 300,
diff --git a/engine/crates/xerj-autoindex/src/extract/pdf.rs b/engine/crates/xerj-autoindex/src/extract/pdf.rs
index 71ea0d19b..0ffce3d24 100644
--- a/engine/crates/xerj-autoindex/src/extract/pdf.rs
+++ b/engine/crates/xerj-autoindex/src/extract/pdf.rs
@@ -478,10 +478,9 @@ fn worker_gate() -> &'static WorkerGate {
GATE.get_or_init(|| WorkerGate {
state: Mutex::new((
0,
- std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(4)
- .min(4),
+ // Default only: `configure_workers` overwrites this with the run's
+ // plan (`crate::resources::plan`) before any extraction starts.
+ xerj_common::resource::cores().min(crate::resources::MAX_PDF_WORKERS),
)),
ready: Condvar::new(),
})
diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
index c1c1e3df1..fe0c6a816 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -255,7 +255,9 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {
url: url.to_owned(),
api_key: None,
workers: 1,
+ scan_workers: 1,
pdf_workers: 1,
+ resource_notes: Vec::new(),
pdf_timeout_secs: 30,
bulk_mb: 64,
bulk_timeout_secs: 3_600,
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 1cb92710e..0aa6449b2 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -14,6 +14,8 @@ pub mod esclient;
pub mod extract;
pub mod ids;
pub mod infer;
+pub mod pool;
+pub mod resources;
pub mod sniff;
pub mod state;
pub mod walk;
@@ -391,7 +393,9 @@ mod phase_a_grouping_tests {
url: "http://unused.invalid".into(),
api_key: None,
workers: 1,
+ scan_workers: 1,
pdf_workers: 1,
+ resource_notes: Vec::new(),
pdf_timeout_secs: 10,
bulk_mb: 1,
bulk_timeout_secs: 10,
@@ -591,10 +595,14 @@ fn build_phase_a(
cfg: &IndexCfg,
) -> (Plan, Vec<dataset::Cluster>) {
use rayon::prelude::*;
- let scans: Vec<FileScan> = files
- .par_iter()
- .map(|f| scan_file(&f.path, f.size, cfg.sample, cfg.max_file_gb))
- .collect();
+ // Same pool as the digest phase: sniffing and sampling are the other half
+ // of the CPU-bound phase `--workers` has to bound (#240 §2).
+ let scans: Vec<FileScan> = crate::pool::install(|| {
+ files
+ .par_iter()
+ .map(|f| scan_file(&f.path, f.size, cfg.sample, cfg.max_file_gb))
+ .collect()
+ });
let rels: Vec<String> = files.iter().map(|f| f.rel.clone()).collect();
let scopes = compute_scopes(root, &rels);
@@ -905,10 +913,27 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {
/// `None` when the run ended before a plan produced one (empty folder,
/// `--dry-run`).
pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
+ // Fix the phase-A pool width BEFORE anything parallel starts: hashing and
+ // sniffing are the CPU-bound phase, and they used to take every core no
+ // matter what the caller asked for (#240 §2).
+ pool::configure(cfg.scan_workers);
extract::pdf::configure_workers(cfg.pdf_workers);
extract::pdf::configure_timeout(cfg.pdf_timeout_secs);
let t0 = Instant::now();
if !cfg.quiet {
+ // What this run decided to take from the machine, before it takes it.
+ eprintln!(
+ "autoindex: {} scan threads, {} index workers, {} pdf workers, --bulk-mb {} \
+ [{}]",
+ cfg.scan_workers,
+ cfg.workers,
+ cfg.pdf_workers,
+ cfg.bulk_mb,
+ xerj_common::resource::describe(),
+ );
+ for note in &cfg.resource_notes {
+ eprintln!("autoindex: {note}");
+ }
eprintln!(
"autoindex: bulk HTTP request timeout: {}s",
cfg.bulk_timeout_secs
@@ -2373,6 +2398,14 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
"records_submitted_this_run": records_total.load(Ordering::Relaxed),
"wall_seconds": (wall * 10.0).round() / 10.0,
"workers": cfg.workers,
+ // The whole resource decision, so a run can be explained after the
+ // fact from its own summary rather than from the machine it ran on.
+ "scan_workers": cfg.scan_workers,
+ "pdf_workers": cfg.pdf_workers,
+ "bulk_mb": cfg.bulk_mb,
+ "cores_available": xerj_common::resource::cores(),
+ "memory_safe_zone_mb": xerj_common::resource::memory_safe_zone_bytes() / (1024 * 1024),
+ "resource_notes": cfg.resource_notes,
"semantic": !cfg.no_semantic,
});
if let Some(g) = &graph_summary {
diff --git a/engine/crates/xerj-autoindex/src/pool.rs b/engine/crates/xerj-autoindex/src/pool.rs
new file mode 100644
index 000000000..51a236c3e
--- /dev/null
+++ b/engine/crates/xerj-autoindex/src/pool.rs
@@ -0,0 +1,86 @@
+//! The phase-A worker pool.
+//!
+//! Phase A — full-content hashing (`content::resolve`) and sniff/sample
+//! (`build_phase_a`) — is the CPU-bound half of an autoindex run. Both used
+//! bare `par_iter()`, which runs on rayon's *global* pool: a pool nothing in
+//! this crate ever sized, so it took every core on the machine regardless of
+//! `--workers`. `--workers 2` on a 12-core Mac still produced a 12-wide digest
+//! storm (#240 §2), which is why turning the knob down did not give the machine
+//! back.
+//!
+//! This module owns a pool of the width the run's [`crate::resources::Plan`]
+//! asked for, and phase A runs inside it.
+
+use std::sync::OnceLock;
+
+static SCAN_POOL: OnceLock<rayon::ThreadPool> = OnceLock::new();
+
+/// Fix the phase-A pool width for this process. Called once per run, before
+/// phase A starts.
+///
+/// The first call wins, because rayon threads cannot be resized once started.
+/// A later call asking for a different width says so rather than pretending —
+/// autoindex runs one index per process today, so this only fires if that ever
+/// changes.
+pub fn configure(threads: usize) {
+ let threads = threads.max(1);
+ let installed = scan_pool_with(threads).current_num_threads();
+ if installed != threads {
+ eprintln!(
+ "autoindex: phase-A pool is already running with {installed} threads; \
+ ignoring the request for {threads}"
+ );
+ }
+}
+
+/// The phase-A pool, built on first use at the machine's full width if
+/// [`configure`] was never called (library use, unit tests).
+pub fn scan_pool() -> &'static rayon::ThreadPool {
+ scan_pool_with(xerj_common::resource::cores())
+}
+
+fn scan_pool_with(threads: usize) -> &'static rayon::ThreadPool {
+ SCAN_POOL.get_or_init(|| {
+ rayon::ThreadPoolBuilder::new()
+ .num_threads(threads.max(1))
+ .thread_name(|i| format!("xerj-scan-{i}"))
+ .build()
+ .expect("failed to build the autoindex scan pool")
+ })
+}
+
+/// Run `f` inside the phase-A pool. Any rayon work started by `f` — including
+/// nested `par_iter`s — is confined to that pool's threads.
+pub fn install<R: Send>(f: impl FnOnce() -> R + Send) -> R {
+ scan_pool().install(f)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use rayon::prelude::*;
+
+ /// The pool is process-global, so this asserts the property that holds
+ /// whatever width the crate's other tests installed first: work submitted
+ /// through `install` runs on the scan pool, never on rayon's default
+ /// global pool.
+ #[test]
+ fn work_submitted_through_install_stays_in_the_scan_pool() {
+ let widths: Vec<usize> = install(|| {
+ (0..64)
+ .into_par_iter()
+ .map(|_| rayon::current_num_threads())
+ .collect()
+ });
+ let pool_width = scan_pool().current_num_threads();
+ assert!(widths.iter().all(|&w| w == pool_width));
+ let name_is_ours = install(|| {
+ (0..64).into_par_iter().all(|_| {
+ std::thread::current()
+ .name()
+ .is_some_and(|n| n.starts_with("xerj-scan-"))
+ })
+ });
+ assert!(name_is_ours, "phase A must not run on the global pool");
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/resources.rs b/engine/crates/xerj-autoindex/src/resources.rs
new file mode 100644
index 000000000..987e45e07
--- /dev/null
+++ b/engine/crates/xerj-autoindex/src/resources.rs
@@ -0,0 +1,206 @@
+//! What one autoindex run may take from the machine it is running on.
+//!
+//! autoindex runs on someone's laptop while they are using it, so this is the
+//! politest consumer XERJ has — and until #240 it was the least considered:
+//! `--workers` defaulted to `min(cores, 8)` for no recorded reason, and it did
+//! not control phase A at all. Phase A (content hashing, sniffing, sampling)
+//! is the CPU-bound half, and it ran on rayon's *default global pool*, i.e.
+//! every core, whatever the user asked for. Lowering `--workers` to get a Mac
+//! back therefore did nothing, which is what people reported.
+//!
+//! [`plan`] is the whole policy, as one pure function:
+//!
+//! * **Phase A** — CPU-bound, latency-critical for the person watching it. Gets
+//! the requested worker count, defaulting to every core
+//! ([`xerj_common::resource::Workload::Latency`]), and now actually runs
+//! inside a pool of that width ([`crate::pool`]).
+//! * **Phase B** — network-bound: measured at 0.69 client cores with 32
+//! workers, so cores are not the constraint there; memory is. Each worker
+//! holds a bulk buffer plus the batch it is building, so the count is capped
+//! by the memory safe zone.
+//! * **PDF workers** — separate processes, each allowed 1536 MiB of address
+//! space (`extract::pdf::WORKER_ADDRESS_SPACE`), so the cap is whatever the
+//! safe zone can actually pay for, never more than the measured 4.
+
+use xerj_common::resource;
+
+const MIB: u64 = 1024 * 1024;
+
+/// Hard ceiling on `--workers`. A value past this is a typo, and silently
+/// clamping typos is the accepted-and-ignored class from #204 — the CLI
+/// rejects it instead.
+pub const MAX_WORKERS: usize = 1024;
+
+/// Ceiling on concurrent PDF subprocesses, unchanged from the value introduced
+/// with the isolated-PDF-worker design: four × 1536 MiB of address space is
+/// already the most a laptop should ever hand to one file format.
+pub const MAX_PDF_WORKERS: usize = 4;
+
+/// Address space one isolated PDF worker may take, mirroring
+/// `extract::pdf::WORKER_ADDRESS_SPACE`. Used only to decide how many such
+/// workers the machine can afford.
+const PDF_WORKER_BYTES: u64 = 1536 * MIB;
+
+/// Working memory one phase-B worker needs: the NDJSON bulk buffer it fills,
+/// the batch of documents it is building, and the request/response copy in
+/// flight. Three times the bulk size is an engineering budget, not a
+/// measurement — it exists so that `--bulk-mb 24` on a 4 GB machine reduces
+/// worker count instead of swapping.
+const WORKER_BYTES_PER_BULK_MIB: u64 = 3;
+
+/// The resource plan for one run.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Plan {
+ /// Threads for the phase-A scan pool (hash, sniff, sample).
+ pub scan_threads: usize,
+ /// Concurrent phase-B index workers.
+ pub index_workers: usize,
+ /// Concurrent isolated PDF extraction subprocesses.
+ pub pdf_workers: usize,
+ /// Bytes this run considers itself entitled to.
+ pub safe_zone_bytes: u64,
+ /// Anything the machine forced on the run, for the operator to see.
+ pub notes: Vec<String>,
+}
+
+/// Build the plan for this machine.
+///
+/// `requested_workers` / `requested_pdf_workers` are the CLI values when the
+/// user passed them, `None` when they did not.
+pub fn plan(
+ requested_workers: Option<usize>,
+ requested_pdf_workers: Option<usize>,
+ bulk_mb: usize,
+) -> Plan {
+ plan_for(
+ resource::cores(),
+ resource::memory_safe_zone_bytes(),
+ requested_workers,
+ requested_pdf_workers,
+ bulk_mb,
+ )
+}
+
+/// Pure planning rule — the tested half of [`plan`].
+pub fn plan_for(
+ cores: usize,
+ safe_zone_bytes: u64,
+ requested_workers: Option<usize>,
+ requested_pdf_workers: Option<usize>,
+ bulk_mb: usize,
+) -> Plan {
+ let cores = cores.max(1);
+ let mut notes = Vec::new();
+
+ // Phase A: every core by default. "Use the machine" belongs here — this is
+ // the phase that is actually CPU-bound.
+ let scan_threads = requested_workers.unwrap_or(cores).max(1);
+
+ // Phase B: the same count, unless the safe zone cannot pay for that many
+ // in-flight bulk buffers.
+ let per_worker = (bulk_mb.max(1) as u64)
+ .saturating_mul(WORKER_BYTES_PER_BULK_MIB)
+ .saturating_mul(MIB);
+ let affordable = (safe_zone_bytes / per_worker).max(1) as usize;
+ let mut index_workers = scan_threads;
+ if index_workers > affordable {
+ notes.push(format!(
+ "memory safe zone {} MiB allows {affordable} index workers at --bulk-mb {bulk_mb}, \
+ not {index_workers}",
+ safe_zone_bytes / MIB
+ ));
+ index_workers = affordable;
+ }
+
+ // PDF workers: bounded by the measured ceiling, by the cores available,
+ // and by what the safe zone can pay for at 1536 MiB of address space each.
+ let pdf_affordable = (safe_zone_bytes / PDF_WORKER_BYTES).max(1) as usize;
+ let pdf_default = cores.min(MAX_PDF_WORKERS);
+ let mut pdf_workers = requested_pdf_workers.unwrap_or(pdf_default).max(1);
+ if pdf_workers > pdf_affordable {
+ notes.push(format!(
+ "memory safe zone {} MiB allows {pdf_affordable} PDF worker(s) at 1536 MiB each, \
+ not {pdf_workers}",
+ safe_zone_bytes / MIB
+ ));
+ pdf_workers = pdf_affordable;
+ }
+
+ Plan {
+ scan_threads,
+ index_workers,
+ pdf_workers: pdf_workers.min(MAX_PDF_WORKERS),
+ safe_zone_bytes,
+ notes,
+ }
+}
+
+impl Plan {
+ /// One line for the run header and the `--json` summary.
+ pub fn describe(&self) -> String {
+ format!(
+ "resources: {} scan threads, {} index workers, {} pdf workers, memory safe zone {} MiB ({})",
+ self.scan_threads,
+ self.index_workers,
+ self.pdf_workers,
+ self.safe_zone_bytes / MIB,
+ resource::describe(),
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const GIB: u64 = 1024 * MIB;
+
+ #[test]
+ fn the_default_plan_uses_the_whole_machine_for_the_cpu_bound_phase() {
+ let plan = plan_for(12, 8 * GIB, None, None, 8);
+ assert_eq!(plan.scan_threads, 12, "phase A is the CPU-bound phase");
+ assert_eq!(plan.index_workers, 12);
+ assert_eq!(plan.pdf_workers, 4);
+ assert!(plan.notes.is_empty());
+ // The pre-#240 default capped both at 8 on any machine with more cores.
+ assert_eq!(plan_for(32, 32 * GIB, None, None, 8).scan_threads, 32);
+ }
+
+ #[test]
+ fn an_explicit_request_is_honoured_on_both_phases() {
+ let plan = plan_for(32, 32 * GIB, Some(2), Some(1), 8);
+ assert_eq!(plan.scan_threads, 2, "--workers must bound phase A too");
+ assert_eq!(plan.index_workers, 2);
+ assert_eq!(plan.pdf_workers, 1);
+ }
+
+ #[test]
+ fn a_small_machine_gets_fewer_workers_and_is_told_why() {
+ // A 32-core box squeezed into a 512 MiB safe zone (small container),
+ // asked for the biggest bulk size: 72 MiB per worker buys 7 of them.
+ let plan = plan_for(32, 512 * MIB, None, None, 24);
+ assert_eq!(plan.index_workers, 7);
+ assert_eq!(
+ plan.scan_threads, 32,
+ "scanning is not what costs the memory"
+ );
+ assert!(plan.notes[0].contains("index workers"));
+ // One PDF worker is all a 1 GiB safe zone can pay for at 1536 MiB each.
+ assert_eq!(plan.pdf_workers, 1);
+ assert!(plan.notes.iter().any(|n| n.contains("PDF worker")));
+ }
+
+ #[test]
+ fn the_plan_is_never_zero_or_absurd() {
+ for cores in [0usize, 1, 2, 256] {
+ for safe in [0u64, 64 * MIB, GIB, 512 * GIB] {
+ for bulk in [1usize, 8, 24] {
+ let plan = plan_for(cores, safe, None, None, bulk);
+ assert!(plan.scan_threads >= 1);
+ assert!(plan.index_workers >= 1);
+ assert!((1..=MAX_PDF_WORKERS).contains(&plan.pdf_workers));
+ }
+ }
+ }
+ }
+}
diff --git a/engine/crates/xerj-autoindex/tests/scan_pool_width.rs b/engine/crates/xerj-autoindex/tests/scan_pool_width.rs
new file mode 100644
index 000000000..0cc77a988
--- /dev/null
+++ b/engine/crates/xerj-autoindex/tests/scan_pool_width.rs
@@ -0,0 +1,59 @@
+//! `--workers N` must produce a phase-A pool of exactly N threads.
+//!
+//! Before #240 phase A (content hashing, sniffing, sampling) ran on rayon's
+//! default global pool, which is sized to every core on first use. A user who
+//! asked for 2 workers on a 12-core Mac still got a 12-wide CPU storm, so
+//! turning the knob down did not give the machine back — the behaviour behind
+//! "Macs are really slow while autoindexing a large code base".
+//!
+//! The pool is process-global, so this lives in its own integration-test file:
+//! one test binary, one pool, no ordering assumptions.
+
+use rayon::prelude::*;
+use xerj_autoindex::pool;
+
+#[test]
+fn configure_bounds_phase_a_to_the_requested_width() {
+ let requested = 2;
+ let machine = std::thread::available_parallelism()
+ .map(|n| n.get())
+ .unwrap();
+ assert!(
+ machine > requested,
+ "only meaningful on a machine with more cores than we ask for (machine={machine})"
+ );
+
+ pool::configure(requested);
+
+ // Pre-fix this was `machine`: phase A saw rayon's global pool.
+ let widths: Vec<usize> = pool::install(|| {
+ (0..256)
+ .into_par_iter()
+ .map(|_| rayon::current_num_threads())
+ .collect()
+ });
+ assert!(
+ widths.iter().all(|&w| w == requested),
+ "phase A must run at the requested width, saw {:?}",
+ widths.iter().max()
+ );
+
+ // And the work really is confined to those threads, not merely counted.
+ let threads: std::collections::BTreeSet<String> = pool::install(|| {
+ (0..256)
+ .into_par_iter()
+ .map(|_| {
+ std::thread::current()
+ .name()
+ .unwrap_or("unnamed")
+ .to_string()
+ })
+ .collect()
+ });
+ assert!(
+ threads.len() <= requested,
+ "phase A used {} distinct threads: {threads:?}",
+ threads.len()
+ );
+ assert!(threads.iter().all(|n| n.starts_with("xerj-scan-")));
+}
diff --git a/engine/crates/xerj-common/Cargo.toml b/engine/crates/xerj-common/Cargo.toml
index 4ee481307..b729f08c7 100644
--- a/engine/crates/xerj-common/Cargo.toml
+++ b/engine/crates/xerj-common/Cargo.toml
@@ -23,6 +23,9 @@ tracing.workspace = true
bytes.workspace = true
byteorder.workspace = true
prometheus.workspace = true
+# Machine probes for `resource`: sysconf/sysctl/setpriority. No abstraction
+# layer buys anything here — the calls differ per platform by design.
+libc = "0.2"
[dev-dependencies]
tempfile.workspace = true
diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rs
index 8eb487731..a63eec027 100644
--- a/engine/crates/xerj-common/src/config.rs
+++ b/engine/crates/xerj-common/src/config.rs
@@ -982,9 +982,7 @@ impl Default for EmbeddingConfig {
onnx_model_path: String::new(),
onnx_tokenizer_path: String::new(),
onnx_scheduling_window: 64,
- onnx_intra_threads: std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(1),
+ onnx_intra_threads: crate::resource::threads_for(crate::resource::Workload::Latency),
onnx_session_pool_size: 1,
onnx_max_pending: 4096,
onnx_max_batch: 64,
@@ -1171,29 +1169,41 @@ pub struct EngineConfig {
/// Doubling shards roughly doubles sustained ingest throughput (linear
/// scaling) until memory bandwidth is saturated.
pub ingest_shards: usize,
- /// Maximum concurrent flush tasks across all shards (default: `max(1, num_cpus / 4)`).
+ /// Maximum concurrent shard flush finalizations (default: the maintenance
+ /// share of the machine, `max(2, num_cpus / 8)` — see
+ /// [`crate::resource::threads_for`]). `XERJ_FIN_CONC` overrides it for
+ /// one run.
pub flush_workers: usize,
- /// Background merge threads (default: `2`).
+ /// Threads in the background merge pool (default: the maintenance share of
+ /// the machine, `max(2, num_cpus / 8)`). Merges are the one pool that is
+ /// deliberately kept narrow: nobody waits on a merge, and an all-core merge
+ /// pass was measured stalling ingest for 17.5 s.
pub merge_workers: usize,
- /// Parallel segment scan threads for search (default: `max(1, num_cpus / 4)`).
+ /// Threads available to search segment fan-out — rayon's global pool
+ /// (default: every core). Search is the path a user waits on, so it gets
+ /// the whole machine unless you deliberately hold cores back.
pub search_workers: usize,
}
impl Default for EngineConfig {
fn default() -> Self {
- let cpus = std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(4);
+ use crate::resource::{threads_for, Workload};
+ let cpus = crate::resource::cores();
Self {
ingest_shards: (cpus / 2).max(1).next_power_of_two(),
- flush_workers: (cpus / 4).max(1),
- merge_workers: 2,
- search_workers: (cpus / 4).max(1),
+ flush_workers: threads_for(Workload::Maintenance),
+ merge_workers: threads_for(Workload::Maintenance),
+ search_workers: threads_for(Workload::Latency),
}
}
}
impl EngineConfig {
+ /// Upper bound on any of the worker knobs. Threads are not free: past this
+ /// the request is far more likely to be a typo than an intention, and a
+ /// silently clamped typo is the bug class in #204.
+ pub const MAX_WORKERS: usize = 4096;
+
pub fn validate(&self) -> Result<(), crate::XerjError> {
if self.ingest_shards == 0 || !self.ingest_shards.is_power_of_two() {
return Err(crate::XerjError::config(format!(
@@ -1207,10 +1217,20 @@ impl EngineConfig {
self.ingest_shards
)));
}
- if self.flush_workers == 0 {
- return Err(crate::XerjError::config(
- "engine.flush_workers must be >= 1",
- ));
+ // Every worker knob is validated, because every worker knob is now
+ // wired to a pool: an out-of-range value must be refused at startup
+ // rather than accepted and quietly replaced with something else.
+ for (name, value) in [
+ ("engine.flush_workers", self.flush_workers),
+ ("engine.merge_workers", self.merge_workers),
+ ("engine.search_workers", self.search_workers),
+ ] {
+ if value == 0 || value > Self::MAX_WORKERS {
+ return Err(crate::XerjError::config(format!(
+ "{name} must be in the range 1..={}, got {value}",
+ Self::MAX_WORKERS
+ )));
+ }
}
Ok(())
}
diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rs
index 7a94e6a1e..a8a3d1765 100644
--- a/engine/crates/xerj-common/src/lib.rs
+++ b/engine/crates/xerj-common/src/lib.rs
@@ -19,12 +19,14 @@
//! - [`schema`] — Index schema management and mapping evolution
//! - [`metrics`] — Prometheus counters, histograms, and gauges
//! - [`net`] — Network trust primitives (trusted-proxy CIDR matching)
+//! - [`resource`] — The machine-resource policy: cores, memory budget, thread priority
pub mod config;
pub mod error;
pub mod fsio;
pub mod metrics;
pub mod net;
+pub mod resource;
pub mod schema;
pub mod types;
diff --git a/engine/crates/xerj-common/src/resource.rs b/engine/crates/xerj-common/src/resource.rs
new file mode 100644
index 000000000..a6d6d6658
--- /dev/null
+++ b/engine/crates/xerj-common/src/resource.rs
@@ -0,0 +1,658 @@
+//! The machine-resource policy — the one place that answers *how many cores*
+//! and *how much memory* XERJ may take on the machine it is running on.
+//!
+//! Before this module the answers were scattered magic numbers: `.min(8)` in
+//! the autoindex CLI, `(cores * 8).clamp(64, 512)` in the server, `cores / 8`
+//! in three engine pools, a hardcoded `8 GiB` "system memory" in the governor
+//! on every non-Linux host, and three `EngineConfig` knobs that nothing read
+//! (issue #240). Each was defensible on its own; together they had no story,
+//! and on a laptop they added up to a bad citizen.
+//!
+//! # The policy
+//!
+//! 1. **Latency-critical work gets the whole machine.** Search fan-out and
+//! bulk parse are what a user is waiting on; holding cores back there only
+//! makes the wait longer.
+//! 2. **Background work gets a named reserve, not the whole machine.** Merges
+//! and flush side-cars have nobody waiting on them, so they run on a
+//! fraction of the cores and at a lower thread priority.
+//! 3. **Memory is budgeted from what the machine actually has**, with an
+//! explicit slice left for the user — never from an assumed constant.
+//! 4. **Every rule is a function here with its reason written down**, so the
+//! next tuning argument is about a number in one place instead of six.
+//!
+//! # Peer precedent (retrieved, not copied — see the reference-coding mandate)
+//!
+//! * `quickwit-common/src/cpus.rs:23-63` (Apache-2.0): core count comes from
+//! `QW_NUM_CPUS`, then `KUBERNETES_LIMITS_CPU`, then the OS, then a warned
+//! default — an env override ahead of the OS, and a *loud* fallback.
+//! * `quickwit-common/src/runtimes.rs:89-110` (Apache-2.0): headroom scaled by
+//! machine size — all cores at 0..=3, `n - 1` at 4..=6, `n - 2` at 7+.
+//! Reserve as a function of the machine, never a flat cap.
+//! * `quickwit-config/src/node_config/mod.rs` `default_merge_concurrency()`
+//! (Apache-2.0): background merges get `num_cpus * 2 / 3`.
+//! * `meilisearch/crates/meilisearch/src/option.rs:818-821,885` (MIT core):
+//! indexing pool = `num_cpus / 2`, with the stated reason "the indexer
+//! avoids using more than half of a machine's total processing units. This
+//! ensures Meilisearch is always ready to perform searches, even while you
+//! are updating an index"; `option.rs:1103-1106` budgets indexing memory at
+//! two thirds of (cgroup-aware) total RAM.
+//! * `tantivy/src/indexer/index_writer.rs:32-36,285-291` (MIT): the writer is
+//! capped at 8 threads, and a memory budget below the per-thread minimum is
+//! **rejected with an error** rather than silently clamped — the same
+//! discipline this module applies to out-of-range knobs.
+//!
+//! What XERJ takes from that is the *shape* — full parallelism on the path a
+//! user waits on, a declared reserve for the path nobody waits on, budgets
+//! derived from the real machine — not the specific constants, which are tied
+//! to those engines' own measurements.
+
+use std::sync::OnceLock;
+
+const MIB: u64 = 1024 * 1024;
+const GIB: u64 = 1024 * MIB;
+
+/// Environment override for the detected core count, honoured ahead of the OS
+/// so a container or a CI runner can pin it (quickwit precedent, `cpus.rs:20`).
+pub const NUM_CPUS_ENV: &str = "XERJ_NUM_CPUS";
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Cores
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// What a pool is for. This is the input to every thread-count decision, so a
+/// new pool has to say which side of the latency/background line it is on.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Workload {
+ /// Someone is waiting on it: search fan-out, bulk parse/analyze/insert,
+ /// client-side content hashing and sniffing. Gets every core.
+ Latency,
+ /// Useful work with no client waiting, but which the user's next request
+ /// depends on: flush side-cars, segment finalisation. Gets every core, at
+ /// a lower thread priority, because holding it back delays visibility.
+ Background,
+ /// Pure maintenance nobody is waiting on: merges, compaction. Gets a
+ /// declared fraction of the machine so it can never take the box over.
+ Maintenance,
+}
+
+/// Logical cores XERJ may use, in the order the answer is trusted:
+/// `XERJ_NUM_CPUS`, the cgroup CPU quota (Linux containers), the OS, then a
+/// warned fallback of 4.
+///
+/// Cached: the answer cannot change usefully within a process, and the cgroup
+/// read is a file parse.
+pub fn cores() -> usize {
+ static CORES: OnceLock<usize> = OnceLock::new();
+ *CORES.get_or_init(|| {
+ let (n, note) = resolve_cores(
+ std::env::var(NUM_CPUS_ENV).ok().as_deref(),
+ cgroup_cpu_quota(),
+ std::thread::available_parallelism().map(|n| n.get()).ok(),
+ );
+ if let Some(note) = note {
+ warn_once(&note);
+ }
+ n
+ })
+}
+
+/// Report a policy problem on both channels.
+///
+/// The server installs a `tracing` subscriber; `xerj autoindex` does not, so a
+/// warning emitted only through `tracing` is invisible to exactly the user most
+/// likely to have set `XERJ_NUM_CPUS` wrong. These fire at most once per process
+/// and only when something is misconfigured or unreadable, so the duplicate line
+/// in a server log is a fair price for never losing the message.
+fn warn_once(message: &str) {
+ tracing::warn!("{message}");
+ eprintln!("xerj: {message}");
+}
+
+/// Pure core-count resolution — the tested half of [`cores`].
+///
+/// Returns the count and an optional warning: an unusable `XERJ_NUM_CPUS` or a
+/// machine whose core count cannot be detected must say so, never resolve
+/// silently to a number the operator did not ask for (issue #204's class).
+fn resolve_cores(
+ env: Option<&str>,
+ cgroup_quota: Option<usize>,
+ os: Option<usize>,
+) -> (usize, Option<String>) {
+ if let Some(raw) = env.map(str::trim).filter(|s| !s.is_empty()) {
+ return match raw.parse::<usize>() {
+ Ok(n) if n >= 1 => (n, None),
+ _ => (
+ os.unwrap_or(4),
+ Some(format!(
+ "{NUM_CPUS_ENV}={raw} is not a positive integer; ignoring it and using the \
+ detected core count instead"
+ )),
+ ),
+ };
+ }
+ match (os, cgroup_quota) {
+ // A cgroup CPU quota is a hard ceiling: the kernel throttles past it,
+ // so sizing pools off the host's core count only builds queues.
+ (Some(os), Some(q)) => (q.min(os).max(1), None),
+ (Some(os), None) => (os, None),
+ (None, Some(q)) => (q.max(1), None),
+ (None, None) => (
+ 4,
+ Some(
+ "could not detect the number of CPUs on this machine; assuming 4 — set \
+ XERJ_NUM_CPUS to the real count"
+ .into(),
+ ),
+ ),
+ }
+}
+
+/// Whole cores permitted by this process's cgroup CPU quota, if any (cgroup v2
+/// `cpu.max`, then cgroup v1 `cpu.cfs_quota_us`/`cpu.cfs_period_us`). A
+/// fractional quota rounds up to 1 — half a core still runs one thread.
+#[cfg(target_os = "linux")]
+fn cgroup_cpu_quota() -> Option<usize> {
+ if let Ok(s) = std::fs::read_to_string("/sys/fs/cgroup/cpu.max") {
+ let mut parts = s.split_whitespace();
+ let quota = parts.next()?;
+ let period: u64 = parts.next()?.parse().ok()?;
+ if quota != "max" && period > 0 {
+ let quota: u64 = quota.parse().ok()?;
+ return Some(quota.div_ceil(period).max(1) as usize);
+ }
+ return None;
+ }
+ let quota: i64 = std::fs::read_to_string("/sys/fs/cgroup/cpu/cpu.cfs_quota_us")
+ .ok()?
+ .trim()
+ .parse()
+ .ok()?;
+ let period: i64 = std::fs::read_to_string("/sys/fs/cgroup/cpu/cpu.cfs_period_us")
+ .ok()?
+ .trim()
+ .parse()
+ .ok()?;
+ (quota > 0 && period > 0).then(|| (quota as u64).div_ceil(period as u64).max(1) as usize)
+}
+
+#[cfg(not(target_os = "linux"))]
+fn cgroup_cpu_quota() -> Option<usize> {
+ None
+}
+
+/// Threads for a pool serving `workload` on this machine.
+pub fn threads_for(workload: Workload) -> usize {
+ threads_for_cores(workload, cores())
+}
+
+/// Pure thread-count rule — the tested half of [`threads_for`].
+///
+/// `Latency` and `Background` get every core: XERJ's measured ingest/read
+/// tuning separates them by *thread priority*, not by width (see the pool
+/// docs in `xerj-engine/src/lib.rs`), and narrowing them would trade
+/// throughput for nothing. `Maintenance` gets `max(2, cores / 8)` — the width
+/// measured on the 1M×c8 ingest benchmark, where an all-core merge pool stalled
+/// ingest for 17.5 s per merge pass.
+pub const fn threads_for_cores(workload: Workload, cores: usize) -> usize {
+ let cores = if cores == 0 { 1 } else { cores };
+ match workload {
+ Workload::Latency | Workload::Background => cores,
+ Workload::Maintenance => {
+ let eighth = cores / 8;
+ if eighth < 2 {
+ if cores < 2 {
+ 1
+ } else {
+ 2
+ }
+ } else {
+ eighth
+ }
+ }
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Thread priority
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Where a pool sits on the maintenance ladder, i.e. how far below foreground
+/// work its threads should be scheduled.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Deprioritize {
+ /// Ingest parse/analyze/insert — one step below reads.
+ Ingest,
+ /// Flush side-cars and finalisation — below ingest.
+ Background,
+ /// Merges — the bottom of the ladder.
+ Maintenance,
+}
+
+/// The platform-specific action that implements a rung of the ladder.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PriorityAction {
+ /// Leave the thread at normal priority.
+ None,
+ /// `nice(n)` on the calling **thread** — Linux semantics, where the nice
+ /// value is a per-task attribute.
+ NiceThread(i32),
+ /// `setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG)` — Darwin's
+ /// thread-scoped background tier.
+ DarwinThreadBackground,
+}
+
+/// The platforms whose scheduling semantics differ enough to matter here.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Platform {
+ Linux,
+ MacOs,
+ Other,
+}
+
+/// This build's platform.
+pub const HOST_PLATFORM: Platform = if cfg!(target_os = "linux") {
+ Platform::Linux
+} else if cfg!(target_os = "macos") {
+ Platform::MacOs
+} else {
+ Platform::Other
+};
+
+/// The ladder, as a decision table — the tested half of
+/// [`deprioritize_current_thread`].
+///
+/// **Why this is not just `nice()` everywhere.** POSIX `nice()` adjusts the
+/// *process*; Linux makes it a per-task (per-thread) attribute, which is what
+/// the measured ingest/background/merge ladder relies on. Darwin keeps the
+/// POSIX meaning, so calling `nice(5)`, `nice(10)`, `nice(15)` from pool
+/// `start_handler`s there does not separate the three pools at all — it
+/// ratchets the *whole server process*, search threads included, toward the
+/// nice ceiling as pool threads start. That is the opposite of the intent, on
+/// the platform whose users reported the slowness (#240).
+///
+/// Darwin's replacement is thread-scoped: `PRIO_DARWIN_THREAD` with
+/// `PRIO_DARWIN_BG` moves *this thread* into the background tier. It is an
+/// on/off tier, not a ladder rung, and it throttles I/O as well as CPU — right
+/// for merges, wrong for ingest and flush side-cars (a user's next search waits
+/// on those). So on macOS only the bottom rung is applied, and the two upper
+/// rungs stay at normal priority rather than being faked with a call that would
+/// deprioritize the whole process.
+///
+/// This decision table is reasoned from documented POSIX/Darwin semantics and
+/// the libc surface; it has **not** been measured on Apple hardware.
+pub const fn priority_action(platform: Platform, class: Deprioritize) -> PriorityAction {
+ match platform {
+ Platform::Linux => match class {
+ Deprioritize::Ingest => PriorityAction::NiceThread(5),
+ Deprioritize::Background => PriorityAction::NiceThread(10),
+ Deprioritize::Maintenance => PriorityAction::NiceThread(15),
+ },
+ Platform::MacOs => match class {
+ Deprioritize::Ingest | Deprioritize::Background => PriorityAction::None,
+ Deprioritize::Maintenance => PriorityAction::DarwinThreadBackground,
+ },
+ // Windows and the BSDs: no per-thread nice with the semantics above.
+ Platform::Other => PriorityAction::None,
+ }
+}
+
+/// Apply the ladder to the calling thread. Call it from a pool's
+/// `start_handler`, once per pool thread.
+pub fn deprioritize_current_thread(class: Deprioritize) {
+ match priority_action(HOST_PLATFORM, class) {
+ PriorityAction::None => {}
+ PriorityAction::NiceThread(_n) => {
+ #[cfg(all(unix, not(target_os = "macos")))]
+ // SAFETY: `nice` takes an int and touches only the caller's
+ // scheduling attributes; on Linux that is this thread.
+ unsafe {
+ let _ = libc::nice(_n);
+ }
+ }
+ PriorityAction::DarwinThreadBackground => {
+ #[cfg(target_os = "macos")]
+ // SAFETY: `setpriority` with PRIO_DARWIN_THREAD and `who = 0`
+ // addresses the calling thread only.
+ unsafe {
+ let _ = libc::setpriority(libc::PRIO_DARWIN_THREAD, 0, libc::PRIO_DARWIN_BG);
+ }
+ }
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Memory
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Total physical RAM, or `None` when this platform has no probe here.
+///
+/// `None` means *unknown*, and callers must treat it as unknown — the bug this
+/// replaces was a non-Linux fallback that returned a fictional 8 GiB, so every
+/// derived budget on a 64 GB Mac was sized for a machine eight times smaller
+/// (#240 §7).
+pub fn total_memory_bytes() -> Option<u64> {
+ static TOTAL: OnceLock<Option<u64>> = OnceLock::new();
+ *TOTAL.get_or_init(|| {
+ let total = probe_total_memory();
+ if total.is_none() {
+ warn_once(&format!(
+ "cannot read this machine's total RAM on {}; memory budgets fall back to \
+ conservative defaults — set them explicitly (limits.max_total_memtable_mb, \
+ autoindex --workers/--bulk-mb) if that is wrong",
+ std::env::consts::OS
+ ));
+ }
+ total
+ })
+}
+
+/// RAM available for a new allocation without swapping — Linux `MemAvailable`.
+/// `None` where unknown (including macOS: Darwin exposes free/inactive/
+/// compressed page counts through `host_statistics64`, which is not in the
+/// pinned `libc` surface, and guessing from `hw.memsize` alone would be a
+/// fabricated number).
+pub fn available_memory_bytes() -> Option<u64> {
+ probe_available_memory()
+}
+
+/// Resident set size of this process, or `None` where this platform has no
+/// probe. `None` must disable an RSS-driven decision, never read as zero.
+pub fn current_rss_bytes() -> Option<u64> {
+ probe_rss()
+}
+
+#[cfg(target_os = "linux")]
+fn probe_total_memory() -> Option<u64> {
+ meminfo_field(&std::fs::read_to_string("/proc/meminfo").ok()?, "MemTotal:")
+}
+
+#[cfg(target_os = "macos")]
+fn probe_total_memory() -> Option<u64> {
+ // `hw.memsize` is the machine's physical RAM in bytes.
+ sysctl_u64(c"hw.memsize")
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos")))]
+fn probe_total_memory() -> Option<u64> {
+ None
+}
+
+#[cfg(target_os = "linux")]
+fn probe_available_memory() -> Option<u64> {
+ meminfo_field(
+ &std::fs::read_to_string("/proc/meminfo").ok()?,
+ "MemAvailable:",
+ )
+}
+
+#[cfg(not(target_os = "linux"))]
+fn probe_available_memory() -> Option<u64> {
+ None
+}
+
+/// Parse one `kB` field out of `/proc/meminfo`, in bytes.
+#[cfg(any(target_os = "linux", test))]
+fn meminfo_field(meminfo: &str, key: &str) -> Option<u64> {
+ for line in meminfo.lines() {
+ if let Some(rest) = line.trim_start().strip_prefix(key) {
+ let kb: u64 = rest.split_whitespace().next()?.parse().ok()?;
+ return Some(kb.saturating_mul(1024));
+ }
+ }
+ None
+}
+
+#[cfg(target_os = "linux")]
+fn probe_rss() -> Option<u64> {
+ let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
+ let pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
+ // SAFETY: `sysconf` reads a system constant.
+ let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
+ let page = if page > 0 { page as u64 } else { 4096 };
+ Some(pages.saturating_mul(page))
+}
+
+#[cfg(target_os = "macos")]
+fn probe_rss() -> Option<u64> {
+ let mut info = std::mem::MaybeUninit::<libc::proc_taskinfo>::zeroed();
+ let size = std::mem::size_of::<libc::proc_taskinfo>() as libc::c_int;
+ // SAFETY: `proc_pidinfo` writes at most `size` bytes into `info` and
+ // reports how many it wrote; anything short is treated as a failure.
+ let written = unsafe {
+ libc::proc_pidinfo(
+ std::process::id() as libc::c_int,
+ libc::PROC_PIDTASKINFO,
+ 0,
+ info.as_mut_ptr() as *mut libc::c_void,
+ size,
+ )
+ };
+ if written != size {
+ return None;
+ }
+ // SAFETY: proc_pidinfo filled the whole struct (checked above).
+ Some(unsafe { info.assume_init() }.pti_resident_size)
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos")))]
+fn probe_rss() -> Option<u64> {
+ None
+}
+
+#[cfg(target_os = "macos")]
+fn sysctl_u64(name: &std::ffi::CStr) -> Option<u64> {
+ let mut value: u64 = 0;
+ let mut len = std::mem::size_of::<u64>();
+ // SAFETY: `name` is NUL-terminated, and the out-buffer length is the size
+ // of the buffer being written.
+ let rc = unsafe {
+ libc::sysctlbyname(
+ name.as_ptr(),
+ &mut value as *mut u64 as *mut libc::c_void,
+ &mut len,
+ std::ptr::null_mut(),
+ 0,
+ )
+ };
+ (rc == 0 && len == std::mem::size_of::<u64>() && value > 0).then_some(value)
+}
+
+/// How many bytes a **client-side** XERJ tool (autoindex) may allocate on a
+/// machine whose owner is also using it.
+///
+/// The server's own admission budgets are cgroup-aware and live in
+/// `xerj-engine::governor`; this is the laptop-citizen rule for the client:
+///
+/// ```text
+/// reserve = max(1 GiB, total / 8) // left for the user
+/// safe = min(available - reserve, total / 2) // never more than half
+/// ```
+///
+/// Half of RAM as the ceiling follows the same reasoning meilisearch gives for
+/// its two-thirds indexing budget (`option.rs:1103-1106`) — a machine that is
+/// also serving its owner should not have its page cache evicted by a
+/// background indexer. When `total` is unknown the caller gets
+/// [`FALLBACK_SAFE_ZONE_BYTES`], which is deliberately small: an unknown
+/// machine is not an excuse to take an unknown amount of it.
+pub fn memory_safe_zone_bytes() -> u64 {
+ match total_memory_bytes() {
+ Some(total) => safe_zone(total, available_memory_bytes()),
+ None => FALLBACK_SAFE_ZONE_BYTES,
+ }
+}
+
+/// The budget used when the machine's RAM cannot be probed at all: 1 GiB,
+/// small enough to be safe on the smallest machine XERJ is expected to run on.
+pub const FALLBACK_SAFE_ZONE_BYTES: u64 = GIB;
+
+/// Pure safe-zone rule — the tested half of [`memory_safe_zone_bytes`].
+fn safe_zone(total: u64, available: Option<u64>) -> u64 {
+ let reserve = (total / 8).max(GIB);
+ let headroom = available.unwrap_or(total).saturating_sub(reserve);
+ headroom.min(total / 2).max(256 * MIB)
+}
+
+/// One line describing what this policy decided, for a startup log or a
+/// `--json` run summary. Sizes are in MiB.
+pub fn describe() -> String {
+ let mib = |b: Option<u64>| match b {
+ Some(b) => format!("{}", b / MIB),
+ None => "unknown".to_string(),
+ };
+ format!(
+ "cores={} ram_total_mib={} ram_available_mib={} safe_zone_mib={}",
+ cores(),
+ mib(total_memory_bytes()),
+ mib(available_memory_bytes()),
+ memory_safe_zone_bytes() / MIB,
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn env_override_beats_the_os_and_a_bad_value_is_reported() {
+ assert_eq!(resolve_cores(Some("6"), None, Some(64)), (6, None));
+ assert_eq!(resolve_cores(Some(" 6 "), None, Some(64)), (6, None));
+ // Accepted-and-ignored is the class this repo keeps re-finding (#204):
+ // an unusable override must be reported, not silently discarded.
+ let (n, note) = resolve_cores(Some("many"), None, Some(64));
+ assert_eq!(n, 64);
+ assert!(note.unwrap().contains("XERJ_NUM_CPUS=many"));
+ let (n, note) = resolve_cores(Some("0"), None, Some(64));
+ assert_eq!(n, 64);
+ assert!(note.is_some());
+ // Empty means "unset", not "invalid".
+ assert_eq!(resolve_cores(Some(""), None, Some(8)), (8, None));
+ }
+
+ #[test]
+ fn a_cgroup_quota_caps_the_host_core_count() {
+ assert_eq!(resolve_cores(None, Some(2), Some(64)), (2, None));
+ // A quota larger than the machine is not a licence to oversubscribe.
+ assert_eq!(resolve_cores(None, Some(128), Some(8)), (8, None));
+ assert_eq!(resolve_cores(None, None, Some(8)), (8, None));
+ let (n, note) = resolve_cores(None, None, None);
+ assert_eq!(n, 4);
+ assert!(note.is_some(), "an undetectable machine must say so");
+ }
+
+ #[test]
+ fn latency_work_gets_every_core_and_maintenance_gets_a_reserve() {
+ for cores in [1usize, 2, 4, 8, 12, 16, 32, 64] {
+ assert_eq!(threads_for_cores(Workload::Latency, cores), cores);
+ assert_eq!(threads_for_cores(Workload::Background, cores), cores);
+ let maint = threads_for_cores(Workload::Maintenance, cores);
+ assert!(maint >= 1 && maint <= cores, "cores={cores} maint={maint}");
+ assert!(
+ maint <= (cores / 2).max(2),
+ "maintenance must never take the machine over: cores={cores} maint={maint}"
+ );
+ }
+ // The measured widths this replaces, preserved exactly.
+ assert_eq!(threads_for_cores(Workload::Maintenance, 32), 4);
+ assert_eq!(threads_for_cores(Workload::Maintenance, 8), 2);
+ assert_eq!(threads_for_cores(Workload::Maintenance, 1), 1);
+ assert_eq!(threads_for_cores(Workload::Latency, 0), 1);
+ }
+
+ #[test]
+ fn macos_never_uses_process_wide_nice_for_the_ladder() {
+ // The #240 §5 defect: `nice()` is per-process on Darwin, so using it
+ // from pool start handlers deprioritizes search along with merges.
+ for class in [
+ Deprioritize::Ingest,
+ Deprioritize::Background,
+ Deprioritize::Maintenance,
+ ] {
+ assert!(
+ !matches!(
+ priority_action(Platform::MacOs, class),
+ PriorityAction::NiceThread(_)
+ ),
+ "{class:?} must not use nice() on macOS"
+ );
+ }
+ assert_eq!(
+ priority_action(Platform::MacOs, Deprioritize::Maintenance),
+ PriorityAction::DarwinThreadBackground
+ );
+ // Ingest and flush side-cars stay at normal priority there: Darwin's
+ // background tier throttles I/O, and a user's next search waits on them.
+ assert_eq!(
+ priority_action(Platform::MacOs, Deprioritize::Ingest),
+ PriorityAction::None
+ );
+ assert_eq!(
+ priority_action(Platform::MacOs, Deprioritize::Background),
+ PriorityAction::None
+ );
+ // Linux keeps the measured ladder.
+ assert_eq!(
+ priority_action(Platform::Linux, Deprioritize::Ingest),
+ PriorityAction::NiceThread(5)
+ );
+ assert_eq!(
+ priority_action(Platform::Linux, Deprioritize::Background),
+ PriorityAction::NiceThread(10)
+ );
+ assert_eq!(
+ priority_action(Platform::Linux, Deprioritize::Maintenance),
+ PriorityAction::NiceThread(15)
+ );
+ }
+
+ #[test]
+ fn meminfo_parsing_reads_total_and_available() {
+ let sample =
+ "MemTotal: 16316908 kB\nMemFree: 1234 kB\nMemAvailable: 8000000 kB\n";
+ assert_eq!(meminfo_field(sample, "MemTotal:"), Some(16_316_908 * 1024));
+ assert_eq!(
+ meminfo_field(sample, "MemAvailable:"),
+ Some(8_000_000 * 1024)
+ );
+ assert_eq!(meminfo_field(sample, "Bogus:"), None);
+ assert_eq!(meminfo_field("MemTotal: garbage\n", "MemTotal:"), None);
+ }
+
+ #[test]
+ fn the_safe_zone_leaves_the_user_a_reserve_and_never_exceeds_half() {
+ // 16 GiB laptop with 10 GiB available: reserve 2 GiB, ceiling 8 GiB.
+ assert_eq!(safe_zone(16 * GIB, Some(10 * GIB)), 8 * GIB);
+ // Same laptop under pressure: only what is actually free, minus reserve.
+ assert_eq!(safe_zone(16 * GIB, Some(4 * GIB)), 2 * GIB);
+ // Availability unknown (macOS): fall back to the half-of-RAM ceiling.
+ assert_eq!(safe_zone(16 * GIB, None), 8 * GIB);
+ // Small container: the 1 GiB floor of the reserve still applies.
+ assert_eq!(safe_zone(2 * GIB, Some(2 * GIB)), GIB);
+ // Never zero, however tight the machine.
+ assert_eq!(safe_zone(512 * MIB, Some(0)), 256 * MIB);
+ for total in [GIB, 4 * GIB, 16 * GIB, 128 * GIB] {
+ assert!(safe_zone(total, None) <= total / 2 || total < 2 * GIB);
+ }
+ }
+
+ #[test]
+ fn this_machine_probes_are_sane() {
+ // Not a fixed expectation — a probe that returns something absurd is
+ // the bug (the 8 GiB constant this replaces would fail on this box).
+ let cores = cores();
+ assert!((1..=4096).contains(&cores));
+ if let Some(total) = total_memory_bytes() {
+ assert!(total >= 256 * MIB, "implausible total RAM: {total}");
+ assert!(memory_safe_zone_bytes() <= total);
+ }
+ #[cfg(any(target_os = "linux", target_os = "macos"))]
+ {
+ let rss = current_rss_bytes().expect("RSS must be probeable here");
+ assert!(rss > 0, "a running process has non-zero RSS");
+ assert_eq!(
+ available_memory_bytes().is_some(),
+ cfg!(target_os = "linux")
+ );
+ }
+ }
+}
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index 136c30deb..cc919150d 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -426,6 +426,13 @@ impl Engine {
// Arc-wrapped.
crate::governor::init(&config);
+ // Install the engine's pool widths from `engine.{flush,merge,search}
+ // _workers` before any pool is built. Idempotent, same as the governor
+ // above: the first engine in a process fixes the widths, and a later
+ // engine asking for different ones is told its request was ignored
+ // rather than left to assume it took effect (#240 §4).
+ crate::pools::init(&config.engine);
+
let engine = Self {
config: Arc::new(config),
indices: Arc::new(DashMap::new()),
diff --git a/engine/crates/xerj-engine/src/governor.rs b/engine/crates/xerj-engine/src/governor.rs
index f003cf165..348630e6a 100644
--- a/engine/crates/xerj-engine/src/governor.rs
+++ b/engine/crates/xerj-engine/src/governor.rs
@@ -529,6 +529,19 @@ fn build(config: &Config) -> ResourceGovernor {
((memory_limit_bytes as u128 * pct as u128) / 100) as u64
};
+ // A configured watermark that cannot be enforced is an accepted-and-ignored
+ // setting (#204): say so, rather than letting an operator believe the
+ // parent circuit breaker is armed when this platform has no RSS probe.
+ if memory_watermark_bytes > 0 && xerj_common::resource::current_rss_bytes().is_none() {
+ tracing::warn!(
+ "limits.memory_watermark_percent={} is configured, but this build cannot read \
+ process RSS on {} — the RSS admission watermark is DISABLED (memtable budget and \
+ disk flood stage still apply)",
+ limits.memory_watermark_percent,
+ std::env::consts::OS
+ );
+ }
+
let max_query_memory_bytes = limits.max_query_memory_mb.saturating_mul(1024 * 1024);
let max_concurrent_searches = (limits.max_concurrent_searches.max(1)) as usize;
@@ -580,58 +593,35 @@ fn build(config: &Config) -> ResourceGovernor {
// System probes (Linux; best-effort with safe fallbacks elsewhere)
// ─────────────────────────────────────────────────────────────────────────
-/// Current resident set size of this process, in bytes. Reads
-/// `/proc/self/statm` (field 2 = resident pages). Returns 0 if unreadable
-/// (the RSS watermark then never trips — safe).
+/// Current resident set size of this process, in bytes, via
+/// [`xerj_common::resource::current_rss_bytes`] (`/proc/self/statm` on Linux,
+/// `proc_pidinfo(PROC_PIDTASKINFO)` on macOS). Returns 0 where the platform
+/// exposes no probe — the RSS watermark then never trips, which is safe but
+/// means no admission control, so [`build`] says so out loud at startup.
+///
+/// Until #240 this returned a hardcoded 0 on *every* non-Linux platform, so
+/// the watermark was dead on macOS however much memory the process took.
pub fn current_rss_bytes() -> u64 {
- #[cfg(target_os = "linux")]
- {
- if let Ok(s) = std::fs::read_to_string("/proc/self/statm") {
- if let Some(res) = s.split_whitespace().nth(1) {
- if let Ok(pages) = res.parse::<u64>() {
- return pages.saturating_mul(page_size_bytes());
- }
- }
- }
- 0
- }
- #[cfg(not(target_os = "linux"))]
- {
- 0
- }
+ xerj_common::resource::current_rss_bytes().unwrap_or(0)
}
-#[cfg(target_os = "linux")]
-fn page_size_bytes() -> u64 {
- // SAFETY: sysconf is a pure read of a system constant.
- let p = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
- if p > 0 {
- p as u64
- } else {
- 4096
- }
-}
-
-/// Total system RAM in bytes (from `/proc/meminfo`). Falls back to 8 GiB if
-/// unreadable so budgets stay sane on exotic platforms.
+/// Total system RAM in bytes. Falls back to [`ASSUMED_TOTAL_BYTES`] on a
+/// platform with no probe.
+///
+/// Until #240 the fallback applied to every non-Linux platform, so a 64 GB Mac
+/// derived its memtable budget, RSS watermark and hydration cache from a
+/// fictional 8 GiB — eight times too small, with no way to tell from the logs.
fn system_total_bytes() -> u64 {
- #[cfg(target_os = "linux")]
- {
- if let Ok(s) = std::fs::read_to_string("/proc/meminfo") {
- for line in s.lines() {
- if let Some(rest) = line.strip_prefix("MemTotal:") {
- if let Some(kb) = rest.split_whitespace().next() {
- if let Ok(kb) = kb.parse::<u64>() {
- return kb.saturating_mul(1024);
- }
- }
- }
- }
- }
- }
- 8 * 1024 * 1024 * 1024
+ xerj_common::resource::total_memory_bytes().unwrap_or(ASSUMED_TOTAL_BYTES)
}
+/// What to assume when the machine's RAM cannot be read at all. Deliberately
+/// unchanged from the pre-#240 constant: shrinking it would quietly re-tune
+/// every derived budget on platforms nobody has measured. The assumption is
+/// now announced (see [`xerj_common::resource::total_memory_bytes`]) instead of
+/// being silently indistinguishable from a real 8 GiB machine.
+const ASSUMED_TOTAL_BYTES: u64 = 8 * 1024 * 1024 * 1024;
+
/// Effective process memory limit: the cgroup memory limit when one is set
/// (container / `systemd-run -p MemoryMax=`), otherwise total system RAM.
/// Takes the min of the two so a generous cgroup value never exceeds RAM.
diff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rs
index 1e07ea989..50fe56a14 100644
--- a/engine/crates/xerj-engine/src/lib.rs
+++ b/engine/crates/xerj-engine/src/lib.rs
@@ -27,6 +27,7 @@ pub mod index_guard;
pub mod ingest_memory;
pub mod memtable;
pub mod painless;
+pub mod pools;
pub mod rbac;
pub mod segment_cache_budget;
pub mod segment_cache_estimates;
@@ -95,15 +96,13 @@ pub fn engine_metrics() -> Option<&'static std::sync::Arc<xerj_common::metrics::
/// search/agg fan-out, so neither side can starve the other's queue (the
/// OS scheduler time-slices the two pools fairly).
///
-/// Sized to all available cores: ingest throughput is unchanged when no
-/// searches run, and under mixed load the kernel — not the rayon job
-/// queue — arbitrates.
+/// Sized to all available cores (`crate::pools`, `Workload::Latency`): ingest
+/// throughput is unchanged when no searches run, and under mixed load the
+/// kernel — not the rayon job queue — arbitrates.
pub(crate) fn ingest_pool() -> &'static rayon::ThreadPool {
static POOL: std::sync::OnceLock<rayon::ThreadPool> = std::sync::OnceLock::new();
POOL.get_or_init(|| {
- let n = std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(8);
+ let n = crate::pools::sizing().ingest;
rayon::ThreadPoolBuilder::new()
.num_threads(n)
.thread_name(|i| format!("xerj-ingest-{i}"))
@@ -118,13 +117,15 @@ pub(crate) fn ingest_pool() -> &'static rayon::ThreadPool {
// slice of that for read-tail stability). Flush side-cars
// are nice(10) (`background_pool`), merges nice(15)
// (`merge_pool`) — the maintenance ladder stays below both.
+ //
+ // The ladder is platform-specific: `nice()` is per-thread on Linux
+ // but per-PROCESS on Darwin, where calling it from a start handler
+ // would deprioritize the whole server, search included (#240 §5).
+ // `resource::deprioritize_current_thread` owns that decision.
.start_handler(|_| {
- // Unix-only: Windows has no nice(2); threads run at normal
- // priority there and the pool separation still applies.
- #[cfg(unix)]
- unsafe {
- let _ = libc::nice(5);
- }
+ xerj_common::resource::deprioritize_current_thread(
+ xerj_common::resource::Deprioritize::Ingest,
+ );
})
.build()
.expect("failed to build ingest rayon pool")
@@ -145,17 +146,14 @@ pub(crate) fn ingest_pool() -> &'static rayon::ThreadPool {
pub(crate) fn background_pool() -> &'static rayon::ThreadPool {
static POOL: std::sync::OnceLock<rayon::ThreadPool> = std::sync::OnceLock::new();
POOL.get_or_init(|| {
- let n = std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(8);
+ let n = crate::pools::sizing().background;
rayon::ThreadPoolBuilder::new()
.num_threads(n)
.thread_name(|i| format!("xerj-bg-{i}"))
.start_handler(|_| {
- #[cfg(unix)]
- unsafe {
- let _ = libc::nice(10);
- }
+ xerj_common::resource::deprioritize_current_thread(
+ xerj_common::resource::Deprioritize::Background,
+ );
})
.build()
.expect("failed to build background rayon pool")
@@ -185,17 +183,14 @@ pub(crate) fn background_pool() -> &'static rayon::ThreadPool {
pub(crate) fn merge_pool() -> &'static rayon::ThreadPool {
static POOL: std::sync::OnceLock<rayon::ThreadPool> = std::sync::OnceLock::new();
POOL.get_or_init(|| {
- let n = std::thread::available_parallelism()
- .map(|n| (n.get() / 8).max(2))
- .unwrap_or(2);
+ let n = crate::pools::sizing().merge;
rayon::ThreadPoolBuilder::new()
.num_threads(n)
.thread_name(|i| format!("xerj-merge-{i}"))
.start_handler(|_| {
- #[cfg(unix)]
- unsafe {
- let _ = libc::nice(15);
- }
+ xerj_common::resource::deprioritize_current_thread(
+ xerj_common::resource::Deprioritize::Maintenance,
+ );
})
.build()
.expect("failed to build merge rayon pool")
@@ -223,22 +218,12 @@ pub(crate) fn merge_pool() -> &'static rayon::ThreadPool {
/// (+9%, peak 377k) with all five mixed read p99s neutral-to-better.
/// Total flush CPU is unchanged; the win is scheduling, not less work.
///
-/// N defaults to `ncores/8` (=4 on the 32-core bench, matching the
-/// measured optimum); `XERJ_FIN_CONC` overrides for tuning.
+/// N comes from `engine.flush_workers`, which defaults to the maintenance
+/// share of the machine, `max(2, ncores/8)` (=4 on the 32-core bench, matching
+/// the measured optimum); `XERJ_FIN_CONC` still overrides it for one run.
pub(crate) fn flush_finalize_gate() -> &'static tokio::sync::Semaphore {
static GATE: std::sync::OnceLock<tokio::sync::Semaphore> = std::sync::OnceLock::new();
- GATE.get_or_init(|| {
- let n = std::env::var("XERJ_FIN_CONC")
- .ok()
- .and_then(|v| v.parse::<usize>().ok())
- .filter(|&n| n > 0)
- .unwrap_or_else(|| {
- std::thread::available_parallelism()
- .map(|c| (c.get() / 8).max(2))
- .unwrap_or(4)
- });
- tokio::sync::Semaphore::new(n)
- })
+ GATE.get_or_init(|| tokio::sync::Semaphore::new(crate::pools::sizing().flush_finalize))
}
// ── Analyzer helpers ──────────────────────────────────────────────────────────
diff --git a/engine/crates/xerj-engine/src/pools.rs b/engine/crates/xerj-engine/src/pools.rs
new file mode 100644
index 000000000..5e63d4765
--- /dev/null
+++ b/engine/crates/xerj-engine/src/pools.rs
@@ -0,0 +1,179 @@
+//! Where the engine's thread pools get their widths.
+//!
+//! Every pool in this crate used to size itself inline from
+//! `available_parallelism()` with its own magic fraction, while
+//! `EngineConfig::{flush_workers, merge_workers, search_workers}` — declared,
+//! defaulted, documented and validated in `xerj-common` — were read by nothing
+//! at all. An operator who set `engine.search_workers = 2` to keep XERJ off
+//! their laptop's cores got no effect and no warning: the accepted-and-ignored
+//! class tracked in #204, and half of #240.
+//!
+//! This module is the single seam between configuration and pool construction:
+//! [`resolve`] turns an [`EngineConfig`] plus the machine policy in
+//! [`xerj_common::resource`] into concrete widths, [`init`] installs them once
+//! per process, and the pools in `lib.rs` read them. Defaults reproduce the
+//! widths the pools already used — the measured ingest/read tuning is
+//! unchanged; what changes is that the knobs now do what they say.
+
+use xerj_common::config::EngineConfig;
+use xerj_common::resource::{self, Workload};
+
+/// Concrete thread counts for one process.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PoolSizing {
+ /// `ingest_pool`: bulk parse/analyze/insert. Latency-critical for writers.
+ pub ingest: usize,
+ /// `background_pool`: flush side-cars and segment finalisation.
+ pub background: usize,
+ /// `merge_pool`: merge re-encode. Pure maintenance.
+ pub merge: usize,
+ /// `flush_finalize_gate`: how many shard finalizes may run at once.
+ pub flush_finalize: usize,
+ /// Rayon's global pool, which is what search segment fan-out runs on.
+ pub search: usize,
+}
+
+/// What [`resolve`] decided, plus anything the operator asked for that could
+/// not be honoured verbatim.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Resolved {
+ pub sizing: PoolSizing,
+ pub warnings: Vec<String>,
+}
+
+/// Turn configuration into pool widths.
+///
+/// `env_flush_finalize` is `XERJ_FIN_CONC`, kept as the tuning override it has
+/// always been; it wins over the config value, and a value that cannot be used
+/// is reported rather than dropped on the floor.
+pub fn resolve(cfg: &EngineConfig, env_flush_finalize: Option<&str>) -> Resolved {
+ let mut warnings = Vec::new();
+
+ let mut flush_finalize = cfg.flush_workers.max(1);
+ if let Some(raw) = env_flush_finalize.map(str::trim).filter(|s| !s.is_empty()) {
+ match raw.parse::<usize>() {
+ Ok(n) if n >= 1 => flush_finalize = n,
+ _ => warnings.push(format!(
+ "XERJ_FIN_CONC={raw} is not a positive integer; using \
+ engine.flush_workers={flush_finalize} instead"
+ )),
+ }
+ }
+
+ Resolved {
+ sizing: PoolSizing {
+ ingest: resource::threads_for(Workload::Latency),
+ background: resource::threads_for(Workload::Background),
+ merge: cfg.merge_workers.max(1),
+ flush_finalize,
+ search: cfg.search_workers.max(1),
+ },
+ warnings,
+ }
+}
+
+static SIZING: std::sync::OnceLock<PoolSizing> = std::sync::OnceLock::new();
+
+/// Install the process-wide pool sizing from config. Idempotent, like
+/// [`crate::governor::init`]: the first caller wins, because rayon pools are
+/// process-global and already-running threads cannot be resized.
+///
+/// A second [`Engine`](crate::Engine) built in the same process with *different*
+/// widths logs a warning naming the values that were ignored — silently serving
+/// one engine's config to another is exactly the bug this module exists to end.
+pub fn init(cfg: &EngineConfig) {
+ let resolved = resolve(cfg, std::env::var("XERJ_FIN_CONC").ok().as_deref());
+ for warning in &resolved.warnings {
+ tracing::warn!("{warning}");
+ }
+ let installed = *SIZING.get_or_init(|| resolved.sizing);
+ if installed != resolved.sizing {
+ tracing::warn!(
+ "engine pool sizing was already fixed for this process ({installed:?}); ignoring \
+ {:?} from this engine's config",
+ resolved.sizing
+ );
+ }
+ install_search_pool(installed.search);
+}
+
+/// The installed sizing, or the policy defaults when no engine has been built
+/// yet (engine-only unit tests that touch a pool directly).
+pub fn sizing() -> PoolSizing {
+ *SIZING.get_or_init(|| resolve(&EngineConfig::default(), None).sizing)
+}
+
+/// Search fan-out runs on rayon's *global* pool, so honouring
+/// `engine.search_workers` means building that pool explicitly — rayon
+/// otherwise defaults it to every core on first use.
+///
+/// `build_global` can only succeed once per process. If some par_iter already
+/// ran, the request cannot be honoured; that is reported with the width the
+/// process actually has, instead of leaving the operator to guess.
+fn install_search_pool(threads: usize) {
+ static DONE: std::sync::Once = std::sync::Once::new();
+ DONE.call_once(|| {
+ if let Err(err) = rayon::ThreadPoolBuilder::new()
+ .num_threads(threads)
+ .thread_name(|i| format!("xerj-search-{i}"))
+ .build_global()
+ {
+ let actual = rayon::current_num_threads();
+ if actual != threads {
+ tracing::warn!(
+ "engine.search_workers={threads} could not be applied ({err}); search \
+ fan-out runs on the already-initialised global pool of {actual} threads"
+ );
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn cfg(flush: usize, merge: usize, search: usize) -> EngineConfig {
+ EngineConfig {
+ flush_workers: flush,
+ merge_workers: merge,
+ search_workers: search,
+ ..EngineConfig::default()
+ }
+ }
+
+ #[test]
+ fn configured_workers_reach_the_pools() {
+ // The #240 §4 defect: these three were read by nothing.
+ let r = resolve(&cfg(3, 5, 7), None);
+ assert_eq!(r.sizing.flush_finalize, 3);
+ assert_eq!(r.sizing.merge, 5);
+ assert_eq!(r.sizing.search, 7);
+ assert!(r.warnings.is_empty());
+ }
+
+ #[test]
+ fn defaults_reproduce_the_measured_widths() {
+ let cores = xerj_common::resource::cores();
+ let r = resolve(&EngineConfig::default(), None);
+ // Latency-critical pools keep the whole machine ...
+ assert_eq!(r.sizing.ingest, cores);
+ assert_eq!(r.sizing.background, cores);
+ assert_eq!(r.sizing.search, cores);
+ // ... maintenance keeps the measured max(2, cores/8).
+ assert_eq!(r.sizing.merge, (cores / 8).max(2).min(cores.max(1)));
+ assert_eq!(r.sizing.flush_finalize, r.sizing.merge);
+ }
+
+ #[test]
+ fn the_env_override_wins_and_a_bad_one_is_reported() {
+ assert_eq!(resolve(&cfg(3, 2, 4), Some("9")).sizing.flush_finalize, 9);
+ assert_eq!(resolve(&cfg(3, 2, 4), Some("")).sizing.flush_finalize, 3);
+ let r = resolve(&cfg(3, 2, 4), Some("lots"));
+ assert_eq!(r.sizing.flush_finalize, 3);
+ assert!(r.warnings[0].contains("XERJ_FIN_CONC=lots"));
+ let r = resolve(&cfg(3, 2, 4), Some("0"));
+ assert_eq!(r.sizing.flush_finalize, 3);
+ assert_eq!(r.warnings.len(), 1);
+ }
+}
diff --git a/engine/crates/xerj-engine/tests/engine_worker_config_is_honoured.rs b/engine/crates/xerj-engine/tests/engine_worker_config_is_honoured.rs
new file mode 100644
index 000000000..cc4592d02
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/engine_worker_config_is_honoured.rs
@@ -0,0 +1,85 @@
+//! `engine.{flush,merge,search}_workers` must reach the pools they name.
+//!
+//! Before #240 all three were declared, defaulted, documented and validated in
+//! `xerj-common::config` and read by **nothing**. Setting
+//! `engine.search_workers = 2` to keep XERJ off a laptop's cores changed no
+//! pool and produced no warning — the accepted-and-ignored class from #204.
+//!
+//! Search segment fan-out runs on rayon's *global* pool, which rayon sizes to
+//! every core on first use unless something builds it first. That makes the
+//! global pool's width the observable for `search_workers`, and it is
+//! process-global state — hence a test file of its own, since each Rust
+//! integration-test file is its own binary.
+
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_engine::pools;
+use xerj_engine::Engine;
+
+#[tokio::test]
+async fn search_workers_sizes_the_pool_search_actually_runs_on() {
+ let requested = 2;
+ let machine = std::thread::available_parallelism()
+ .map(|n| n.get())
+ .unwrap();
+ assert!(
+ machine > requested,
+ "this assertion is only meaningful on a machine with more cores than we ask for \
+ (machine={machine})"
+ );
+
+ let dir = TempDir::new().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ config.engine.search_workers = requested;
+ config.engine.merge_workers = 3;
+ config.engine.flush_workers = 5;
+ let _engine = Engine::new(config).expect("engine::new");
+
+ // Pre-fix this reported `machine` (32 on the dev box): the config value was
+ // never read, so search fan-out took every core no matter what was asked.
+ assert_eq!(
+ rayon::current_num_threads(),
+ requested,
+ "engine.search_workers must size the global pool that search fans out on"
+ );
+
+ let sizing = pools::sizing();
+ assert_eq!(sizing.search, requested);
+ assert_eq!(
+ sizing.merge, 3,
+ "engine.merge_workers must reach merge_pool"
+ );
+ assert_eq!(
+ sizing.flush_finalize, 5,
+ "engine.flush_workers must reach the flush finalize gate"
+ );
+}
+
+#[test]
+fn out_of_range_worker_counts_are_refused_not_clamped() {
+ for name in [
+ "engine.flush_workers",
+ "engine.merge_workers",
+ "engine.search_workers",
+ ] {
+ for bad in [0usize, usize::MAX] {
+ let mut engine = Config::default().engine;
+ match name {
+ "engine.flush_workers" => engine.flush_workers = bad,
+ "engine.merge_workers" => engine.merge_workers = bad,
+ _ => engine.search_workers = bad,
+ }
+ let err = engine
+ .validate()
+ .expect_err("an unusable worker count must be refused, never clamped");
+ assert!(
+ err.to_string().contains(name),
+ "the error must name the setting, got: {err}"
+ );
+ }
+ }
+ // merge_workers = 0 used to pass validation entirely: only flush_workers
+ // was checked, and nothing read any of the three anyway.
+ assert!(Config::default().engine.validate().is_ok());
+}
diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rs
index 68f2a25d9..5296a227f 100644
--- a/engine/crates/xerj-server/src/brain.rs
+++ b/engine/crates/xerj-server/src/brain.rs
@@ -416,17 +416,20 @@ fn live_node_docs(es: &Es, brain: &str) -> u64 {
}
fn index_cfg(cfg: &BrainCfg, brain: &str, api_key: Option<String>) -> IndexCfg {
- let cores = std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(8);
+ // Same resource policy as `xerj autoindex` itself — `xerj brain` composes
+ // autoindex, so it must not invent its own worker counts (#240).
+ const BULK_MB: usize = 8;
+ let plan = xerj_autoindex::resources::plan(None, None, BULK_MB);
IndexCfg {
root: cfg.root.clone(),
url: cfg.url.clone(),
api_key,
- workers: cores.min(8),
- pdf_workers: cores.min(4),
+ workers: plan.index_workers,
+ scan_workers: plan.scan_threads,
+ pdf_workers: plan.pdf_workers,
+ resource_notes: plan.notes,
pdf_timeout_secs: 120,
- bulk_mb: 8,
+ bulk_mb: BULK_MB,
bulk_timeout_secs: 300,
prefix: "ax".into(),
state_dir: None,
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 69d208de9..ce67d608b 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -1012,9 +1012,7 @@ async fn run_cli_index(cmd: IndexCmdArgs) -> Result<()> {
let batch_size = cmd.batch.max(1);
let workers = if cmd.workers == 0 {
- std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(8)
+ xerj_common::resource::threads_for(xerj_common::resource::Workload::Latency)
} else {
cmd.workers
};
@@ -1449,9 +1447,9 @@ fn main() -> Result<()> {
if matches!(std::env::args().nth(1).as_deref(), Some("__extract-pdf")) {
std::process::exit(xerj_autoindex::extract::pdf::run_worker_cli());
}
- let cores = std::thread::available_parallelism()
- .map(|n| n.get())
- .unwrap_or(8);
+ // Cores from the resource policy, so `XERJ_NUM_CPUS` and a container CPU
+ // quota reach the async runtime the same way they reach every pool (#240).
+ let cores = xerj_common::resource::cores();
// ~8× cores, clamped to a sane band; env override wins.
let worker_threads = std::env::var("TOKIO_WORKER_THREADS")
.ok()
diff --git a/landing/docs/recipes/zero-config-autoindex.html b/landing/docs/recipes/zero-config-autoindex.html
index 714637638..18c0dc6e0 100644
--- a/landing/docs/recipes/zero-config-autoindex.html
+++ b/landing/docs/recipes/zero-config-autoindex.html
@@ -265,7 +265,7 @@ xerj autoindex ~/some-folder
xerj autoindex map
curl localhost:9200/ax-*/_search -H 'Content-Type: application/json' \
-d '{"query":{"match_all":{}},"size":3}'</pre>
- <p>Useful knobs (all optional): <code class="inline">--url</code> for a non-default endpoint, <code class="inline">--workers N</code> (default min(cores,&nbsp;8)), <code class="inline">--prefix</code> to namespace the indices (default <code class="inline">ax</code>), <code class="inline">--no-semantic</code> for pure BM25+keyword without vector fields, <code class="inline">--dry-run</code> to print the inferred plan without indexing anything, <code class="inline">--follow-symlinks</code> (loop-safe), <code class="inline">--sample N</code> records per file for inference (default 500).</p>
+ <p>Useful knobs (all optional): <code class="inline">--url</code> for a non-default endpoint, <code class="inline">--workers N</code> (default: every core, reduced when the memory safe zone cannot pay for that many in-flight bulk buffers; bounds both the scan and the indexing phase), <code class="inline">--prefix</code> to namespace the indices (default <code class="inline">ax</code>), <code class="inline">--no-semantic</code> for pure BM25+keyword without vector fields, <code class="inline">--dry-run</code> to print the inferred plan without indexing anything, <code class="inline">--follow-symlinks</code> (loop-safe), <code class="inline">--sample N</code> records per file for inference (default 500).</p>
<p>Your dataset names, field types, and counts will reflect <em>your</em> folder — that is the point. The behaviors shown here (decimal-comma → <code class="inline">double</code>, date strings → typed <code class="inline">date</code>, keyword inference, junk recording, resume-to-identical-counts) are the invariants.</p>
<hr>