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
perf(autoindex): reuse the phase-A PDF extraction in phase B instead of parsing twice
xerj-org53555e7ec7c4
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex 3b6b4ff60..055c30b9d 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -130,9 +130,14 @@ pub fn print_help() {Image-only pages need OCR. Page parse failures reject the whole PDF instead\n\of silently creating a partial index. XERJ_PDF_WORKER_BIN is a trusted,\n\developer-only executable override.\n\- Current cost: phase-A sampling parses/materializes each complete PDF, and\n\- phase-B indexing parses it again. A framed, early-stop protocol is planned;\n\- use fewer --pdf-workers when parent memory is constrained.\n\+ On Linux, fresh runs attempt to retain each validated PDF extraction in\n\+ bounded anonymous storage under --state-dir. Live admission-time checks\n\+ attempt to preserve disk and descriptor headroom; refused artifacts are\n\+ parsed again in phase B and reported under pdf_extraction_reuse. Other\n\+ platforms currently disable this optimization. Frozen-plan resumes skip\n\+ phase A and parse unfinished PDFs once.\n\+ --pdf-workers bounds both phase-A parser processes and phase-B replay\n\+ materialization; --workers does not widen that PDF memory gate.\n\\n\EMBEDDINGS:\n\autoindex sends semantic_text to the running server; it does not choose the\n\diff --git a/engine/crates/xerj-autoindex/src/extract/pdf.rs b/engine/crates/xerj-autoindex/src/extract/pdf.rsindex 0ffce3d24..4adc8e78f 100644--- a/engine/crates/xerj-autoindex/src/extract/pdf.rs+++ b/engine/crates/xerj-autoindex/src/extract/pdf.rs@@ -12,12 +12,14 @@ use anyhow::{anyhow, Context, Result};use pdf_oxide::PdfDocument;use serde::{Deserialize, Serialize};use serde_json::{Map, Value};-use std::io::{Read, Write};+use std::fs::File;+use std::io::{BufReader, BufWriter, Read, Seek, Write};use std::path::{Path, PathBuf};use std::process::{Command, Stdio};use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::{Condvar, Mutex, OnceLock};+use std::sync::{Arc, Condvar, Mutex, OnceLock};use std::time::{Duration, Instant};+use xxhash_rust::xxh3::Xxh3;const PDF_CAP: u64 = 512 << 20;const MAX_PAGES: usize = 100_000;@@ -26,10 +28,823 @@ const MAX_EXTRACTED_TEXT: usize = 64 << 20;const MAX_WORKER_OUTPUT: usize = 32 << 20;const MAX_WORKER_STDERR: u64 = 64 << 10;const WORKER_ADDRESS_SPACE: u64 = 1536 << 20;+// The spool is an optional accelerator on the same filesystem and descriptor+// table as correctness-critical state. The byte ceiling includes pessimistic+// 32 MiB reservations held by concurrently serializing PDF responses, not only+// completed artifact lengths. Hundreds of small retained artifacts plus four+// in-flight maximum-sized reservations fit while optional pressure stays below+// the fixed ceiling.+const MAX_SPOOL_BYTES: u64 = 384 << 20;+const MAX_SPOOL_HANDLES: u64 = 512;+// This is an admission-time floor, not a guarantee against other processes+// consuming filesystem space after the snapshot.+const MIN_FILESYSTEM_HEADROOM: u64 = 4 << 30;+const JOURNAL_FILESYSTEM_HEADROOM: u64 = 64 << 20;+// Preserve a base allowance for the journal/lock/model/runtime plus four+// descriptors per general and PDF worker for staging, sockets, and pipes.+const MIN_DESCRIPTOR_HEADROOM: u64 = 64;+const DESCRIPTOR_HEADROOM_PER_WORKER: u64 = 4;++#[cfg(test)]+static CORRUPT_REPLAY_SOURCE_SIZE: AtomicU64 = AtomicU64::new(u64::MAX);+#[cfg(test)]+static CORRUPTED_REPLAY_RESERVATION_DROPPED: std::sync::atomic::AtomicBool =+ std::sync::atomic::AtomicBool::new(false);++#[cfg(test)]+pub(crate) fn corrupt_replay_for_source_size(source_size: u64) {+ CORRUPTED_REPLAY_RESERVATION_DROPPED.store(false, Ordering::SeqCst);+ CORRUPT_REPLAY_SOURCE_SIZE.store(source_size, Ordering::SeqCst);+}++#[cfg(test)]+pub(crate) fn corrupted_replay_reservation_was_dropped() -> bool {+ CORRUPTED_REPLAY_RESERVATION_DROPPED.load(Ordering::SeqCst)+}pub fn extract(path: &Path, sink: Sink) -> Result<ExtractStats> {let _permit = worker_gate().acquire();let response = spawn_worker(path)?;+ Ok(deliver(response, sink))+}++/// Run the isolated parser once and retain its bounded protocol response in an+/// anonymous, run-local file for Phase B.+///+/// The spool is deliberately not durable state. A process restart has a frozen+/// inference plan but no trusted open handle, so it parses the PDF again. This+/// avoids coupling extraction cache recovery to the publication journal.+pub(crate) fn extract_and_spool(+ path: &Path,+ state_dir: &Path,+ source_size: u64,+ source_digest: &str,+ budget: &Arc<ExtractionSpoolBudget>,+ sink: Sink,+) -> 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.+ budget.record_phase_a_parse();+ let (spool, fallback) =+ try_spool_response(state_dir, source_size, source_digest, budget, &response);+ let stats = deliver(response, sink);+ Ok((stats, spool, fallback))+}++pub(crate) struct SpoolFallback {+ pub(crate) category: &'static str,+ pub(crate) message: String,+}++fn try_spool_response(+ state_dir: &Path,+ source_size: u64,+ source_digest: &str,+ budget: &Arc<ExtractionSpoolBudget>,+ response: &WorkerResponse,+) -> (Option<ExtractionSpool>, Option<SpoolFallback>) {+ let reservation = budget.try_reserve(MAX_WORKER_OUTPUT as u64);+ match reservation {+ Ok(reservation) => {+ match spool_response(state_dir, source_size, source_digest, response, reservation) {+ Ok(spool) => {+ budget.record_artifact_accepted(spool.bytes);+ (Some(spool), None)+ }+ Err(error) => {+ budget.record_io_fallback();+ budget.record_fallback_category("artifact_io");+ budget.record_artifact_rejected();+ (+ None,+ Some(SpoolFallback {+ category: "artifact_io",+ message: format!(+ "could not retain the run-local extraction artifact: {error:#}"+ ),+ }),+ )+ }+ }+ }+ Err(category) => (+ {+ budget.record_artifact_rejected();+ budget.record_fallback_category(category);+ None+ },+ Some(SpoolFallback {+ category,+ message: format!(+ "admission refused ({category}); snapshot headroom or the bounded {} MiB/{}-artifact ceiling would be exceeded",+ budget.limit >> 20, budget.max_spools+ ),+ }),+ ),+ }+}++fn spool_response(+ state_dir: &Path,+ source_size: u64,+ source_digest: &str,+ response: &WorkerResponse,+ mut reservation: ExtractionSpoolReservation,+) -> Result<ExtractionSpool> {+ validate_response_identity(response)?;+ let mut file = tempfile::tempfile_in(state_dir).with_context(|| {+ format!(+ "create anonymous PDF extraction spool under {}",+ state_dir.display()+ )+ })?;+ {+ let mut writer = BufWriter::new(&mut file);+ serde_json::to_writer(&mut writer, &response)+ .context("serialize validated PDF extraction spool")?;+ writer.flush().context("flush PDF extraction spool")?;+ }+ let bytes = file+ .stream_position()+ .context("measure PDF extraction spool")?;+ if bytes > MAX_WORKER_OUTPUT as u64 {+ return Err(anyhow!(+ "validated PDF extraction spool exceeded the {} MiB parent-memory safety limit",+ MAX_WORKER_OUTPUT >> 20+ ));+ }+ let artifact_digest = artifact_digest(&mut file, bytes)?;+ reservation.shrink_to(bytes);+ file.rewind().context("rewind PDF extraction spool")?;+ Ok(ExtractionSpool {+ file: Mutex::new(file),+ source_size,+ source_digest: source_digest.to_owned(),+ bytes,+ artifact_digest,+ _reservation: reservation,+ })+}++fn artifact_digest(file: &mut File, bytes: u64) -> Result<u128> {+ file.rewind().context("rewind PDF extraction spool")?;+ let mut hash = Xxh3::new();+ let mut remaining = bytes;+ let mut buffer = [0u8; 64 * 1024];+ while remaining > 0 {+ let limit = usize::try_from(remaining.min(buffer.len() as u64))+ .context("size PDF extraction spool digest buffer")?;+ let read = file+ .read(&mut buffer[..limit])+ .context("read PDF extraction spool for digest")?;+ anyhow::ensure!(read > 0, "PDF extraction spool was truncated while hashing");+ hash.update(&buffer[..read]);+ remaining -= read as u64;+ }+ Ok(hash.digest128())+}++pub(crate) struct ExtractionSpoolBudget {+ admission: Mutex<()>,+ used: AtomicU64,+ spools: AtomicU64,+ limit: u64,+ max_spools: u64,+ live_capacity: Option<LiveCapacity>,+ reservations_started: AtomicU64,+ cumulative_reserved_bytes: AtomicU64,+ artifacts_created: AtomicU64,+ artifacts_not_created: AtomicU64,+ phase_b_eligible_artifacts: AtomicU64,+ artifacts_discarded_before_replay: AtomicU64,+ exact_artifact_bytes: AtomicU64,+ peak_retained_or_reserved_bytes: AtomicU64,+ peak_live_artifacts: AtomicU64,+ phase_a_pdf_parser_calls: AtomicU64,+ capacity_status: &'static str,+ capacity_reason: &'static str,+ fallback_examples: Mutex<Vec<serde_json::Value>>,+ fallback_examples_total: AtomicU64,+ fallback_categories: Mutex<std::collections::BTreeMap<&'static str, u64>>,+ initial_available_bytes: Option<u64>,+ initial_descriptor_limit: Option<u64>,+ initial_open_descriptors: Option<u64>,+ filesystem_headroom: Option<u64>,+ descriptor_headroom: Option<u64>,+ capacity_fallbacks: AtomicU64,+ io_fallbacks: AtomicU64,+ replay_verified: AtomicU64,+ replay_integrity_failures: AtomicU64,+ phase_b_pdf_parses: AtomicU64,+}++struct LiveCapacity {+ state_dir: PathBuf,+ filesystem_headroom: u64,+ descriptor_headroom: u64,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+struct ExtractionSpoolCapacity {+ bytes: u64,+ handles: u64,+ filesystem_headroom: u64,+ descriptor_headroom: u64,+}++impl ExtractionSpoolBudget {+ pub(crate) fn new(limit: u64, max_spools: u64) -> Arc<Self> {+ Arc::new(Self {+ admission: Mutex::new(()),+ used: AtomicU64::new(0),+ spools: AtomicU64::new(0),+ limit,+ max_spools,+ live_capacity: None,+ reservations_started: AtomicU64::new(0),+ cumulative_reserved_bytes: AtomicU64::new(0),+ artifacts_created: AtomicU64::new(0),+ artifacts_not_created: AtomicU64::new(0),+ phase_b_eligible_artifacts: AtomicU64::new(0),+ artifacts_discarded_before_replay: AtomicU64::new(0),+ 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),+ capacity_status: "enabled",+ capacity_reason: "explicit_budget",+ fallback_examples: Mutex::new(Vec::new()),+ fallback_examples_total: AtomicU64::new(0),+ fallback_categories: Mutex::new(std::collections::BTreeMap::new()),+ initial_available_bytes: None,+ initial_descriptor_limit: None,+ initial_open_descriptors: None,+ filesystem_headroom: None,+ descriptor_headroom: None,+ capacity_fallbacks: AtomicU64::new(0),+ io_fallbacks: AtomicU64::new(0),+ replay_verified: AtomicU64::new(0),+ replay_integrity_failures: AtomicU64::new(0),+ phase_b_pdf_parses: AtomicU64::new(0),+ })+ }++ /// Derive an optimization budget from the resources shared with the+ /// correctness-critical journal, Phase-B staging files, HTTP sockets, and+ /// worker pipes. If either resource cannot preserve explicit headroom,+ /// admission is disabled and Phase B uses the existing safe reparse path.+ pub(crate) fn for_state_dir(+ state_dir: &Path,+ workers: usize,+ pdf_workers: usize,+ bulk_mb: usize,+ ) -> (Arc<Self>, Option<String>) {+ let available_bytes = match available_space_for(state_dir) {+ Ok(bytes) => bytes,+ Err(error) => {+ let mut budget = Self::new(0, 0);+ let inner = Arc::get_mut(&mut budget).expect("new budget has one owner");+ inner.capacity_status = "disabled";+ inner.capacity_reason = "free_space_probe_unavailable";+ return (+ budget,+ Some(format!(+ "disabled because free space under {} could not be measured: {error}",+ state_dir.display()+ )),+ );+ }+ };+ let (descriptor_limit, open_descriptors) = descriptor_snapshot_for(state_dir);+ let capacity = derive_spool_capacity(+ available_bytes,+ descriptor_limit,+ open_descriptors,+ workers,+ pdf_workers,+ bulk_mb,+ );+ let warning = if capacity.bytes < MAX_WORKER_OUTPUT as u64 || capacity.handles == 0 {+ Some(format!(+ "disabled to preserve {} MiB filesystem and {} descriptor headroom \+ ({} MiB free, descriptor limit {})",+ capacity.filesystem_headroom >> 20,+ capacity.descriptor_headroom,+ available_bytes >> 20,+ descriptor_limit+ .map(|limit| limit.to_string())+ .unwrap_or_else(|| "unavailable".into())+ ))+ } else if capacity.bytes < MAX_SPOOL_BYTES || capacity.handles < MAX_SPOOL_HANDLES {+ Some(format!(+ "limited to {} MiB and {} artifacts to preserve {} MiB filesystem and {} \+ descriptor headroom",+ capacity.bytes >> 20,+ capacity.handles,+ capacity.filesystem_headroom >> 20,+ capacity.descriptor_headroom+ ))+ } else {+ None+ };+ let capacity_status = if capacity.bytes < MAX_WORKER_OUTPUT as u64 || capacity.handles == 0+ {+ "disabled"+ } else if capacity.bytes < MAX_SPOOL_BYTES || capacity.handles < MAX_SPOOL_HANDLES {+ "limited"+ } else {+ "enabled"+ };+ let capacity_reason = if descriptor_limit.is_none() || open_descriptors.is_none() {+ "descriptor_probe_unavailable"+ } else if capacity.bytes < MAX_WORKER_OUTPUT as u64 {+ "filesystem_headroom"+ } else if capacity.handles == 0 {+ "descriptor_headroom"+ } else if capacity_status == "limited" {+ "resource_share_limited"+ } else {+ "full_bounded_capacity"+ };+ let budget = Arc::new(Self {+ admission: Mutex::new(()),+ used: AtomicU64::new(0),+ spools: AtomicU64::new(0),+ limit: capacity.bytes,+ max_spools: capacity.handles,+ live_capacity: Some(LiveCapacity {+ state_dir: state_dir.to_owned(),+ filesystem_headroom: capacity.filesystem_headroom,+ descriptor_headroom: capacity.descriptor_headroom,+ }),+ reservations_started: AtomicU64::new(0),+ cumulative_reserved_bytes: AtomicU64::new(0),+ artifacts_created: AtomicU64::new(0),+ artifacts_not_created: AtomicU64::new(0),+ phase_b_eligible_artifacts: AtomicU64::new(0),+ artifacts_discarded_before_replay: AtomicU64::new(0),+ 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),+ capacity_status,+ capacity_reason,+ fallback_examples: Mutex::new(Vec::new()),+ fallback_examples_total: AtomicU64::new(0),+ fallback_categories: Mutex::new(std::collections::BTreeMap::new()),+ initial_available_bytes: Some(available_bytes),+ initial_descriptor_limit: descriptor_limit,+ initial_open_descriptors: open_descriptors,+ filesystem_headroom: Some(capacity.filesystem_headroom),+ descriptor_headroom: Some(capacity.descriptor_headroom),+ capacity_fallbacks: AtomicU64::new(0),+ io_fallbacks: AtomicU64::new(0),+ replay_verified: AtomicU64::new(0),+ replay_integrity_failures: AtomicU64::new(0),+ phase_b_pdf_parses: AtomicU64::new(0),+ });+ (budget, warning)+ }++ fn try_reserve(+ self: &Arc<Self>,+ bytes: u64,+ ) -> std::result::Result<ExtractionSpoolReservation, &'static str> {+ if let Some(live) = &self.live_capacity {+ let available = available_space_for(&live.state_dir).map_err(|_| {+ self.capacity_fallbacks.fetch_add(1, Ordering::Relaxed);+ "free_space_probe_failed"+ })?;+ // `available` already excludes bytes occupied by retained spool+ // files; adding `used` again would double-count them.+ if available < live.filesystem_headroom.saturating_add(bytes) {+ self.capacity_fallbacks.fetch_add(1, Ordering::Relaxed);+ return Err("filesystem_admission_floor");+ }+ let (Some(limit), Some(open)) = descriptor_snapshot_for(&live.state_dir) else {+ self.capacity_fallbacks.fetch_add(1, Ordering::Relaxed);+ return Err("descriptor_probe_failed");+ };+ if open+ .saturating_add(live.descriptor_headroom)+ .saturating_add(1)+ > limit+ {+ self.capacity_fallbacks.fetch_add(1, Ordering::Relaxed);+ return Err("descriptor_admission_floor");+ }+ }+ // Serialize the tiny accounting transition so a handle claim that is+ // subsequently rejected by the byte ceiling cannot inflate the+ // advertised live-artifact peak.+ let _admission = self.admission.lock().unwrap();+ let previous_spools = self+ .spools+ .fetch_update(Ordering::AcqRel, Ordering::Acquire, |spools| {+ (spools < self.max_spools).then_some(spools + 1)+ })+ .map_err(|_| {+ self.capacity_fallbacks.fetch_add(1, Ordering::Relaxed);+ "artifact_count_ceiling"+ })?;+ let mut used = self.used.load(Ordering::Acquire);+ loop {+ let Some(next) = used.checked_add(bytes) else {+ self.spools.fetch_sub(1, Ordering::AcqRel);+ self.capacity_fallbacks.fetch_add(1, Ordering::Relaxed);+ return Err("byte_accounting_overflow");+ };+ if next > self.limit {+ self.spools.fetch_sub(1, Ordering::AcqRel);+ self.capacity_fallbacks.fetch_add(1, Ordering::Relaxed);+ return Err("byte_ceiling");+ }+ match self+ .used+ .compare_exchange_weak(used, next, Ordering::AcqRel, Ordering::Acquire)+ {+ Ok(_) => {+ self.peak_live_artifacts+ .fetch_max(previous_spools + 1, Ordering::Relaxed);+ self.reservations_started.fetch_add(1, Ordering::Relaxed);+ self.cumulative_reserved_bytes+ .fetch_add(bytes, Ordering::Relaxed);+ self.peak_retained_or_reserved_bytes+ .fetch_max(next, Ordering::Relaxed);+ return Ok(ExtractionSpoolReservation {+ budget: Arc::clone(self),+ bytes,+ #[cfg(test)]+ cleanup_probe: std::sync::atomic::AtomicBool::new(false),+ });+ }+ Err(actual) => used = actual,+ }+ }+ }++ pub(crate) fn report(&self) -> serde_json::Value {+ serde_json::json!({+ "reservations_started": self.reservations_started.load(Ordering::Relaxed),+ "cumulative_reserved_bytes": self.cumulative_reserved_bytes.load(Ordering::Relaxed),+ "artifacts_created": self.artifacts_created.load(Ordering::Relaxed),+ "artifacts_not_created": self.artifacts_not_created.load(Ordering::Relaxed),+ "phase_b_eligible_artifacts": self.phase_b_eligible_artifacts.load(Ordering::Relaxed),+ "artifacts_discarded_before_replay": self.artifacts_discarded_before_replay.load(Ordering::Relaxed),+ "exact_artifact_bytes": self.exact_artifact_bytes.load(Ordering::Relaxed),+ "current_retained_or_reserved_bytes": self.used.load(Ordering::Relaxed),+ "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),+ "capacity_fallbacks": self.capacity_fallbacks.load(Ordering::Relaxed),+ "io_fallbacks": self.io_fallbacks.load(Ordering::Relaxed),+ "replay_verified": self.replay_verified.load(Ordering::Relaxed),+ "replay_integrity_failures": self.replay_integrity_failures.load(Ordering::Relaxed),+ "phase_b_pdf_parses": self.phase_b_pdf_parses.load(Ordering::Relaxed),+ "byte_ceiling": self.limit,+ "artifact_ceiling": self.max_spools,+ "capacity_status": self.capacity_status,+ "capacity_reason": self.capacity_reason,+ "fallback_examples": self.fallback_examples.lock().unwrap().clone(),+ "fallback_examples_limit": 3,+ "fallback_examples_truncated": self.fallback_examples_total.load(Ordering::Relaxed) > 3,+ "fallback_categories": self.fallback_categories.lock().unwrap().clone(),+ "capacity": {+ "initial_available_bytes": self.initial_available_bytes,+ "initial_descriptor_limit": self.initial_descriptor_limit,+ "initial_open_descriptors": self.initial_open_descriptors,+ "filesystem_headroom": self.filesystem_headroom,+ "descriptor_headroom": self.descriptor_headroom,+ },+ })+ }++ pub(crate) fn record_io_fallback(&self) {+ self.io_fallbacks.fetch_add(1, Ordering::Relaxed);+ }++ pub(crate) fn record_reparse(&self) {+ self.phase_b_pdf_parses.fetch_add(1, Ordering::Relaxed);+ }++ 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,+ "replay_verification",+ &format!(+ "run-local PDF extraction artifact could not be verified; reparsed source: \+ {error:#}"+ ),+ );+ }++ pub(crate) fn platform_reuse_is_unavailable(&self) -> bool {+ 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,+ category: &'static str,+ message: &str,+ ) {+ self.fallback_examples_total.fetch_add(1, Ordering::Relaxed);+ let mut examples = self.fallback_examples.lock().unwrap();+ if examples.len() < 3 {+ examples.push(serde_json::json!({+ "path": path,+ "category": category,+ "message": message,+ }));+ }+ }++ fn record_fallback_category(&self, category: &'static str) {+ *self+ .fallback_categories+ .lock()+ .unwrap()+ .entry(category)+ .or_default() += 1;+ }++ fn record_phase_a_parse(&self) {+ self.phase_a_pdf_parser_calls+ .fetch_add(1, Ordering::Relaxed);+ }++ fn record_artifact_accepted(&self, bytes: u64) {+ self.artifacts_created.fetch_add(1, Ordering::Relaxed);+ self.exact_artifact_bytes+ .fetch_add(bytes, Ordering::Relaxed);+ }++ fn record_artifact_rejected(&self) {+ self.artifacts_not_created.fetch_add(1, Ordering::Relaxed);+ }++ pub(crate) fn record_phase_b_eligible(&self) {+ self.phase_b_eligible_artifacts+ .fetch_add(1, Ordering::Relaxed);+ }++ pub(crate) fn record_discarded_before_replay(&self) {+ self.artifacts_discarded_before_replay+ .fetch_add(1, Ordering::Relaxed);+ }++ pub(crate) fn record_source_generation_changed(&self) {+ self.record_fallback_category("source_generation_changed");+ }+}++fn available_space_for(state_dir: &Path) -> std::io::Result<u64> {+ #[cfg(test)]+ if let Some(value) = injected_probe_value(state_dir, "available-bytes") {+ return Ok(value);+ }+ fs2::available_space(state_dir)+}++fn descriptor_snapshot_for(state_dir: &Path) -> (Option<u64>, Option<u64>) {+ #[cfg(test)]+ {+ let limit = injected_probe_value(state_dir, "fd-limit");+ let open = injected_probe_value(state_dir, "fd-open");+ if limit.is_some() || open.is_some() {+ return (limit, open);+ }+ }+ #[cfg(not(test))]+ let _ = state_dir;+ (descriptor_soft_limit(), open_descriptor_count())+}++#[cfg(test)]+fn injected_probe_value(state_dir: &Path, name: &str) -> Option<u64> {+ std::fs::read_to_string(state_dir.join(format!(".autoindex-test-pdf-spool-{name}")))+ .ok()?+ .trim()+ .parse()+ .ok()+}++fn derive_spool_capacity(+ available_bytes: u64,+ descriptor_limit: Option<u64>,+ open_descriptors: Option<u64>,+ workers: usize,+ pdf_workers: usize,+ bulk_mb: usize,+) -> ExtractionSpoolCapacity {+ let workers = workers as u64;+ let pdf_workers = pdf_workers as u64;+ let bulk_bytes = (bulk_mb as u64).saturating_mul(1 << 20);+ let filesystem_headroom = MIN_FILESYSTEM_HEADROOM+ .max(available_bytes / 2)+ .max(JOURNAL_FILESYSTEM_HEADROOM.saturating_add(workers.saturating_mul(bulk_bytes)));+ let bytes = MAX_SPOOL_BYTES.min(available_bytes.saturating_sub(filesystem_headroom));++ let descriptor_headroom = MIN_DESCRIPTOR_HEADROOM+ .saturating_add(workers.saturating_mul(DESCRIPTOR_HEADROOM_PER_WORKER))+ .saturating_add(pdf_workers.saturating_mul(DESCRIPTOR_HEADROOM_PER_WORKER));+ let handles = descriptor_limit+ .zip(open_descriptors)+ .map(|(limit, open)| {+ let live_cap = limit.saturating_sub(open.saturating_add(descriptor_headroom));+ MAX_SPOOL_HANDLES.min(live_cap)+ })+ .unwrap_or(0);++ ExtractionSpoolCapacity {+ bytes,+ handles,+ filesystem_headroom,+ descriptor_headroom,+ }+}++#[cfg(unix)]+fn descriptor_soft_limit() -> Option<u64> {+ let mut limit = libc::rlimit {+ rlim_cur: 0,+ rlim_max: 0,+ };+ if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 {+ return None;+ }+ if limit.rlim_cur == libc::RLIM_INFINITY {+ Some(u64::MAX)+ } else {+ Some(limit.rlim_cur)+ }+}++#[cfg(not(unix))]+fn descriptor_soft_limit() -> Option<u64> {+ None+}++#[cfg(target_os = "linux")]+fn open_descriptor_count() -> Option<u64> {+ // Reading this directory temporarily owns one descriptor, so the count is+ // conservatively one higher than the steady state after this function.+ std::fs::read_dir("/proc/self/fd")+ .ok()+ .and_then(|entries| u64::try_from(entries.count()).ok())+}++#[cfg(not(target_os = "linux"))]+fn open_descriptor_count() -> Option<u64> {+ None+}++struct ExtractionSpoolReservation {+ budget: Arc<ExtractionSpoolBudget>,+ bytes: u64,+ #[cfg(test)]+ cleanup_probe: std::sync::atomic::AtomicBool,+}++impl ExtractionSpoolReservation {+ fn shrink_to(&mut self, bytes: u64) {+ debug_assert!(bytes <= self.bytes);+ let released = self.bytes - bytes;+ self.bytes = bytes;+ let previous = self.budget.used.fetch_sub(released, Ordering::AcqRel);+ debug_assert!(previous >= released);+ }+}++impl Drop for ExtractionSpoolReservation {+ fn drop(&mut self) {+ let previous = self.budget.used.fetch_sub(self.bytes, Ordering::AcqRel);+ debug_assert!(previous >= self.bytes);+ let previous_spools = self.budget.spools.fetch_sub(1, Ordering::AcqRel);+ debug_assert!(previous_spools > 0);+ #[cfg(test)]+ if self.cleanup_probe.load(Ordering::SeqCst) {+ CORRUPTED_REPLAY_RESERVATION_DROPPED.store(true, Ordering::SeqCst);+ }+ }+}++/// A validated worker response bound to one inventory generation.+///+/// `File` is anonymous and the mutex owns its single seek cursor. Phase A and+/// Phase B are sequential today, but cursor ownership remains explicit rather+/// than relying on cloned Unix file descriptors with shared offsets.+pub(crate) struct ExtractionSpool {+ file: Mutex<File>,+ source_size: u64,+ source_digest: String,+ bytes: u64,+ artifact_digest: u128,+ _reservation: ExtractionSpoolReservation,+}++impl ExtractionSpool {+ 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)+ }++ fn replay_with_gate(+ self,+ source_size: u64,+ 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+ // 32 MiB response bound by the general autoindex worker count.+ let _permit = gate.acquire();+ let ExtractionSpool {+ file,+ source_size: expected_size,+ source_digest: expected_digest,+ bytes,+ artifact_digest: expected_artifact_digest,+ _reservation: reservation,+ } = self;+ let budget = Arc::clone(&reservation.budget);+ let decoded = (|| -> Result<WorkerResponse> {+ anyhow::ensure!(+ source_size == expected_size && source_digest == expected_digest,+ "PDF extraction spool belongs to a different source generation; retry extraction"+ );+ let mut file = file+ .into_inner()+ .map_err(|_| anyhow!("PDF extraction spool lock was poisoned"))?;+ #[cfg(test)]+ if CORRUPT_REPLAY_SOURCE_SIZE+ .compare_exchange(source_size, u64::MAX, Ordering::SeqCst, Ordering::SeqCst)+ .is_ok()+ {+ reservation.cleanup_probe.store(true, Ordering::SeqCst);+ file.set_len(8)+ .context("inject PDF extraction spool truncation")?;+ }+ let actual_bytes = file+ .metadata()+ .context("measure PDF extraction spool before replay")?+ .len();+ anyhow::ensure!(+ actual_bytes == bytes,+ "PDF extraction spool length changed (expected {}, found {}); retry extraction",+ bytes,+ actual_bytes+ );+ let actual_digest = artifact_digest(&mut file, bytes)?;+ anyhow::ensure!(+ actual_digest == expected_artifact_digest,+ "PDF extraction spool content changed; retry extraction"+ );+ file.rewind().context("rewind PDF extraction spool")?;+ let response: WorkerResponse = serde_json::from_reader(BufReader::new(&mut file))+ .context("PDF extraction spool is malformed or truncated; retry extraction")?;+ validate_response_identity(&response)?;+ Ok(response)+ })();+ // The optional artifact and its reservation are gone before `deliver`+ // can expand records into the unbounded correctness-critical stage.+ // Replay is deliberately one-shot.+ drop(reservation);+ match decoded {+ Ok(response) => {+ budget.replay_verified.fetch_add(1, Ordering::Relaxed);+ Ok(deliver(response, sink))+ }+ Err(error) => {+ budget+ .replay_integrity_failures+ .fetch_add(1, Ordering::Relaxed);+ Err(error)+ }+ }+ }+}++fn deliver(response: WorkerResponse, sink: Sink) -> ExtractStats {let mut stats = ExtractStats::default();for record in response.records {stats.records += 1;@@ -37,7 +852,7 @@ pub fn extract(path: &Path, sink: Sink) -> Result<ExtractStats> {break;}}- Ok(stats)+ stats}#[derive(Debug, Serialize, Deserialize)]@@ -186,6 +1001,11 @@ fn spawn_worker(path: &Path) -> Result<WorkerResponse> {path.display())})?;+ validate_response_identity(&response)?;+ Ok(response)+}++fn validate_response_identity(response: &WorkerResponse) -> Result<()> {if response.schema != 1 {return Err(anyhow!("PDF parser returned unsupported extraction schema {}; update parent and worker together",@@ -205,7 +1025,7 @@ fn spawn_worker(path: &Path) -> Result<WorkerResponse> {pdf_oxide::VERSION, response.parser));}- Ok(response)+ Ok(())}static WORKER_TIMEOUT_SECS: AtomicU64 = AtomicU64::new(120);@@ -448,6 +1268,17 @@ struct WorkerGate {}impl WorkerGate {+ /// `limit` is the width the resource policy decided+ /// (`crate::resources::plan`), already range-checked at the CLI — it is+ /// taken as given, not re-clamped against a second opinion. Only zero is+ /// corrected, because a gate of width 0 parks every parser forever.+ fn new(limit: usize) -> Self {+ Self {+ state: Mutex::new((0, limit.max(1))),+ ready: Condvar::new(),+ }+ }+fn set_limit(&self, limit: usize) {self.state.lock().expect("PDF worker gate poisoned").1 = limit;self.ready.notify_all();@@ -475,14 +1306,10 @@ impl Drop for WorkerPermit<'_> {fn worker_gate() -> &'static WorkerGate {static GATE: OnceLock<WorkerGate> = OnceLock::new();- GATE.get_or_init(|| WorkerGate {- state: Mutex::new((- 0,- // 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(),+ GATE.get_or_init(|| {+ // Default only: `configure_workers` overwrites this with the run's+ // plan (`crate::resources::plan`) before any extraction starts.+ WorkerGate::new(xerj_common::resource::cores().min(crate::resources::MAX_PDF_WORKERS))})}@@ -541,10 +1368,19 @@ fn validate_text_quality(text: &str) -> Result<()> {#[cfg(test)]mod tests {- use super::{extract_in_process, normalize_legacy_symbol_glyphs, validate_text_quality};+ use super::{+ containment_description, derive_spool_capacity, extract_in_process,+ normalize_legacy_symbol_glyphs, spool_response, try_spool_response, validate_text_quality,+ WorkerResponse, JOURNAL_FILESYSTEM_HEADROOM, MAX_SPOOL_BYTES, MAX_SPOOL_HANDLES,+ MAX_WORKER_OUTPUT, MIN_DESCRIPTOR_HEADROOM, MIN_FILESYSTEM_HEADROOM,+ };use crate::infer::{infer_fields, FieldAcc};use serde_json::Value;use std::collections::HashMap;+ use std::io::{Read, Seek, Write};+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::sync::{Arc, Barrier};+ use std::time::Duration;fn write_prose_pdf(path: &std::path::Path) {let prose = "Quarterly revenue increased because subscription demand remained strong. \@@ -643,4 +1479,638 @@ mod tests {Some(Value::String(_))));}++ fn response(records: Vec<crate::extract::RawRecord>) -> WorkerResponse {+ WorkerResponse {+ schema: 1,+ extractor: format!("xerj-autoindex/{}", env!("CARGO_PKG_VERSION")),+ parser: format!("pdf_oxide/{}", pdf_oxide::VERSION),+ containment: containment_description().to_string(),+ records,+ }+ }++ #[test]+ fn anonymous_spool_replays_exact_records_and_rejects_another_generation() {+ let source = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let path = source.path().join("quarterly-report.pdf");+ write_prose_pdf(&path);+ let expected = extract_in_process(&path).unwrap();+ let budget = super::ExtractionSpoolBudget::new(2 * super::MAX_WORKER_OUTPUT as u64, 2);+ let spool = spool_response(+ state.path(),+ 123,+ "axf2-generation-a",+ &response(expected.clone()),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap();+ let wrong_generation = spool_response(+ state.path(),+ 123,+ "axf2-generation-a",+ &response(expected.clone()),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap();++ // The artifact exists only as an open handle; it adds no recoverable+ // path or stale-cache state under the journal directory.+ assert_eq!(std::fs::read_dir(state.path()).unwrap().count(), 0);++ let mut replayed = Vec::new();+ let stats = spool+ .replay(123, "axf2-generation-a", &mut |record| {+ replayed.push(record);+ true+ })+ .unwrap();+ assert_eq!(stats.records as usize, expected.len());+ assert_eq!(+ serde_json::to_value(&replayed).unwrap(),+ serde_json::to_value(&expected).unwrap()+ );++ let error = wrong_generation+ .replay(123, "axf2-generation-b", &mut |_| true)+ .unwrap_err();+ assert!(error.to_string().contains("different source generation"));+ }++ #[test]+ fn spool_replay_early_stop_matches_direct_delivery() {+ let state = tempfile::tempdir().unwrap();+ let records: Vec<_> = (0..5)+ .map(|index| crate::extract::RawRecord {+ fields: serde_json::Map::from_iter([(+ "ordinal".into(),+ serde_json::Value::from(index),+ )]),+ locator: format!("p1-s{index}"),+ group: None,+ origin: FieldOrigin::Extractor,+ })+ .collect();+ let expected = response(records.clone());+ let mut direct = Vec::new();+ let direct_stats = super::deliver(expected, &mut |record| {+ direct.push(record);+ direct.len() < 3+ });++ let budget = super::ExtractionSpoolBudget::new(super::MAX_WORKER_OUTPUT as u64, 1);+ let spool = spool_response(+ state.path(),+ 7,+ "digest",+ &response(records),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap();+ let mut replayed = Vec::new();+ let replay_stats = spool+ .replay(7, "digest", &mut |record| {+ assert_eq!(budget.used.load(Ordering::Acquire), 0);+ assert_eq!(budget.spools.load(Ordering::Acquire), 0);+ replayed.push(record);+ replayed.len() < 3+ })+ .unwrap();++ assert_eq!(replay_stats.records, direct_stats.records);+ assert_eq!(+ serde_json::to_value(replayed).unwrap(),+ serde_json::to_value(direct).unwrap()+ );+ }++ #[test]+ fn spool_budget_accepts_exact_limit_and_rejects_limit_plus_one() {+ let budget = super::ExtractionSpoolBudget::new(1024, 2);+ let exact = budget.try_reserve(1024).expect("exact limit must fit");+ assert!(budget.try_reserve(1).is_err());+ drop(exact);+ assert!(budget.try_reserve(1025).is_err());+ assert!(budget.try_reserve(1024).is_ok());++ let rejected = super::ExtractionSpoolBudget::new(0, 1);+ assert!(rejected.try_reserve(1).is_err());+ assert_eq!(+ rejected+ .peak_live_artifacts+ .load(std::sync::atomic::Ordering::Acquire),+ 0,+ "a byte-refused provisional handle is not a live artifact"+ );+ }++ #[test]+ fn fallback_examples_are_exactly_bounded_and_report_truncation() {+ let budget = super::ExtractionSpoolBudget::new(0, 0);+ for index in 0..4 {+ budget.record_fallback_example(+ &format!("report-{index}.pdf"),+ "test_fallback",+ "injected",+ );+ }+ let report = budget.report();+ assert_eq!(report["fallback_examples"].as_array().unwrap().len(), 3);+ assert_eq!(report["fallback_examples_limit"], 3);+ assert_eq!(report["fallback_examples_truncated"], true);+ assert_eq!(report["fallback_examples"][0]["path"], "report-0.pdf");+ assert_eq!(report["fallback_examples"][2]["path"], "report-2.pdf");+ }++ #[test]+ fn failed_worker_protocol_call_is_not_reported_as_a_completed_phase_a_parse() {+ let source = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let missing = source.path().join("missing.pdf");+ let budget = super::ExtractionSpoolBudget::new(super::MAX_WORKER_OUTPUT as u64, 1);+ let error = match super::extract_and_spool(+ &missing,+ state.path(),+ 0,+ "digest",+ &budget,+ &mut |_| true,+ ) {+ Err(error) => error,+ Ok(_) => panic!("a missing PDF cannot produce a worker response"),+ };+ assert!(!format!("{error:#}").is_empty());+ assert_eq!(budget.report()["phase_a_pdf_parser_calls"], 0);+ assert_eq!(budget.report()["reservations_started"], 0);+ }++ #[test]+ fn spool_handle_cap_retains_more_than_twelve_small_artifacts() {+ let budget = super::ExtractionSpoolBudget::new(MAX_SPOOL_BYTES, MAX_SPOOL_HANDLES);+ let mut retained = Vec::new();+ for _ in 0..20 {+ let mut reservation = budget.try_reserve(MAX_WORKER_OUTPUT as u64).unwrap();+ reservation.shrink_to(1 << 20);+ retained.push(reservation);+ }+ assert_eq!(budget.spools.load(Ordering::Acquire), 20);+ assert_eq!(budget.used.load(Ordering::Acquire), 20 << 20);+ drop(retained);+ assert_eq!(budget.spools.load(Ordering::Acquire), 0);+ }++ #[test]+ fn many_small_artifacts_plus_four_transient_reservations_fit_384_mib() {+ const ARTIFACTS: u64 = 360;+ const EXACT_ARTIFACT_BYTES: u64 = 220 << 20;+ let budget = super::ExtractionSpoolBudget::new(MAX_SPOOL_BYTES, MAX_SPOOL_HANDLES);+ let base = EXACT_ARTIFACT_BYTES / ARTIFACTS;+ let remainder = EXACT_ARTIFACT_BYTES % ARTIFACTS;+ let mut retained = Vec::new();+ for index in 0..ARTIFACTS {+ let mut reservation = budget.try_reserve(MAX_WORKER_OUTPUT as u64).unwrap();+ reservation.shrink_to(base + u64::from(index < remainder));+ retained.push(reservation);+ }+ let transient: Vec<_> = (0..4)+ .map(|_| budget.try_reserve(MAX_WORKER_OUTPUT as u64).unwrap())+ .collect();+ assert_eq!(+ budget.used.load(Ordering::Acquire),+ EXACT_ARTIFACT_BYTES + 4 * MAX_WORKER_OUTPUT as u64+ );+ assert!(budget.used.load(Ordering::Acquire) < MAX_SPOOL_BYTES);+ drop(transient);+ drop(retained);+ }++ #[test]+ fn shared_capacity_preserves_disk_and_descriptor_headroom() {+ let capacity = derive_spool_capacity(8 << 30, Some(4096), Some(32), 8, 4, 24);+ assert_eq!(capacity.bytes, MAX_SPOOL_BYTES);+ assert_eq!(capacity.handles, MAX_SPOOL_HANDLES);+ assert_eq!(capacity.filesystem_headroom, 4 << 30);+ assert_eq!(+ capacity.descriptor_headroom,+ MIN_DESCRIPTOR_HEADROOM + 8 * 4 + 4 * 4+ );++ let constrained = derive_spool_capacity(1536 << 20, Some(512), Some(32), 8, 4, 24);+ assert_eq!(constrained.filesystem_headroom, MIN_FILESYSTEM_HEADROOM);+ assert_eq!(constrained.bytes, 0);+ assert_eq!(+ constrained.handles,+ 512 - 32 - (MIN_DESCRIPTOR_HEADROOM + 8 * 4 + 4 * 4)+ );+ }++ #[test]+ fn shared_capacity_refuses_low_disk_before_staging_headroom_is_spent() {+ let just_too_small = MIN_FILESYSTEM_HEADROOM + MAX_WORKER_OUTPUT as u64 - 1;+ let capacity = derive_spool_capacity(just_too_small, Some(4096), Some(16), 8, 4, 24);+ assert!(capacity.bytes < MAX_WORKER_OUTPUT as u64);++ let exact = derive_spool_capacity(+ MIN_FILESYSTEM_HEADROOM + MAX_WORKER_OUTPUT as u64,+ Some(4096),+ Some(16),+ 8,+ 4,+ 24,+ );+ assert_eq!(exact.bytes, MAX_WORKER_OUTPUT as u64);++ let worker_bound = derive_spool_capacity(8 << 30, Some(4096), Some(16), 200, 4, 24);+ assert_eq!(+ worker_bound.filesystem_headroom,+ JOURNAL_FILESYSTEM_HEADROOM + 200 * (24 << 20)+ );+ }++ #[test]+ fn shared_capacity_refuses_low_or_unmeasurable_descriptor_capacity() {+ let low_limit = derive_spool_capacity(8 << 30, Some(128), Some(16), 8, 4, 24);+ assert_eq!(low_limit.handles, 0);++ let unknown_limit = derive_spool_capacity(8 << 30, None, Some(16), 8, 4, 24);+ assert_eq!(unknown_limit.handles, 0);++ let unknown_usage = derive_spool_capacity(8 << 30, Some(4096), None, 8, 4, 24);+ assert_eq!(unknown_usage.handles, 0);+ }++ #[test]+ fn live_admission_uses_injected_disk_and_descriptor_probe_values() {+ let state = tempfile::tempdir().unwrap();+ let write_probe = |name: &str, value: u64| {+ std::fs::write(+ state+ .path()+ .join(format!(".autoindex-test-pdf-spool-{name}")),+ value.to_string(),+ )+ .unwrap();+ };+ write_probe("available-bytes", 16 << 30);+ write_probe("fd-limit", 4096);+ write_probe("fd-open", 16);+ let (budget, warning) = super::ExtractionSpoolBudget::for_state_dir(state.path(), 8, 4, 24);+ assert!(warning.is_none());++ write_probe(+ "available-bytes",+ MIN_FILESYSTEM_HEADROOM + MAX_WORKER_OUTPUT as u64 - 1,+ );+ assert_eq!(+ budget.try_reserve(MAX_WORKER_OUTPUT as u64).err().unwrap(),+ "filesystem_admission_floor"+ );++ write_probe("available-bytes", 16 << 30);+ write_probe("fd-limit", 128);+ write_probe("fd-open", 16);+ assert_eq!(+ budget.try_reserve(MAX_WORKER_OUTPUT as u64).err().unwrap(),+ "descriptor_admission_floor"+ );+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn low_rlimit_subprocess_disables_optional_spooling() {+ const CHILD: &str = "XERJ_TEST_LOW_RLIMIT_PDF_SPOOL_CHILD";+ if std::env::var_os(CHILD).is_some() {+ let mut limit = libc::rlimit {+ rlim_cur: 0,+ rlim_max: 0,+ };+ assert_eq!(+ unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) },+ 0+ );+ limit.rlim_cur = limit.rlim_max.min(96);+ assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0);+ let state = tempfile::tempdir().unwrap();+ std::fs::write(+ state+ .path()+ .join(".autoindex-test-pdf-spool-available-bytes"),+ (16_u64 << 30).to_string(),+ )+ .unwrap();+ let (budget, _) = super::ExtractionSpoolBudget::for_state_dir(state.path(), 8, 4, 24);+ assert_eq!(budget.report()["capacity_status"], "disabled");+ assert_eq!(budget.report()["capacity_reason"], "descriptor_headroom");+ return;+ }+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "extract::pdf::tests::low_rlimit_subprocess_disables_optional_spooling",+ "--nocapture",+ ])+ .env(CHILD, "1")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "low-RLIMIT child failed:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );+ }++ #[test]+ fn multi_megabyte_spool_replays_with_exact_integrity() {+ const BODY_BYTES: usize = 2 * 1024 * 1024;+ let state = tempfile::tempdir().unwrap();+ let body = "quarterly-results ".repeat(BODY_BYTES / "quarterly-results ".len());+ let record = crate::extract::RawRecord {+ fields: serde_json::Map::from_iter([("body".into(), body.clone().into())]),+ locator: "p1-s0".into(),+ group: None,+ origin: FieldOrigin::Extractor,+ };+ let budget = super::ExtractionSpoolBudget::new(super::MAX_WORKER_OUTPUT as u64, 1);+ let spool = spool_response(+ state.path(),+ 7,+ "digest",+ &response(vec![record]),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap();+ assert!(spool.bytes >= BODY_BYTES as u64);+ assert!(spool.bytes < super::MAX_WORKER_OUTPUT as u64);++ let mut replayed_body = None;+ let stats = spool+ .replay(7, "digest", &mut |record| {+ replayed_body = record.fields["body"].as_str().map(ToOwned::to_owned);+ true+ })+ .unwrap();+ assert_eq!(stats.records, 1);+ assert_eq!(replayed_body.as_deref(), Some(body.as_str()));+ }++ #[test]+ fn spool_replay_verifies_exact_length_and_digest_before_decode() {+ let source = tempfile::tempdir().unwrap();+ let state = tempfile::tempdir().unwrap();+ let path = source.path().join("quarterly-report.pdf");+ write_prose_pdf(&path);+ let records = extract_in_process(&path).unwrap();++ let budget = super::ExtractionSpoolBudget::new(3 * super::MAX_WORKER_OUTPUT as u64, 3);+ let truncated = spool_response(+ state.path(),+ 7,+ "digest",+ &response(records.clone()),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap();+ truncated.file.lock().unwrap().set_len(8).unwrap();+ let error = truncated.replay(7, "digest", &mut |_| true).unwrap_err();+ assert!(format!("{error:#}").contains("length changed"));++ let appended = spool_response(+ state.path(),+ 7,+ "digest",+ &response(records.clone()),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap();+ {+ let mut file = appended.file.lock().unwrap();+ file.seek(std::io::SeekFrom::End(0)).unwrap();+ file.write_all(b" ").unwrap();+ file.flush().unwrap();+ }+ let error = appended.replay(7, "digest", &mut |_| true).unwrap_err();+ assert!(format!("{error:#}").contains("length changed"));++ let mutated = spool_response(+ state.path(),+ 7,+ "digest",+ &response(records.clone()),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap();+ {+ let mut file = mutated.file.lock().unwrap();+ file.rewind().unwrap();+ let mut first = [0u8; 1];+ file.read_exact(&mut first).unwrap();+ file.rewind().unwrap();+ file.write_all(if first == *b"{" { b"[" } else { b"{" })+ .unwrap();+ file.flush().unwrap();+ }+ assert_eq!(+ mutated.file.lock().unwrap().metadata().unwrap().len(),+ mutated.bytes+ );+ let error = mutated.replay(7, "digest", &mut |_| true).unwrap_err();+ assert!(error.to_string().contains("content changed"));+ }++ fn rewrite_spool_and_reseal(+ spool: &mut super::ExtractionSpool,+ rewrite: impl FnOnce(&mut Vec<u8>),+ ) {+ let mut file = spool.file.lock().unwrap();+ file.rewind().unwrap();+ let mut bytes = Vec::new();+ file.read_to_end(&mut bytes).unwrap();+ rewrite(&mut bytes);+ file.set_len(0).unwrap();+ file.rewind().unwrap();+ file.write_all(&bytes).unwrap();+ file.flush().unwrap();+ spool.bytes = bytes.len() as u64;+ spool.artifact_digest = super::artifact_digest(&mut file, spool.bytes).unwrap();+ file.rewind().unwrap();+ }++ #[test]+ fn replay_rejects_malformed_json_after_physical_integrity_passes() {+ let state = tempfile::tempdir().unwrap();+ let budget = super::ExtractionSpoolBudget::new(super::MAX_WORKER_OUTPUT as u64, 1);+ let mut spool = spool_response(+ state.path(),+ 7,+ "digest",+ &response(Vec::new()),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap();+ rewrite_spool_and_reseal(&mut spool, |bytes| bytes[0] = b'[');++ let error = spool.replay(7, "digest", &mut |_| true).unwrap_err();+ assert!(+ format!("{error:#}").contains("malformed or truncated"),+ "{error:#}"+ );+ assert_eq!(budget.report()["replay_integrity_failures"], 1);+ }++ #[test]+ fn replay_rejects_worker_protocol_mismatch_after_integrity_passes() {+ let state = tempfile::tempdir().unwrap();+ let budget = super::ExtractionSpoolBudget::new(super::MAX_WORKER_OUTPUT as u64, 1);+ let mut spool = spool_response(+ state.path(),+ 7,+ "digest",+ &response(Vec::new()),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap();+ rewrite_spool_and_reseal(&mut spool, |bytes| {+ let needle = b"xerj-autoindex/";+ let offset = bytes+ .windows(needle.len())+ .position(|window| window == needle)+ .unwrap();+ bytes[offset] = b'X';+ });++ let error = spool.replay(7, "digest", &mut |_| true).unwrap_err();+ assert!(+ format!("{error:#}").contains("extractor version mismatch"),+ "{error:#}"+ );+ assert_eq!(budget.report()["replay_integrity_failures"], 1);+ }++ #[test]+ fn concurrent_spool_replay_never_exceeds_configured_pdf_gate() {+ const REPLAYS: usize = 8;+ const LIMIT: usize = 2;+ let state = tempfile::tempdir().unwrap();+ let budget = super::ExtractionSpoolBudget::new(+ REPLAYS as u64 * super::MAX_WORKER_OUTPUT as u64,+ REPLAYS as u64,+ );+ let records = vec![crate::extract::RawRecord {+ fields: serde_json::Map::new(),+ locator: "page:1".into(),+ group: None,+ origin: FieldOrigin::Extractor,+ }];+ let spools: Vec<_> = (0..REPLAYS)+ .map(|_| {+ spool_response(+ state.path(),+ 7,+ "digest",+ &response(records.clone()),+ budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).unwrap(),+ )+ .unwrap()+ })+ .collect();+ let gate = Arc::new(super::WorkerGate::new(LIMIT));+ let start = Arc::new(Barrier::new(REPLAYS));+ let active = Arc::new(AtomicUsize::new(0));+ let maximum = Arc::new(AtomicUsize::new(0));++ std::thread::scope(|scope| {+ for spool in spools {+ let gate = Arc::clone(&gate);+ let start = Arc::clone(&start);+ let active = Arc::clone(&active);+ let maximum = Arc::clone(&maximum);+ scope.spawn(move || {+ start.wait();+ spool+ .replay_with_gate(+ 7,+ "digest",+ &mut |_| {+ let now = active.fetch_add(1, Ordering::SeqCst) + 1;+ maximum.fetch_max(now, Ordering::SeqCst);+ std::thread::sleep(Duration::from_millis(20));+ active.fetch_sub(1, Ordering::SeqCst);+ true+ },+ &gate,+ false,+ )+ .unwrap();+ });+ }+ });+ assert_eq!(maximum.load(Ordering::SeqCst), LIMIT);+ }++ #[test]+ fn spool_budget_is_atomic_and_refunded_on_physical_drop() {+ let budget = super::ExtractionSpoolBudget::new(100, 2);+ let mut first = budget.try_reserve(80).unwrap();+ assert!(budget.try_reserve(21).is_err());+ first.shrink_to(40);+ let second = budget.try_reserve(60).unwrap();+ assert!(budget.try_reserve(1).is_err());+ drop(second);+ assert!(budget.try_reserve(60).is_ok());+ drop(first);++ let count_budget = super::ExtractionSpoolBudget::new(1_000, 1);+ let only = count_budget.try_reserve(1).unwrap();+ assert!(count_budget.try_reserve(1).is_err());+ drop(only);+ assert!(count_budget.try_reserve(1).is_ok());+ }++ #[test]+ fn concurrent_reservations_report_exact_peak_live_artifacts() {+ const RESERVATIONS: usize = 32;+ let budget = super::ExtractionSpoolBudget::new(RESERVATIONS as u64, RESERVATIONS as u64);+ let barrier = Arc::new(Barrier::new(RESERVATIONS + 1));+ std::thread::scope(|scope| {+ for _ in 0..RESERVATIONS {+ let budget = Arc::clone(&budget);+ let barrier = Arc::clone(&barrier);+ scope.spawn(move || {+ let reservation = budget.try_reserve(1).unwrap();+ barrier.wait();+ barrier.wait();+ drop(reservation);+ });+ }+ barrier.wait();+ assert_eq!(+ budget.peak_live_artifacts.load(Ordering::Acquire),+ RESERVATIONS as u64+ );+ assert_eq!(budget.spools.load(Ordering::Acquire), RESERVATIONS as u64);+ barrier.wait();+ });+ assert_eq!(budget.spools.load(Ordering::Acquire), 0);+ }++ #[test]+ fn spool_io_failure_preserves_a_clean_fallback_and_refunds_capacity() {+ let state = tempfile::tempdir().unwrap();+ let not_a_directory = state.path().join("regular-file");+ std::fs::write(¬_a_directory, b"not a directory").unwrap();+ let budget = super::ExtractionSpoolBudget::new(super::MAX_WORKER_OUTPUT as u64, 1);+ let response = response(Vec::new());++ let (spool, fallback) =+ try_spool_response(¬_a_directory, 7, "digest", &budget, &response);+ assert!(spool.is_none());+ let fallback = fallback.unwrap();+ assert_eq!(fallback.category, "artifact_io");+ assert!(fallback.message.contains("could not retain"));+ assert!(fallback.message.contains("anonymous PDF extraction spool"));++ // The failed attempt must not strand either the byte or handle charge.+ assert!(budget.try_reserve(super::MAX_WORKER_OUTPUT as u64).is_ok());+ }}diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex b00e26f8e..1a9b96d93 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -16,6 +16,31 @@ use std::thread;static FAILPOINT_TEST_LOCK: Mutex<()> = Mutex::new(());+#[cfg(unix)]+struct PdfWorkerEnvGuard;++#[cfg(unix)]+impl Drop for PdfWorkerEnvGuard {+ fn drop(&mut self) {+ std::env::remove_var("XERJ_PDF_WORKER_BIN");+ std::env::remove_var("XERJ_TEST_PDF_COUNT");+ }+}++fn inject_pdf_spool_capacity(state_dir: &Path) {+ for (name, value) in [+ ("available-bytes", 16_u64 << 30),+ ("fd-limit", 4096),+ ("fd-open", 16),+ ] {+ fs::write(+ state_dir.join(format!(".autoindex-test-pdf-spool-{name}")),+ value.to_string(),+ )+ .unwrap();+ }+}+#[derive(Default)]struct MockState {docs: HashMap<String, Value>,@@ -1295,3 +1320,394 @@ fn the_resource_plan_is_announced_on_the_progress_surface_with_the_width_it_got(assert_eq!(report["scan_workers"], serde_json::json!(installed));assert_eq!(report["workers"], serde_json::json!(3));}++#[cfg(unix)]+#[test]+fn fresh_pdf_is_parsed_once_and_failed_publication_retry_reparses_once() {+ 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\nfake bytes consumed by the isolated test worker\n",+ )+ .unwrap();+ fs::copy(&pdf, corpus.path().join("quarterly-report-copy.pdf")).unwrap();++ let count = tools.path().join("worker-count");+ let worker = tools.path().join("pdf-worker");+ let worker_script = String::from_utf8(+ br#"#!/bin/sh+printf '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}]}'+"#+ .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 endpoint = MockEndpoint::start(1);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ 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"));+ assert_eq!(+ fs::read_to_string(&count).unwrap().lines().count(),+ 1,+ "Phase A's extraction must be replayed in Phase B, not parsed again"+ );+ assert_eq!(file_done_count(state_dir.path()), 0);++ // The process-local spool is intentionally not journal state. A retry has+ // a frozen plan, performs exactly one fresh extraction in Phase B, and+ // commits only after the backend accepts it.+ assert_eq!(run_index(config).unwrap(), 0);+ assert_eq!(fs::read_to_string(&count).unwrap().lines().count(), 2);+ assert_eq!(file_done_count(state_dir.path()), 1);+ assert_eq!(endpoint.state.lock().unwrap().docs.len(), 1);+}++#[cfg(unix)]+#[test]+fn refused_pdf_spool_reparses_and_reports_fallback_without_weakening_publication() {+ use std::os::unix::fs::PermissionsExt;++ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let tools = tempfile::tempdir().unwrap();+ fs::write(+ corpus.path().join("quarterly-report.pdf"),+ b"%PDF-1.4\nfake bytes consumed by the isolated test worker\n",+ )+ .unwrap();+ fs::write(+ state_dir+ .path()+ .join(".autoindex-test-pdf-spool-available-bytes"),+ ((4_u64 << 30) + (32 << 20) - 1).to_string(),+ )+ .unwrap();+ fs::write(+ state_dir.path().join(".autoindex-test-pdf-spool-fd-limit"),+ "4096",+ )+ .unwrap();+ fs::write(+ state_dir.path().join(".autoindex-test-pdf-spool-fd-open"),+ "16",+ )+ .unwrap();++ let count = tools.path().join("worker-count");+ let worker = tools.path().join("pdf-worker");+ let worker_script = String::from_utf8(+ br#"#!/bin/sh+printf '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}]}'+"#+ .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 endpoint = MockEndpoint::start(0);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ 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!(fs::read_to_string(&count).unwrap().lines().count(), 2);+ assert_eq!(file_done_count(state_dir.path()), 1);+ assert_eq!(endpoint.state.lock().unwrap().docs.len(), 1);+ let reuse = report.unwrap()["pdf_extraction_reuse"].clone();+ assert_eq!(reuse["reservations_started"], 0);+ assert_eq!(reuse["capacity_fallbacks"], 1);+ 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["capacity_status"], "disabled");+ assert_eq!(+ reuse["fallback_examples"][0]["path"],+ "quarterly-report.pdf"+ );+}++#[cfg(unix)]+#[test]+fn refused_spool_does_not_pay_a_second_phase_a_source_hash() {+ use std::os::unix::fs::PermissionsExt;++ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ 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(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);++ 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}]}'+"#+ .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();+ 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);+ assert!(scan.pdf_spool.is_none());+ assert_eq!(scan.pdf_spool_fallbacks.len(), 1);+ for fallback in &scan.pdf_spool_fallbacks {+ budget.record_fallback_example(+ "quarterly-report.pdf",+ fallback.category,+ &fallback.message,+ );+ }+ let report = budget.report();+ assert_eq!(report["artifacts_created"], 0);+ assert_eq!(report["phase_b_eligible_artifacts"], 0);+ assert_eq!(report["artifacts_discarded_before_replay"], 0);+ assert_eq!(report["fallback_categories"]["artifact_count_ceiling"], 1);+ assert!(report["fallback_categories"]+ .get("source_generation_changed")+ .is_none());+}++#[cfg(unix)]+#[test]+fn verified_but_junk_pdf_spool_is_created_then_discarded_not_eligible() {+ 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("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,+ }])+ .unwrap()+ .digests+ .remove(0);+ let worker = tools.path().join("pdf-worker");+ let script = format!(+ "#!/bin/sh\nprintf '%s' '{{\"schema\":1,\"extractor\":\"xerj-autoindex/{}\",\"parser\":\"pdf_oxide/0.3.75\",\"containment\":\"test worker\",\"records\":[]}}'\n",+ env!("CARGO_PKG_VERSION")+ );+ fs::write(&worker, script).unwrap();+ fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();+ 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);+ 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());+ 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);+}++#[cfg(unix)]+#[test]+fn multi_pdf_run_reuses_every_artifact_and_reports_exact_success_counters() {+ 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();+ const PDFS: usize = 6;+ for index in 0..PDFS {+ fs::write(+ corpus.path().join(format!("quarterly-report-{index}.pdf")),+ format!("%PDF-1.4\nunique isolated worker input {index}\n"),+ )+ .unwrap();+ }++ let count = tools.path().join("worker-count");+ let worker = tools.path().join("pdf-worker");+ let worker_script = String::from_utf8(+ br#"#!/bin/sh+printf '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}]}'+"#+ .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 endpoint = MockEndpoint::start(0);+ let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ config.workers = 8;+ config.pdf_workers = 2;+ 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!(+ fs::read_to_string(&count).unwrap().lines().count(),+ PDFS,+ "each unique PDF must be parsed once in Phase A and replayed in Phase B"+ );+ assert_eq!(endpoint.state.lock().unwrap().docs.len(), PDFS);+ let reuse = report.unwrap()["pdf_extraction_reuse"].clone();+ assert_eq!(reuse["reservations_started"], PDFS);+ assert_eq!(+ reuse["cumulative_reserved_bytes"],+ PDFS as u64 * (32_u64 << 20)+ );+ assert_eq!(reuse["artifacts_created"], PDFS);+ assert_eq!(reuse["artifacts_not_created"], 0);+ assert_eq!(reuse["phase_b_eligible_artifacts"], PDFS);+ assert_eq!(reuse["artifacts_discarded_before_replay"], 0);+ assert!(reuse["exact_artifact_bytes"].as_u64().unwrap() > 0);+ assert_eq!(reuse["current_retained_or_reserved_bytes"], 0);+ 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["capacity_fallbacks"], 0);+ assert_eq!(reuse["io_fallbacks"], 0);+ assert_eq!(reuse["replay_verified"], PDFS);+ assert_eq!(reuse["replay_integrity_failures"], 0);+ assert_eq!(reuse["phase_b_pdf_parses"], 0);+ assert_eq!(reuse["fallback_examples"].as_array().unwrap().len(), 0);+ assert_eq!(reuse["fallback_examples_truncated"], false);+ assert_eq!(reuse["fallback_categories"].as_object().unwrap().len(), 0);+}++#[cfg(unix)]+#[test]+fn corrupted_pdf_replay_reparses_without_blaming_the_source_or_backend() {+ 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("report.pdf");+ fs::write(&pdf, b"%PDF-1.4\ntest worker input\n").unwrap();+ let worker = tools.path().join("pdf-worker");+ let count = tools.path().join("worker-count");+ let worker_script = String::from_utf8(+ br#"#!/bin/sh+printf '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}]}'+"#+ .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 endpoint = MockEndpoint::start(0);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ 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();+ assert_eq!(code, 0);+ assert_eq!(fs::read_to_string(&count).unwrap().lines().count(), 2);+ assert_eq!(endpoint.state.lock().unwrap().docs.len(), 1);+ assert_eq!(file_done_count(state_dir.path()), 1);+ assert!(crate::extract::pdf::corrupted_replay_reservation_was_dropped());+ 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["phase_b_pdf_parses"], 1);+ assert_eq!(reuse["current_live_artifacts"], 0);+ assert_eq!(reuse["current_retained_or_reserved_bytes"], 0);+ assert_eq!(reuse["fallback_categories"]["replay_verification"], 1);+ assert_eq!(+ reuse["fallback_examples"][0]["category"],+ "replay_verification"+ );+}++#[test]+fn junk_scan_drops_its_spool_before_indexable_spools_are_retained() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::sync::Arc;++ struct DropProbe(Arc<AtomicUsize>);+ impl Drop for DropProbe {+ fn drop(&mut self) {+ self.0.fetch_add(1, Ordering::SeqCst);+ }+ }++ let drops = Arc::new(AtomicUsize::new(0));+ let budget = crate::extract::pdf::ExtractionSpoolBudget::new(1, 1);+ let mut junk = Some(DropProbe(Arc::clone(&drops)));+ assert!(take_pdf_spool_if_indexable(&mut junk, true, &budget).is_none());+ assert!(junk.is_none());+ assert_eq!(drops.load(Ordering::SeqCst), 1);++ let mut indexable = Some(DropProbe(Arc::clone(&drops)));+ let retained = take_pdf_spool_if_indexable(&mut indexable, false, &budget);+ assert!(retained.is_some());+ assert_eq!(drops.load(Ordering::SeqCst), 1);+ let report = budget.report();+ assert_eq!(report["artifacts_discarded_before_replay"], 1);+ assert_eq!(+ report["phase_b_eligible_artifacts"], 0,+ "eligibility is recorded only after the final todo set is known"+ );+ drop(retained);+ assert_eq!(drops.load(Ordering::SeqCst), 2);+}diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex db02d51d0..c0a4d0366 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -183,6 +183,10 @@ struct FileScan {sniffed: Option<Sniffed>,sketches: Vec<GroupSketch>,junk: Option<(String, String)>, // (status, reason)+ /// Run-local PDF extraction produced during sampling. This is consumed by+ /// Phase B only when it is bound to the same full-content generation.+ pdf_spool: Option<extract::pdf::ExtractionSpool>,+ pdf_spool_fallbacks: Vec<extract::pdf::SpoolFallback>,}/// One sampled group within a file: every field it produced, plus the names@@ -195,11 +199,37 @@ struct GroupSketch {records: u64,}-fn scan_file(path: &Path, size: u64, sample: usize, max_file_gb: u64) -> FileScan {+fn take_pdf_spool_if_indexable<T>(+ spool: &mut Option<T>,+ is_junk: bool,+ budget: &extract::pdf::ExtractionSpoolBudget,+) -> Option<T> {+ if is_junk {+ if spool.is_some() {+ budget.record_discarded_before_replay();+ }+ spool.take();+ None+ } else {+ spool.take()+ }+}++fn scan_file(+ path: &Path,+ size: u64,+ digest: &str,+ state_dir: &Path,+ pdf_spool_budget: &std::sync::Arc<extract::pdf::ExtractionSpoolBudget>,+ sample: usize,+ max_file_gb: u64,+) -> FileScan {let mut out = FileScan {sniffed: None,sketches: Vec::new(),junk: None,+ pdf_spool: None,+ pdf_spool_fallbacks: Vec::new(),};let sn = match sniff::sniff(path) {Ok(s) => s,@@ -269,7 +299,53 @@ fn scan_file(path: &Path, size: u64, sample: usize, max_file_gb: u64) -> FileSca(entry.1 as usize) < sample}};- match extract::extract(path, &sn, limit, &mut sink) {+ let extraction = if sn.family == Family::Pdf {+ match extract::pdf::extract_and_spool(+ path,+ state_dir,+ size,+ digest,+ pdf_spool_budget,+ &mut sink,+ ) {+ Ok((stats, spool, fallback)) => {+ // The inventory digest was computed before Phase A. Only hand+ // bytes to Phase B when the source still matches that exact+ // generation after the parser has finished reading it.+ // If no reusable artifact exists, avoid a second full-file+ // read: Phase B performs the authoritative generation check+ // immediately before its ordinary reparse.+ if spool.is_none() {+ out.pdf_spool_fallbacks.extend(fallback);+ } else {+ match content::verify(path, size, digest) {+ Ok(()) => {+ out.pdf_spool = spool;+ out.pdf_spool_fallbacks.extend(fallback);+ }+ Err(error) => {+ if spool.is_some() {+ pdf_spool_budget.record_discarded_before_replay();+ }+ pdf_spool_budget.record_source_generation_changed();+ out.pdf_spool_fallbacks.extend(fallback);+ out.pdf_spool_fallbacks.push(extract::pdf::SpoolFallback {+ category: "source_generation_changed",+ message: format!(+ "source generation changed after extraction: {error:#}"+ ),+ });+ }+ }+ }+ Ok(stats)+ }+ Err(error) => Err(error),+ }+ } else {+ extract::extract(path, &sn, limit, &mut sink)+ };+ match extraction {Ok(stats) => {if groups.is_empty() {out.junk = Some((@@ -310,7 +386,10 @@ mod clustering_key_tests {let path = dir.join(name);std::fs::write(&path, body).unwrap();let size = std::fs::metadata(&path).unwrap().len();- scan_file(&path, size, 500, 2)+ // 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)}/// The #178 mechanism, from the extractor to the clustering key: a source@@ -595,6 +674,79 @@ fn compute_scopes(root: &Path, rels: &[String]) -> Vec<String> {.collect()}+/// What phase A produces: the frozen plan, the clusters phase B needs, and+/// the run-local PDF artifacts (index-aligned with `files`) that phase B may+/// replay instead of parsing again. A spool is always optional — every entry+/// may legitimately be `None`.+struct PhaseA {+ plan: Plan,+ clusters: Vec<dataset::Cluster>,+ pdf_spools: Vec<Option<extract::pdf::ExtractionSpool>>,+}++/// 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.+///+/// Reporting goes 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,+) {+ if pdf_spool_budget.is_globally_disabled() {+ return;+ }+ let reasons: Vec<(&str, &extract::pdf::SpoolFallback)> = scans+ .iter()+ .enumerate()+ .flat_map(|(index, scan)| {+ scan.pdf_spool_fallbacks+ .iter()+ .map(move |fallback| (files[index].rel.as_str(), fallback))+ })+ .collect();+ for (path, fallback) in &reasons {+ pdf_spool_budget.record_fallback_example(path, fallback.category, &fallback.message);+ }+ if reasons.is_empty() {+ return;+ }+ if pdf_spool_budget.platform_reuse_is_unavailable() {+ pr.note(+ "phase A: run-local PDF extraction reuse is unavailable on this platform; \+ phase B will use the normal parser",+ );+ return;+ }+ pr.note(&format!(+ "phase A: {} PDF extraction(s) could not retain a bounded run-local artifact; \+ phase B will parse them again safely",+ reasons.len()+ ));+ if let Some(warning) = pdf_spool_capacity_warning {+ pr.note(&format!(" PDF reuse capacity: {warning}"));+ }+ for (path, fallback) in reasons.iter().take(3) {+ pr.note(&format!(+ " PDF reuse fallback for {path}: {}",+ fallback.message+ ));+ }+ if reasons.len() > 3 {+ pr.note(&format!(+ " … and {} more PDF reuse fallback(s)",+ reasons.len() - 3+ ));+ }+}+/// Sniff + sample every file, cluster into datasets, and assemble the plan./// Pure planning: reads the tree, never the server — which is what makes the/// #173/#196 grouping behaviour testable end-to-end without a cluster.@@ -604,24 +756,46 @@ 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>,cfg: &IndexCfg,pr: &Progress,-) -> (Plan, Vec<dataset::Cluster>) {+) -> PhaseA {use rayon::prelude::*;// 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).+ // 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.let scans: Vec<FileScan> = crate::pool::install(|| {files.par_iter()- .map(|f| {+ .zip(digests.par_iter())+ .map(|(f, digest)| {let _in_flight = pr.file(&f.rel, f.size);- scan_file(&f.path, f.size, cfg.sample, cfg.max_file_gb)+ scan_file(+ &f.path,+ f.size,+ digest,+ state_dir,+ pdf_spool_budget,+ cfg.sample,+ cfg.max_file_gb,+ )}).collect()});+ report_pdf_spool_fallbacks(+ files,+ &scans,+ pdf_spool_budget,+ pdf_spool_capacity_warning,+ pr,+ );+let rels: Vec<String> = files.iter().map(|f| f.rel.clone()).collect();let scopes = compute_scopes(root, &rels);// (family, gzip) per file, from the scan's sniff — reused for assignments@@ -632,12 +806,18 @@ fn build_phase_a(.collect();let mut sketches = Vec::new();let mut junk_files = Vec::new();- for (i, sc) in scans.into_iter().enumerate() {+ let mut pdf_spools: Vec<Option<extract::pdf::ExtractionSpool>> =+ (0..files.len()).map(|_| None).collect();+ for (i, mut sc) in scans.into_iter().enumerate() {let family = sc.sniffed.as_ref().map(|s| s.family).unwrap_or(Family::Binary);+ // A file that phase A junks is never indexed, so its artifact is+ // refunded here rather than held to the phase A→B boundary.+ pdf_spools[i] =+ take_pdf_spool_if_indexable(&mut sc.pdf_spool, sc.junk.is_some(), pdf_spool_budget);if let Some((status, reason)) = sc.junk {junk_files.push(JunkFile {file_key: keys[i].clone(),@@ -746,7 +926,11 @@ fn build_phase_a(duplicate_files,alias_paths_indexed: true,};- (plan, clusters)+ PhaseA {+ plan,+ clusters,+ pdf_spools,+ }}// ─── mapping builder ─────────────────────────────────────────────────────@@ -1183,6 +1367,21 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {// ── Phase A: inference (skipped when a frozen plan exists) ──────────let mut clusters_rt: Option<Vec<dataset::Cluster>> = None;+ let mut pdf_spools: Vec<Option<extract::pdf::ExtractionSpool>> =+ (0..files.len()).map(|_| None).collect();+ // Both worker widths come from the one resource policy (#240), and since+ // that policy may set them apart, the spool's headroom is sized for the+ // wider phase: phase-A scan threads are what hold artifact descriptors+ // open, phase-B workers are what hold bulk buffers. Reserving for the+ // larger of the two can only make this optional accelerator hand capacity+ // back — never take headroom the run still needs.+ let (pdf_spool_budget, pdf_spool_capacity_warning) =+ extract::pdf::ExtractionSpoolBudget::for_state_dir(+ &state_dir,+ cfg.workers.max(scan_threads),+ cfg.pdf_workers,+ cfg.bulk_mb,+ );let mut plan: Plan = if let Some(p) = journal.plan.clone() {p} else {@@ -1194,15 +1393,23 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {"phase A: sniffing + sampling {} files with {scan_threads} threads…",files.len()));- let (plan, clusters) = build_phase_a(+ let PhaseA {+ plan,+ clusters,+ pdf_spools: spools,+ } = build_phase_a(&cfg.root,&files,&keys,&digests,duplicate_files.clone(),+ &state_dir,+ &pdf_spool_budget,+ pdf_spool_capacity_warning.as_deref(),&cfg,&pr,);+ pdf_spools = spools;pr.note(&format!("phase A: {} datasets inferred, {} junk/skipped files",plan.datasets.len(),@@ -1389,6 +1596,18 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {// genuinely fresh and skip the delete round trip.cleanup_required.extend(todo.iter().map(|&i| keys[i].clone()));}+ let todo_set: std::collections::HashSet<usize> = todo.iter().copied().collect();+ for (index, spool) in pdf_spools.iter_mut().enumerate() {+ if spool.is_none() {+ continue;+ }+ if todo_set.contains(&index) {+ pdf_spool_budget.record_phase_b_eligible();+ } else {+ pdf_spool_budget.record_discarded_before_replay();+ spool.take();+ }+ }// Every publication, including a fresh one, receives durable intent// before its first bulk. A failed fresh publication therefore skips the// unnecessary delete now but is recognized as pending and cleaned on the@@ -1557,14 +1776,35 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {// Percent and ETA are bytes-based, never file-count-based. The queue is// biggest-first, so a files-done percent races to ~100% and then sits// there for minutes on the one big file still in flight (#241 §5/§6).+ // A replayed PDF still costs its own bytes to stage and send, so a spooled+ // file counts toward the same denominator as a parsed one.let todo_bytes: u64 = todo.iter().map(|&i| files[i].size).sum();+ let n_pdf_spools = todo+ .iter()+ .filter(|&&index| pdf_spools[index].is_some())+ .count();pr.phase("index", n_todo as u64, todo_bytes);pr.note(&format!("phase B: indexing {} files with {} workers → {}",n_todo, cfg.workers, cfg.url));+ if n_pdf_spools > 0 {+ pr.note(&format!(+ "phase B: reusing {n_pdf_spools} run-local PDF extraction(s); these PDFs will not be \+ parsed a second time"+ ));+ }- let queue = Mutex::new(todo);+ // Move each optional artifact into its sole Phase-B job. A replay cannot+ // be retried or retained accidentally after staging begins.+ let queue = Mutex::new(+ todo.into_iter()+ .map(|index| {+ let spool = pdf_spools[index].take();+ (index, spool)+ })+ .collect::<Vec<_>>(),+ );let mut paths_by_key: HashMap<String, Vec<String>> = files.iter().zip(keys.iter())@@ -1589,8 +1829,8 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {for _ in 0..cfg.workers.min(n_todo.max(1)) {scope.spawn(|| {loop {- let i = match queue.lock().unwrap().pop() {- Some(i) => i,+ let (i, pdf_spool) = match queue.lock().unwrap().pop() {+ Some(job) => job,None => break,};let f = &files[i];@@ -1789,8 +2029,53 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {// Demoted one-off config files (#173) index as// documents — their key sets are configuration, not a// schema (see `dataset` module docs).+ //+ // `as_document` deliberately outranks artifact replay.+ // It decides the record *shape*: phase A built this+ // dataset's mapping by re-sampling the file through+ // `extract_as_document`, whereas an artifact replays+ // PDF-parser page records. Replaying here would publish+ // records the frozen plan does not describe. Today no+ // PDF can reach this branch (`demotable_family` is+ // JSON/YAML/XML only), so this is a guard that keeps+ // the precedence right if that set ever widens — the+ // artifact is refunded rather than replayed.let res = if fa.as_document {+ if pdf_spool.is_some() {+ pdf_spool_budget.record_discarded_before_replay();+ }+ drop(pdf_spool);extract::extract_as_document(&f.path, sn.gzip, &mut sink)+ } else if sn.family == Family::Pdf {+ match pdf_spool {+ Some(spool) => {+ match spool.replay(f.size, expected_digest, &mut sink) {+ Ok(stats) => Ok(stats),+ Err(replay_error) => {+ // Replay verifies the complete+ // artifact before `deliver`+ // invokes the sink, so falling+ // back here cannot duplicate a+ // partially staged record stream.+ pdf_spool_budget+ .record_replay_fallback(&f.rel, &replay_error);+ pdf_spool_budget.record_reparse();+ extract::extract(&f.path, &sn, None, &mut sink)+ .with_context(|| {+ format!(+ "reparse {} after run-local PDF artifact \+ verification failed: {replay_error:#}",+ f.rel+ )+ })+ }+ }+ }+ None => {+ pdf_spool_budget.record_reparse();+ extract::extract(&f.path, &sn, None, &mut sink)+ }+ }} else {extract::extract(&f.path, &sn, None, &mut sink)};@@ -2519,6 +2804,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {"bulk_congestion_events": es.bulk_congestion_events(),"resource_notes": cfg.resource_notes,"semantic": !cfg.no_semantic,+ "pdf_extraction_reuse": pdf_spool_budget.report(),});if let Some(g) = &graph_summary {run_doc["graph"] = g.clone();