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): rebase the PDF parse-once spool onto main and close the review blockers
xerj-orgc521b7c7ed49
diff --git a/engine/crates/xerj-autoindex/src/extract/pdf.rs b/engine/crates/xerj-autoindex/src/extract/pdf.rsindex 4adc8e78f..3a41fd677 100644--- a/engine/crates/xerj-autoindex/src/extract/pdf.rs+++ b/engine/crates/xerj-autoindex/src/extract/pdf.rs@@ -45,6 +45,16 @@ const JOURNAL_FILESYSTEM_HEADROOM: u64 = 64 << 20;const MIN_DESCRIPTOR_HEADROOM: u64 = 64;const DESCRIPTOR_HEADROOM_PER_WORKER: u64 = 4;+/// Serializes every test that mutates the process-global+/// `XERJ_PDF_WORKER_BIN`/`XERJ_TEST_PDF_COUNT` pair. The variables are read+/// inside `spawn_worker`, so a test that sets them changes the behaviour of+/// every other test running concurrently in this binary — including tests in+/// sibling modules. Take this before the first `set_var` and hold it until the+/// restoring guard drops. Poison is ignored on purpose: a panicking test must+/// not cascade into unrelated failures here.+#[cfg(test)]+pub(crate) static WORKER_BIN_ENV_LOCK: Mutex<()> = Mutex::new(());+#[cfg(test)]static CORRUPT_REPLAY_SOURCE_SIZE: AtomicU64 = AtomicU64::new(u64::MAX);#[cfg(test)]@@ -84,8 +94,11 @@ pub(crate) fn extract_and_spool() -> Result<(ExtractStats, Option<ExtractionSpool>, Option<SpoolFallback>)> {let _permit = worker_gate().acquire();let response = spawn_worker(path)?;- // Count completed parser protocol calls, not attempts that failed before- // producing a response which Phase A could use.+ // Counted only once the worker has produced a usable protocol response.+ // An invocation that spawned and then failed, timed out, or was killed is+ // deliberately excluded — hence `..._responses` and not `..._calls` in the+ // report. Total parser *invocations* are not a number this counter can+ // honestly supply.budget.record_phase_a_parse();let (spool, fallback) =try_spool_response(state_dir, source_size, source_digest, budget, &response);@@ -222,7 +235,7 @@ pub(crate) struct ExtractionSpoolBudget {exact_artifact_bytes: AtomicU64,peak_retained_or_reserved_bytes: AtomicU64,peak_live_artifacts: AtomicU64,- phase_a_pdf_parser_calls: AtomicU64,+ phase_a_pdf_parser_responses: AtomicU64,capacity_status: &'static str,capacity_reason: &'static str,fallback_examples: Mutex<Vec<serde_json::Value>>,@@ -272,7 +285,7 @@ impl ExtractionSpoolBudget {exact_artifact_bytes: AtomicU64::new(0),peak_retained_or_reserved_bytes: AtomicU64::new(0),peak_live_artifacts: AtomicU64::new(0),- phase_a_pdf_parser_calls: AtomicU64::new(0),+ phase_a_pdf_parser_responses: AtomicU64::new(0),capacity_status: "enabled",capacity_reason: "explicit_budget",fallback_examples: Mutex::new(Vec::new()),@@ -388,7 +401,7 @@ impl ExtractionSpoolBudget {exact_artifact_bytes: AtomicU64::new(0),peak_retained_or_reserved_bytes: AtomicU64::new(0),peak_live_artifacts: AtomicU64::new(0),- phase_a_pdf_parser_calls: AtomicU64::new(0),+ phase_a_pdf_parser_responses: AtomicU64::new(0),capacity_status,capacity_reason,fallback_examples: Mutex::new(Vec::new()),@@ -498,7 +511,7 @@ impl ExtractionSpoolBudget {"peak_retained_or_reserved_bytes": self.peak_retained_or_reserved_bytes.load(Ordering::Relaxed),"current_live_artifacts": self.spools.load(Ordering::Relaxed),"peak_live_artifacts": self.peak_live_artifacts.load(Ordering::Relaxed),- "phase_a_pdf_parser_calls": self.phase_a_pdf_parser_calls.load(Ordering::Relaxed),+ "phase_a_pdf_parser_responses": self.phase_a_pdf_parser_responses.load(Ordering::Relaxed),"capacity_fallbacks": self.capacity_fallbacks.load(Ordering::Relaxed),"io_fallbacks": self.io_fallbacks.load(Ordering::Relaxed),"replay_verified": self.replay_verified.load(Ordering::Relaxed),@@ -530,8 +543,13 @@ impl ExtractionSpoolBudget {self.phase_b_pdf_parses.fetch_add(1, Ordering::Relaxed);}+ /// A verified artifact that failed one of its pre-replay checks. This is+ /// an *integrity* outcome, already counted by `replay_integrity_failures`+ /// inside `replay_with_gate`; it deliberately does not touch+ /// `io_fallbacks`, which counts only the artifact-creation I/O failures in+ /// `try_spool_response`. A digest, JSON, or protocol-identity mismatch is+ /// not an I/O event and reporting it as one would overstate disk trouble.pub(crate) fn record_replay_fallback(&self, path: &str, error: &anyhow::Error) {- self.record_io_fallback();self.record_fallback_category("replay_verification");self.record_fallback_example(path,@@ -547,14 +565,6 @@ impl ExtractionSpoolBudget {self.capacity_status == "disabled" && self.capacity_reason == "descriptor_probe_unavailable"}- /// True when no artifact can ever be retained on this run, for any reason- /// (unsupported platform, insufficient capacity, or a zero budget). The- /// caller uses this to skip building per-file fallback diagnostics that- /// would only restate one global fact once per PDF.- pub(crate) fn is_globally_disabled(&self) -> bool {- self.capacity_status == "disabled"- }-pub(crate) fn record_fallback_example(&self,path: &str,@@ -582,7 +592,7 @@ impl ExtractionSpoolBudget {}fn record_phase_a_parse(&self) {- self.phase_a_pdf_parser_calls+ self.phase_a_pdf_parser_responses.fetch_add(1, Ordering::Relaxed);}@@ -757,13 +767,25 @@ pub(crate) struct ExtractionSpool {}impl ExtractionSpool {+ /// Verify and deliver the retained response exactly once.+ ///+ /// Four checks can fail against a caller that routed the right artifact to+ /// the right file: the artifact's physical length, its content digest, its+ /// JSON decode, and the worker protocol identity inside it. The+ /// `source_size`/`source_digest` comparison below is a fifth check of a+ /// different kind — a binding assertion. Phase B derives both values from+ /// the same inventory entry that Phase A spooled under, so at the+ /// production call site it can only fire if an artifact were routed to the+ /// wrong file. Mutation of the *source* between phases is caught earlier+ /// and with full strength by the `content::verify` call that Phase B runs+ /// before extraction (`lib.rs`), not here.pub(crate) fn replay(self,source_size: u64,source_digest: &str,sink: Sink,) -> Result<ExtractStats> {- self.replay_with_gate(source_size, source_digest, sink, worker_gate(), true)+ self.replay_with_gate(source_size, source_digest, sink, worker_gate())}fn replay_with_gate(@@ -772,7 +794,6 @@ impl ExtractionSpool {source_digest: &str,sink: Sink,gate: &WorkerGate,- _observe_global_replay: bool,) -> Result<ExtractStats> {// JSON decoding materializes a bounded WorkerResponse just like the// parser protocol. Share the PDF gate so Phase B cannot multiply that@@ -788,6 +809,7 @@ impl ExtractionSpool {} = self;let budget = Arc::clone(&reservation.budget);let decoded = (|| -> Result<WorkerResponse> {+ // Binding assertion, not a source-mutation check — see `replay`.anyhow::ensure!(source_size == expected_size && source_digest == expected_digest,"PDF extraction spool belongs to a different source generation; retry extraction"@@ -1549,7 +1571,7 @@ mod tests {)]),locator: format!("p1-s{index}"),group: None,- origin: FieldOrigin::Extractor,+ origin: super::FieldOrigin::Extractor,}).collect();let expected = response(records.clone());@@ -1625,9 +1647,33 @@ mod tests {#[test]fn failed_worker_protocol_call_is_not_reported_as_a_completed_phase_a_parse() {+ // `spawn_worker` reads the process-global `XERJ_PDF_WORKER_BIN`, which+ // the run_index tests in `failure_resume_http_tests` point at a stub+ // that answers successfully for *any* path. Without both the shared+ // lock and an explicitly failing worker of our own, this test's+ // outcome depends on which other test happens to be running — it only+ // passed in CI because of `--test-threads=2` plus name ordering.+ let _env_lock = super::WORKER_BIN_ENV_LOCK+ .lock()+ .unwrap_or_else(|poison| poison.into_inner());let source = tempfile::tempdir().unwrap();let state = tempfile::tempdir().unwrap();let missing = source.path().join("missing.pdf");+ let previous = std::env::var_os("XERJ_PDF_WORKER_BIN");+ std::env::set_var(+ "XERJ_PDF_WORKER_BIN",+ source.path().join("no-such-pdf-worker"),+ );+ struct RestoreWorkerBin(Option<std::ffi::OsString>);+ impl Drop for RestoreWorkerBin {+ 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 = RestoreWorkerBin(previous);let budget = super::ExtractionSpoolBudget::new(super::MAX_WORKER_OUTPUT as u64, 1);let error = match super::extract_and_spool(&missing,@@ -1638,10 +1684,10 @@ mod tests {&mut |_| true,) {Err(error) => error,- Ok(_) => panic!("a missing PDF cannot produce a worker response"),+ Ok(_) => panic!("a worker binary that does not exist cannot produce a response"),};assert!(!format!("{error:#}").is_empty());- assert_eq!(budget.report()["phase_a_pdf_parser_calls"], 0);+ assert_eq!(budget.report()["phase_a_pdf_parser_responses"], 0);assert_eq!(budget.report()["reservations_started"], 0);}@@ -1829,7 +1875,7 @@ mod tests {fields: serde_json::Map::from_iter([("body".into(), body.clone().into())]),locator: "p1-s0".into(),group: None,- origin: FieldOrigin::Extractor,+ origin: super::FieldOrigin::Extractor,};let budget = super::ExtractionSpoolBudget::new(super::MAX_WORKER_OUTPUT as u64, 1);let spool = spool_response(@@ -2000,7 +2046,7 @@ mod tests {fields: serde_json::Map::new(),locator: "page:1".into(),group: None,- origin: FieldOrigin::Extractor,+ origin: super::FieldOrigin::Extractor,}];let spools: Vec<_> = (0..REPLAYS).map(|_| {@@ -2039,7 +2085,6 @@ mod tests {true},&gate,- false,).unwrap();});diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex 1a9b96d93..caba5d212 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -16,8 +16,29 @@ use std::thread;static FAILPOINT_TEST_LOCK: Mutex<()> = Mutex::new(());+/// Owns the process-global PDF worker environment for the duration of one+/// test. `XERJ_PDF_WORKER_BIN` is read inside `spawn_worker`, so a test that+/// sets it silently rewrites what every concurrently running test in this+/// binary observes — including the unit tests in `extract::pdf`. Acquire this+/// **before** the first `set_var`; the shared lock is the only thing that+/// makes those two suites safe to run at the default thread count.#[cfg(unix)]-struct PdfWorkerEnvGuard;+struct PdfWorkerEnvGuard {+ /// Held, never read: dropping it after the environment is cleared is the+ /// whole point.+ _lock: std::sync::MutexGuard<'static, ()>,+}++#[cfg(unix)]+impl PdfWorkerEnvGuard {+ fn acquire() -> Self {+ Self {+ _lock: crate::extract::pdf::WORKER_BIN_ENV_LOCK+ .lock()+ .unwrap_or_else(|poison| poison.into_inner()),+ }+ }+}#[cfg(unix)]impl Drop for PdfWorkerEnvGuard {@@ -1344,7 +1365,7 @@ fn fresh_pdf_is_parsed_once_and_failed_publication_retry_reparses_once() {let worker_script = String::from_utf8(br#"#!/bin/shprintf 'parse\n' >> "$XERJ_TEST_PDF_COUNT"-printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"title":"quarterly-report","page":1,"body":"Quarterly revenue increased while operating margin improved.","pdf_pages_total":1,"pdf_pages_with_text":1,"pdf_pages_omitted":0},"locator":"p1-s0","group":null}]}'+printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"title":"quarterly-report","page":1,"body":"Quarterly revenue increased while operating margin improved.","pdf_pages_total":1,"pdf_pages_with_text":1,"pdf_pages_omitted":0},"locator":"p1-s0","group":null,"origin":"extractor"}]}'"#.to_vec(),)@@ -1355,9 +1376,9 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":let endpoint = MockEndpoint::start(1);let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ let _env = PdfWorkerEnvGuard::acquire();std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);std::env::set_var("XERJ_TEST_PDF_COUNT", &count);- let _env = PdfWorkerEnvGuard;let first = run_index(config.clone()).unwrap_err();assert!(format!("{first:#}").contains("bulk backend failed"));@@ -1414,7 +1435,7 @@ fn refused_pdf_spool_reparses_and_reports_fallback_without_weakening_publicationlet worker_script = String::from_utf8(br#"#!/bin/shprintf 'parse\n' >> "$XERJ_TEST_PDF_COUNT"-printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"title":"quarterly-report","page":1,"body":"Quarterly revenue increased while operating margin improved.","pdf_pages_total":1,"pdf_pages_with_text":1,"pdf_pages_omitted":0},"locator":"p1-s0","group":null}]}'+printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"title":"quarterly-report","page":1,"body":"Quarterly revenue increased while operating margin improved.","pdf_pages_total":1,"pdf_pages_with_text":1,"pdf_pages_omitted":0},"locator":"p1-s0","group":null,"origin":"extractor"}]}'"#.to_vec(),)@@ -1425,9 +1446,9 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":let endpoint = MockEndpoint::start(0);let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ let _env = PdfWorkerEnvGuard::acquire();std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);std::env::set_var("XERJ_TEST_PDF_COUNT", &count);- let _env = PdfWorkerEnvGuard;let (code, report) = run_index_report(config).unwrap();assert_eq!(code, 0);@@ -1440,7 +1461,7 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":assert_eq!(reuse["phase_b_pdf_parses"], 1);assert_eq!(reuse["replay_verified"], 0);assert_eq!(reuse["artifacts_not_created"], 1);- assert_eq!(reuse["phase_a_pdf_parser_calls"], 1);+ assert_eq!(reuse["phase_a_pdf_parser_responses"], 1);assert_eq!(reuse["capacity_status"], "disabled");assert_eq!(reuse["fallback_examples"][0]["path"],@@ -1460,13 +1481,16 @@ fn refused_spool_does_not_pay_a_second_phase_a_source_hash() {let pdf = corpus.path().join("quarterly-report.pdf");fs::write(&pdf, b"%PDF-1.4\nsame-size-source-generation\n").unwrap();let size = fs::metadata(&pdf).unwrap().len();- let digest = content::resolve(vec![crate::walk::FileEntry {- path: pdf.clone(),- rel: "quarterly-report.pdf".into(),- rel_id: "quarterly-report.pdf".into(),- is_symlink: false,- size,- }])+ let digest = content::resolve_reporting(+ vec![crate::walk::FileEntry {+ path: pdf.clone(),+ rel: "quarterly-report.pdf".into(),+ rel_id: "quarterly-report.pdf".into(),+ is_symlink: false,+ size,+ }],+ &|_| {},+ ).unwrap().digests.remove(0);@@ -1475,7 +1499,7 @@ fn refused_spool_does_not_pay_a_second_phase_a_source_hash() {let worker_script = String::from_utf8(br#"#!/bin/shprintf 'Z' | dd of="$2" bs=1 seek=10 conv=notrunc 2>/dev/null-printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"body":"Quarterly revenue increased while operating margin improved."},"locator":"p1-s0","group":null}]}'+printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"body":"Quarterly revenue increased while operating margin improved."},"locator":"p1-s0","group":null,"origin":"extractor"}]}'"#.to_vec(),)@@ -1483,11 +1507,24 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":.replace("__XERJ_VERSION__", env!("CARGO_PKG_VERSION"));fs::write(&worker, worker_script).unwrap();fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();+ let _env = PdfWorkerEnvGuard::acquire();std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);- let _env = PdfWorkerEnvGuard;let budget = crate::extract::pdf::ExtractionSpoolBudget::new(0, 0);- let scan = scan_file(&pdf, size, &digest, state_dir.path(), &budget, 100, 1);+ let progress = Progress::silent();+ let scan = scan_file(+ &pdf,+ size,+ &digest,+ &PhaseAContext {+ state_dir: state_dir.path(),+ budget: &budget,+ capacity_warning: None,+ progress: &progress,+ },+ 100,+ 1,+ );assert!(scan.pdf_spool.is_none());assert_eq!(scan.pdf_spool_fallbacks.len(), 1);for fallback in &scan.pdf_spool_fallbacks {@@ -1507,6 +1544,94 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":.is_none());}+/// The other half of the branch above: with capacity available the artifact+/// *is* created, and phase A must then throw it away because the source moved+/// underneath the parser. Without this the source-generation arm of+/// `scan_file` has no test at all — its sibling above deliberately runs with a+/// zero budget, so it never reaches the `content::verify` comparison.+#[cfg(unix)]+#[test]+fn source_changed_during_phase_a_discards_the_artifact_and_names_the_reason() {+ use std::os::unix::fs::PermissionsExt;++ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ inject_pdf_spool_capacity(state_dir.path());+ let tools = tempfile::tempdir().unwrap();+ let pdf = corpus.path().join("quarterly-report.pdf");+ fs::write(&pdf, b"%PDF-1.4\nsame-size-source-generation\n").unwrap();+ let size = fs::metadata(&pdf).unwrap().len();+ let digest = content::resolve_reporting(+ vec![crate::walk::FileEntry {+ path: pdf.clone(),+ rel: "quarterly-report.pdf".into(),+ rel_id: "quarterly-report.pdf".into(),+ is_symlink: false,+ size,+ }],+ &|_| {},+ )+ .unwrap()+ .digests+ .remove(0);++ // Same trick as the sibling test: the worker rewrites one byte of its own+ // input, so the file keeps its length and changes its digest.+ let worker = tools.path().join("pdf-worker");+ let worker_script = String::from_utf8(+ br#"#!/bin/sh+printf 'Z' | dd of="$2" bs=1 seek=10 conv=notrunc 2>/dev/null+printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"body":"Quarterly revenue increased while operating margin improved."},"locator":"p1-s0","group":null,"origin":"extractor"}]}'+"#+ .to_vec(),+ )+ .unwrap()+ .replace("__XERJ_VERSION__", env!("CARGO_PKG_VERSION"));+ fs::write(&worker, worker_script).unwrap();+ fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();+ let _env = PdfWorkerEnvGuard::acquire();+ std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);++ let (budget, _) =+ crate::extract::pdf::ExtractionSpoolBudget::for_state_dir(state_dir.path(), 1, 1, 8);+ let progress = Progress::silent();+ let scan = scan_file(+ &pdf,+ size,+ &digest,+ &PhaseAContext {+ state_dir: state_dir.path(),+ budget: &budget,+ capacity_warning: None,+ progress: &progress,+ },+ 100,+ 1,+ );++ assert!(+ scan.pdf_spool.is_none(),+ "an artifact bound to a superseded source generation must not reach phase B"+ );+ let categories: Vec<&str> = scan+ .pdf_spool_fallbacks+ .iter()+ .map(|fallback| fallback.category)+ .collect();+ assert_eq!(categories, vec!["source_generation_changed"]);+ let report = budget.report();+ assert_eq!(report["artifacts_created"], 1);+ assert_eq!(report["artifacts_discarded_before_replay"], 1);+ assert_eq!(report["phase_b_eligible_artifacts"], 0);+ assert_eq!(report["current_live_artifacts"], 0);+ assert_eq!(report["current_retained_or_reserved_bytes"], 0);+ assert_eq!(+ report["fallback_categories"]["source_generation_changed"],+ 1+ );+}+#[cfg(unix)]#[test]fn verified_but_junk_pdf_spool_is_created_then_discarded_not_eligible() {@@ -1520,13 +1645,16 @@ fn verified_but_junk_pdf_spool_is_created_then_discarded_not_eligible() {let pdf = corpus.path().join("empty-report.pdf");fs::write(&pdf, b"%PDF-1.4\nempty test input\n").unwrap();let size = fs::metadata(&pdf).unwrap().len();- let digest = content::resolve(vec![crate::walk::FileEntry {- path: pdf.clone(),- rel: "empty-report.pdf".into(),- rel_id: "empty-report.pdf".into(),- is_symlink: false,- size,- }])+ let digest = content::resolve_reporting(+ vec![crate::walk::FileEntry {+ path: pdf.clone(),+ rel: "empty-report.pdf".into(),+ rel_id: "empty-report.pdf".into(),+ is_symlink: false,+ size,+ }],+ &|_| {},+ ).unwrap().digests.remove(0);@@ -1537,12 +1665,25 @@ fn verified_but_junk_pdf_spool_is_created_then_discarded_not_eligible() {);fs::write(&worker, script).unwrap();fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();+ let _env = PdfWorkerEnvGuard::acquire();std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);- let _env = PdfWorkerEnvGuard;let (budget, _) =crate::extract::pdf::ExtractionSpoolBudget::for_state_dir(state_dir.path(), 1, 1, 8);- let mut scan = scan_file(&pdf, size, &digest, state_dir.path(), &budget, 100, 1);+ let progress = Progress::silent();+ let mut scan = scan_file(+ &pdf,+ size,+ &digest,+ &PhaseAContext {+ state_dir: state_dir.path(),+ budget: &budget,+ capacity_warning: None,+ progress: &progress,+ },+ 100,+ 1,+ );assert!(scan.junk.is_some());assert!(scan.pdf_spool.is_some());assert!(take_pdf_spool_if_indexable(&mut scan.pdf_spool, true, &budget).is_none());@@ -1576,7 +1717,7 @@ fn multi_pdf_run_reuses_every_artifact_and_reports_exact_success_counters() {let worker_script = String::from_utf8(br#"#!/bin/shprintf 'parse\n' >> "$XERJ_TEST_PDF_COUNT"-printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"title":"quarterly-report","page":1,"body":"Quarterly revenue increased while operating margin improved.","pdf_pages_total":1,"pdf_pages_with_text":1,"pdf_pages_omitted":0},"locator":"p1-s0","group":null}]}'+printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"title":"quarterly-report","page":1,"body":"Quarterly revenue increased while operating margin improved.","pdf_pages_total":1,"pdf_pages_with_text":1,"pdf_pages_omitted":0},"locator":"p1-s0","group":null,"origin":"extractor"}]}'"#.to_vec(),)@@ -1589,9 +1730,9 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);config.workers = 8;config.pdf_workers = 2;+ let _env = PdfWorkerEnvGuard::acquire();std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);std::env::set_var("XERJ_TEST_PDF_COUNT", &count);- let _env = PdfWorkerEnvGuard;let (code, report) = run_index_report(config).unwrap();assert_eq!(code, 0);assert_eq!(@@ -1615,7 +1756,7 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":assert!(reuse["peak_retained_or_reserved_bytes"].as_u64().unwrap() > 0);assert_eq!(reuse["current_live_artifacts"], 0);assert!(reuse["peak_live_artifacts"].as_u64().unwrap() > 0);- assert_eq!(reuse["phase_a_pdf_parser_calls"], PDFS);+ assert_eq!(reuse["phase_a_pdf_parser_responses"], PDFS);assert_eq!(reuse["capacity_fallbacks"], 0);assert_eq!(reuse["io_fallbacks"], 0);assert_eq!(reuse["replay_verified"], PDFS);@@ -1643,7 +1784,7 @@ fn corrupted_pdf_replay_reparses_without_blaming_the_source_or_backend() {let worker_script = String::from_utf8(br#"#!/bin/shprintf 'parse\n' >> "$XERJ_TEST_PDF_COUNT"-printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"body":"Quarterly revenue increased while operating margin improved."},"locator":"p1-s0","group":null}]}'+printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"body":"Quarterly revenue increased while operating margin improved."},"locator":"p1-s0","group":null,"origin":"extractor"}]}'"#.to_vec(),)@@ -1654,9 +1795,9 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":let endpoint = MockEndpoint::start(0);let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ let _env = PdfWorkerEnvGuard::acquire();std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);std::env::set_var("XERJ_TEST_PDF_COUNT", &count);- let _env = PdfWorkerEnvGuard;crate::extract::pdf::corrupt_replay_for_source_size(fs::metadata(&pdf).unwrap().len());let (code, report) = run_index_report(config).unwrap();@@ -1668,7 +1809,10 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":let reuse = report.unwrap()["pdf_extraction_reuse"].clone();assert_eq!(reuse["replay_verified"], 0);assert_eq!(reuse["replay_integrity_failures"], 1);- assert_eq!(reuse["io_fallbacks"], 1);+ assert_eq!(+ reuse["io_fallbacks"], 0,+ "a corrupted artifact is an integrity failure, not an I/O failure"+ );assert_eq!(reuse["phase_b_pdf_parses"], 1);assert_eq!(reuse["current_live_artifacts"], 0);assert_eq!(reuse["current_retained_or_reserved_bytes"], 0);diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex c0a4d0366..3e2df8904 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -215,15 +215,31 @@ fn take_pdf_spool_if_indexable<T>(}}+/// Everything phase A needs beyond the file list and the run config: where a+/// run-local PDF artifact may live, the shared admission budget, the one-line+/// capacity explanation reported when files fall back — and the progress+/// surface those lines go out through, because phase A now reports every file+/// it touches (#241) as well as every artifact it could not keep.+///+/// Grouped so `scan_file` and `build_phase_a` each take one parameter instead+/// of four.+struct PhaseAContext<'a> {+ state_dir: &'a Path,+ budget: &'a std::sync::Arc<extract::pdf::ExtractionSpoolBudget>,+ capacity_warning: Option<&'a str>,+ progress: &'a Progress,+}+fn scan_file(path: &Path,size: u64,digest: &str,- state_dir: &Path,- pdf_spool_budget: &std::sync::Arc<extract::pdf::ExtractionSpoolBudget>,+ ctx: &PhaseAContext<'_>,sample: usize,max_file_gb: u64,) -> FileScan {+ let state_dir = ctx.state_dir;+ let pdf_spool_budget = ctx.budget;let mut out = FileScan {sniffed: None,sketches: Vec::new(),@@ -389,7 +405,14 @@ mod clustering_key_tests {// Clustering keys are decided by extraction, not by PDF artifact// reuse: a zero budget keeps these cases on the plain parse path.let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);- scan_file(&path, size, "d0", dir, &budget, 500, 2)+ let progress = Progress::silent();+ let ctx = PhaseAContext {+ state_dir: dir,+ budget: &budget,+ capacity_warning: None,+ progress: &progress,+ };+ scan_file(&path, size, "d0", &ctx, 500, 2)}/// The #178 mechanism, from the extractor to the clustering key: a source@@ -504,16 +527,26 @@ mod phase_a_grouping_tests {.map(|f| ids::file_key(&f.path, f.size).unwrap()).collect();let digests: Vec<String> = (0..files.len()).map(|i| format!("d{i}")).collect();- let (plan, _) = build_phase_a(+ // Planning is what these cases assert on; a zero budget keeps every+ // file on the plain parse path so no artifact is ever retained.+ let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);+ let progress = Progress::silent();+ let ctx = PhaseAContext {+ state_dir: root,+ budget: &budget,+ capacity_warning: None,+ progress: &progress,+ };+ build_phase_a(root,&files,&keys,&digests,Vec::new(),+ &ctx,&cfg_for(root),- &Progress::silent(),- );- plan+ )+ .plan}const CODE: &str = "// The event loop dispatches every ready connection to a worker.\n\@@ -686,23 +719,21 @@ struct PhaseA {/// Record and report why individual PDFs could not retain a run-local/// artifact. Reuse is an accelerator, so this is purely informational: every-/// listed file is parsed again by the normal phase B path. When the budget is-/// globally disabled there is nothing to explain — no artifact was ever-/// attempted — so nothing is recorded or printed.+/// listed file is parsed again by the normal phase B path. Recording is kept+/// even when the budget is globally disabled — the stored examples are the+/// only place the `--json` report explains *why* nothing was reused, and they+/// are already capped at three.///-/// Reporting goes through the progress surface, never a bare `eprintln!`:+/// Reporting goes out through the progress surface, never a bare `eprintln!`:/// stderr belongs to that surface, so `--progress none` stays silent and/// `--progress json` stays a single parseable stream (#241).fn report_pdf_spool_fallbacks(files: &[walk::FileEntry],scans: &[FileScan],- pdf_spool_budget: &extract::pdf::ExtractionSpoolBudget,- pdf_spool_capacity_warning: Option<&str>,- pr: &Progress,+ ctx: &PhaseAContext<'_>,) {- if pdf_spool_budget.is_globally_disabled() {- return;- }+ let pdf_spool_budget = ctx.budget;+ let pr = ctx.progress;let reasons: Vec<(&str, &extract::pdf::SpoolFallback)> = scans.iter().enumerate()@@ -730,7 +761,7 @@ fn report_pdf_spool_fallbacks(phase B will parse them again safely",reasons.len()));- if let Some(warning) = pdf_spool_capacity_warning {+ if let Some(warning) = ctx.capacity_warning {pr.note(&format!(" PDF reuse capacity: {warning}"));}for (path, fallback) in reasons.iter().take(3) {@@ -756,45 +787,30 @@ fn build_phase_a(keys: &[String],digests: &[String],duplicate_files: Vec<DuplicateFile>,- state_dir: &Path,- pdf_spool_budget: &std::sync::Arc<extract::pdf::ExtractionSpoolBudget>,- pdf_spool_capacity_warning: Option<&str>,+ ctx: &PhaseAContext<'_>,cfg: &IndexCfg,- pr: &Progress,) -> PhaseA {use rayon::prelude::*;+ let pdf_spool_budget = ctx.budget;+ let pr = ctx.progress;// Same pool as the digest phase: sniffing and sampling are the other half// of the CPU-bound phase `--workers` has to bound (#240 §2). Progress is// reported from inside that pool, so the straggler the ticker names is the// file a scan-pool thread is genuinely sitting on (#241). Retaining a PDF- // artifact happens inside that same guard, so a spooled file is counted- // exactly like a plainly parsed one.+ // artifact happens inside that same guard, so a file whose extraction is+ // spooled is counted exactly like a plainly parsed one.let scans: Vec<FileScan> = crate::pool::install(|| {files.par_iter().zip(digests.par_iter()).map(|(f, digest)| {let _in_flight = pr.file(&f.rel, f.size);- scan_file(- &f.path,- f.size,- digest,- state_dir,- pdf_spool_budget,- cfg.sample,- cfg.max_file_gb,- )+ scan_file(&f.path, f.size, digest, ctx, cfg.sample, cfg.max_file_gb)}).collect()});- report_pdf_spool_fallbacks(- files,- &scans,- pdf_spool_budget,- pdf_spool_capacity_warning,- pr,- );+ report_pdf_spool_fallbacks(files, &scans, ctx);let rels: Vec<String> = files.iter().map(|f| f.rel.clone()).collect();let scopes = compute_scopes(root, &rels);@@ -1382,6 +1398,12 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {cfg.pdf_workers,cfg.bulk_mb,);+ let phase_a_context = PhaseAContext {+ state_dir: &state_dir,+ budget: &pdf_spool_budget,+ capacity_warning: pdf_spool_capacity_warning.as_deref(),+ progress: &pr,+ };let mut plan: Plan = if let Some(p) = journal.plan.clone() {p} else {@@ -1403,11 +1425,8 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {&keys,&digests,duplicate_files.clone(),- &state_dir,- &pdf_spool_budget,- pdf_spool_capacity_warning.as_deref(),+ &phase_a_context,&cfg,- &pr,);pdf_spools = spools;pr.note(&format!(