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): never abort a run over a legacy global-catalog mapping (#755) (#886)
xerj-org18a3692bf589
diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rsindex 1790c1464..daee0b289 100644--- a/engine/crates/xerj-autoindex/src/catalog.rs+++ b/engine/crates/xerj-autoindex/src/catalog.rs@@ -8,6 +8,32 @@ use serde_json::{json, Value};pub const CATALOG_INDEX: &str = "autoindex-catalog";+/// The corpus-scope field the #737/#693 exclusion sweeps term-query (#755).+///+/// It exists because `prefix` cannot be relied on to be a `keyword` on an+/// upgraded install. v1.0.0-rc.15 (`61b31ef3`) started writing `prefix` on the+/// catalog's run document while [`catalog_mapping`] still did not declare it,+/// so every catalog touched by rc.15..rc.67 has `prefix` **dynamically inferred+/// as `text`** — and a `term` query against an analyzed field does not match a+/// raw scope value. #737 (rc.68) then declared `prefix` as `keyword` and+/// installed it with a hard `update_mapping`, which is the 400 that aborted+/// every run on those installs.+///+/// This field is the migration: no release before this one ever wrote it, so no+/// existing catalog can hold a conflicting inferred type for it, and declaring+/// it `keyword` is always accepted. Every catalog document that carries+/// `prefix` carries `corpus_scope` with the same value, and the sweeps query+/// both — `prefix` for documents written by rc.68..this release on a catalog+/// where it really is a keyword, `corpus_scope` for everything written from+/// here on.+///+/// It is installed **additively**, by `ensure_generation_mappings` on the+/// generated path and by its own tolerant install on the legacy graph path —+/// deliberately not by [`catalog_mapping`], whose value is a frozen digest an+/// already-committed generation is compared against. See that function's second+/// tripwire.+pub const CORPUS_SCOPE_FIELD: &str = "corpus_scope";+/// Explicit mapping for a **freshly created** catalog index.////// Tripwire — `started` is bimodal across installs, on purpose. This function@@ -43,6 +69,20 @@ pub const CATALOG_INDEX: &str = "autoindex-catalog";/// server-side range query, `sort`, or date aggregation on `started` must first/// migrate legacy catalogs by reindexing them — not by adding `started` to the/// additive upgrade, which is exactly the abort above.+///+/// Second tripwire — **this value is a frozen on-disk contract** (#755). It is+/// hashed into `index_identity` by `generation_contract_identities`, and that+/// digest is written into every committed generation's execution record in the+/// journal. Two live comparisons then demand equality against a record an+/// *older binary* froze: the incremental-reconcile no-change arm, and+/// `provision_generation`'s replay of a pending generation. So adding or+/// removing a property here does not "plan a fresh generation" — it makes the+/// next run of every existing state dir abort, permanently on the no-change arm+/// because that arm writes no new generation. A field the catalog needs but the+/// contract does not can be installed additively in `ensure_generation_mappings`+/// (`duplicate_of`, `CORPUS_SCOPE_FIELD`) instead. `catalog_mapping_is_the_frozen_on_disk_contract`+/// pins the current value; changing it deliberately means also giving the+/// identity comparisons an upgrade path.pub fn catalog_mapping() -> Value {// The trailing run-metadata fields are inserted after the literal rather// than written inside it: `serde_json::json!` recurses once per key, and at@@ -114,6 +154,12 @@ pub fn catalog_mapping() -> Value {// sibling corpus would otherwise be caught by an unscoped `file_key`/`path`// sweep. Written by `file_doc`/`duplicate_file_doc` (the sweep's targets).properties.insert("prefix".into(), json!({"type": "keyword"}));+ // #755: `CORPUS_SCOPE_FIELD` is deliberately NOT declared here. This+ // function's value is hashed into `index_identity` (see the frozen-digest+ // tripwire on this function), so declaring it would move the digest and+ // abort every already-committed state dir on upgrade. It is installed+ // additively in `ensure_generation_mappings`, the same way `duplicate_of`+ // is, which is outside the hash.mapping}@@ -200,6 +246,9 @@ pub fn file_doc(json!({"doc_kind": "file","prefix": prefix, // #737: corpus scope for a scoped exclusion sweep+ // #755: the same scope on a field that is `keyword` even on a+ // catalog whose `prefix` an older build left inferred as `text`.+ CORPUS_SCOPE_FIELD: prefix,"file_key": file_key,"path": path,"format": format,@@ -228,6 +277,8 @@ pub fn duplicate_file_doc(json!({"doc_kind": "file","prefix": prefix, // #737: corpus scope for a scoped exclusion sweep+ // #755: keyword-safe scope, see `file_doc`.+ CORPUS_SCOPE_FIELD: prefix,"file_key": file_key,"path": path,"format": "duplicate",diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex 1ee9c2ec5..5125290b0 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -79,6 +79,10 @@ struct MockState {response_delay_ms: u64,catalog_preexists: bool,catalog_mapping_upgraded: bool,+ /// #755: whether a catalog `_mapping` PUT declared the keyword corpus-scope+ /// field. On this legacy path it arrives in its own PUT, because `prefix`+ /// cannot be re-declared on a catalog that already holds it as `text`.+ catalog_corpus_scope_mapped: bool,catalog_bulk_before_upgrade: bool,/// Set if the additive mapping upgrade ever asks for `started`. This is/// the executable half of `catalog::catalog_mapping`'s tripwire: against a@@ -256,6 +260,10 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {.and_then(Value::as_str).is_some()});+ let corpus_scope_requested = mapping+ .pointer(&format!("/properties/{}/type", catalog::CORPUS_SCOPE_FIELD))+ .and_then(Value::as_str)+ == Some("keyword");let mut locked = state.lock().unwrap();locked.started_mapping_requested |= started_requested;if locked.catalog_preexists && started_requested {@@ -288,7 +296,12 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {}),)} else {- locked.catalog_mapping_upgraded = upgraded;+ // #755: the additive upgrade and the corpus-scope field arrive in+ // SEPARATE PUTs now, so this accumulates rather than overwrites —+ // the flag means "the additive upgrade has landed", and the guard+ // that new run metadata must not precede it depends on that.+ locked.catalog_mapping_upgraded |= upgraded;+ locked.catalog_corpus_scope_mapped |= corpus_scope_requested;(200, json!({"acknowledged": true}))}} else if method == "POST" && path == "/_bulk" {@@ -1686,6 +1699,14 @@ fn existing_catalog_is_upgraded_before_new_run_metadata_is_written() {);let state = endpoint.state.lock().unwrap();assert!(state.catalog_mapping_upgraded);+ assert!(+ state.catalog_corpus_scope_mapped,+ "#755: the legacy path must also install the keyword `{}` field — `prefix` is not \+ re-declarable on a catalog that already holds it as text (rc.15..rc.67 inferred it \+ from the run document), so the #737/#693 scoped sweeps have nothing exact to match \+ on without it",+ catalog::CORPUS_SCOPE_FIELD+ );assert!(!state.started_mapping_requested,"the additive upgrade asked a legacy catalog for `started`; a real v1.0.0-rc.4 catalog \diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 3180cddbb..f5f106130 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -32,12 +32,23 @@ struct HttpState {embedding_identity_sha256: String,saw_dataset_mapping_update: bool,saw_catalog_mapping_update: bool,- /// Opt-in (#755/#760): make the catalog `_mapping` PUT fail with the exact- /// `field [X] already exists as [text]` conflict an older-build catalog- /// produces, so a test can prove the run surfaces the ENRICHED error rather- /// than the opaque mapper_parsing_exception. Off by default — every other- /// test's faithful-accept behaviour is unchanged.- catalog_mapping_conflict: bool,+ /// Opt-in (#755/#760): the fields this catalog already holds as `text`,+ /// standing in for an older-build (v1.0.0-rc.15..rc.67) catalog. A catalog+ /// `_mapping` PUT that still declares one of them fails with the exact+ /// `field [X] already exists as [text]` conflict a real engine produces;+ /// 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.+ 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.+ catalog_mapping_unavailable: bool,+ /// The `properties` object of the last catalog `_mapping` PUT the endpoint+ /// ACKNOWLEDGED — what a legacy catalog actually ends up declaring.+ installed_catalog_properties: Option<Value>,+ /// How many catalog `_mapping` PUTs were attempted (the drop-and-retry+ /// loop's cost).+ catalog_mapping_puts: usize,}struct HttpEndpoint {@@ -94,6 +105,28 @@ impl HttpEndpoint {fn data_bulk_requests(&self) -> usize {self.state.lock().unwrap().data_bulk_requests}++ /// #755: the catalog mapping the endpoint finally acknowledged.+ fn installed_catalog_properties(&self) -> Value {+ self.state+ .lock()+ .unwrap()+ .installed_catalog_properties+ .clone()+ .expect("no catalog _mapping PUT was acknowledged")+ }++ /// #755: every catalog document the run published.+ fn catalog_docs(&self) -> Vec<Value> {+ self.state+ .lock()+ .unwrap()+ .docs+ .iter()+ .filter(|((index, _), _)| index == catalog::CATALOG_INDEX)+ .map(|(_, doc)| doc.clone())+ .collect()+ }}impl Drop for HttpEndpoint {@@ -185,13 +218,26 @@ fn handle_http(mut stream: TcpStream, state: &Arc<Mutex<HttpState>>) {} else if method == "PUT" {let value: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);let mut locked = state.lock().unwrap();- let mut inject_catalog_conflict = false;+ // #755: the first still-declared field this catalog already holds as+ // `text`, if any — the engine reports one conflict per request.+ let mut conflict: Option<String> = None;+ let mut unavailable = false;if path.ends_with("/_mapping") {assert!(value.get("properties").is_some());assert!(value.get("mappings").is_none());if path.starts_with(&format!("/{}/", catalog::CATALOG_INDEX)) {locked.saw_catalog_mapping_update = true;- inject_catalog_conflict = locked.catalog_mapping_conflict;+ locked.catalog_mapping_puts += 1;+ unavailable = locked.catalog_mapping_unavailable;+ let declared = value["properties"].as_object().cloned().unwrap_or_default();+ conflict = locked+ .legacy_text_catalog_fields+ .iter()+ .find(|field| declared.contains_key(field.as_str()))+ .cloned();+ if conflict.is_none() && !unavailable {+ locked.installed_catalog_properties = Some(Value::Object(declared));+ }} else {locked.saw_dataset_mapping_update = true;}@@ -199,8 +245,13 @@ fn handle_http(mut stream: TcpStream, state: &Arc<Mutex<HttpState>>) {assert!(value.pointer("/mappings/properties").is_some());assert!(value.get("properties").is_none());}- if inject_catalog_conflict {- let reason = "field [prefix] already exists as [text], cannot add [keyword]";+ if unavailable {+ (+ 503,+ json!({"error": {"type": "unavailable_shards_exception", "reason": "no node"}}),+ )+ } else if let Some(field) = conflict {+ let reason = format!("field [{field}] already exists as [text], cannot add [keyword]");(400,json!({@@ -226,6 +277,7 @@ fn handle_http(mut stream: TcpStream, state: &Arc<Mutex<HttpState>>) {match status {200 => "OK",400 => "Bad Request",+ 503 => "Service Unavailable",_ => "Internal Server Error",},bytes.len(),@@ -560,36 +612,292 @@ fn final_snapshot_count(state_dir: &Path) -> usize {.unwrap_or(0)}-/// #755/#760: an older-build global catalog holds a field mapped as `text`, so-/// the generation's keyword `_mapping` update conflicts. The run must surface-/// the ENRICHED, actionable error (name the field + reindex recovery), not the-/// opaque `mapper_parsing_exception`. This exercises the `.map_err` wiring end to-/// end — the helper's own unit tests pass even if that wiring is dropped, so-/// this is what actually guards it (evidence lens, #756 review).+/// #755: an older-build global catalog holds `prefix` (and, on a fully dynamic+/// catalog, `doc_kind`) mapped as `text`, so the generation's keyword `_mapping`+/// update conflicts. Before this fix the whole run aborted — and because+/// `autoindex-catalog` is ONE index shared by every corpus on the node, that+/// bricked `xerj autoindex` outright for anyone upgrading from v1.0.0-rc.15..67.+///+/// An upgrade must never abort a run over a mapping an earlier release left+/// behind: the run has to complete, every field the engine will accept has to be+/// installed, and corpus scoping has to keep working — which it does by moving+/// onto `catalog::CORPUS_SCOPE_FIELD`, a keyword field no older release wrote.+///+/// End-to-end on purpose (#760): `install_catalog_mapping`'s own unit tests pass+/// even if the wiring at the catalog `update_mapping` is dropped, so this is what+/// actually guards it.#[test]-fn a_legacy_text_mapped_catalog_surfaces_the_actionable_error() {+fn a_legacy_text_mapped_catalog_completes_the_run_instead_of_aborting() {let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());let corpus = tempfile::tempdir().unwrap();let state_dir = tempfile::tempdir().unwrap();fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n").unwrap();let endpoint = HttpEndpoint::start();- endpoint.state.lock().unwrap().catalog_mapping_conflict = true;+ endpoint.state.lock().unwrap().legacy_text_catalog_fields =+ vec!["prefix".into(), "doc_kind".into()];let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);- let error = run_index(config).unwrap_err();- let msg = format!("{error:#}");+ // The run COMPLETES. This is the whole bug: it used to abort here.+ assert_eq!(run_index(config).unwrap(), 0);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);+ assert_eq!(endpoint.data_docs().len(), 1);++ // Exactly the two legacy fields were given up, and nothing else.+ let installed = endpoint.installed_catalog_properties();+ let installed = installed.as_object().expect("properties object");+ assert!(+ !installed.contains_key("prefix") && !installed.contains_key("doc_kind"),+ "a field the catalog already holds as text cannot be re-declared: {installed:?}"+ );+ assert_eq!(+ installed["path"]["type"], "keyword",+ "every non-conflicting field must still be installed: {installed:?}"+ );+ // …including the keyword field corpus scoping moved onto. No release ever+ // wrote it, so a legacy catalog cannot be holding it as text.+ assert_eq!(+ installed[catalog::CORPUS_SCOPE_FIELD]["type"],+ "keyword",+ "the corpus-scope field must survive the legacy conflict: {installed:?}"+ );++ // And the published catalog documents carry the scope on that field, so the+ // #737/#693 scoped sweeps stay exact on this node.+ let scoped = endpoint+ .catalog_docs()+ .into_iter()+ .filter(|doc| doc.get("doc_kind").and_then(Value::as_str) == Some("file"))+ .collect::<Vec<_>>();+ assert!(!scoped.is_empty(), "the run published no file catalog docs");+ for doc in &scoped {+ assert_eq!(+ doc[catalog::CORPUS_SCOPE_FIELD],+ "incremental-http",+ "every file catalog doc must carry the keyword corpus scope: {doc}"+ );+ }+}++/// #755: the conflict tolerance is narrow on purpose. A catalog `_mapping` PUT+/// that fails for any reason OTHER than a legacy field type — an unreachable+/// node, a 503, an unrelated 400 — is a real failure and must still abort,+/// rather than being retried into a silently narrower catalog mapping.+#[test]+fn an_unavailable_catalog_mapping_still_aborts_the_run() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n").unwrap();+ let endpoint = HttpEndpoint::start();+ endpoint.state.lock().unwrap().catalog_mapping_unavailable = true;+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);++ let msg = format!("{:#}", run_index(config).unwrap_err());assert!(- msg.contains("older build") && msg.contains("Reindex"),- "expected the enriched migration error, got: {msg}"+ msg.contains("install generation catalog mapping") && msg.contains("503"),+ "an unrelated mapping failure must abort with its own reason: {msg}"+ );+ assert_eq!(+ endpoint.state.lock().unwrap().catalog_mapping_puts,+ 1,+ "a non-conflict failure must not be retried: {msg}"+ );+}++/// #755: tolerating the legacy mapping is not the same as hiding it. Documents+/// an older build already wrote keep the legacy type, so a scoped sweep can+/// still miss them — the operator has to be told, through the progress surface+/// that owns stderr (#241), with the reindex that retires the field.+#[test]+fn a_legacy_text_mapped_catalog_warns_through_the_progress_surface() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());+ let endpoint = HttpEndpoint::start();+ endpoint.state.lock().unwrap().legacy_text_catalog_fields = vec!["prefix".into()];+ let es = Es::with_bulk_timeout(&endpoint.url, None, 30).expect("es client");+ let (pr, sink) = progress::Progress::capture(+ progress::Surface::Plain,+ std::time::Duration::from_secs(3600),+ );++ ensure_generation_mappings(&es, &Plan::default(), &pr).expect("legacy catalog must not abort");++ let text = String::from_utf8(sink.lock().unwrap().clone()).unwrap();+ assert!(+ text.contains("older build") && text.contains("`prefix`"),+ "the operator must be told which field is legacy: {text}");- // The named field and the raw reason are both preserved in the chain.assert!(- msg.contains("`prefix`"),- "must name the conflicting field: {msg}"+ text.contains("run CONTINUES") && text.contains("_reindex"),+ "…and what happened plus how to retire it: {text}"+ );+ assert!(+ text.contains(catalog::CORPUS_SCOPE_FIELD),+ "…and where corpus scoping moved to: {text}"+ );+}++/// #755: a healthy catalog is untouched — one `_mapping` PUT, nothing dropped.+#[test]+fn a_current_catalog_installs_its_mapping_in_a_single_put() {+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());+ let endpoint = HttpEndpoint::start();+ let es = Es::with_bulk_timeout(&endpoint.url, None, 30).expect("es client");+ let (pr, sink) = progress::Progress::capture(+ progress::Surface::Plain,+ std::time::Duration::from_secs(3600),+ );++ ensure_generation_mappings(&es, &Plan::default(), &pr).expect("fresh catalog");++ assert_eq!(endpoint.state.lock().unwrap().catalog_mapping_puts, 1);+ assert_eq!(+ endpoint.installed_catalog_properties()["prefix"]["type"],+ "keyword",+ "a catalog with no legacy field keeps the full declared mapping");assert!(- msg.contains("already exists as [text]"),- "must preserve the raw reason: {msg}"+ String::from_utf8(sink.lock().unwrap().clone())+ .unwrap()+ .is_empty(),+ "a healthy catalog must not warn"+ );+}++/// Rewrite a journal so every generation in it carries the `index_identity` the+/// PREVIOUSLY SHIPPED release froze for the same plan — the exact on-disk state+/// of an install that is being upgraded.+///+/// The digests that bind the log are recomputed with it (`desired_manifest_digest`+/// on the begin/validate/commit records, and the next generation's+/// `base_manifest_digest`), so the journal stays internally valid and the only+/// thing that has moved is the frozen contract identity. Returns the identity+/// written in (previous release) and the one this build had written (this+/// build); while the contract holds they are equal and the rewrite is a+/// byte-for-byte no-op — that is the property under test.+fn freeze_journal_identities_as_previous_release(state_dir: &Path) -> (String, String) {+ let path = state_dir.join("journal.ndjson");+ let raw = fs::read_to_string(&path).unwrap();+ let mut previous_release = None;+ let mut this_build = None;+ let mut committed_digest: Option<String> = None;+ let mut pending_digest: Option<String> = None;+ let mut out = String::new();+ for line in raw.lines() {+ let Ok(mut record) = serde_json::from_str::<Value>(line) else {+ out.push_str(line);+ out.push('\n');+ continue;+ };+ match record.get("kind").and_then(Value::as_str) {+ Some("sync_begin") => {+ if let Some(digest) = &committed_digest {+ record["base_manifest_digest"] = json!(digest);+ }+ let plan: Plan = serde_json::from_value(record["desired"]["plan"].clone()).unwrap();+ let frozen = frozen_contract::index_identity(&plan);+ this_build = record["desired"]["execution"]["index_identity"]+ .as_str()+ .map(str::to_owned);+ record["desired"]["execution"]["index_identity"] = json!(frozen);+ previous_release = Some(frozen);+ let manifest: crate::sync::GenerationManifest =+ serde_json::from_value(record["desired"].clone()).unwrap();+ let digest = crate::sync::manifest_digest(&manifest).unwrap();+ record["desired_manifest_digest"] = json!(digest);+ pending_digest = Some(digest);+ }+ Some("sync_validated") | Some("sync_abort") => {+ record["desired_manifest_digest"] = json!(pending_digest.clone().unwrap());+ }+ Some("sync_commit") => {+ let digest = pending_digest.clone().unwrap();+ record["desired_manifest_digest"] = json!(digest);+ committed_digest = Some(digest);+ }+ _ => {}+ }+ out.push_str(&serde_json::to_string(&record).unwrap());+ out.push('\n');+ }+ fs::write(&path, out).unwrap();+ (+ previous_release.expect("the journal has a sync_begin"),+ this_build.expect("the sync_begin carries an execution identity"),+ )+}++/// #755 upgrade path, end to end: generations frozen by the PREVIOUS RELEASE+/// must still be reconcilable by this build.+///+/// `index_identity` is hashed out of `catalog::catalog_mapping()` and frozen in+/// the journal's execution record, and two hard `ensure!`s then demand equality+/// against it: `provision_generation` when a pending (mid-commit) generation is+/// replayed ("desired generation index identity disagrees with its frozen+/// mappings"), and the incremental-reconcile no-change arm ("autoindex+/// execution configuration changed since the committed generation") — which+/// writes no new generation, so a mismatch there never heals. Declaring one+/// extra catalog property would therefore trade #755's abort for a different+/// abort against the very same upgrading population.+///+/// Both arms run here over a journal rewritten to the previous release's+/// identity: an unchanged corpus first (the no-change arm), then a generation+/// left pending mid-commit (the replay).+/// `catalog_mapping_is_the_frozen_on_disk_contract` pins the contract itself;+/// this test pins the wiring that consumes it.+#[test]+fn a_generation_frozen_by_the_previous_release_still_reconciles() {+ 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 corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let source = corpus.path().join("a.csv");+ fs::write(&source, "id,value\n1,committed\n").unwrap();+ let endpoint = HttpEndpoint::start();+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);++ // One committed generation, aged to the previous release's contract.+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ let (previous_release, this_build) =+ freeze_journal_identities_as_previous_release(state_dir.path());++ // Unchanged corpus → the no-change arm's ensure!. This is the permanent+ // one: it commits no new generation, so a mismatch here never heals.+ let unchanged = run_index(config.clone()).unwrap_or_else(|error| {+ panic!(+ "an unchanged corpus committed by the previous release must reconcile, not abort \+ (previous release froze {previous_release}, this build computes {this_build}): \+ {error:#}"+ )+ });+ assert_eq!(unchanged, 0);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);++ // Now a generation left pending mid-commit, aged the same way.+ fs::write(&source, "id,value\n1,sealed-pending\n2,sealed-second\n").unwrap();+ endpoint.state.lock().unwrap().fail_next_data_bulk = true;+ assert!(run_index(config.clone()).is_err());+ assert_eq!(journal_events(state_dir.path(), "sync_begin"), 2);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 1);+ let (previous_release, this_build) =+ freeze_journal_identities_as_previous_release(state_dir.path());++ // Replay of that pending generation → `provision_generation`'s ensure!.+ let resumed = run_index(config).unwrap_or_else(|error| {+ panic!(+ "a pending generation frozen by the previous release must replay, not abort \+ (previous release froze {previous_release}, this build computes {this_build}): \+ {error:#}"+ )+ });+ assert_eq!(resumed, 0);+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 2);+ assert_eq!(endpoint.data_docs().len(), 2);+ assert_eq!(+ previous_release, this_build,+ "this build must compute the identity the previous release froze; the catalog mapping \+ is hashed into it, so a property added there aborts every upgraded state dir");}@@ -2482,6 +2790,93 @@ fn sweep_excluded_groups_does_not_delete_a_sibling_corpus_catalog_doc() {);}+/// #755: the scope the sweep actually relies on is `corpus_scope`, not+/// `prefix`. On a catalog upgraded from v1.0.0-rc.15..rc.67, `prefix` is+/// dynamically mapped `text`, so a `term` against it does not match the raw+/// scope value and the #737/#693 scoped deletes silently no-op — an alias doc+/// that the frozen plan does not name is then left searchable, which is exactly+/// the #439 exposure #589 exists to close. The docs seeded here carry ONLY the+/// keyword scope field, standing in for a catalog whose `prefix` cannot be+/// term-matched; the sweep must still find this corpus's docs and must still+/// leave the live sibling corpus's alone.+///+/// Fail-before: with only the `prefix`-scoped deletes (pre-#755), the `ax` alias+/// doc below survives the sweep.+#[test]+fn sweep_excluded_groups_scopes_on_the_keyword_corpus_scope_field() {+ let ep = HttpEndpoint::start();++ {+ let mut st = ep.state.lock().unwrap();+ // An alias doc the frozen plan does not name, so ONLY the term-scoped+ // `file_key` delete can reach it — the `_id` sweep cannot.+ st.docs.insert(+ (+ catalog::CATALOG_INDEX.to_string(),+ "file-alias:ax:unlisted".into(),+ ),+ json!({+ "doc_kind": "file",+ catalog::CORPUS_SCOPE_FIELD: "ax",+ "file_key": "shared-key",+ "path": "vendor/LICENSE",+ "status": "duplicate",+ }),+ );+ // A live sibling corpus's byte-identical doc under its own scope.+ st.docs.insert(+ (+ catalog::CATALOG_INDEX.to_string(),+ "file-alias:bx:sibling".into(),+ ),+ json!({+ "doc_kind": "file",+ catalog::CORPUS_SCOPE_FIELD: "bx",+ "file_key": "shared-key",+ "path": "vendor/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: "vendor/LICENSE".into(),+ }];++ sweep_excluded_groups(&es, "ax", &plan, &excluded, None, 0).expect("sweep");++ let st = ep.state.lock().unwrap();+ assert!(+ !st.docs.contains_key(&(+ catalog::CATALOG_INDEX.to_string(),+ "file-alias:ax:unlisted".to_string()+ )),+ "#755: an excluded file's catalog doc must be swept on the keyword scope \+ field, not only on a `prefix` an upgraded catalog holds as text"+ );+ assert!(+ st.docs.contains_key(&(+ catalog::CATALOG_INDEX.to_string(),+ "file-alias:bx:sibling".to_string()+ )),+ "#755: the keyword scope must still bound the sweep to THIS corpus"+ );+}+/// #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 6e23b7548..f40d36b8e 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -186,7 +186,68 @@ pub(crate) fn generation_contract_identities(plan: &Plan) -> Result<(String, Str))}-pub(crate) fn ensure_generation_mappings(es: &Es, plan: &Plan) -> Result<()> {+/// The generation contract exactly as the shipped releases froze it on disk+/// (#755).+///+/// `index_identity` is written into every committed generation's execution+/// record in the journal and then compared for **equality** on the next run —+/// on the incremental-reconcile no-change arm, and in `provision_generation`+/// when a pending generation is replayed. So the identity this build computes+/// for a plan has to equal the identity the *previously shipped* build computed+/// for the same plan, or upgrading aborts every existing state dir. That is the+/// abort class this change exists to remove, so it must not be reintroduced by+/// the change itself.+///+/// This fixture is the shipped side of that equality: `CATALOG_MAPPING_JSON` is+/// `catalog::catalog_mapping()` serialized, captured verbatim from the+/// v1.0.0-rc.68..rc.71 tree (the releases that wrote the journals now in the+/// field), and [`index_identity`] mirrors `generation_contract_identities`'+/// index digest over it. `catalog_mapping_is_the_frozen_on_disk_contract`+/// compares the two; `a_generation_frozen_by_the_previous_release_still_reconciles`+/// runs the indexer over a journal carrying it.+#[cfg(test)]+pub(crate) mod frozen_contract {+ use super::*;++ /// `serde_json::to_string(&catalog::catalog_mapping())` on v1.0.0-rc.71.+ pub(crate) const CATALOG_MAPPING_JSON: &str = r#"{"mappings":{"properties":{"doc_kind":{"type":"keyword"},"slug":{"type":"keyword"},"index_name":{"type":"keyword"},"record_count":{"type":"long"},"junk_records":{"type":"long"},"bytes":{"type":"long"},"file_count":{"type":"long"},"formats":{"type":"keyword"},"time_field":{"type":"keyword"},"time_min":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"time_max":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"semantic_field":{"type":"keyword"},"fields_json":{"type":"text"},"sample_queries_json":{"type":"text"},"notes":{"type":"text"},"path":{"type":"keyword"},"file_key":{"type":"keyword"},"format":{"type":"keyword"},"status":{"type":"keyword"},"reason":{"type":"text"},"duplicate_of":{"type":"keyword"},"records":{"type":"long"},"junk":{"type":"long"},"run_id":{"type":"keyword"},"corr_kind":{"type":"keyword"},"a_dataset":{"type":"keyword"},"b_dataset":{"type":"keyword"},"a_index":{"type":"keyword"},"b_index":{"type":"keyword"},"a_field":{"type":"keyword"},"b_field":{"type":"keyword"},"grade":{"type":"keyword"},"overlap":{"type":"long"},"containment":{"type":"double"},"range_overlap":{"type":"double"},"pearson_r":{"type":"double"},"activity_correlated":{"type":"boolean"},"started":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"summary_generated_at":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"invocation_telemetry_scope":{"type":"keyword"},"junk_records_this_run":{"type":"long"},"prefix":{"type":"keyword"}}}}"#;++ /// The `index_identity` a v1.0.0-rc.68..rc.71 binary froze for `plan`:+ /// `generation_contract_identities`' index digest, hashing the mapping+ /// above instead of this build's `catalog::catalog_mapping()`.+ pub(crate) fn index_identity(plan: &Plan) -> String {+ let mut datasets = plan.datasets.iter().collect::<Vec<_>>();+ datasets.sort_by(|left, right| {+ left.slug+ .cmp(&right.slug)+ .then_with(|| left.index.cmp(&right.index))+ });+ let indices = datasets+ .iter()+ .map(|dataset| {+ json!({+ "index": dataset.index,+ "mapping": build_mapping(&dataset.specs),+ })+ })+ .collect::<Vec<_>>();+ let value = json!({+ "datasets": indices,+ "catalog_index": catalog::CATALOG_INDEX,+ "catalog_mapping": serde_json::from_str::<Value>(CATALOG_MAPPING_JSON)+ .expect("the frozen catalog mapping parses"),+ "document_ids": DOCUMENT_IDS_IDENTITY,+ });+ let bytes = serde_json::to_vec(&json!({+ "contract": DOCUMENT_IDS_IDENTITY,+ "value": value,+ }))+ .expect("the frozen contract serializes");+ format!("{:032x}", xxhash_rust::xxh3::xxh3_128(&bytes))+ }+}++pub(crate) fn ensure_generation_mappings(es: &Es, plan: &Plan, pr: &Progress) -> Result<()> {for dataset in &plan.datasets {let mut create_body = build_mapping(&dataset.specs);create_body["mappings"]["properties"]["ax_paths"] = json!({"type": "keyword"});@@ -200,38 +261,164 @@ pub(crate) fn ensure_generation_mappings(es: &Es, plan: &Plan) -> Result<()> {}let mut catalog_create_body = catalog::catalog_mapping();catalog_create_body["mappings"]["properties"]["duplicate_of"] = json!({"type": "keyword"});+ // #755: the corpus-scope field rides here, beside `duplicate_of`, and NOT+ // inside `catalog::catalog_mapping` — that function's value is hashed into+ // the `index_identity` frozen in every committed generation, so declaring a+ // new property there would abort the next run of every existing state dir+ // (the very upgrade abort this change exists to remove). This body is not+ // hashed, so the field is installed on every run without moving the digest.+ catalog_create_body["mappings"]["properties"][catalog::CORPUS_SCOPE_FIELD] =+ json!({"type": "keyword"});let catalog_update_body = json!({"properties": catalog_create_body["mappings"]["properties"].clone()});es.ensure_index(catalog::CATALOG_INDEX, &catalog_create_body)?;- es.update_mapping(catalog::CATALOG_INDEX, &catalog_update_body)- .map_err(|e| explain_legacy_catalog_mapping_conflict(catalog::CATALOG_INDEX, e))+ install_catalog_mapping(es, &catalog_update_body, pr).context("install generation catalog mapping")}-/// The generated catalog declares its fields as `keyword` (exact corpus-scoped-/// exclusion sweeps depend on it; #737 added `prefix`). A catalog created by an-/// older build can hold one of those fields dynamically mapped as `text`, and-/// Elasticsearch cannot change a field's type in place, so the additive-/// `update_mapping` fails with an opaque `mapper_parsing_exception` naming-/// whichever field it checked first. Name the cause and the (operator-driven,-/// data-preserving) recovery instead of surfacing the raw type conflict.+/// Install the catalog mapping without letting a legacy field type abort the+/// run (#755).///-/// An automatic reindex is deliberately NOT done here: the catalog is global-/// across every corpus and its scoping drives deletions, so migrating it is a-/// maintainer decision, not a silent side effect of a run.-fn explain_legacy_catalog_mapping_conflict(index: &str, err: anyhow::Error) -> anyhow::Error {- let msg = format!("{err:#}");- if let Some(field) = legacy_text_field_in_conflict(&msg) {- return err.context(format!(- "the global `{index}` was created by an older build: its `{field}` is mapped as text, \- but this version needs the catalog fields as keyword (corpus-scoped sweeps depend on \- exact matching) and Elasticsearch cannot change a field's type in place. Reindex \- `{index}` into an index with the current mapping (create a fresh index with the \- keyword mapping, `_reindex` into it, then swap), and retry"- ));+/// The global `autoindex-catalog` is shared by every corpus on the node and it+/// outlives releases, so it can already hold a field whose dynamically inferred+/// type disagrees with what this build declares — and Elasticsearch cannot+/// change a field's type in place. The concrete instance this exists for:+/// v1.0.0-rc.15 (`61b31ef3`) began writing `prefix` on the catalog's run+/// document while `catalog::catalog_mapping` still did not declare it, so every+/// catalog written by rc.15..rc.67 inferred `prefix` as **text**; #737 (rc.68)+/// then declared it `keyword` and installed it with a hard `update_mapping`.+/// The result was a 400 `mapper_parsing_exception` on *every* subsequent+/// autoindex run against that node — an upgrade that bricks the tool.+///+/// A run must never abort because of a mapping an *earlier* release left+/// behind. Elasticsearch reports one conflicting field per request, so this+/// drops the named field and retries, which converges in at most one attempt+/// per declared property: every field this build *can* install gets installed,+/// including `catalog::CORPUS_SCOPE_FIELD` — a field no release ever wrote, so+/// it is always accepted as `keyword` and carries the corpus scope the #737+/// sweeps need even on a catalog whose `prefix` is text.+///+/// What is tolerated is a *narrower declared mapping*. The operator is warned,+/// with the reindex that retires the legacy field. Two limits on that tolerance+/// are real, and neither is papered over:+///+/// * A leftover analyzed field does not merely match *fewer* documents. A+/// `term` against `text` matches the analyzed TOKENS, so a single-token scope+/// 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.+/// * 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+/// them — a catalog holding `run_id` as text would install without it and+/// then fail at the very end of the run in `finish_generated_run`, whose+/// `run_id` + `doc_kind` lookup requires exactly one hit. No catalog created+/// by `ensure_index` can be in that state (`catalog_mapping` declares+/// `run_id`); one auto-created by a stray document write could be.+///+/// An automatic reindex is deliberately still NOT done here: the catalog is+/// global across every corpus and its scoping drives deletions, so rewriting it+/// wholesale is a maintainer decision, not a silent side effect of a run.+fn install_catalog_mapping(es: &Es, body: &Value, pr: &Progress) -> Result<()> {+ let mut properties = body+ .get("properties")+ .and_then(Value::as_object)+ .cloned()+ .context("catalog mapping update body has no `properties` object")?;+ // One removal per iteration, so the loop is bounded by the declared field+ // count; the extra turn is the (empty-properties) fixed point.+ let attempts = properties.len() + 1;+ let mut legacy: Vec<String> = Vec::new();+ for _ in 0..attempts {+ let err = match es.update_mapping(+ catalog::CATALOG_INDEX,+ &json!({"properties": Value::Object(properties.clone())}),+ ) {+ Ok(()) => {+ if !legacy.is_empty() {+ pr.warn(&legacy_catalog_mapping_warning(+ catalog::CATALOG_INDEX,+ &legacy,+ ));+ }+ return Ok(());+ }+ Err(err) => err,+ };+ // Anything that is not a legacy type conflict — a 503, a refused+ // connection, an unrelated 400 — is a real failure and still aborts.+ let Some(field) = legacy_text_field_in_conflict(&format!("{err:#}")) else {+ return Err(err);+ };+ // The conflict names a field this request did not declare: dropping it+ // cannot make progress, so surface the error rather than spin. The+ // warning's "the run continues" wording would be a lie here, so this+ // says only what is true.+ if properties.remove(&field).is_none() {+ return Err(err.context(format!(+ "`{}` reports a type conflict on `{field}`, which this mapping update does not \+ declare — there is nothing to give up, so the conflict cannot be worked around \+ here. Reindex `{}` into an index created with the current mapping",+ catalog::CATALOG_INDEX,+ catalog::CATALOG_INDEX,+ )));+ }+ legacy.push(field);}- err+ anyhow::bail!(+ "`{}` mapping install did not converge after {attempts} attempts (legacy fields: {})",+ catalog::CATALOG_INDEX,+ legacy.join(", ")+ )+}++/// The operator-facing account of a legacy-mapped global catalog: which fields+/// an older build left as `text`, what the run did about it, and the+/// data-preserving reindex that retires them.+fn legacy_catalog_mapping_warning(index: &str, legacy: &[String]) -> String {+ let named = legacy+ .iter()+ .map(|field| format!("`{field}`"))+ .collect::<Vec<_>>()+ .join(", ");+ let (is, it) = if legacy.len() == 1 {+ ("is", "that field")+ } else {+ ("are", "those fields")+ };+ // Where the scope field itself is the casualty, saying "scoping travels on+ // it" would be exactly backwards. That needs something else on the node to+ // have written `corpus_scope` as text first, but the run must describe the+ // state it is actually in.+ let scoping = if legacy+ .iter()+ .any(|field| field == catalog::CORPUS_SCOPE_FIELD)+ {+ format!(+ "This catalog holds the corpus-scope field `{scope}` as text too, so NO exactly \+ matchable scope remains: a scoped sweep of an excluded file's catalog documents can \+ match nothing, or — on a single-token prefix — a sibling corpus's. Reindex before \+ relying on exclusions",+ scope = catalog::CORPUS_SCOPE_FIELD,+ )+ } else {+ format!(+ "corpus scoping travels on the keyword `{scope}` field that every catalog document \+ this build writes carries",+ scope = catalog::CORPUS_SCOPE_FIELD,+ )+ };+ format!(+ "autoindex: the global `{index}` was created by an older build — {named} {is} mapped as \+ text, and Elasticsearch cannot change a field's type in place. The run CONTINUES: every \+ other catalog field was installed as declared, and {scoping}. Documents an older build \+ left behind keep the legacy type, so a scoped sweep can still miss them — to retire \+ {it}, reindex `{index}` into an index created with the current mapping (fresh index with \+ the keyword mapping, `_reindex` into it, then swap)"+ )}/// Pull the field name out of an ES `field [X] already exists as [text], …`@@ -246,56 +433,81 @@ fn legacy_text_field_in_conflict(msg: &str) -> Option<String> {#[cfg(test)]mod catalog_mapping_conflict_tests {- use super::explain_legacy_catalog_mapping_conflict;+ use super::{legacy_catalog_mapping_warning, legacy_text_field_in_conflict};#[test]- fn legacy_text_prefix_conflict_is_explained_not_opaque() {- let raw = anyhow::anyhow!(- "PUT /autoindex-catalog/_mapping failed: 400 Bad Request \- field [prefix] already exists as [text], cannot add [keyword]"- );- let explained = format!(- "{:#}",- explain_legacy_catalog_mapping_conflict("autoindex-catalog", raw)- );- assert!(- explained.contains("older build")- && explained.contains("Reindex")- && explained.contains("`prefix`"),- "conflict must be explained with the field + migration path, got: {explained}"+ fn the_conflicting_field_is_pulled_out_of_the_mapper_exception() {+ let raw = "PUT /autoindex-catalog/_mapping failed: 400 Bad Request \+ field [prefix] already exists as [text], cannot add [keyword]";+ assert_eq!(+ legacy_text_field_in_conflict(raw).as_deref(),+ Some("prefix"));- // The original opaque reason is preserved in the chain.- assert!(explained.contains("already exists as [text]"));}#[test]fn a_different_legacy_text_field_is_named() {// Not just prefix: a fully-dynamic legacy catalog conflicts on whatever// field the server checks first (e.g. doc_kind).- let raw =- anyhow::anyhow!("field [doc_kind] already exists as [text], cannot add [keyword]");- let explained = format!(- "{:#}",- explain_legacy_catalog_mapping_conflict("autoindex-catalog", raw)+ let raw = "field [doc_kind] already exists as [text], cannot add [keyword]";+ assert_eq!(+ legacy_text_field_in_conflict(raw).as_deref(),+ Some("doc_kind")+ );+ }++ /// If the scope field itself is what the catalog holds as text, the warning+ /// must not go on claiming scoping "travels on" it. Nothing autoindex has+ /// ever written can put a catalog in that state, but a stray document write+ /// into the shared index can — which is exactly how #755's own repro+ /// manufactures a legacy `prefix`.+ #[test]+ fn a_legacy_scope_field_is_not_described_as_carrying_the_scope() {+ let warning = legacy_catalog_mapping_warning(+ "autoindex-catalog",+ &[crate::catalog::CORPUS_SCOPE_FIELD.to_string()],+ );+ assert!(+ warning.contains("NO exactly matchable scope remains"),+ "must say the scope is gone, not that it travels on the lost field: {warning}");assert!(- explained.contains("`doc_kind`") && explained.contains("Reindex"),- "must name the actual conflicting field, got: {explained}"+ !warning.contains("corpus scoping travels on"),+ "must not claim the dropped field carries the scope: {warning}"+ );+ assert!(+ warning.contains("_reindex"),+ "must still name the way out: {warning}");}#[test]- fn unrelated_mapping_errors_pass_through_unchanged() {- let raw = anyhow::anyhow!("PUT /autoindex-catalog/_mapping failed: 503 unavailable");- let out = format!(- "{:#}",- explain_legacy_catalog_mapping_conflict("autoindex-catalog", raw)+ fn unrelated_mapping_errors_are_not_read_as_a_legacy_conflict() {+ // A 503 must abort the run, so it must not look like a droppable field.+ let raw = "PUT /autoindex-catalog/_mapping failed: 503 unavailable";+ assert_eq!(legacy_text_field_in_conflict(raw), None);+ }++ #[test]+ fn the_warning_names_every_legacy_field_the_scope_field_and_the_reindex() {+ let warning = legacy_catalog_mapping_warning(+ "autoindex-catalog",+ &["prefix".to_string(), "doc_kind".to_string()],+ );+ assert!(+ warning.contains("`prefix`") && warning.contains("`doc_kind`"),+ "must name every tolerated field: {warning}"+ );+ assert!(+ warning.contains("older build")+ && warning.contains("run CONTINUES")+ && warning.contains("_reindex"),+ "must say what happened and how to retire the legacy fields: {warning}");assert!(- !out.contains("older build"),- "must not annotate unrelated errors: {out}"+ warning.contains(crate::catalog::CORPUS_SCOPE_FIELD),+ "must name the field corpus scoping moved to: {warning}");- assert!(out.contains("503 unavailable"));}}@@ -3339,14 +3551,46 @@ fn sweep_excluded_groups(// docs owned by a still-live SIBLING corpus (`current_keys` only guards// the same corpus). The `prefix` keyword field (written by `file_doc`/// `duplicate_file_doc`) makes the scope term-queryable.- es.delete_by_query(- catalog::CATALOG_INDEX,- &json!({"bool": {"filter": [- {"term": {"prefix": prefix}},- {"term": {"path": entry.path}},- ]}}),- )- .with_context(|| format!("sweep catalog entry for newly-excluded {}", entry.path))?;+ //+ // #755: each scoped delete runs TWICE, once per scope field. `prefix`+ // is only a `keyword` on a catalog this build (or #737's) created — on+ // an install upgraded from rc.15..rc.67 it is dynamically inferred+ // `text`, where a `term` does not match the raw scope value and the+ // sweep silently no-ops. `catalog::CORPUS_SCOPE_FIELD` carries the same+ // value on a field no older release ever wrote, so it is `keyword`+ // everywhere; `prefix` stays for documents written by rc.68..this+ // release, which do not carry the new field. Two conjunctive deletes+ // rather than one `should` disjunction: each is a query shape the+ // 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.+ 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+ )+ })?;+ }// #693: also purge the file's `file-alias:` duplicate catalog docs// (`catalog::duplicate_file_doc`). Each carries the DUPLICATE's own// `path`, so the `path` term above misses them, leaving an excluded@@ -3356,14 +3600,22 @@ fn sweep_excluded_groups(// (`UnsupportedInventoryDelta::between`: the `current_keys` guard), so a// `file_key` term cannot strand a still-live byte-identical duplicate in// the same corpus; the `prefix` filter (#737) guards the cross-corpus axis.- es.delete_by_query(- catalog::CATALOG_INDEX,- &json!({"bool": {"filter": [- {"term": {"prefix": prefix}},- {"term": {"file_key": entry.file_key}},- ]}}),- )- .with_context(|| format!("sweep catalog aliases for newly-excluded {}", entry.path))?;+ // #755: both scope fields, for the reason given on the delete above.+ 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+ )+ })?;+ }// #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// pre-#737 binary has no `prefix` value and would survive the sweep on@@ -3810,7 +4062,8 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.clone();pin_pending_embedding_identity(&es, &mut journal, &pending)?;pr.phase("replay", 0, 0);- let mut backend = sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20);+ let mut backend =+ sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20, &pr);sync_executor::replay_pending_operations(&state_dir, &mut journal, &mut backend)?;// Through the progress surface, never a bare `eprintln!`: stderr// belongs to that surface, so `--progress none` stays silent and@@ -4025,7 +4278,8 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {&pr,plan,)?;- let mut backend = sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20);+ let mut backend =+ sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20, &pr);sync_executor::replay_pending_operations(&state_dir, &mut journal, &mut backend)?;let summary = finish_generated_run(&es, &mut journal, &cfg)?;let code = generated_exit_code(&summary);@@ -4703,7 +4957,8 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {&pr,plan,)?;- let mut backend = sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20);+ let mut backend =+ sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20, &pr);sync_executor::replay_pending_operations(&state_dir, &mut journal, &mut backend)?;let summary = finish_generated_run(&es, &mut journal, &cfg)?;let code = generated_exit_code(&summary);@@ -4760,6 +5015,26 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {}}),).context("upgrade autoindex catalog mapping")?;+ // #755: `prefix` is deliberately absent from the additive upgrade above for+ // exactly the `started` reason — rc.15..rc.67 inferred it as TEXT from the+ // run document, so declaring it `keyword` here would 400 and abort this+ // path too. `catalog::CORPUS_SCOPE_FIELD` is the way out: no release ever+ // wrote it, so it is always installable, and it gives this path the same+ // exact corpus scope the generated path gets. Separate from the PUT above+ // so a pre-existing conflict in one of those fields cannot take it down.+ //+ // Through `install_catalog_mapping`, so this path is fail-soft on exactly+ // the same terms as the generated one: if something outside autoindex has+ // written `corpus_scope` into the shared catalog as text — which is how the+ // #755 repro creates its legacy state in the first place — the run states+ // what it lost and continues, rather than reproducing the abort this change+ // exists to remove.+ install_catalog_mapping(+ &es,+ &json!({"properties": {catalog::CORPUS_SCOPE_FIELD: {"type": "keyword"}}}),+ &pr,+ )+ .context("install autoindex catalog corpus-scope mapping")?;// A replacement transaction starts before the effective new plan is// persisted and before live visibility changes. If the process dies at// any later boundary, journal replay removes the older file_done and@@ -7942,6 +8217,62 @@ mod generation_contract_identity_tests {assert_ne!(index_changed.1, expected.1);}+ /// #755 — `index_identity` is a FROZEN ON-DISK CONTRACT, not a free-running+ /// digest. Every committed generation writes it into its journal execution+ /// record, and the next run requires equality in two places: the+ /// incremental-reconcile no-change arm ("autoindex execution configuration+ /// changed since the committed generation; rebuild with a new --state-dir+ /// and a new --prefix") and `provision_generation` ("desired generation+ /// index identity disagrees with its frozen mappings"). So adding a+ /// property to `catalog::catalog_mapping()` — which is hashed into that+ /// identity — does not plan a fresh generation: it aborts the next run of+ /// every state dir an older binary committed, permanently on the no-change+ /// arm, because that arm writes no new generation to heal with. That is the+ /// same abort-on-upgrade class #755 exists to remove, which is why+ /// `catalog::CORPUS_SCOPE_FIELD` is installed additively in+ /// `ensure_generation_mappings` (outside the hash) instead of declared in+ /// the mapping.+ ///+ /// Both halves are pinned, so updating the fixture to match a changed+ /// mapping still fails: the serialized mapping against the copy captured+ /// from the shipped tree, and the digests against literals measured by+ /// compiling v1.0.0-rc.71 itself.+ #[test]+ fn catalog_mapping_is_the_frozen_on_disk_contract() {+ assert_eq!(+ serde_json::to_string(&catalog::catalog_mapping()).unwrap(),+ frozen_contract::CATALOG_MAPPING_JSON,+ "the catalog mapping is hashed into every committed generation's \+ `index_identity`; changing it aborts the next run of every existing \+ state dir. Install new catalog fields additively in \+ `ensure_generation_mappings` instead"+ );++ let single = Plan {+ datasets: vec![dataset("a", "ax-a", "json")],+ ..Plan::default()+ };+ let (schema_identity, index_identity) = generation_contract_identities(&single).unwrap();+ assert_eq!(+ index_identity, "2efb962fc36e015915c287ce8bb90e55",+ "measured on v1.0.0-rc.71: this exact digest is in the field, frozen \+ in committed journals"+ );+ assert_eq!(schema_identity, "fa78053f17039af9bbe0238a415f2268");+ assert_eq!(index_identity, frozen_contract::index_identity(&single));++ // Not only the one-dataset shape: the shipped-side mirror has to agree+ // for any plan, since a real journal's plan is whatever was scanned.+ let many = Plan {+ datasets: vec![dataset("b", "ax-b", "csv"), dataset("a", "ax-a", "json")],+ ..Plan::default()+ };+ assert_eq!(+ generation_contract_identities(&many).unwrap().1,+ frozen_contract::index_identity(&many)+ );+ }+/// ONBOARDING-401-REPRO.md §3: a *successful* run signed off by printing/// `next:` commands that carried no credential, so against an auth-enabled/// server (the default) every one of them answered 401 — including thediff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rsindex d8938b90c..f7f9bc0c4 100644--- a/engine/crates/xerj-autoindex/src/sync_executor.rs+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs@@ -212,15 +212,26 @@ pub struct EsSyncBackend<'a> {es: &'a crate::esclient::Es,state_dir: &'a Path,bulk_bytes: usize,+ /// #755: the run's progress surface, so a legacy-catalog mapping warning+ /// reaches the operator through the surface that owns stderr (#241) rather+ /// than a bare `eprintln!` that `--progress none` cannot silence and+ /// `--progress json` cannot parse.+ pr: &'a crate::progress::Progress,}#[cfg_attr(not(test), allow(dead_code))]impl<'a> EsSyncBackend<'a> {- pub fn new(es: &'a crate::esclient::Es, state_dir: &'a Path, bulk_bytes: usize) -> Self {+ pub fn new(+ es: &'a crate::esclient::Es,+ state_dir: &'a Path,+ bulk_bytes: usize,+ pr: &'a crate::progress::Progress,+ ) -> Self {Self {es,state_dir,bulk_bytes: bulk_bytes.max(64 * 1024),+ pr,}}@@ -535,7 +546,7 @@ impl SyncOperationBackend for EsSyncBackend<'_> {execution.index_identity == index_identity,"desired generation index identity disagrees with its frozen mappings");- crate::ensure_generation_mappings(self.es, &desired.plan)+ crate::ensure_generation_mappings(self.es, &desired.plan, self.pr)}fn apply(@@ -2565,7 +2576,11 @@ mod tests {let es = crate::esclient::Es::new("http://127.0.0.1:1", None).unwrap();let state = tempfile::tempdir().unwrap();- let _backend = EsSyncBackend::new(&es, state.path(), 1);+ let (pr, _sink) = crate::progress::Progress::capture(+ crate::progress::Surface::Silent,+ std::time::Duration::from_secs(3600),+ );+ let _backend = EsSyncBackend::new(&es, state.path(), 1, &pr);}#[test]