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): delete a data stream's backing indices before recording the removal
xerj-org01597b296ad0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7851c4917..49c0f281d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -456,6 +456,58 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0service and addressable and the operator can retry the delete once the causeis fixed.+- **Index templates, ingest pipelines, data streams and ILM policies survive a+ restart** ([#203](https://github.com/xerj-org/xerj/issues/203)). Index+ templates, legacy (v1) templates, component templates, ingest pipelines, data+ streams and ILM policies lived only in memory: `PUT /_index_template/logs`+ answered `{"acknowledged": true}` and `GET` answered 404 after the next+ restart, and the next index that should have matched the template was created+ without it — with no error anywhere. All six are now persisted together in+ `<data_dir>/cluster_state.json`, written atomically (tmp → fsync → rename →+ fsync the parent directory) so the write is committed at the request, not in+ a shutdown hook, and restored in `Engine::new` before the listeners come up.+ A write that fails is rolled back in memory and answered with a 500 instead+ of `acknowledged`. Restored pipelines are recompiled, not just re-read —+ storing the definition alone would have left `?pipeline=x` accepted and+ silently inert after a restart.++ Four defects found while verifying it, each reproduced first:++ - Concurrent management writes corrupted each other (all flushes staged+ through one fixed `.tmp` path — 32 parallel template PUTs returned+ `store_exception`). Snapshot-and-write is now serialized.+ - A rollover interrupted between "backing index created" and "generation+ persisted" wedged the data stream forever: every later rollover recomputed+ the same name and got `409 resource_already_exists_exception`. Boot now+ adopts the highest generation actually present on disk, warns, and persists+ the repair once.+ - A `cluster_state.json` that could not be **read** (EACCES after a uid+ change on a container volume, a backup tool's chmod, EIO) came up as empty+ maps, and the next management write renamed a snapshot of those empty maps+ over a file whose bytes were perfectly good. The load failure now latches:+ every management mutation is refused with a 500 naming the file, and the+ file is not touched, until a boot loads it cleanly. The corrupt-parse arm+ refuses too, and still keeps a `cluster_state.corrupt.json` copy.+ - `DELETE /_data_stream/<name>` recorded the removal before destroying the+ backing indices, so a crash in that window stranded `.ds-<name>-00000N`+ directories that no data-stream API could reach — GET and DELETE answered+ 404 while `PUT /_data_stream/<name>` answered+ `409 resource_already_exists_exception` permanently. The order is reversed:+ the removal is recorded only once every backing index is gone, and a+ backing index that cannot be deleted now aborts the DELETE with a 500+ (it was previously swallowed and answered `acknowledged`) so the operator+ can retry.++ **Known gaps, deliberately not closed here.** `.ds-*` indices that no data+ stream claims — left by a data dir written before this change, or by a+ DELETE interrupted by an older build — are **not** cleaned up or adopted+ automatically; boot now names them in a warning and the recovery is+ `DELETE /<backing-index>` per index, because an orphan may hold the only copy+ of real data. And `aliases.json` still has the read-error shape that was+ fixed here for `cluster_state.json`: an unreadable aliases file is swallowed+ at boot and overwritten by the next alias write. That is pre-existing+ behaviour, not introduced here, and is tracked separately.+- **`autoindex` no longer leaves immortal catalog entries for skipped files**([#238](https://github.com/xerj-org/xerj/issues/238)). A file added after theresume plan was frozen is skipped and reported in the catalog — but thatdiff --git a/engine/crates/xerj-api/tests/cluster_metadata_survives_restart.rs b/engine/crates/xerj-api/tests/cluster_metadata_survives_restart.rsindex 590aad19f..b95d28899 100644--- a/engine/crates/xerj-api/tests/cluster_metadata_survives_restart.rs+++ b/engine/crates/xerj-api/tests/cluster_metadata_survives_restart.rs@@ -594,3 +594,147 @@ async fn concurrent_writes_do_not_corrupt_the_store() {);}}++/// `DELETE /_data_stream/<name>` must not leave a backing index behind.+///+/// Now that the stream is persisted, the *order* of the two destructive steps+/// decides whether a crash mid-delete is recoverable. Recording the removal+/// first and destroying the backing indices second leaves `.ds-<name>-00000N`+/// directories that no data-stream API can reach: GET and DELETE answer 404+/// while `PUT /_data_stream/<name>` answers `409+/// resource_already_exists_exception` — permanently, which is the same wedge+/// the interrupted-rollover test above exists to prevent.+///+/// This test pins the observable end state of a clean delete: nothing left on+/// disk, nothing left in the document, and the name immediately reusable+/// after a restart.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_deleted_data_stream_leaves_no_backing_index_behind() {+ let dir = tempfile::tempdir().expect("tempdir");++ {+ let app = app_over(dir.path());+ let (st, body) = put_json(&app, "/_data_stream/events", json!({})).await;+ assert_eq!(st, StatusCode::OK, "PUT _data_stream: {body}");+ for _ in 0..2 {+ let (st, body) = post(&app, "/events/_rollover", json!({})).await;+ assert_eq!(st, StatusCode::OK, "rollover: {body}");+ }+ assert!(+ dir.path().join(".ds-events-000003").is_dir(),+ "fixture is wrong: three generations should exist"+ );++ let (st, body) = delete(&app, "/_data_stream/events").await;+ assert_eq!(st, StatusCode::OK, "DELETE _data_stream: {body}");+ }++ let leftovers: Vec<String> = std::fs::read_dir(dir.path())+ .expect("read data dir")+ .filter_map(|e| e.ok())+ .map(|e| e.file_name().to_string_lossy().into_owned())+ .filter(|n| n.starts_with(".ds-events-"))+ .collect();+ assert!(+ leftovers.is_empty(),+ "a delete that answered 200 left backing indices on disk: {leftovers:?}"+ );++ let state: Value = serde_json::from_slice(+ &std::fs::read(dir.path().join("cluster_state.json")).expect("read"),+ )+ .expect("parse");+ assert!(+ state["data_streams"]["events"].is_null(),+ "the removal did not reach disk: {state}"+ );++ // The name must be reusable — the wedge shows up here as a 409 naming a+ // backing index the operator can no longer see.+ let app = app_over(dir.path());+ let (st, body) = put_json(&app, "/_data_stream/events", json!({})).await;+ assert_eq!(+ st,+ StatusCode::OK,+ "the stream name must be free after a delete + restart: {body}"+ );+}++/// A backing index that cannot be destroyed must abort the delete, not be+/// acknowledged.+///+/// This is the ordering above stated as a property rather than an outcome: the+/// removal is only recorded once every backing index is really gone. The+/// failure is injected where it actually happens in the field — the directory+/// cannot be unlinked (read-only mount, EACCES after a uid change, EIO) —+/// and the assertions are that the operator is told, that the stream is still+/// fully addressable, that the document on disk still names it, and that the+/// retry after the cause is fixed completes the job.+///+/// Unix-only, and skipped when the process can write through a `chmod 555`+/// (i.e. running as root), where the failure cannot be injected this way.+#[cfg(unix)]+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_backing_index_that_cannot_be_deleted_aborts_the_delete() {+ use std::os::unix::fs::PermissionsExt;++ let dir = tempfile::tempdir().expect("tempdir");+ let app = app_over(dir.path());+ let (st, body) = put_json(&app, "/_data_stream/orders", json!({})).await;+ assert_eq!(st, StatusCode::OK, "PUT _data_stream: {body}");++ let backing = dir.path().join(".ds-orders-000001");+ assert!(backing.is_dir(), "fixture is wrong: no backing index");+ let before = std::fs::read_to_string(dir.path().join("cluster_state.json")).expect("read");++ // Make the backing index's own contents un-unlinkable. Nothing inside is+ // destroyed, and the data dir stays writable — so a flush would succeed+ // if the code reached one, which is what makes the assertion below about+ // the document meaningful.+ std::fs::set_permissions(&backing, std::fs::Permissions::from_mode(0o555)).expect("chmod 555");+ if std::fs::File::create(backing.join("root-probe")).is_ok() {+ let _ = std::fs::remove_file(backing.join("root-probe"));+ std::fs::set_permissions(&backing, std::fs::Permissions::from_mode(0o755))+ .expect("chmod 755");+ eprintln!("skipped: permissions do not deny this process (running as root?)");+ return;+ }++ let (st, body) = delete(&app, "/_data_stream/orders").await;+ std::fs::set_permissions(&backing, std::fs::Permissions::from_mode(0o755)).expect("chmod 755");+ assert_eq!(+ st,+ StatusCode::INTERNAL_SERVER_ERROR,+ "a delete that could not destroy a backing index must report it, not \+ answer acknowledged: {body}"+ );++ let (st, body) = get(&app, "/_data_stream/orders").await;+ assert_eq!(+ st,+ StatusCode::OK,+ "the stream must stay addressable after a failed delete, or the \+ operator has no way to retry it: {body}"+ );+ assert_eq!(+ std::fs::read_to_string(dir.path().join("cluster_state.json")).expect("read"),+ before,+ "the removal must not have been recorded while the data is still there"+ );++ // The cause is fixed; the retry finishes the job.+ let (st, body) = delete(&app, "/_data_stream/orders").await;+ assert_eq!(st, StatusCode::OK, "retry after the cause is fixed: {body}");+ assert!(+ !backing.exists(),+ "the retry left the backing index on disk"+ );+ let state: Value = serde_json::from_slice(+ &std::fs::read(dir.path().join("cluster_state.json")).expect("read"),+ )+ .expect("parse");+ assert!(+ state["data_streams"]["orders"].is_null(),+ "the retry did not record the removal: {state}"+ );+}diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex 4c575e817..34f14da08 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -851,6 +851,11 @@ impl Engine {// actually present, and before the server accepts requests.engine.load_cluster_state();+ // Then say plainly which `.ds-*` indices no restored stream claims.+ // Nothing is deleted — see the doc comment; this is the log line that+ // stops an unreachable backing index from being invisible.+ engine.warn_orphaned_backing_indices();+// Restore ISM/ILM policies and managed-index execution state so a// policy attached before a restart keeps running afterward instead// of silently going idle. Separate files (`ism_policies.json`,@@ -2095,6 +2100,69 @@ impl Engine {}}+ /// Name every `.ds-*` index on disk that no restored data stream claims.+ ///+ /// This does **not** reconcile anything — nothing is deleted, adopted or+ /// repaired, because an orphan may hold the only copy of somebody's data.+ /// It exists so the state is not *silent*: an orphaned backing index is+ /// unreachable through the data-stream API (`GET` and `DELETE` on the+ /// stream answer 404, while `PUT /_data_stream/<name>` answers+ /// `409 resource_already_exists_exception` naming the orphan), so without+ /// a line in the boot log the operator has no way to learn the name they+ /// have to pass to `DELETE /<backing-index>` to clear it.+ ///+ /// Expected sources: a data dir written by a build that predates+ /// `cluster_state.json` (data streams were not persisted at all then), or+ /// a `DELETE /_data_stream` interrupted by a build that recorded the+ /// removal before destroying the backing indices. Skipped entirely when+ /// the cluster state did not load — then every stream is unknown and+ /// every backing index would look orphaned.+ fn warn_orphaned_backing_indices(&self) {+ if !self+ .cluster_state_loaded+ .load(std::sync::atomic::Ordering::Acquire)+ {+ return;+ }+ // Snapshot both maps before comparing them: nothing here may hold a+ // shard guard on one map while taking one on the other.+ let backing: Vec<String> = self+ .indices+ .iter()+ .map(|e| e.key().clone())+ .filter(|n| n.starts_with(".ds-"))+ .collect();+ if backing.is_empty() {+ return;+ }+ let streams: Vec<(String, Vec<String>)> = self+ .data_streams+ .iter()+ .map(|s| (s.key().clone(), s.value().backing_indices.clone()))+ .collect();+ let claimed = |index: &str| {+ streams.iter().any(|(stream, indices)| {+ indices.iter().any(|b| b == index)+ || index+ .strip_prefix(&format!(".ds-{stream}-"))+ .is_some_and(|gen| gen.parse::<u64>().is_ok())+ })+ };+ let mut orphans: Vec<String> = backing.into_iter().filter(|n| !claimed(n)).collect();+ if orphans.is_empty() {+ return;+ }+ orphans.sort();+ warn!(+ count = orphans.len(),+ indices = orphans.join(","),+ "backing indices on disk belong to no known data stream — they are \+ unreachable through the data-stream API and are NOT deleted \+ automatically; remove each with DELETE /<index> once you have \+ confirmed the data is not wanted"+ );+ }+/// Insert into a persisted map and durably record the result, rolling the/// in-memory change back if the write fails so a 500 never leaves a/// change that only this process can see.@@ -2856,27 +2924,81 @@ impl Engine {.map(|(_, v)| v).ok_or_else(|| EngineError::Common(xerj_common::XerjError::index_not_found(name)))?;- // Record the removal before any backing index is destroyed: if the- // process dies mid-delete, a boot that still believes in the stream- // is recoverable (it warns about the missing backing indices), while- // one that has forgotten it leaves orphaned `.ds-*` directories no- // API can reach. A write failure here aborts the delete outright —- // nothing has been destroyed yet, so the stream is put back intact.+ // Destroy the backing indices FIRST, and only then record the removal.+ // The two orderings fail differently and only one of them is+ // recoverable:+ //+ // destroy → record (this one): a crash in the window leaves+ // `cluster_state.json` still describing the stream while some of its+ // `.ds-*` directories are already gone. The next boot restores the+ // stream and warns `restored data stream references backing indices+ // that are not present in the data dir` (see `load_cluster_state`),+ // `GET /_data_stream/<name>` still answers, and re-issuing the+ // DELETE finishes the job.+ //+ // record → destroy: a crash in the window strands+ // `.ds-<name>-00000N` directories that no data-stream API can reach+ // — GET and DELETE answer 404 while `PUT /_data_stream/<name>`+ // answers `409 resource_already_exists_exception` forever, and boot+ // does not reconcile it. That is the same permanent wedge this PR+ // fixes for an interrupted rollover, so it is not the ordering to+ // ship.+ //+ // A backing index that cannot be destroyed therefore aborts the+ // delete: the stream is put back and the caller gets the error, so+ // the operator can retry rather than be told `acknowledged` about+ // data that is still on disk. A retry is safe — an already-deleted+ // backing index is simply absent from `self.indices` on the next+ // pass.+ let mut delete_err: Option<EngineError> = None;+ for backing in &ds.backing_indices {+ let Some((_, idx)) = self.indices.remove(backing) else {+ // Not open: nothing left to destroy under this name (a+ // previous attempt already removed it).+ continue;+ };+ match idx.delete_all_data().await {+ Ok(()) => {}+ // `remove_dir_all` reports an already-absent directory as+ // NotFound, which is the outcome we were asking for.+ Err(EngineError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}+ Err(e) => {+ warn!(+ data_stream = name,+ backing = backing.as_str(), error = %e,+ "backing index could not be deleted — the data stream \+ is left in place so the DELETE can be retried"+ );+ // Put it back so a retry can try again, and so the stream+ // we are about to restore does not point at an index the+ // engine has forgotten how to reach.+ self.indices.insert(backing.clone(), idx);+ if delete_err.is_none() {+ delete_err = Some(e);+ }+ }+ }+ }+ if let Some(e) = delete_err {+ self.data_streams.insert(name.to_string(), ds);+ return Err(e);+ }++ // Only now is the removal safe to make durable. A write failure here+ // means the data is gone but the document still names the stream —+ // the recoverable half of the window above, so put the stream back in+ // memory as well, keeping memory and disk saying the same thing, and+ // report the error instead of acknowledging.if let Err(e) = self.flush_cluster_state() {self.data_streams.insert(name.to_string(), ds);return Err(e);}- // Remove the alias.+ // Remove the alias. Last, so a failure anywhere above leaves the+ // stream fully addressable for the retry.self.aliases.remove(name);self.flush_aliases();- // Delete every backing index.- for backing in &ds.backing_indices {- if let Ok(idx) = self.indices.remove(backing).map(|(_, v)| v).ok_or(()) {- let _ = idx.delete_all_data().await;- }- }info!(name, "data stream deleted");Ok(())}