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): skip and record a file that changes mid-run instead of aborting (#1911) (#1917)

xerj-org235584b856c3
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 580ddbf0b..71216f99e 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -1236,6 +1236,89 @@ fn a_rerun_after_an_added_file_succeeds_and_fresh_absorbs_it() {
assert!(indexed.contains("second.csv"), "{indexed:?}");
}
+/// #1911: one file that changed between phase A's digest and phase B's read
+/// (a live lock file on Windows) aborted the whole run with "bulk/backend
+/// failures", after other files' records were already live — 87 partial
+/// indices and a journal to clean by hand, and a retry met the same file. It is
+/// now one skipped file with the reason in the catalog: every other file is
+/// indexed and journaled, the run completes with exit 3, and the next run
+/// indexes the file's new content.
+#[test]
+fn a_file_that_changes_mid_run_is_skipped_and_the_run_finishes() {
+ 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();
+ fs::write(corpus.path().join("first.csv"), "id,value\n1,first\n").unwrap();
+ fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();
+ let live = corpus.path().join("app.lock");
+ fs::write(&live, "pid 1\n").unwrap();
+ let endpoint = MockEndpoint::start(usize::MAX);
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
+
+ let grow = live.clone();
+ arm_phase_b_start_hook(state_dir.path(), move || {
+ let mut f = fs::OpenOptions::new().append(true).open(grow).unwrap();
+ f.write_all(b"pid 2 took the lock\n").unwrap();
+ });
+ let (code, report) =
+ run_index_report(config.clone()).expect("one changing file must not abort the run");
+ assert_eq!(
+ code, 3,
+ "a skipped file is completed-with-junk, not a failure"
+ );
+ let report = report.unwrap();
+ assert_eq!(report["files_junk"], 1, "{report}");
+ assert_eq!(
+ file_done_count(state_dir.path()),
+ 2,
+ "every other file is journaled done"
+ );
+ {
+ let locked = endpoint.state.lock().unwrap();
+ let mut paths: Vec<&str> = data_rows(&locked)
+ .iter()
+ .filter_map(|doc| doc["ax_path"].as_str())
+ .collect();
+ paths.sort_unstable();
+ paths.dedup();
+ assert_eq!(paths, vec!["first.csv", "second.csv"], "{paths:?}");
+ let skipped: Vec<&Value> = locked
+ .catalog_docs
+ .values()
+ .filter(|doc| doc["path"].as_str() == Some("app.lock"))
+ .collect();
+ assert_eq!(
+ skipped.len(),
+ 1,
+ "the changed file is recorded: {skipped:?}"
+ );
+ assert_eq!(skipped[0]["status"], "skipped", "{}", skipped[0]);
+ let reason = skipped[0]["reason"].as_str().unwrap_or_default();
+ assert!(
+ reason.contains("changed while this run was reading it"),
+ "{reason}"
+ );
+ assert!(reason.contains("changed size"), "{reason}");
+ assert!(reason.contains("rerun"), "{reason}");
+ }
+
+ // The file has settled: the same command picks up its current content.
+ let (code, _) = run_index_report(config).expect("the rerun completes");
+ assert_eq!(code, 0, "nothing is left to skip once the file is still");
+ let locked = endpoint.state.lock().unwrap();
+ let indexed: std::collections::HashSet<&str> = locked
+ .docs
+ .values()
+ .filter_map(|doc| doc["ax_path"].as_str())
+ .collect();
+ assert!(indexed.contains("app.lock"), "{indexed:?}");
+}
+
#[test]
fn completed_plan_rejects_vanished_content_group_before_remote_mutation() {
let _guard = FAILPOINT_TEST_LOCK
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 49141d73f..d3ce442cf 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -2098,6 +2098,40 @@ impl Drop for SampleLimitOverride {
#[cfg(test)]
static REPLACEMENT_FAILPOINT: Mutex<Option<(u8, std::path::PathBuf)>> = Mutex::new(None);
+/// A test-only action run once when phase B starts, for the run that uses the
+/// given state directory: the window between phase A's digest and phase B's
+/// read, where a live file (a lock file, a log) changes under the run (#1911).
+/// Keyed on the state directory for the same reason as
+/// [`REPLACEMENT_FAILPOINT`].
+#[cfg(test)]
+type PhaseBStartHook = (std::path::PathBuf, Box<dyn FnOnce() + Send>);
+#[cfg(test)]
+static PHASE_B_START_HOOK: Mutex<Option<PhaseBStartHook>> = Mutex::new(None);
+
+#[cfg(test)]
+pub(crate) fn arm_phase_b_start_hook(state_dir: &Path, action: impl FnOnce() + Send + 'static) {
+ *PHASE_B_START_HOOK.lock().unwrap_or_else(|p| p.into_inner()) =
+ Some((state_dir.to_path_buf(), Box::new(action)));
+}
+
+#[cfg(test)]
+fn phase_b_start_hook(state_dir: &Path) {
+ let action = {
+ let mut armed = PHASE_B_START_HOOK.lock().unwrap_or_else(|p| p.into_inner());
+ match armed.as_ref() {
+ Some((dir, _)) if dir == state_dir => armed.take().map(|(_, action)| action),
+ _ => None,
+ }
+ };
+ if let Some(action) = action {
+ action();
+ }
+}
+
+#[cfg(not(test))]
+#[inline]
+fn phase_b_start_hook(_state_dir: &Path) {}
+
/// Arm [`replacement_failpoint`] for the run that uses `state_dir`, once.
#[cfg(test)]
pub(crate) fn arm_replacement_failpoint(boundary: u8, state_dir: &Path) {
@@ -7905,6 +7939,7 @@ fn run_index_report_inner(
"phase B: indexing {} files with {} workers → {}",
n_todo, cfg.workers, cfg.url
));
+ phase_b_start_hook(&state_dir);
if n_pdf_spools > 0 {
pr.note(&format!(
"phase B: reusing {n_pdf_spools} run-local PDF extraction(s); these PDFs will not be \
@@ -8047,11 +8082,17 @@ fn run_index_report_inner(
continue;
}
};
+ // #1911: a file that changed since phase A hashed it (a lock
+ // file, a log, a sqlite -wal) is ONE skipped file, not a reason
+ // to abort every other file's run. Nothing of it is staged yet.
if let Err(error) = content::verify(&f.path, f.size, expected_digest) {
- let mut errors = bulk_errors.lock().unwrap();
- if errors.len() < 5 {
- errors.push(format!("{error:#}"));
- }
+ extra_junk.lock().unwrap().push(changed_during_run_junk(
+ key,
+ &f.rel,
+ &format_str(Some(&sn)),
+ f.size,
+ &error,
+ ));
continue;
}
// File-card anchor node (§6.6.2a): one card doc per corpus
@@ -8387,10 +8428,18 @@ fn run_index_report_inner(
}
}
if send_err.is_none() {
+ // #1911: changed while it was being extracted. Its records are
+ // only staged locally (visibility starts below), so skipping it
+ // here leaves nothing of it on the node from this run.
if let Err(error) = content::verify(&f.path, f.size, expected_digest) {
- send_err = Some(format!(
- "{error:#}; no records from this changing file were made visible"
+ extra_junk.lock().unwrap().push(changed_during_run_junk(
+ key,
+ &f.rel,
+ &format_str(Some(&sn)),
+ f.size,
+ &error,
));
+ continue;
}
}
// Visibility begins only after extraction and the second
@@ -9671,6 +9720,35 @@ fn run_index_report_inner(
Ok((code, Some(run_doc)))
}
+/// The catalog entry for a source file that changed between phase A's digest
+/// and phase B's read (#1911).
+///
+/// That used to land in `bulk_errors`, which aborts the whole run after phase B:
+/// one live lock file on Windows stopped a 1,894-file run at ~258 s and left
+/// its partial indices and journal for hand cleanup — and every retry met the
+/// same still-changing file. It is now one `skipped` file with the reason, the
+/// run finishes (exit 3, like any other skipped file), and because the file is
+/// never journaled done, the next run picks up whatever it then holds.
+fn changed_during_run_junk(
+ file_key: &str,
+ rel: &str,
+ format: &str,
+ bytes: u64,
+ error: &anyhow::Error,
+) -> JunkFile {
+ JunkFile {
+ file_key: file_key.to_string(),
+ rel: rel.to_string(),
+ format: format.to_string(),
+ status: "skipped".into(),
+ reason: format!(
+ "changed while this run was reading it, so it was skipped and nothing from it was \
+ made visible ({error:#}); rerun to index its current content"
+ ),
+ bytes,
+ }
+}
+
fn format_str(sn: Option<&Sniffed>) -> String {
match sn {
Some(s) if s.gzip => format!("{}(gzip)", s.family.as_str()),