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(lifecycle): port #262's ILM safety rails onto the shipped engine (#282)
xerj-orgbb76adbd57bb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9ab0df067..23cc2c8fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **`PUT /{index}/_settings {"index.lifecycle.name": null}` actually detaches+ the index, and the detach survives a restart** (#282, ported from #262). The+ null previously fell through a string-only settings reader, so the operator+ got `200 acknowledged` while the index stayed attached — to a policy whose+ delete phase then destroyed it. A detach now removes the execution cursor,+ writes a persisted tombstone (`ism_managed_indices.json` grew a+ `managed`/`detached` envelope; the old bare-map file is still read), and+ scrubs the stale `index.lifecycle.name` from the stored settings.+- **The lifecycle delete action gained #262's safety rails.** It now refuses —+ visibly, in `explain`, never silently — to delete a dot-prefixed internal+ index (`.ds-*` backing indices exempt), a data stream's current write index,+ or an index whose age cannot be established from its execution cursor.+- **An ILM policy naming an action the engine cannot execute is refused at PUT+ time with the action named** (400), instead of being stored with the action+ silently dropped — the accepted-and-ignored class (#204). Executable ILM+ actions are `rollover`, `delete`, `readonly`.++### Added++- **`GET /_ilm/status`, `POST /_ilm/start`, `POST /_ilm/stop`** (#282): the+ operator can halt lifecycle execution without stopping the node; a stopped+ engine's tick touches nothing. The flag is in-memory — a restart resumes+ execution — while the per-index detach tombstone is the durable stop.+- **`POST /{index}/_ilm/remove`** (#282): ES's own detach verb; goes through+ the same tombstoned detach path as the settings-null route. A literal name+ that is not an index answers 404 rather than writing a tombstone for a+ ghost.+- **A crafted filename can no longer forge records on the agent progressstream** (the first rc.15 known issue below). Every externally-controlledstring — in-flight paths, the paths and error text interpolated into humandiff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 578ba2e90..af678a733 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -1142,7 +1142,7 @@ pub async fn create_index(// silent on a missing/untranslatable policy — real ILM is// equally lenient here: it discovers the policy by name lazily// and simply doesn't start managing until one exists.- if let Some(policy_name) = ilm_policy_name_from_settings(&body) {+ if let Some(Some(policy_name)) = ilm_lifecycle_directive_from_settings(&body) {let _ = crate::ism_api::attach_policy(&state, &index, &policy_name).await;}@@ -22116,31 +22116,72 @@ pub async fn put_settings(sync_display_blocks(&state, name).await;}- // Same lazy, best-effort `index.lifecycle.name` attach as create_index —- // `PUT {index}/_settings {"index.lifecycle.name": "policy"}` is the- // other real ILM entry point (attaching to an index that already- // exists, not just at creation).- if let Some(policy_name) = ilm_policy_name_from_settings(&body) {- for idx in &targets {- let _ = crate::ism_api::attach_policy(&state, idx, &policy_name).await;+ // `PUT {index}/_settings` is the other real ILM entry point — for+ // attaching (`"index.lifecycle.name": "policy"`) AND for detaching+ // (`"index.lifecycle.name": null`, issue #282). The detach goes through+ // `Engine::detach_lifecycle`, which tombstones and persists it: the+ // `acknowledged: true` this handler returns must still be true after a+ // restart, and must stop the delete phase immediately.+ match ilm_lifecycle_directive_from_settings(&body) {+ Some(Some(policy_name)) => {+ for idx in &targets {+ let _ = crate::ism_api::attach_policy(&state, idx, &policy_name).await;+ }+ }+ Some(None) => {+ for idx in &targets {+ // Never tombstone a name that is not an index: a persisted+ // tombstone for a ghost is unbounded state writable from+ // the public port (#262 hit exactly this in review).+ if state.engine.get_index(idx).is_ok() {+ state.engine.detach_lifecycle(idx);+ }+ }}+ None => {}}Json(json!({ "acknowledged": true })).into_response()}-/// Extract `index.lifecycle.name` from an index-settings body, accepting-/// both the nested (`{"index":{"lifecycle":{"name":"..."}}}`,-/// `{"settings":{...}}`-wrapped at create time) and flat dotted-key-/// (`{"index.lifecycle.name":"..."}`) forms ES accepts for every index-/// setting.-fn ilm_policy_name_from_settings(body: &Value) -> Option<String> {+/// What a settings body asks lifecycle management to do about the index's+/// attachment, reading both the nested (`{"index":{"lifecycle":{"name":+/// "..."}}}`, `{"settings":{...}}`-wrapped at create time) and flat+/// dotted-key (`{"index.lifecycle.name":"..."}`) forms ES accepts for every+/// index setting.+///+/// Three-valued on purpose (issue #282, ported from #262's+/// `lifecycle_directive_from_settings`), because `Option<String>` cannot+/// tell "the caller said nothing about `index.lifecycle.name`" apart from+/// "the caller said `null`", and those mean opposite things:+///+/// * `None` — the body does not mention `index.lifecycle.name`. Leave the+/// attachment exactly as it is.+/// * `Some(None)` — explicit `null` (or an empty string): **detach**, ES's+/// documented way to stop managing an index. Before #282 this arm did+/// not exist: the null fell through `Value::as_str` and the index stayed+/// attached to a policy whose delete phase later fired — the data-loss+/// defect found in #262's review.+/// * `Some(Some(policy))` — attach to `policy`.+fn ilm_lifecycle_directive_from_settings(body: &Value) -> Option<Option<String>> {let settings = body.get("settings").unwrap_or(body);- settings+ let v = settings.pointer("/index/lifecycle/name")- .or_else(|| settings.get("index.lifecycle.name"))- .and_then(Value::as_str)- .map(String::from)+ .or_else(|| settings.get("index.lifecycle.name"))?;+ match v {+ Value::Null => Some(None),+ Value::String(s) => {+ let t = s.trim();+ if t.is_empty() {+ Some(None)+ } else {+ Some(Some(t.to_string()))+ }+ }+ // Any other JSON type is not a policy name. Treat it as "said+ // nothing" rather than guessing a detach out of a malformed body.+ _ => None,+ }}// ─────────────────────────────────────────────────────────────────────────────@@ -24072,41 +24113,37 @@ pub async fn put_ilm_policy(Path(name): Path<String>,Json(body): Json<Value>,) -> impl IntoResponse {+ // Translate into the shared internal model (`xerj_engine::lifecycle`)+ // FIRST, and refuse the PUT outright if any part of the policy is not+ // executable (issue #282, ported from #262's `validate_policy`+ // allowlist). This used to accept the policy with an advisory+ // `"xerj_lifecycle_execution": "unsupported"` note in the response —+ // but nothing reads a response note twice: the policy sat stored and+ // GET-able, looking configured, while executing less than it said (or+ // nothing at all). Accepted-and-ignored is this repo's dominant bug+ // class (#204); a 400 naming the action is the honest answer.+ let policy = match xerj_engine::lifecycle::translate_ilm_policy(&body) {+ Ok(policy) => policy,+ Err(reason) => {+ return ApiError::new(xerj_common::XerjError::invalid_query(format!(+ "ILM policy '{name}' was refused, not stored: {reason}"+ )))+ .into_response();+ }+ };+// Persist the raw policy verbatim in the ILM store; `get_ilm_policy`// reads it back out of this same DashMap, so PUT then GET round-trips- // faithfully regardless of whether translation below succeeds — and the- // store is written to `<data_dir>/cluster_state.json`, so it round-trips- // after a restart too (issue #203). This write goes first because it is- // the one that can fail loudly: if the document cannot be persisted the- // request is a 500 and nothing has happened yet, rather than an- // `acknowledged` that a reboot silently undoes.+ // faithfully — and the store is written to+ // `<data_dir>/cluster_state.json`, so it round-trips after a restart+ // too (issue #203). If the document cannot be persisted the request is+ // a 500 and nothing has happened, rather than an `acknowledged` that a+ // reboot silently undoes.if let Err(e) = state.engine.put_ilm_policy(name.clone(), body.clone()) {return ApiError::new(xerj_common::XerjError::from(e)).into_response();}-- // Translate into the shared internal model (`xerj_engine::lifecycle`)- // so the SAME background job that drives native ISM policies also- // drives this one — see that module's doc comment for why. Real ILM- // is lenient about phase actions it can't reproduce internally too- // (e.g. `searchable_snapshot` is best-effort); mirroring that, a- // translation failure here doesn't fail the PUT — the policy is- // still stored and GET-able, it just won't actually execute (no entry- // lands in `ism_policies`) until it's fixed. Surfaced back in the- // response so this isn't silent.- match xerj_engine::lifecycle::translate_ilm_policy(&body) {- Ok(policy) => {- state.engine.put_ism_policy(name, policy);- Json(json!({ "acknowledged": true })).into_response()- }- Err(reason) => Json(json!({- "acknowledged": true,- "xerj_lifecycle_execution": {- "status": "unsupported",- "reason": reason,- }- }))- .into_response(),- }+ state.engine.put_ism_policy(name, policy);+ Json(json!({ "acknowledged": true })).into_response()}// GET _ilm/policy (no name segment) — the form Kibana's own ILM UI calls to@@ -24263,6 +24300,88 @@ pub async fn ilm_explain(Json(json!({ "indices": Value::Object(indices) })).into_response()}+/// Resolve an index spec for the ILM endpoints that refuse ghosts: every+/// *named* (non-wildcard) part must be an existing index or alias, and the+/// result is filtered to indices that actually exist. A wildcard matching+/// nothing is a legal empty answer (ES's `allow_no_indices=true` default);+/// a literal that names nothing is a 404 `index_not_found_exception`.+///+/// Exists because `resolve_index_selector`'s documented fallback returns a+/// literal name whether or not it exists — the right default for lenient+/// read endpoints, and exactly wrong for a detach that writes a persisted+/// tombstone per target (#262 shipped that bug first and fixed it as+/// `resolve_existing_index_targets`; same name, same rule here).+async fn resolve_existing_index_targets(+ state: &AppState,+ spec: &str,+) -> Result<Vec<String>, xerj_common::XerjError> {+ for part in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) {+ if part == "_all" || part.contains('*') {+ continue;+ }+ if state.engine.get_index(part).is_err() && !state.engine.aliases.contains_key(part) {+ return Err(xerj_common::XerjError::index_not_found(part));+ }+ }+ Ok(resolve_index_selector(state, spec)+ .await+ .into_iter()+ .filter(|t| state.engine.get_index(t).is_ok())+ .collect())+}++/// `POST /{index}/_ilm/remove` — stop managing these indices (issue #282).+///+/// ES's own verb for detaching; until #282 the only detach route was `PUT+/// /{index}/_settings {"index.lifecycle.name": null}` — which was itself+/// silently ignored. Both now go through [`xerj_engine::Engine::detach_lifecycle`],+/// so a detach is recorded (tombstoned + persisted) once, whichever surface+/// the operator used.+pub async fn remove_ilm_policy_from_index(+ State(state): State<AppState>,+ Path(index): Path<String>,+) -> impl IntoResponse {+ let targets = match resolve_existing_index_targets(&state, &index).await {+ Ok(t) => t,+ Err(e) => return ApiError::new(e).into_response(),+ };+ for name in &targets {+ state.engine.detach_lifecycle(name);+ }+ Json(json!({ "has_failures": false, "failed_indexes": [] })).into_response()+}++/// `GET /_ilm/status` — `RUNNING`/`STOPPED` plus XERJ's honest counters+/// (issue #282). An operator halting retention needs to see that the halt+/// took; a status endpoint that cannot disagree with the executor is the+/// receipt (`operation_mode` reads the same flag `lifecycle::tick` checks).+pub async fn get_ilm_status(State(state): State<AppState>) -> impl IntoResponse {+ let running = state.engine.lifecycle_execution_running();+ Json(json!({+ "operation_mode": if running { "RUNNING" } else { "STOPPED" },+ "xerj": {+ "managed_indices": state.engine.managed_indices.len(),+ "detached_indices": state.engine.lifecycle_detached.len(),+ "policies": state.engine.ism_policies.len(),+ }+ }))+ .into_response()+}++/// `POST /_ilm/start` and `POST /_ilm/stop` — the operator's kill switch+/// (issue #282): halt lifecycle execution without stopping the node. The+/// flag is in-memory (a restart resumes execution — erring on the side of+/// retention running); the detach tombstone is the durable per-index stop.+pub async fn start_ilm(State(state): State<AppState>) -> impl IntoResponse {+ state.engine.set_lifecycle_execution_running(true);+ Json(json!({ "acknowledged": true, "operation_mode": "RUNNING" })).into_response()+}++pub async fn stop_ilm(State(state): State<AppState>) -> impl IntoResponse {+ state.engine.set_lifecycle_execution_running(false);+ Json(json!({ "acknowledged": true, "operation_mode": "STOPPED" })).into_response()+}+// ─────────────────────────────────────────────────────────────────────────────// Component Templates// PUT /_component_template/{name}diff --git a/engine/crates/xerj-api/src/ism_api.rs b/engine/crates/xerj-api/src/ism_api.rsindex 0f280c5c3..cb411088b 100644--- a/engine/crates/xerj-api/src/ism_api.rs+++ b/engine/crates/xerj-api/src/ism_api.rs@@ -228,6 +228,9 @@ pub async fn attach_policy(state: &AppState, index: &str, policy_id: &str) -> Repolicy.default_state.clone(),lifecycle::now_ms(),);+ // An explicit attach overrides an earlier detach: clear the tombstone+ // (#282) before inserting so the persisted state says one thing.+ state.engine.lifecycle_detached.remove(index);state.engine.managed_indices@@ -250,8 +253,11 @@ pub async fn remove_ism_policy(State(state): State<AppState>,Path(index): Path<String>,) -> impl IntoResponse {- if state.engine.managed_indices.remove(&index).is_some() {- state.engine.persist_managed_indices();+ if state.engine.managed_indices.contains_key(&index) {+ // One shared detach path (engine method) for all three detach+ // routes, so the acknowledged detach is tombstoned and persisted+ // identically whichever surface the operator used (#282).+ state.engine.detach_lifecycle(&index);Json(single_index_success()).into_response()} else {Json(not_managed_failure(diff --git a/engine/crates/xerj-api/src/router.rs b/engine/crates/xerj-api/src/router.rsindex 69acda4f9..2d170650e 100644--- a/engine/crates/xerj-api/src/router.rs+++ b/engine/crates/xerj-api/src/router.rs@@ -483,6 +483,15 @@ pub fn build_es_compat_router(state: AppState) -> Router {.delete(es_compat::delete_ilm_policy),).route("/:index/_ilm/explain", get(es_compat::ilm_explain))+ // Operator surface (issue #282): status, the start/stop kill+ // switch, and ES's own detach verb.+ .route("/_ilm/status", get(es_compat::get_ilm_status))+ .route("/_ilm/start", post(es_compat::start_ilm))+ .route("/_ilm/stop", post(es_compat::stop_ilm))+ .route(+ "/:index/_ilm/remove",+ post(es_compat::remove_ilm_policy_from_index),+ )// ── ISM (OpenSearch Index State Management) ─────────────────────────// Same execution engine as ILM above — see `xerj_engine::lifecycle`..route(diff --git a/engine/crates/xerj-api/tests/ilm_safety_rails.rs b/engine/crates/xerj-api/tests/ilm_safety_rails.rsnew file mode 100644index 000000000..6748a3af6--- /dev/null+++ b/engine/crates/xerj-api/tests/ilm_safety_rails.rs@@ -0,0 +1,455 @@+//! Issue #282: port #262's ILM safety rails onto the shipped lifecycle+//! engine (#247).+//!+//! Four rails, each of which #262 carried and the merged #247 engine did+//! not, each independently a real defect:+//!+//! 1. **Detach must be honoured and survive restart.** `PUT+//! /{index}/_settings {"index.lifecycle.name": null}` is ES's+//! documented way to stop managing an index. Before the fix the null+//! was silently ignored (`ilm_policy_name_from_settings` only reads+//! strings), so the operator got `200 acknowledged` and the delete+//! phase later destroyed the index anyway — the data-loss class from+//! the #262 review.+//! 2. **Fail-closed action allowlist.** An ILM policy naming an action+//! this engine cannot execute (`forcemerge`, `set_priority`, …) must+//! be refused at PUT time with the action named, not stored with the+//! action silently dropped (the accepted-and-ignored class, #204).+//! 3. **Delete rails.** The lifecycle delete action must never remove a+//! dot-prefixed internal index (brains, `.kibana*`; `.ds-*` backing+//! indices are the one exempt family), never a data stream's current+//! write index, and never an index whose age cannot be established+//! from its execution cursor.+//! 4. **Operator kill switch.** `GET /_ilm/status`, `POST /_ilm/start`,+//! `POST /_ilm/stop` and `POST /{index}/_ilm/remove` must exist; while+//! stopped, a tick must not act.+//!+//! Elasticsearch is referenced for wire semantics only; no ES code is+//! reproduced here.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++fn config_for(dir: &std::path::Path) -> xerj_common::config::Config {+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ config+}++/// Build a fresh app over `dir`, returning the state handle too so tests+/// can drive `lifecycle::tick` deterministically (the background manager is+/// only spawned by the server binary, never by `Engine::new`).+fn state_over(dir: &std::path::Path) -> (axum::Router, xerj_api::state::AppState) {+ let config = config_for(dir);+ 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);+ let app = xerj_api::router::build_es_compat_router(state.clone());+ (app, state)+}++async fn send(app: &axum::Router, req: Request<Body>) -> (StatusCode, Value) {+ let response = app.clone().oneshot(req).await.expect("response");+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .expect("body");+ (+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ )+}++async fn req_json(+ app: &axum::Router,+ method: &str,+ path: &str,+ body: Option<Value>,+) -> (StatusCode, Value) {+ let mut builder = Request::builder().method(method).uri(path);+ let body = match body {+ Some(v) => {+ builder = builder.header("content-type", "application/json");+ Body::from(v.to_string())+ }+ None => Body::empty(),+ };+ send(app, builder.body(body).expect("request")).await+}++/// An ES ILM policy whose only phase is an immediate delete — the fastest+/// route to the data-loss outcome every rail below exists to prevent.+fn wipe_policy() -> Value {+ json!({+ "policy": {+ "phases": {+ "delete": { "min_age": "0ms", "actions": { "delete": {} } }+ }+ }+ })+}++/// A native ISM policy whose default state deletes immediately.+fn kill_now_policy() -> Value {+ json!({+ "policy": {+ "default_state": "kill",+ "states": [+ { "name": "kill", "actions": [ { "delete": {} } ], "transitions": [] }+ ]+ }+ })+}++async fn ilm_managed(app: &axum::Router, index: &str) -> bool {+ let (status, body) = req_json(app, "GET", &format!("/{index}/_ilm/explain"), None).await;+ assert_eq!(status, StatusCode::OK, "explain failed: {body}");+ body["indices"][index]["managed"].as_bool().unwrap_or(false)+}++async fn index_exists(app: &axum::Router, index: &str) -> bool {+ let (status, _) = req_json(app, "GET", &format!("/{index}"), None).await;+ status == StatusCode::OK+}++// ─────────────────────────────────────────────────────────────────────────────+// Rail 1 — detach tombstone+// ─────────────────────────────────────────────────────────────────────────────++#[tokio::test]+async fn settings_null_detach_is_honoured_and_survives_restart() {+ let dir = tempfile::tempdir().expect("tempdir");+ let (app, state) = state_over(dir.path());++ let (status, _) = req_json(&app, "PUT", "/_ilm/policy/wipe-fast", Some(wipe_policy())).await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = req_json(+ &app,+ "PUT",+ "/detach-idx",+ Some(json!({ "settings": { "index.lifecycle.name": "wipe-fast" } })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert!(ilm_managed(&app, "detach-idx").await, "attach sanity check");++ // The operator detaches. ES's documented way to stop managing an index.+ let (status, body) = req_json(+ &app,+ "PUT",+ "/detach-idx/_settings",+ Some(json!({ "index.lifecycle.name": null })),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "detach refused: {body}");++ // The acknowledgement must be authoritative: the index is no longer+ // managed, and a lifecycle pass must not touch it.+ assert!(+ !ilm_managed(&app, "detach-idx").await,+ "index still managed after an acknowledged `index.lifecycle.name: null`"+ );+ xerj_engine::lifecycle::tick(&state.engine).await;+ assert!(+ index_exists(&app, "detach-idx").await,+ "lifecycle tick deleted an index the operator had detached"+ );++ // …and it must survive a restart: nothing is handed over in memory.+ drop(app);+ drop(state);+ let (app, state) = state_over(dir.path());+ assert!(+ !ilm_managed(&app, "detach-idx").await,+ "detach forgotten across restart"+ );+ xerj_engine::lifecycle::tick(&state.engine).await;+ assert!(+ index_exists(&app, "detach-idx").await,+ "restart re-attached a detached index and the delete phase fired"+ );+}++// ─────────────────────────────────────────────────────────────────────────────+// Rail 2 — fail-closed action allowlist+// ─────────────────────────────────────────────────────────────────────────────++#[tokio::test]+async fn unexecutable_ilm_actions_are_refused_at_put_not_skipped() {+ let dir = tempfile::tempdir().expect("tempdir");+ let (app, _state) = state_over(dir.path());++ let (status, body) = req_json(+ &app,+ "PUT",+ "/_ilm/policy/needs-forcemerge",+ Some(json!({+ "policy": {+ "phases": {+ "hot": {+ "actions": {+ "rollover": { "max_docs": 1 },+ "forcemerge": { "max_num_segments": 1 }+ }+ }+ }+ }+ })),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "a policy with an action this engine cannot honour must be refused, got: {body}"+ );+ assert!(+ body.to_string().contains("forcemerge"),+ "refusal must name the action: {body}"+ );++ // Fail-closed means nothing was stored either.+ let (status, _) = req_json(&app, "GET", "/_ilm/policy/needs-forcemerge", None).await;+ assert_eq!(+ status,+ StatusCode::NOT_FOUND,+ "refused policy must not be stored"+ );+}++// ─────────────────────────────────────────────────────────────────────────────+// Rail 3 — delete rails+// ─────────────────────────────────────────────────────────────────────────────++#[tokio::test]+async fn delete_action_never_removes_a_dot_prefixed_internal_index() {+ let dir = tempfile::tempdir().expect("tempdir");+ let (app, state) = state_over(dir.path());++ state+ .engine+ .create_index(".ledger", xerj_common::Schema::empty())+ .expect("create dot index");+ let (status, _) = req_json(+ &app,+ "PUT",+ "/_plugins/_ism/policies/kill-now",+ Some(kill_now_policy()),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = req_json(+ &app,+ "POST",+ "/_plugins/_ism/add/.ledger",+ Some(json!({ "policy_id": "kill-now" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ xerj_engine::lifecycle::tick(&state.engine).await;++ assert!(+ state.engine.get_index(".ledger").is_ok(),+ "lifecycle delete action removed a dot-prefixed internal index"+ );+ // The refusal is visible, not silent: the cursor reports failure.+ let managed = state+ .engine+ .managed_indices+ .get(".ledger")+ .expect("still managed");+ assert!(+ managed.failed,+ "refusing a delete must surface in explain, got: {}",+ managed.info_message+ );+}++#[tokio::test]+async fn delete_action_never_removes_a_data_streams_write_index() {+ let dir = tempfile::tempdir().expect("tempdir");+ let (app, state) = state_over(dir.path());++ let (status, _) = req_json(&app, "PUT", "/_data_stream/logs-ds", None).await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = req_json(+ &app,+ "PUT",+ "/_plugins/_ism/policies/kill-now",+ Some(kill_now_policy()),+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ // Attach to the stream's one (and therefore write) backing index.+ let (status, _) = req_json(+ &app,+ "POST",+ "/_plugins/_ism/add/.ds-logs-ds-000001",+ Some(json!({ "policy_id": "kill-now" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ xerj_engine::lifecycle::tick(&state.engine).await;++ assert!(+ state.engine.get_index(".ds-logs-ds-000001").is_ok(),+ "lifecycle delete action removed the current write index of a data stream"+ );++ // After a rollover the old generation is no longer the write index and+ // the rail must step aside — retention on rolled-over generations is+ // the entire point of ILM on a data stream.+ let (status, _) = req_json(&app, "POST", "/logs-ds/_rollover", None).await;+ assert_eq!(status, StatusCode::OK);+ xerj_engine::lifecycle::tick(&state.engine).await;+ assert!(+ state.engine.get_index(".ds-logs-ds-000001").is_err(),+ "rolled-over backing index should now be deletable by the policy"+ );+ assert!(+ state.engine.get_index(".ds-logs-ds-000002").is_ok(),+ "the new write index must survive"+ );+}++#[tokio::test]+async fn delete_action_refuses_an_index_whose_age_cannot_be_established() {+ let dir = tempfile::tempdir().expect("tempdir");+ let (app, state) = state_over(dir.path());++ let (status, _) = req_json(&app, "PUT", "/age-unknown-idx", Some(json!({}))).await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = req_json(+ &app,+ "PUT",+ "/_plugins/_ism/policies/kill-now",+ Some(kill_now_policy()),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = req_json(+ &app,+ "POST",+ "/_plugins/_ism/add/age-unknown-idx",+ Some(json!({ "policy_id": "kill-now" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ // Simulate a cursor whose state-entry time was lost (hand-edited or+ // corrupt `ism_managed_indices.json`): age is unestablishable.+ state+ .engine+ .managed_indices+ .get_mut("age-unknown-idx")+ .expect("managed")+ .state_entered_at_ms = 0;++ xerj_engine::lifecycle::tick(&state.engine).await;++ assert!(+ state.engine.get_index("age-unknown-idx").is_ok(),+ "lifecycle delete action removed an index whose age cannot be established"+ );+}++// ─────────────────────────────────────────────────────────────────────────────+// Rail 4 — operator surface: status / start / stop / remove+// ─────────────────────────────────────────────────────────────────────────────++#[tokio::test]+async fn ilm_stop_halts_execution_and_start_resumes_it() {+ let dir = tempfile::tempdir().expect("tempdir");+ let (app, state) = state_over(dir.path());++ let (status, body) = req_json(&app, "GET", "/_ilm/status", None).await;+ assert_eq!(status, StatusCode::OK, "GET _ilm/status missing: {body}");+ assert_eq!(body["operation_mode"], "RUNNING");++ let (status, _) = req_json(&app, "PUT", "/stop-guard-idx", Some(json!({}))).await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = req_json(+ &app,+ "PUT",+ "/_plugins/_ism/policies/kill-now",+ Some(kill_now_policy()),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = req_json(+ &app,+ "POST",+ "/_plugins/_ism/add/stop-guard-idx",+ Some(json!({ "policy_id": "kill-now" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ let (status, body) = req_json(&app, "POST", "/_ilm/stop", None).await;+ assert_eq!(status, StatusCode::OK, "POST _ilm/stop missing: {body}");+ let (_, body) = req_json(&app, "GET", "/_ilm/status", None).await;+ assert_eq!(body["operation_mode"], "STOPPED");++ xerj_engine::lifecycle::tick(&state.engine).await;+ assert!(+ state.engine.get_index("stop-guard-idx").is_ok(),+ "a tick acted while lifecycle execution was stopped"+ );++ let (status, _) = req_json(&app, "POST", "/_ilm/start", None).await;+ assert_eq!(status, StatusCode::OK);+ xerj_engine::lifecycle::tick(&state.engine).await;+ assert!(+ state.engine.get_index("stop-guard-idx").is_err(),+ "tick did not resume after POST _ilm/start"+ );+}++#[tokio::test]+async fn index_ilm_remove_detaches_and_404s_on_a_ghost() {+ let dir = tempfile::tempdir().expect("tempdir");+ let (app, state) = state_over(dir.path());++ let (status, _) = req_json(&app, "PUT", "/remove-me", Some(json!({}))).await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = req_json(+ &app,+ "PUT",+ "/_plugins/_ism/policies/kill-now",+ Some(kill_now_policy()),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = req_json(+ &app,+ "POST",+ "/_plugins/_ism/add/remove-me",+ Some(json!({ "policy_id": "kill-now" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ let (status, body) = req_json(&app, "POST", "/remove-me/_ilm/remove", None).await;+ assert_eq!(+ status,+ StatusCode::OK,+ "POST /{{index}}/_ilm/remove missing: {body}"+ );+ assert_eq!(body["has_failures"], false, "body: {body}");+ assert!(!ilm_managed(&app, "remove-me").await);++ xerj_engine::lifecycle::tick(&state.engine).await;+ assert!(+ state.engine.get_index("remove-me").is_ok(),+ "tick deleted an index after _ilm/remove detached it"+ );++ // A name that is not an index at all is a 404, not a silent success.+ let (status, _) = req_json(&app, "POST", "/ghost-idx/_ilm/remove", None).await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex b66cb4a66..08b645e04 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -508,6 +508,23 @@ pub struct Engine {/// action, timestamps). Presence in this map is what "managed" means —/// an index with no entry here is not touched by the background job.pub managed_indices: Arc<DashMap<String, crate::lifecycle::ManagedIndexState>>,+ /// Persisted detach tombstones (issue #282, ported from #262): an index+ /// name lands here when an operator explicitly detached it — `PUT+ /// /{index}/_settings {"index.lifecycle.name": null}`, `POST+ /// /{index}/_ilm/remove`, or `POST /_plugins/_ism/remove/{index}`. An+ /// acknowledged detach must be authoritative across restarts: mere+ /// *absence* from `managed_indices` cannot distinguish "never managed"+ /// from "operator said stop", and any future code path that re-derives+ /// attachments (e.g. from persisted index settings, which may still+ /// carry a stale `index.lifecycle.name`) MUST consult this set first.+ /// Cleared by an explicit re-attach or by deleting the index. Persisted+ /// in `ism_managed_indices.json` alongside the cursors.+ pub lifecycle_detached: Arc<DashMap<String, ()>>,+ /// Operator kill switch for lifecycle execution (`POST /_ilm/stop` /+ /// `/_ilm/start`): while false, `lifecycle::tick` returns without+ /// acting. In-memory only, matching #262's rc — a restart resumes+ /// execution, which errs on the side of retention running.+ pub lifecycle_running: Arc<std::sync::atomic::AtomicBool>,/// index name → creation time (epoch ms), for `min_index_age` and for/// `GET /{index}`'s `creation_date` (previously synthesized as/// `Utc::now()` on every request — see `record_index_created_at`).@@ -732,6 +749,8 @@ impl Engine {ilm_policies: Arc::new(DashMap::new()),ism_policies: Arc::new(DashMap::new()),managed_indices: Arc::new(DashMap::new()),+ lifecycle_detached: Arc::new(DashMap::new()),+ lifecycle_running: Arc::new(std::sync::atomic::AtomicBool::new(true)),index_created_at: Arc::new(DashMap::new()),component_templates: Arc::new(DashMap::new()),snapshot_repos: Arc::new(DashMap::new()),@@ -1690,15 +1709,28 @@ impl Engine {}}- /// Persist the whole `managed_indices` map. Called by `lifecycle::tick`- /// after any change, and by the attach/detach handlers.+ /// Persist the whole `managed_indices` map plus the detach tombstones+ /// (issue #282). Called by `lifecycle::tick` after any change, and by+ /// the attach/detach handlers.+ ///+ /// On-disk shape is an envelope — `{"managed": {...}, "detached":+ /// [...]}` — so the acknowledged detaches survive a restart alongside+ /// the cursors. `load_persisted_managed_indices` still accepts the+ /// pre-#282 bare-map form.pub fn persist_managed_indices(&self) {- let snapshot: std::collections::HashMap<String, crate::lifecycle::ManagedIndexState> = self+ let managed: std::collections::HashMap<String, crate::lifecycle::ManagedIndexState> = self.managed_indices.iter().map(|e| (e.key().clone(), e.value().clone())).collect();- let bytes = match serde_json::to_vec_pretty(&snapshot) {+ let mut detached: Vec<String> = self+ .lifecycle_detached+ .iter()+ .map(|e| e.key().clone())+ .collect();+ detached.sort();+ let envelope = serde_json::json!({ "managed": managed, "detached": detached });+ let bytes = match serde_json::to_vec_pretty(&envelope) {Ok(b) => b,Err(e) => {warn!(error = %e, "failed to serialize managed_indices for persistence");@@ -1714,21 +1746,88 @@ impl Engine {let Ok(bytes) = std::fs::read(self.managed_indices_path()) else {return;};- match serde_json::from_slice::<- std::collections::HashMap<String, crate::lifecycle::ManagedIndexState>,- >(&bytes)- {- Ok(map) => {- let n = map.len();- for (index_name, state) in map {- self.managed_indices.insert(index_name, state);- }- if n > 0 {- info!(count = n, "restored persisted ISM managed-index state");+ // `deny_unknown_fields` is what keeps the two on-disk shapes+ // unambiguous: without it, a pre-#282 bare-map file (index names as+ // top-level keys) would "successfully" parse as an envelope with+ // every cursor silently ignored as an unknown field — the exact+ // accepted-and-ignored class this issue removes.+ #[derive(serde::Deserialize)]+ #[serde(deny_unknown_fields)]+ struct Envelope {+ #[serde(default)]+ managed: std::collections::HashMap<String, crate::lifecycle::ManagedIndexState>,+ #[serde(default)]+ detached: Vec<String>,+ }+ let (map, detached) = match serde_json::from_slice::<Envelope>(&bytes) {+ Ok(env) => (env.managed, env.detached),+ Err(_) => match serde_json::from_slice::<+ std::collections::HashMap<String, crate::lifecycle::ManagedIndexState>,+ >(&bytes)+ {+ Ok(map) => (map, Vec::new()),+ Err(e) => {+ warn!(error = %e, "ignoring corrupt ism_managed_indices.json");+ return;}+ },+ };+ let n = map.len();+ for (index_name, state) in map {+ self.managed_indices.insert(index_name, state);+ }+ for index_name in detached {+ self.lifecycle_detached.insert(index_name, ());+ }+ if n > 0 {+ info!(count = n, "restored persisted ISM managed-index state");+ }+ }++ /// Detach `index` from lifecycle management and record a persisted+ /// tombstone for it (issue #282). This is THE detach path — `PUT+ /// /{index}/_settings {"index.lifecycle.name": null}`, `POST+ /// /{index}/_ilm/remove` and `POST /_plugins/_ism/remove/{index}` all+ /// land here, so a detach is recorded once and the executor cannot+ /// disagree with the operator about which route it honoured (#262's+ /// `set_index_lifecycle_policy` made the same call).+ ///+ /// Also scrubs `index.lifecycle.name` from the stored display settings:+ /// ES drops the setting on removal rather than reporting a name that is+ /// no longer in force, and a stale name here is exactly the input a+ /// future settings-derived re-attach would trip over.+ ///+ /// Returns whether the index was managed before the call.+ pub fn detach_lifecycle(&self, index: &str) -> bool {+ let was_managed = self.managed_indices.remove(index).is_some();+ self.lifecycle_detached.insert(index.to_string(), ());+ if let Some(mut stored) = self.index_settings.get_mut(index) {+ let v = stored.value_mut();+ if let Some(obj) = v.as_object_mut() {+ obj.remove("index.lifecycle.name");+ }+ if let Some(lifecycle) = v+ .pointer_mut("/index/lifecycle")+ .and_then(Value::as_object_mut)+ {+ lifecycle.remove("name");}- Err(e) => warn!(error = %e, "ignoring corrupt ism_managed_indices.json"),}+ self.persist_managed_indices();+ was_managed+ }++ /// Whether `lifecycle::tick` is allowed to act — the `POST /_ilm/stop`+ /// kill switch (issue #282).+ pub fn lifecycle_execution_running(&self) -> bool {+ self.lifecycle_running+ .load(std::sync::atomic::Ordering::Relaxed)+ }++ /// `POST /_ilm/start` / `POST /_ilm/stop`.+ pub fn set_lifecycle_execution_running(&self, running: bool) {+ self.lifecycle_running+ .store(running, std::sync::atomic::Ordering::Relaxed);}/// Spawn the background lifecycle-execution job: every@@ -2498,6 +2597,16 @@ impl Engine {self.index_settings.remove(name);self.index_mappings.remove(name);self.index_alias_metadata.remove(name);++ // Lifecycle bookkeeping: a deleted index needs neither an execution+ // cursor nor a detach tombstone (#282) — and clearing the tombstone+ // here means a *recreated* index with the same name starts fresh+ // rather than inheriting a years-old "operator said stop".+ let had_lifecycle_state = self.managed_indices.remove(name).is_some()+ | self.lifecycle_detached.remove(name).is_some();+ if had_lifecycle_state {+ self.persist_managed_indices();+ }}/// Remove `<data_dir>/<name>` from disk, refusing anything that does not@@ -2925,6 +3034,25 @@ impl Engine {Ok(())}+ /// Drop a deleted backing index from its data stream's generation list+ /// so the stream does not keep advertising an index that no longer+ /// exists (#282, ported from #262's `detach_data_stream_backing_index`)+ /// — and persist the shrunken list, or a restart would reload the+ /// deleted generation from `cluster_state.json` as an orphan.+ pub(crate) fn detach_data_stream_backing_index(&self, index: &str) {+ let mut changed = false;+ for mut entry in self.data_streams.iter_mut() {+ let before = entry.backing_indices.len();+ entry.backing_indices.retain(|b| b != index);+ changed |= entry.backing_indices.len() != before;+ }+ if changed {+ if let Err(e) = self.flush_cluster_state() {+ warn!(error = %e, "failed to persist data-stream state after lifecycle delete");+ }+ }+ }+/// Roll over a data stream: create the next backing index and update the alias.pub fn rollover_data_stream(&self, name: &str) -> Result<String> {// Same reason as `create_data_stream`, plus: the generation counter isdiff --git a/engine/crates/xerj-engine/src/lifecycle.rs b/engine/crates/xerj-engine/src/lifecycle.rsindex d1a75de31..163aa013b 100644--- a/engine/crates/xerj-engine/src/lifecycle.rs+++ b/engine/crates/xerj-engine/src/lifecycle.rs@@ -355,20 +355,20 @@ fn translate_ilm_phase_actions(}"delete" => LifecycleAction::Delete(EmptyParams {}),"readonly" => LifecycleAction::ReadOnly(EmptyParams {}),- "set_priority" | "allocate" | "unfollow" | "shrink" | "forcemerge" | "freeze" => {- // Real ILM actions with no XERJ equivalent (no shard- // allocation awareness, no shrink/forcemerge-as-a-lifecycle-- // step wiring, no CCR). Skipped rather than erroring the- // whole policy translation — matches this engine's existing- // "explicit error only where behavior would be silently- // wrong" policy: skipping a no-op-shaped action is honest- // (nothing was promised and not delivered), unlike- // replica_count which IS user-visible if silently ignored.- continue;- }+ // Fail-closed allowlist (issue #282, ported from #262's+ // `validate_policy`): an action this engine cannot execute is+ // refused with its name, never silently dropped. This used to+ // skip `set_priority`/`allocate`/`unfollow`/`shrink`/+ // `forcemerge`/`freeze` on the argument that a no-op-shaped+ // action is harmless — but a policy is a contract, and+ // accepting one while quietly not honouring part of it is this+ // repo's dominant bug class (#204). The operator can remove the+ // action from the policy; they cannot remove a silent skip.other => {return Err(format!(- "phase '{phase_name}' action '{other}' has no ISM/XERJ equivalent"+ "phase '{phase_name}' action '{other}' is not executable by this engine \+ (executable ILM actions: rollover, delete, readonly) — refusing the \+ policy rather than accepting it and skipping the action"))}};@@ -451,11 +451,60 @@ pub enum ActionOutcome {IndexDeleted,}+/// Why the delete action must not fire on `index`, if it must not — the+/// delete rails (issue #282, ported from #262's `ilm_delete_block_reason`).+///+/// One function, one answer: the executor's refusal and the operator-visible+/// failure message can never disagree about what happened.+///+/// * Dot-prefixed names are XERJ/Kibana internals (`.xerj-memory-*`+/// brains, `.kibana*`, security stores). A wildcard settings update or a+/// copy-pasted attach must not be able to point a 7-day retention policy+/// at a user's second brain. Data-stream backing indices (`.ds-*`) are+/// the one dotted family lifecycle deletion is *for*, so they are exempt+/// from this rail (and covered by the next one while current).+/// * A data stream's current write index is where new documents are+/// landing right now; ES's own delete phase refuses it too.+/// * An index whose age cannot be established must be skipped, never+/// deleted on a guess (quickwit's janitor makes the same call for+/// undatable splits — `retention_policy_execution.rs:65-76`, Apache-2.0,+/// approach adapted). In this engine's cursor model the age clock is+/// `state_entered_at_ms`; a cursor whose entry time is missing (0, from+/// a hand-edited or partially-corrupt state file) or in the future+/// (clock skew) establishes nothing.+fn delete_block_reason(engine: &Engine, index: &str, state_entered_at_ms: i64) -> Option<String> {+ if index.starts_with('.') && !index.starts_with(".ds-") {+ return Some(+ "dot-prefixed internal index — the lifecycle delete action never removes one"+ .to_string(),+ );+ }+ let write_index_owner =+ engine+ .data_streams+ .iter()+ .find_map(|e| match e.value().backing_indices.last() {+ Some(write_index) if write_index == index => Some(e.key().clone()),+ _ => None,+ });+ if let Some(stream) = write_index_owner {+ return Some(format!("current write index of data stream '{stream}'"));+ }+ if state_entered_at_ms <= 0 || now_ms() < state_entered_at_ms {+ return Some(+ "index age cannot be established (state-entry time is missing or in the future)"+ .to_string(),+ );+ }+ None+}+async fn execute_action(engine: &Engine,index_name: &str,action: &LifecycleAction,state_age_ms: i64,+ state_entered_at_ms: i64,) -> Result<ActionOutcome> {match action {LifecycleAction::Rollover(rollover) => {@@ -483,8 +532,16 @@ async fn execute_action(Ok(ActionOutcome::Done)}LifecycleAction::Delete(_) => {+ if let Some(reason) = delete_block_reason(engine, index_name, state_entered_at_ms) {+ // An Err here surfaces as `failed: true` + this message in+ // explain — visible refusal, not a silent skip (#204).+ return Err(EngineError::Common(xerj_common::XerjError::invalid_query(+ format!("refusing lifecycle delete of '{index_name}': {reason}"),+ )));+ }engine.delete_index(index_name).await?;engine.managed_indices.remove(index_name);+ engine.detach_data_stream_backing_index(index_name);Ok(ActionOutcome::IndexDeleted)}LifecycleAction::ReadOnly(_) => {@@ -513,6 +570,11 @@ async fn execute_action(/// actions have completed — evaluate its transitions in order and move to/// the first one whose conditions are met.pub async fn tick(engine: &Engine) {+ // Operator kill switch (`POST /_ilm/stop`, issue #282): while stopped,+ // a tick observes nothing and touches nothing.+ if !engine.lifecycle_execution_running() {+ return;+ }let snapshot: Vec<(String, ManagedIndexState)> = engine.managed_indices.iter()@@ -551,7 +613,15 @@ pub async fn tick(engine: &Engine) {if managed.next_action_index < state_def.actions.len() {let action = &state_def.actions[managed.next_action_index];- match execute_action(engine, &index_name, action, state_age_ms).await {+ match execute_action(+ engine,+ &index_name,+ action,+ state_age_ms,+ managed.state_entered_at_ms,+ )+ .await+ {Ok(ActionOutcome::Done) => {managed.next_action_index += 1;managed.failed = false;@@ -827,7 +897,11 @@ mod tests {}#[test]- fn translate_ilm_skips_unmapped_actions_errors_on_unknown() {+ fn translate_ilm_refuses_unexecutable_actions_naming_them() {+ // Issue #282: `set_priority` (and friends) used to be silently+ // skipped; the fail-closed allowlist refuses them with the action+ // named so the operator learns at PUT time, not from a policy that+ // quietly does less than it says.let ilm = json!({"policy": {"phases": {@@ -837,12 +911,16 @@ mod tests {}}});- let policy = translate_ilm_policy(&ilm).unwrap();- assert!(policy.states[0].actions.is_empty());+ let err = translate_ilm_policy(&ilm).unwrap_err();+ assert!(err.contains("set_priority"), "must name the action: {err}");let ilm_bad = json!({"policy": { "phases": { "hot": { "actions": { "totally_made_up": {} } } } }});- assert!(translate_ilm_policy(&ilm_bad).is_err());+ let err = translate_ilm_policy(&ilm_bad).unwrap_err();+ assert!(+ err.contains("totally_made_up"),+ "must name the action: {err}"+ );}}