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(api): merge PUT _cluster/settings into stored settings, as ES does (#1595)
Jay Hemnanid62221a62872
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex da63c3726..d85645457 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -33268,13 +33268,15 @@ pub async fn restore_snapshot(// GET /_cluster/pending_tasks// ─────────────────────────────────────────────────────────────────────────────-pub async fn get_cluster_settings(State(state): State<AppState>) -> impl IntoResponse {+pub async fn get_cluster_settings(+ State(state): State<AppState>,+ axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,+) -> impl IntoResponse {let settings = state.engine.cluster_settings.read().await;- let persistent = settings.get("persistent").cloned().unwrap_or(json!({}));- let transient = settings.get("transient").cloned().unwrap_or(json!({}));+ let flat = flat_settings_param(¶ms);Json(json!({- "persistent": persistent,- "transient": transient,+ "persistent": render_settings(settings.get("persistent"), flat),+ "transient": render_settings(settings.get("transient"), flat),"defaults": {},})).into_response()@@ -33282,25 +33284,81 @@ pub async fn get_cluster_settings(State(state): State<AppState>) -> impl IntoRespub async fn put_cluster_settings(State(state): State<AppState>,+ axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,Json(body): Json<Value>,) -> impl IntoResponse {let mut settings = state.engine.cluster_settings.write().await;- if let Some(persistent) = body.get("persistent") {- settings["persistent"] = persistent.clone();- }- if let Some(transient) = body.get("transient") {- settings["transient"] = transient.clone();+ // ES merges an update into the stored settings, keyed by the flat dotted+ // name whichever form the request used, and `null` removes a setting.+ // The response lists only the settings this request set.+ let mut updated = json!({ "persistent": {}, "transient": {} });+ for scope in ["persistent", "transient"] {+ let Some(update) = body.get(scope) else {+ continue;+ };+ let mut flat = serde_json::Map::new();+ flatten_settings("", update, &mut flat);+ if !settings[scope].is_object() {+ settings[scope] = json!({});+ }+ if let Some(stored) = settings[scope].as_object_mut() {+ for (key, value) in flat {+ if value.is_null() {+ stored.remove(&key);+ } else {+ updated[scope][key.as_str()] = value.clone();+ stored.insert(key, value);+ }+ }+ }}- let persistent = settings.get("persistent").cloned().unwrap_or(json!({}));- let transient = settings.get("transient").cloned().unwrap_or(json!({}));+ let flat = flat_settings_param(¶ms);Json(json!({"acknowledged": true,- "persistent": persistent,- "transient": transient,+ "persistent": render_settings(updated.get("persistent"), flat),+ "transient": render_settings(updated.get("transient"), flat),})).into_response()}+/// `?flat_settings` / `?flat_settings=true`; ES defaults to the nested form.+fn flat_settings_param(params: &std::collections::HashMap<String, String>) -> bool {+ matches!(+ params.get("flat_settings").map(String::as_str),+ Some("" | "true")+ )+}++/// Settings are stored under flat dotted keys; render them nested unless the+/// caller asked for `flat_settings`.+fn render_settings(stored: Option<&Value>, flat: bool) -> Value {+ let stored = stored.cloned().unwrap_or(json!({}));+ if flat {+ stored+ } else {+ expand_dotted_keys(stored)+ }+}++/// Flattens `{"a": {"b": 1}}` into `{"a.b": 1}`.+fn flatten_settings(prefix: &str, value: &Value, out: &mut serde_json::Map<String, Value>) {+ match value {+ Value::Object(map) => {+ for (key, child) in map {+ let key = if prefix.is_empty() {+ key.clone()+ } else {+ format!("{prefix}.{key}")+ };+ flatten_settings(&key, child, out);+ }+ }+ _ => {+ out.insert(prefix.to_string(), value.clone());+ }+ }+}+pub async fn cluster_reroute(State(state): State<AppState>,axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,diff --git a/engine/crates/xerj-api/tests/cluster_settings_merge.rs b/engine/crates/xerj-api/tests/cluster_settings_merge.rsnew file mode 100644index 000000000..357755f27--- /dev/null+++ b/engine/crates/xerj-api/tests/cluster_settings_merge.rs@@ -0,0 +1,139 @@+//! `PUT /_cluster/settings` merges into the stored settings, the way+//! Elasticsearch does: a later request for one setting must not drop the+//! others, the nested object form is stored under the same dotted keys as the+//! flat form, and `null` removes a setting. The runtime readers (disk+//! flood-stage and memory-breaker overrides) look settings up by flat key, so+//! a replaced or nested setting silently stopped applying. `GET` renders the+//! nested form unless `flat_settings=true` is passed.+//!+//! Elasticsearch is referenced for semantics only; no code from it is+//! reproduced here.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+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();+ 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)+}++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 put_settings(app: &axum::Router, body: Value) {+ let (status, _) = send(+ app,+ Request::put("/_cluster/settings")+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request"),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+}++async fn get_settings(app: &axum::Router) -> Value {+ get_settings_at(app, "/_cluster/settings?flat_settings=true").await+}++async fn get_settings_at(app: &axum::Router, uri: &str) -> Value {+ let (status, body) = send(app, Request::get(uri).body(Body::empty()).expect("request")).await;+ assert_eq!(status, StatusCode::OK);+ body+}++const FLOOD: &str = "cluster.routing.allocation.disk.watermark.flood_stage";+const BREAKER: &str = "indices.breaker.total.limit";++#[tokio::test]+async fn a_second_put_keeps_earlier_settings() {+ let (app, _dir) = app().await;+ put_settings(&app, json!({ "persistent": { FLOOD: "99%" } })).await;+ put_settings(&app, json!({ "persistent": { BREAKER: "70%" } })).await;+ put_settings(&app, json!({ "transient": { "search.max_buckets": 100 } })).await;++ let got = get_settings(&app).await;+ assert_eq!(got["persistent"][FLOOD], "99%", "{got}");+ assert_eq!(got["persistent"][BREAKER], "70%", "{got}");+ assert_eq!(got["transient"]["search.max_buckets"], 100, "{got}");+}++#[tokio::test]+async fn nested_form_is_stored_under_dotted_keys() {+ let (app, _dir) = app().await;+ put_settings(+ &app,+ json!({ "persistent": { "cluster": { "routing": { "allocation": { "disk": {+ "watermark": { "flood_stage": "99%" }+ } } } } } }),+ )+ .await;++ let got = get_settings(&app).await;+ assert_eq!(got["persistent"][FLOOD], "99%", "{got}");+}++#[tokio::test]+async fn null_removes_a_setting() {+ let (app, _dir) = app().await;+ put_settings(+ &app,+ json!({ "persistent": { FLOOD: "99%", BREAKER: "70%" } }),+ )+ .await;+ put_settings(&app, json!({ "persistent": { FLOOD: null } })).await;++ let got = get_settings(&app).await;+ assert!(got["persistent"].get(FLOOD).is_none(), "{got}");+ assert_eq!(got["persistent"][BREAKER], "70%", "{got}");+}++#[tokio::test]+async fn get_is_nested_unless_flat_settings() {+ let (app, _dir) = app().await;+ put_settings(&app, json!({ "persistent": { BREAKER: "70%" } })).await;++ let nested = get_settings_at(&app, "/_cluster/settings").await;+ assert_eq!(+ nested["persistent"]["indices"]["breaker"]["total"]["limit"], "70%",+ "{nested}"+ );+ let flat = get_settings_at(&app, "/_cluster/settings?flat_settings=true").await;+ assert_eq!(flat["persistent"][BREAKER], "70%", "{flat}");+}++#[tokio::test]+async fn put_response_lists_only_this_requests_settings() {+ let (app, _dir) = app().await;+ put_settings(&app, json!({ "persistent": { FLOOD: "99%" } })).await;++ let (status, body) = send(+ &app,+ Request::put("/_cluster/settings?flat_settings=true")+ .header("content-type", "application/json")+ .body(Body::from(+ json!({ "persistent": { BREAKER: "70%" } }).to_string(),+ ))+ .expect("request"),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(body["persistent"], json!({ BREAKER: "70%" }), "{body}");+ assert_eq!(body["transient"], json!({}), "{body}");+}diff --git a/engine/tests/es-compat-yaml/src/main.rs b/engine/tests/es-compat-yaml/src/main.rsindex 5ad38813a..fb3a1084a 100644--- a/engine/tests/es-compat-yaml/src/main.rs+++ b/engine/tests/es-compat-yaml/src/main.rs@@ -1299,8 +1299,17 @@ fn resolve_action(action: &str, params: &serde_yaml::Mapping) -> (String, String("GET".into(), path, None)}"cluster.state" => ("GET".into(), "/_cluster/state".into(), None),- "cluster.get_settings" => ("GET".into(), "/_cluster/settings".into(), None),- "cluster.put_settings" => ("PUT".into(), "/_cluster/settings".into(), body),+ "cluster.get_settings" | "cluster.put_settings" => {+ let path = match get_param_str(params, "flat_settings") {+ Some(v) => format!("/_cluster/settings?flat_settings={}", v),+ None => "/_cluster/settings".to_string(),+ };+ if action == "cluster.get_settings" {+ ("GET".into(), path, None)+ } else {+ ("PUT".into(), path, body)+ }+ }// Cat"cat.indices" => ("GET".into(), "/_cat/indices".into(), None),diff --git a/engine/tests/es-compat-yaml/yaml/cluster/cluster.put_settings/10_merge.yml b/engine/tests/es-compat-yaml/yaml/cluster/cluster.put_settings/10_merge.ymlnew file mode 100644index 000000000..9da5a5d22--- /dev/null+++ b/engine/tests/es-compat-yaml/yaml/cluster/cluster.put_settings/10_merge.yml@@ -0,0 +1,46 @@+---+"Put settings merges into the stored settings":+ - do:+ cluster.put_settings:+ body:+ persistent:+ cluster.routing.allocation.enable: "all"++ - do:+ cluster.put_settings:+ body:+ persistent:+ search:+ allow_expensive_queries: "true"++ - do:+ cluster.get_settings: {}++ - match: { persistent.cluster.routing.allocation.enable: "all" }+ - match: { persistent.search.allow_expensive_queries: "true" }++ - do:+ cluster.put_settings:+ body:+ persistent:+ cluster:+ routing:+ allocation:+ enable: null++ - do:+ cluster.get_settings: {}++ - is_false: persistent.cluster.routing.allocation.enable+ - match: { persistent.search.allow_expensive_queries: "true" }++ - do:+ cluster.put_settings:+ body:+ persistent:+ search.allow_expensive_queries: null++ - do:+ cluster.get_settings: {}++ - is_false: persistent.search.allow_expensive_queries