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(engine): persist index mappings durably — explicit PUT mappings survived restart only in memory
xerj-org33d06fb4956c
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex ad43fbb8f..9015b5085 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -559,10 +559,11 @@ pub async fn create_index(}));}if !mappings_val.is_null() {+ // Persists es_mapping.json into the index dir (atomic) so+ // the create-time mapping survives a restart.state.engine- .index_mappings- .insert(index.clone(), mappings_val.clone());+ .put_index_mapping(&index, mappings_val.clone());}if let Some(aliases) = body.get("aliases").and_then(Value::as_object) {// Alias keys can also contain date math@@ -1188,7 +1189,9 @@ pub async fn put_mapping(} else {existing = body.clone();}- state.engine.index_mappings.insert(idx_name.clone(), existing);+ // Persists es_mapping.json into the index dir (atomic) so the+ // merged mapping survives a restart.+ state.engine.put_index_mapping(idx_name, existing);}Json(json!({ "acknowledged": true })).into_response()diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex 850e0bd12..cd0259216 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -322,6 +322,11 @@ impl Engine {match Index::open(index_name.clone(), &engine.config, &data_dir) {Ok(idx) => {info!(name = name_str.as_str(), "opened existing index");+ // Restore the raw ES mapping blob (analyzers, formats,+ // dims — full fidelity) BEFORE any ingest/query can run,+ // so GET /_mapping and mapping-dependent code paths see+ // the same mapping as pre-restart.+ engine.load_persisted_es_mapping(&name_str);engine.indices.insert(name_str, idx);}Err(e) => {@@ -462,6 +467,51 @@ impl Engine {Ok(())}+ /// Register the raw ES mapping blob for `name` and persist it into the+ /// index data dir (atomic temp-file + rename) so `GET /{index}/_mapping`+ /// round-trips the exact user-provided mapping (analyzers, date formats,+ /// dense_vector dims/similarity, multi-fields) across restarts.+ ///+ /// This is the single write path for `engine.index_mappings` — both+ /// index-create-with-mappings and PUT /_mapping go through here.+ pub fn put_index_mapping(&self, name: &str, mapping: Value) {+ let index_dir = self.data_dir.join(name);+ if index_dir.is_dir() {+ match serde_json::to_vec_pretty(&mapping) {+ Ok(bytes) => {+ if let Err(e) = crate::index::write_file_atomic(+ &index_dir.join("es_mapping.json"),+ &bytes,+ ) {+ warn!(index = name, error = %e, "failed to persist es_mapping.json");+ }+ }+ Err(e) => {+ warn!(index = name, error = %e, "failed to serialize index mapping for persistence");+ }+ }+ }+ self.index_mappings.insert(name.to_string(), mapping);+ }++ /// Load a previously-persisted raw ES mapping blob for `name` (if any)+ /// into the in-memory `index_mappings` map. Called whenever an index is+ /// (re)opened from disk — boot scan and snapshot restore. A missing+ /// file is fine (pre-fix indices, dynamic-only indices): readers fall+ /// back to schema-derived properties from `schema.json`.+ fn load_persisted_es_mapping(&self, name: &str) {+ let path = self.data_dir.join(name).join("es_mapping.json");+ let Ok(bytes) = std::fs::read(&path) else { return };+ match serde_json::from_slice::<Value>(&bytes) {+ Ok(mapping) => {+ self.index_mappings.insert(name.to_string(), mapping);+ }+ Err(e) => {+ warn!(index = name, error = %e, "ignoring corrupt es_mapping.json");+ }+ }+ }+/// Find the highest-priority template matching `index_name`.fn best_matching_template(&self, index_name: &str) -> Option<IndexTemplate> {let mut best: Option<(i32, IndexTemplate)> = None;@@ -995,6 +1045,9 @@ impl Engine {let index_name = IndexName::new(idx_name).map_err(EngineError::Common)?;match Index::open(index_name, &self.config, &self.data_dir) {Ok(idx) => {+ // Snapshot dirs carry es_mapping.json — reload it so the+ // restored index serves the same mapping it was saved with.+ self.load_persisted_es_mapping(idx_name);self.indices.insert(idx_name.clone(), idx);info!(index = idx_name, "index restored from snapshot");}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 76c351c4a..d9adc8ea5 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -464,7 +464,19 @@ impl Index {let settings_path = index_dir.join("settings.json");if !settings.is_null() {let bytes = serde_json::to_vec_pretty(&settings)?;- std::fs::write(&settings_path, bytes)?;+ write_file_atomic(&settings_path, &bytes)?;+ }++ // Persist the schema at create time so an explicit mapping+ // (PUT /{index} with a mappings body) survives a restart.+ // Historically schema.json was only written by put_mapping /+ // dynamic-field evolution, so a create-time mapping silently+ // degraded to ManagedSchema::dynamic() (empty) after reboot —+ // keyword FST routing, analyzers, and doc-values typing all+ // reverted to inference until a manual _mapping PUT.+ {+ let bytes = serde_json::to_vec_pretty(&managed)?;+ write_file_atomic(&index_dir.join("schema.json"), &bytes)?;}// Build analyzer registry, applying any custom analysis settings.@@ -5847,7 +5859,7 @@ impl Index {let path = self.data_dir.join("settings.json");let bytes = serde_json::to_vec_pretty(&settings)?;- std::fs::write(&path, bytes).map_err(EngineError::Io)?;+ write_file_atomic(&path, &bytes).map_err(EngineError::Io)?;*self.settings.write().await = settings;Ok(())}@@ -5974,7 +5986,7 @@ impl Index {async fn save_schema(&self, schema: &ManagedSchema) -> Result<()> {let path = self.data_dir.join("schema.json");let bytes = serde_json::to_vec_pretty(schema)?;- std::fs::write(&path, bytes).map_err(EngineError::Io)?;+ write_file_atomic(&path, &bytes).map_err(EngineError::Io)?;Ok(())}@@ -8441,6 +8453,30 @@ fn store_config_from(config: &Config) -> IndexStoreConfig {}}+/// Write `bytes` to `path` atomically: write a same-directory temp file,+/// fsync it, then rename over the target. A kill -9 mid-write leaves+/// either the old file or the new file on disk, never a truncated one.+/// This matters for `schema.json`: `load_schema` treats a torn file as+/// "no schema" and silently falls back to an empty dynamic mapping,+/// which is a mapping-loss corruption after crash.+pub fn write_file_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {+ let tmp = path.with_extension("tmp");+ {+ use std::io::Write as _;+ let mut f = std::fs::File::create(&tmp)?;+ f.write_all(bytes)?;+ f.sync_all()?;+ }+ std::fs::rename(&tmp, path)?;+ // Make the rename itself durable across power loss.+ if let Some(parent) = path.parent() {+ if let Ok(dir) = std::fs::File::open(parent) {+ let _ = dir.sync_all();+ }+ }+ Ok(())+}+fn load_schema(index_dir: &Path) -> std::result::Result<ManagedSchema, ()> {let path = index_dir.join("schema.json");let bytes = std::fs::read(path).map_err(|_| ())?;