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): POST /_aliases stores and enforces alias metadata (#2319)
ordinary being6e97380b5a1e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3b7f6a59c..eaabf02d1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -142,6 +142,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0snippets at the same citation. Rendered text is deduped only when both itslocator and displayed passage match an already-shown block; display labels,separators and match citations no longer stand in for source ranges.+- `POST /_aliases` stores the alias metadata it is given: `filter`, routing,+ `is_write_index` and `is_hidden`. Those fields were dropped by the action+ parser, so a filtered alias created through the standard API exposed every+ document while the same alias created with `PUT /{index}/_alias/{name}`+ worked; `_cat/aliases` also printed `-` for the filter. Removing an alias (or+ re-adding it without a filter) now clears the stored metadata, so a stale+ filter cannot outlive its definition.- x86_64 release binaries no longer require AVX2. The build baseline is`x86-64-v2` (SSE4.2). The HNSW eight-accumulator dot product — the kerneldiff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex be45777ae..f1468b268 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -25110,6 +25110,98 @@ pub struct AliasAction {pub struct AliasActionParams {pub index: String,pub alias: String,+ /// `POST /_aliases` carries the same per-alias metadata `PUT+ /// /{index}/_alias/{name}` does. These used to be missing from this struct,+ /// so serde silently discarded them and a filtered alias created through+ /// the standard action API exposed every document.+ #[serde(default)]+ pub filter: Option<Value>,+ #[serde(default)]+ pub routing: Option<Value>,+ #[serde(default)]+ pub index_routing: Option<Value>,+ #[serde(default)]+ pub search_routing: Option<Value>,+ #[serde(default)]+ pub is_write_index: Option<bool>,+ #[serde(default)]+ pub is_hidden: Option<bool>,+}++/// The metadata object `PUT /{index}/_alias/{name}` and `POST /_aliases` both+/// persist for an alias. Empty means "no metadata" (and clears any stale+/// entry on a re-add).+fn alias_action_meta(add: &AliasActionParams) -> Value {+ let mut obj = serde_json::Map::new();+ if let Some(v) = &add.filter {+ obj.insert("filter".to_string(), v.clone());+ }+ if let Some(v) = &add.routing {+ obj.insert("routing".to_string(), v.clone());+ }+ if let Some(v) = &add.index_routing {+ obj.insert("index_routing".to_string(), v.clone());+ }+ if let Some(v) = &add.search_routing {+ obj.insert("search_routing".to_string(), v.clone());+ }+ if let Some(v) = add.is_write_index {+ obj.insert("is_write_index".to_string(), Value::Bool(v));+ }+ if let Some(v) = add.is_hidden {+ obj.insert("is_hidden".to_string(), Value::Bool(v));+ }+ Value::Object(obj)+}++/// Replace (or clear, for empty metadata) one alias's metadata on one index+/// and persist it. Clearing matters: re-adding an alias without a filter must+/// not leave the previous filter enforced.+fn store_alias_meta(state: &AppState, index: &str, alias: &str, meta: &Value) {+ let mut existing = state+ .engine+ .index_alias_metadata+ .get(index)+ .map(|v| v.clone())+ .unwrap_or_else(|| json!({}));+ if !existing.is_object() {+ existing = json!({});+ }+ if let Some(obj) = existing.as_object_mut() {+ if meta.as_object().map(|o| o.is_empty()).unwrap_or(true) {+ obj.remove(alias);+ } else {+ obj.insert(alias.to_string(), meta.clone());+ }+ }+ state+ .engine+ .index_alias_metadata+ .insert(index.to_string(), existing);+ state.engine.flush_alias_metadata();+}++/// Drop one alias's stored metadata after the alias itself was removed.+fn clear_alias_meta(state: &AppState, index: &str, alias: &str) {+ let Some(mut existing) = state+ .engine+ .index_alias_metadata+ .get(index)+ .map(|v| v.clone())+ else {+ return;+ };+ let Some(obj) = existing.as_object_mut() else {+ return;+ };+ if obj.remove(alias).is_none() {+ return;+ }+ state+ .engine+ .index_alias_metadata+ .insert(index.to_string(), existing);+ state.engine.flush_alias_metadata();}#[derive(Debug, Deserialize)]@@ -25178,10 +25270,15 @@ pub async fn post_aliases(for step in &plan {match step {Resolved::Add(add, targets) => {+ let meta = alias_action_meta(add);+ if let Some(reason) = alias_value_type_error(&add.alias, &meta) {+ return es_bad_request("illegal_argument_exception", &reason, None);+ }for target in targets {if let Err(error) = state.engine.add_alias(&add.alias, target) {return ApiError::new(xerj_common::XerjError::from(error)).into_response();}+ store_alias_meta(&state, target, &add.alias, &meta);}}Resolved::Remove(remove, targets) => {@@ -25189,6 +25286,7 @@ pub async fn post_aliases(if let Err(error) = state.engine.remove_alias(&remove.alias, target) {return ApiError::new(xerj_common::XerjError::from(error)).into_response();}+ clear_alias_meta(&state, target, &remove.alias);}}}@@ -25478,24 +25576,9 @@ pub async fn put_alias(let attach = |idx_name: &str| -> xerj_engine::Result<()> {state.engine.add_alias(&alias, idx_name)?;- if !alias_meta.as_object().map(|o| o.is_empty()).unwrap_or(true) {- let mut existing = state- .engine- .index_alias_metadata- .get(idx_name)- .map(|v| v.clone())- .unwrap_or(json!({}));- if let Some(obj) = existing.as_object_mut() {- obj.insert(alias.clone(), alias_meta.clone());- } else {- existing = json!({ alias.clone(): alias_meta.clone() });- }- state- .engine- .index_alias_metadata- .insert(idx_name.to_string(), existing);- state.engine.flush_alias_metadata();- }+ // Re-putting an alias replaces its definition: an empty body clears a+ // previous filter instead of leaving it enforced.+ store_alias_meta(&state, idx_name, &alias, &alias_meta);Ok(())};@@ -25528,11 +25611,13 @@ pub async fn delete_alias(if let Err(error) = state.engine.remove_alias(&alias, &index) {return ApiError::new(xerj_common::XerjError::from(error)).into_response();}+ clear_alias_meta(&state, &index, &alias);} else {for idx in &targets {if let Err(error) = state.engine.remove_alias(&alias, idx) {return ApiError::new(xerj_common::XerjError::from(error)).into_response();}+ clear_alias_meta(&state, idx, &alias);}}Json(json!({ "acknowledged": true })).into_response()@@ -32417,17 +32502,44 @@ pub async fn cat_aliases(}}+ // `_cat/aliases` used to print a literal `-` for every metadata column, so+ // a filtered alias created by `POST /_aliases` (or PUT …/_alias/…) looked+ // unfiltered here even after the read paths honoured the filter. `*` is+ // ES's text/JSON rendering for "this alias has a filter".+ let cat_cell = |meta: &Value, key: &str| -> String {+ match meta.get(key) {+ None | Some(Value::Null) => "-".to_string(),+ Some(Value::String(s)) => s.clone(),+ Some(other) => other.to_string(),+ }+ };+ let render = |alias: &str, index: &str| -> (String, String, String, String) {+ let meta = alias_meta_for(&state, index, alias);+ let filter = if meta.get("filter").is_some() {+ "*".to_string()+ } else {+ "-".to_string()+ };+ (+ filter,+ cat_cell(&meta, "index_routing"),+ cat_cell(&meta, "search_routing"),+ cat_cell(&meta, "is_write_index"),+ )+ };+if params.format.as_deref() == Some("json") {let arr: Vec<Value> = rows.iter().map(|(alias, index)| {+ let (filter, ri, rs, iw) = render(alias, index);json!({"alias": alias,"index": index,- "filter": "-",- "routing.index": "-",- "routing.search": "-",- "is_write_index": "-",+ "filter": filter,+ "routing.index": ri,+ "routing.search": rs,+ "is_write_index": iw,})}).collect();@@ -32436,7 +32548,10 @@ pub async fn cat_aliases(let lines: Vec<String> = rows.iter()- .map(|(alias, index)| format!("{alias} {index} - - - -"))+ .map(|(alias, index)| {+ let (filter, ri, rs, iw) = render(alias, index);+ format!("{alias} {index} {filter} {ri} {rs} {iw}")+ }).collect();let body = if lines.is_empty() {String::new()diff --git a/engine/crates/xerj-api/tests/post_aliases_filter_is_stored_and_enforced.rs b/engine/crates/xerj-api/tests/post_aliases_filter_is_stored_and_enforced.rsnew file mode 100644index 000000000..ddaa71d67--- /dev/null+++ b/engine/crates/xerj-api/tests/post_aliases_filter_is_stored_and_enforced.rs@@ -0,0 +1,266 @@+//! `POST /_aliases` must persist the alias metadata it is given.+//!+//! `AliasActionParams` used to carry only `index` and `alias`, so serde+//! silently discarded `filter` (and routing / is_write_index). The requested+//! alias was created, `acknowledged: true` came back, and every read through it+//! exposed the whole backing index — a filtered alias is the standard+//! poor-man's document boundary, so that is a data leak, not a cosmetic one.+//!+//! The standard action API now stores the same metadata `PUT+//! /{index}/_alias/{name}` does, persists it, and removes it on `remove` (or+//! when an alias is re-added without a filter) so a stale filter cannot+//! outlive its definition.+//!+//! 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+}++fn app_over(dir: &std::path::Path) -> axum::Router {+ 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);+ xerj_api::router::build_es_compat_router(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");+ let body = if bytes.is_empty() {+ Value::Null+ } else {+ serde_json::from_slice(&bytes).unwrap_or(Value::Null)+ };+ (status, body)+}++fn json_req(method: &str, path: &str, body: Value) -> Request<Body> {+ Request::builder()+ .method(method)+ .uri(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request")+}++async fn get(app: &axum::Router, path: &str) -> (StatusCode, Value) {+ send(+ app,+ Request::get(path).body(Body::empty()).expect("request"),+ )+ .await+}++async fn post(app: &axum::Router, path: &str, body: Value) -> (StatusCode, Value) {+ send(app, json_req("POST", path, body)).await+}++async fn put(app: &axum::Router, path: &str, body: Value) -> (StatusCode, Value) {+ send(app, json_req("PUT", path, body)).await+}++async fn seed(app: &axum::Router) {+ let (status, body) = put(+ app,+ "/di",+ json!({"mappings": {"properties": {"k": {"type": "keyword"}}}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ for (id, k) in [("1", "a"), ("2", "a"), ("3", "b")] {+ let (status, body) = put(app, &format!("/di/_doc/{id}"), json!({"k": k})).await;+ assert!(status.is_success(), "{body}");+ }+ let (status, body) = post(app, "/di/_refresh", Value::Null).await;+ assert_eq!(status, StatusCode::OK, "{body}");+}++async fn search_total(app: &axum::Router, index: &str, body: Value) -> u64 {+ let (status, resp) = post(app, &format!("/{index}/_search"), body).await;+ assert_eq!(status, StatusCode::OK, "{resp}");+ resp["hits"]["total"]["value"].as_u64().unwrap_or(0)+}++async fn count(app: &axum::Router, index: &str, body: Value) -> u64 {+ let (status, resp) = post(app, &format!("/{index}/_count"), body).await;+ assert_eq!(status, StatusCode::OK, "{resp}");+ resp["count"].as_u64().unwrap_or(0)+}++async fn add_filtered_alias(app: &axum::Router) {+ let (status, body) = post(+ app,+ "/_aliases",+ json!({"actions": [{"add": {+ "index": "di",+ "alias": "da",+ "filter": {"term": {"k": "a"}},+ }}]}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["acknowledged"], true, "{body}");+}++#[tokio::test]+async fn post_aliases_filter_is_stored_and_enforced() {+ let dir = tempfile::tempdir().expect("tempdir");+ let app = app_over(dir.path());+ seed(&app).await;+ add_filtered_alias(&app).await;++ // The definition itself: metadata came back rather than `-`.+ let (status, body) = get(&app, "/_alias/da").await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(+ body.pointer("/di/aliases/da/filter"),+ Some(&json!({"term": {"k": "a"}})),+ "the filter must be part of the alias definition: {body}"+ );+ let (status, body) = get(&app, "/_cat/aliases?format=json&h=alias,index,filter").await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert!(+ !body[0]["filter"].as_str().unwrap_or_default().contains('-'),+ "cat/aliases must render the filter, not `-`: {body}"+ );++ // Every read path that resolves an alias must honour the slice.+ assert_eq!(+ search_total(&app, "da", json!({"size": 0, "query": {"match_all": {}}})).await,+ 2,+ "the alias exposes only k=a"+ );+ assert_eq!(+ count(&app, "da", json!({"query": {"match_all": {}}})).await,+ 2+ );+ assert_eq!(+ search_total(+ &app,+ "da",+ json!({"size": 0, "query": {"term": {"k": "b"}}})+ )+ .await,+ 0,+ "a document outside the filter must not be reachable through the alias"+ );++ // The msearch alias path shares the same metadata.+ let response = app+ .clone()+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/_msearch")+ .header("content-type", "application/x-ndjson")+ .body(Body::from(+ "{\"index\":\"da\"}\n{\"size\":0,\"query\":{\"match_all\":{}}}\n".to_string(),+ ))+ .expect("request"),+ )+ .await+ .expect("response");+ let body: Value = serde_json::from_slice(+ &axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap(),+ )+ .unwrap();+ assert_eq!(body["responses"][0]["hits"]["total"]["value"], 2, "{body}");+}++#[tokio::test]+async fn post_aliases_filter_survives_restart_and_is_removed_with_the_alias() {+ let dir = tempfile::tempdir().expect("tempdir");+ {+ let app = app_over(dir.path());+ seed(&app).await;+ add_filtered_alias(&app).await;+ assert_eq!(+ search_total(&app, "da", json!({"size": 0, "query": {"match_all": {}}})).await,+ 2+ );+ }++ // Fresh engine, same data dir: only what reached disk is visible.+ let app = app_over(dir.path());+ let (status, body) = get(&app, "/_alias/da").await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(+ body.pointer("/di/aliases/da/filter"),+ Some(&json!({"term": {"k": "a"}})),+ "the POST /_aliases filter must be persisted: {body}"+ );+ assert_eq!(+ search_total(&app, "da", json!({"size": 0, "query": {"match_all": {}}})).await,+ 2,+ "the persisted filter must still be enforced"+ );++ // Remove the alias: its metadata must go with it, so re-adding the alias+ // without a filter exposes the whole index instead of a stale slice.+ let (status, body) = post(+ &app,+ "/_aliases",+ json!({"actions": [{"remove": {"index": "di", "alias": "da"}}]}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let (status, body) = get(&app, "/_alias/da").await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert!(+ body.get("di").is_none(),+ "the removed alias must be gone: {body}"+ );+ let (status, body) = post(+ &app,+ "/_aliases",+ json!({"actions": [{"add": {"index": "di", "alias": "da"}}]}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(+ search_total(&app, "da", json!({"size": 0, "query": {"match_all": {}}})).await,+ 3,+ "a re-added alias without a filter is not filtered"+ );+}++#[tokio::test]+async fn re_putting_an_alias_without_a_body_clears_its_filter() {+ let dir = tempfile::tempdir().expect("tempdir");+ let app = app_over(dir.path());+ seed(&app).await;+ let (status, body) = put(+ &app,+ "/di/_alias/da",+ json!({"filter": {"term": {"k": "a"}}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(+ search_total(&app, "da", json!({"size": 0, "query": {"match_all": {}}})).await,+ 2+ );+ let (status, body) = put(&app, "/di/_alias/da", json!({})).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(+ search_total(&app, "da", json!({"size": 0, "query": {"match_all": {}}})).await,+ 3,+ "an empty re-put replaces the alias definition, filter included"+ );+}