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): refuse a reused --prefix on a different folder (#1634)

xerj-orgf9e24c10bb95
diff --git a/demo/usecases/autoindex/README.md b/demo/usecases/autoindex/README.md
index d806991c5..b7c678387 100644
--- a/demo/usecases/autoindex/README.md
+++ b/demo/usecases/autoindex/README.md
@@ -23,6 +23,14 @@ xerj autoindex status [--url U] [--state-dir P]
Exit codes: `0` complete · `3` completed-with-junk (junk recorded, never
fatal) · `2` usage · `1` endpoint unreachable / journal-config mismatch.
+`--prefix` names one source folder. Re-running it on a different folder is
+refused (exit 1) before anything is written: catalog datasets are
+`ds:<prefix>:<slug>` and indices are `<prefix>-*`, so finalize would retire
+the earlier datasets. Several repositories indexed as separate runs under
+one prefix also collapse into a single `<prefix>-docs` dataset. Use one
+`--prefix` per folder, index the parent folder once, or pass
+`--replace-prefix` to retire the earlier datasets on purpose.
+
## The one-binary, zero-config promise
- **One binary.** `autoindex` ships inside `xerj` itself. It is a pure
diff --git a/docs/recipes/zero-config-indexing.md b/docs/recipes/zero-config-indexing.md
index 8ee0aa740..26252ca87 100644
--- a/docs/recipes/zero-config-indexing.md
+++ b/docs/recipes/zero-config-indexing.md
@@ -449,7 +449,15 @@ Useful knobs (all optional): `--url` for a non-default endpoint, `--workers N`
(the *default* is every core, reduced when the memory safe zone cannot pay for
that many in-flight bulk buffers; a value you pass is honoured as typed and the
disagreement is printed, not applied; bounds both the scan and the indexing
-phase), `--prefix` to namespace the indices (default `ax`),
+phase), `--prefix` to namespace the indices (default `ax`; one prefix is one
+source folder — the same prefix on a different folder is refused, because
+catalog datasets are keyed `ds:<prefix>:<slug>` and indices are `<prefix>-*`,
+so finalize would overwrite the earlier datasets. Indexing several
+repositories as separate runs under one prefix also collapses them: each
+repo indexed on its own has an empty scope and becomes the single dataset
+`<prefix>-docs`. Index the parent folder once, use one `--prefix` per
+folder, or pass `--replace-prefix` to retire the earlier datasets on
+purpose. `--dry-run` does not bypass the refusal),
`--no-semantic` for pure BM25+keyword without vector fields, `--dry-run` to
print the inferred plan without indexing anything, `--follow-symlinks`
(loop-safe — and a followed link is judged by what it resolves to: a target
diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rs
index 5616a2514..69f629999 100644
--- a/engine/crates/xerj-autoindex/src/catalog.rs
+++ b/engine/crates/xerj-autoindex/src/catalog.rs
@@ -545,6 +545,98 @@ pub fn file_matches_prefix(doc: &Value, prefix: &str) -> bool {
== Some(prefix)
}
+/// Label used when a catalog run under `prefix` has no `root`.
+///
+/// An empty root cannot be proved to be this folder, so it counts as a
+/// different source. The string is stable so the refusal can name it.
+pub const UNRECORDED_PREFIX_ROOT: &str = "(root not recorded on the catalog run)";
+
+/// Source roots of the *latest* catalog run under `prefix` that are not `root`.
+///
+/// Only `doc_kind: run` documents whose prefix matches exactly are considered.
+/// A sibling prefix (`ax-2` when this run is `ax`) is not a collision: the
+/// server filter can over-match a legacy analyzed `prefix` field. Older run
+/// documents are history: after `--replace-prefix` the new folder's run is
+/// the latest, and re-running that folder must not keep demanding the flag.
+/// `started` is an ISO-8601 timestamp, so the greatest string is the latest.
+/// Runs that share that timestamp are one cohort. Duplicate roots collapse
+/// to one line.
+pub fn foreign_prefix_roots(runs: &[Value], prefix: &str, root: &str) -> Vec<String> {
+ let matching: Vec<&Value> = runs
+ .iter()
+ .filter(|run| run.get("doc_kind").and_then(Value::as_str) == Some("run"))
+ .filter(|run| {
+ run.get("prefix")
+ .or_else(|| run.get(CORPUS_SCOPE_FIELD))
+ .and_then(Value::as_str)
+ == Some(prefix)
+ })
+ .collect();
+ let latest = matching
+ .iter()
+ .filter_map(|run| run.get("started").and_then(Value::as_str))
+ .max()
+ .map(str::to_owned);
+ let mut foreign = std::collections::BTreeSet::new();
+ for run in matching {
+ if let Some(started) = &latest {
+ if run.get("started").and_then(Value::as_str) != Some(started.as_str()) {
+ continue;
+ }
+ }
+ let recorded_root = run.get("root").and_then(Value::as_str).unwrap_or("");
+ if recorded_root == root {
+ continue;
+ }
+ if recorded_root.is_empty() {
+ foreign.insert(UNRECORDED_PREFIX_ROOT.to_string());
+ } else {
+ foreign.insert(recorded_root.to_string());
+ }
+ }
+ foreign.into_iter().collect()
+}
+
+/// What a reused prefix will do, for both the refusal and the
+/// `--replace-prefix` warning. `replacing` is true only when the operator
+/// passed the flag and the run is going to continue.
+pub fn prefix_reuse_message(
+ prefix: &str,
+ root: &str,
+ others: &[String],
+ replacing: bool,
+) -> String {
+ let listed = others
+ .iter()
+ .map(|other| format!(" {other}"))
+ .collect::<Vec<_>>()
+ .join("\n");
+ let ending = if replacing {
+ format!(
+ "--replace-prefix is set, so this run continues. Finalize will overwrite catalog \
+ documents keyed ds:{prefix}:<slug> and write into {prefix}-* indices, retiring the \
+ earlier datasets."
+ )
+ } else {
+ "Nothing was written. Pass --replace-prefix to retire those datasets on purpose, or use \
+ one --prefix per source folder. --dry-run does not bypass this check."
+ .to_string()
+ };
+ format!(
+ "autoindex: --prefix {prefix} already indexes a different folder.\n\
+ this run: {root}\n\
+ already indexed from:\n\
+ {listed}\n\
+ Catalog datasets are keyed ds:{prefix}:<slug> and indices are named {prefix}-*. \
+ Finalizing this run overwrites those catalog documents and retires the earlier datasets.\n\
+ A shared prefix also drops per-repo provenance. Each repository indexed as its own \
+ folder has an empty scope, so every one of them becomes the single dataset \
+ {prefix}-docs (catalog id ds:{prefix}:docs). Index the parent folder that contains \
+ the repositories, or pass a distinct --prefix per repository.\n\
+ {ending}"
+ )
+}
+
/// How many dataset detail sections the default map prints before it asks
/// for a page. The summary table always lists every dataset; the per-dataset
/// field tables and sample queries are what blow the map up to hundreds of
@@ -1190,3 +1282,81 @@ mod sample_query_tests {
assert!(super::file_id("ax-a", "k").starts_with("file:ax-a:"));
}
}
+
+#[cfg(test)]
+mod prefix_reuse_tests {
+ use super::*;
+
+ fn run(prefix: &str, root: &str) -> Value {
+ json!({"doc_kind": "run", "prefix": prefix, "root": root})
+ }
+
+ /// Same prefix, different folder: the earlier root is named, and the
+ /// message says finalize retires `ds:<prefix>:<slug>` and that separately
+ /// indexed repos collapse into `<prefix>-docs`.
+ #[test]
+ fn a_different_folder_under_the_same_prefix_is_named() {
+ let runs = vec![
+ run("ref", "/data/stockfish"),
+ run("ref", "/data/stockfish"),
+ run("ref-other", "/data/elsewhere"),
+ json!({"doc_kind": "dataset", "prefix": "ref", "root": "/data/not-a-run"}),
+ ];
+ let foreign = foreign_prefix_roots(&runs, "ref", "/data/lucaschess");
+ assert_eq!(foreign, vec!["/data/stockfish".to_string()]);
+ let message = prefix_reuse_message("ref", "/data/lucaschess", &foreign, false);
+ assert!(message.contains("this run: /data/lucaschess"), "{message}");
+ assert!(message.contains("/data/stockfish"), "{message}");
+ assert!(message.contains("ds:ref:<slug>"), "{message}");
+ assert!(message.contains("ref-*"), "{message}");
+ assert!(message.contains("ref-docs"), "{message}");
+ assert!(message.contains("ds:ref:docs"), "{message}");
+ assert!(message.contains("Nothing was written"), "{message}");
+ assert!(message.contains("--replace-prefix"), "{message}");
+ assert!(
+ !message.contains("/data/elsewhere"),
+ "a sibling prefix is not this corpus: {message}"
+ );
+ }
+
+ /// Re-running the same folder is not a collision, even when older run
+ /// documents for that root are still in the catalog.
+ #[test]
+ fn the_same_folder_is_not_a_collision() {
+ let runs = vec![run("ref", "/data/stockfish"), run("ref", "/data/stockfish")];
+ assert!(foreign_prefix_roots(&runs, "ref", "/data/stockfish").is_empty());
+ }
+
+ /// After `--replace-prefix`, the new folder's run is the latest. Re-running
+ /// that folder must not keep seeing the folder it replaced.
+ #[test]
+ fn the_latest_run_owns_the_prefix() {
+ let runs = vec![
+ json!({"doc_kind":"run","prefix":"ref","root":"/data/old","started":"2026-10-01T00:00:00Z"}),
+ json!({"doc_kind":"run","prefix":"ref","root":"/data/new","started":"2026-10-02T00:00:00Z"}),
+ ];
+ assert!(foreign_prefix_roots(&runs, "ref", "/data/new").is_empty());
+ assert_eq!(
+ foreign_prefix_roots(&runs, "ref", "/data/old"),
+ vec!["/data/new".to_string()]
+ );
+ }
+
+ /// A run that never recorded its root cannot be proved to be this folder.
+ #[test]
+ fn a_run_with_no_root_is_a_collision() {
+ let runs = vec![json!({"doc_kind": "run", "prefix": "ref"})];
+ assert_eq!(
+ foreign_prefix_roots(&runs, "ref", "/data/stockfish"),
+ vec![UNRECORDED_PREFIX_ROOT.to_string()]
+ );
+ }
+
+ #[test]
+ fn replace_prefix_says_the_run_continues() {
+ let message = prefix_reuse_message("ref", "/data/new", &["/data/old".into()], true);
+ assert!(message.contains("--replace-prefix is set"), "{message}");
+ assert!(message.contains("this run continues"), "{message}");
+ assert!(!message.contains("Nothing was written"), "{message}");
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index f3dc4b867..0a31f98eb 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -67,6 +67,10 @@ pub struct IndexCfg {
pub bulk_timeout_secs: u64,
pub snapshot_max_bytes: u64,
pub prefix: String,
+ /// `--replace-prefix`: this folder may take over a prefix whose catalog
+ /// runs were indexed from a different root. Off by default; without it
+ /// that run is refused before anything is written.
+ pub replace_prefix: bool,
pub state_dir: Option<PathBuf>,
pub fresh: bool,
pub follow_symlinks: bool,
@@ -274,7 +278,21 @@ pub fn help_text_with(feedback: bool) -> String {
\x20\x20\x20\x20--bulk-timeout-secs <N>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20bulk HTTP request timeout in seconds (default 300;\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20valid range 1..=3600)\n\
- \x20\x20\x20\x20--prefix <P> index prefix (default ax)\n\
+ \x20\x20\x20\x20--prefix <P> index prefix (default ax). One prefix is one\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20source folder. The same prefix on a different\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20folder is refused: datasets are keyed\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20ds:<prefix>:<slug> and indices are <prefix>-*,\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20so finalize overwrites the earlier datasets.\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Several repositories under one prefix also\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20collapse: each repo indexed on its own has an\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20empty scope and becomes the single dataset\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<prefix>-docs. Use one --prefix per folder,\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20or index the parent folder once\n\
+ \x20\x20\x20\x20--replace-prefix retire datasets already stored under --prefix\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20that were indexed from a different folder.\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Prints those folders and continues. Without\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20this flag that run is refused and nothing\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20is written. --dry-run does not bypass it\n\
\x20\x20\x20\x20--state-dir <PATH> resume journal location (default ~/.xerj/autoindex/<hash>/);\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20for an s3:// source this is also where the local\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20object mirror lives, so point it at a disk with room\n\
@@ -721,6 +739,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
let mut snapshot_max_bytes = 64u64 << 30;
let mut bulk_timeout_explicit = false;
let mut prefix = "ax".to_string();
+ let mut replace_prefix = false;
let mut prefix_explicit = false;
let mut state_dir: Option<PathBuf> = None;
let mut endpoint_url: Option<String> = None;
@@ -856,6 +875,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
prefix = it.next().ok_or("--prefix needs a value")?;
prefix_explicit = true;
}
+ "--replace-prefix" => replace_prefix = true,
"--state-dir" => state_dir = it.next().map(PathBuf::from),
"--endpoint-url" => {
let value = it.next().ok_or(
@@ -1633,6 +1653,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
bulk_timeout_secs,
snapshot_max_bytes,
prefix,
+ replace_prefix,
state_dir,
fresh,
follow_symlinks,
@@ -2694,6 +2715,22 @@ mod tests {
}
}
+ #[test]
+ fn replace_prefix_is_off_unless_asked_and_help_names_the_refusal() {
+ assert!(!index(&["data", "--prefix", "ref"]).replace_prefix);
+ assert!(index(&["data", "--prefix", "ref", "--replace-prefix"]).replace_prefix);
+ let help = super::help_text();
+ assert!(help.contains("--replace-prefix"), "{help}");
+ assert!(
+ help.contains("ds:<prefix>:<slug>"),
+ "help must say how catalog ids collide: {help}"
+ );
+ assert!(
+ help.contains("<prefix>-docs"),
+ "help must say a shared prefix collapses per-repo provenance: {help}"
+ );
+ }
+
/// #1586: a second positional folder used to fall through to
/// `unknown argument: repoB`, which reads as if the first folder were
/// refused and says nothing about how to index both. The refusal must
diff --git a/engine/crates/xerj-autoindex/src/detect/e2e.rs b/engine/crates/xerj-autoindex/src/detect/e2e.rs
index cdbd4d2df..9552fe47c 100644
--- a/engine/crates/xerj-autoindex/src/detect/e2e.rs
+++ b/engine/crates/xerj-autoindex/src/detect/e2e.rs
@@ -356,6 +356,7 @@ pub(super) fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {
bulk_timeout_secs: 300,
snapshot_max_bytes: 64 << 30,
prefix: "ax".into(),
+ replace_prefix: false,
state_dir: Some(state_dir.to_owned()),
fresh: false,
follow_symlinks: false,
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 b6e049151..580ddbf0b 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -792,6 +792,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {
bulk_timeout_secs: 3_600,
snapshot_max_bytes: 64 << 30,
prefix: "failure-test".into(),
+ replace_prefix: false,
state_dir: Some(state_dir.to_owned()),
fresh: false,
follow_symlinks: false,
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 3fcd69ab9..4fb6d5415 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -948,6 +948,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str, semantic: bool) -> IndexCfg {
bulk_timeout_secs: 30,
snapshot_max_bytes: 64 << 30,
prefix: "incremental-http".into(),
+ replace_prefix: false,
state_dir: Some(state_dir.to_owned()),
fresh: false,
follow_symlinks: false,
diff --git a/engine/crates/xerj-autoindex/src/label_http_tests.rs b/engine/crates/xerj-autoindex/src/label_http_tests.rs
index 6a9fe920c..1512124d3 100644
--- a/engine/crates/xerj-autoindex/src/label_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/label_http_tests.rs
@@ -369,6 +369,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str, label: &Path) -> IndexCfg {
bulk_timeout_secs: 30,
snapshot_max_bytes: 64 << 30,
prefix: "label-http".into(),
+ replace_prefix: false,
state_dir: Some(state_dir.to_owned()),
fresh: false,
follow_symlinks: false,
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index d4d2d247b..3adc1f674 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -3064,6 +3064,7 @@ mod phase_a_grouping_tests {
bulk_timeout_secs: 10,
snapshot_max_bytes: 64 << 30,
prefix: "t".into(),
+ replace_prefix: false,
state_dir: None,
fresh: true,
follow_symlinks: false,
@@ -5865,6 +5866,35 @@ fn legacy_rebuild_argv(cfg: &IndexCfg, state_dir: &Path, prefix: &str) -> Vec<St
argv
}
+/// Run documents in the shared catalog whose `prefix` term-matches.
+///
+/// A missing catalog is an empty list: the first index of a node has nothing
+/// to collide with. Any other search failure is returned — skipping the
+/// check on a 401 or a 500 would let the overwrite this guard exists to stop
+/// proceed. The caller re-checks the prefix exactly; a legacy analyzed
+/// `prefix` field can over-return sibling corpora.
+fn catalog_runs_for_prefix(es: &Es, prefix: &str) -> Result<Vec<Value>> {
+ let body = json!({
+ "size": 500,
+ "query": {"bool": {"filter": [
+ {"term": {"doc_kind": "run"}},
+ {"term": {"prefix": prefix}}
+ ]}}
+ });
+ let Some(page) = es.search_present(catalog::CATALOG_INDEX, &body)? else {
+ return Ok(Vec::new());
+ };
+ Ok(page
+ .pointer("/hits/hits")
+ .and_then(Value::as_array)
+ .map(|hits| {
+ hits.iter()
+ .filter_map(|hit| hit.get("_source").cloned())
+ .collect()
+ })
+ .unwrap_or_default())
+}
+
fn run_index_report_inner(
mut cfg: IndexCfg,
tally: &ScanTally,
@@ -6009,6 +6039,44 @@ fn run_index_report_inner(
.state_dir
.clone()
.unwrap_or_else(|| state::default_state_dir(&root_str, &cfg.url, &cfg.prefix));
+ // Same --prefix on a different folder overwrites catalog ids
+ // `ds:{prefix}:{slug}` and writes into `{prefix}-*` at finalize. The
+ // journals do not share a state dir (the default key includes the root),
+ // so nothing local notices a *new* folder. Refuse before preflight
+ // creates state, and before --dry-run walks the tree. --replace-prefix
+ // is the explicit opt-in; it prints the same facts and continues.
+ //
+ // A journal that already binds this state dir to this root, url, and
+ // prefix is a resume or an incremental re-run of the same folder,
+ // including one the local plan / `--fresh` gates are about to refuse.
+ // Those refusals promise the only remote call is the readiness GET, so
+ // this guard must not search the catalog on that path. A different
+ // folder has no such journal and still hits the check.
+ if !state::journal_continues_folder(&state_dir, &root_str, &cfg.url, &cfg.prefix) {
+ let foreign_roots = catalog::foreign_prefix_roots(
+ &catalog_runs_for_prefix(&es, &cfg.prefix)?,
+ &cfg.prefix,
+ &root_str,
+ );
+ if !foreign_roots.is_empty() {
+ let message = catalog::prefix_reuse_message(
+ &cfg.prefix,
+ &root_str,
+ &foreign_roots,
+ cfg.replace_prefix,
+ );
+ if cfg.replace_prefix {
+ // `warn` replaces newlines (they are not a safe display char), so
+ // each sentence is its own line. The refusal below keeps the
+ // newlines: it is an error, not a progress record.
+ for line in message.lines() {
+ pr.warn(line);
+ }
+ } else {
+ anyhow::bail!("{message}");
+ }
+ }
+ }
// Acquire state authority before discovery as well as hashing. A waiter
// must never classify a path snapshot taken while another owner was
// publishing or replacing the durable plan.
diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rs
index 6520a1db3..c02ef0efb 100644
--- a/engine/crates/xerj-autoindex/src/state.rs
+++ b/engine/crates/xerj-autoindex/src/state.rs
@@ -96,7 +96,10 @@ pub struct PlanDataset {
#[cfg(test)]
mod tests {
- use super::{acquire_watch_ownership, run_id_in_second, Journal, StateLock, WATCH_OWNER_LOCK};
+ use super::{
+ acquire_watch_ownership, journal_continues_folder, run_id_in_second, Journal, StateLock,
+ WATCH_OWNER_LOCK,
+ };
/// `flock` ownership follows the open file description, so an inherited
/// descriptor can unlock the acquiring parent's lock. Model that post-fork
@@ -429,6 +432,39 @@ mod tests {
}
}
+ /// The prefix guard skips its catalog read only when the journal already
+ /// belongs to this folder. A different root, a different prefix, and a
+ /// missing journal all stay on the catalog-check path.
+ #[test]
+ fn journal_continues_folder_matches_only_the_recorded_run() {
+ let dir = tempfile::tempdir().unwrap();
+ assert!(!journal_continues_folder(
+ dir.path(),
+ "root",
+ "url",
+ "prefix"
+ ));
+ drop(Journal::open(dir.path(), "root", "url", "prefix", 300, true).unwrap());
+ assert!(journal_continues_folder(
+ dir.path(),
+ "root",
+ "url",
+ "prefix"
+ ));
+ assert!(!journal_continues_folder(
+ dir.path(),
+ "other-root",
+ "url",
+ "prefix"
+ ));
+ assert!(!journal_continues_folder(
+ dir.path(),
+ "root",
+ "url",
+ "other-prefix"
+ ));
+ }
+
/// A readable journal must not be reported as unreadable just because the
/// run asked for `--fresh`; the note is a discarded-state warning, not a
/// `--fresh` banner.
@@ -773,6 +809,47 @@ pub fn default_state_dir(root: &str, url: &str, prefix: &str) -> PathBuf {
.join(crate::ids::state_key(root, url, prefix))
}
+/// Whether `state_dir` already holds a journal run for this exact root, url,
+/// and prefix.
+///
+/// A same-folder resume, an incremental re-run, and a locally refused
+/// `--fresh` all re-enter through that journal. The prefix-collision guard
+/// must not query the catalog on that path: those refusals are local, and
+/// the HTTP fixtures require that a refused attempt perform only the
+/// readiness GET. A different folder does not satisfy this — the default
+/// state directory includes the root, and an explicit state directory
+/// recorded for another root or prefix compares unequal — so the catalog
+/// check still runs for it.
+///
+/// An absent, unreadable, or corrupt journal is not a continuation, and
+/// neither is a journal whose `run` record names something else. This reads
+/// the file and does not create the directory or take the state lock.
+pub fn journal_continues_folder(state_dir: &Path, root: &str, url: &str, prefix: &str) -> bool {
+ let Ok(text) = std::fs::read_to_string(state_dir.join("journal.ndjson")) else {
+ return false;
+ };
+ let mut saw_match = false;
+ for line in text.lines() {
+ if line.is_empty() {
+ continue;
+ }
+ let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
+ return false;
+ };
+ if value.get("kind").and_then(|kind| kind.as_str()) != Some("run") {
+ continue;
+ }
+ let recorded_root = value.get("root").and_then(|v| v.as_str()).unwrap_or("");
+ let recorded_url = value.get("url").and_then(|v| v.as_str()).unwrap_or("");
+ let recorded_prefix = value.get("prefix").and_then(|v| v.as_str()).unwrap_or("");
+ if recorded_root != root || recorded_url != url || recorded_prefix != prefix {
+ return false;
+ }
+ saw_match = true;
+ }
+ saw_match
+}
+
fn apply_legacy_plan(
plan: Plan,
committed: &mut Option<crate::sync::CommittedManifest>,
diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rs
index 5ce99fa86..9b45a1c2c 100644
--- a/engine/crates/xerj-server/src/brain.rs
+++ b/engine/crates/xerj-server/src/brain.rs
@@ -617,6 +617,7 @@ fn index_cfg(cfg: &BrainCfg, brain: &str, api_key: Option<String>) -> IndexCfg {
bulk_timeout_secs: 300,
snapshot_max_bytes: 64u64 << 30,
prefix: "ax".into(),
+ replace_prefix: false,
state_dir: None,
fresh: cfg.fresh,
follow_symlinks: false,