Skip to content

armgit / xerj

Public Imported from GitHub
0

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

fix(autoindex): compress phase-B stages into unnamed temp files

Cursor Agente8ceefbddf9e
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index 20c6a4b15..983e8209f 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -7465,6 +7465,7 @@ dependencies = [
"xerj-wasm",
"xxhash-rust",
"zip 9.0.5",
+ "zstd",
]
[[package]]
diff --git a/engine/crates/xerj-autoindex/Cargo.toml b/engine/crates/xerj-autoindex/Cargo.toml
index 72c409f26..f2a56aa3a 100644
--- a/engine/crates/xerj-autoindex/Cargo.toml
+++ b/engine/crates/xerj-autoindex/Cargo.toml
@@ -50,6 +50,8 @@ memchr.workspace = true
rayon.workspace = true
libc = "0.2"
tempfile.workspace = true
+# Phase-B per-file stages are zstd-compressed (#2427, `stage.rs`).
+zstd.workspace = true
fs2 = "0.4"
# ES-compat HTTP client. Blocking mode: all of autoindex is synchronous
# (std threads), invoked from the server binary via spawn_blocking.
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 8fbbb8f76..f850db6ad 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -52,6 +52,7 @@ pub mod search;
pub mod sessions;
pub mod sniff;
pub mod source;
+mod stage;
pub mod staleness;
pub mod state;
mod sync;
@@ -64,7 +65,7 @@ use anyhow::{Context, Result};
use serde::Serialize;
use serde_json::{json, Map, Value};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
-use std::io::{BufRead, BufReader, Seek, Write};
+use std::io::{BufRead, Write};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Condvar, Mutex};
@@ -10871,10 +10872,7 @@ fn run_index_report_inner(
// only source that can name a PDF page boundary's
// predecessor (p2-s0 follows the LAST section of page 1).
let mut prev_section: Option<(String, String)> = None;
- let mut staged = match tempfile::Builder::new()
- .prefix(".autoindex-stage-")
- .tempfile_in(&state_dir)
- {
+ let mut staged = match stage::Stage::create_in(&state_dir) {
Ok(file) => file,
Err(error) => {
let mut errors = bulk_errors.lock().unwrap();
@@ -10939,12 +10937,9 @@ fn run_index_report_inner(
align_hit_locators(&mut fields, &f.rel);
let action = json!({"index": {
"_index": rt.index, "_id": cf.anchor_doc_id}});
- if let Err(error) = writeln!(
- staged.as_file_mut(),
- "{}\n{}",
- action,
- Value::Object(fields)
- ) {
+ if let Err(error) =
+ writeln!(&mut staged, "{}\n{}", action, Value::Object(fields))
+ {
send_err = Some(format!("stage file card for {}: {error}", f.rel));
}
}
@@ -11038,7 +11033,7 @@ fn run_index_report_inner(
let action = json!({"index": {"_index": rt.index, "_id": id}});
let doc = Value::Object(fields);
if let Err(error) = writeln!(
- staged.as_file_mut(),
+ &mut staged,
"{}\n{}",
action,
serde_json::to_string(&doc).unwrap_or_else(|_| "{}".into())
@@ -11314,12 +11309,21 @@ fn run_index_report_inner(
}
}
}
+ // The stage is consumed here whether or not the send runs: an
+ // early error drops it, and the unnamed file goes with it.
+ let staged_len = staged.raw_bytes();
+ let mut reader = None;
if send_err.is_none() {
- if let Err(error) = staged.as_file_mut().rewind() {
- send_err = Some(format!("rewind staged records for {}: {error}", f.rel));
+ match staged.into_reader() {
+ Ok((r, _disk)) => reader = Some(r),
+ Err(error) => {
+ send_err = Some(format!("rewind staged records for {}: {error}", f.rel));
+ }
}
+ } else {
+ drop(staged);
}
- if send_err.is_none() {
+ if let Some(mut reader) = reader.filter(|_| send_err.is_none()) {
// The second half of a mailbox's bar: staged bytes
// handed to the engine, out of staged bytes in total.
// Credit is taken at submission: the shared buffer
@@ -11327,9 +11331,7 @@ fn run_index_report_inner(
// flush carries them, and the bar measures reading
// work, not wire time.
let credit_send = sn.family == Family::Mbox;
- let staged_len = staged.as_file().metadata().map(|m| m.len()).unwrap_or(0);
let mut staged_sent = 0u64;
- let mut reader = BufReader::new(staged.as_file_mut());
// A LOCAL chunk, not the bulk: chunks join whatever
// the other workers are staging in the shared buffer,
// so a small file stops paying for its own round-trip.
diff --git a/engine/crates/xerj-autoindex/src/stage.rs b/engine/crates/xerj-autoindex/src/stage.rs
new file mode 100644
index 000000000..72b0888a9
--- /dev/null
+++ b/engine/crates/xerj-autoindex/src/stage.rs
@@ -0,0 +1,178 @@
+//! Per-file staging area for phase B (#2427).
+//!
+//! Phase B stages every record of a file locally, re-verifies the source, and
+//! only then makes the file visible on the node (#1911). Two properties of
+//! the old staging file showed up in the 1 GB gate's fair autoindex leg
+//! (state dir at 677 MB, three `.autoindex-stage-*` files of ~215 MB each):
+//!
+//! * **Size.** A staged record is the bulk action line plus the document with
+//! its provenance fields (`ax_path`, `ax_paths`, `ax_file`, `ax_run`, ...).
+//! For row-shaped sources that is several times the source: a 31.7 MB ADS-B
+//! trace staged as ~215 MB (6.8x). With `--workers 4`, the stages of the
+//! files in flight held hundreds of megabytes of disk for minutes while the
+//! node throttled bulks. The staged stream is extremely repetitive (the same
+//! index name, path, key, run id and dataset on every record), so it is now
+//! zstd-compressed on the way to disk; see the test for the ratio on a
+//! trace-shaped file.
+//! * **Lifetime.** The stage was a *named* temp file. `NamedTempFile::drop`
+//! removes it after the file is sent or abandoned, but a client stopped by a
+//! signal (`timeout`, Ctrl-C, OOM kill) never runs drop, so the files stayed
+//! in the state dir until the next run's journal open swept them. The stage
+//! is now an *unnamed* temp file (`O_TMPFILE` on Linux, unlinked at creation
+//! elsewhere): the kernel frees it when the descriptor closes, including on
+//! SIGKILL, so nothing can be left behind. The journal-open sweep of the
+//! reserved prefix stays for state dirs written by older binaries.
+//!
+//! A blocking global byte budget was considered and rejected: a worker parked
+//! on it still counts as "could add bytes" for the shared bulk pipe's settle
+//! barrier, so the oldest stage's settle could wait on it forever. The bound
+//! is instead `workers x compressed stage`, which the compression keeps small.
+
+use std::fs::File;
+use std::io::{self, BufReader, Seek, Write};
+use std::path::Path;
+
+/// zstd level for stages: level 1 compresses this stream >10x at hundreds of
+/// MB/s, far above phase B's send rate, so it never paces the run.
+const STAGE_ZSTD_LEVEL: i32 = 1;
+
+/// Reader over a finished stage: the decompressed NDJSON, in write order.
+pub(crate) type StageReader = BufReader<zstd::stream::read::Decoder<'static, BufReader<File>>>;
+
+/// One file's staged NDJSON, compressed into an unnamed temp file.
+pub(crate) struct Stage {
+ encoder: zstd::stream::write::Encoder<'static, File>,
+ raw_bytes: u64,
+}
+
+impl Stage {
+ /// Create an unnamed stage in `dir` (the run's state dir, so its disk use
+ /// lands on the same filesystem the operator budgeted for state).
+ pub(crate) fn create_in(dir: &Path) -> io::Result<Self> {
+ let file = tempfile::tempfile_in(dir)?;
+ let encoder = zstd::stream::write::Encoder::new(file, STAGE_ZSTD_LEVEL)?;
+ Ok(Self {
+ encoder,
+ raw_bytes: 0,
+ })
+ }
+
+ /// Uncompressed bytes written so far (what the send loop will read back).
+ pub(crate) fn raw_bytes(&self) -> u64 {
+ self.raw_bytes
+ }
+
+ /// Finish compression and return a reader positioned at the first staged
+ /// line, plus the compressed size on disk.
+ pub(crate) fn into_reader(self) -> io::Result<(StageReader, u64)> {
+ let mut file = self.encoder.finish()?;
+ let disk_bytes = file.stream_position()?;
+ file.rewind()?;
+ let decoder = zstd::stream::read::Decoder::new(file)?;
+ Ok((BufReader::new(decoder), disk_bytes))
+ }
+}
+
+impl Write for Stage {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ let n = self.encoder.write(buf)?;
+ self.raw_bytes += n as u64;
+ Ok(n)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.encoder.flush()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::BufRead;
+
+ /// Trace-shaped records: what the gate's ADS-B files stage as.
+ fn trace_record(i: u64) -> String {
+ format!(
+ "{{\"index\":{{\"_index\":\"ax-adsb-traces\",\"_id\":\"0f3c9a1b2d4e5f60718293a4b5c6d7e8-{i}\"}}}}\n\
+ {{\"t\":{},\"lat\":{:.5},\"lon\":{:.5},\"alt\":{},\"gs\":{:.1},\"track\":{},\
+ \"ax_path\":\"adsb/traces/00/trace_full_000000.json\",\
+ \"ax_paths\":[\"adsb/traces/00/trace_full_000000.json\"],\
+ \"ax_file\":\"5b1f0c8e4a7d2e9f3c6b0a1d8e7f4c2b9a6d3e0f1c8b5a2d9e6f3c0b7a4d1e8f\",\
+ \"ax_locator\":\"trace[{i}]\",\"ax_dataset\":\"adsb-traces\",\
+ \"ax_run\":\"run-20261026T230000Z-7f3a\",\"ax_format\":\"json\"}}\n",
+ 1_729_000_000 + i,
+ (i as f64 * 0.731).sin() * 89.0,
+ (i as f64 * 0.377).cos() * 179.0,
+ (i * 7919) % 45_000,
+ (i % 600) as f64 + 0.5,
+ (i * 31) % 360,
+ )
+ }
+
+ #[test]
+ fn stage_round_trips_and_stays_far_below_raw_size() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut stage = Stage::create_in(dir.path()).unwrap();
+ let mut expected = Vec::new();
+ for i in 0..50_000 {
+ let rec = trace_record(i);
+ stage.write_all(rec.as_bytes()).unwrap();
+ expected.push(rec);
+ }
+ let raw = stage.raw_bytes();
+ assert_eq!(raw, expected.iter().map(|r| r.len() as u64).sum::<u64>());
+ let (mut reader, disk) = stage.into_reader().unwrap();
+ // Several times smaller on disk than the stream the node will receive.
+ assert!(
+ disk * 5 < raw,
+ "stage compressed {raw} raw bytes only to {disk} on disk"
+ );
+ // Lines come back exactly, in order, two per record.
+ let mut line = String::new();
+ for rec in &expected {
+ let mut got = String::new();
+ for _ in 0..2 {
+ line.clear();
+ assert!(reader.read_line(&mut line).unwrap() > 0);
+ got.push_str(&line);
+ }
+ assert_eq!(&got, rec);
+ }
+ line.clear();
+ assert_eq!(reader.read_line(&mut line).unwrap(), 0);
+ }
+
+ #[test]
+ fn stages_leave_nothing_in_the_state_dir() {
+ let dir = tempfile::tempdir().unwrap();
+ let listing = || std::fs::read_dir(dir.path()).unwrap().count();
+ let mut stages: Vec<Stage> = (0..4)
+ .map(|_| Stage::create_in(dir.path()).unwrap())
+ .collect();
+ for (n, stage) in stages.iter_mut().enumerate() {
+ for i in 0..1_000 {
+ stage
+ .write_all(trace_record(i + n as u64).as_bytes())
+ .unwrap();
+ }
+ }
+ // Live stages have no directory entry, so neither an abandoned retry
+ // nor a client killed mid-file (no drop runs) can leave one behind.
+ assert_eq!(listing(), 0);
+ let (reader, _) = stages.pop().unwrap().into_reader().unwrap();
+ assert_eq!(listing(), 0);
+ drop(reader);
+ drop(stages);
+ assert_eq!(listing(), 0);
+ }
+
+ #[test]
+ fn empty_stage_reads_back_empty() {
+ let dir = tempfile::tempdir().unwrap();
+ let stage = Stage::create_in(dir.path()).unwrap();
+ assert_eq!(stage.raw_bytes(), 0);
+ let (mut reader, _) = stage.into_reader().unwrap();
+ let mut line = String::new();
+ assert_eq!(reader.read_line(&mut line).unwrap(), 0);
+ }
+}