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): finish compressed stages before replacing live records

xerj-orgb8179b37213d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 338d70499..6d30a2018 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- `xerj autoindex` compresses per-file phase-B stages with zstd level 1 and
+ uses temporary files cleaned up by the operating system when the client
+ exits (#2493, part of #2427). It finishes buffered compression before
+ deleting previous records, so a stage finalization error preserves the old
+ records and an ordinary resume can complete the replacement. Compression
+ savings depend on the data; this does not impose a disk or server-memory cap.
+- `autoindex` bulk back-pressure patience is now measured since the last
+ progress, not since the first round. A window the server drains a few
+ records at a time (per-item 429 `resource_exhausted` on an embedding
+ deadline or admission refusal) used to abort with `bulk backend failed`
+ once the rounds together passed the 600 s `THROTTLE_PATIENCE`, even though
+ every round settled records. Each round that settles at least one item now
+ restarts the patience clock and the backoff; rounds that settle nothing
+ still count, so a server that answers 429 forever fails at the same limits
+ as before.
+
## [1.0.0-rc.100] - 2026-10-26
**rc.100: faster autoindex and search, shaped by your field reports.** This
@@ -17,8 +35,9 @@ return (#2443, #2434, #2454, #2465). Search keeps its own share of the memory
budget while merges run (#2484, #2485), autoindex plans large folders in
bounded memory with fewer, larger datasets (#2417, #2430), and a
`semantic_text` test segment shrinks from 20.1 MB to 1.8 MB on disk
-(#2471). Every release candidate now passes a performance gate with autoindex and search budgets
-and an Elasticsearch floor before it ships (#2432). Thank you to everyone
+(#2471). A local performance harness adds autoindex and search budgets and an
+Elasticsearch floor (#2432); release-workflow integration remains open in
+#2433. Thank you to everyone
who filed a field report: they shaped this release. The memory-ceiling work
continues in #2427 and #1122, which stay open.
@@ -126,9 +145,9 @@ continues in #2427 and #1122, which stay open.
- **Release performance gate** for autoindex and search. It adds
`gen_corpus.py`, `autoindex_release_gate.sh` and `gate.py`, with per-phase
- budgets, an Elasticsearch floor and an rc.99 comparison harness, and it
- runs before a release is cut (#2432). The live-tree memory follow-up is
- tracked in #2433, which stays open.
+ budgets, an Elasticsearch floor and an rc.99 comparison harness (#2432).
+ Release-workflow wiring and the live-tree memory follow-up remain pending
+ in #2433; the harness is currently available for local runs.
- `xerj init` prints the Kimi CLI MCP config path (`~/.kimi-code/mcp.json`),
and the README marks the Kimi CLI row as tested (#2386).
@@ -170,14 +189,6 @@ continues in #2427 and #1122, which stay open.
so a `\`-separated path stayed whole and was refused as an unsafe repo
name; it now names the repo `Foo`, as `F:/Projects/Foo` already did.
-- `xerj autoindex` no longer leaves large `.autoindex-stage-*` files in the
- state dir (#2427, PR [#2493](https://github.com/xerj-org/xerj/pull/2493)).
- Phase B staged each file as uncompressed NDJSON in a named temp file, which
- was several times the size of the source for row-shaped data (a 31.7 MB
- trace staged as about 215 MB) and was left behind when the client was
- killed by a signal. Stages are now zstd-compressed and written to an
- unnamed temp file that the kernel frees when the client exits, however it
- exits.
- `xerj code` shows the part of a long definition that matched the query,
not its first `--full` characters (#2464). The matching text could sit
thousands of characters below the signature, so a hit named the right
@@ -198,15 +209,6 @@ continues in #2427 and #1122, which stay open.
batch's merge reservation, so concurrent merge admission sees it.
`_forcemerge` batches are charged but never refused, and neither is a
small batch that the yield-streak rule (#2468) lets run to completion (PR #2470).
-- `autoindex` bulk back-pressure patience is now measured since the last
- progress, not since the first round. A window the server drains a few
- records at a time (per-item 429 `resource_exhausted` on an embedding
- deadline or admission refusal) used to abort with `bulk backend failed`
- once the rounds together passed the 600 s `THROTTLE_PATIENCE`, even though
- every round settled records. Each round that settles at least one item now
- restarts the patience clock and the backoff; rounds that settle nothing
- still count, so a server that answers 429 forever fails at the same limits
- as before.
- The parent memory breaker no longer flaps, and background merges and flush
finalizes are bounded while it is engaged (#2427). A 3,000 MB autoindex run
diff --git a/docs/perf-release-gate.md b/docs/perf-release-gate.md
index 41a924630..ac3f0e718 100644
--- a/docs/perf-release-gate.md
+++ b/docs/perf-release-gate.md
@@ -143,16 +143,18 @@ python3 scripts/perf/es_baseline.py --es http://127.0.0.1:9200 --corpus /tmp/c1g
## CI
-The workflow (`.github/workflows/perf-gate.yml`) is maintained by hand. See the
-tracking issue for the ready-to-paste YAML. It runs:
-
-* on PRs touching autoindex, engine or server paths: the 1 GB tier;
-* nightly: the 1 GB tier with `--baseline` set to the latest release binary, plus the ES floor;
-* on `v*` tags, as a job `release.yml` depends on (`needs: [build, perf-gate]`): the 5 GB tier.
-
-Results are uploaded as the `perf-gate-*` artifact (`results.json` holds every
-raw measurement, budget and verdict) and summarized in the job summary and as
-a PR comment.
+The harness is implemented, but `.github/workflows/perf-gate.yml` is not
+present and the publication job in `release.yml` depends only on `build`.
+A successful release build therefore does **not** establish that these
+performance budgets passed. Workflow wiring remains open in
+[#2433](https://github.com/xerj-org/xerj/issues/2433), alongside the remaining
+memory failures. The YAML in that issue describes the intended PR, nightly
+and release jobs; it is not a workflow currently running in this repository.
+
+Use the local commands above for measurements until that integration lands.
+Keep the raw `candidate.json`, any baseline JSON, `results.json`, and node and
+client logs with the verdict. Do not loosen budgets or report an incomplete
+run as a passing release gate.
## Changing a budget
diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rs
index 95d3aa853..874afa7dd 100644
--- a/engine/crates/xerj-autoindex/src/esclient.rs
+++ b/engine/crates/xerj-autoindex/src/esclient.rs
@@ -4446,6 +4446,8 @@ mod tests {
let server_stop = Arc::clone(&stop);
let rounds = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let server_rounds = Arc::clone(&rounds);
+ let accepted = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
+ let server_accepted = Arc::clone(&accepted);
let server = std::thread::spawn(move || loop {
match listener.accept() {
Ok((mut stream, _)) => {
@@ -4456,6 +4458,23 @@ mod tests {
.filter(|line| !line.is_empty())
.count()
/ 2;
+ let offered: Vec<String> = request_body(&request)
+ .split(|b| *b == b'\n')
+ .filter(|line| !line.is_empty())
+ .step_by(2)
+ .map(|line| {
+ let action: serde_json::Value = serde_json::from_slice(line).unwrap();
+ action["index"]["_id"].as_str().unwrap().to_owned()
+ })
+ .collect();
+ {
+ let mut accepted = server_accepted.lock().unwrap();
+ assert!(
+ offered.iter().all(|id| !accepted.contains(id)),
+ "accepted records were re-offered"
+ );
+ accepted.push(offered[0].clone());
+ }
server_rounds.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(60));
let mut statuses = vec![429u16; actions];
@@ -4479,6 +4498,7 @@ mod tests {
let elapsed = started.elapsed();
stop.store(true, Ordering::SeqCst);
server.join().unwrap();
+ assert_eq!(*accepted.lock().unwrap(), ids);
assert_eq!(outcome.server_errors, 0, "{outcome:?}");
assert_eq!(outcome.throttled_out, 0, "{outcome:?}");
assert!(outcome.exhausted_after.is_none(), "{outcome:?}");
@@ -4550,7 +4570,7 @@ mod tests {
);
assert_eq!(outcome.throttled_out, 2, "{outcome:?}");
assert!(
- elapsed >= Duration::from_millis(300) && elapsed < Duration::from_secs(3),
+ elapsed >= Duration::from_millis(300),
"stopped at the patience after the last progress, took {elapsed:?}"
);
}
diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
index eb68c67dc..a7a5cd7ba 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -3267,6 +3267,91 @@ fn existing_completion_is_invalidated_and_partial_visibility_is_deleted_on_resum
}
}
+#[test]
+fn stage_finish_failure_preserves_previous_records_and_resume_replaces_them() {
+ let _guard = FAILPOINT_TEST_LOCK
+ .lock()
+ .unwrap_or_else(|p| p.into_inner());
+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
+ .lock()
+ .unwrap_or_else(|p| p.into_inner());
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ let path = corpus.path().join("records.csv");
+ fs::write(&path, "id,value\n0,old\n1,old\n").unwrap();
+ let endpoint = MockEndpoint::start(usize::MAX);
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
+ assert_eq!(run_index(config.clone()).unwrap(), 0);
+ let (old_docs, old_deletes, old_bulks) = {
+ let state = endpoint.state.lock().unwrap();
+ (
+ state.docs.clone(),
+ state.delete_calls,
+ state.data_bulk_number,
+ )
+ };
+ assert!(!old_docs.is_empty());
+ fs::write(&path, "id,value\n0,new\n1,new\n").unwrap();
+
+ // Compression can buffer a successful write until into_reader finishes
+ // the frame. This local failure must precede the remote replacement.
+ arm_replacement_failpoint(5, state_dir.path());
+ let error = run_index(config.clone()).unwrap_err();
+ assert!(
+ format!("{error:#}").contains("injected replacement crash boundary 5"),
+ "{error:#}"
+ );
+ {
+ let state = endpoint.state.lock().unwrap();
+ assert_eq!(
+ state.delete_calls, old_deletes,
+ "deleted before stage finished"
+ );
+ assert_eq!(state.data_bulk_number, old_bulks);
+ assert_eq!(
+ state.docs, old_docs,
+ "previous records must remain readable"
+ );
+ }
+ assert_eq!(file_done_count(state_dir.path()), 1);
+ let replay = state::Journal::open(
+ state_dir.path(),
+ &config.root.to_string_lossy(),
+ &config.url,
+ &config.prefix,
+ config.bulk_timeout_secs,
+ false,
+ )
+ .unwrap();
+ assert!(
+ replay.done.is_empty(),
+ "failed replacement cannot be committed"
+ );
+ assert_eq!(replay.pending_replacements.len(), 1);
+ drop(replay);
+
+ assert_eq!(run_index(config.clone()).unwrap(), 0);
+ assert_eq!(file_done_count(state_dir.path()), 2);
+ let (new_docs, new_bulks) = {
+ let state = endpoint.state.lock().unwrap();
+ assert_eq!(state.delete_calls, old_deletes + 1);
+ let rows: Vec<_> = state
+ .docs
+ .values()
+ .filter(|doc| doc.get("value").is_some())
+ .collect();
+ assert_eq!(rows.len(), 2);
+ assert!(rows.iter().all(|doc| doc["value"].as_str() == Some("new")));
+ (state.docs.clone(), state.data_bulk_number)
+ };
+ // A zero-work rerun must retain the completed replacement unchanged.
+ assert_eq!(run_index(config).unwrap(), 0);
+ let state = endpoint.state.lock().unwrap();
+ assert_eq!(state.docs, new_docs);
+ assert_eq!(state.data_bulk_number, new_bulks);
+ assert_eq!(state.delete_calls, old_deletes + 1);
+}
+
#[test]
fn resume_repairs_kills_after_plan_delete_and_final_bulk_before_file_done() {
let _guard = FAILPOINT_TEST_LOCK
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index f850db6ad..1b406af9f 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -11273,9 +11273,28 @@ fn run_index_report_inner(
continue;
}
}
+ // Finish buffered compression before the first remote mutation.
+ // ENOSPC can surface here even when every earlier write succeeded;
+ // keep the previous records live and the replacement pending then.
+ // Reference: tantivy 3a55bc98, src/directory/mmap_directory/mod.rs:
+ // 372-376 flushes the temporary writer before publishing its file.
+ // 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() {
+ match staged.into_reader() {
+ Ok((r, _disk)) => reader = Some(r),
+ Err(error) => {
+ send_err = Some(format!("finish staged records for {}: {error}", f.rel));
+ }
+ }
+ } else {
+ drop(staged);
+ }
// Visibility begins only after extraction and the second
- // full-content verification. Delete-before-replace makes
- // a retry clean up any partial prior attempt.
+ // full-content verification and stage finalization.
+ // Delete-before-replace makes a retry clean up any partial prior attempt.
if send_err.is_none() && cleanup_required.contains(key) {
let prior = superseded.get(&f.rel);
let mut indices: Vec<String> = fa
@@ -11309,20 +11328,6 @@ 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() {
- 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 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.
diff --git a/engine/crates/xerj-autoindex/src/stage.rs b/engine/crates/xerj-autoindex/src/stage.rs
index 72b0888a9..6a240218f 100644
--- a/engine/crates/xerj-autoindex/src/stage.rs
+++ b/engine/crates/xerj-autoindex/src/stage.rs
@@ -1,17 +1,16 @@
//! 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):
+//! only then makes the file visible on the node (#1911). Finish the compressed
+//! stream before deleting any prior records: buffered writes may fail at
+//! finalization. Two properties motivated replacing the old staging file:
//!
//! * **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
+//! For row-shaped sources the provenance can exceed the source data, and
+//! concurrent workers each retain a stage while bulks are throttled.
+//! The staged stream repeats 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`
@@ -19,21 +18,22 @@
//! 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
+//! on other Unix systems): the kernel frees it when the descriptor closes, including on
+//! SIGKILL. Windows uses delete-on-close. 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.
+//! barrier, so the oldest stage's settle could wait on it forever. Disk use
+//! still depends on concurrent stages and their compressibility; this is not
+//! a hard disk quota or a fix for the node's process memory limit.
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.
+/// Use zstd's fast level; avoid the high-effort compression that previously
+/// stalled background merges (#2441). Savings depend on the input.
const STAGE_ZSTD_LEVEL: i32 = 1;
/// Reader over a finished stage: the decompressed NDJSON, in write order.
@@ -43,6 +43,8 @@ pub(crate) type StageReader = BufReader<zstd::stream::read::Decoder<'static, Buf
pub(crate) struct Stage {
encoder: zstd::stream::write::Encoder<'static, File>,
raw_bytes: u64,
+ #[cfg(test)]
+ state_dir: std::path::PathBuf,
}
impl Stage {
@@ -54,6 +56,8 @@ impl Stage {
Ok(Self {
encoder,
raw_bytes: 0,
+ #[cfg(test)]
+ state_dir: dir.to_path_buf(),
})
}
@@ -65,6 +69,9 @@ impl Stage {
/// 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)> {
+ // Model a buffered write failing at finish, scoped to one test run.
+ #[cfg(test)]
+ crate::replacement_failpoint(5, &self.state_dir).map_err(io::Error::other)?;
let mut file = self.encoder.finish()?;
let disk_bytes = file.stream_position()?;
file.rewind()?;
@@ -122,6 +129,7 @@ mod tests {
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();
+ eprintln!("trace stage: raw_bytes={raw} compressed_bytes={disk}");
// Several times smaller on disk than the stream the node will receive.
assert!(
disk * 5 < raw,
@@ -156,10 +164,13 @@ mod tests {
.unwrap();
}
}
- // Live stages have no directory entry, so neither an abandoned retry
+ // On Unix live stages have no directory entry, so neither an abandoned retry
// nor a client killed mid-file (no drop runs) can leave one behind.
+ // Windows delete-on-close files may remain visible until closed.
+ #[cfg(unix)]
assert_eq!(listing(), 0);
let (reader, _) = stages.pop().unwrap().into_reader().unwrap();
+ #[cfg(unix)]
assert_eq!(listing(), 0);
drop(reader);
drop(stages);
@@ -175,4 +186,29 @@ mod tests {
let mut line = String::new();
assert_eq!(reader.read_line(&mut line).unwrap(), 0);
}
+
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn buffered_stage_write_can_fail_only_when_finishing() {
+ let dir = tempfile::tempdir().unwrap();
+ let file = std::fs::OpenOptions::new()
+ .write(true)
+ .open("/dev/full")
+ .unwrap();
+ let mut stage = Stage {
+ encoder: zstd::stream::write::Encoder::new(file, STAGE_ZSTD_LEVEL).unwrap(),
+ raw_bytes: 0,
+ state_dir: dir.path().to_owned(),
+ };
+ let bytes = b"{\"index\":{}}\n{\"value\":\"buffered until finish\"}\n";
+ stage
+ .write_all(bytes)
+ .expect("small writes are buffered by zstd");
+ assert_eq!(stage.raw_bytes(), bytes.len() as u64);
+ let error = stage
+ .into_reader()
+ .err()
+ .expect("finishing must report ENOSPC");
+ assert_eq!(error.raw_os_error(), Some(libc::ENOSPC));
+ }
}