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(api): apply template semantic_text and default_pipeline on index create (#2283)
xerj-org6d897e713c13
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9b5978cb2..760fd7d2a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- A matching index template's `semantic_text` properties and+ `index.default_pipeline` are applied when an index is created, including+ the body `xerj autoindex` sends and the first bulk or single-document+ write that auto-creates the index. The template already matched (a+ `keyword` field from it was mapped), but `semantic_text` was stored as+ `object` and the default pipeline was dropped, so the pipeline never ran+ ([#2281](https://github.com/xerj-org/xerj/issues/2281)).+- `POST /{index}/_count` honours `min_score`. The handler rebuilds a `size: 0`search body from the query alone, so the threshold used to be dropped: for`{"query":{"match":…},"min_score":10}` `_search` returned 0 while `_count`diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 917ebe79c..f07cc500e 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -1504,9 +1504,23 @@ pub async fn create_index(return refusal;}+ // A matching index template contributes mappings and settings the request+ // did not set. The request wins on a field or setting it names. Merged+ // before validation and schema build so `semantic_text` is parsed by the+ // same mapper as an explicit mapping, and `index.default_pipeline` is+ // stored where `default_pipeline_for` and `GET /_settings` read it+ // (#2281). A schema-only pass cannot: the stored mapping was the request+ // body, so a template `semantic_text` was rendered back as `object`, and+ // the template's settings were never copied.+ let (mappings_val, merged_settings) = state.engine.merge_index_template(+ &index,+ body.get("mappings").cloned().unwrap_or(Value::Null),+ body.get("settings").cloned().unwrap_or(Value::Null),+ );+ let settings_ref = (!merged_settings.is_null()).then_some(&merged_settings);+// Validate mapping field types before creating — ES returns// mapper_parsing_exception for unsupported types.- let mappings_val = body.get("mappings").cloned().unwrap_or(Value::Null);if let Some(props) = mappings_val.get("properties").and_then(Value::as_object) {if let Some(refusal) = empty_field_name_refusal(props) {return refusal;@@ -1557,8 +1571,7 @@ pub async fn create_index(// @timestamp heuristic. Mirror the field + order into the// `__xy_index_sort_*` internal keys so the search handler's// default-sort hook picks them up.- let explicit_sort_field: Option<String> = body- .get("settings")+ let explicit_sort_field: Option<String> = settings_ref.and_then(|s| {s.pointer("/index/sort/field").or_else(|| s.pointer("/index/sort.field"))@@ -1570,8 +1583,7 @@ pub async fn create_index(Value::Array(mut a) => a.first_mut().and_then(|x| x.as_str().map(String::from)),_ => None,});- let explicit_sort_order: String = body- .get("settings")+ let explicit_sort_order: String = settings_ref.and_then(|s| {s.pointer("/index/sort/order").or_else(|| s.pointer("/index/sort.order"))@@ -1585,14 +1597,17 @@ pub async fn create_index(}).unwrap_or_else(|| "asc".to_string());- // Thread the request's `settings` into the store config at create time- // (custom analysis config, and the per-index `index.xerj_ingest_shards` WAL- // shard override that `xerj autoindex` uses to keep each of its hundreds of- // indices at a single WAL file descriptor). create_index_with_settings- // applies index templates identically to create_index.- let create_settings = body.get("settings").cloned().unwrap_or(Value::Null);+ // Thread the merged `settings` into the store config at create time+ // (custom analysis config, the template's `index.default_pipeline`, and+ // the per-index `index.xerj_ingest_shards` WAL shard override that+ // `xerj autoindex` uses to keep each of its hundreds of indices at a+ // single WAL file descriptor). create_index_with_settings applies index+ // templates to the schema; the mapping blob and display settings below+ // are the merged body, so a template field is not re-derived from the+ // native type.+ let create_settings = merged_settings;let display_settings = create_time_index_settings(- body.get("settings"),+ (!create_settings.is_null()).then_some(&create_settings),&explicit_sort_field,&explicit_sort_order,declared_timestamp_date,diff --git a/engine/crates/xerj-api/tests/index_template_applies_semantic_text.rs b/engine/crates/xerj-api/tests/index_template_applies_semantic_text.rsnew file mode 100644index 000000000..2bba8e219--- /dev/null+++ b/engine/crates/xerj-api/tests/index_template_applies_semantic_text.rs@@ -0,0 +1,425 @@+//! Issue #2281: a composable index template that declares `semantic_text`+//! and `index.default_pipeline` was stored and read back, and a `keyword`+//! field from it landed on a matching index, but the semantic field was+//! mapped as `object` and the default pipeline was not copied onto the+//! index. `xerj autoindex` creates that index with `PUT /{index}` (its own+//! mappings and settings), and the first bulk write can also auto-create+//! it. Both have to come out the way an explicit create that named the+//! field and the pipeline does.+//!+//! Elasticsearch is referenced for wire semantics only. It is AGPL-3.0 /+//! SSPL-1.0 / Elastic-2.0 licensed and no code from it is reproduced here.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++fn app() -> (axum::Router, tempfile::TempDir) {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ (xerj_api::router::build_es_compat_router(state), dir)+}++async fn send(app: &axum::Router, req: Request<Body>) -> (StatusCode, Value) {+ let res = app.clone().oneshot(req).await.expect("response");+ let status = res.status();+ let bytes = axum::body::to_bytes(res.into_body(), 8 * 1024 * 1024)+ .await+ .expect("body");+ let body = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ (status, body)+}++fn put(path: &str, body: Value) -> Request<Body> {+ Request::builder()+ .method("PUT")+ .uri(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request")+}++fn post(path: &str, body: Value) -> Request<Body> {+ Request::builder()+ .method("POST")+ .uri(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request")+}++fn get(path: &str) -> Request<Body> {+ Request::builder()+ .method("GET")+ .uri(path)+ .body(Body::empty())+ .expect("request")+}++fn ndjson(path: &str, body: &str) -> Request<Body> {+ Request::builder()+ .method("POST")+ .uri(path)+ .header("content-type", "application/x-ndjson")+ .body(Body::from(body.to_string()))+ .expect("request")+}++/// The pipeline from the report: copy `impl` onto `diagnostic_semantic`.+/// The ES `copy` processor is stored as `copy_field` and the config keys+/// (`source`, `target`) pass through, which is what that stage reads.+async fn define_copy_pipeline(app: &axum::Router, id: &str) {+ let (status, body) = send(+ app,+ put(+ &format!("/_ingest/pipeline/{id}"),+ json!({+ "processors": [{+ "copy": { "source": "impl", "target": "diagnostic_semantic" }+ }]+ }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+}++/// The template from the report: dotted `index.default_pipeline`, a+/// `semantic_text` field, and a `keyword` marker that already applied.+async fn define_template(app: &axum::Router, name: &str, pattern: &str, pipeline: &str) {+ let (status, body) = send(+ app,+ put(+ &format!("/_index_template/{name}"),+ json!({+ "index_patterns": [pattern],+ "priority": 100,+ "template": {+ "settings": { "index.default_pipeline": pipeline },+ "mappings": {+ "properties": {+ "diagnostic_semantic": { "type": "semantic_text" },+ "diagnostic_template_marker": { "type": "keyword" }+ }+ }+ }+ }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["acknowledged"], true, "{body}");+}++fn field_type<'a>(mapping: &'a Value, index: &str, field: &str) -> Option<&'a str> {+ mapping+ .pointer(&format!("/{index}/mappings/properties/{field}/type"))+ .and_then(Value::as_str)+}++const IMPL_TEXT: &str = "graph edges connect nodes in a network";++async fn assert_template_mapping_and_pipeline(app: &axum::Router, index: &str, pipeline: &str) {+ let (status, mapping) = send(app, get(&format!("/{index}/_mapping"))).await;+ assert_eq!(status, StatusCode::OK, "{mapping}");+ assert_eq!(+ field_type(&mapping, index, "diagnostic_semantic"),+ Some("semantic_text"),+ "{mapping}"+ );+ assert_eq!(+ field_type(&mapping, index, "diagnostic_template_marker"),+ Some("keyword"),+ "{mapping}"+ );++ let (status, settings) = send(app, get(&format!("/{index}/_settings"))).await;+ assert_eq!(status, StatusCode::OK, "{settings}");+ assert_eq!(+ settings+ .pointer(&format!("/{index}/settings/index/default_pipeline"))+ .and_then(Value::as_str),+ Some(pipeline),+ "{settings}"+ );+}++async fn assert_copied_and_searchable(app: &axum::Router, index: &str, id: &str) {+ let (status, doc) = send(app, get(&format!("/{index}/_doc/{id}"))).await;+ assert_eq!(status, StatusCode::OK, "{doc}");+ assert_eq!(doc["_source"]["impl"], IMPL_TEXT, "{doc}");+ assert_eq!(+ doc["_source"]["diagnostic_semantic"], IMPL_TEXT,+ "the default pipeline must copy impl: {doc}"+ );++ let (status, hits) = send(+ app,+ post(+ &format!("/{index}/_search"),+ json!({+ "query": {+ "semantic": {+ "field": "diagnostic_semantic",+ "query": "graph edges"+ }+ }+ }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{hits}");+ let total = hits["hits"]["total"]["value"].as_u64().unwrap_or(0);+ assert!(+ total >= 1,+ "semantic_text must be embedded, not just spelled in the mapping: {hits}"+ );+}++#[tokio::test]+async fn an_empty_create_applies_semantic_text_and_the_default_pipeline() {+ let (app, _dir) = app();+ define_copy_pipeline(&app, "js2281-copy").await;+ define_template(&app, "js2281", "js2281-*", "js2281-copy").await;++ let (status, body) = send(&app, put("/js2281-plain", json!({}))).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_template_mapping_and_pipeline(&app, "js2281-plain", "js2281-copy").await;++ let (status, body) = send(+ &app,+ put(+ "/js2281-plain/_doc/1?refresh=true",+ json!({ "impl": IMPL_TEXT }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::CREATED, "{body}");+ assert_copied_and_searchable(&app, "js2281-plain", "1").await;+}++#[tokio::test]+async fn an_autoindex_create_body_keeps_the_template_field_and_pipeline() {+ let (app, _dir) = app();+ define_copy_pipeline(&app, "js2281-copy").await;+ define_template(&app, "js2281", "js2281-*", "js2281-copy").await;++ // The body `xerj autoindex --code-analyzer code` PUTs: its own text+ // fields, the code analyzer, one WAL shard, and the dotted strict-unknown+ // setting. The template's fields are not in this body.+ let (status, body) = send(+ &app,+ put(+ "/js2281-auto",+ json!({+ "settings": {+ "analysis": { "analyzer": { "default": { "type": "code" } } },+ "index": { "xerj_ingest_shards": 1 },+ "index.query.strict_unknown_fields": true+ },+ "mappings": { "properties": {+ "impl": { "type": "text" },+ "path": { "type": "keyword" },+ "ax_paths": { "type": "keyword" }+ } }+ }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_template_mapping_and_pipeline(&app, "js2281-auto", "js2281-copy").await;++ let (status, mapping) = send(&app, get("/js2281-auto/_mapping")).await;+ assert_eq!(status, StatusCode::OK, "{mapping}");+ assert_eq!(field_type(&mapping, "js2281-auto", "impl"), Some("text"));+ assert_eq!(field_type(&mapping, "js2281-auto", "path"), Some("keyword"));++ let (_, settings) = send(&app, get("/js2281-auto/_settings")).await;+ assert_eq!(+ settings.pointer("/js2281-auto/settings/index/xerj_ingest_shards"),+ Some(&json!("1")),+ "{settings}"+ );++ let (status, search) = send(+ &app,+ post(+ "/js2281-auto/_search",+ json!({ "query": { "term": { "not_a_field": "x" } } }),+ ),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "the dotted strict setting must still be in force: {search}"+ );++ let (status, bulk) = send(+ &app,+ ndjson(+ "/_bulk?refresh=true",+ &format!(+ "{}\n{}\n",+ json!({"index": {"_index": "js2281-auto", "_id": "1"}}),+ json!({"impl": IMPL_TEXT, "path": "src/a.ts"})+ ),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{bulk}");+ assert_eq!(bulk["errors"], false, "{bulk}");+ assert_copied_and_searchable(&app, "js2281-auto", "1").await;+}++#[tokio::test]+async fn the_first_bulk_write_auto_creates_with_the_template() {+ let (app, _dir) = app();+ define_copy_pipeline(&app, "js2281-copy").await;+ define_template(&app, "js2281", "js2281-*", "js2281-copy").await;++ let (status, bulk) = send(+ &app,+ ndjson(+ "/_bulk?refresh=true",+ &format!(+ "{}\n{}\n",+ json!({"index": {"_index": "js2281-bulk", "_id": "1"}}),+ json!({"impl": IMPL_TEXT})+ ),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{bulk}");+ assert_eq!(bulk["errors"], false, "{bulk}");+ assert_template_mapping_and_pipeline(&app, "js2281-bulk", "js2281-copy").await;+ assert_copied_and_searchable(&app, "js2281-bulk", "1").await;+}++#[tokio::test]+async fn the_first_document_write_auto_creates_with_the_template() {+ let (app, _dir) = app();+ define_copy_pipeline(&app, "js2281-copy").await;+ define_template(&app, "js2281", "js2281-*", "js2281-copy").await;++ let (status, body) = send(+ &app,+ put(+ "/js2281-doc/_doc/1?refresh=true",+ json!({ "impl": IMPL_TEXT }),+ ),+ )+ .await;+ assert!(+ status == StatusCode::CREATED || status == StatusCode::OK,+ "{status} {body}"+ );+ assert_template_mapping_and_pipeline(&app, "js2281-doc", "js2281-copy").await;+ assert_copied_and_searchable(&app, "js2281-doc", "1").await;+}++#[tokio::test]+async fn the_request_wins_on_a_field_and_on_the_pipeline_it_names() {+ let (app, _dir) = app();+ define_copy_pipeline(&app, "js2281-copy").await;+ let (status, body) = send(+ &app,+ put(+ "/_ingest/pipeline/js2281-set",+ json!({ "processors": [{ "set": { "field": "env", "value": "prod" } }] }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ define_template(&app, "js2281", "js2281-*", "js2281-copy").await;++ let (status, body) = send(+ &app,+ put(+ "/js2281-override",+ json!({+ "mappings": { "properties": {+ "diagnostic_semantic": { "type": "keyword" }+ } }+ }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let (_, mapping) = send(&app, get("/js2281-override/_mapping")).await;+ assert_eq!(+ field_type(&mapping, "js2281-override", "diagnostic_semantic"),+ Some("keyword"),+ "{mapping}"+ );+ assert_eq!(+ field_type(&mapping, "js2281-override", "diagnostic_template_marker"),+ Some("keyword"),+ "{mapping}"+ );+ let (_, settings) = send(&app, get("/js2281-override/_settings")).await;+ assert_eq!(+ settings.pointer("/js2281-override/settings/index/default_pipeline"),+ Some(&json!("js2281-copy")),+ "{settings}"+ );++ let (status, body) = send(+ &app,+ put(+ "/js2281-pipe",+ json!({ "settings": { "index": { "default_pipeline": "js2281-set" } } }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let (_, settings) = send(&app, get("/js2281-pipe/_settings")).await;+ assert_eq!(+ settings.pointer("/js2281-pipe/settings/index/default_pipeline"),+ Some(&json!("js2281-set")),+ "{settings}"+ );+ let (status, body) = send(+ &app,+ put(+ "/js2281-pipe/_doc/1?refresh=true",+ json!({ "impl": IMPL_TEXT }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::CREATED, "{body}");+ let (_, doc) = send(&app, get("/js2281-pipe/_doc/1")).await;+ assert_eq!(doc["_source"]["env"], "prod", "{doc}");+ assert!(+ doc["_source"].get("diagnostic_semantic").is_none(),+ "the request pipeline replaced the template copy: {doc}"+ );+}++#[tokio::test]+async fn an_index_outside_the_pattern_does_not_inherit_the_template() {+ let (app, _dir) = app();+ define_copy_pipeline(&app, "js2281-copy").await;+ define_template(&app, "js2281", "js2281-*", "js2281-copy").await;++ let (status, body) = send(&app, put("/other-plain", json!({}))).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let (_, mapping) = send(&app, get("/other-plain/_mapping")).await;+ assert!(+ field_type(&mapping, "other-plain", "diagnostic_semantic").is_none(),+ "{mapping}"+ );+ let (_, settings) = send(&app, get("/other-plain/_settings")).await;+ assert!(+ settings+ .pointer("/other-plain/settings/index/default_pipeline")+ .is_none(),+ "{settings}"+ );+}diff --git a/engine/crates/xerj-engine/src/bulk.rs b/engine/crates/xerj-engine/src/bulk.rsindex 6170046fe..e808f8f4c 100644--- a/engine/crates/xerj-engine/src/bulk.rs+++ b/engine/crates/xerj-engine/src/bulk.rs@@ -1375,7 +1375,12 @@ pub async fn process_bulk_with_opts(});mapping_has_semantic_text(&props.unwrap_or(Value::Null))})- .unwrap_or(false);+ .unwrap_or(false)+ // The index does not exist yet. A matching template's+ // `semantic_text` is applied by the auto-create this batch is+ // about to do; classifying from the absent mapping sent the+ // first write down the turbo path, which never embeds (#2281).+ || engine.absent_index_template_has_semantic_text(target);cache.insert(target.to_string(), has);has};diff --git a/engine/crates/xerj-engine/src/cluster_apply.rs b/engine/crates/xerj-engine/src/cluster_apply.rsindex 7c4cffd09..601ba7ffd 100644--- a/engine/crates/xerj-engine/src/cluster_apply.rs+++ b/engine/crates/xerj-engine/src/cluster_apply.rs@@ -125,12 +125,20 @@ impl Engine {if self.get_index(name).is_ok() {return Ok(());}+ // Same template merge as `PUT /{index}` (#2281). Peers apply this+ // spec as given and do not re-read their own templates.+ let (mappings, settings) = self.merge_index_template(name, Value::Null, Value::Null);+ let index_settings = if settings.as_object().is_some_and(|m| !m.is_empty()) {+ settings.clone()+ } else {+ Value::Null+ };let spec = ReplicatedIndexSpec {name: name.to_string(),schema: Schema::empty(),- settings: Value::Null,- mappings: Value::Null,- index_settings: Value::Null,+ settings,+ mappings,+ index_settings,aliases: Value::Null,};match self.replicate_index_create(spec).await {diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex bc7e4be4d..13af60469 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -1438,44 +1438,101 @@ impl Engine {/// The cluster proposer calls this once and replicates the effective/// schema. The applier must not call it again: nodes can have different/// local templates, and a second pass would diverge.+ ///+ /// `semantic_text` stays a text field with an embedding contract. It used+ /// to fall through to `object` here, so a template that matched (its+ /// `keyword` fields appeared) still could not embed (#2281). The raw ES+ /// mapping and settings are merged separately by+ /// [`Engine::merge_index_template`] — this pass only builds the native+ /// schema, and `schema_to_es_properties` cannot spell `semantic_text`.pub(crate) fn apply_index_template(&self, name: &str, schema: Schema) -> Schema {let mut effective_schema = schema;+ let mut new_semantic_targets = Vec::new();if let Some(tmpl) = self.best_matching_template(name) {- if let Some(props) = tmpl.mappings.get("properties") {- if let Some(obj) = props.as_object() {- for (field_name, field_def) in obj {- let es_type = field_def- .get("type")- .and_then(Value::as_str)- .unwrap_or("object");- let native_type = es_type_to_field_type(es_type);- if !effective_schema- .fields- .iter()- .any(|f| &f.name == field_name)- {- let mut fc = xerj_common::types::FieldConfig::new(- field_name.clone(),- native_type,- );- // #790: a template's `date_nanos` keeps nanosecond- // precision; `FieldConfig::new` already made a- // plain `date` millisecond-scaled.- if native_type == xerj_common::types::FieldType::Date- && es_type == "date_nanos"- {- fc.options.date_precision =- Some(xerj_common::types::DatePrecision::Nanos);- }- let _ = effective_schema.add_field(fc);- }+ if let Some(props) = tmpl.mappings.get("properties").and_then(Value::as_object) {+ for (field_name, field_def) in props {+ if effective_schema+ .fields+ .iter()+ .any(|f| &f.name == field_name)+ {+ continue;+ }+ let fc = field_from_template_property(field_name, field_def);+ if let Some(embedding) = fc.embedding.as_ref() {+ new_semantic_targets.push(+ embedding+ .target_field+ .clone()+ .unwrap_or_else(|| format!("{field_name}_vector")),+ );}+ let _ = effective_schema.add_field(fc);}}}+ // Only companions of fields this pass added. A caller that already+ // built the schema (the ES create handler) has its own companions;+ // adding them again would fail the duplicate-name check, and running+ // this for every create would change indexes that have no template.+ for target in new_semantic_targets {+ if effective_schema.fields.iter().any(|f| f.name == target) {+ continue;+ }+ let source = effective_schema.fields.iter().find(|f| {+ f.embedding.as_ref().and_then(|e| e.target_field.as_deref())+ == Some(target.as_str())+ });+ let Some(source) = source else {+ continue;+ };+ let mut companion =+ xerj_common::types::FieldConfig::new(target, xerj_common::types::FieldType::Vector);+ companion.options.dimensions = source.options.dimensions;+ companion.options.similarity = source.options.similarity.clone();+ let _ = effective_schema.add_field(companion);+ }effective_schema}+ /// Merge the highest-priority matching template into a create body.+ ///+ /// Request mappings and settings win where both sides name the same field+ /// or setting. Template values fill the gaps. With no matching template+ /// the inputs are returned unchanged.+ ///+ /// Callers that persist the ES mapping blob and `index_settings` must use+ /// this result. [`Engine::apply_index_template`] only updates the native+ /// schema, which cannot round-trip `semantic_text` or+ /// `index.default_pipeline` (#2281).+ pub fn merge_index_template(+ &self,+ index_name: &str,+ mappings: Value,+ settings: Value,+ ) -> (Value, Value) {+ let Some(tmpl) = self.best_matching_template(index_name) else {+ return (mappings, settings);+ };+ (+ merge_template_mappings(&tmpl.mappings, mappings),+ merge_template_settings(&tmpl.settings, settings),+ )+ }++ /// `true` when `index` does not exist yet and a matching template declares+ /// `semantic_text`. Bulk classifies the embed path before auto-create, so+ /// a template-only field would otherwise take the turbo path and never be+ /// embedded (#2281).+ pub(crate) fn absent_index_template_has_semantic_text(&self, index: &str) -> bool {+ if self.indices.contains_key(index) || self.failed_indices.contains_key(index) {+ return false;+ }+ self.best_matching_template(index)+ .and_then(|t| t.mappings.get("properties").cloned())+ .is_some_and(|props| json_properties_have_semantic_text(&props))+ }+/// Create a new index with explicit settings (e.g. custom analysis configuration).////// The `settings` value is stored alongside the index and used to configure@@ -3563,8 +3620,19 @@ impl Engine {xerj_common::XerjError::index_unavailable(name, f.reason.clone()),));}- // Auto-create with empty schema.- self.create_index(name, Schema::empty())?;+ // Auto-create. A matching template supplies the mapping and settings+ // an explicit `PUT /{index}` would have merged in (#2281). The schema+ // is filled by `apply_index_template` inside `create_index_with_settings`;+ // the raw mapping and the display settings are what `GET /_mapping`+ // and `default_pipeline_for` read, and neither is implied by the schema.+ let (mappings, settings) = self.merge_index_template(name, Value::Null, Value::Null);+ self.create_index_with_settings(name, Schema::empty(), settings.clone())?;+ if mappings.as_object().is_some_and(|m| !m.is_empty()) {+ self.put_index_mapping(name, mappings)?;+ }+ if settings.as_object().is_some_and(|m| !m.is_empty()) {+ self.index_settings.insert(name.to_string(), settings);+ }self.get_index(name)}@@ -4361,14 +4429,22 @@ impl Engine {/// write addressed to an alias does not pick up its backing index's default/// pipeline. That is a known gap, identical on every write path.pub fn default_pipeline_for(&self, index: &str) -> Option<String> {- self.index_settings.get(index).and_then(|v| {- v.get("index")- .and_then(|ix| ix.get("default_pipeline"))- .or_else(|| v.get("index.default_pipeline"))- .or_else(|| v.get("default_pipeline"))- .and_then(Value::as_str)- .map(str::to_string)- })+ if let Some(p) = self+ .index_settings+ .get(index)+ .and_then(|v| pipeline_setting(v.value()))+ {+ return Some(p);+ }+ // A write that auto-creates the index resolves the pipeline before+ // that create (#2281). The template's default applies only then: an+ // index that already exists keeps whatever it was created with, even+ // when this in-memory map was not rehydrated after a restart.+ if self.indices.contains_key(index) || self.failed_indices.contains_key(index) {+ return None;+ }+ self.best_matching_template(index)+ .and_then(|t| pipeline_setting(&t.settings))}/// Compile and register a typed transform pipeline from a JSON config,@@ -5120,11 +5196,236 @@ pub(crate) fn glob_match(pattern: &str, text: &str) -> bool {dp[m][n]}+/// `index.default_pipeline` in any of the three spellings settings arrive in.+fn pipeline_setting(v: &Value) -> Option<String> {+ v.get("index")+ .and_then(|ix| ix.get("default_pipeline"))+ .or_else(|| v.get("index.default_pipeline"))+ .or_else(|| v.get("default_pipeline"))+ .and_then(Value::as_str)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+}++fn value_is_empty_object(v: &Value) -> bool {+ v.is_null() || v.as_object().is_some_and(|m| m.is_empty())+}++/// Template mappings fill fields the request did not declare. A request+/// property replaces the template's property of the same name. Other mapping+/// keys (`dynamic`, `_source`, …) follow the same rule.+fn merge_template_mappings(template: &Value, request: Value) -> Value {+ let Some(template_obj) = template.as_object().filter(|m| !m.is_empty()) else {+ return request;+ };+ let Some(request_obj) = request.as_object().filter(|m| !m.is_empty()) else {+ return template.clone();+ };+ let mut out = template_obj.clone();+ for (key, value) in request_obj {+ if key == "properties" {+ let mut props = out+ .get("properties")+ .and_then(Value::as_object)+ .cloned()+ .unwrap_or_default();+ if let Some(req_props) = value.as_object() {+ for (field, def) in req_props {+ props.insert(field.clone(), def.clone());+ }+ out.insert("properties".to_string(), Value::Object(props));+ } else {+ out.insert(key.clone(), value.clone());+ }+ } else {+ out.insert(key.clone(), value.clone());+ }+ }+ Value::Object(out)+}++/// Deep-merge `over` onto `base`. Objects combine; `over` wins on a leaf.+fn deep_merge_request_wins(base: &Value, over: &Value) -> Value {+ match (base.as_object(), over.as_object()) {+ (Some(base), Some(over)) => {+ let mut out = base.clone();+ for (k, v) in over {+ match out.get(k) {+ Some(existing) if existing.is_object() && v.is_object() => {+ out.insert(k.clone(), deep_merge_request_wins(existing, v));+ }+ _ => {+ out.insert(k.clone(), v.clone());+ }+ }+ }+ Value::Object(out)+ }+ _ => over.clone(),+ }+}++/// Write `pipeline` in both spellings `default_pipeline_for` and+/// `GET /_settings` read. Nested `index.default_pipeline` is what the settings+/// response shows once an `index` object exists; a sibling dotted key is+/// dropped by that response, which is how a template pipeline disappeared+/// beside `xerj autoindex`'s `index.xerj_ingest_shards` (#2281).+fn write_default_pipeline(settings: &mut Value, pipeline: &str) {+ if !settings.is_object() {+ *settings = serde_json::json!({});+ }+ let Some(obj) = settings.as_object_mut() else {+ return;+ };+ obj.insert(+ "index.default_pipeline".to_string(),+ Value::String(pipeline.to_string()),+ );+ let index = obj+ .entry("index".to_string())+ .or_insert_with(|| serde_json::json!({}));+ if let Some(index_obj) = index.as_object_mut() {+ index_obj.insert(+ "default_pipeline".to_string(),+ Value::String(pipeline.to_string()),+ );+ }+}++/// Copy single-segment `index.<key>` entries into the nested `index` object+/// when that object does not already name them. Keys with a further dot+/// (`index.query.strict_unknown_fields`) stay as dotted keys: that is a+/// spelling the reader looks up literally, and folding it would hide it.+fn hoist_single_segment_index_keys(mut settings: Value) -> Value {+ let dotted: Vec<(String, Value)> = {+ let Some(obj) = settings.as_object() else {+ return settings;+ };+ obj.iter()+ .filter_map(|(k, v)| {+ let rest = k.strip_prefix("index.")?;+ if rest.is_empty() || rest.contains('.') {+ return None;+ }+ Some((rest.to_string(), v.clone()))+ })+ .collect()+ };+ if dotted.is_empty() {+ return settings;+ }+ let Some(obj) = settings.as_object_mut() else {+ return settings;+ };+ let index = obj+ .entry("index".to_string())+ .or_insert_with(|| serde_json::json!({}));+ if let Some(index_obj) = index.as_object_mut() {+ for (k, v) in dotted {+ index_obj.entry(k).or_insert(v);+ }+ }+ settings+}++fn merge_template_settings(template: &Value, request: Value) -> Value {+ let request_pipeline = pipeline_setting(&request);+ let template_pipeline = pipeline_setting(template);+ let Some(template_obj) = template.as_object().filter(|m| !m.is_empty()) else {+ return request;+ };+ let mut merged = if value_is_empty_object(&request) {+ Value::Object(template_obj.clone())+ } else {+ deep_merge_request_wins(&Value::Object(template_obj.clone()), &request)+ };+ // The request's spelling wins over the template's, whichever of the two+ // forms each side used. Filling gaps via deep-merge alone keeps a+ // template nested value when the request only set the dotted key.+ if let Some(pipeline) = request_pipeline.or(template_pipeline) {+ write_default_pipeline(&mut merged, &pipeline);+ }+ hoist_single_segment_index_keys(merged)+}++/// One template property, in the same native shape `es_properties_to_fields`+/// builds for an explicit mapping. `semantic_text` is text plus an embedding+/// contract — not `object` (#2281).+fn field_from_template_property(name: &str, field_def: &Value) -> xerj_common::types::FieldConfig {+ use xerj_common::types::{EmbeddingConfig, FieldConfig, FieldType};+ let es_type = field_def+ .get("type")+ .and_then(Value::as_str)+ .unwrap_or("object");+ let native_type = es_type_to_field_type(es_type);+ let mut fc = FieldConfig::new(name.to_string(), native_type);+ // #790: a template's `date_nanos` keeps nanosecond precision;+ // `FieldConfig::new` already made a plain `date` millisecond-scaled.+ if native_type == FieldType::Date && es_type == "date_nanos" {+ fc.options.date_precision = Some(xerj_common::types::DatePrecision::Nanos);+ }+ if es_type == "semantic_text" {+ // Same default as `es_properties_to_fields`: analyzed text has no+ // doc values unless the mapping asks. An explicit `true` is kept.+ fc.options.doc_values = field_def+ .get("doc_values")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ let dims = field_def+ .get("dimensions")+ .or_else(|| field_def.get("dims"))+ .and_then(Value::as_u64)+ .map(|d| d as usize)+ .unwrap_or(xerj_ai::local::DEFAULT_DIMS);+ fc.options.dimensions = Some(dims);+ fc.options.similarity = Some(+ field_def+ .get("similarity")+ .and_then(Value::as_str)+ .unwrap_or("cosine")+ .to_string(),+ );+ let target_field = field_def+ .get("target_field")+ .and_then(Value::as_str)+ .map(str::to_string)+ .unwrap_or_else(|| format!("{name}_vector"));+ fc.embedding = Some(EmbeddingConfig {+ endpoint: field_def+ .get("inference_endpoint")+ .and_then(Value::as_str)+ .map(str::to_string),+ model: field_def+ .get("inference_id")+ .or_else(|| field_def.get("model_id"))+ .and_then(Value::as_str)+ .map(str::to_string),+ target_field: Some(target_field),+ });+ }+ fc+}++fn json_properties_have_semantic_text(props: &Value) -> bool {+ let Some(obj) = props.as_object() else {+ return false;+ };+ obj.values().any(|spec| {+ spec.get("type").and_then(Value::as_str) == Some("semantic_text")+ || spec+ .get("properties")+ .is_some_and(json_properties_have_semantic_text)+ })+}+/// Convert an ES field type string to a native FieldType.fn es_type_to_field_type(es_type: &str) -> xerj_common::types::FieldType {use xerj_common::types::FieldType;match es_type {- "text" => FieldType::Text,+ // `semantic_text` carries the source text. The embedding lives on the+ // companion vector. Falling through to `Object` is what made a+ // template field report `type: object` (#2281).+ "text" | "semantic_text" => FieldType::Text,"keyword" | "constant_keyword" | "wildcard" => FieldType::Keyword,"long" | "integer" | "short" | "byte" | "unsigned_long" => FieldType::Long,"double" | "float" | "half_float" | "scaled_float" => FieldType::Double,@@ -5590,6 +5891,137 @@ mod governor_thread_spawn_tests {}}+#[cfg(test)]+mod index_template_merge_tests {+ //! #2281: a template's `semantic_text` and `index.default_pipeline` have+ //! to survive the merge with the body `xerj autoindex` actually sends.+ use super::{field_from_template_property, merge_template_mappings, merge_template_settings};+ use serde_json::json;++ #[test]+ fn dotted_template_pipeline_survives_an_autoindex_settings_body() {+ let template = json!({ "index.default_pipeline": "jsqlite-copy" });+ let request = json!({+ "index": { "xerj_ingest_shards": 1 },+ "index.query.strict_unknown_fields": true,+ "analysis": { "analyzer": { "default": { "type": "code" } } }+ });+ let merged = merge_template_settings(&template, request);+ assert_eq!(+ merged.pointer("/index/default_pipeline"),+ Some(&json!("jsqlite-copy")),+ "{merged}"+ );+ assert_eq!(+ merged.get("index.default_pipeline"),+ Some(&json!("jsqlite-copy")),+ "{merged}"+ );+ assert_eq!(+ merged.pointer("/index/xerj_ingest_shards"),+ Some(&json!(1)),+ "{merged}"+ );+ assert_eq!(+ merged.get("index.query.strict_unknown_fields"),+ Some(&json!(true)),+ "{merged}"+ );+ assert!(+ merged+ .pointer("/index/query.strict_unknown_fields")+ .is_none(),+ "a multi-dot key must stay dotted: {merged}"+ );+ assert_eq!(+ merged.pointer("/analysis/analyzer/default/type"),+ Some(&json!("code")),+ "{merged}"+ );+ }++ #[test]+ fn the_request_pipeline_wins_in_either_spelling() {+ let dotted_request = merge_template_settings(+ &json!({ "index": { "default_pipeline": "from-template" } }),+ json!({ "index.default_pipeline": "from-request" }),+ );+ assert_eq!(+ dotted_request.pointer("/index/default_pipeline"),+ Some(&json!("from-request")),+ "{dotted_request}"+ );+ let nested_request = merge_template_settings(+ &json!({ "index.default_pipeline": "from-template" }),+ json!({ "index": { "default_pipeline": "from-request" } }),+ );+ assert_eq!(+ nested_request.pointer("/index/default_pipeline"),+ Some(&json!("from-request")),+ "{nested_request}"+ );+ assert_eq!(+ nested_request.get("index.default_pipeline"),+ Some(&json!("from-request")),+ "{nested_request}"+ );+ }++ #[test]+ fn request_properties_replace_template_properties_of_the_same_name() {+ let merged = merge_template_mappings(+ &json!({+ "properties": {+ "diagnostic_semantic": { "type": "semantic_text" },+ "diagnostic_template_marker": { "type": "keyword" }+ }+ }),+ json!({+ "properties": {+ "impl": { "type": "text" },+ "diagnostic_semantic": { "type": "keyword" }+ }+ }),+ );+ assert_eq!(+ merged.pointer("/properties/diagnostic_semantic/type"),+ Some(&json!("keyword"))+ );+ assert_eq!(+ merged.pointer("/properties/diagnostic_template_marker/type"),+ Some(&json!("keyword"))+ );+ assert_eq!(+ merged.pointer("/properties/impl/type"),+ Some(&json!("text"))+ );+ }++ #[test]+ fn semantic_text_is_text_with_an_embedding_contract() {+ use xerj_common::types::FieldType;+ let semantic = field_from_template_property(+ "diagnostic_semantic",+ &json!({ "type": "semantic_text" }),+ );+ assert_eq!(semantic.field_type, FieldType::Text);+ assert!(!semantic.options.doc_values);+ let embedding = semantic.embedding.expect("embedding");+ assert_eq!(+ embedding.target_field.as_deref(),+ Some("diagnostic_semantic_vector")+ );+ assert_eq!(semantic.options.dimensions, Some(384));++ let keyword = field_from_template_property(+ "diagnostic_template_marker",+ &json!({ "type": "keyword" }),+ );+ assert_eq!(keyword.field_type, FieldType::Keyword);+ assert!(keyword.embedding.is_none());+ }+}+#[cfg(test)]mod pressure_drain_tests {use super::pressure_drain_due;diff --git a/engine/tests/es-compat-yaml/yaml/indices/indices.create/60_index_template_semantic_text.yml b/engine/tests/es-compat-yaml/yaml/indices/indices.create/60_index_template_semantic_text.ymlnew file mode 100644index 000000000..95536eb6c--- /dev/null+++ b/engine/tests/es-compat-yaml/yaml/indices/indices.create/60_index_template_semantic_text.yml@@ -0,0 +1,110 @@+setup:+ - do:+ ingest.put_pipeline:+ id: "tmpl_copy"+ body:+ processors:+ - copy:+ source: "impl"+ target: "diagnostic_semantic"++ - do:+ indices.put_index_template:+ name: "js2281"+ body:+ index_patterns: ["js2281-*"]+ priority: 100+ template:+ settings:+ index.default_pipeline: "tmpl_copy"+ mappings:+ properties:+ diagnostic_semantic:+ type: semantic_text+ diagnostic_template_marker:+ type: keyword++---+"A matching index template applies semantic_text and index.default_pipeline":+ - do:+ indices.create:+ index: js2281-plain++ - do:+ indices.get_mapping:+ index: js2281-plain+ - match: { js2281-plain.mappings.properties.diagnostic_semantic.type: "semantic_text" }+ - match: { js2281-plain.mappings.properties.diagnostic_template_marker.type: "keyword" }++ - do:+ indices.get_settings:+ index: js2281-plain+ - match: { js2281-plain.settings.index.default_pipeline: "tmpl_copy" }++ - do:+ index:+ index: js2281-plain+ id: "1"+ refresh: true+ body: { impl: "graph edges connect nodes in a network" }++ - do:+ get:+ index: js2281-plain+ id: "1"+ - match: { _source.diagnostic_semantic: "graph edges connect nodes in a network" }++---+"An autoindex-shaped create keeps the template field beside its own mapping":+ - do:+ indices.create:+ index: js2281-auto+ body:+ settings:+ index:+ xerj_ingest_shards: 1+ index.query.strict_unknown_fields: true+ mappings:+ properties:+ impl:+ type: text+ path:+ type: keyword++ - do:+ indices.get_mapping:+ index: js2281-auto+ - match: { js2281-auto.mappings.properties.diagnostic_semantic.type: "semantic_text" }+ - match: { js2281-auto.mappings.properties.impl.type: "text" }+ - match: { js2281-auto.mappings.properties.path.type: "keyword" }++ - do:+ indices.get_settings:+ index: js2281-auto+ - match: { js2281-auto.settings.index.default_pipeline: "tmpl_copy" }+ - match: { js2281-auto.settings.index.xerj_ingest_shards: "1" }++---+"The first bulk write auto-creates from the template":+ - do:+ bulk:+ refresh: true+ body:+ - '{"index": {"_index": "js2281-bulk", "_id": "1"}}'+ - '{"impl": "graph edges connect nodes in a network"}'++ - do:+ indices.get_mapping:+ index: js2281-bulk+ - match: { js2281-bulk.mappings.properties.diagnostic_semantic.type: "semantic_text" }++ - do:+ indices.get_settings:+ index: js2281-bulk+ - match: { js2281-bulk.settings.index.default_pipeline: "tmpl_copy" }++ - do:+ get:+ index: js2281-bulk+ id: "1"+ - match: { _source.diagnostic_semantic: "graph edges connect nodes in a network" }