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 exclusion sweep's catalog scope is exact whatever the mapping (#890) (#896)
xerj-org62334b8640e4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 55ca0aeb4..19ca6d7cd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **The exclusion sweep can no longer delete a sibling corpus's catalog+ documents on a catalog an older build left `text`-mapped**+ ([#890](https://github.com/xerj-org/xerj/issues/890)). `autoindex-catalog` is+ shared by every corpus on the node, so when a widened ignore rule excludes a+ file, the sweep that removes its already-published documents is scoped to the+ corpus's `prefix`. On any catalog a v1.0.0-rc.15..rc.67 build wrote to before+ the mapping declared that field — which includes catalogs first created by an+ earlier release — it is dynamically inferred **`text`**, and a `term` query+ against an analyzed field matches the field's *tokens*: `prefix: "ax"` also+ reached documents whose prefix is `ax-2` (tokens `[ax, 2]`). Conjoined with+ the `path`/`file_key` a+ byte-identical file (a LICENSE, a lockfile) shares between corpora, the sweep+ deleted the **sibling corpus's live catalog documents** — the cross-corpus+ over-delete the scope was added in+ [#737](https://github.com/xerj-org/xerj/issues/737) to prevent, and a delete+ is not recoverable. Present since v1.0.0-rc.68.++ Both scoped catalog deletes now go through an exact scoped delete: the same+ query still selects candidates server-side, but every hit's raw scope values+ are re-checked against `_source` before it is deleted by `_id`. That is+ independent of the catalog's mapping, so it holds on a keyword catalog and a+ legacy text one alike, and it covers the `path`/`file_key` conjunct as well as+ the corpus scope. Coverage of the excluding corpus's own documents is+ unchanged, including alias documents the frozen plan does not name, which only+ this pass can reach. The candidate walk is bounded at ten pages of 1,000, and+ it ends on an exact `hits.total` as well as on a short page, so the boundary+ case of exactly 10,000 candidates completes rather than refusing. Past that+ bound it fails *closed* — it refuses with a `_reindex` remedy rather than+ reporting a removal it only partly made.++ Not fixed here: on a legacy catalog an analyzed field can also match *fewer*+ documents than it should, so a scoped sweep can still miss a document an older+ build wrote. That is the under-match+ [#755](https://github.com/xerj-org/xerj/issues/755) answers with the keyword+ `corpus_scope` field, and the run already warns with the `_reindex` that+ retires the legacy mapping.+- **CI's default-parallelism test step no longer races itself for a port**([#751](https://github.com/xerj-org/xerj/issues/751), the second half). Withthe deadlock above fixed, the same step then failed on a real port race thatdiff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 8c0978f9c..19f58217a 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -39,6 +39,10 @@ struct HttpState {/// a PUT that no longer declares any of them is acknowledged, exactly like/// the engine. Empty by default — every other test's faithful-accept/// behaviour is unchanged.+ ///+ /// #890: it also governs how a `term` on such a field MATCHES, in searches+ /// and in delete-by-query alike. A legacy field is not merely undeclarable,+ /// it is analyzed, and that is the whole defect — see [`term_matches`].legacy_text_catalog_fields: Vec<String>,/// Opt-in (#755): fail the catalog `_mapping` PUT with a 503 instead. Not a/// type conflict, so it must still abort the run.@@ -374,6 +378,33 @@ fn bulk_http(body: &[u8], state: &Arc<Mutex<HttpState>>) -> (u16, Value) {(200, json!({"errors": false, "items": []}))}+/// Does a `term` query for `expected` on `field` match `doc`, given the fields+/// this catalog holds as legacy `text` (#890)?+///+/// A `term` query is NOT analyzed, but the FIELD is. On a `keyword` field the+/// match is byte-exact, which is what every other test relies on. On a `text`+/// field the term is compared against the stored value's analyzed TOKENS, so+/// `{"term": {"prefix": "ax"}}` matches a document whose prefix is `ax-2`+/// (standard-analyzer tokens `[ax, 2]`) — the cross-corpus reach #890 is about.+/// Tokenisation here is the standard analyzer's shape for these values: split on+/// non-alphanumerics, lowercased.+fn term_matches(doc: &Value, field: &str, expected: &Value, legacy_text: &[String]) -> bool {+ if doc.get(field) == Some(expected) {+ return true;+ }+ if !legacy_text.iter().any(|legacy| legacy == field) {+ return false;+ }+ let (Some(stored), Some(term)) = (doc.get(field).and_then(Value::as_str), expected.as_str())+ else {+ return false;+ };+ stored+ .split(|ch: char| !ch.is_alphanumeric())+ .filter(|token| !token.is_empty())+ .any(|token| token.to_lowercase() == term)+}+fn delete_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> usize {let index = path.trim_start_matches('/')@@ -417,6 +448,7 @@ fn delete_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> usize.collect()});let mut locked = state.lock().unwrap();+ let legacy_text = locked.legacy_text_catalog_fields.clone();let before = locked.docs.len();locked.docs.retain(|(candidate, id), doc| {if candidate != index {@@ -429,10 +461,16 @@ fn delete_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> usizeif terms.is_empty() {return false; // no constraint: a match-all delete}- // Retain (do NOT delete) unless the doc matches every term.- !terms- .iter()- .all(|(field, expected)| doc.get(field) == Some(expected))+ // 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)+ })});before - locked.docs.len()}@@ -468,13 +506,24 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> Value.pointer("/query/bool/must_not/0/exists/field").and_then(Value::as_str);let locked = state.lock().unwrap();- let matching: Vec<_> = locked+ // #890: a catalog field an older build left as `text` is ANALYZED, so a+ // `term` on it matches tokens, not the raw value. `legacy` is empty for+ // every other index, which keeps every other search byte-exact.+ let legacy_text = locked.legacy_text_catalog_fields.clone();+ let legacy_for = |index: &str| -> &[String] {+ if index == catalog::CATALOG_INDEX {+ &legacy_text+ } else {+ &[]+ }+ };+ let mut matching: Vec<_> = locked.docs.iter().filter(|((index, _), doc)| {indices.contains(&index.as_str())&& term- .map(|(field, value)| doc.get(field) == Some(value))+ .map(|(field, value)| term_matches(doc, field, value, legacy_for(index))).unwrap_or(true)&& terms.map(|(field, values)| {@@ -488,7 +537,9 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> Value.get("term").and_then(Value::as_object).and_then(|term| term.iter().next())- .is_none_or(|(field, value)| doc.get(field) == Some(value))+ .is_none_or(|(field, value)| {+ term_matches(doc, field, value, legacy_for(index))+ })// A per-dataset read-back scopes `terms` on `ax_file`// and `term` on `ax_dataset` in the same `bool.filter`,// so an endpoint that honoured only the latter would@@ -509,13 +560,29 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> Value.unwrap_or(true)}).collect();+ // #890: honour `from`/`size` when the request states them — the scoped+ // catalog sweep pages, and a page has to be a page. A request that omits+ // them still gets everything, which is what every older fixture assumes.+ // Ordering is by `_id` so a page boundary is not `HashMap` iteration order.+ matching.sort_by_key(|(key, _)| *key);+ let total = matching.len();+ let from = query+ .get("from")+ .and_then(Value::as_u64)+ .map_or(0usize, |from| from as usize);+ let size = query+ .get("size")+ .and_then(Value::as_u64)+ .map_or(total, |size| size as usize);let hits = matching.iter()+ .skip(from)+ .take(size).map(|((_, id), source)| json!({"_id": id, "_source": source})).collect::<Vec<_>>();json!({"hits": {- "total": {"value": matching.len(), "relation": "eq"},+ "total": {"value": total, "relation": "eq"},"hits": hits},"aggregations": {}@@ -2983,6 +3050,264 @@ fn sweep_excluded_groups_scopes_on_the_keyword_corpus_scope_field() {);}+/// #890: the exclusion sweep must not reach ACROSS corpora on a catalog an+/// older build left with `prefix` mapped `text`.+///+/// `autoindex-catalog` is global, and on any install upgraded from+/// v1.0.0-rc.15..rc.67 `prefix` is dynamically inferred `text` (the #755 root+/// cause). A `term` query is not analyzed but the field is, so+/// `{"term": {"prefix": "ax"}}` matches the analyzed TOKENS of `ax-2`+/// (`[ax, 2]`) — and conjoined with a `path`/`file_key` a byte-identical file+/// shares, the #737 prefix-scoped `delete_by_query` deletes the SIBLING+/// corpus's live catalog documents. A delete is not recoverable.+///+/// The endpoint models exactly that: `legacy_text_catalog_fields` now governs+/// how a `term` matches on the catalog, not only which `_mapping` PUT is+/// refused. Fail-before, measured rather than reasoned: with `lib.rs` reverted+/// to the bare `delete_by_query` this replaces, the run reports+/// `Survivors: []` — sweeping corpus `ax` deleted all FOUR catalog documents,+/// both of corpus `ax-2`'s included.+///+/// The last two assertions are the other half, and they are why the fix is an+/// exact-scope delete rather than skipping the `prefix` pass on a legacy+/// catalog: corpus `ax`'s own documents — including an alias the frozen plan+/// does not name, which ONLY the term-scoped pass can reach — must still be+/// swept. Skipping the pass would leave that one searchable, which is the #439+/// exposure #589 exists to close.+#[test]+fn sweep_excluded_groups_cannot_reach_a_sibling_corpus_on_a_text_mapped_prefix() {+ let ep = HttpEndpoint::start();+ // The excluding corpus and a sibling whose prefix shares its first token.+ let ax_main = catalog::file_id("ax", "shared-key");+ let ax_alias = "file-alias:ax:unlisted".to_string();+ let sibling_main = catalog::file_id("ax-2", "shared-key");+ let sibling_alias = "file-alias:ax-2:sibling".to_string();++ {+ let mut st = ep.state.lock().unwrap();+ // A catalog written by rc.15..rc.67: `prefix` is text, and no document+ // carries the keyword `corpus_scope` field, which no such release wrote.+ st.legacy_text_catalog_fields = vec!["prefix".into()];+ st.docs.insert(+ (catalog::CATALOG_INDEX.to_string(), ax_main.clone()),+ json!({"doc_kind": "file", "prefix": "ax", "file_key": "shared-key", "path": "LICENSE"}),+ );+ // An `ax` alias the FROZEN plan does not name, so the by-`_id` sweep+ // (#739) cannot reach it — only the term-scoped `file_key` pass can.+ st.docs.insert(+ (catalog::CATALOG_INDEX.to_string(), ax_alias.clone()),+ json!({+ "doc_kind": "file",+ "prefix": "ax",+ "file_key": "shared-key",+ "path": "vendor/LICENSE",+ "status": "duplicate",+ }),+ );+ // The live sibling corpus's byte-identical copies.+ st.docs.insert(+ (catalog::CATALOG_INDEX.to_string(), sibling_main.clone()),+ json!({"doc_kind": "file", "prefix": "ax-2", "file_key": "shared-key", "path": "LICENSE"}),+ );+ st.docs.insert(+ (catalog::CATALOG_INDEX.to_string(), sibling_alias.clone()),+ json!({+ "doc_kind": "file",+ "prefix": "ax-2",+ "file_key": "shared-key",+ "path": "sibling/LICENSE",+ "status": "duplicate",+ }),+ );+ }++ let es = Es::with_bulk_timeout(&ep.url, None, 30).expect("es client");+ let mut plan = Plan::default();+ plan.datasets.push(crate::state::PlanDataset {+ slug: "ds".into(),+ index: "incremental-http-ds".into(),+ family: "csv".into(),+ group: None,+ specs: Vec::new(),+ time_field: None,+ semantic_field: None,+ sampled_records: 1,+ file_count: 1,+ });+ let excluded = vec![InventoryDeltaEntry {+ file_key: "shared-key".into(),+ path: "LICENSE".into(),+ }];++ sweep_excluded_groups(&es, "ax", &plan, &excluded, None, 0).expect("sweep");++ // Read the four verdicts 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 resulting panic-in-a-destructor 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 be clean.+ let present = |id: &String| {+ ep.state+ .lock()+ .unwrap()+ .docs+ .contains_key(&(catalog::CATALOG_INDEX.to_string(), id.clone()))+ };+ let (sibling_main_kept, sibling_alias_kept) = (present(&sibling_main), present(&sibling_alias));+ let (ax_main_swept, ax_alias_swept) = (!present(&ax_main), !present(&ax_alias));+ // Every message carries the full survivor set, so ONE failing run reports+ // the whole before-picture rather than only the first verdict that broke.+ let survivors = {+ let mut ids: Vec<String> = ep+ .state+ .lock()+ .unwrap()+ .docs+ .keys()+ .filter(|(index, _)| index == catalog::CATALOG_INDEX)+ .map(|(_, id)| id.clone())+ .collect();+ ids.sort();+ format!("{ids:?}")+ };++ assert!(+ sibling_main_kept,+ "#890: a sibling corpus whose prefix shares an analyzed token must keep its \+ catalog document — a text-mapped `prefix` is not a scope. Survivors: {survivors}"+ );+ assert!(+ sibling_alias_kept,+ "#890: the same holds for the sibling's alias doc, reached by `file_key`. \+ Survivors: {survivors}"+ );+ assert!(+ ax_main_swept,+ "#890: the excluding corpus's own document must still be swept. \+ Survivors: {survivors}"+ );+ assert!(+ ax_alias_swept,+ "#890: …including an alias the frozen plan does not name, which only the \+ term-scoped pass reaches — the fix is an exact scope, not a skipped pass. \+ Survivors: {survivors}"+ );+}++/// #890 (review follow-up): the scoped sweep's page walk must end on the+/// candidate set it actually has, not on a short page it may never be sent.+///+/// `delete_catalog_docs_scoped` reads `SCOPED_SWEEP_PAGE` hits at a time for at+/// most `SCOPED_SWEEP_MAX_PAGES` pages. Its first version ended the walk ONLY+/// on a short page, so a scope conjunction matching exactly+/// `SCOPED_SWEEP_MAX_PAGES * SCOPED_SWEEP_PAGE` documents — every page full,+/// the last one included — fell out of the loop and returned the "refusing to+/// report a partial removal" error while `ids` already held the complete,+/// re-checked set: a run aborted on an answer the function was holding. That+/// off-by-one is unreachable from the four-document fixture above, which is why+/// this walks the boundary the way+/// `the_alias_sweep_partitions_its_paths_exactly_across_the_chunk_boundary`+/// walks `ALIAS_SWEEP_CHUNK`: 0 / 1 / PAGE-1 / PAGE / PAGE+1 / MAX*PAGE, plus+/// the one candidate over the cap, which must still refuse AND still delete+/// nothing.+///+/// Every case includes one sibling-corpus document, and it sorts LAST, so the+/// per-hit re-check is proven on the final page of a multi-page walk rather+/// than only inside the first page. `prefix` is legacy `text` here for the+/// reason it is in the test above: that is what makes the sibling a candidate+/// the server returns and the client has to drop.+#[test]+fn the_scoped_catalog_sweep_pages_to_the_exact_end_of_its_candidate_set() {+ let ep = HttpEndpoint::start();+ let es = Es::with_bulk_timeout(&ep.url, None, 30).expect("es client");+ // Sorts after every `file-alias:` id below (`-` < `:`), so it is the last+ // hit of the last page.+ let sibling = "file:ax-2:shared-key".to_string();+ let cap = SCOPED_SWEEP_MAX_PAGES * SCOPED_SWEEP_PAGE;++ for candidates in [+ 0,+ 1,+ SCOPED_SWEEP_PAGE - 1,+ SCOPED_SWEEP_PAGE,+ SCOPED_SWEEP_PAGE + 1,+ cap,+ cap + 1,+ ] {+ // `candidates` counts what the QUERY returns. One of them is the+ // sibling; the rest are this corpus's own documents, all of which the+ // sweep must remove.+ let own = candidates.saturating_sub(1);+ {+ let mut st = ep.state.lock().unwrap();+ st.docs.clear();+ st.legacy_text_catalog_fields = vec!["prefix".into()];+ for n in 0..own {+ st.docs.insert(+ (+ catalog::CATALOG_INDEX.to_string(),+ format!("file-alias:ax:{n:06}"),+ ),+ json!({"doc_kind": "file", "prefix": "ax", "path": "LICENSE"}),+ );+ }+ if candidates > 0 {+ st.docs.insert(+ (catalog::CATALOG_INDEX.to_string(), sibling.clone()),+ json!({"doc_kind": "file", "prefix": "ax-2", "path": "LICENSE"}),+ );+ }+ }++ let swept = delete_catalog_docs_scoped(&es, &[("prefix", "ax"), ("path", "LICENSE")]);++ // Read every verdict out and RELEASE the endpoint's lock before+ // asserting, for the reason the test above gives: an assert that fires+ // while holding it poisons the mutex the server thread also takes.+ let (survivors, sibling_kept) = {+ let st = ep.state.lock().unwrap();+ let survivors = st+ .docs+ .keys()+ .filter(|(index, _)| index == catalog::CATALOG_INDEX)+ .count();+ let sibling_kept = st+ .docs+ .contains_key(&(catalog::CATALOG_INDEX.to_string(), sibling.clone()));+ (survivors, sibling_kept)+ };++ if candidates > cap {+ assert!(+ swept.is_err(),+ "#890: past {cap} candidates the sweep must refuse rather than report a \+ partial removal ({candidates} candidates)"+ );+ assert_eq!(+ survivors, candidates,+ "#890: a refusal must delete NOTHING — a partial sweep reported as a failure \+ is still a partial sweep ({candidates} candidates)"+ );+ continue;+ }++ swept.unwrap_or_else(|err| {+ panic!("#890: {candidates} candidates is inside the page budget, not past it: {err}")+ });+ assert_eq!(+ survivors,+ usize::from(candidates > 0),+ "#890: every one of this corpus's {own} documents must be swept, across page \+ boundaries as much as inside one page ({candidates} candidates)"+ );+ assert!(+ sibling_kept || candidates == 0,+ "#890: the sibling corpus's document must survive the re-check on whichever page \+ it lands ({candidates} candidates)"+ );+ }+}+/// #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 b5f8597e9..819422bee 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -308,8 +308,11 @@ pub(crate) fn ensure_generation_mappings(es: &Es, plan: &Plan, pr: &Progress) ->/// value (`ax`) also matches a sibling corpus whose scope is `ax-2` (tokens/// `[ax, 2]`) — wider, not narrower, and across the corpus boundary #737 drew./// That is precisely why the scope moved to `CORPUS_SCOPE_FIELD` instead of-/// being left on a possibly-text `prefix`; see the sweep comment in-/// `sweep_excluded_groups` for what the `prefix` pass can still reach.+/// being left on a possibly-text `prefix`. The widening is no longer load-+/// bearing on the delete path either: since #890 the sweeps go through+/// [`delete_catalog_docs_scoped`], which re-checks each hit's raw scope value+/// before deleting it by `_id`, so a legacy analyzed field can cost this+/// catalog *coverage* but can no longer cost a sibling corpus its documents./// * The loop gives up whatever field the engine names, and the safety of doing/// so is not uniform across fields. It holds for the conjunctive scope filters/// above; it does not hold for the `ensure!`-guarded exact reads built on@@ -703,6 +706,17 @@ const ALIAS_SWEEP_CHUNK: usize = 1_024;/// `path` and `status` are both `keyword` in [`catalog::catalog_mapping`], and/// `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.fn alias_sweep_query(paths: &[&str]) -> Value {json!({"bool": {@@ -3538,6 +3552,132 @@ fn finish_generated_run(es: &Es, journal: &mut state::Journal, cfg: &IndexCfg) -Ok(summary)}+/// One search page of [`delete_catalog_docs_scoped`], and its page budget.+/// `from + PAGE` stays inside the default `max_result_window` (10k) at the cap,+/// so no page is refused. Named at module scope so the boundary test walks the+/// same numbers the sweep does rather than its own copy of them.+const SCOPED_SWEEP_PAGE: usize = 1_000;+const SCOPED_SWEEP_MAX_PAGES: usize = 10;++/// Delete the `autoindex-catalog` documents whose `_source` matches EVERY+/// `(field, value)` pair **exactly**, whatever type this catalog's mapping+/// gives those fields (#890).+///+/// A plain scoped `_delete_by_query` cannot promise that on this index. The+/// catalog is global across every corpus on the node and it outlives releases,+/// so a field it holds is not necessarily the type this build declares:+/// v1.0.0-rc.15 began writing `prefix` before `catalog::catalog_mapping`+/// declared it, so any catalog an rc.15..rc.67 build wrote to before that+/// mapping landed holds `prefix` as dynamically-inferred **`text`** — which+/// includes catalogs first created by an EARLIER release and only later touched+/// by one of those (see [`install_catalog_mapping`] for that history). A `term`+/// query is not analyzed, but the FIELD is: against+/// `text` it matches when one of the stored value's analyzed TOKENS equals the+/// term. So `{"term": {"prefix": "ax"}}` also reaches a document whose prefix is+/// `ax-2` (tokens `[ax, 2]`) — a **sibling corpus's** document, which is exactly+/// the cross-corpus over-delete #737 drew the scope to prevent, and a delete is+/// not recoverable.+///+/// The scope therefore cannot rest on the query alone. The server-side query+/// stays — it is what keeps the candidate set small — but it is treated as a+/// *filter*, not as the decision: every returned hit is re-checked against the+/// raw scope values here, and only the exact ones are deleted, by `_id`. That is+/// mapping-independent by construction, so it holds on a keyword catalog and on+/// a legacy text one alike, and it holds for the `path`/`file_key` conjunct as+/// well as for the corpus scope. Where the field really is a keyword the result+/// is identical to the delete this replaces, up to the page budget below: past+/// [`SCOPED_SWEEP_MAX_PAGES`] * [`SCOPED_SWEEP_PAGE`] candidates for one scope+/// conjunction this refuses where the old `_delete_by_query` would have kept+/// going.+///+/// It cannot invent coverage the query does not return: on a legacy catalog an+/// analyzed field can also match FEWER documents than it should (a multi-token+/// value like `vendor/LICENSE` produces no token equal to itself, so a `term`+/// finds nothing), and no client-side check can recover a hit the server never+/// sent. That under-match is #755's subject, answered by+/// `catalog::CORPUS_SCOPE_FIELD` and by the by-`_id` sweep in the caller; this+/// function is only about never deleting more than the scope names.+fn delete_catalog_docs_scoped(es: &Es, scope: &[(&str, &str)]) -> Result<()> {+ let query = json!({"bool": {"filter": scope+ .iter()+ .map(|(field, value)| json!({"term": {*field: *value}}))+ .collect::<Vec<Value>>()}});+ let mut ids: Vec<String> = Vec::new();+ let mut from = 0usize;+ for _ in 0..SCOPED_SWEEP_MAX_PAGES {+ let page = es.search(+ catalog::CATALOG_INDEX,+ &json!({"query": query.clone(), "from": from, "size": SCOPED_SWEEP_PAGE}),+ )?;+ let hits = page+ .pointer("/hits/hits")+ .and_then(Value::as_array)+ .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());+ }+ }+ }+ from += hits.len();+ // The candidate set is exhausted on a short page — and ALSO once the+ // hits seen reach an EXACT `hits.total`. Both rules are needed: at+ // exactly `SCOPED_SWEEP_MAX_PAGES * SCOPED_SWEEP_PAGE` candidates every+ // page comes back full, so the short-page rule alone falls out of the+ // loop and refuses while already holding the complete, re-checked set.+ //+ // `relation: "gte"` is an honest LOWER bound rather than a count (a+ // capped hybrid sub-list, a timed-out scan), so it is never trusted to+ // end the walk; that case falls back to the short-page rule alone.+ let total_is_exact =+ page.pointer("/hits/total/relation").and_then(Value::as_str) != Some("gte");+ let total = page.pointer("/hits/total/value").and_then(Value::as_u64);+ let exhausted = hits.len() < SCOPED_SWEEP_PAGE+ || (total_is_exact && total.is_some_and(|total| from as u64 >= total));+ if exhausted {+ // The whole candidate set has been seen. Delete the exact ones, in+ // requests that stay requests — the same bound, and for the same+ // reason, as the duplicate-alias sweep's [`ALIAS_SWEEP_CHUNK`].+ for chunk in ids.chunks(ALIAS_SWEEP_CHUNK) {+ es.delete_by_query(catalog::CATALOG_INDEX, &json!({"ids": {"values": chunk}}))?;+ }+ return Ok(());+ }+ }+ // Refusing beats deleting a prefix of the set and reporting success: an+ // exclusion that only partly removes data is the #439 exposure. Reaching+ // here needs MORE than `SCOPED_SWEEP_MAX_PAGES * SCOPED_SWEEP_PAGE` (10k)+ // catalog documents matching one file's scope conjunction. A keyword+ // catalog CAN produce that — one content group of 10k+ byte-identical+ // files, each carrying its own alias doc — so this is a real, if narrow,+ // narrowing of the `_delete_by_query` it replaces, which repeated+ // 10k-document passes of its own. It fails CLOSED, and the remedy it names+ // 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",+ catalog::CATALOG_INDEX,+ scope+ .iter()+ .map(|(field, value)| format!("{field}={value}"))+ .collect::<Vec<_>>()+ .join(", "),+ catalog::CATALOG_INDEX,+ ))+}+/// #589: sweep the documents an exclusion left behind. A file still on disk/// that a widened ignore/hidden/`.xerjignore` rule now skips must have its/// already-published documents removed — an exclusion that cannot remove data@@ -3599,32 +3739,23 @@ fn sweep_excluded_groups(// engine and this crate already exercise, and neither drops its scope// term.//- // Honest bound on the `prefix` pass, inherited from #737 and NOT fixed- // here: it is exactly scoped only where `prefix` really is a keyword. On- // a legacy catalog that holds it as `text`, a `term` matches the- // analyzed TOKENS, so a single-token scope value (`ax`) also matches a- // sibling corpus whose prefix is `ax-2` (tokens `[ax, 2]`) — the- // cross-corpus over-delete #737 exists to prevent. The conjunction- // bounds it: only a sibling doc that ALSO carries this file's exact- // `path`/`file_key` is reachable, i.e. a byte-identical file shared with- // that sibling, and a multi-token prefix (`xc-ml-libs`) can never match- // an analyzed field at all. The `_reindex` in the legacy-catalog warning- // is what retires it; #890 tracks skipping this pass outright once the- // mapping install has established that `prefix` is legacy text.+ // #890: neither pass may be a bare `delete_by_query`. On a catalog+ // upgraded from rc.15..rc.67 `prefix` is `text`, and a `term` against an+ // analyzed field matches TOKENS — `prefix: "ax"` also reaches a sibling+ // corpus whose prefix is `ax-2` (tokens `[ax, 2]`), deleting ITS catalog+ // documents for a byte-identical file. `delete_catalog_docs_scoped`+ // keeps the same query as the candidate filter and then re-checks every+ // scope value against the returned `_source` before deleting by `_id`,+ // so the scope is exact whatever the catalog's mapping says — for the+ // `path`/`file_key` conjunct as much as for the corpus scope.for scope_field in [catalog::CORPUS_SCOPE_FIELD, "prefix"] {- es.delete_by_query(- catalog::CATALOG_INDEX,- &json!({"bool": {"filter": [- {"term": {scope_field: prefix}},- {"term": {"path": entry.path}},- ]}}),- )- .with_context(|| {- format!(- "sweep catalog entry ({scope_field}-scoped) for newly-excluded {}",- entry.path- )- })?;+ delete_catalog_docs_scoped(es, &[(scope_field, prefix), ("path", &entry.path)])+ .with_context(|| {+ format!(+ "sweep catalog entry ({scope_field}-scoped) for newly-excluded {}",+ entry.path+ )+ })?;}// #693: also purge the file's `file-alias:` duplicate catalog docs// (`catalog::duplicate_file_doc`). Each carries the DUPLICATE's own@@ -3636,20 +3767,16 @@ fn sweep_excluded_groups(// `file_key` term cannot strand a still-live byte-identical duplicate in// the same corpus; the `prefix` filter (#737) guards the cross-corpus axis.// #755: both scope fields, for the reason given on the delete above.+ // #890: and both through the exact scoped delete, for the reason given+ // there — an alias sweep runs on the same cross-corpus axis.for scope_field in [catalog::CORPUS_SCOPE_FIELD, "prefix"] {- es.delete_by_query(- catalog::CATALOG_INDEX,- &json!({"bool": {"filter": [- {"term": {scope_field: prefix}},- {"term": {"file_key": entry.file_key}},- ]}}),- )- .with_context(|| {- format!(- "sweep catalog aliases ({scope_field}-scoped) for newly-excluded {}",- entry.path- )- })?;+ delete_catalog_docs_scoped(es, &[(scope_field, prefix), ("file_key", &entry.file_key)])+ .with_context(|| {+ format!(+ "sweep catalog aliases ({scope_field}-scoped) for newly-excluded {}",+ entry.path+ )+ })?;}// #739: the two scoped deletes above match only docs that carry the// `prefix` field, which was added in #737 — a `file:` doc written by a