Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(api): honour wait_for_status, report a failed index as existing, keep a failed delete addressable

xerj-orgef160f746c1c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 970f2f6ad..930cd5dd8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,9 +21,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the verbatim open error, enumerated with its reason by
`GET /_cluster/indices/failed`, reopenable via
`POST /_cluster/indices/failed/{name}/_retry` once the cause is fixed, and
- deletable through the ordinary `DELETE /{index}`. Reads, writes and creates
- against it return `503 no_shard_available_action_exception` carrying the
- reason instead of a `404` that claimed it did not exist.
+ deletable through the ordinary `DELETE /{index}`. Searches, writes and
+ creates against it return `503 no_shard_available_action_exception` carrying
+ the reason instead of a `404` that claimed it did not exist, while the
+ metadata surfaces — `GET /{index}`, `HEAD /{index}` (the `indices.exists()`
+ every ES client calls), `_mapping`, `_settings`, `_cat/indices` — report it
+ as an index that exists, the way ES answers those from cluster metadata
+ rather than from a shard. Before this, `HEAD` said the name was free and the
+ following `PUT` said it was unavailable.
Two related defects in the same report are fixed with it. **Readiness no
longer hard-fails on a partly degraded node** — `/health/ready` returned
@@ -36,6 +41,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
now count an unopenable index as an unassigned primary, agreeing with
`/v1/health` and `/v1/cluster/health`.
+ Because `red` is now reachable on `_cluster/health` for the first time, the
+ two conditions that gate on it are consulted rather than assumed:
+ `wait_for_active_shards=all` and `wait_for_status=green|yellow` both answer
+ `408` with `timed_out: true` on a red node instead of `200 timed_out: false`.
+ `GET /_cluster/health?wait_for_status=green&timeout=30s` is the bootstrap gate
+ every docker healthcheck, CI wait loop and Kibana startup uses; a red node
+ used to sail straight through it. A green or yellow cluster is unaffected.
+
+- **A `DELETE /{index}` that could not remove the bytes no longer strands the
+ index.** The open-index path pulled the handle out of the engine before
+ `remove_dir_all`, so a removal that failed (read-only mount, `EACCES`) freed
+ the name while the directory survived: no handle, no failed-index entry,
+ nothing on `_cat/indices`, and the next `DELETE` answered `404` — the same
+ dead end as [#206](https://github.com/xerj-org/xerj/issues/206), reached from
+ the other side. The handle is now restored on failure, so the index stays in
+ service and addressable and the operator can retry the delete once the cause
+ is fixed.
+
- **`autoindex` no longer leaves immortal catalog entries for skipped files**
([#238](https://github.com/xerj-org/xerj/issues/238)). A file added after the
resume plan was frozen is skipped and reported in the catalog — but that
diff --git a/docs/recipes/production-deployment.md b/docs/recipes/production-deployment.md
index a13182e58..6db51553c 100644
--- a/docs/recipes/production-deployment.md
+++ b/docs/recipes/production-deployment.md
@@ -228,12 +228,26 @@ curl -s -XDELETE localhost:9200/broken
```
A retry that does not work returns `503` with the *current* reason, not the
-one recorded at boot. While an index is in this state, reads and writes to it
-return `503 no_shard_available_action_exception` naming the open error —
+one recorded at boot. While an index is in this state, searches and writes to
+it return `503 no_shard_available_action_exception` naming the open error —
**not** `404 index_not_found`, which would be a lie: the name is taken and the
data is still on disk. Creating an index over that name is refused for the
same reason.
+Existence is answered separately from data, the way ES answers it: `GET
+/broken`, `HEAD /broken` (the `indices.exists()` your client library calls),
+`GET /broken/_mapping` and `GET /broken/_settings` all return `200` and report
+the index as existing, because those read metadata and never touch a shard. So
+a client that probes before writing gets one consistent answer — the name is
+taken — instead of a `404` from `HEAD` followed by a `503` from the `PUT`.
+
+Watch for the failure on the health surfaces, not the existence probes:
+`_cat/health` and `_cluster/health` both report `red` with
+`unassigned_primary_shards: 1`, and the two conditions that gate on it are
+honoured — `wait_for_status=green` and `wait_for_active_shards=all` answer
+`408` with `"timed_out": true` rather than reporting success on a red node, so
+a startup gate written against real ES behaves the same here.
+
### gRPC posture
The gRPC `XerjSearch` service (default `:8081`) always speaks **plaintext
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index dc1fc533d..5c5dd494a 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -151,10 +151,15 @@ pub struct ClusterHealthParams {
/// `cluster` (default), `indices`, `shards`.
#[serde(default)]
pub level: Option<String>,
- /// Passthroughs — accepted for compatibility and surfaced as `timed_out`
- /// only if we actually time out (we don't — local single-node).
+ /// The status the caller is waiting for (`green` / `yellow` / `red`).
+ /// Consulted: on a **red** cluster a request for `green` or `yellow` is
+ /// unmet and the response carries `timed_out: true` / 408. See
+ /// `wait_for_status_unmet` in `cluster_health_inner` for why the check is
+ /// deliberately narrowed to the red case.
#[serde(default)]
pub wait_for_status: Option<String>,
+ /// Passthroughs — accepted for compatibility and surfaced as `timed_out`
+ /// only if we actually time out (we don't — local single-node).
#[serde(default)]
pub wait_for_no_relocating_shards: Option<String>,
#[serde(default)]
@@ -429,6 +434,39 @@ async fn cluster_health_inner(
.unwrap_or(false),
None => false,
};
+ // `wait_for_status` was accepted and never consulted. That was harmless
+ // while `red` was unreachable on this endpoint; it stopped being harmless
+ // the moment an unopenable primary made it reachable (issue #206), because
+ // `GET /_cluster/health?wait_for_status=green&timeout=30s` is the standard
+ // bootstrap gate — every docker healthcheck, CI wait loop and Kibana
+ // startup reads a 200 with `timed_out: false` as "the status I asked for
+ // was reached", and a red node would have sailed through it.
+ //
+ // ES treats the condition as met iff the observed status is at least as
+ // good as the requested one (`response.getStatus().value() <=
+ // request.waitForStatus().value()`, GREEN=0 / YELLOW=1 / RED=2 —
+ // elasticsearch/server/src/main/java/org/elasticsearch/action/admin/cluster/health/
+ // TransportClusterHealthAction.java:398; approach only, ES is AGPL/SSPL/
+ // Elastic-2.0 and nothing is copied from it). Unmet after the timeout sets
+ // `timed_out`, which this handler already maps to 408.
+ //
+ // Deliberately narrowed to the red case: our single-node simulation
+ // reports `yellow` for any index configured with replicas, and the
+ // ES-YAML suite asks `wait_for_status=green` of exactly those. Applying
+ // the full `observed <= requested` comparison would start timing those out
+ // on a cluster that is behaving as designed, so a green or yellow cluster
+ // is byte-identical to before this change. The residual gap
+ // (`wait_for_status=green` still answered permissively on a yellow
+ // single-node cluster) is pre-existing and unrelated to #206.
+ let wait_for_status_unmet = status == "red"
+ && matches!(
+ params
+ .wait_for_status
+ .as_deref()
+ .map(|s| s.trim().to_ascii_lowercase())
+ .as_deref(),
+ Some("green") | Some("yellow")
+ );
// When the caller explicitly requests `wait_for_nodes>=N`, we
// satisfy it by reporting `N` as the declared cluster size so
// the multinode smoke suite converges. But if the caller also
@@ -456,7 +494,9 @@ async fn cluster_health_inner(
.map(|_| wait_for_nodes)
.unwrap_or(1)
};
- let timed_out = wait_for_active_shards_unmet || (aggressive_timeout && wait_for_nodes > 1);
+ let timed_out = wait_for_active_shards_unmet
+ || wait_for_status_unmet
+ || (aggressive_timeout && wait_for_nodes > 1);
let mut resp = json!({
"cluster_name": "xerj",
@@ -1609,23 +1649,44 @@ async fn get_index_inner(
.any(|w| w == "open" || w == "all");
let all = state.engine.list_indices().await;
+ // An index whose directory refused to open still EXISTS — this endpoint
+ // is the metadata read, not a shard read. ES resolves it out of cluster
+ // metadata and never consults a shard
+ // (elasticsearch/server/src/main/java/org/elasticsearch/action/admin/
+ // indices/get/TransportGetIndexAction.java:107 `localClusterStateOperation`
+ // → :113 `concreteIndexNames(state.metadata(), request)` then
+ // `project.findMappings/findAllAliases/settings`; approach only, nothing
+ // copied — ES is AGPL/SSPL/Elastic-2.0), so a red index answers 200 with
+ // its metadata there. Answering 404 `index_not_found` here was the same
+ // lie issue #206 is about, and it contradicted every other surface in the
+ // same run: `_cat/indices` printed a red row for the name while
+ // `GET /{name}` said it did not exist.
+ //
+ // `list_failed_indices` is visibility-filtered, so a failed brain a scoped
+ // key may not read stays invisible to it here too.
+ let failed_names: Vec<String> = state
+ .engine
+ .list_failed_indices()
+ .into_iter()
+ .map(|f| f.name)
+ .collect();
// Resolve the selector into concrete names.
let mut selected: Vec<String> = Vec::new();
let mut had_missing = false;
for part in index.split(',').map(str::trim).filter(|s| !s.is_empty()) {
if part == "_all" || part == "*" {
- for info in &all {
- if !selected.contains(&info.name) {
- selected.push(info.name.clone());
+ for name in all.iter().map(|i| &i.name).chain(failed_names.iter()) {
+ if !selected.contains(name) {
+ selected.push(name.clone());
}
}
continue;
}
if part.contains('*') {
- for info in &all {
- if glob_match_simple(part, &info.name) && !selected.contains(&info.name) {
- selected.push(info.name.clone());
+ for name in all.iter().map(|i| &i.name).chain(failed_names.iter()) {
+ if glob_match_simple(part, name) && !selected.contains(name) {
+ selected.push(name.clone());
}
}
continue;
@@ -1640,7 +1701,8 @@ async fn get_index_inner(
selected.push(n.clone());
}
}
- } else if all.iter().any(|info| info.name == part) {
+ } else if all.iter().any(|info| info.name == part) || failed_names.iter().any(|n| n == part)
+ {
if !selected.contains(&part.to_string()) {
selected.push(part.to_string());
}
@@ -1691,8 +1753,13 @@ async fn get_index_inner(
let mut body = serde_json::Map::new();
for name in &selected {
+ // `None` = the name exists but has no open handle (a failed index).
+ // Its metadata is still served — the schema-derived mapping fallback
+ // is the only part that needs a live index, and a failed index falls
+ // back to the mapping blob persisted next to its data instead.
let idx = match state.engine.get_index(name) {
- Ok(i) => i,
+ Ok(i) => Some(i),
+ Err(_) if failed_names.iter().any(|n| n == name) => None,
Err(_) => continue,
};
@@ -1714,13 +1781,17 @@ async fn get_index_inner(
// Mappings: prefer the raw blob written at create; fall back to the
// schema-derived properties (which tracks subsequent put_mapping).
let stored_mappings = state.engine.index_mappings.get(name).map(|v| v.clone());
- let mappings = match stored_mappings {
- Some(m) if !m.is_null() => m,
- _ => {
- let schema = idx.schema().await;
+ let mappings = match (stored_mappings, &idx) {
+ (Some(m), _) if !m.is_null() => m,
+ (_, Some(i)) => {
+ let schema = i.schema().await;
let properties = schema_to_es_properties(&schema);
json!({ "properties": properties })
}
+ // Failed index with no persisted mapping blob: report an empty
+ // mapping rather than inventing one. Nothing is known about its
+ // fields until it opens.
+ (_, None) => json!({ "properties": {} }),
};
// Settings: replay what was written (normalized to strings), merged
@@ -2229,8 +2300,21 @@ pub async fn get_mapping(
}
let mut out = serde_json::Map::new();
for name in &targets {
+ // `None` = a failed index (issue #206): no open handle, but its
+ // persisted mapping blob is still readable and is exactly what an
+ // operator needs while recovering it. Only the schema-derived
+ // fallback below requires a live index.
let idx = match state.engine.get_index(name) {
- Ok(i) => i,
+ Ok(i) => Some(i),
+ Err(_)
+ if state
+ .engine
+ .list_failed_indices()
+ .iter()
+ .any(|f| &f.name == name) =>
+ {
+ None
+ }
Err(_) => continue,
};
let stored = state
@@ -2240,9 +2324,14 @@ pub async fn get_mapping(
.map(|v| v.clone())
.unwrap_or(Value::Null);
let mut mappings = if stored.is_null() {
- let schema = idx.schema().await;
- let properties = schema_to_es_properties(&schema);
- json!({ "properties": properties })
+ match &idx {
+ Some(i) => {
+ let schema = i.schema().await;
+ let properties = schema_to_es_properties(&schema);
+ json!({ "properties": properties })
+ }
+ None => json!({ "properties": {} }),
+ }
} else {
stored
};
@@ -23144,10 +23233,26 @@ pub async fn head_index(
State(state): State<AppState>,
Path(index): Path<String>,
) -> impl IntoResponse {
- match state.engine.get_index(&index) {
- Ok(_) => StatusCode::OK.into_response(),
- Err(_) => StatusCode::NOT_FOUND.into_response(),
+ if state.engine.get_index(&index).is_ok() {
+ return StatusCode::OK.into_response();
+ }
+ // This is the existence probe every ES client's `indices.exists()` calls,
+ // and existence is a metadata question. An index whose directory refused
+ // to open still occupies its name and still has bytes on disk, so 404 here
+ // was the same lie `GET /{index}` told (issue #206) — and a client that
+ // did HEAD (404) then PUT (503 `no_shard_available_action_exception`) got
+ // two incompatible answers about one name. Visibility-filtered via
+ // `list_failed_indices`, so a scoped key cannot probe for another brain's
+ // failed index either.
+ if state
+ .engine
+ .list_failed_indices()
+ .iter()
+ .any(|f| f.name == index)
+ {
+ return StatusCode::OK.into_response();
}
+ StatusCode::NOT_FOUND.into_response()
}
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/engine/crates/xerj-api/tests/failed_index_is_visible_and_actionable.rs b/engine/crates/xerj-api/tests/failed_index_is_visible_and_actionable.rs
index bcbad450b..2deb596ca 100644
--- a/engine/crates/xerj-api/tests/failed_index_is_visible_and_actionable.rs
+++ b/engine/crates/xerj-api/tests/failed_index_is_visible_and_actionable.rs
@@ -157,6 +157,110 @@ async fn all_four_health_surfaces_agree_that_the_node_is_red() {
assert_eq!(waited["timed_out"], true, "{waited}");
}
+/// `wait_for_status` is the standard bootstrap gate — the docker healthcheck,
+/// the CI wait loop and Kibana's startup all issue
+/// `GET /_cluster/health?wait_for_status=green&timeout=30s` and read a 200 with
+/// `timed_out: false` as "the status I asked for was reached". It used to be
+/// accepted and never consulted, which was invisible while `red` was
+/// unreachable on this endpoint and actively wrong the moment an unopenable
+/// primary made it reachable: a red node sailed through every one of those
+/// gates.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn wait_for_status_does_not_report_success_on_a_red_node() {
+ let (state, _dir) = node_with_one_broken_index().await;
+ let es = build_es_compat_router(state);
+
+ for requested in ["green", "yellow", "GREEN"] {
+ let uri = format!("/_cluster/health?wait_for_status={requested}&timeout=30s");
+ let (status, body) = send_json(&es, "GET", &uri).await;
+ assert_eq!(
+ status,
+ StatusCode::REQUEST_TIMEOUT,
+ "wait_for_status={requested} on a red node: {body}"
+ );
+ assert_eq!(body["timed_out"], true, "{body}");
+ assert_eq!(body["status"], "red", "{body}");
+ }
+
+ // `wait_for_status=red` IS satisfied by a red cluster — ES's rule is
+ // "observed at least as good as requested", not "observed equals green".
+ let (status, body) = send_json(&es, "GET", "/_cluster/health?wait_for_status=red").await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(body["timed_out"], false, "{body}");
+
+ // …and a healthy node is untouched: no wait_for_status request on a green
+ // cluster may start timing out because of this.
+ let dir = tempfile::tempdir().expect("tempdir");
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ let engine = Engine::new(config.clone()).expect("clean boot");
+ engine.create_index("fine", Schema::empty()).unwrap();
+ let green = build_es_compat_router(AppState::new(
+ config,
+ engine,
+ Metrics::new().expect("metrics"),
+ ));
+ for requested in ["green", "yellow", "red"] {
+ let uri = format!("/_cluster/health?wait_for_status={requested}&timeout=30s");
+ let (status, body) = send_json(&green, "GET", &uri).await;
+ assert_eq!(status, StatusCode::OK, "{requested}: {body}");
+ assert_eq!(body["timed_out"], false, "{requested}: {body}");
+ assert_eq!(body["status"], "green", "{requested}: {body}");
+ }
+}
+
+/// `GET /{index}` and `HEAD /{index}` are the two canonical existence probes —
+/// `indices.exists()` in every ES client is the HEAD. Both answered
+/// `404 index_not_found_exception "no such index [broken]"` for a failed index,
+/// which contradicted `_cat/indices` (a red row for the same name) and
+/// `_settings` (200) in the same run, and left a client that did HEAD (404)
+/// then PUT (503) with two incompatible answers about one name.
+///
+/// ES resolves both out of cluster metadata and never touches a shard
+/// (`TransportGetIndexAction.localClusterStateOperation` →
+/// `concreteIndexNames(state.metadata(), request)`), so a red index answers
+/// 200 with its metadata there. It does here now too.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_failed_index_exists_on_the_existence_probes() {
+ let (state, _dir) = node_with_one_broken_index().await;
+ let app = build_es_compat_router(state);
+
+ let (status, _) = send(&app, "HEAD", "/broken").await;
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "HEAD /{{index}} is indices.exists(); the name IS taken"
+ );
+
+ let (status, body) = send_json(&app, "GET", "/broken").await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(
+ body["broken"]["settings"]["index"]["uuid"].is_string(),
+ "the metadata read must return the index, not an empty object: {body}"
+ );
+
+ // A wildcard/_all metadata read enumerates it for the same reason.
+ let (status, body) = send_json(&app, "GET", "/_all").await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(body["broken"].is_object(), "{body}");
+ assert!(body["healthy"].is_object(), "{body}");
+
+ // A name that never existed is still an honest 404 on both.
+ let (status, _) = send(&app, "HEAD", "/never-existed").await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ let (status, body) = send_json(&app, "GET", "/never-existed").await;
+ assert_eq!(status, StatusCode::NOT_FOUND, "{body}");
+
+ // The *data* doors still refuse: existing-but-unservable is 503, which is
+ // the distinction the 404 destroyed.
+ let (status, body) = send_json(&app, "GET", "/broken/_search").await;
+ assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{body}");
+ assert_eq!(
+ body["error"]["type"], "no_shard_available_action_exception",
+ "{body}"
+ );
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cluster_state_carries_the_failed_index_as_an_unassigned_primary() {
let (state, _dir) = node_with_one_broken_index().await;
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index 6e0f19cfa..19f538df2 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -542,6 +542,14 @@ impl Engine {
}
Err(e) => {
warn!(name = name_str.as_str(), error = %e, "failed to open index");
+ // The mapping blob lives beside the data, not inside
+ // the store, so it is readable even when the store
+ // refuses to open. Load it so the metadata surfaces
+ // (`GET /{index}`, `GET /{index}/_mapping`) can still
+ // tell the operator what was in the index they are
+ // trying to recover. Propagation into the (absent)
+ // handle no-ops.
+ engine.load_persisted_es_mapping(&name_str);
engine.record_failed_index(&name_str, e.to_string());
}
}
@@ -1227,7 +1235,24 @@ impl Engine {
));
}
match self.indices.remove(name).map(|(_, v)| v) {
- Some(idx) => idx.delete_all_data().await?,
+ Some(idx) => {
+ // The handle is pulled out of the map first so no write can
+ // land in a directory that is being removed — but if the
+ // removal then fails (read-only mount, EACCES, EROFS), the
+ // name has been freed while the bytes are still there. That
+ // is exactly the stuck state issue #206 is about, arrived at
+ // from the other side: `Engine::indices` no longer holds it,
+ // `failed_indices` never did, so `_cat/indices` cannot show
+ // it, `DELETE` answers 404 and none of the three recovery
+ // levers this module adds can name it. Put the handle back so
+ // a delete that did not happen leaves the index addressable
+ // and the operator can retry it.
+ if let Err(e) = idx.delete_all_data().await {
+ self.indices.insert(name.to_string(), idx);
+ warn!(name, error = %e, "index delete failed; index left in service");
+ return Err(e);
+ }
+ }
None => {
// Not open. If it is a known failed index, its bytes are still
// on disk and removing them is exactly what the operator asked
diff --git a/engine/crates/xerj-engine/tests/failed_index_recovery.rs b/engine/crates/xerj-engine/tests/failed_index_recovery.rs
index e7257800a..44ce36d41 100644
--- a/engine/crates/xerj-engine/tests/failed_index_recovery.rs
+++ b/engine/crates/xerj-engine/tests/failed_index_recovery.rs
@@ -159,6 +159,77 @@ async fn a_failed_index_can_be_deleted_without_a_restart() {
assert!(matches!(e, XerjError::IndexNotFound { .. }), "{e:?}");
}
+/// The failed-index arm of `delete_index` drops its bookkeeping only after the
+/// bytes are gone. The **open**-index arm did the opposite: the handle was
+/// pulled out of `Engine::indices` before `delete_all_data`, so a removal that
+/// failed left the name freed and the directory alive — no handle, no
+/// `failed_indices` entry, nothing on `_cat/indices`, `DELETE` answering 404
+/// and none of the three recovery levers able to name it. That is issue #206's
+/// stuck state reached from the other side, and it only became
+/// operator-visible once `DELETE` started propagating the error instead of
+/// dropping it.
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_delete_that_failed_leaves_the_index_addressable() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let (dir, good) = data_dir_with_one_broken_index(&["keeper"], "keeper").await;
+ // Undo the corruption — this test is about a healthy, open index whose
+ // *bytes* refuse to go away, not about a failed one.
+ std::fs::write(dir.path().join("keeper").join("snapshot.json"), &good).unwrap();
+ let engine = Engine::new(config_for(&dir)).expect("boot");
+ assert!(engine.get_index("keeper").is_ok());
+
+ // Make the removal fail: with the index directory read-only its entries
+ // cannot be unlinked, so `remove_dir_all` returns EACCES.
+ let index_dir = dir.path().join("keeper");
+ let original = std::fs::metadata(&index_dir).unwrap().permissions();
+ std::fs::set_permissions(&index_dir, std::fs::Permissions::from_mode(0o555)).unwrap();
+
+ // Skip rather than lie if the platform/user does not enforce the mode
+ // (running as root, or an fs that ignores it) — the assertion below would
+ // be vacuous there.
+ let enforced = std::fs::write(index_dir.join(".perm-probe"), b"x").is_err();
+ if !enforced {
+ let _ = std::fs::remove_file(index_dir.join(".perm-probe"));
+ std::fs::set_permissions(&index_dir, original).unwrap();
+ eprintln!("skipping: directory permissions are not enforced for this user");
+ return;
+ }
+
+ let err = engine
+ .delete_index("keeper")
+ .await
+ .expect_err("a delete whose bytes cannot be removed must fail");
+ assert!(
+ index_dir.exists(),
+ "the directory survived the failed delete"
+ );
+
+ // The point of the test: the name did not become a dead end.
+ assert!(
+ engine.get_index("keeper").is_ok(),
+ "a delete that did not happen must leave the index addressable ({err})"
+ );
+ assert!(
+ engine
+ .list_indices()
+ .await
+ .iter()
+ .any(|i| i.name == "keeper"),
+ "and still enumerable, or no surface can show it"
+ );
+
+ // Once the cause is fixed the operator's retry works — no restart.
+ std::fs::set_permissions(&index_dir, original).unwrap();
+ engine
+ .delete_index("keeper")
+ .await
+ .expect("retrying the delete after fixing the cause must work");
+ assert!(!index_dir.exists());
+ assert!(engine.list_indices().await.is_empty());
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn retry_reports_the_live_reason_and_succeeds_once_the_cause_is_fixed() {
let (dir, good) = data_dir_with_one_broken_index(&["broken"], "broken").await;