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
autoindex: stemming analyzer by default for profiler-marked semantic prose (#1059)
xerj-org348990473c21
diff --git a/docs/ZERO_TOKEN_DIRECTION.md b/docs/ZERO_TOKEN_DIRECTION.mdindex c77309ff6..567603d2a 100644--- a/docs/ZERO_TOKEN_DIRECTION.md+++ b/docs/ZERO_TOKEN_DIRECTION.md@@ -280,7 +280,11 @@ The descriptions below are the defects as found and measured.is accepted. At the time, this is why stemming could not be turned on. Fixedby PR [#991](https://github.com/xerj-org/xerj/pull/991): the declareddefault analyzer is honoured at flush, at segment query and at merge, and- stemming can be turned on.+ stemming can be turned on. As of #1059 `xerj autoindex` turns it on by+ default: every dataset index it CREATES for profiler-marked semantic prose+ (the measured `word_ratio`/`mean_tokens` election) declares the built-in+ Snowball `stemmer` analyzer as `analysis.analyzer.default`; indexes created+ by earlier builds are untouched.- **Neural ingest leaves the machine idle**([#938](https://github.com/xerj-org/xerj/issues/938)). One `_bulk` stream into a`semantic_text` field runs at 6.1 documents per second on ~1,470-characterdiff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rsindex ac39a6f18..d0e30594a 100644--- a/engine/crates/xerj-autoindex/src/catalog.rs+++ b/engine/crates/xerj-autoindex/src/catalog.rs@@ -165,6 +165,7 @@ pub fn catalog_mapping() -> Value {pub const GOTCHAS: &[&str] = &["hybrid search: use {\"query\":{\"hybrid\":{\"queries\":[…]}}} ONLY — retriever.rrf is a silent stub and rank.rrf is ignored on this engine",+ "indexes CREATED by this build stem English text fields (Snowball, via a declared `analysis.analyzer.default`) whenever the profiler marked the dataset's prose semantic — plurals and inflections match (`databases` ↔ `database`) on `text`/`semantic_text` fields of THOSE indexes; keyword fields are never stemmed, and indexes an older build created keep the unstemmed `standard` analyzer (analysis settings are fixed at index creation — reindex into a fresh index to change them)","semantic_text fields are embedded server-side: the DEFAULT is the built-in LEXICAL feature-hash embedder (384-dim hybrid lexical+vector, NOT neural) — start the server with `--embed-mode neural` (built-in Candle BERT), `--embed-mode proxy`, or an ONNX-enabled build with `--embed-mode onnx-experimental --onnx-model … --onnx-tokenizer …` for neural semantics; ONNX runs only when this map shows a semantic_field, and its first real inference is confirmed by the server activation log","semantic queries ignore _source filtering and return the ~8KB *_vector field in _source — strip client-side","exact filters use TOP-LEVEL keyword fields (term on .keyword subfields returns 0 hits on this engine)",@@ -833,6 +834,7 @@ mod sample_query_tests {specs,time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,}diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rsindex 8852e9bc5..c7d9f838e 100644--- a/engine/crates/xerj-autoindex/src/esclient.rs+++ b/engine/crates/xerj-autoindex/src/esclient.rs@@ -1995,6 +1995,43 @@ mod tests {stream.write_all(body).unwrap();}+ /// #1059: the wire body of a dataset-index CREATE carries the stemming+ /// analyzer declaration next to the single-WAL-shard setting — the two+ /// create-only settings compose under one `settings` object, and the+ /// analyzer is not dropped or mangled on the way out. Observed on the+ /// socket, not on the builder, so the transport layer cannot lose it.+ #[test]+ fn ensure_index_puts_the_declared_analyzer_beside_the_wal_shard_setting() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ let server = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let request = read_request(&mut stream);+ let text = String::from_utf8_lossy(&request);+ assert!(text.starts_with("PUT /ax-prose HTTP/1.1"), "{text}");+ let body = text.split("\r\n\r\n").nth(1).unwrap_or_default();+ let sent: serde_json::Value = serde_json::from_str(body.trim()).unwrap();+ assert_eq!(+ sent.pointer("/settings/analysis/analyzer/default/type"),+ Some(&serde_json::json!("stemmer")),+ "{sent}"+ );+ assert_eq!(+ sent.pointer("/settings/index/xerj_ingest_shards"),+ Some(&serde_json::json!(1)),+ "the WAL-shard setting must land beside the analyzer, not replace it: {sent}"+ );+ respond_json(&mut stream, br#"{"acknowledged":true}"#);+ });+ let es = Es::new(&format!("http://{address}"), None).unwrap();+ let body = serde_json::json!({+ "mappings": {"properties": {"body": {"type": "semantic_text"}}},+ "settings": {"analysis": {"analyzer": {"default": {"type": "stemmer"}}}}+ });+ es.ensure_index("ax-prose", &body).unwrap();+ server.join().unwrap();+ }+/// A deleted index is an answer for the probes that ask whether the server/// still holds what a journal claims it holds — `search` propagating that/// 404 replaces `xerj brain`'s recovery text with a raw HTTP error. Everydiff --git a/engine/crates/xerj-autoindex/src/generation_catalog.rs b/engine/crates/xerj-autoindex/src/generation_catalog.rsindex 364e3f822..721c0b24e 100644--- a/engine/crates/xerj-autoindex/src/generation_catalog.rs+++ b/engine/crates/xerj-autoindex/src/generation_catalog.rs@@ -521,6 +521,7 @@ mod tests {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 2,file_count: 1,}diff --git a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rsindex f81920ef7..8a9488836 100644--- a/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs@@ -73,6 +73,7 @@ fn dataset() -> PlanDataset {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 2,file_count: 0,}diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex e24f1ef10..72106f830 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -2932,6 +2932,7 @@ fn sweep_excluded_groups_deletes_only_the_excluded_files_documents() {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});@@ -3015,6 +3016,7 @@ fn sweep_excluded_groups_invalidates_the_excluded_files_edges() {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});@@ -3089,6 +3091,7 @@ fn sweep_excluded_groups_purges_the_excluded_files_alias_catalog_docs() {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});@@ -3163,6 +3166,7 @@ fn sweep_excluded_groups_does_not_delete_a_sibling_corpus_catalog_doc() {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});@@ -3251,6 +3255,7 @@ fn sweep_excluded_groups_scopes_on_the_keyword_corpus_scope_field() {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});@@ -3360,6 +3365,7 @@ fn sweep_excluded_groups_cannot_reach_a_sibling_corpus_on_a_text_mapped_prefix()specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});@@ -3850,6 +3856,7 @@ fn sweep_excluded_groups_deletes_a_legacy_main_doc_by_id() {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});@@ -3916,6 +3923,7 @@ fn sweep_excluded_groups_deletes_a_legacy_alias_doc_by_id() {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});@@ -3988,6 +3996,7 @@ fn sweep_excluded_groups_invalidates_inbound_edges() {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});diff --git a/engine/crates/xerj-autoindex/src/infer/mod.rs b/engine/crates/xerj-autoindex/src/infer/mod.rsindex 2d2f144b9..95c6ab3bf 100644--- a/engine/crates/xerj-autoindex/src/infer/mod.rs+++ b/engine/crates/xerj-autoindex/src/infer/mod.rs@@ -668,6 +668,62 @@ pub fn elect_time_field(specs: &[FieldSpec]) -> Option<String> {.map(|s| s.name.clone())}+/// The analyzer autoindex declares as `settings.analysis.analyzer.default`+/// when a dataset's sample carries profiler-marked semantic prose (#1059).+///+/// `"stemmer"` is the built-in `standard` pipeline (Unicode word split ++/// lowercase) plus the Snowball English stemmer and NOTHING else — see+/// `AnalyzerRegistry::register_defaults` (xerj-fts). It is the minimal delta+/// from today's default: the only change to the term space is that plurals+/// and inflections collapse onto their stems, which is exactly the recall the+/// issue is after. `"english"` was considered and rejected as the default+/// because it additionally drops stop words, which changes every document's+/// BM25 length norm — a scoring change, not just a recall change, and one+/// that would have to be re-measured against the same BEIR arms before it+/// could be honest.+pub const STEMMING_TEXT_ANALYZER: &str = "stemmer";++/// Does this dataset's index get the stemming analyzer at create time?+///+/// `Some(STEMMING_TEXT_ANALYZER)` when at least one field the profiler typed+/// as text (`text` or `semantic_text`) is marked semantic by the SAME+/// measured predicate that gates the embedding election —+/// [`FieldAcc::looks_natural_language`]: `word_ratio >= 0.55 &&+/// mean_tokens >= 3.0`. That predicate is what separates prose from+/// identifiers (measured: `word_ratio` 0.00 for `trace_id`/`user_id`/+/// numerics, 0.78–1.00 for prose, log messages and source code — see the+/// `word_tokens` field's doc comment), so a dataset of identifiers or enums+/// keeps the unstemmed `standard` analyzer and its exact term space.+///+/// The unit of the declaration is the INDEX, not the field: the honoured+/// surface (#937, fixed by #991) is a declared DEFAULT analyzer, which the+/// engine applies to every `Text` field at flush, segment query and merge+/// (keyword fields keep the whole-value `keyword` analyzer regardless), so a+/// dataset with any semantic prose gets stemming on all of its text fields —+/// including non-elected ones like `defs`. That is deliberate: stemming an+/// identifier token is a no-op or a consistent fold on both sides of the+/// match, and the alternative (a per-field `analyzer` in the mapping) is the+/// accepted-and-ignored surface the #937 audit named as still open.+///+/// This does NOT consult `no_semantic`: stemming is a LEXICAL-arm property+/// (BM25 recall on plurals), and a `--no-semantic` run is precisely the run+/// whose retrieval is all lexical.+pub fn elected_default_analyzer(+ specs: &[FieldSpec],+ fields: &HashMap<String, FieldAcc>,+) -> Option<&'static str> {+ specs+ .iter()+ .any(|s| {+ matches!(s.es_type.as_str(), "text" | "semantic_text")+ && fields+ .get(&s.name)+ .map(|a| a.looks_natural_language())+ .unwrap_or(false)+ })+ .then_some(STEMMING_TEXT_ANALYZER)+}+#[cfg(test)]mod tests {use super::*;@@ -873,4 +929,87 @@ mod tests {let specs = infer_fields(&fields, 30, true);assert_eq!(specs[0].semantic, None, "neither side holds 90% of 30");}++ /// #1059: a dataset whose text field the profiler marks semantic+ /// (`looks_natural_language` — the same measured predicate that gates the+ /// embedding election) elects the stemming analyzer; a dataset of+ /// identifiers, enums and numerics does not, keeping `standard`'s exact+ /// term space.+ #[test]+ fn a_semantic_prose_dataset_elects_the_stemming_analyzer_and_an_id_dataset_does_not() {+ let prose = "The connection pool retries every failed handshake with backoff. \+ Each worker owns one socket and never shares it across threads.";+ let mut prose_acc = FieldAcc::default();+ for _ in 0..20 {+ prose_acc.add(&Value::String(format!("{prose} {prose}")));+ }+ assert!(prose_acc.looks_natural_language());++ // Identifier/enum/numeric shapes: word_ratio ~0 — the measured+ // `trace_id` case the `word_tokens` doc comment records.+ let mut id_acc = FieldAcc::default();+ for i in 0..20 {+ id_acc.add(&Value::String(format!(+ "741e7b6b-dbd2-4a7f-93a9-4ba50fb561{i:02}"+ )));+ id_acc.add(&Value::Number(i.into()));+ }+ assert!(!id_acc.looks_natural_language());++ let mut fields = HashMap::new();+ fields.insert("body".to_string(), prose_acc);+ fields.insert("trace_id".to_string(), id_acc.clone());+ let specs = infer_fields(&fields, 40, false);+ assert_eq!(+ elected_default_analyzer(&specs, &fields),+ Some("stemmer"),+ "{specs:#?}"+ );++ // The id-only dataset elects nothing.+ let mut id_fields = HashMap::new();+ id_fields.insert("trace_id".to_string(), id_acc);+ let id_specs = infer_fields(&id_fields, 20, true);+ assert_eq!(elected_default_analyzer(&id_specs, &id_fields), None);+ }++ /// #1059: a prose field that the profiler marks semantic but that the+ /// election left LEXICAL (here: `--no-semantic` elects no+ /// `semantic_text`) still elects the stemming analyzer — stemming is a+ /// lexical-arm property and does not ride the embedding election.+ #[test]+ fn a_no_semantic_run_still_elects_the_stemming_analyzer_for_prose() {+ let prose = "The connection pool retries every failed handshake with backoff. \+ Each worker owns one socket and never shares it across threads.";+ let mut acc = FieldAcc::default();+ for _ in 0..20 {+ acc.add(&Value::String(format!("{prose} {prose}")));+ }+ let mut fields = HashMap::new();+ fields.insert("body".to_string(), acc);+ let specs = infer_fields(&fields, 40, true);+ assert_eq!(specs[0].es_type, "text", "no_semantic keeps it lexical");+ assert_eq!(elected_default_analyzer(&specs, &fields), Some("stemmer"));+ }++ /// #1059: prose sampled on a field the profiler types KEYWORD does not+ /// elect the analyzer through that field — the declaration targets text+ /// fields, and a keyword field's whole-value term space must not be part+ /// of the decision. (A dataset whose ONLY natural language rides keyword+ /// fields keeps `standard`.)+ #[test]+ fn prose_on_a_keyword_typed_field_does_not_elect_the_stemming_analyzer() {+ let mut acc = FieldAcc::default();+ for _ in 0..20 {+ acc.add(&Value::String(+ "the connection pool retries the failed handshake".into(),+ ));+ }+ assert!(acc.looks_natural_language());+ let mut fields = HashMap::new();+ fields.insert("status".to_string(), acc);+ let specs = infer_fields(&fields, 20, true);+ assert_eq!(specs[0].es_type, "keyword", "{specs:#?}");+ assert_eq!(elected_default_analyzer(&specs, &fields), None);+ }}diff --git a/engine/crates/xerj-autoindex/src/init.rs b/engine/crates/xerj-autoindex/src/init.rsindex 0f152443d..a501f4449 100644--- a/engine/crates/xerj-autoindex/src/init.rs+++ b/engine/crates/xerj-autoindex/src/init.rs@@ -331,6 +331,14 @@ mod tests {#[test]fn second_run_is_idempotent() {+ // The pair must see ONE `HOME`: `run_init_in` reads it through+ // `dirs_home()` to decide whether the Claude skill is in scope, and+ // the auth-note `Sandbox` tests below swap `HOME` under the same+ // `ENV_LOCK`. Without the lock, a sandboxed test landing between the+ // two runs makes the first see no `~/.claude` (skill out of scope)+ // and the second see one (skill "wrote") — a scheduling-dependent+ // failure, not an idempotency failure.+ let _env = ENV_LOCK.lock().unwrap_or_else(|poison| poison.into_inner());let d = tmp();run_init_in(d.path(), "http://x:1", false).unwrap();let first = fs::read_to_string(d.path().join("AGENTS.md")).unwrap();diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex de5ff3e25..d8450b43c 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -311,8 +311,7 @@ fn install_dataset_mappings() -> Result<Vec<MappingRefusal>> {let mut refused = Vec::new();for dataset in &plan.datasets {- let mut create_body = build_mapping(&dataset.specs);- create_body["mappings"]["properties"]["ax_paths"] = json!({"type": "keyword"});+ let create_body = dataset_create_body(dataset);let update_body = json!({"properties": create_body["mappings"]["properties"].clone()});@@ -335,6 +334,46 @@ fn install_dataset_mappings(Ok(refused)}+/// The index-create body for one dataset: the frozen mapping+/// ([`build_mapping`]) plus, when the profiler marked the dataset's prose+/// semantic, the #1059 stemming analyzer declaration.+///+/// The analyzer goes into `settings.analysis.analyzer.default` — the surface+/// #937 (fixed by #991) made real: a declared default analyzer is honoured at+/// flush, at segment query and at merge, and the memtable has always resolved+/// it, so a whole index analyses one way for its whole life. A per-field+/// `analyzer` in the mapping is NOT used: that is the accepted-and-ignored+/// surface the #937 audit left open (`docs/ZERO_TOKEN_DIRECTION.md`).+///+/// Two properties this placement is load-bearing for:+///+/// - **The frozen identities.** `build_mapping`'s value is hashed into every+/// committed generation's `index_identity` (`generation_contract_identities`),+/// so the analyzer must NOT be declared inside it — here, in the create+/// body only, the digests are byte-identical to an older build's for the+/// same specs and no existing state dir aborts on upgrade. The transport+/// layer then adds `settings.index.xerj_ingest_shards` beside it+/// (`with_single_wal_shard`), the established precedent for a create-only+/// setting that lives outside the frozen contract.+/// - **New indexes only.** Analysis settings are immutable server-side after+/// creation (a settings PUT naming `analysis` is refused), and+/// [`Es::ensure_index`] tolerates `resource_already_exists` without+/// re-sending the body — so an index an earlier run or an older build+/// created is untouched, keeping its `standard` term space and its+/// postings, and only an index THIS run creates gets the stemmer. The+/// marker therefore rides the plan frozen in the journal: a pending+/// generation replayed after a restart still declares the analyzer.+fn dataset_create_body(dataset: &PlanDataset) -> Value {+ let mut create_body = build_mapping(&dataset.specs);+ create_body["mappings"]["properties"]["ax_paths"] = json!({"type": "keyword"});+ if let Some(analyzer) = &dataset.text_analyzer {+ create_body["settings"] = json!({"analysis": {"analyzer": {+ "default": {"type": analyzer}+ }}});+ }+ create_body+}+fn ensure_generation_catalog_mapping(es: &Es, pr: &Progress) -> Result<()> {let mut catalog_create_body = catalog::catalog_mapping();catalog_create_body["mappings"]["properties"]["duplicate_of"] = json!({"type": "keyword"});@@ -2972,6 +3011,10 @@ fn build_phase_a(.iter().find(|s| s.es_type == "semantic_text").map(|s| s.name.clone());+ // #1059: the dataset's text-analyzer election, from the same sampled+ // accumulators that elected the semantic body above. Deterministic in+ // the sample, so the same bytes elect the same analyzer on every run.+ let text_analyzer = infer::elected_default_analyzer(&specs, &c.fields).map(str::to_string);datasets.push(PlanDataset {slug: c.slug.clone(),index: format!("{}-{}", cfg.prefix, c.slug),@@ -2984,6 +3027,7 @@ fn build_phase_a(specs,time_field,semantic_field,+ text_analyzer,sampled_records: c.records,file_count: c.members.len(),});@@ -6249,8 +6293,12 @@ fn run_index_report_inner(// stays fatal, exactly as before.let mut refused: Vec<MappingRefusal> = Vec::new();for d in &plan.datasets {+ // The same create body the generated route installs+ // (`dataset_create_body`): frozen mapping, `ax_paths`, and — when the+ // profiler marked this dataset's prose semantic — the #1059 stemming+ // analyzer declaration in `settings.analysis.analyzer.default`.let installed = es- .ensure_index(&d.index, &build_mapping(&d.specs))+ .ensure_index(&d.index, &dataset_create_body(d)).with_context(|| format!("create index {}", d.index)).and_then(|()| {es.update_mapping(@@ -9728,6 +9776,7 @@ mod generation_contract_identity_tests {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 0,file_count: 0,}@@ -9813,6 +9862,27 @@ mod generation_contract_identity_tests {);}+ /// #1059: the stemming-analyzer election rides the plan but NOT the frozen+ /// identities. If this ever breaks — the analyzer declared inside+ /// `build_mapping`, or a serialized spec field carrying it — the next run+ /// of every existing state dir aborts on the no-change arm with "autoindex+ /// execution configuration changed since the committed generation", which+ /// is exactly the upgrade-abort class the frozen-contract work removed.+ #[test]+ fn electing_the_stemming_analyzer_does_not_move_the_frozen_identities() {+ let mut plan = Plan {+ datasets: vec![dataset("a", "ax-a", "json")],+ ..Plan::default()+ };+ let before = generation_contract_identities(&plan).unwrap();+ plan.datasets[0].text_analyzer = Some(infer::STEMMING_TEXT_ANALYZER.to_string());+ let after = generation_contract_identities(&plan).unwrap();+ assert_eq!(+ before, after,+ "the analyzer declaration must stay outside the hashed contract"+ );+ }+/// 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 the@@ -9915,6 +9985,119 @@ mod generation_contract_identity_tests {}}+/// #1059 — the stemming-analyzer declaration on the dataset index-create+/// body: what it carries, what it must never touch, and what an index that+/// already exists does with it (nothing).+#[cfg(test)]+mod stem_default_tests {+ use super::*;+ use crate::infer::FieldSpec;+ use serde_json::json;++ fn dataset(slug: &str, text_analyzer: Option<&str>) -> PlanDataset {+ let spec = FieldSpec {+ name: "body".into(),+ es_type: "semantic_text".into(),+ date_enc: None,+ semantic: None,+ cardinality_est: 0,+ cardinality_overflow: false,+ null_ratio: 0.0,+ avg_len: 240.0,+ coverage: 1.0,+ examples: vec![],+ notes: vec![],+ date_min: None,+ date_max: None,+ date_evidence: vec![],+ };+ PlanDataset {+ slug: slug.into(),+ index: format!("ax-{slug}"),+ family: "text".into(),+ group: None,+ specs: vec![spec],+ time_field: None,+ semantic_field: Some("body".into()),+ text_analyzer: text_analyzer.map(str::to_string),+ sampled_records: 1,+ file_count: 1,+ }+ }++ /// A dataset the profiler marked semantic declares the stemming analyzer+ /// as `settings.analysis.analyzer.default` on the CREATE body — the+ /// surface #937/#991 made honoured at flush, segment query and merge —+ /// while the mapping itself is byte-identical to a dataset that declares+ /// nothing (the mapping is the frozen on-disk contract; the analyzer must+ /// stay outside it).+ #[test]+ fn a_semantic_dataset_declares_the_stemming_analyzer_on_the_create_body() {+ let body = dataset_create_body(&dataset("prose", Some(infer::STEMMING_TEXT_ANALYZER)));+ assert_eq!(+ body.pointer("/settings/analysis/analyzer/default/type"),+ Some(&json!("stemmer")),+ "{body}"+ );+ // The mapping side is untouched: same properties as an undeclaring+ // dataset, no per-field `analyzer` keys (the accepted-and-ignored+ // surface), and `ax_paths` still present.+ let undeclaring = dataset_create_body(&dataset("prose", None));+ assert_eq!(+ body["mappings"], undeclaring["mappings"],+ "the analyzer declaration must not touch the mapping"+ );+ assert_eq!(+ body.pointer("/mappings/properties/body"),+ Some(&json!({"type": "semantic_text"}))+ );+ assert_eq!(+ body.pointer("/mappings/properties/ax_paths"),+ Some(&json!({"type": "keyword"}))+ );+ assert!(body.pointer("/mappings/properties/body/analyzer").is_none());+ }++ /// A dataset with no profiler-marked prose sends NO settings at all — the+ /// create body is exactly the frozen mapping plus `ax_paths`, so the+ /// server keeps `standard`'s exact term space for identifier/enum data.+ #[test]+ fn a_non_semantic_dataset_sends_no_analyzer_settings() {+ let body = dataset_create_body(&dataset("events", None));+ assert!(body.get("settings").is_none(), "{body}");+ assert_eq!(+ body.pointer("/mappings/properties/ax_paths"),+ Some(&json!({"type": "keyword"}))+ );+ }++ /// The declaration survives the journal round-trip, because a pending+ /// generation replayed after a restart provisions its indexes from the+ /// DESERIALIZED plan: an analyzer marker lost to serialization would+ /// create that index unstemmed.+ #[test]+ fn the_analyzer_election_survives_the_journal_round_trip() {+ let plan = Plan {+ datasets: vec![dataset("prose", Some(infer::STEMMING_TEXT_ANALYZER))],+ ..Plan::default()+ };+ let round: Plan = serde_json::from_value(serde_json::to_value(&plan).unwrap()).unwrap();+ assert_eq!(+ round.datasets[0].text_analyzer.as_deref(),+ Some(infer::STEMMING_TEXT_ANALYZER)+ );+ // A plan frozen by an older build deserializes with no election —+ // the honest value for an index that already exists unstemmed.+ let legacy = serde_json::json!({+ "slug": "events", "index": "ax-events", "family": "json",+ "specs": [], "sampled_records": 0, "file_count": 0+ });+ let legacy: PlanDataset = serde_json::from_value(legacy).unwrap();+ assert_eq!(legacy.text_analyzer, None);+ assert!(dataset_create_body(&legacy).get("settings").is_none());+ }+}+#[cfg(test)]mod code_coverage_tests {use super::*;diff --git a/engine/crates/xerj-autoindex/src/reconcile_plan.rs b/engine/crates/xerj-autoindex/src/reconcile_plan.rsindex 752a7b1c0..df121499c 100644--- a/engine/crates/xerj-autoindex/src/reconcile_plan.rs+++ b/engine/crates/xerj-autoindex/src/reconcile_plan.rs@@ -683,6 +683,7 @@ mod tests {specs,time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,}diff --git a/engine/crates/xerj-autoindex/src/refused_dataset_tests.rs b/engine/crates/xerj-autoindex/src/refused_dataset_tests.rsindex 3721ac911..cb60b1f9c 100644--- a/engine/crates/xerj-autoindex/src/refused_dataset_tests.rs+++ b/engine/crates/xerj-autoindex/src/refused_dataset_tests.rs@@ -19,6 +19,7 @@ fn dataset(slug: &str) -> PlanDataset {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 0,}diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex d6579fb1b..8735268a4 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -44,6 +44,28 @@ pub struct PlanDataset {pub time_field: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub semantic_field: Option<String>,+ /// The analyzer this dataset's index declares at CREATE time for its text+ /// fields (#1059): `Some("stemmer")` when the profiler marked at least one+ /// of the dataset's text fields as natural-language prose, else `None`.+ ///+ /// It rides the PLAN and not [`crate::infer::FieldSpec`] on purpose: the+ /// specs are hashed into every committed generation's `schema_identity`+ /// (`generation_contract_identities` serializes `dataset.specs` verbatim),+ /// so a new serialized spec field would move that digest for every+ /// prose-carrying dataset and abort the next run of every existing state+ /// dir on the incremental no-change arm — the exact upgrade-abort class+ /// the frozen-contract work removed. This struct is serialized into the+ /// journal but the identity digests read it through named keys only, so a+ /// new field here is invisible to them.+ ///+ /// `#[serde(default)]` so a plan frozen by an older build deserializes+ /// with `None` — which is also the honest value: an index that an older+ /// build created was written with the `standard` analyzer, and the+ /// analysis settings of an existing index are immutable server-side, so+ /// the declaration only ever lands on an index THIS build creates+ /// (`install_dataset_mappings`).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub text_analyzer: Option<String>,pub sampled_records: u64,pub file_count: usize,}@@ -1581,6 +1603,7 @@ mod sync_journal_tests {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 0,});@@ -1600,6 +1623,7 @@ mod sync_journal_tests {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,});diff --git a/engine/crates/xerj-autoindex/src/sync.rs b/engine/crates/xerj-autoindex/src/sync.rsindex a24ff646c..97214371f 100644--- a/engine/crates/xerj-autoindex/src/sync.rs+++ b/engine/crates/xerj-autoindex/src/sync.rs@@ -1827,6 +1827,7 @@ mod tests {specs: Vec::new(),time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 0,file_count: 0,});diff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rsindex b34cb0afb..6d9f97da5 100644--- a/engine/crates/xerj-autoindex/src/sync_executor.rs+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs@@ -2697,6 +2697,7 @@ mod tests {specs: vec![],time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: 1,}],@@ -2750,6 +2751,7 @@ mod tests {specs: vec![],time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 1,file_count: files.len(),}],@@ -3098,6 +3100,7 @@ mod tests {specs: vec![],time_field: None,semantic_field: None,+ text_analyzer: None,sampled_records: 2,file_count: 1,};