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(autoindex): keep PDF workers running when RLIMIT_AS is refused (#2336) (#2338)
xerj-org37774bd780e9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 89ff434fa..87b3d1f4d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -126,6 +126,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- `xerj autoindex` no longer junks every PDF on an OS that rejects+ `setrlimit(RLIMIT_AS)` (macOS 27 returns `EINVAL`; a hard limit below+ 1536 MiB returns `EPERM`). The address-space cap is crash isolation: the+ refusal is logged once and the worker still starts. Linux still applies+ the 1536 MiB cap. The same refusal is ignored for the isolated `.xls`+ reader. If every PDF fails because the worker could not start, the run+ finishes `ok=false exit=1 reason=pdf-worker-unavailable` instead of+ looking like completed-with-junk+ ([#2336](https://github.com/xerj-org/xerj/issues/2336)).+- `xerj autoindex` indexes `.sql` schema, migration, and routine files ascode. `CREATE TABLE` / `VIEW` / `FUNCTION` / `PROCEDURE` / `INDEX` /`TRIGGER` / `TYPE` / `SCHEMA` / `SEQUENCE` become symbols, and the sourcediff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex 0f3f00c11..1a70f5628 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -557,8 +557,10 @@ pub fn help_text_with(feedback: bool) -> String {\n\PDF EXTRACTION:\n\\x20\x20\x20\x20Each PDF uses a fresh process. Limits: 512 MiB input, 32 MiB worker output,\n\- \x20\x20\x20\x20100,000 pages, and 1.5 GiB address space on Unix. This is crash/resource\n\- \x20\x20\x20\x20isolation, not a security sandbox; non-Unix platforms have no OS memory cap.\n\+ \x20\x20\x20\x20100,000 pages, and a 1.5 GiB address-space cap on Unix where the OS accepts\n\+ \x20\x20\x20\x20RLIMIT_AS. If the OS refuses that cap (EINVAL or EPERM, as on macOS 27), the\n\+ \x20\x20\x20\x20refusal is logged once and the worker still starts. The cap is crash isolation,\n\+ \x20\x20\x20\x20not a security sandbox; non-Unix platforms have no OS memory cap.\n\\x20\x20\x20\x20Image-only pages need OCR. Page parse failures reject the whole PDF instead\n\\x20\x20\x20\x20of silently creating a partial index. XERJ_PDF_WORKER_BIN is a trusted,\n\\x20\x20\x20\x20developer-only executable override.\n\@@ -798,8 +800,11 @@ pub fn help_text_with(feedback: bool) -> String {\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20that does not fit is not started, including with --yes.\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Already-indexed files are not deleted unless --drop-indexed\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20is also set;\n\- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x202 usage; 1 endpoint/journal failure, a refused corpus removal, or a\n\- \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20refused unsafe state transition\n",+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x202 usage; 1 endpoint/journal failure, a refused corpus removal, a\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20refused unsafe state transition, or pdf-worker-unavailable — every PDF\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20failed because the isolated parser could not start. Other files may\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20already be indexed. Read `reason` on the xerj-done line; the summary\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20on stdout opens with `not ok:`\n",feedback_block = xerj_common::feedback::block(feedback),default_poll = crate::objwatch::cost::DEFAULT_POLL_INTERVAL_SECS,default_budget = crate::objwatch::cost::DEFAULT_MAX_MONTHLY_CLASS_A,diff --git a/engine/crates/xerj-autoindex/src/extract/mod.rs b/engine/crates/xerj-autoindex/src/extract/mod.rsindex 433b663ad..02cd44ba9 100644--- a/engine/crates/xerj-autoindex/src/extract/mod.rs+++ b/engine/crates/xerj-autoindex/src/extract/mod.rs@@ -19,6 +19,8 @@ pub mod mbox;pub(crate) mod opc;pub mod pdf;pub mod pptx;+#[cfg(unix)]+pub(crate) mod rlimit;pub mod sqldump;pub mod sqlite_x;pub mod sqlsrc;diff --git a/engine/crates/xerj-autoindex/src/extract/pdf.rs b/engine/crates/xerj-autoindex/src/extract/pdf.rsindex ea6b17966..81ceda503 100644--- a/engine/crates/xerj-autoindex/src/extract/pdf.rs+++ b/engine/crates/xerj-autoindex/src/extract/pdf.rs@@ -4,7 +4,9 @@//! codes as Latin-1. `pdf_oxide` resolves the object graph and font mappings//! before returning Unicode text. Each document runs in a fresh worker process//! so parser state or failure cannot contaminate the server. On Unix the worker-//! also gets a process group and an address-space limit. This is crash/resource+//! also gets a process group and, where the kernel accepts `RLIMIT_AS`, a+//! 1536 MiB address-space cap. A kernel that rejects that cap (`EINVAL` /+//! `EPERM`, as on macOS 27) still runs the worker. This is crash/resource//! isolation, not a security sandbox: the worker retains the user's authority.use super::{split_sections, ExtractStats, FieldOrigin, RawRecord, Sink};@@ -950,7 +952,8 @@ fn spawn_worker(path: &Path) -> Result<WorkerResponse> {set_worker_memory_limit(&mut command);let mut child = command.spawn().with_context(|| {format!(- "could not start the isolated PDF parser for {}; check process/resource limits",+ "{} for {}; check process/resource limits",+ crate::state::PDF_WORKER_START_FAILURE,path.display())})?;@@ -1178,19 +1181,25 @@ fn read_capped(mut input: impl Read, cap: usize) -> Result<CappedRead> {#[cfg(unix)]fn set_worker_memory_limit(command: &mut Command) {use std::os::unix::process::CommandExt;+ // Probe in the parent so a refusal can be logged once on the progress+ // stream. The child still decides: `pre_exec` skips EINVAL/EPERM and+ // fails the spawn only for some other errno. `setrlimit` and the errno+ // read are async-signal-safe; `from_raw_os_error` runs only on that+ // fatal path, which is the same allocation the old code made for every+ // failure.+ let _ = super::rlimit::address_space_cap_supported();unsafe {command.pre_exec(|| {if libc::setpgid(0, 0) != 0 {return Err(std::io::Error::last_os_error());}- let limit = libc::rlimit {- rlim_cur: WORKER_ADDRESS_SPACE,- rlim_max: WORKER_ADDRESS_SPACE,- };- if libc::setrlimit(libc::RLIMIT_AS, &limit) != 0 {- return Err(std::io::Error::last_os_error());+ match super::rlimit::apply_address_space_cap(WORKER_ADDRESS_SPACE) {+ super::rlimit::AddressSpaceCap::Applied+ | super::rlimit::AddressSpaceCap::Skipped => Ok(()),+ super::rlimit::AddressSpaceCap::Failed(errno) => {+ Err(std::io::Error::from_raw_os_error(errno))+ }}- Ok(())});}}@@ -1225,7 +1234,11 @@ fn terminate_worker_descendants(_process_group: u32) {}#[cfg(unix)]fn containment_description() -> &'static str {- "fresh process; Unix process-group cleanup; 1536 MiB RLIMIT_AS; not a security sandbox"+ if super::rlimit::current_address_space_is_capped(WORKER_ADDRESS_SPACE) {+ "fresh process; Unix process-group cleanup; 1536 MiB RLIMIT_AS; not a security sandbox"+ } else {+ "fresh process; Unix process-group cleanup; no RLIMIT_AS cap on this process; not a security sandbox"+ }}#[cfg(not(unix))]diff --git a/engine/crates/xerj-autoindex/src/extract/rlimit.rs b/engine/crates/xerj-autoindex/src/extract/rlimit.rsnew file mode 100644index 000000000..205f60dd1--- /dev/null+++ b/engine/crates/xerj-autoindex/src/extract/rlimit.rs@@ -0,0 +1,237 @@+//! Address-space cap for isolated extraction workers (`RLIMIT_AS`).+//!+//! The cap is crash isolation: a parser that allocates until it dies takes+//! the worker with it, and the parent keeps scanning. It is not a security+//! boundary. Some kernels reject the resource outright — macOS 27 returns+//! `EINVAL` for `setrlimit(RLIMIT_AS, 1536 MiB)` and for `ulimit -v` — and+//! an unprivileged process gets `EPERM` when the requested hard limit is+//! above the one it inherited. Either refusal used to fail `Command::spawn`+//! inside `pre_exec`, so every PDF (and every isolated `.xls`) was junk+//! before `exec` (#2336).+//!+//! `EINVAL` and `EPERM` are skipped. The worker still starts, in its own+//! process group, under whatever limit it inherited. Any other errno still+//! fails that one spawn. Linux keeps the cap: the probe there succeeds and+//! the child installs it.++use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::OnceLock;++/// Byte value the parent probes with. Matches the PDF worker cap. A kernel+/// that rejects this call rejects the resource; the `.xls` worker uses the+/// same answer and still installs its own (larger) ceiling when the probe+/// says the call works.+const PROBE_BYTES: u64 = 1536 << 20;++/// One-line progress note. Present only after a probe has observed a refusal,+/// and only once per process.+pub(crate) const ADDRESS_SPACE_CAP_WARNING: &str = "\+warning: this OS refused setrlimit(RLIMIT_AS) for isolated extraction workers; \+they still start without that address-space cap. The cap is crash isolation, \+not a security boundary.";++static CAP_SUPPORTED: OnceLock<bool> = OnceLock::new();+static CAP_WARNING_ANNOUNCED: AtomicBool = AtomicBool::new(false);++/// What one `setrlimit(RLIMIT_AS)` call did. `Skipped` is a successful spawn+/// decision: the platform will not install the cap.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum AddressSpaceCap {+ Applied,+ Skipped,+ Failed(i32),+}++/// `EINVAL` (resource rejected) and `EPERM` (cannot raise the hard limit).+pub(crate) fn refusal_is_benign(errno: i32) -> bool {+ errno == libc::EINVAL || errno == libc::EPERM+}++pub(crate) fn classify_address_space_cap(rc: i32, errno: i32) -> AddressSpaceCap {+ if rc == 0 {+ AddressSpaceCap::Applied+ } else if refusal_is_benign(errno) {+ AddressSpaceCap::Skipped+ } else {+ AddressSpaceCap::Failed(errno)+ }+}++/// Install `bytes` as both the soft and hard `RLIMIT_AS`. Safe to call from+/// `pre_exec`: on the refusal path it reads `errno` and does not allocate.+pub(crate) fn apply_address_space_cap(bytes: u64) -> AddressSpaceCap {+ let limit = libc::rlimit {+ rlim_cur: bytes as libc::rlim_t,+ rlim_max: bytes as libc::rlim_t,+ };+ let rc = unsafe { libc::setrlimit(libc::RLIMIT_AS, &limit) };+ // `errno` is only meaningful when the call failed. A success leaves it+ // stale, and [`classify_address_space_cap`] ignores it when `rc == 0`.+ classify_address_space_cap(rc, if rc == 0 { 0 } else { errno_raw() })+}++/// `true` when this OS accepted a 1536 MiB `RLIMIT_AS` in a forked child.+///+/// The probe runs in the parent, once. The child calls `setrlimit` and+/// `_exit` only — both async-signal-safe — so a fork from the multithreaded+/// indexer does not touch the Rust allocator. The parent's own limit is not+/// modified. An inconclusive probe (fork failure, or an errno other than+/// `EINVAL`/`EPERM`) answers `true`, and the worker's `pre_exec` still skips+/// a later benign refusal.+pub(crate) fn address_space_cap_supported() -> bool {+ *CAP_SUPPORTED.get_or_init(probe_address_space_cap)+}++/// The progress note for a refused cap, the first time it is asked after the+/// probe has run and failed. `None` before the probe, when the cap was+/// accepted, and on every call after the first announcement.+pub(crate) fn take_address_space_cap_warning() -> Option<&'static str> {+ let supported = *CAP_SUPPORTED.get()?;+ warning_if_refused(supported, &CAP_WARNING_ANNOUNCED)+}++pub(crate) fn warning_if_refused(supported: bool, announced: &AtomicBool) -> Option<&'static str> {+ if supported || announced.swap(true, Ordering::SeqCst) {+ return None;+ }+ Some(ADDRESS_SPACE_CAP_WARNING)+}++/// Whether the calling process currently has `RLIMIT_AS` pinned to `bytes`.+/// The worker reports this in its containment string, so a platform that+/// refused the cap does not claim the cap is in force.+pub(crate) fn current_address_space_is_capped(bytes: u64) -> bool {+ let mut current = libc::rlimit {+ rlim_cur: 0,+ rlim_max: 0,+ };+ if unsafe { libc::getrlimit(libc::RLIMIT_AS, &mut current) } != 0 {+ return false;+ }+ current.rlim_cur == bytes as libc::rlim_t && current.rlim_max == bytes as libc::rlim_t+}++pub(crate) fn errno_raw() -> i32 {+ // `__error` on the BSDs (including macOS); `__errno_location` on Linux+ // and Android. Both are async-signal-safe. OpenBSD's `___errno` is not+ // covered; this crate's CI is Linux, macOS, and Windows.+ #[cfg(any(+ target_os = "macos",+ target_os = "ios",+ target_os = "watchos",+ target_os = "tvos",+ target_os = "visionos",+ target_os = "freebsd",+ target_os = "dragonfly",+ target_os = "netbsd"+ ))]+ unsafe {+ *libc::__error()+ }+ #[cfg(not(any(+ target_os = "macos",+ target_os = "ios",+ target_os = "watchos",+ target_os = "tvos",+ target_os = "visionos",+ target_os = "freebsd",+ target_os = "dragonfly",+ target_os = "netbsd"+ )))]+ unsafe {+ *libc::__errno_location()+ }+}++fn probe_address_space_cap() -> bool {+ let pid = unsafe { libc::fork() };+ if pid < 0 {+ return true;+ }+ if pid == 0 {+ let code = match apply_address_space_cap(PROBE_BYTES) {+ AddressSpaceCap::Applied => 0,+ AddressSpaceCap::Skipped => 2,+ AddressSpaceCap::Failed(_) => 3,+ };+ unsafe { libc::_exit(code) };+ }+ let mut status: libc::c_int = 0;+ if unsafe { libc::waitpid(pid, &mut status, 0) } != pid {+ return true;+ }+ // Exit 2 is the only definitive refusal. Anything else (applied, an+ // unexpected errno, a signal) still attempts the cap in the worker.+ if libc::WIFEXITED(status) {+ return libc::WEXITSTATUS(status) != 2;+ }+ true+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn einval_and_eperm_skip_the_cap_and_other_errnos_fail_the_spawn() {+ assert_eq!(+ classify_address_space_cap(0, libc::EINVAL),+ AddressSpaceCap::Applied,+ "a successful setrlimit ignores a stale errno"+ );+ assert_eq!(+ classify_address_space_cap(-1, libc::EINVAL),+ AddressSpaceCap::Skipped+ );+ assert_eq!(+ classify_address_space_cap(-1, libc::EPERM),+ AddressSpaceCap::Skipped+ );+ assert_eq!(+ classify_address_space_cap(-1, libc::EFAULT),+ AddressSpaceCap::Failed(libc::EFAULT)+ );+ assert_eq!(+ classify_address_space_cap(-1, libc::ENOMEM),+ AddressSpaceCap::Failed(libc::ENOMEM)+ );+ }++ #[test]+ fn the_refusal_warning_is_announced_once_and_only_when_the_cap_was_refused() {+ let announced = AtomicBool::new(false);+ assert!(warning_if_refused(true, &announced).is_none());+ assert!(+ !announced.load(Ordering::SeqCst),+ "an accepted cap is not a warning"+ );+ let first = warning_if_refused(false, &announced).unwrap();+ assert!(first.contains("setrlimit(RLIMIT_AS)"));+ assert!(first.contains("still start"));+ assert!(warning_if_refused(false, &announced).is_none());+ }++ #[test]+ fn probing_the_cap_does_not_change_the_parent_limit() {+ let mut before = libc::rlimit {+ rlim_cur: 0,+ rlim_max: 0,+ };+ assert_eq!(unsafe { libc::getrlimit(libc::RLIMIT_AS, &mut before) }, 0);+ let supported = address_space_cap_supported();+ let mut after = libc::rlimit {+ rlim_cur: 0,+ rlim_max: 0,+ };+ assert_eq!(unsafe { libc::getrlimit(libc::RLIMIT_AS, &mut after) }, 0);+ assert_eq!(before.rlim_cur, after.rlim_cur);+ assert_eq!(before.rlim_max, after.rlim_max);+ // Linux accepts the call. A refusal here would mean this runner+ // cannot install the cap the PDF worker documents, which is the+ // macOS 27 failure mode and must not be silent on Linux CI.+ #[cfg(target_os = "linux")]+ assert!(supported, "Linux accepts setrlimit(RLIMIT_AS, 1536 MiB)");+ #[cfg(not(target_os = "linux"))]+ let _ = supported;+ }+}diff --git a/engine/crates/xerj-autoindex/src/extract/xls.rs b/engine/crates/xerj-autoindex/src/extract/xls.rsindex 9aa40c542..70d05d5f5 100644--- a/engine/crates/xerj-autoindex/src/extract/xls.rs+++ b/engine/crates/xerj-autoindex/src/extract/xls.rs@@ -342,10 +342,14 @@ fn run_worker(.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null());+ // Probe in the parent. A kernel that rejects RLIMIT_AS (macOS 27, EINVAL)+ // must not fail this spawn; the warning is taken from the progress stream+ // after the scan. The child still skips EINVAL/EPERM itself.+ let _ = super::rlimit::address_space_cap_supported();// SAFETY: the closure runs in the forked child before exec and calls only// async-signal-safe libc (`setpgid`, `setrlimit`). Its own process group so// the parent can reap the whole tree; the rlimits cap the child's blast- // radius to itself.+ // radius to itself. A benign RLIMIT_AS refusal does not allocate.unsafe {command.pre_exec(worker_pre_exec);}@@ -477,42 +481,72 @@ fn worker_pre_exec() -> std::io::Result<()> {/// Only ever *lowers* a limit: an unprivileged process cannot raise its hard/// limit, so the target is clamped to whatever was inherited. This matters when/// the indexer already runs under a tighter cgroup or `ulimit -v` — trying to-/// set a higher ceiling there would `EPERM` and fail the whole spawn, turning-/// every `.xls` (benign included) into junk.+/// set a higher ceiling there would `EPERM`.+///+/// `RLIMIT_AS` treats `EINVAL` and `EPERM` as "this platform will not install+/// the cap" and returns `Ok` (#2336). The cap is crash isolation. Failing the+/// spawn junked every `.xls` on macOS 27, where `setrlimit(RLIMIT_AS)` is+/// rejected outright. `RLIMIT_CPU` stays strict: a failure there is still a+/// failed spawn.#[cfg(unix)]fn set_worker_rlimits() -> std::io::Result<()> {// Set `$res`'s soft/hard limits to the requested values, each capped at the// inherited hard limit so the call never tries to RAISE a ceiling (which an- // unprivileged process may not do, and which would `EPERM` the whole spawn).- // A macro, not a function, so the resource constant is passed straight to- // libc without naming its type — that type is `__rlimit_resource_t` on- // glibc but `c_int` on macOS/BSD.+ // unprivileged process may not do). A macro, not a function, so the+ // resource constant is passed straight to libc without naming its type —+ // that type is `__rlimit_resource_t` on glibc but `c_int` on macOS/BSD.+ // `$benign` skips EINVAL/EPERM without allocating; the fatal path builds+ // the `io::Error` only when the spawn must fail.macro_rules! clamp {- ($res:expr, $soft:expr, $hard:expr) => {{+ ($res:expr, $soft:expr, $hard:expr, $benign:expr) => {{let mut current = libc::rlimit {rlim_cur: 0,rlim_max: 0,};// SAFETY: plain libc FFI over an out-param `rlimit`.- if unsafe { libc::getrlimit($res, &mut current) } != 0 {- return Err(std::io::Error::last_os_error());- }- let ceiling = current.rlim_max; // inherited hard limit (maybe RLIM_INFINITY)- let want_hard = ($hard as libc::rlim_t).min(ceiling);- let want_soft = ($soft as libc::rlim_t).min(want_hard);- let limit = libc::rlimit {- rlim_cur: want_soft,- rlim_max: want_hard,+ let refused = if unsafe { libc::getrlimit($res, &mut current) } != 0 {+ let errno = super::rlimit::errno_raw();+ if $benign && super::rlimit::refusal_is_benign(errno) {+ true+ } else {+ return Err(std::io::Error::from_raw_os_error(errno));+ }+ } else {+ false};- // SAFETY: as above; cur <= max <= inherited max, so this only lowers.- if unsafe { libc::setrlimit($res, &limit) } != 0 {- return Err(std::io::Error::last_os_error());+ if !refused {+ let ceiling = current.rlim_max; // inherited hard limit (maybe RLIM_INFINITY)+ let want_hard = ($hard as libc::rlim_t).min(ceiling);+ let want_soft = ($soft as libc::rlim_t).min(want_hard);+ let limit = libc::rlimit {+ rlim_cur: want_soft,+ rlim_max: want_hard,+ };+ // SAFETY: as above; cur <= max <= inherited max, so this only lowers.+ if unsafe { libc::setrlimit($res, &limit) } != 0 {+ let errno = super::rlimit::errno_raw();+ if $benign && super::rlimit::refusal_is_benign(errno) {+ // Inherited limit stands. The worker still starts.+ } else {+ return Err(std::io::Error::from_raw_os_error(errno));+ }+ }}}};}- clamp!(libc::RLIMIT_AS, WORKER_ADDRESS_SPACE, WORKER_ADDRESS_SPACE);+ clamp!(+ libc::RLIMIT_AS,+ WORKER_ADDRESS_SPACE,+ WORKER_ADDRESS_SPACE,+ true+ );// Soft limit sends SIGXCPU; hard limit (a touch higher) escalates to SIGKILL.- clamp!(libc::RLIMIT_CPU, WORKER_CPU_SECONDS, WORKER_CPU_SECONDS + 2);+ clamp!(+ libc::RLIMIT_CPU,+ WORKER_CPU_SECONDS,+ WORKER_CPU_SECONDS + 2,+ false+ );Ok(())}diff --git a/engine/crates/xerj-autoindex/src/generation_catalog.rs b/engine/crates/xerj-autoindex/src/generation_catalog.rsindex 8f84b096a..4b2cbcd77 100644--- a/engine/crates/xerj-autoindex/src/generation_catalog.rs+++ b/engine/crates/xerj-autoindex/src/generation_catalog.rs@@ -371,6 +371,12 @@ pub fn project_generation(.iter().any(|dataset| dataset.semantic_field.is_some()),});+ // #2336: absent unless every PDF failed to start the isolated parser, so+ // a generation with no such failure serializes the run document it always+ // did. The terminal line reads this field back and exits 1.+ if let Some(n) = desired.plan.pdf_worker_unavailable_count() {+ run_doc["pdf_worker_unavailable"] = json!(n);+ }// #929: a generation that lacks a dataset says so in the one document every// reader of the corpus starts from (`Plan::refused_run_fields`).for (key, value) in desired.plan.refused_run_fields() {diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex e9bf19350..bd50a8f4a 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -1102,6 +1102,7 @@ fn project_reconcile_plan(}).collect()});+ note_worker_address_space_cap(pr);let rebuild = incremental_schema_rebuild_command(cfg, state_dir);reconcile_plan::reconcile_plan(inventory, base_plan, scans, cfg.sample, &rebuild)}@@ -1538,6 +1539,11 @@ fn alias_sweep_notes(paths: &[&str], error: &str) -> Vec<String> {/// that still contains junk reports 3 again instead of flapping to 0.fn generated_exit_code(summary: &Value) -> i32 {let count = |field: &str| summary.get(field).and_then(Value::as_u64).unwrap_or(0);+ // #2336: every PDF failed because the worker process could not start.+ // Exit 3 would call that success. The field is absent on every other run.+ if count("pdf_worker_unavailable") > 0 {+ return 1;+ }if count("junk_records_total") > 0 || count("files_junk") > 0 {3} else {@@ -1551,17 +1557,26 @@ fn generated_exit_code(summary: &Value) -> i32 {/// unless something it reads first says otherwise. The `xerj-done` line on/// stderr already carries `ok=true`, yet it is the LAST line of a long progress/// stream and the summary on stdout opened with a timing line that never-/// mentioned the exit code at all. So every finished run now leads with one-/// line that starts `ok:` and names the exit code in words; exit 3 also says-/// what was recorded and where to look, so junk stays visible.+/// mentioned the exit code at all. A finished run leads with one line that+/// starts `ok:` and names the exit code in words; exit 3 also says what was+/// recorded and where to look, so junk stays visible. A family-wide PDF+/// worker startup failure (#2336) leads with `not ok:` and exit 1.pub(crate) fn outcome_headline(code: i32,junk_files: u64,junk_records: u64,alias_sweep_failed: bool,stale_plan_files: u64,+ pdf_worker_unavailable: Option<u64>,files_removed: u64,) -> String {+ if let Some(n) = pdf_worker_unavailable.filter(|n| *n > 0) {+ return format!(+ "not ok: the isolated PDF parser could not start for {}, so no PDF text was indexed. \+ Other files in this run were still indexed. Exit 1 ({PDF_WORKER_UNAVAILABLE_REASON})",+ estimate::count_phrase(n, "PDF file", "PDF files")+ );+ }if code != 3 {return format!("ok: indexed and searchable (exit {code}, completed)");}@@ -1693,6 +1708,14 @@ fn finish_generated_progress(pr: &Progress, code: i32, summary: &Value, skipped_extra.push(("skipped_dataless", skipped_dataless));}extra.extend(coverage.fields());+ note_worker_address_space_cap(pr);+ let pdf_down = count("pdf_worker_unavailable");+ if pdf_down > 0 {+ pr.note(&pdf_worker_unavailable_note(pdf_down));+ extra.push(("pdf_worker_unavailable", pdf_down));+ pr.finish(false, 1, PDF_WORKER_UNAVAILABLE_REASON, &extra);+ return;+ }pr.finish(true,code,@@ -1705,6 +1728,31 @@ fn finish_generated_progress(pr: &Progress, code: i32, summary: &Value, skipped_);}+/// `xerj-done` reason when every PDF failed because the isolated parser+/// process could not start (#2336). Exit 1, `ok=false`. Other files in the+/// same run may already be indexed; a corrupt PDF that the worker did parse+/// stays exit 3.+const PDF_WORKER_UNAVAILABLE_REASON: &str = "pdf-worker-unavailable";++fn pdf_worker_unavailable_note(count: u64) -> String {+ format!(+ "warning: the isolated PDF parser could not start for {}, so no PDF text was indexed. \+ Other files in this run were still indexed. This is a worker startup failure (process \+ or resource limits). Exit 1 ({PDF_WORKER_UNAVAILABLE_REASON}).",+ estimate::count_phrase(count, "PDF file", "PDF files")+ )+}++#[cfg(unix)]+fn note_worker_address_space_cap(progress: &Progress) {+ if let Some(warning) = extract::rlimit::take_address_space_cap_warning() {+ progress.note(warning);+ }+}++#[cfg(not(unix))]+fn note_worker_address_space_cap(_progress: &Progress) {}+fn inventory_size_map(inventory: &content::Inventory) -> HashMap<&str, u64> {inventory.keys@@ -4944,6 +4992,7 @@ fn build_phase_a(});report_pdf_spool_fallbacks(files, &scans, ctx);+ note_worker_address_space_cap(pr);let rels: Vec<String> = files.iter().map(|f| f.rel.clone()).collect();let scopes = compute_scopes(root, &rels);@@ -6539,6 +6588,12 @@ fn finish_generated_run(es: &Es, journal: &mut state::Journal, cfg: &IndexCfg) -if let Some(skipped) = skip_doc {summary["skipped"] = skipped;}+ // Recomputed from the committed plan, not only copied from the catalog+ // document: a no-op re-run reads the previous run document, which may+ // predate this field, and a family-wide worker failure must still exit 1.+ if let Some(n) = committed.plan.pdf_worker_unavailable_count() {+ summary["pdf_worker_unavailable"] = json!(n);+ }journal.finish(&summary)?;if cfg.json {println!("{summary}");@@ -6552,6 +6607,12 @@ fn finish_generated_run(es: &Es, journal: &mut state::Journal, cfg: &IndexCfg) -count("junk_records_total"),false,0,+ summary+ .get("pdf_worker_unavailable")+ .and_then(Value::as_u64)+ .filter(|n| *n > 0),+ // File removal is reported on the graph path. This printer+ // is the generated route, which does not sweep membership.0,));@@ -11663,6 +11724,12 @@ fn run_index_report_inner(if let Some(skipped) = skipped_json(&all_junk) {run_doc["skipped"] = skipped;}+ // #2336: present only when every PDF failed to start the isolated parser.+ // A single corrupt PDF stays ordinary junk and does not set the field.+ let pdf_worker_unavailable = plan.pdf_worker_unavailable_count();+ if let Some(n) = pdf_worker_unavailable {+ run_doc["pdf_worker_unavailable"] = json!(n);+ }// Owned lines: the resume-plan update below mutates `plan.junk_files`,// which `all_junk` borrows. The summary prints these after that update.let skip_lines = skipped_lines(&all_junk);@@ -11755,8 +11822,11 @@ fn run_index_report_inner(// than on a code of their own: inventing another success code would break// every caller that already branches on 0/3. The `reason` is what tells// them apart. A removal is not exit 0: that is what the run printed when- // the documents stayed live (#2314).- let code = if junk_total_records > 0+ // the documents stayed live (#2314). A PDF worker that could not start is+ // exit 1: exit 3 would call a missing PDF family success (#2336).+ let code = if pdf_worker_unavailable.is_some() {+ 1+ } else if junk_total_records > 0|| junk_file_count > 0|| alias_sweep_error.is_some()|| skipped_appeared > 0@@ -11777,6 +11847,7 @@ fn run_index_report_inner(junk_total_records,alias_sweep_error.is_some(),skipped_appeared as u64,+ pdf_worker_unavailable,files_removed,));@@ -11929,14 +12000,22 @@ fn run_index_report_inner(if dataless_skipped > 0 {done_fields.push(("skipped_dataless", dataless_skipped));}+ if let Some(n) = pdf_worker_unavailable {+ done_fields.push(("pdf_worker_unavailable", n));+ pr.note(&pdf_worker_unavailable_note(n));+ }+ note_worker_address_space_cap(&pr);pr.finish(- true,+ pdf_worker_unavailable.is_none(),code,- // A stale plan wins the `reason` when files on disk were not indexed:- // junk is the everyday state, and `completed-with-junk` is what hid- // those files (#2076). The alias-sweep failure is next: it needs an- // operator, and junk does not.- if skipped_appeared > 0 {+ // A worker that cannot start wins the `reason`: exit 3 would call a+ // missing PDF family success (#2336). A stale plan is next, because+ // junk is the everyday state and `completed-with-junk` is what hid+ // those files (#2076). The alias-sweep failure needs an operator,+ // and ordinary junk does not.+ if pdf_worker_unavailable.is_some() {+ PDF_WORKER_UNAVAILABLE_REASON+ } else if skipped_appeared > 0 {STALE_RESUME_PLAN_REASON} else if alias_sweep_error.is_some() {ALIAS_SWEEP_FAILED_REASON@@ -13956,11 +14035,11 @@ mod generation_contract_identity_tests {/// what was recorded instead of hiding it.#[test]fn a_finished_run_leads_with_an_ok_line_that_spells_out_exit_3() {- let clean = outcome_headline(0, 0, 0, false, 0, 0);+ let clean = outcome_headline(0, 0, 0, false, 0, None, 0);assert!(clean.starts_with("ok: indexed and searchable"), "{clean}");assert!(clean.contains("exit 0"), "{clean}");- let junk = outcome_headline(3, 1, 0, false, 0, 0);+ let junk = outcome_headline(3, 1, 0, false, 0, None, 0);assert!(junk.starts_with("ok: indexed and searchable"), "{junk}");assert!(junk.contains("exit 3 (completed-with-junk) is SUCCESS, not an error"),@@ -13970,10 +14049,10 @@ mod generation_contract_identity_tests {assert!(junk.contains("xerj autoindex"), "{junk}");assert!(!junk.contains('\n'), "one line: {junk}");- let both = outcome_headline(3, 2, 5, false, 0, 0);+ let both = outcome_headline(3, 2, 5, false, 0, None, 0);assert!(both.contains("2 files and 5 records"), "{both}");- let removed = outcome_headline(3, 0, 0, false, 0, 1);+ let removed = outcome_headline(3, 0, 0, false, 0, None, 1);assert!(removed.contains("exit 3 (files-removed) is SUCCESS, not an error"),"{removed}"@@ -13987,13 +14066,13 @@ mod generation_contract_identity_tests {"a removal is not junk: {removed}");assert!(!removed.contains('\n'), "one line: {removed}");- let removed_and_junk = outcome_headline(3, 1, 0, false, 0, 2);+ let removed_and_junk = outcome_headline(3, 1, 0, false, 0, None, 2);assert!(removed_and_junk.contains("Also recorded as junk: 1 file"),"{removed_and_junk}");- let stale = outcome_headline(3, 0, 0, false, 2, 0);+ let stale = outcome_headline(3, 0, 0, false, 2, None, 0);assert!(stale.contains("exit 3 (stale-resume-plan)"), "{stale}");assert!(stale.contains("2 files skipped because the resumed plan is stale"),@@ -14005,13 +14084,18 @@ mod generation_contract_identity_tests {"a stale plan is not junk: {stale}");assert!(!stale.contains('\n'), "one line: {stale}");- let stale_and_junk = outcome_headline(3, 1, 0, false, 2, 0);+ let stale_and_junk = outcome_headline(3, 1, 0, false, 2, None, 0);assert!(stale_and_junk.contains("Also recorded as junk: 1 file"),"{stale_and_junk}");- let sweep = outcome_headline(3, 4, 0, true, 0, 0);+ let sweep = outcome_headline(3, 4, 0, true, 0, None, 0);+ let pdfs = outcome_headline(1, 4, 0, false, 0, Some(4), 0);+ assert!(pdfs.starts_with("not ok:"), "{pdfs}");+ assert!(pdfs.contains("4 PDF files"), "{pdfs}");+ assert!(pdfs.contains(PDF_WORKER_UNAVAILABLE_REASON), "{pdfs}");+ assert!(!pdfs.contains("is SUCCESS"), "{pdfs}");assert!(sweep.starts_with("ok: indexed and searchable"), "{sweep}");assert!(sweep.contains(ALIAS_SWEEP_FAILED_REASON), "{sweep}");assert!(sweep.contains("rerun the same command"), "{sweep}");@@ -14369,6 +14453,50 @@ mod code_coverage_tests {assert!(!text.contains("warning:"), "{text}");}+ #[test]+ fn every_pdf_failing_to_start_ends_the_run_as_a_worker_outage() {+ let (pr, buffer) = progress::Progress::capture(+ progress::Surface::Plain,+ std::time::Duration::from_secs(3600),+ );+ finish_generated_progress(+ &pr,+ 3,+ &json!({+ "files_indexed": 2,+ "records_total": 4,+ "generation": 1,+ "code_files": 0,+ "code_files_indexed": 0,+ "code_files_junked": 0,+ "pdf_worker_unavailable": 2,+ }),+ 0,+ );+ let text = captured(&buffer);+ let done = text+ .lines()+ .find(|line| line.starts_with("xerj-done "))+ .unwrap_or_else(|| panic!("{text}"));+ assert!(done.contains("ok=false"), "{done}");+ assert!(done.contains("exit=1"), "{done}");+ assert!(done.contains("reason=pdf-worker-unavailable"), "{done}");+ assert!(done.contains("pdf_worker_unavailable=2"), "{done}");+ assert!(+ text.lines()+ .any(|line| line.starts_with("warning:") && line.contains("isolated PDF parser")),+ "{text}"+ );+ assert!(+ text.trim_end()+ .lines()+ .next_back()+ .unwrap()+ .starts_with("xerj-done "),+ "the warning precedes the terminal line: {text}"+ );+ }+#[test]fn skipped_dataless_placeholders_are_counted_on_the_terminal_line() {let (pr, buffer) = progress::Progress::capture(diff --git a/engine/crates/xerj-autoindex/src/resources.rs b/engine/crates/xerj-autoindex/src/resources.rsindex 41fd64722..9d3f4cd86 100644--- a/engine/crates/xerj-autoindex/src/resources.rs+++ b/engine/crates/xerj-autoindex/src/resources.rs@@ -18,9 +18,11 @@//! 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.+//! * **PDF workers** — separate processes, each budgeted 1536 MiB of address+//! space (`extract::pdf::WORKER_ADDRESS_SPACE`). The OS cap is installed+//! where `setrlimit(RLIMIT_AS)` is accepted (#2336); a refusal does not+//! raise this budget. The count is whatever the safe zone can pay for,+//! never more than the measured 4.//!//! Two rules keep the memory arithmetic from doing damage of its own://!diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex c2ef99d4d..396b14c9d 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -576,6 +576,11 @@ pub struct FileAssignment {pub as_document: bool,}+/// Substring of a PDF junk reason that means the isolated parser process+/// never started. Kept here so the run summary and the spawn error cannot+/// drift: a family-wide failure is this reason on every PDF, with none indexed.+pub(crate) const PDF_WORKER_START_FAILURE: &str = "could not start the isolated PDF parser";+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct JunkFile {pub file_key: String,@@ -586,6 +591,10 @@ pub struct JunkFile {pub bytes: u64,}+fn is_pdf_format(format: &str) -> bool {+ format.strip_suffix("(gzip)").unwrap_or(format) == "pdf"+}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct DuplicateFile {/// Content identity of the canonical file.@@ -663,6 +672,35 @@ pub struct RefusedDataset {}impl Plan {+ /// `Some(n)` when every PDF in this plan failed because the isolated+ /// parser could not start, and none was indexed (#2336).+ ///+ /// One corrupt PDF stays ordinary junk. A platform that cannot spawn the+ /// worker fails the whole family the same way, and exit 3 would report+ /// that as success. `n` is the number of PDF files.+ pub(crate) fn pdf_worker_unavailable_count(&self) -> Option<u64> {+ let indexed = self+ .files+ .values()+ .filter(|file| file.family == "pdf")+ .count();+ if indexed > 0 {+ return None;+ }+ let mut pdfs = 0u64;+ let mut start_failures = 0u64;+ for junk in &self.junk_files {+ if !is_pdf_format(&junk.format) {+ continue;+ }+ pdfs += 1;+ if junk.reason.contains(PDF_WORKER_START_FAILURE) {+ start_failures += 1;+ }+ }+ (pdfs > 0 && start_failures == pdfs).then_some(pdfs)+ }+/// The run-document fields that say a corpus lacks a dataset (#929); empty/// when nothing was refused, so a run document with nothing to report stays/// byte-identical to the one earlier releases published — the generated@@ -2938,3 +2976,59 @@ mod compatibility_tests {drop(journal);}}++#[cfg(test)]+mod pdf_worker_unavailable_tests {+ use super::{FileAssignment, JunkFile, Plan, PDF_WORKER_START_FAILURE};++ fn junk(format: &str, reason: &str) -> JunkFile {+ JunkFile {+ file_key: format!("key-{format}"),+ rel: format!("f.{format}"),+ format: format.to_string(),+ status: "junk".into(),+ reason: reason.into(),+ bytes: 1,+ }+ }++ fn indexed_pdf() -> FileAssignment {+ FileAssignment {+ rel: "a.pdf".into(),+ path_id: "a.pdf".into(),+ is_symlink: Some(false),+ family: "pdf".into(),+ gzip: false,+ content_digest: None,+ assignments: Vec::new(),+ as_document: false,+ }+ }++ #[test]+ fn every_pdf_start_failure_counts_gzip_members_and_ignores_other_formats() {+ let mut plan = Plan::default();+ let reason = format!("extract failed: {PDF_WORKER_START_FAILURE} for quarterly.pdf");+ plan.junk_files.push(junk("pdf", &reason));+ plan.junk_files.push(junk("pdf(gzip)", &reason));+ plan.junk_files.push(junk("txt", "unreadable"));+ assert_eq!(plan.pdf_worker_unavailable_count(), Some(2));+ }++ #[test]+ fn a_parsed_pdf_or_a_different_failure_stays_ordinary_junk() {+ let mut mixed = Plan::default();+ mixed.junk_files.push(junk("pdf", PDF_WORKER_START_FAILURE));+ mixed.junk_files.push(junk("pdf", "damaged"));+ assert_eq!(mixed.pdf_worker_unavailable_count(), None);++ let mut indexed = Plan::default();+ indexed.files.insert("k".into(), indexed_pdf());+ indexed+ .junk_files+ .push(junk("pdf", PDF_WORKER_START_FAILURE));+ assert_eq!(indexed.pdf_worker_unavailable_count(), None);++ assert_eq!(Plan::default().pdf_worker_unavailable_count(), None);+ }+}diff --git a/engine/crates/xerj-server/tests/pdf_worker.rs b/engine/crates/xerj-server/tests/pdf_worker.rsindex 5cd23c3cf..710aba42c 100644--- a/engine/crates/xerj-server/tests/pdf_worker.rs+++ b/engine/crates/xerj-server/tests/pdf_worker.rs@@ -253,3 +253,47 @@ fn pdf_worker_accepts_non_utf8_unix_paths() {let response: Value = serde_json::from_slice(&output.stdout).unwrap();assert_eq!(response["records"][0]["fields"]["page"], 1);}++/// The parent spawn path (`extract` → `pre_exec`) is what #2336 broke: a+/// refused `RLIMIT_AS` failed `Command::spawn` before `exec`, so+/// `XERJ_PDF_WORKER_BIN` never ran. This calls that path with the real+/// worker. On Linux the 1536 MiB cap is applied; on a kernel that returns+/// `EINVAL` or `EPERM` the worker still starts.+#[cfg(unix)]+#[test]+fn parent_spawn_extracts_a_small_pdf_when_the_address_space_cap_is_refused_or_applied() {+ let _env = env_guard();+ let previous = std::env::var_os("XERJ_PDF_WORKER_BIN");+ std::env::set_var("XERJ_PDF_WORKER_BIN", env!("CARGO_BIN_EXE_xerj"));+ struct Restore(Option<std::ffi::OsString>);+ impl Drop for Restore {+ fn drop(&mut self) {+ match self.0.take() {+ Some(value) => std::env::set_var("XERJ_PDF_WORKER_BIN", value),+ None => std::env::remove_var("XERJ_PDF_WORKER_BIN"),+ }+ }+ }+ let _restore = Restore(previous);++ let temp = tempfile::tempdir().unwrap();+ let pdf = temp.path().join("quarterly-report.pdf");+ write_prose_pdf(&pdf);++ let mut bodies = Vec::new();+ let mut sink = |record: xerj_autoindex::extract::RawRecord| {+ if let Some(body) = record.fields.get("body").and_then(|value| value.as_str()) {+ bodies.push(body.to_string());+ }+ true+ };+ let stats = xerj_autoindex::extract::pdf::extract(&pdf, &mut sink)+ .expect("isolated PDF parser starts even if RLIMIT_AS is refused");+ assert!(stats.records >= 1, "records={}", stats.records);+ assert!(+ bodies+ .iter()+ .any(|body| body.contains("operating margin improved")),+ "{bodies:?}"+ );+}