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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(autoindex): the duplicate-alias sweep is scoped to this corpus, per hit (#905) (#911)
xerj-org980b26296906
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cc3a6cfb2..0209c6664 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -234,6 +234,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0separate work: it has to prove the #825 union/sum contract with tombstonespresent, and is not attempted here.+- **`autoindex`: a run no longer deletes a sibling corpus's duplicate-alias+ catalog documents** ([#905](https://github.com/xerj-org/xerj/issues/905)).+ Data loss, and the second of the two holes the #890 review found.+ `autoindex-catalog` is one index shared by every corpus on the node, but the+ duplicate-alias sweep issued at the end of a run was+ `{"bool": {"filter": [{"term": {"status": "duplicate"}}, {"terms": {"path":+ [...]}}]}}` with **no corpus scope at all** — and `path` is a logical path+ inside a corpus, not a node-unique key. Two checkouts on one node that each+ carry `LICENSE` and `vendor/LICENSE` is the ordinary shape of that, and a+ delete is not recoverable. Unlike #890 this needed no legacy mapping: it was+ unscoped on a current `keyword` catalog too.++ The query still selects the candidates — it is what keeps the candidate set+ small — but the scope is now applied per hit and the deletes go by `_id`, the+ pattern #890's `delete_catalog_docs_scoped` introduced (both sweeps share one+ page walk now, so there is one copy of its paging rules rather than two). A+ simple scope filter would have traded one defect for another, which is why+ this was split out of #896 rather than folded into it: the sweep exists+ *because* alias ids changed as identity evolved, and its oldest targets+ (v1.0.0-rc.10..rc.56, before #416 put the corpus prefix into the `_id`) carry+ no corpus field and no prefix in their id, so a server-side+ `corpus_scope`/`prefix` term would simply stop matching them. Attribution is+ therefore layered: `corpus_scope` (#755), else `prefix` (#737) read from raw+ `_source`, else the prefix in the `_id` (#416). Below that the document names+ no corpus at all, and rather than guess in either direction the sweep deletes+ such a hit only when its `_id` is one this corpus itself would have written+ under the pre-#416 scheme — the reconstruct-the-id move #739 already makes —+ and otherwise leaves it in place and says so, by path and id, in a new+ non-fatal note. The sweep stays non-fatal (#345) throughout.++ Scope, stated rather than implied: this is the legacy (graph) run path only.+ A `--no-graph` run returns from the generated path long before this sweep and+ retires stale catalog documents by their prefix-scoped `_id`+ (`generation_catalog::managed_non_run_ids`), which was never unscoped.+- **`--embed-mode neural`: re-indexing an unchanged corpus no longer fails,and the identity can now tell one model from another**([#487](https://github.com/xerj-org/xerj/issues/487),diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rsindex daee0b289..c75699bab 100644--- a/engine/crates/xerj-autoindex/src/catalog.rs+++ b/engine/crates/xerj-autoindex/src/catalog.rs@@ -296,12 +296,44 @@ pub fn duplicate_file_doc(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:{}:{}",+ "{ALIAS_ID_PREFIX}{}:{}",prefix,crate::ids::doc_id("duplicate-file", file_key, identity))}+/// The `file-alias:` prefix every alias id has carried since v1.0.0-rc.10.+pub const ALIAS_ID_PREFIX: &str = "file-alias:";++/// Every `_id` a **pre-#416** build could have written for this alias.+///+/// #416 (v1.0.0-rc.57) put the corpus prefix into the id —+/// `file-alias:{prefix}:{body}`. Before it, from rc.10 (`c529e604`) onwards,+/// the id was `file-alias:{body}` with the identical body, and the document+/// carried no corpus field either (`prefix` arrived with #737/rc.68,+/// [`CORPUS_SCOPE_FIELD`] with #755). Such a document therefore names no+/// corpus anywhere, which is why #905's sweep reconstructs the ids its OWN+/// corpus would have written instead of guessing from the document.+///+/// Two candidates, not one, because `path_id` is `#[serde(default)]` on+/// `state::DuplicateFile`: a plan written before this alias's `path_id` was+/// recorded produced `identity = path`, and the same plan today produces+/// `identity = path_id`. The two coincide when `path_id` is empty, and the+/// caller collects them into a set.+pub fn unprefixed_duplicate_file_ids(file_key: &str, path: &str, path_id: &str) -> Vec<String> {+ let mut ids = vec![format!(+ "{ALIAS_ID_PREFIX}{}",+ crate::ids::doc_id("duplicate-file", file_key, path)+ )];+ if !path_id.is_empty() {+ ids.push(format!(+ "{ALIAS_ID_PREFIX}{}",+ crate::ids::doc_id("duplicate-file", file_key, path_id)+ ));+ }+ ids+}+/// Build the five ready-to-send query classes for a dataset./// Only verified-working forms are ever emitted.pub fn build_sample_queries(pd: &PlanDataset, correlations: &[KeyCorr]) -> Vec<Value> {diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex 0fdf40d12..a9e2a5d6a 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -109,6 +109,11 @@ struct MockState {/// with a 500 whose body names the condition. Scoped to the one call so/// the fixture proves the sweep is what wedged the run (#345), not that a/// server which 500s everything fails.+ ///+ /// #905: the sweep is a candidate `_search` followed by a by-`_id` delete+ /// now, not one `_delete_by_query`, so the fault is injected on the search.+ /// It is still the first and only server call the sweep makes, which is+ /// what the fixture needs.fail_alias_sweep: bool,/// One entry per alias-sweep request, holding the paths it named. The/// sweep used to be one round trip per duplicate path, so the batching is@@ -316,10 +321,53 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {.pointer("/query/term/file_key").and_then(Value::as_str).map(str::to_owned);+ // #905: the scoped catalog sweeps delete by exact `_id` now — the+ // corpus scope is decided client-side, per hit, so the delete carries+ // no predicate at all beyond the id list.+ let ids: Vec<String> = query+ .pointer("/query/ids/values")+ .and_then(Value::as_array)+ .map(|values| {+ values+ .iter()+ .filter_map(Value::as_str)+ .map(str::to_owned)+ .collect()+ })+ .unwrap_or_default();+ let mut locked = state.lock().unwrap();+ locked.delete_calls += 1;+ if let Some(key) = ax_file {+ locked+ .docs+ .retain(|_, doc| doc.get("ax_file").and_then(Value::as_str) != Some(key.as_str()));+ }+ if let Some(key) = file_key {+ locked+ .catalog_docs+ .retain(|_, doc| doc.get("file_key").and_then(Value::as_str) != Some(key.as_str()));+ }+ // Catalog only: every by-`_id` delete this client issues names+ // `catalog::CATALOG_INDEX`.+ for id in &ids {+ locked.catalog_docs.remove(id);+ }+ (200, json!({"deleted": ids.len(), "failures": []}))+ } else if method == "GET" && path.ends_with("/_count") {+ (200, json!({"count": state.lock().unwrap().docs.len()}))+ } else if method == "POST" && path.ends_with("/_search") {+ // Report the REAL number of stored docs: `run_index` verifies live+ // counts against the journal (#195), so a mock that always answered 0+ // hits would (rightly) fail every successful run. The generated path+ // additionally reads back per-file and per-catalog projections, so the+ // count is filtered by whichever identity the query names.+ let query: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);// The catalog's duplicate-alias sweep. Recognised by SHAPE — a// `status: duplicate` filter beside a `path` terms list — because// since #345 one request carries a whole chunk of paths rather than- // one path per round trip.+ // one path per round trip. #905 moved it from `_delete_by_query` to a+ // candidate `_search`: the query is the same, and it is still one+ // request per chunk, which is what the batching assertion measures.let filter = query.pointer("/query/bool/filter").and_then(Value::as_array)@@ -343,85 +391,83 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {}).unwrap_or_default()});- let mut locked = state.lock().unwrap();- locked.delete_calls += 1;- if let Some(key) = ax_file {- locked- .docs- .retain(|_, doc| doc.get("ax_file").and_then(Value::as_str) != Some(key.as_str()));- }- if let Some(key) = file_key {- locked- .catalog_docs- .retain(|_, doc| doc.get("file_key").and_then(Value::as_str) != Some(key.as_str()));- }- // Recorded before the fault so a refused sweep is counted too — the- // point of the batching assertion is how many round trips the run- // made, not how many of them succeeded.- if let Some(swept) = &alias_sweep {+ if let Some(swept) = alias_sweep {+ let mut locked = state.lock().unwrap();+ // Recorded before the fault so a refused sweep is counted too —+ // the point of the batching assertion is how many round trips the+ // run made, not how many of them succeeded.locked.alias_sweep_batches.push(swept.clone());- }- match alias_sweep {- Some(_) if locked.fail_alias_sweep => (+ if locked.fail_alias_sweep {// What a poisoned catalog collection really answers: a 500// whose BODY names the condition. The client used to keep the// status and discard the body, which is the whole reason #345// was filed "not investigated".- 500,- json!({- "error": {- "type": "internal_server_error_exception",- "reason": "collection publication was interrupted; reopen the index \- so WAL recovery can rebuild a consistent searchable state"- },- "status": 500- }),- ),- Some(swept) => {- locked.catalog_docs.retain(|_, doc| {- doc.get("status").and_then(Value::as_str) != Some("duplicate")- || !swept- .iter()- .any(|path| doc.get("path").and_then(Value::as_str) == Some(path))- });- (200, json!({"deleted": 0, "failures": []}))+ (+ 500,+ json!({+ "error": {+ "type": "internal_server_error_exception",+ "reason": "collection publication was interrupted; reopen the index \+ so WAL recovery can rebuild a consistent searchable state"+ },+ "status": 500+ }),+ )+ } else {+ let mut hits: Vec<Value> = locked+ .catalog_docs+ .iter()+ .filter(|(_, doc)| {+ doc.get("status").and_then(Value::as_str) == Some("duplicate")+ && swept.iter().any(|path| {+ doc.get("path").and_then(Value::as_str) == Some(path.as_str())+ })+ })+ .map(|(id, doc)| json!({"_id": id, "_source": doc}))+ .collect();+ // Deterministic order, so a page boundary is never `HashMap`+ // iteration order.+ hits.sort_by(|left, right| left["_id"].as_str().cmp(&right["_id"].as_str()));+ (+ 200,+ json!({+ "hits": {+ "total": {"value": hits.len(), "relation": "eq"},+ "hits": hits+ },+ "aggregations": {}+ }),+ )}- None => (200, json!({"deleted": 0, "failures": []})),- }- } else if method == "GET" && path.ends_with("/_count") {- (200, json!({"count": state.lock().unwrap().docs.len()}))- } else if method == "POST" && path.ends_with("/_search") {- // Report the REAL number of stored docs: `run_index` verifies live- // counts against the journal (#195), so a mock that always answered 0- // hits would (rightly) fail every successful run. The generated path- // additionally reads back per-file and per-catalog projections, so the- // count is filtered by whichever identity the query names.- let query: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);- let ax_file = query- .pointer("/query/term/ax_file")- .or_else(|| query.pointer("/query/bool/must/0/term/ax_file"))- .and_then(Value::as_str);- let file_key = query- .pointer("/query/term/file_key")- .and_then(Value::as_str);- let locked = state.lock().unwrap();- let documents = if file_key.is_some() {- &locked.catalog_docs} else {- &locked.docs- };- let count = documents- .values()- .filter(|doc| {- ax_file.is_none_or(|key| doc.get("ax_file").and_then(Value::as_str) == Some(key))- && file_key- .is_none_or(|key| doc.get("file_key").and_then(Value::as_str) == Some(key))- })- .count();- (- 200,- json!({"hits":{"total":{"value":count},"hits":[]},"aggregations":{}}),- )+ let ax_file = query+ .pointer("/query/term/ax_file")+ .or_else(|| query.pointer("/query/bool/must/0/term/ax_file"))+ .and_then(Value::as_str);+ let file_key = query+ .pointer("/query/term/file_key")+ .and_then(Value::as_str);+ let locked = state.lock().unwrap();+ let documents = if file_key.is_some() {+ &locked.catalog_docs+ } else {+ &locked.docs+ };+ let count = documents+ .values()+ .filter(|doc| {+ ax_file+ .is_none_or(|key| doc.get("ax_file").and_then(Value::as_str) == Some(key))+ && file_key.is_none_or(|key| {+ doc.get("file_key").and_then(Value::as_str) == Some(key)+ })+ })+ .count();+ (+ 200,+ json!({"hits":{"total":{"value":count},"hits":[]},"aggregations":{}}),+ )+ }} else {// ping, index creation/mapping, refresh, and catalog operations(200, json!({"acknowledged": true}))diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 19f58217a..490ebed06 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -417,6 +417,11 @@ fn delete_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> usize// `prefix` + `path`/`file_key` bool filter). A doc is deleted iff it// matches EVERY collected term.let mut terms: Vec<(String, Value)> = Vec::new();+ // #905: and every `/query/bool/filter[].terms` value ARRAY too — the+ // duplicate-alias sweep's path list is one of those, and an endpoint that+ // dropped it deleted at every path instead of at the named ones, which+ // makes a delete look wider than the engine's.+ let mut any_of: Vec<(String, Vec<Value>)> = Vec::new();if let Some((field, value)) = query.pointer("/query/term").and_then(Value::as_object)@@ -436,6 +441,16 @@ fn delete_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> usize{terms.push((field.clone(), value.clone()));}+ if let Some((field, values)) = filter+ .pointer("/terms")+ .and_then(Value::as_object)+ .and_then(|terms| terms.iter().next())+ {+ any_of.push((+ field.clone(),+ values.as_array().cloned().unwrap_or_default(),+ ));+ }}}// #739: an `ids` query deletes by exact `_id` (the main `file:` doc sweep).@@ -458,19 +473,25 @@ fn delete_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> usize// ids query: delete iff this doc's _id is listed (nothing else).return !ids.contains(id);}- if terms.is_empty() {+ if terms.is_empty() && any_of.is_empty() {return false; // no constraint: a match-all delete}+ let legacy: &[String] = if candidate == catalog::CATALOG_INDEX {+ &legacy_text+ } else {+ &[]+ };// Retain (do NOT delete) unless the doc matches every term — #890: on- // the catalog's legacy text fields, "matches" means the analyzed tokens.- !terms.iter().all(|(field, expected)| {- let legacy: &[String] = if candidate == catalog::CATALOG_INDEX {- &legacy_text- } else {- &[]- };- term_matches(doc, field, expected, legacy)- })+ // the catalog's legacy text fields, "matches" means the analyzed tokens+ // — and lands inside every `terms` value list (#905).+ !(terms+ .iter()+ .all(|(field, expected)| term_matches(doc, field, expected, legacy))+ && any_of.iter().all(|(field, values)| {+ values+ .iter()+ .any(|value| term_matches(doc, field, value, legacy))+ }))});before - locked.docs.len()}@@ -3308,6 +3329,281 @@ fn the_scoped_catalog_sweep_pages_to_the_exact_end_of_its_candidate_set() {}}+/// #905 (data loss), end to end through the real finalize: a run over one+/// corpus must not delete a SIBLING corpus's duplicate-alias catalog document.+///+/// `autoindex-catalog` is global across every corpus on the node and `path` is+/// a logical path INSIDE a corpus, so the duplicate-alias sweep's+/// `{status: duplicate} + {path: [...]}` query reaches every corpus that has a+/// duplicate at the same relative path. Two checkouts that each carry+/// `LICENSE.csv` and `docs/LICENSE.csv` is the ordinary shape of that, not a+/// contrived one — and unlike #890 it needs no legacy mapping: this fixture's+/// catalog is the current `keyword` one.+///+/// The corpus next door is the one in+/// `a_file_shared_with_another_corpus_on_the_same_node_is_not_a_fatal_condition`+/// with ONE line added: its own duplicate at the same relative path. That is+/// what puts `docs/LICENSE.csv` into the second run's alias-sweep list and+/// makes the sweep reach next door.+///+/// Both runs take the DEFAULT graph path (`no_graph: false`), because that is+/// where this sweep lives: a `--no-graph` run returns from the generated path+/// several thousand lines earlier and retires stale catalog documents by their+/// prefix-scoped `_id` instead (`generation_catalog::managed_non_run_ids`),+/// which was never unscoped. That is the honest blast radius of #905.+///+/// FAIL-BEFORE, measured: with the body of `sweep_duplicate_aliases` replaced+/// by the `es.delete_by_query(CATALOG_INDEX, &alias_sweep_query(paths))` this+/// PR removes — i.e. the code as it stands on `main` — the run ends with ONE+/// alias document instead of two: the second corpus swept the first corpus's+/// away and then wrote its own.+#[test]+fn this_corpus_finalize_leaves_a_sibling_corpus_alias_document_alone() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK+ .lock()+ .unwrap_or_else(|p| p.into_inner());+ let shared = "id,value\n1,apache-2.0\n2,copied-verbatim\n";+ let endpoint = HttpEndpoint::start();++ let first = tempfile::tempdir().unwrap();+ let first_state = tempfile::tempdir().unwrap();+ fs::create_dir(first.path().join("docs")).unwrap();+ fs::write(first.path().join("LICENSE.csv"), shared).unwrap();+ fs::write(first.path().join("docs").join("LICENSE.csv"), shared).unwrap();+ let mut config = cfg(first.path(), first_state.path(), &endpoint.url, false);+ config.no_graph = false;+ config.brain = Some("testbrain".into());+ let (code, summary) = run_index_report(config).expect("the first corpus indexes");+ let summary = summary.expect("the first corpus reports");+ assert_eq!(code, 0);+ assert_eq!(+ summary["duplicate_files"], 1,+ "the first corpus must publish one alias document, or there is nothing \+ next door for the second run to reach: {summary}"+ );++ // The second corpus: its own state dir and its own --prefix, exactly the+ // isolation the CLI's refusals recommend — and its own duplicate at the+ // SAME relative path, which is what the first corpus's alias sits at.+ let second = tempfile::tempdir().unwrap();+ let second_state = tempfile::tempdir().unwrap();+ fs::create_dir(second.path().join("docs")).unwrap();+ fs::write(second.path().join("LICENSE.csv"), shared).unwrap();+ fs::write(second.path().join("docs").join("LICENSE.csv"), shared).unwrap();+ let mut config = cfg(second.path(), second_state.path(), &endpoint.url, false);+ config.prefix = "incremental-http-second".into();+ config.no_graph = false;+ config.brain = Some("testbrain-second".into());+ let (code, summary) = run_index_report(config).expect("the second corpus indexes");+ let summary = summary.expect("the second corpus reports");+ assert_eq!(code, 0, "the second corpus is a clean run: {summary}");+ assert_eq!(+ summary["duplicate_files"], 1,+ "the second corpus publishes its own alias at the same path: {summary}"+ );++ let aliases: Vec<(String, String)> = {+ let st = endpoint.state.lock().unwrap();+ let mut aliases: Vec<(String, String)> = st+ .docs+ .iter()+ .filter(|((index, _), doc)| {+ index == catalog::CATALOG_INDEX+ && doc.get("status").and_then(Value::as_str) == Some("duplicate")+ })+ .map(|((_, id), doc)| {+ (+ id.clone(),+ doc.get(catalog::CORPUS_SCOPE_FIELD)+ .and_then(Value::as_str)+ .unwrap_or("<no corpus_scope>")+ .to_string(),+ )+ })+ .collect();+ aliases.sort();+ aliases+ };+ // Sorted by corpus, not by `_id`: the two ids share a body and differ only+ // in their prefix, where `-` sorts before `:`.+ let mut scopes: Vec<&str> = aliases.iter().map(|(_, scope)| scope.as_str()).collect();+ scopes.sort_unstable();+ assert_eq!(+ scopes,+ vec!["incremental-http", "incremental-http-second"],+ "#905: both corpora must keep their own duplicate-alias document — the \+ second corpus's sweep is scoped to itself, not to the logical path. \+ Aliases: {aliases:?}"+ );+}++/// #905, at the sweep itself: every identity scheme the catalog can still hold.+///+/// The end-to-end test above proves the wiring on documents this build wrote.+/// This one proves the part a naive scope filter would have broken. The sweep+/// exists BECAUSE alias ids changed as identity evolved, so it has to keep+/// reaching this corpus's older documents while stopping at the corpus+/// boundary — and the older a document is, the less corpus evidence it carries:+///+/// * current (`_source.corpus_scope`, #755/rc.72)+/// * `_source.prefix` only (#737/rc.68)+/// * neither, but a prefix-scoped `_id` (#416/rc.57)+/// * neither, and an `_id` with no prefix in it either (rc.10..rc.56) — the+/// case the issue calls out, decided by reconstructing the ids THIS corpus+/// would have written rather than by guessing.+///+/// The last document is the honest residual: anonymous, and NOT one of this+/// corpus's reconstructions (a different `file_key`). It is left in place —+/// deleting a document that names no owner is the reach this fix removes — and+/// it is reported, non-fatally, by `stranded_alias_notes`.+///+/// FAIL-BEFORE, measured: with `sweep_duplicate_aliases`'s body replaced by the+/// unscoped `delete_by_query` this PR removes, all four of the sibling's and+/// the anonymous stranger's documents are deleted too — `Survivors: []`.+#[test]+fn the_duplicate_alias_sweep_scopes_every_identity_scheme_to_this_corpus() {+ let ep = HttpEndpoint::start();+ let es = Es::with_bulk_timeout(&ep.url, None, 30).expect("es client");+ // The logical path both corpora hold a duplicate at.+ let path = "docs/LICENSE.csv";+ let key = "shared-key";+ let path_id = "pid-docs-license";++ // This corpus ("ax"), one document per scheme. All of these must be swept.+ let ax_current = catalog::duplicate_file_id("ax", key, path, path_id);+ let ax_prefix_field = "file-alias:ax:00000000000000000000000000000737".to_string();+ let ax_id_only = "file-alias:ax:00000000000000000000000000000416".to_string();+ let ax_anonymous = catalog::unprefixed_duplicate_file_ids(key, path, path_id);+ // The sibling ("bx"), the same three attributable schemes. All must survive.+ let bx_current = catalog::duplicate_file_id("bx", key, path, path_id);+ let bx_prefix_field = "file-alias:bx:00000000000000000000000000000737".to_string();+ let bx_id_only = "file-alias:bx:00000000000000000000000000000416".to_string();+ // Anonymous, and not reconstructible as ours: a different `file_key`, so a+ // pre-#416 build of SOME corpus wrote it and nothing says which.+ let anonymous_stranger =+ catalog::unprefixed_duplicate_file_ids("someone-elses-key", path, "")[0].clone();++ let alias_doc = |scope: Option<&str>, prefix: Option<&str>| {+ let mut doc = json!({+ "doc_kind": "file",+ "file_key": key,+ "path": path,+ "format": "duplicate",+ "status": "duplicate",+ });+ if let Some(scope) = scope {+ doc[catalog::CORPUS_SCOPE_FIELD] = json!(scope);+ }+ if let Some(prefix) = prefix {+ doc["prefix"] = json!(prefix);+ }+ doc+ };+ let mut seeded: Vec<String> = vec![+ ax_current.clone(),+ ax_prefix_field.clone(),+ ax_id_only.clone(),+ bx_current.clone(),+ bx_prefix_field.clone(),+ bx_id_only.clone(),+ anonymous_stranger.clone(),+ ];+ seeded.extend(ax_anonymous.iter().cloned());+ {+ let mut st = ep.state.lock().unwrap();+ let mut put = |id: &String, doc: Value| {+ st.docs+ .insert((catalog::CATALOG_INDEX.to_string(), id.clone()), doc);+ };+ put(&ax_current, alias_doc(Some("ax"), Some("ax")));+ put(&ax_prefix_field, alias_doc(None, Some("ax")));+ put(&ax_id_only, alias_doc(None, None));+ for id in &ax_anonymous {+ put(id, alias_doc(None, None));+ }+ put(&bx_current, alias_doc(Some("bx"), Some("bx")));+ put(&bx_prefix_field, alias_doc(None, Some("bx")));+ put(&bx_id_only, alias_doc(None, None));+ put(&anonymous_stranger, alias_doc(None, None));+ }++ // What the finalize passes: the ids THIS corpus would have written for its+ // own aliases under the pre-#416 scheme, reconstructed from its plan.+ let own: HashSet<String> = catalog::unprefixed_duplicate_file_ids(key, path, path_id)+ .into_iter()+ .collect();+ let mut stranded: Vec<String> = Vec::new();+ let swept = sweep_duplicate_aliases(&es, "ax", &[path], &own, &mut stranded);++ // Read every verdict out and RELEASE the endpoint's lock before asserting:+ // an assert that fires while holding it poisons the mutex the server thread+ // also takes, and the panic-in-a-destructor that follows aborts the whole+ // test binary instead of failing this one test. This test is written to+ // fail on unfixed code, so its failure mode has to stay clean.+ let (survivors, alive): (String, Vec<String>) = {+ let st = ep.state.lock().unwrap();+ let mut alive: Vec<String> = seeded+ .iter()+ .filter(|id| {+ st.docs+ .contains_key(&(catalog::CATALOG_INDEX.to_string(), (*id).clone()))+ })+ .cloned()+ .collect();+ alive.sort();+ (format!("{alive:?}"), alive)+ };+ swept.expect("the sweep completes");++ for (id, what) in [+ (&ax_current, "current-scheme"),+ (&ax_prefix_field, "#737 `prefix`-field"),+ (&ax_id_only, "#416 prefix-in-id"),+ ] {+ assert!(+ !alive.contains(id),+ "#905: this corpus's own {what} alias must still be swept — the scope is \+ applied per hit, not by narrowing the query. Survivors: {survivors}"+ );+ }+ for id in &ax_anonymous {+ assert!(+ !alive.contains(id),+ "#905: this corpus's pre-#416 alias carries no corpus anywhere, so it is swept \+ on a reconstructed id — not stranded. Survivors: {survivors}"+ );+ }+ for (id, what) in [+ (&bx_current, "current-scheme"),+ (&bx_prefix_field, "#737 `prefix`-field"),+ (&bx_id_only, "#416 prefix-in-id"),+ ] {+ assert!(+ alive.contains(id),+ "#905: a sibling corpus's {what} alias at the same logical path must survive — \+ deleting it is the data loss. Survivors: {survivors}"+ );+ }+ assert!(+ alive.contains(&anonymous_stranger),+ "#905: an alias that names no corpus and is not one of this corpus's own \+ reconstructions is left in place, not deleted on a guess. Survivors: {survivors}"+ );++ // …and it is reported. Silently stranding it would be the other half of the+ // trade the issue warned about.+ assert_eq!(stranded.len(), 1, "{stranded:?}");+ assert!(stranded[0].contains(path), "{stranded:?}");+ let notes = stranded_alias_notes(&stranded).join("\n");+ assert!(notes.contains("LEFT IN PLACE"), "{notes}");+ assert!(notes.contains(&anonymous_stranger), "{notes}");+ assert!(+ stranded_alias_notes(&[]).is_empty(),+ "an ordinary corpus with nothing stranded says nothing"+ );+}+/// #739: a `file:` catalog doc written by a pre-#737 binary has NO `prefix`/// field, so the #737 prefix-scoped sweep misses it on the first upgraded run./// The by-`_id` delete catches it (the id encodes the prefix), while a siblingdiff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 819422bee..5bda68c0f 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -707,16 +707,20 @@ const ALIAS_SWEEP_CHUNK: usize = 1_024;/// `terms` here takes a plain value array — never the `{index, id, path}`/// lookup form, which `_delete_by_query` does not resolve.///-/// KNOWN, NOT FIXED HERE (#905): this query carries **no corpus scope**, and-/// `path` is a logical path inside a corpus rather than a node-unique key, so a-/// run over one corpus can delete another corpus's `status: duplicate` catalog-/// documents at the same path. Unlike #890 that needs no legacy mapping, and-/// unlike #890 it takes only alias documents, which the sibling rewrites on its-/// next run. It is not a scope filter away: this sweep deliberately reaches-/// documents whose ids follow HISTORICAL identity schemes, some of which carry-/// no corpus evidence at all — see #905 for the shape a fix has to take, and for-/// why [`delete_catalog_docs_scoped`]'s recheck is the pattern that makes one-/// possible.+/// It carries **no corpus scope**, and it must not grow one (#905). `path` is a+/// logical path inside a corpus rather than a node-unique key and+/// `autoindex-catalog` is global across every corpus on the node, so this query+/// on its own reaches a SIBLING corpus's `status: duplicate` documents at the+/// same path. It stays a candidate FILTER: [`sweep_duplicate_aliases`] decides+/// per hit which corpus each candidate belongs to and deletes only this+/// corpus's, by `_id`.+///+/// A scope filter here instead would have been wrong in the other direction:+/// this sweep exists to reach documents whose ids follow HISTORICAL identity+/// schemes, and the oldest of those (pre-#416) carry no corpus field and no+/// prefix in their `_id` — a server-side `corpus_scope`/`prefix` term would+/// simply stop matching them and strand them. See+/// [`catalog_doc_corpus`] for how attribution is decided instead.fn alias_sweep_query(paths: &[&str]) -> Value {json!({"bool": {@@ -728,6 +732,162 @@ fn alias_sweep_query(paths: &[&str]) -> Value {})}+/// Read a string field out of a search hit's `_source`.+///+/// Raw `_source`, never a server-side `term`: the whole point of the per-hit+/// re-check both catalog sweeps do is that the catalog's MAPPING cannot be+/// trusted to make a `term` byte-exact (#890).+fn source_str<'a>(hit: &'a Value, field: &str) -> Option<&'a str> {+ hit.pointer("/_source")+ .and_then(|source| source.get(field))+ .and_then(Value::as_str)+}++/// Which corpus a catalog hit belongs to, decided from the document itself+/// (#905).+///+/// `autoindex-catalog` is global across every corpus on the node, so before+/// deleting anything out of it a sweep has to answer this. Three layers of+/// evidence, newest first, because the catalog outlives releases and a+/// document written years of release-numbers ago carries less of it:+///+/// 1. `catalog::CORPUS_SCOPE_FIELD` — #755 (v1.0.0-rc.72), `keyword` on every+/// catalog by construction, since no earlier release ever wrote the field.+/// 2. `prefix` — #737 (rc.68). Read from raw `_source`, never term-queried: on+/// a catalog an rc.15..rc.67 build touched it is dynamically-inferred+/// `text`, and that is exactly the #890 over-match.+/// 3. the `_id` — #416 (rc.57) put the corpus prefix into it+/// (`file-alias:{prefix}:{body}`). The prefix is a `sanitize_slug` output,+/// so it holds no `:`, and the body is `ids::doc_id`'s 32 hex characters,+/// which hold none either: the split is unambiguous.+///+/// Below that — an alias document written by rc.10..rc.56 — there is no corpus+/// evidence anywhere in the document, and [`CatalogDocCorpus::Anonymous`] says+/// so rather than guessing. What the caller does with that is the caller's+/// decision to make out loud; see [`sweep_duplicate_aliases`].+enum CatalogDocCorpus<'a> {+ /// The document names its corpus, in a field or in its `_id`.+ Named(&'a str),+ /// The document names no corpus at all.+ Anonymous,+}++fn catalog_doc_corpus<'a>(id: &'a str, hit: &'a Value) -> CatalogDocCorpus<'a> {+ if let Some(scope) = source_str(hit, catalog::CORPUS_SCOPE_FIELD) {+ return CatalogDocCorpus::Named(scope);+ }+ if let Some(prefix) = source_str(hit, "prefix") {+ return CatalogDocCorpus::Named(prefix);+ }+ if let Some((prefix, _)) = id+ .strip_prefix(catalog::ALIAS_ID_PREFIX)+ .and_then(|body| body.split_once(':'))+ {+ return CatalogDocCorpus::Named(prefix);+ }+ CatalogDocCorpus::Anonymous+}++/// Delete THIS corpus's `status: duplicate` catalog documents at `paths`+/// (#905).+///+/// [`alias_sweep_query`] selects the candidates and cannot be scoped (see its+/// comment); the scope is applied here, per hit, by [`catalog_doc_corpus`].+/// A candidate the query returns that belongs to a sibling corpus is left+/// alone — an unscoped `_delete_by_query` took it, which is the data loss this+/// exists to stop.+///+/// THE ANONYMOUS CASE, DECIDED ON PURPOSE. A pre-#416 alias document names no+/// corpus, so "is this ours?" cannot be read off it. Neither blanket answer is+/// acceptable: deleting every anonymous hit keeps the whole cross-corpus reach+/// for exactly the catalogs most likely to hold such documents, and keeping+/// every anonymous hit strands the stale alias this sweep exists to remove —+/// the trade the issue warned a naive scope filter would silently make.+///+/// So neither is taken. The caller passes the ids this corpus ITSELF would+/// have written under the pre-#416 scheme, reconstructed from its own frozen+/// plan and current inventory by+/// [`catalog::unprefixed_duplicate_file_ids`] — the same reconstruct-the-id+/// move #739 already makes for legacy `file:`/`file-alias:` documents. An+/// anonymous hit whose `_id` is one of those is ours and is deleted; any other+/// anonymous hit is left in place and NAMED, so an operator can see the one+/// residual rather than discover it in `xerj autoindex map`.+///+/// The residual is bounded and it is honest to state it: a pre-#416 id is+/// `doc_id("duplicate-file", file_key, path|path_id)` with no corpus in it, so+/// two corpora holding a byte-identical file at the same logical path wrote+/// the SAME `_id` — one document, whichever ran last. Deleting it on a+/// reconstructed-id match therefore removes a document that was never uniquely+/// the sibling's, and both corpora rewrite their own prefix-scoped alias on+/// their next run. What is NOT claimed: that this recovers every pre-#416+/// alias. One whose `file_key` changed since (its content was edited) cannot be+/// reconstructed, and it is reported stranded rather than deleted.+fn sweep_duplicate_aliases(+ es: &Es,+ prefix: &str,+ paths: &[&str],+ own_unprefixed_ids: &HashSet<String>,+ stranded: &mut Vec<String>,+) -> Result<()> {+ let query = alias_sweep_query(paths);+ let label = format!(+ "corpus={prefix}, status=duplicate, {} path(s) from `{}`",+ paths.len(),+ paths.first().copied().unwrap_or("")+ );+ delete_catalog_hits_where(es, &query, &label, |id, hit| {+ match catalog_doc_corpus(id, hit) {+ CatalogDocCorpus::Named(owner) => owner == prefix,+ CatalogDocCorpus::Anonymous if own_unprefixed_ids.contains(id) => true,+ CatalogDocCorpus::Anonymous => {+ stranded.push(match source_str(hit, "path") {+ Some(path) => format!("{path} ({id})"),+ None => id.to_string(),+ });+ false+ }+ }+ })+}++/// What a run says about the alias documents the sweep deliberately did not+/// delete.+///+/// Loud for the same reason [`alias_sweep_notes`] is: the cost is real. A+/// stale pre-#416 alias left in the catalog makes `xerj autoindex map` report+/// a duplicate path twice, and the operator can only act on it if they are+/// told. It is NOT an error — the alternative was deleting a document this run+/// cannot prove is its own, and this file's whole subject is that a delete is+/// not recoverable.+///+/// Same listing cap and one-note-per-line rule as every other human-facing+/// listing here ([`REFUSAL_LIST_CAP`], [`progress::Progress::note`]).+fn stranded_alias_notes(stranded: &[String]) -> Vec<String> {+ if stranded.is_empty() {+ return Vec::new();+ }+ let mut notes = vec![format!(+ "note: {} catalog alias document(s) at this corpus's duplicate path(s) carry no corpus \+ in the document and none in their `_id` either — the id scheme v1.0.0-rc.10..rc.56 \+ wrote — and none matched an id this corpus would have written, so they were LEFT IN \+ PLACE rather than deleted: another corpus on this node may own them. `xerj autoindex \+ map` can therefore report a duplicate path twice. Reindex `{}` to retire them.",+ stranded.len(),+ catalog::CATALOG_INDEX,+ )];+ notes.extend(+ stranded+ .iter()+ .take(REFUSAL_LIST_CAP)+ .map(|doc| format!(" alias left in place: {doc}")),+ );+ let remaining = stranded.len().saturating_sub(REFUSAL_LIST_CAP);+ if remaining > 0 {+ notes.push(format!(" … and {remaining} more"));+ }+ notes+}+/// The `reason` a run finishes with when every document is indexed but the/// legacy-scheme catalog alias sweep could not be completed.///@@ -3602,6 +3762,43 @@ fn delete_catalog_docs_scoped(es: &Es, scope: &[(&str, &str)]) -> Result<()> {.iter().map(|(field, value)| json!({"term": {*field: *value}})).collect::<Vec<Value>>()}});+ let label = scope+ .iter()+ .map(|(field, value)| format!("{field}={value}"))+ .collect::<Vec<_>>()+ .join(", ");+ delete_catalog_hits_where(es, &query, &label, |_id, hit| {+ // The re-check. A hit whose stored scope value is not byte-equal to+ // what the caller asked for belongs to something else — a sibling+ // corpus, or another file — and is left alone.+ scope.iter().all(|(field, value)| {+ hit.pointer("/_source")+ .and_then(|source| source.get(*field))+ .and_then(Value::as_str)+ == Some(*value)+ })+ })+}++/// The page walk both scoped catalog sweeps share: read the candidate set+/// `query` selects, ask `accept` about every hit, and delete by `_id` exactly+/// the hits it accepts — nothing at all, if it accepts nothing.+///+/// Split out of [`delete_catalog_docs_scoped`] for #905, which needs the same+/// walk under a different per-hit decision (corpus attribution rather than a+/// byte-exact `_source` compare) and must not carry a second copy of the paging+/// rules: the off-by-one those rules encode was a real defect once already (the+/// #890 review follow-up), and one copy of it is enough.+///+/// `accept` is `FnMut` so a caller can record what it declined as it goes.+/// #905's does, because a candidate it cannot attribute to a corpus is one it+/// deliberately leaves behind and therefore has to be able to name.+fn delete_catalog_hits_where(+ es: &Es,+ query: &Value,+ scope_label: &str,+ mut accept: impl FnMut(&str, &Value) -> bool,+) -> Result<()> {let mut ids: Vec<String> = Vec::new();let mut from = 0usize;for _ in 0..SCOPED_SWEEP_MAX_PAGES {@@ -3615,19 +3812,11 @@ fn delete_catalog_docs_scoped(es: &Es, scope: &[(&str, &str)]) -> Result<()> {.cloned().unwrap_or_default();for hit in &hits {- // The re-check. A hit whose stored scope value is not byte-equal to- // what the caller asked for belongs to something else — a sibling- // corpus, or another file — and is left alone.- let exact = scope.iter().all(|(field, value)| {- hit.pointer("/_source")- .and_then(|source| source.get(*field))- .and_then(Value::as_str)- == Some(*value)- });- if exact {- if let Some(id) = hit.get("_id").and_then(Value::as_str) {- ids.push(id.to_string());- }+ let Some(id) = hit.get("_id").and_then(Value::as_str) else {+ continue;+ };+ if accept(id, hit) {+ ids.push(id.to_string());}}from += hits.len();@@ -3666,14 +3855,9 @@ fn delete_catalog_docs_scoped(es: &Es, scope: &[(&str, &str)]) -> Result<()> {// is the one the legacy-catalog warning already gives.Err(anyhow::anyhow!("scoped sweep of `{}` still had candidates after {SCOPED_SWEEP_MAX_PAGES} pages of \- {SCOPED_SWEEP_PAGE} for scope [{}]; refusing to report a partial removal — reindex `{}` \- into an index created with the current mapping",+ {SCOPED_SWEEP_PAGE} for scope [{scope_label}]; refusing to report a partial removal — \+ reindex `{}` into an index created with the current mapping",catalog::CATALOG_INDEX,- scope- .iter()- .map(|(field, value)| format!("{field}={value}"))- .collect::<Vec<_>>()- .join(", "),catalog::CATALOG_INDEX,))}@@ -4644,6 +4828,13 @@ fn run_index_report_tallied(cfg: IndexCfg, tally: &ScanTally) -> Result<(i32, Oplet mut content_changed = std::collections::HashSet::new();let mut stale_alias_ids = Vec::new();let mut alias_paths_to_replace = std::collections::HashSet::new();+ // #905: the same aliases, under the pre-#416 id scheme that carries no+ // corpus prefix. The path sweep below cannot attribute such a document from+ // the document itself, so it attributes it by reconstructing the ids THIS+ // corpus would have written. Kept in lockstep with `alias_paths_to_replace`+ // — both are extended from `previous_aliases` here and from+ // `inventory.duplicates` after this block.+ let mut own_unprefixed_alias_ids: HashSet<String> = HashSet::new();let mut plan_changed = journal.plan.is_none();// Preserve legacy document IDs while upgrading old plans with full digests.// A later same-size/tail mutation is then detected and reindexed.@@ -4651,6 +4842,9 @@ fn run_index_report_tallied(cfg: IndexCfg, tally: &ScanTally) -> Result<(i32, Oplet 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()));+ own_unprefixed_alias_ids.extend(previous_aliases.iter().flat_map(|alias| {+ catalog::unprefixed_duplicate_file_ids(&alias.file_key, &alias.rel, &alias.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)}));@@ -4763,6 +4957,9 @@ fn run_index_report_tallied(cfg: IndexCfg, tally: &ScanTally) -> Result<(i32, Opplan.duplicate_files = inventory.duplicates.clone();}alias_paths_to_replace.extend(inventory.duplicates.iter().map(|alias| alias.rel.clone()));+ own_unprefixed_alias_ids.extend(inventory.duplicates.iter().flat_map(|alias| {+ catalog::unprefixed_duplicate_file_ids(&alias.file_key, &alias.rel, &alias.path_id)+ }));let files = inventory.files.clone();let keys = inventory.keys.clone();let digests = inventory.digests.clone();@@ -6473,8 +6670,9 @@ fn run_index_report_tallied(cfg: IndexCfg, tally: &ScanTally) -> Result<(i32, Op// ── catalog write ────────────────────────────────────────────────────// Alias IDs changed as identity evolved. Remove by logical path first so// catalogs created by any previous identity scheme cannot survive beside- // the one current alias document. One request per CHUNK of paths — see- // [`alias_sweep_query`].+ // the one current alias document. One CHUNK of paths per candidate walk —+ // see [`alias_sweep_query`] for why the query stays unscoped, and+ // [`sweep_duplicate_aliases`] for where the corpus scope is applied instead.let mut alias_sweep_paths: Vec<&str> =alias_paths_to_replace.iter().map(String::as_str).collect();// Sorted so the chunk boundaries — and the failure report below — are the@@ -6486,6 +6684,9 @@ fn run_index_report_tallied(cfg: IndexCfg, tally: &ScanTally) -> Result<(i32, Op// and for the two things that keep the downgrade honest.let mut alias_sweep_failed: Vec<&str> = Vec::new();let mut alias_sweep_error: Option<String> = None;+ // #905: candidates at this corpus's duplicate paths that name no corpus and+ // are not this corpus's own reconstructed ids. Left in place, and reported.+ let mut stranded_aliases: Vec<String> = Vec::new();for chunk in alias_sweep_chunks {let _delete = pr.file(&match chunk {@@ -6495,7 +6696,13 @@ fn run_index_report_tallied(cfg: IndexCfg, tally: &ScanTally) -> Result<(i32, Op},0,);- if let Err(error) = es.delete_by_query(catalog::CATALOG_INDEX, &alias_sweep_query(chunk)) {+ if let Err(error) = sweep_duplicate_aliases(+ &es,+ &cfg.prefix,+ chunk,+ &own_unprefixed_alias_ids,+ &mut stranded_aliases,+ ) {alias_sweep_failed.extend_from_slice(chunk);alias_sweep_error.get_or_insert_with(|| format!("{error:#}"));}@@ -6508,6 +6715,9 @@ fn run_index_report_tallied(cfg: IndexCfg, tally: &ScanTally) -> Result<(i32, Oppr.note(¬e);}}+ for note in stranded_alias_notes(&stranded_aliases) {+ pr.note(¬e);+ }let mut cat_buf: Vec<u8> = Vec::new();let push_doc = |id: &str, doc: &Value, buf: &mut Vec<u8>| {let action = json!({"index": {"_index": catalog::CATALOG_INDEX, "_id": id}});