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): #416 scope catalog doc IDs by corpus prefix (no cross-corpus overwrite)

xerj-org7b21a2e9b73f
diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rs
index 927af2ba6..9ab7b8aec 100644
--- a/engine/crates/xerj-autoindex/src/catalog.rs
+++ b/engine/crates/xerj-autoindex/src/catalog.rs
@@ -123,6 +123,8 @@ pub const GOTCHAS: &[&str] = &[
];
pub struct DatasetDocInput<'a> {
+ /// Corpus scope (`--prefix`): keeps catalog ids from colliding across corpora (#416).
+ pub prefix: &'a str,
pub pd: &'a PlanDataset,
pub record_count: u64,
pub junk_records: u64,
@@ -142,7 +144,7 @@ pub struct DatasetDocInput<'a> {
}
pub fn dataset_doc(inp: &DatasetDocInput) -> (String, Value) {
- let id = format!("ds:{}", inp.pd.slug);
+ let id = format!("ds:{}:{}", inp.prefix, inp.pd.slug);
let fields_json = serde_json::to_string(&inp.pd.specs).unwrap_or_else(|_| "[]".into());
let doc = json!({
"doc_kind": "dataset",
@@ -170,12 +172,13 @@ pub fn dataset_doc(inp: &DatasetDocInput) -> (String, Value) {
/// Catalog document id for a file. One definition, because the sweep that
/// removes a junk/skipped file's document (`lib.rs`, "stale junk-catalog
/// sweep") has to name the id without holding the document.
-pub fn file_id(file_key: &str) -> String {
- format!("file:{file_key}")
+pub fn file_id(prefix: &str, file_key: &str) -> String {
+ format!("file:{prefix}:{file_key}")
}
#[allow(clippy::too_many_arguments)] // 1:1 with the file-status doc's fields
pub fn file_doc(
+ prefix: &str,
file_key: &str,
path: &str,
format: &str,
@@ -187,7 +190,7 @@ pub fn file_doc(
run_id: &str,
) -> (String, Value) {
(
- file_id(file_key),
+ file_id(prefix, file_key),
json!({
"doc_kind": "file",
"file_key": file_key,
@@ -204,6 +207,7 @@ pub fn file_doc(
}
pub fn duplicate_file_doc(
+ prefix: &str,
file_key: &str,
path: &str,
path_id: &str,
@@ -211,7 +215,7 @@ pub fn duplicate_file_doc(
bytes: u64,
run_id: &str,
) -> (String, Value) {
- let alias_id = duplicate_file_id(file_key, path, path_id);
+ let alias_id = duplicate_file_id(prefix, file_key, path, path_id);
(
alias_id,
json!({
@@ -230,10 +234,11 @@ pub fn duplicate_file_doc(
)
}
-pub fn duplicate_file_id(file_key: &str, path: &str, path_id: &str) -> String {
+pub fn duplicate_file_id(prefix: &str, file_key: &str, path: &str, path_id: &str) -> String {
let identity = if path_id.is_empty() { path } else { path_id };
format!(
- "file-alias:{}",
+ "file-alias:{}:{}",
+ prefix,
crate::ids::doc_id("duplicate-file", file_key, identity)
)
}
@@ -779,4 +784,23 @@ mod sample_query_tests {
assert!(full_text["body"].get("_source").is_none());
assert!(full_text["body"].get("fields").is_none());
}
+
+ /// #416 (data-loss): the shared `autoindex-catalog` index is written by
+ /// every corpus, so its doc ids MUST be scoped by the corpus `--prefix` —
+ /// otherwise two corpora indexing the same file key (or producing the same
+ /// slug) overwrite each other's catalog entry. FAIL-BEFORE: dropping the
+ /// prefix from the id bodies makes these `assert_ne!` collide.
+ #[test]
+ fn catalog_ids_are_prefix_scoped_across_corpora() {
+ // Same key, different corpus prefix -> distinct ids (no overwrite).
+ assert_ne!(super::file_id("ax-a", "k"), super::file_id("ax-b", "k"));
+ assert_ne!(
+ super::duplicate_file_id("ax-a", "k", "p", "pi"),
+ super::duplicate_file_id("ax-b", "k", "p", "pi"),
+ );
+ // Idempotent within one corpus (a re-run must upsert, not duplicate).
+ assert_eq!(super::file_id("ax-a", "k"), super::file_id("ax-a", "k"));
+ // The prefix is actually in the id (not just concatenated key).
+ assert!(super::file_id("ax-a", "k").starts_with("file:ax-a:"));
+ }
}
diff --git a/engine/crates/xerj-autoindex/src/generation_catalog.rs b/engine/crates/xerj-autoindex/src/generation_catalog.rs
index 11b8c05d8..c4b1a8414 100644
--- a/engine/crates/xerj-autoindex/src/generation_catalog.rs
+++ b/engine/crates/xerj-autoindex/src/generation_catalog.rs
@@ -109,6 +109,7 @@ pub fn project_generation(
let format = assignment_format(assignment.family.as_str(), assignment.gzip);
code.observe(&format, group.expected_records);
let (id, doc) = catalog::file_doc(
+ &execution.prefix,
&group.content_id,
&group.canonical.rel,
&format,
@@ -122,6 +123,7 @@ pub fn project_generation(
insert_unique(&mut documents, id, doc)?;
for alias in &group.aliases {
let (id, doc) = catalog::duplicate_file_doc(
+ &execution.prefix,
&group.content_id,
&alias.rel,
&alias.path_id,
@@ -138,6 +140,7 @@ pub fn project_generation(
// these cannot double-count the groups above.
code.observe(&junk.format, 0);
let (id, doc) = catalog::file_doc(
+ &execution.prefix,
&junk.file_key,
&junk.rel,
&junk.format,
@@ -176,6 +179,7 @@ pub fn project_generation(
formats.sort();
formats.dedup();
let (id, doc) = catalog::dataset_doc(&catalog::DatasetDocInput {
+ prefix: &execution.prefix,
pd: dataset,
record_count: stats.record_count,
junk_records: stats.junk_records,
@@ -283,23 +287,23 @@ pub fn expected_ax_run<'a>(
}
#[cfg(test)]
-fn managed_non_run_ids(plan: &crate::state::Plan) -> BTreeSet<String> {
+fn managed_non_run_ids(prefix: &str, plan: &crate::state::Plan) -> BTreeSet<String> {
+ // #416: these prior-generation ids MUST match the write path's (prefixed)
+ // ids exactly, or the stale-sweep never removes them → orphan rows.
let mut ids = BTreeSet::new();
- ids.extend(plan.files.keys().map(|key| format!("file:{key}")));
+ ids.extend(plan.files.keys().map(|key| catalog::file_id(prefix, key)));
ids.extend(
plan.junk_files
.iter()
- .map(|junk| format!("file:{}", junk.file_key)),
- );
- ids.extend(
- plan.duplicate_files
- .iter()
- .map(|alias| catalog::duplicate_file_id(&alias.file_key, &alias.rel, &alias.path_id)),
+ .map(|junk| catalog::file_id(prefix, &junk.file_key)),
);
+ ids.extend(plan.duplicate_files.iter().map(|alias| {
+ catalog::duplicate_file_id(prefix, &alias.file_key, &alias.rel, &alias.path_id)
+ }));
ids.extend(
plan.datasets
.iter()
- .map(|dataset| format!("ds:{}", dataset.slug)),
+ .map(|dataset| format!("ds:{}:{}", prefix, dataset.slug)),
);
ids
}
@@ -571,7 +575,7 @@ mod tests {
&metadata("generation-2"),
&stats(),
&BTreeMap::new(),
- &managed_non_run_ids(&base.plan),
+ &managed_non_run_ids("ax", &base.plan),
)
.unwrap();
@@ -581,7 +585,7 @@ mod tests {
.values()
.all(|doc| { doc.get("run_id").and_then(Value::as_str) == Some("generation-2") }));
assert_eq!(
- projection.documents["file:keep"]["run_id"], "generation-2",
+ projection.documents["file:ax:keep"]["run_id"], "generation-2",
"an unchanged peer remains visible in the latest data map"
);
}
@@ -645,18 +649,19 @@ mod tests {
&metadata("generation-2"),
&no_dataset_stats,
&BTreeMap::new(),
- &managed_non_run_ids(&base.plan),
+ &managed_non_run_ids("ax", &base.plan),
)
.unwrap();
- assert_eq!(projection.documents["file:indexed"]["status"], "junk");
- assert!(projection.stale_ids.contains("file:old-junk"));
+ assert_eq!(projection.documents["file:ax:indexed"]["status"], "junk");
+ assert!(projection.stale_ids.contains("file:ax:old-junk"));
assert!(projection.stale_ids.contains(&catalog::duplicate_file_id(
+ "ax",
&duplicate.file_key,
&duplicate.rel,
&duplicate.path_id
)));
- assert!(!projection.stale_ids.contains("file:indexed"));
+ assert!(!projection.stale_ids.contains("file:ax:indexed"));
}
#[test]
@@ -690,7 +695,7 @@ mod tests {
&metadata("g2"),
&stats(),
&BTreeMap::new(),
- &managed_non_run_ids(&base.plan),
+ &managed_non_run_ids("ax", &base.plan),
)
.unwrap();
projection.validate_observed(&projection.documents).unwrap();
@@ -700,7 +705,7 @@ mod tests {
assert!(projection.validate_observed(&missing).is_err());
let mut changed = projection.documents.clone();
- changed.get_mut("ds:reports").unwrap()["record_count"] = json!(999);
+ changed.get_mut("ds:ax:reports").unwrap()["record_count"] = json!(999);
assert!(projection.validate_observed(&changed).is_err());
}
}
diff --git a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs
index f485819d5..fa879e5e8 100644
--- a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs
@@ -222,24 +222,26 @@ fn plan(indexed: &[(&str, &str)], junk_files: Vec<JunkFile>) -> Plan {
fn prior_managed_ids(base: &CommittedManifest) -> BTreeSet<String> {
let mut ids = BTreeSet::new();
- ids.extend(base.plan.files.keys().map(|key| format!("file:{key}")));
ids.extend(
base.plan
- .junk_files
- .iter()
- .map(|junk| format!("file:{}", junk.file_key)),
+ .files
+ .keys()
+ .map(|key| catalog::file_id("ax", key)),
);
ids.extend(
base.plan
- .duplicate_files
+ .junk_files
.iter()
- .map(|alias| catalog::duplicate_file_id(&alias.file_key, &alias.rel, &alias.path_id)),
+ .map(|junk| catalog::file_id("ax", &junk.file_key)),
);
+ ids.extend(base.plan.duplicate_files.iter().map(|alias| {
+ catalog::duplicate_file_id("ax", &alias.file_key, &alias.rel, &alias.path_id)
+ }));
ids.extend(
base.plan
.datasets
.iter()
- .map(|dataset| format!("ds:{}", dataset.slug)),
+ .map(|dataset| format!("ds:ax:{}", dataset.slug)),
);
ids
}
@@ -274,8 +276,8 @@ fn junk_only_add_change_and_delete_converge_without_hiding_unchanged_data() {
)
.unwrap();
endpoint.publish(&projection, &BTreeSet::new()).unwrap();
- assert_eq!(endpoint.documents["file:junk-a"]["status"], "junk");
- assert_eq!(endpoint.documents["file:keep"]["run_id"], "g2");
+ assert_eq!(endpoint.documents["file:ax:junk-a"]["status"], "junk");
+ assert_eq!(endpoint.documents["file:ax:keep"]["run_id"], "g2");
let base = committed(added);
let changed = generation(
@@ -298,7 +300,7 @@ fn junk_only_add_change_and_delete_converge_without_hiding_unchanged_data() {
.unwrap();
endpoint.publish(&projection, &BTreeSet::new()).unwrap();
assert_eq!(
- endpoint.documents["file:junk-a"]["reason"],
+ endpoint.documents["file:ax:junk-a"]["reason"],
"unsupported archive"
);
@@ -318,10 +320,10 @@ fn junk_only_add_change_and_delete_converge_without_hiding_unchanged_data() {
&prior_managed_ids(&base),
)
.unwrap();
- assert!(projection.stale_ids.contains("file:junk-a"));
+ assert!(projection.stale_ids.contains("file:ax:junk-a"));
endpoint.publish(&projection, &BTreeSet::new()).unwrap();
- assert!(!endpoint.documents.contains_key("file:junk-a"));
- assert_eq!(endpoint.documents["file:keep"]["run_id"], "g4");
+ assert!(!endpoint.documents.contains_key("file:ax:junk-a"));
+ assert_eq!(endpoint.documents["file:ax:keep"]["run_id"], "g4");
}
#[test]
@@ -353,8 +355,8 @@ fn indexed_and_junk_transitions_replace_the_same_catalog_identity() {
&prior_managed_ids(&base),
)
.unwrap();
- assert_eq!(junk_projection.documents["file:same"]["status"], "junk");
- assert!(!junk_projection.stale_ids.contains("file:same"));
+ assert_eq!(junk_projection.documents["file:ax:same"]["status"], "junk");
+ assert!(!junk_projection.stale_ids.contains("file:ax:same"));
let base = committed(became_junk);
let indexed_again = generation(
@@ -372,8 +374,8 @@ fn indexed_and_junk_transitions_replace_the_same_catalog_identity() {
&prior_managed_ids(&base),
)
.unwrap();
- assert_eq!(projection.documents["file:same"]["status"], "indexed");
- assert!(!projection.stale_ids.contains("file:same"));
+ assert_eq!(projection.documents["file:ax:same"]["status"], "indexed");
+ assert!(!projection.stale_ids.contains("file:ax:same"));
}
#[test]
@@ -435,12 +437,16 @@ fn exact_run_dataset_file_ids_and_payloads_are_generation_bound() {
.keys()
.cloned()
.collect::<BTreeSet<_>>(),
- BTreeSet::from(["ds:reports".into(), "file:report".into(), "run:g2".into()])
+ BTreeSet::from([
+ "ds:ax:reports".into(),
+ "file:ax:report".into(),
+ "run:g2".into()
+ ])
);
assert_eq!(projection.documents["run:g2"]["records_total"], 2);
assert_eq!(projection.documents["run:g2"]["files_total"], 1);
- assert_eq!(projection.documents["ds:reports"]["record_count"], 2);
- assert_eq!(projection.documents["file:report"]["records"], 2);
+ assert_eq!(projection.documents["ds:ax:reports"]["record_count"], 2);
+ assert_eq!(projection.documents["file:ax:report"]["records"], 2);
assert!(projection
.documents
.values()
@@ -483,7 +489,7 @@ fn stale_alias_and_independently_observed_correlation_are_deleted() {
&observed_prior,
)
.unwrap();
- let alias_id = catalog::duplicate_file_id(&alias.file_key, &alias.rel, &alias.path_id);
+ let alias_id = catalog::duplicate_file_id("ax", &alias.file_key, &alias.rel, &alias.path_id);
assert!(projection.stale_ids.contains(&alias_id));
let mut endpoint = CatalogEndpoint::default();
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 e3d5fda61..04b201ce7 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -1493,7 +1493,7 @@ fn a_multi_table_dump_reconciles_each_dataset_against_its_own_sealed_count() {
for doc in endpoint.data_docs() {
let slug = doc["ax_dataset"].as_str().unwrap().to_owned();
assert!(
- dataset_docs.contains_key(&format!("ds:{slug}")),
+ dataset_docs.contains_key(&format!("ds:incremental-http:{slug}")),
"record published under an uncatalogued dataset {slug}"
);
}
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index fab6fc371..5bd18f150 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -3552,11 +3552,9 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
let needs_alias_path_migration = !plan.alias_paths_indexed;
let previous_aliases = plan.duplicate_files.clone();
alias_paths_to_replace.extend(previous_aliases.iter().map(|alias| alias.rel.clone()));
- stale_alias_ids.extend(
- plan.duplicate_files
- .iter()
- .map(|old| catalog::duplicate_file_id(&old.file_key, &old.rel, &old.path_id)),
- );
+ stale_alias_ids.extend(plan.duplicate_files.iter().map(|old| {
+ catalog::duplicate_file_id(&cfg.prefix, &old.file_key, &old.rel, &old.path_id)
+ }));
let selected_plan_keys =
select_resume_plan_keys(&inventory.files, &inventory.keys, plan, &journal_path)?;
for (index, planned_key) in selected_plan_keys.into_iter().enumerate() {
@@ -3634,7 +3632,9 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
let current_alias_ids: std::collections::HashSet<String> = inventory
.duplicates
.iter()
- .map(|alias| catalog::duplicate_file_id(&alias.file_key, &alias.rel, &alias.path_id))
+ .map(|alias| {
+ catalog::duplicate_file_id(&cfg.prefix, &alias.file_key, &alias.rel, &alias.path_id)
+ })
.collect();
stale_alias_ids.retain(|id| !current_alias_ids.contains(id));
// The historical global flag cannot identify which live documents
@@ -5328,7 +5328,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
for key in &swept_junk_keys {
let action = json!({"delete": {
"_index": catalog::CATALOG_INDEX,
- "_id": catalog::file_id(key),
+ "_id": catalog::file_id(&cfg.prefix, key),
}});
cat_buf.extend_from_slice(action.to_string().as_bytes());
cat_buf.push(b'\n');
@@ -5385,6 +5385,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
formats.dedup();
let (tmin, tmax) = ds_timerange.get(&d.slug).cloned().unwrap_or((None, None));
let (id, doc) = catalog::dataset_doc(&catalog::DatasetDocInput {
+ prefix: &cfg.prefix,
pd: d,
record_count: *ds_counts.get(&d.slug).unwrap_or(&0),
junk_records: durable.junk,
@@ -5429,6 +5430,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
.unwrap_or_else(|| "unknown".into());
code_coverage.observe(&fmt, fd.records);
let (id, doc) = catalog::file_doc(
+ &cfg.prefix,
&fd.file_key,
current_path,
&fmt,
@@ -5489,6 +5491,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
for jf in &all_junk {
code_coverage.observe(&jf.format, 0);
let (id, doc) = catalog::file_doc(
+ &cfg.prefix,
&jf.file_key,
&jf.rel,
&jf.format,
@@ -5504,6 +5507,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
}
for duplicate in &plan.duplicate_files {
let (id, doc) = catalog::duplicate_file_doc(
+ &cfg.prefix,
&duplicate.file_key,
&duplicate.rel,
&duplicate.path_id,