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,engine): data-stream rollover honours dry_run and conditions (#2900)
ordinary beingb78004832f52
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2f9ec9d19..6cc5ed51f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -139,6 +139,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Data-stream `_rollover` honours `dry_run` and its `conditions` instead of+ ignoring the body: `max_docs`/`max_age` are ORed and reported in+ `conditions`, and a dry run or an unmet condition creates no backing index.+ The response names the real old/new backing indices, and the new backing is+ marked as the write index so writes through the stream continue after a+ rollover. Size-based conditions and alias-rollover body fields are refused+ rather than silently ignored.+- `xerj mcp` no longer answers a JSON-RPC notification, and runs every`tools/call` off the stdio read loop (#2898). A `tools/call` with no `id`, orwith `id: null`, used to be awaited on the read loop, so a stalled search helddiff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex a9517e973..09fe4c615 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -37368,20 +37368,191 @@ pub async fn delete_data_stream(}}+#[derive(Debug, Deserialize, Default)]+pub struct RolloverParams {+ /// `_rollover?dry_run=true` — the query-parameter form ES also accepts.+ #[serde(default)]+ pub dry_run: Option<bool>,+}++/// `POST /{data_stream}/_rollover`.+///+/// The body used to be ignored entirely: `dry_run: true` created a backing+/// index, `conditions` never blocked a rollover, and `old_index` reported the+/// data-stream name instead of the current backing index. This handler now+/// evaluates the conditions this build can support before calling the engine,+/// reports the candidate old/new backing names even when it does not roll,+/// and never mutates anything for a dry run. Conditions the build cannot+/// evaluate (size-based) and body fields that belong to index-alias rollover+/// (`new_index`, `settings`, `mappings`, `aliases`) are refused rather than+/// silently ignored (issue #204).pub async fn rollover_data_stream(State(state): State<AppState>,Path(name): Path<String>,+ Query(params): Query<RolloverParams>,+ body: OptionalJson<Value>,) -> impl IntoResponse {+ let body = match body.0 {+ None | Some(Value::Null) => json!({}),+ Some(Value::Object(map)) => Value::Object(map),+ Some(_) => {+ return es_bad_request(+ "illegal_argument_exception",+ "rollover body must be an object",+ None,+ )+ }+ };+ const ALLOWED: &[&str] = &["conditions", "dry_run"];+ if let Some(object) = body.as_object() {+ for key in object.keys() {+ if !ALLOWED.contains(&key.as_str()) {+ return es_bad_request(+ "illegal_argument_exception",+ &format!(+ "rollover field [{key}] is not supported for data streams by this XERJ version"+ ),+ None,+ );+ }+ }+ }+ let body_dry_run = match body.get("dry_run") {+ None => None,+ Some(Value::Bool(value)) => Some(*value),+ Some(_) => {+ return es_bad_request(+ "illegal_argument_exception",+ "[dry_run] must be a boolean",+ None,+ )+ }+ };+ let dry_run = body_dry_run.or(params.dry_run).unwrap_or(false);++ // The write backing index and the next generated name. This is the same+ // naming rule the engine uses, so a dry run reports the name a real+ // rollover would create.+ let (old_index, new_index, docs) = match state.engine.data_streams.get(&name) {+ Some(ds) => {+ let Some(old_index) = ds.backing_indices.last().cloned() else {+ return ApiError::new(xerj_common::XerjError::internal(format!(+ "data stream [{name}] has no backing index"+ )))+ .into_response();+ };+ let new_index = format!(".ds-{}-{:06}", name, ds.generation + 1);+ drop(ds);+ let docs = state+ .engine+ .get_index(&old_index)+ .map(|idx| idx.live_doc_count())+ .unwrap_or(0);+ (old_index, new_index, docs)+ }+ None => {+ let e = xerj_common::XerjError::index_not_found(&name);+ return ApiError::new(e).into_response();+ }+ };++ // ES validates the target index even for a dry run; an existing candidate+ // is a conflict, not a successful "would roll".+ if state.engine.get_index(&new_index).is_ok() {+ let e = xerj_common::XerjError::index_already_exists(&new_index);+ return ApiError::new(e).into_response();+ }++ let conditions = body.get("conditions");+ let mut condition_results = serde_json::Map::new();+ let mut condition_met = conditions.is_none();+ if let Some(conditions) = conditions {+ let Some(conditions) = conditions.as_object() else {+ return es_bad_request(+ "illegal_argument_exception",+ "[conditions] must be an object",+ None,+ );+ };+ if conditions.is_empty() {+ condition_met = true;+ }+ for (condition, value) in conditions {+ let met = match condition.as_str() {+ "max_docs" => {+ let Some(max_docs) = value.as_u64() else {+ return es_bad_request(+ "illegal_argument_exception",+ &format!("[max_docs] must be a non-negative integer, got [{value}]"),+ None,+ );+ };+ let met = docs >= max_docs;+ condition_results.insert(format!("[max_docs: {max_docs}]"), Value::Bool(met));+ met+ }+ "max_age" => {+ let Some(raw) = value.as_str() else {+ return es_bad_request(+ "illegal_argument_exception",+ &format!("[max_age] must be a time value, got [{value}]"),+ None,+ );+ };+ let Some(threshold_ms) = parse_time_to_millis(raw) else {+ return es_bad_request(+ "illegal_argument_exception",+ &format!("failed to parse [max_age] value [{raw}]"),+ None,+ );+ };+ let created_ms = state+ .engine+ .index_created_at+ .get(&old_index)+ .map(|v| *v)+ .unwrap_or_else(|| Utc::now().timestamp_millis());+ let age_ms = (Utc::now().timestamp_millis() - created_ms).max(0) as u64;+ let met = age_ms >= threshold_ms;+ condition_results.insert(format!("[max_age: {raw}]"), Value::Bool(met));+ met+ }+ other => {+ return es_bad_request(+ "illegal_argument_exception",+ &format!(+ "rollover condition [{other}] is not supported by this XERJ version"+ ),+ None,+ )+ }+ };+ condition_met |= met;+ }+ }++ let mut response = json!({+ "acknowledged": true,+ "shards_acknowledged": true,+ "old_index": old_index.clone(),+ "new_index": new_index.clone(),+ "rolled_over": false,+ "dry_run": dry_run,+ });+ if conditions.is_some() {+ response["conditions"] = Value::Object(condition_results);+ }++ if dry_run || !condition_met {+ return Json(response).into_response();+ }+match state.engine.rollover_data_stream(&name) {- Ok(new_index) => Json(json!({- "acknowledged": true,- "shards_acknowledged": true,- "old_index": name,- "new_index": new_index,- "rolled_over": true,- "dry_run": false,- }))- .into_response(),+ Ok(created) => {+ response["new_index"] = json!(created);+ response["rolled_over"] = json!(true);+ Json(response).into_response()+ }Err(e) => ApiError::new(xerj_common::XerjError::from(e)).into_response(),}}diff --git a/engine/crates/xerj-api/tests/data_stream_rollover_conditions.rs b/engine/crates/xerj-api/tests/data_stream_rollover_conditions.rsnew file mode 100644index 000000000..084c1109d--- /dev/null+++ b/engine/crates/xerj-api/tests/data_stream_rollover_conditions.rs@@ -0,0 +1,281 @@+//! `POST /{data_stream}/_rollover` must honour its request body.+//!+//! The handler used to ignore the body completely: `dry_run: true` created a+//! backing index, `conditions` never blocked a rollover, and `old_index`+//! reported the data-stream name instead of the current backing index. A caller+//! asking "would this roll, and why?" got a real mutation and a misleading+//! answer.+//!+//! This pins the ES behavior for the conditions this build can evaluate:+//! `max_docs` and `max_age` are ORed and reported in a `conditions` map; the+//! candidate old/new backing index names are returned even when no roll+//! happens; a dry run and an unmet condition never create an index; and+//! unsupported conditions (`max_size`, ...) or alias-rollover body fields are+//! refused instead of silently ignored.+//!+//! 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;++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)+}++async fn call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(path);+ let body = if body.is_null() {+ Body::empty()+ } else {+ req = req.header("content-type", "application/json");+ Body::from(body.to_string())+ };+ let response = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ (+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ )+}++async fn create_stream(app: &axum::Router, name: &str) {+ let (status, body) = call(app, "PUT", &format!("/_data_stream/{name}"), Value::Null).await;+ assert_eq!(status, StatusCode::OK, "{body}");+}++async fn write_doc(app: &axum::Router, stream: &str, id: &str) {+ let (status, body) = call(+ app,+ "PUT",+ &format!("/{stream}/_doc/{id}"),+ json!({"@timestamp": "2026-11-03T00:00:00Z", "v": id}),+ )+ .await;+ assert_eq!(status, StatusCode::CREATED, "{body}");+}++async fn refresh(app: &axum::Router, stream: &str) {+ let (status, body) = call(app, "POST", &format!("/{stream}/_refresh"), Value::Null).await;+ assert_eq!(status, StatusCode::OK, "{body}");+}++/// `(generation, backing index names)`.+async fn stream_state(app: &axum::Router, stream: &str) -> (u64, Vec<String>) {+ let (status, body) = call(app, "GET", &format!("/_data_stream/{stream}"), Value::Null).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let ds = &body["data_streams"][0];+ (+ ds["generation"].as_u64().unwrap_or(0),+ ds["indices"]+ .as_array()+ .unwrap()+ .iter()+ .map(|i| i["index_name"].as_str().unwrap_or_default().to_string())+ .collect(),+ )+}++async fn rollover(app: &axum::Router, path: &str, body: Value) -> (StatusCode, Value) {+ call(app, "POST", path, body).await+}++fn reason(body: &Value) -> &str {+ body.pointer("/error/root_cause/0/reason")+ .and_then(Value::as_str)+ .or_else(|| body.get("error").and_then(Value::as_str))+ .unwrap_or_default()+}++#[tokio::test]+async fn dry_run_reports_candidate_without_creating() {+ let (app, _dir) = app().await;+ create_stream(&app, "ds").await;+ write_doc(&app, "ds", "1").await;+ refresh(&app, "ds").await;++ let (status, body) = rollover(&app, "/ds/_rollover", json!({"dry_run": true})).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["old_index"], ".ds-ds-000001", "{body}");+ assert_eq!(body["new_index"], ".ds-ds-000002", "{body}");+ assert_eq!(body["rolled_over"], false, "{body}");+ assert_eq!(body["dry_run"], true, "{body}");++ let (generation, indices) = stream_state(&app, "ds").await;+ assert_eq!(generation, 1);+ assert_eq!(indices, vec![".ds-ds-000001"]);+ let (status, _) = call(&app, "GET", "/.ds-ds-000002", Value::Null).await;+ assert_eq!(+ status,+ StatusCode::NOT_FOUND,+ "a dry run must not create the candidate backing index"+ );+}++#[tokio::test]+async fn dry_run_query_parameter_is_honoured() {+ let (app, _dir) = app().await;+ create_stream(&app, "ds").await;+ write_doc(&app, "ds", "1").await;+ refresh(&app, "ds").await;++ let (status, body) = rollover(&app, "/ds/_rollover?dry_run=true", json!({})).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["rolled_over"], false, "{body}");+ assert_eq!(body["dry_run"], true, "{body}");+ assert_eq!(stream_state(&app, "ds").await.0, 1);+}++#[tokio::test]+async fn max_docs_condition_blocks_then_rolls() {+ let (app, _dir) = app().await;+ create_stream(&app, "ds").await;+ write_doc(&app, "ds", "1").await;+ refresh(&app, "ds").await;++ let (status, body) = rollover(+ &app,+ "/ds/_rollover",+ json!({"conditions": {"max_docs": 2}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["rolled_over"], false, "{body}");+ assert_eq!(body["conditions"]["[max_docs: 2]"], false, "{body}");+ assert_eq!(body["old_index"], ".ds-ds-000001", "{body}");+ assert_eq!(body["new_index"], ".ds-ds-000002", "{body}");+ assert_eq!(stream_state(&app, "ds").await.0, 1);++ write_doc(&app, "ds", "2").await;+ refresh(&app, "ds").await;+ let (status, body) = rollover(+ &app,+ "/ds/_rollover",+ json!({"conditions": {"max_docs": 2}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["rolled_over"], true, "{body}");+ assert_eq!(body["conditions"]["[max_docs: 2]"], true, "{body}");+ assert_eq!(body["old_index"], ".ds-ds-000001", "{body}");+ assert_eq!(body["new_index"], ".ds-ds-000002", "{body}");++ let (generation, indices) = stream_state(&app, "ds").await;+ assert_eq!(generation, 2);+ assert_eq!(indices, vec![".ds-ds-000001", ".ds-ds-000002"]);++ // The data stream now writes to the new backing index.+ let (status, body) = call(+ &app,+ "PUT",+ "/ds/_doc/3",+ json!({"@timestamp": "2026-11-03T00:00:01Z"}),+ )+ .await;+ assert_eq!(status, StatusCode::CREATED, "{body}");+ assert_eq!(body["_index"], ".ds-ds-000002", "{body}");+}++#[tokio::test]+async fn max_age_condition() {+ let (app, _dir) = app().await;+ create_stream(&app, "ds").await;+ write_doc(&app, "ds", "1").await;+ refresh(&app, "ds").await;++ let (status, body) = rollover(+ &app,+ "/ds/_rollover",+ json!({"conditions": {"max_age": "1h"}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["rolled_over"], false, "{body}");+ assert_eq!(body["conditions"]["[max_age: 1h]"], false, "{body}");+ assert_eq!(stream_state(&app, "ds").await.0, 1);++ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ let (status, body) = rollover(+ &app,+ "/ds/_rollover",+ json!({"conditions": {"max_age": "1ms"}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["rolled_over"], true, "{body}");+ assert_eq!(body["conditions"]["[max_age: 1ms]"], true, "{body}");+ assert_eq!(stream_state(&app, "ds").await.0, 2);+}++#[tokio::test]+async fn conditions_are_ored() {+ let (app, _dir) = app().await;+ create_stream(&app, "ds").await;+ write_doc(&app, "ds", "1").await;+ refresh(&app, "ds").await;+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;++ let (status, body) = rollover(+ &app,+ "/ds/_rollover",+ json!({"conditions": {"max_docs": 100, "max_age": "1ms"}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["rolled_over"], true, "{body}");+ assert_eq!(body["conditions"]["[max_docs: 100]"], false, "{body}");+ assert_eq!(body["conditions"]["[max_age: 1ms]"], true, "{body}");+}++#[tokio::test]+async fn unsupported_conditions_and_body_fields_are_refused() {+ let (app, _dir) = app().await;+ create_stream(&app, "ds").await;+ write_doc(&app, "ds", "1").await;+ refresh(&app, "ds").await;++ let (status, body) = rollover(+ &app,+ "/ds/_rollover",+ json!({"conditions": {"max_size": "1gb"}}),+ )+ .await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");+ assert!(reason(&body).contains("max_size"), "{body}");+ assert_eq!(stream_state(&app, "ds").await.0, 1);++ let (status, body) = rollover(&app, "/ds/_rollover", json!({"new_index": "custom-name"})).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");+ assert!(reason(&body).contains("new_index"), "{body}");+ assert_eq!(stream_state(&app, "ds").await.0, 1);+}++#[tokio::test]+async fn plain_rollover_reports_backing_names() {+ let (app, _dir) = app().await;+ create_stream(&app, "ds").await;+ write_doc(&app, "ds", "1").await;+ refresh(&app, "ds").await;++ let (status, body) = rollover(&app, "/ds/_rollover", json!({})).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["old_index"], ".ds-ds-000001", "{body}");+ assert_eq!(body["new_index"], ".ds-ds-000002", "{body}");+ assert_eq!(body["rolled_over"], true, "{body}");+ assert_eq!(body["dry_run"], false, "{body}");+ let (generation, indices) = stream_state(&app, "ds").await;+ assert_eq!(generation, 2);+ assert_eq!(indices, vec![".ds-ds-000001", ".ds-ds-000002"]);+}diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex 148e4105a..1827ef017 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -4316,6 +4316,29 @@ impl Engine {Ok(())}+ /// Set (or clear) `is_write_index` on one alias member while preserving+ /// that member's filter/routing metadata.+ fn set_alias_write_flag(&self, index: &str, alias: &str, write: bool) {+ let mut entry = self+ .index_alias_metadata+ .entry(index.to_string())+ .or_insert_with(|| serde_json::json!({}));+ if !entry.is_object() {+ *entry = serde_json::json!({});+ }+ let aliases = entry.as_object_mut().expect("alias metadata object");+ let alias_meta = aliases+ .entry(alias.to_string())+ .or_insert_with(|| serde_json::json!({}));+ if !alias_meta.is_object() {+ *alias_meta = serde_json::json!({});+ }+ alias_meta+ .as_object_mut()+ .expect("alias metadata object")+ .insert("is_write_index".to_string(), serde_json::json!(write));+ }+/// 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 is@@ -4327,6 +4350,7 @@ impl Engine {.get_mut(name).ok_or_else(|| EngineError::Common(xerj_common::XerjError::index_not_found(name)))?;+ let previous_backings = ds.backing_indices.clone();ds.generation += 1;let new_backing = format!(".ds-{}-{:06}", name, ds.generation);drop(ds); // release borrow before calling create_index@@ -4344,6 +4368,17 @@ impl Engine {self.add_alias(name, &new_backing)?;}+ // Data-stream writes resolve through this alias, not a separate+ // stream-write path. With two members and no write flag the alias is+ // ambiguous, so the first write after the rollover used to answer 400+ // "no write index is defined". Mark the new backing as the writer and+ // clear every older member (preserving their filter/routing).+ for old_backing in &previous_backings {+ self.set_alias_write_flag(old_backing, name, false);+ }+ self.set_alias_write_flag(&new_backing, name, true);+ self.flush_alias_metadata();+if let Some(mut ds) = self.data_streams.get_mut(name) {ds.backing_indices.push(new_backing.clone());}