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(autoindex): fail fast when the node disk is at flood stage (#2087)
xerj-orgfb0f352bc5fc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 451c42a08..9a3d0cdb6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -54,6 +54,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0and includes them([#2076](https://github.com/xerj-org/xerj/issues/2076)).+- `xerj autoindex` checks the node's data volume against the disk+ flood-stage watermark before walking or hashing. A volume already at or+ over the watermark (default 95%) used to fail only at the first write,+ after the prepare. The run now stops immediately and reports the free+ space, the threshold, and `limits.disk_flood_stage_percent`. The probe+ reads the node (`GET /_cat/allocation?format=json`), not the client's+ disk. A node that does not report the threshold is unchanged, and+ `--dry-run` (which writes nothing) is never refused for disk.+- Playground user dashboards resolve their inherited template for chart dataand panel editing. Cloning a user dashboard retains the underlying template;missing or cyclic template references keep the blank fallback. Customdiff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex c33aff3be..497e1e4d5 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -34683,14 +34683,20 @@ pub async fn cat_allocation(let (disk_total, disk_avail) = read_disk_stats(&state.config.server.data_dir).unwrap_or((10 * 1024 * 1024 * 1024, 8 * 1024 * 1024 * 1024));let disk_used_bytes = disk_total.saturating_sub(disk_avail);- let disk_percent = ((disk_total - disk_avail) * 100)- .checked_div(disk_total)- .unwrap_or(0);+ // Same integer percent the governor admits on (`used * 100 / total` in+ // u128). The previous u64 multiply overflows on a volume larger than+ // `u64::MAX / 100`, which would report a low percent while the write+ // block used the real one. Realistic disks are unchanged.+ let disk_percent = if disk_total == 0 {+ 0+ } else {+ ((disk_used_bytes as u128 * 100) / disk_total as u128) as u64+ };let shards = health.index_count;if params.format.as_deref() == Some("json") {- return Json(vec![json!({+ let mut row = json!({"shards": shards.to_string(),"disk.indices": format!("{indices_bytes}b"),"disk.used": format!("{disk_used_bytes}b"),@@ -34700,8 +34706,18 @@ pub async fn cat_allocation("host": "127.0.0.1","ip": "127.0.0.1","node": "xerj-node-1",- })])- .into_response();+ });+ // #2077: effective flood-stage gate, so autoindex can refuse before+ // it walks. Not cat columns — the text table below is unchanged.+ // Omitted when no governor is installed; the client then does not+ // guess a threshold.+ if let Some(governor) = xerj_engine::governor::global() {+ let gate = governor.disk_flood_admission();+ row["disk.flood_stage"] = json!(gate.flood_pct.to_string());+ row["disk.threshold_enabled"] = json!(gate.threshold_enabled.to_string());+ row["disk.flood_blocked"] = json!(gate.blocked.to_string());+ }+ return Json(vec![row]).into_response();}let body = format!(diff --git a/engine/crates/xerj-api/tests/flood_stage_allocation.rs b/engine/crates/xerj-api/tests/flood_stage_allocation.rsnew file mode 100644index 000000000..466f9c798--- /dev/null+++ b/engine/crates/xerj-api/tests/flood_stage_allocation.rs@@ -0,0 +1,85 @@+//! `/_cat/allocation?format=json` carries the node's flood-stage gate (#2077).+//!+//! Autoindex reads this before it walks. The numbers are the data directory's+//! filesystem (the same `statvfs` the governor admits on), not a client-side+//! guess, and the threshold is the governor's effective percent — config+//! default 95, after any live cluster-settings override. The plain-text cat+//! table does not grow a column.++use axum::body::Body;+use axum::http::Request;+use tower::ServiceExt;++async fn app() -> (axum::Router, tempfile::TempDir) {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ (xerj_api::router::build_es_compat_router(state), dir)+}++#[tokio::test]+async fn allocation_json_reports_the_flood_stage_gate_and_text_does_not() {+ let (app, _dir) = app().await;++ let response = app+ .clone()+ .oneshot(+ Request::get("/_cat/allocation?format=json")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .expect("json allocation");+ assert!(response.status().is_success());+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let body: serde_json::Value = serde_json::from_slice(&bytes).expect("json");+ let row = body+ .as_array()+ .and_then(|rows| rows.first())+ .expect("one allocation row");+ assert_eq!(row["disk.flood_stage"], "95");+ assert_eq!(row["disk.threshold_enabled"], "true");+ assert!(+ row["disk.flood_blocked"] == "true" || row["disk.flood_blocked"] == "false",+ "blocked is a cat-style boolean string: {row}"+ );+ let avail = row["disk.avail"].as_str().expect("disk.avail");+ assert!(+ avail.ends_with('b') && avail[..avail.len() - 1].chars().all(|c| c.is_ascii_digit()),+ "free space is a raw byte count, which is what autoindex parses: {avail}"+ );+ let percent: u64 = row["disk.percent"]+ .as_str()+ .expect("disk.percent")+ .parse()+ .expect("integer percent");+ assert!(percent <= 100, "{percent}");++ let response = app+ .oneshot(+ Request::get("/_cat/allocation")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .expect("text allocation");+ assert!(response.status().is_success());+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let text = String::from_utf8(bytes.to_vec()).unwrap();+ assert!(+ text.contains("xerj-node-1"),+ "the text table is still the cat line: {text}"+ );+ assert!(+ !text.contains("flood"),+ "flood-stage fields are not text columns: {text}"+ );+}diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex ac732999e..ac61fdf98 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -894,8 +894,11 @@ fn assert_unsupported_delta_without_remote_mutation(let attempted_requests = endpoint.state.lock().unwrap().requests[request_start..].to_vec();assert_eq!(attempted_requests,- [("GET".to_owned(), "/".to_owned())],- "a refused attempt may perform only the endpoint-readiness GET"+ [+ ("GET".to_owned(), "/".to_owned()),+ ("GET".to_owned(), "/_cat/allocation?format=json".to_owned(),),+ ],+ "a refused attempt may perform only the readiness GET and the read-only flood-stage probe");assert_eq!(fs::read(journal_path).unwrap(),@@ -1478,7 +1481,10 @@ fn completed_plan_rejects_mixed_membership_delta_in_stable_order() {let error = run_index(config).unwrap_err();assert_eq!(endpoint.state.lock().unwrap().requests[request_start..],- [("GET".to_owned(), "/".to_owned())]+ [+ ("GET".to_owned(), "/".to_owned()),+ ("GET".to_owned(), "/_cat/allocation?format=json".to_owned(),),+ ]);let typed = errordiff --git a/engine/crates/xerj-autoindex/src/flood.rs b/engine/crates/xerj-autoindex/src/flood.rsnew file mode 100644index 000000000..8d84c708b--- /dev/null+++ b/engine/crates/xerj-autoindex/src/flood.rs@@ -0,0 +1,418 @@+//! Fail fast when the node's data volume is already at the flood-stage+//! watermark (#2077).+//!+//! The watermark lives on the **node**: `limits.disk_flood_stage_percent`+//! (default 95) measured against the filesystem that holds the node's data+//! directory. Autoindex and the node are not necessarily the same machine, so+//! this probe reads `GET /_cat/allocation?format=json` — the endpoint that+//! already reports that volume's used percent and free bytes — plus the+//! effective threshold and the latched write block the node adds to that+//! JSON. It does not `stat` the client's disk.+//!+//! A node that does not send `disk.flood_stage` (an older XERJ, Elasticsearch,+//! or the HTTP doubles in this crate's tests) is not guessed at. Those runs+//! behave as they did before: the write itself still reports the block if one+//! engages later.++use serde_json::Value;++use crate::esclient::Es;++const ALLOCATION_PATH: &str = "/_cat/allocation?format=json";++/// `None` when the node cannot be asked or does not report a flood-stage+/// threshold. A stats blip must not abort a run whose disk is fine, and the+/// write path still refuses if the block is actually engaged.+pub(crate) fn refusal(es: &Es) -> Option<String> {+ let (status, body) = es.request_json("GET", ALLOCATION_PATH, None).ok()?;+ if !(200..300).contains(&status) {+ return None;+ }+ refusal_from_allocation(&body)+}++/// Decide from one `/_cat/allocation?format=json` body.+///+/// `Some` is the error text for a volume already at or over the watermark,+/// or for a write block the node has not released yet (the 1% hysteresis+/// below the threshold still refuses writes). `None` means index.+pub(crate) fn refusal_from_allocation(body: &Value) -> Option<String> {+ let row = body.as_array()?.first()?;+ // Absent threshold: this response is not the XERJ flood-stage report.+ // Do not assume 95. The node's config may be 99 (the #2077 workaround)+ // or 0 (watermark off), and a hard-coded default would refuse both.+ let flood_raw = parse_u64(row.get("disk.flood_stage")?)?;+ let flood = u8::try_from(flood_raw.min(100)).ok()?;+ let enabled = row+ .get("disk.threshold_enabled")+ .and_then(parse_bool)+ .unwrap_or(true);+ let blocked = row+ .get("disk.flood_blocked")+ .and_then(parse_bool)+ .unwrap_or(false);+ let used = row.get("disk.percent").and_then(parse_u64);+ let free = row.get("disk.avail").and_then(parse_bytes);++ let over = enabled && flood > 0 && used.is_some_and(|pct| pct >= u64::from(flood));+ if !blocked && !over {+ return None;+ }+ Some(refusal_message(free, used, flood, blocked && !over))+}++fn refusal_message(free: Option<u64>, used: Option<u64>, flood: u8, hysteresis: bool) -> String {+ let free = match free {+ Some(bytes) => format_bytes(bytes),+ None => "unknown".to_string(),+ };+ let used = match used {+ Some(pct) => format!("{pct}% used"),+ None => "used percent unknown".to_string(),+ };+ let why = if hysteresis {+ "the disk flood-stage write block is still engaged"+ } else {+ "its data volume is already at or over the disk flood-stage watermark"+ };+ format!(+ "the node will refuse every write: {why} (free {free}, {used}, threshold {flood}%). \+ Set limits.disk_flood_stage_percent above the used percent in the node config and \+ restart (0 disables the watermark), or raise it live with \+ PUT /_cluster/settings {{\"persistent\":{{\"cluster.routing.allocation.disk.watermark.flood_stage\":\"<percent>\"}}}}. \+ No files were walked and nothing was written."+ )+}++/// Same scale as the engine's flood-stage log line (`2.0gb`, `512b`).+fn format_bytes(bytes: u64) -> String {+ const KB: u64 = 1024;+ const MB: u64 = 1024 * KB;+ const GB: u64 = 1024 * MB;+ if bytes >= GB {+ format!("{:.1}gb", bytes as f64 / GB as f64)+ } else if bytes >= MB {+ format!("{:.1}mb", bytes as f64 / MB as f64)+ } else if bytes >= KB {+ format!("{:.1}kb", bytes as f64 / KB as f64)+ } else {+ format!("{bytes}b")+ }+}++fn parse_u64(value: &Value) -> Option<u64> {+ match value {+ Value::Number(n) => n.as_u64(),+ Value::String(s) => s.trim().trim_end_matches('%').parse().ok(),+ _ => None,+ }+}++fn parse_bool(value: &Value) -> Option<bool> {+ match value {+ Value::Bool(b) => Some(*b),+ Value::String(s) => match s.trim() {+ "true" => Some(true),+ "false" => Some(false),+ _ => None,+ },+ _ => None,+ }+}++/// `/_cat/allocation` emits free space as a raw byte count with a `b` suffix+/// (`"2147483648b"`). Anything else is left unknown rather than guessed.+fn parse_bytes(value: &Value) -> Option<u64> {+ match value {+ Value::Number(n) => n.as_u64(),+ Value::String(s) => {+ let s = s.trim();+ let s = s+ .strip_suffix('b')+ .or_else(|| s.strip_suffix('B'))+ .unwrap_or(s);+ if !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()) {+ s.parse().ok()+ } else {+ None+ }+ }+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn row(percent: &str, avail: &str, flood: &str, enabled: &str, blocked: &str) -> Value {+ json!([{+ "disk.percent": percent,+ "disk.avail": avail,+ "disk.flood_stage": flood,+ "disk.threshold_enabled": enabled,+ "disk.flood_blocked": blocked,+ }])+ }++ #[test]+ fn at_or_over_the_watermark_refuses_with_free_space_threshold_and_override() {+ let message = refusal_from_allocation(&row("98", "2147483648b", "95", "true", "false"))+ .expect("98% against a 95% watermark must refuse");+ assert!(message.contains("free 2.0gb"), "{message}");+ assert!(message.contains("98% used"), "{message}");+ assert!(message.contains("threshold 95%"), "{message}");+ assert!(+ message.contains("limits.disk_flood_stage_percent"),+ "{message}"+ );+ assert!(message.contains("No files were walked"), "{message}");+ assert!(+ message.contains("at or over the disk flood-stage watermark"),+ "{message}"+ );++ // The watermark is inclusive: used == threshold is already blocked+ // (`disk_used_pct >= flood_pct` in the governor).+ assert!(refusal_from_allocation(&row("95", "1b", "95", "true", "false")).is_some());+ }++ #[test]+ fn a_healthy_volume_and_a_raised_or_disabled_watermark_do_not_refuse() {+ assert!(refusal_from_allocation(&row("40", "1000b", "95", "true", "false")).is_none());+ // One percent under the threshold, block not latched.+ assert!(refusal_from_allocation(&row("94", "1000b", "95", "true", "false")).is_none());+ // The field-report workaround: config raised to 99 while the volume+ // sits at 98. Writes are admitted; autoindex must not refuse.+ assert!(refusal_from_allocation(&row("98", "1000b", "99", "true", "false")).is_none());+ // `limits.disk_flood_stage_percent = 0` turns the watermark off.+ assert!(refusal_from_allocation(&row("98", "1000b", "0", "true", "false")).is_none());+ // `cluster.routing.allocation.disk.threshold_enabled: false`.+ assert!(refusal_from_allocation(&row("98", "1000b", "95", "false", "false")).is_none());+ }++ #[test]+ fn hysteresis_still_refuses_and_a_silent_node_does_not() {+ let message = refusal_from_allocation(&row("94", "4096b", "95", "true", "true"))+ .expect("a latched block under the threshold still refuses writes");+ assert!(+ message.contains("write block is still engaged"),+ "{message}"+ );+ assert!(message.contains("free 4.0kb"), "{message}");+ assert!(message.contains("threshold 95%"), "{message}");++ // Older XERJ / Elasticsearch / the in-crate HTTP doubles: allocation+ // JSON without the threshold is not a reason to stop.+ assert!(refusal_from_allocation(&json!([{+ "disk.percent": "99",+ "disk.avail": "1b"+ }]))+ .is_none());+ assert!(refusal_from_allocation(&json!({"acknowledged": true})).is_none());+ assert!(refusal_from_allocation(&json!([])).is_none());+ }++ /// The probe runs before the walk: a flooded node refuses with the+ /// override text and never opens the folder, and a healthy node is not+ /// refused (the walk then reports that the root is a file).+ #[test]+ fn autoindex_refuses_before_walk_only_when_the_node_reports_flood_stage() {+ let flooded = Node::start(true);+ let healthy = Node::start(false);+ let root_dir = tempfile::tempdir().unwrap();+ let root = root_dir.path().join("not-a-folder");+ std::fs::write(&root, "bytes the walk must not have to read\n").unwrap();++ let flooded_state = tempfile::tempdir().unwrap();+ let error = crate::run_index_report(index_cfg(&root, flooded_state.path(), &flooded.url))+ .expect_err("a flooded data volume must fail the run");+ let message = format!("{error:#}");+ assert!(+ message.contains("limits.disk_flood_stage_percent"),+ "{message}"+ );+ assert!(message.contains("free 2.0gb"), "{message}");+ assert!(message.contains("threshold 95%"), "{message}");+ assert!(+ !message.contains("is not a directory"),+ "the walk must not have started: {message}"+ );+ assert!(+ !flooded_state.path().join(".autoindex.lock").exists(),+ "refusing before the walk must not open the state directory"+ );+ assert_eq!(+ flooded.requests(),+ vec![+ ("GET".to_string(), "/".to_string()),+ (+ "GET".to_string(),+ "/_cat/allocation?format=json".to_string(),+ ),+ ]+ );++ let healthy_state = tempfile::tempdir().unwrap();+ let error = crate::run_index_report(index_cfg(&root, healthy_state.path(), &healthy.url))+ .expect_err("a file root still cannot be walked");+ let message = format!("{error:#}");+ assert!(+ message.contains("is not a directory"),+ "a healthy volume must reach the walk: {message}"+ );+ assert!(+ !message.contains("limits.disk_flood_stage_percent"),+ "{message}"+ );++ // A dry run writes nothing: a flooded node does not refuse it.+ let dry_state = tempfile::tempdir().unwrap();+ let mut dry = index_cfg(&root, dry_state.path(), &flooded.url);+ dry.dry_run = true;+ if let Err(error) = crate::run_index_report(dry) {+ let message = format!("{error:#}");+ assert!(+ !message.contains("limits.disk_flood_stage_percent"),+ "a dry run must not be refused for disk: {message}"+ );+ }+ }++ fn index_cfg(+ root: &std::path::Path,+ state: &std::path::Path,+ url: &str,+ ) -> crate::cli::IndexCfg {+ let args = vec![+ root.to_string_lossy().to_string(),+ "--url".into(),+ url.into(),+ "--state-dir".into(),+ state.to_string_lossy().to_string(),+ "--prefix".into(),+ "flood2077".into(),+ "--no-graph".into(),+ "--quiet".into(),+ ];+ match crate::cli::parse(args).expect("argv parses") {+ crate::cli::Cmd::Index(cfg) => *cfg,+ other => panic!("expected index, got {other:?}"),+ }+ }++ struct Node {+ url: String,+ requests: std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>>,+ stop: std::sync::Arc<std::sync::atomic::AtomicBool>,+ join: Option<std::thread::JoinHandle<()>>,+ }++ impl Node {+ fn start(flooded: bool) -> Self {+ use std::io::{BufRead, BufReader, Read, Write};+ use std::net::TcpListener;+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::{Arc, Mutex};+ use std::time::Duration;++ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ listener.set_nonblocking(true).unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ let requests = Arc::new(Mutex::new(Vec::new()));+ let stop = Arc::new(AtomicBool::new(false));+ let requests_bg = Arc::clone(&requests);+ let stop_bg = Arc::clone(&stop);+ let join = std::thread::spawn(move || {+ while !stop_bg.load(Ordering::Relaxed) {+ match listener.accept() {+ Ok((mut stream, _)) => {+ stream.set_nonblocking(false).unwrap();+ stream+ .set_read_timeout(Some(Duration::from_secs(5)))+ .unwrap();+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut request_line = String::new();+ if reader.read_line(&mut request_line).unwrap_or(0) == 0 {+ continue;+ }+ let mut content_length = 0usize;+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line).unwrap_or(0) == 0 {+ break;+ }+ if line == "\r\n" || line.is_empty() {+ break;+ }+ if let Some(value) =+ line.to_ascii_lowercase().strip_prefix("content-length:")+ {+ content_length = value.trim().parse().unwrap_or(0);+ }+ }+ if content_length > 0 {+ let mut body = vec![0; content_length];+ let _ = reader.read_exact(&mut body);+ }+ let mut parts = request_line.split_whitespace();+ let method = parts.next().unwrap_or("").to_string();+ let path = parts.next().unwrap_or("").to_string();+ requests_bg+ .lock()+ .unwrap()+ .push((method.clone(), path.clone()));+ let (status, body) = if method == "GET" && path == "/" {+ (200, r#"{"ok":true}"#)+ } else if method == "GET" && path.starts_with("/_cat/allocation") {+ if flooded {+ (+ 200,+ r#"[{"disk.percent":"98","disk.avail":"2147483648b","disk.flood_stage":"95","disk.threshold_enabled":"true","disk.flood_blocked":"false"}]"#,+ )+ } else {+ (+ 200,+ r#"[{"disk.percent":"10","disk.avail":"1073741824b","disk.flood_stage":"95","disk.threshold_enabled":"true","disk.flood_blocked":"false"}]"#,+ )+ }+ } else {+ (404, r#"{"error":"absent"}"#)+ };+ let reason = if status == 200 { "OK" } else { "Not Found" };+ let _ = write!(+ stream,+ "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ }+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ std::thread::sleep(Duration::from_millis(5));+ }+ Err(error) => panic!("accept failed: {error}"),+ }+ }+ });+ Self {+ url,+ requests,+ stop,+ join: Some(join),+ }+ }++ fn requests(&self) -> Vec<(String, String)> {+ self.requests.lock().unwrap().clone()+ }+ }++ impl Drop for Node {+ fn drop(&mut self) {+ self.stop.store(true, std::sync::atomic::Ordering::Relaxed);+ if let Some(join) = self.join.take() {+ let _ = join.join();+ }+ }+ }+}diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 3093db5d9..5dffa0c1a 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -2111,8 +2111,11 @@ fn fresh_cannot_destroy_a_committed_generation() {let attempted = endpoint.state.lock().unwrap().requests[requests_before..].to_vec();assert_eq!(attempted,- [("GET".to_owned(), "/".to_owned())],- "a refused --fresh may perform only the endpoint-readiness GET"+ [+ ("GET".to_owned(), "/".to_owned()),+ ("GET".to_owned(), "/_cat/allocation?format=json".to_owned(),),+ ],+ "a refused --fresh may perform only the readiness GET and the read-only flood-stage probe");// The surviving authority still reconciles the real folder change.@@ -2219,8 +2222,11 @@ fn fresh_cannot_destroy_a_pending_generation() {let attempted = endpoint.state.lock().unwrap().requests[requests_before..].to_vec();assert_eq!(attempted,- [("GET".to_owned(), "/".to_owned())],- "a refused --fresh may perform only the endpoint-readiness GET"+ [+ ("GET".to_owned(), "/".to_owned()),+ ("GET".to_owned(), "/_cat/allocation?format=json".to_owned(),),+ ],+ "a refused --fresh may perform only the readiness GET and the read-only flood-stage probe");// The pending transaction is still resumable from its sealed source.diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex b4fac552c..98fbbf36d 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -15,6 +15,7 @@ pub mod esclient;pub mod estimate;pub mod extract;pub mod feedback;+mod flood;pub mod gain;pub mod gate;mod generation_catalog;@@ -6473,6 +6474,21 @@ fn run_index_report_inner(if let Err(e) = es.ping() {anyhow::bail!("{}", node_ping_failure(&cfg.url, &e));}+ // #2077: the flood-stage write block used to surface only when the first+ // bulk was rejected, after walk/hash/scan/prepare (~10 minutes on the+ // report). The watermark is the node's data volume, which may not be+ // this client's disk, so the probe reads the node. A node that does not+ // report the threshold is left alone — a hard-coded 95 would refuse the+ // `limits.disk_flood_stage_percent = 99` workaround and a disabled+ // watermark. Nothing has been walked or written yet, so bailing here+ // leaves no journal and no remote mutation.+ // A dry run writes nothing, so a full volume is not a reason to refuse+ // it: the plan (and its size) is exactly what a user short on disk needs.+ if !cfg.dry_run {+ if let Some(message) = flood::refusal(&es) {+ anyhow::bail!("{message}");+ }+ }// `--label <question-set>` (#1062): every record's payload goes through// the node's /_decide at ingest and the answers are stamped on as@@ -6533,9 +6549,10 @@ fn run_index_report_inner(// A journal that already binds this state dir to this root, url, and// prefix is a resume or an incremental re-run of the same folder,// including one the local plan / `--fresh` gates are about to refuse.- // Those refusals promise the only remote call is the readiness GET, so- // this guard must not search the catalog on that path. A different- // folder has no such journal and still hits the check.+ // Those refusals promise no catalog search and no remote mutation. The+ // only remote calls on that path are the readiness GET and the read-only+ // flood-stage probe (#2077), so this guard must not search the catalog+ // there. A different folder has no such journal and still hits the check.if !state::journal_continues_folder(&state_dir, &root_str, &cfg.url, &cfg.prefix) {let foreign_roots = catalog::foreign_prefix_roots(&catalog_runs_for_prefix(&es, &cfg.prefix)?,diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex 74cedcbd3..0debae8c8 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -816,10 +816,10 @@ pub fn default_state_dir(root: &str, url: &str, prefix: &str) -> PathBuf {/// `--fresh` all re-enter through that journal. The prefix-collision guard/// must not query the catalog on that path: those refusals are local, and/// the HTTP fixtures require that a refused attempt perform only the-/// readiness GET. A different folder does not satisfy this — the default-/// state directory includes the root, and an explicit state directory-/// recorded for another root or prefix compares unequal — so the catalog-/// check still runs for it.+/// readiness GET and the read-only flood-stage probe (#2077). A different+/// folder does not satisfy this — the default state directory includes the+/// root, and an explicit state directory recorded for another root or+/// prefix compares unequal — so the catalog check still runs for it.////// An absent, unreadable, or corrupt journal is not a continuation, and/// neither is a journal whose `run` record names something else. This readsdiff --git a/engine/crates/xerj-engine/src/governor.rs b/engine/crates/xerj-engine/src/governor.rsindex 64758c243..3d89b8e70 100644--- a/engine/crates/xerj-engine/src/governor.rs+++ b/engine/crates/xerj-engine/src/governor.rs@@ -236,6 +236,23 @@ impl ResourceGovernor {Ok(())}+ /// Effective flood-stage gate for `/_cat/allocation` (#2077).+ ///+ /// `flood_pct` is `limits.disk_flood_stage_percent` after a live+ /// `cluster.routing.allocation.disk.watermark.flood_stage` override.+ /// `0` means the watermark is off. `threshold_enabled` mirrors+ /// `cluster.routing.allocation.disk.threshold_enabled` (default true).+ /// `blocked` is the latched write block, including the 1% release+ /// hysteresis, so a volume that has dipped just under the threshold+ /// still reports that writes will be refused.+ pub fn disk_flood_admission(&self) -> DiskFloodAdmission {+ DiskFloodAdmission {+ flood_pct: self.disk_flood_pct.load(Ordering::Relaxed),+ threshold_enabled: self.disk_threshold_enabled.load(Ordering::Relaxed),+ blocked: self.disk_blocked.load(Ordering::Relaxed),+ }+ }+/// Applies (or clears) a runtime override of the disk flood-stage/// percent, read each sampler tick from the/// `cluster.routing.allocation.disk.watermark.flood_stage` persistent@@ -539,6 +556,14 @@ impl Drop for SearchPermit {}}+/// The disk flood-stage gate `/_cat/allocation` reports to clients (#2077).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct DiskFloodAdmission {+ pub flood_pct: u8,+ pub threshold_enabled: bool,+ pub blocked: bool,+}+/// A cheap, `Copy`-able snapshot of governor state.#[derive(Debug, Clone, Copy)]pub struct GovernorSnapshot {@@ -1953,8 +1978,13 @@ mod tests {let mut cfg = Config::default();cfg.limits.disk_flood_stage_percent = 95;let g = build(&cfg);+ let gate = g.disk_flood_admission();+ assert_eq!(gate.flood_pct, 95);+ assert!(gate.threshold_enabled);+ assert!(!gate.blocked);assert!(g.check_disk_block("i").is_ok());g.refresh(0, 0, 96); // over flood stage+ assert!(g.disk_flood_admission().blocked);assert!(g.check_disk_block("i").is_err());g.refresh(0, 0, 95); // still within release hysteresis (>= 94)assert!(g.check_disk_block("i").is_err());@@ -1996,6 +2026,8 @@ mod tests {// sample and keeps it off however full the disk gets.g.set_disk_threshold_enabled(Some(false));g.refresh(0, 0, 97);+ assert!(!g.disk_flood_admission().threshold_enabled);+ assert!(!g.disk_flood_admission().blocked);assert!(g.check_disk_block("i").is_ok());g.refresh(0, 0, 100);assert!(g.check_disk_block("i").is_ok());