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): keep run identity unique inside one process

xerj-orgd61c8750868f
diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
index 1c3af9254..732881360 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -750,3 +750,50 @@ fn fresh_cannot_destroy_a_pending_generation() {
assert!(rendered.contains("sealed-pending"), "{rendered}");
assert!(rendered.contains("sealed-second"), "{rendered}");
}
+
+/// Two runs started in the same process and the same UTC second must not share
+/// a `run_id`.
+///
+/// The generation catalog keys its managed documents on `run_id`, so a
+/// collision makes the second run read the first run's documents back as its
+/// own generation. `xerj brain` calls `run_index_report` more than once per
+/// process, so this is reachable without any concurrency.
+#[test]
+fn same_second_runs_in_one_process_do_not_share_a_generation_identity() {
+ let _guard = HTTP_E2E_LOCK.lock().unwrap();
+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let corpus = tempfile::tempdir().unwrap();
+ let first_state = tempfile::tempdir().unwrap();
+ let second_state = tempfile::tempdir().unwrap();
+ fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n").unwrap();
+ let endpoint = HttpEndpoint::start();
+
+ assert_eq!(
+ run_index(cfg(corpus.path(), first_state.path(), &endpoint.url, false)).unwrap(),
+ 0
+ );
+ let second = run_index_report(cfg(
+ corpus.path(),
+ second_state.path(),
+ &endpoint.url,
+ false,
+ ));
+ let (code, summary) = second.expect("a second run in the same second must commit");
+ assert_eq!(code, 0);
+ assert_eq!(summary.unwrap()["generation"], 1);
+
+ let run_id = |state_dir: &Path| -> String {
+ fs::read_to_string(state_dir.join("journal.ndjson"))
+ .unwrap()
+ .lines()
+ .filter_map(|line| serde_json::from_str::<Value>(line).ok())
+ .find_map(|event| {
+ event
+ .get("run_id")
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ })
+ .expect("journal records a run_id")
+ };
+ assert_ne!(run_id(first_state.path()), run_id(second_state.path()));
+}
diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rs
index 16a13c522..b89fab475 100644
--- a/engine/crates/xerj-autoindex/src/state.rs
+++ b/engine/crates/xerj-autoindex/src/state.rs
@@ -50,7 +50,7 @@ pub struct PlanDataset {
#[cfg(test)]
mod tests {
- use super::Journal;
+ use super::{run_id_in_second, Journal};
#[test]
fn legacy_journal_can_resume_with_a_custom_operational_timeout() {
@@ -71,6 +71,19 @@ mod tests {
assert!(text.contains("\"bulk_timeout_secs\":3600"));
}
+ /// Run identity must stay unique inside one process even when the
+ /// one-second timestamp component cannot distinguish two runs. The
+ /// generation catalog keys managed documents on `run_id`, so a duplicate
+ /// makes a run read another run's documents back as its own generation.
+ #[test]
+ fn run_ids_minted_in_the_same_second_and_process_are_distinct() {
+ let second = "20260804T000000Z";
+ let first = run_id_in_second(second);
+ let next = run_id_in_second(second);
+ assert_ne!(first, next);
+ assert!(first.starts_with(&format!("run-{second}-")), "{first}");
+ }
+
#[test]
fn fresh_journal_records_each_runs_effective_operational_timeout() {
let dir = tempfile::tempdir().unwrap();
@@ -390,6 +403,32 @@ pub struct Journal {
pub legacy_migration_reasons: Vec<String>,
}
+/// Per-process monotonic suffix for [`new_run_id`].
+///
+/// The timestamp component only has one-second resolution, so two runs started
+/// in the same second by the same process used to produce the same `run_id`.
+/// That is reachable from library consumers — `xerj brain` calls
+/// `run_index_report` more than once in one process — and a collision is not
+/// benign: the generation catalog keys managed documents on `run_id`, so the
+/// second run inherits the first run's documents as its own generation.
+static RUN_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// Identity for a brand-new run: UTC second, process id, and a monotonic
+/// per-process sequence number that makes same-second runs distinct.
+fn new_run_id() -> String {
+ run_id_in_second(&chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string())
+}
+
+/// Split out of [`new_run_id`] so the same-second case is testable without
+/// depending on where a test happens to land inside a wall-clock second.
+fn run_id_in_second(second: &str) -> String {
+ format!(
+ "run-{second}-{:04x}-{:04x}",
+ std::process::id() & 0xffff,
+ RUN_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & 0xffff
+ )
+}
+
pub fn default_state_dir(root: &str, url: &str, prefix: &str) -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
Path::new(&home)
@@ -860,13 +899,7 @@ impl Journal {
}
}
let is_new = run_id.is_none();
- let run_id = run_id.unwrap_or_else(|| {
- format!(
- "run-{}-{:04x}",
- chrono::Utc::now().format("%Y%m%dT%H%M%SZ"),
- std::process::id() & 0xffff
- )
- });
+ let run_id = run_id.unwrap_or_else(new_run_id);
let file = std::fs::OpenOptions::new()
.create(true)
.append(true)