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): _reindex honours aliases on both sides
Tong-bit-art81cf4d1eb495
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 463ee8417..54f93be6f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -79,6 +79,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- `_reindex` follows aliases on both sides: a source alias is searched across+ every backing index and each member's alias filter is applied, and a+ destination alias writes to its single write index (an ambiguous alias is+ refused with `illegal_argument_exception`). Previously only the first+ backing index was read or written and filters were ignored, so the call+ reported success over the wrong data.+- `xerj autoindex` no longer runs out of memory while planning a large folder.It used to keep the sampled values of every file in memory at once beforegrouping them into datasets, and kept them all until the end of the run;diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 776236042..81ad610f0 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -28109,6 +28109,22 @@ pub struct ReindexDest {pub pipeline: Option<String>,}+/// The filter attached to `alias` on one backing index, if any. Alias+/// metadata is stored per (backing index, alias), so a multi-index alias can+/// carry a different filter on each member; a concrete source has no entry.+fn alias_filter_for(state: &AppState, backing: &str, alias: &str) -> Option<Value> {+ state+ .engine+ .index_alias_metadata+ .get(backing)+ .and_then(|v| {+ v.get(alias)+ .and_then(|meta| meta.get("filter"))+ .filter(|filter| !filter.is_null())+ .cloned()+ })+}+pub async fn reindex(State(state): State<AppState>,Json(body): Json<ReindexBody>,@@ -28152,7 +28168,16 @@ pub async fn reindex(}let source_name = &body.source.index;- let dest_name = &body.dest.index;+ // The destination may be an alias. ES routes a write through an alias to+ // its single write index and rejects an ambiguous alias;+ // `get_or_create_index` resolves an alias to its FIRST member, so the old+ // path copied the whole corpus into whichever member happened to be listed+ // first. Resolve before the pipeline check so a refused destination writes+ // nothing (not even a new index).+ let dest_name = match write_target_or_refusal(&state, &body.dest.index) {+ Ok(name) => name,+ Err(resp) => return resp,+ };// `dest.pipeline` is checked BEFORE a single document is copied. A name// that does not resolve, or one this build cannot run, fails the whole@@ -28190,36 +28215,16 @@ pub async fn reindex(};// Get or create destination index.- let dest_idx = match state.engine.get_or_create_index(dest_name) {- Ok(i) => i,- Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),- };-- // Fetch all docs from source via paginated search_after to handle large indices.- let source_idx = match state.engine.get_index(source_name) {+ let dest_idx = match state.engine.get_or_create_index(&dest_name) {Ok(i) => i,Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),};- // Flush the source memtable to segments before paging. `_id`-sorted- // `search_after` keyset pagination is correct over on-disk segments, but- // the in-memory memtable's field-sort path does NOT order by `_id`- // reliably, so un-flushed recent writes would be skipped or duplicated- // across pages. Reindex is a snapshot-style bulk op, so a single flush up- // front is an acceptable cost and makes the whole source keyset-pageable.- //- // Propagated, not swallowed, for the same reason as `clone_index_to`: the- // flush is a precondition of the paging being complete, so a failed flush- // must not be followed by a reindex that reports `"total": N` over a source- // it could not read consistently (issue #204).- if let Err(e) = source_idx.flush().await {- return ApiError::new(xerj_common::XerjError::internal(format!(- "reindex from [{source_name}] into [{dest_name}] was not attempted: flushing \- the source failed ({e}); the copy needs a flushed source to page over it \- without skipping or duplicating documents"- )))- .into_response();- }+ // `source.index` may be an index, alias, or data stream. For an alias ES+ // searches EVERY backing index and applies each member's alias filter;+ // `get_index` resolves an alias to its first member only, so the old path+ // silently copied a fraction of the alias and ignored its filters.+ let source_members = state.engine.resolve_alias(source_name);let query_val = body.source@@ -28239,138 +28244,186 @@ pub async fn reindex(let mut noops = 0usize;let mut failures: Vec<Value> = Vec::new();let mut batches = 0usize;- // Keyset cursor: `[last_id]` of the previous page (the sole sort key is- // `_id: asc`). `None` on the first page. This replaces `from`-offset- // paging, which silently truncated at `max_result_window` (~10k) once- // `from` exceeded the deep-paging limit.- let mut search_after: Option<Value> = None;- loop {- let mut search_body_val = json!({- "query": query_val,- "size": page_size,- "sort": [{ "_id": "asc" }],- // Reindex copies documents verbatim, so it must always read the- // COMPLETE `_source` — including engine-generated embedding- // companions. Omitting `_source` would inherit the search default,- // which deliberately hides those companions from ordinary API- // responses; inheriting it here would silently drop embeddings from- // every reindexed document.- "_source": true,- });- if let Some(ref sa) = search_after {- search_body_val["search_after"] = sa.clone();+ for source_member in &source_members {+ let source_idx = match state.engine.get_index(source_member) {+ Ok(i) => i,+ Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),+ };++ // Flush the member's memtable to segments before paging. `_id`-sorted+ // `search_after` keyset pagination is correct over on-disk segments,+ // but the in-memory memtable's field-sort path does NOT order by `_id`+ // reliably, so un-flushed recent writes would be skipped or duplicated+ // across pages. Reindex is a snapshot-style bulk op, so a flush up+ // front is an acceptable cost and makes the member keyset-pageable.+ //+ // Propagated, not swallowed, for the same reason as `clone_index_to`:+ // the flush is a precondition of the paging being complete, so a failed+ // flush must not be followed by a reindex that reports `"total": N` over+ // a source it could not read consistently (issue #204).+ if let Err(e) = source_idx.flush().await {+ return ApiError::new(xerj_common::XerjError::internal(format!(+ "reindex from [{source_name}] into [{dest_name}] was not attempted: flushing \+ the source failed ({e}); the copy needs a flushed source to page over it \+ without skipping or duplicating documents"+ )))+ .into_response();}- let search_req = match xerj_query::parse_request(&search_body_val)- .map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))- {- Ok(r) => r,- Err(e) => return ApiError::new(e).into_response(),+ // An alias filter is part of the source view. It is stored per+ // (backing index, alias), so a multi-index alias can filter each+ // member differently; a concrete source has no entry. AND the filter+ // with the caller's query (`must` + `filter`) so neither is ignored.+ let effective_query = match alias_filter_for(&state, source_member, source_name) {+ Some(filter) => json!({+ "bool": {+ "must": [query_val.clone()],+ "filter": [filter],+ }+ }),+ None => query_val.clone(),};- let results = match source_idx.search(&search_req).await {- Ok(r) => r,- Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),- };- // A script resource limit in `source.query` makes matching fail-closed,- // so this batch is a subset of the documents the caller asked to copy.- // Reporting a completed reindex over a silently truncated source is the- // same class of defect as a silently wrong score.- if let Some(reason) = &results.script_failure {- return script_limit_response(reason);- }+ // Keyset cursor: `[last_id]` of the previous page (the sole sort key+ // is `_id: asc`). Reset per member: ids are only ordered within one+ // index. This replaces `from`-offset paging, which silently truncated+ // at `max_result_window` (~10k) once `from` exceeded the deep-paging+ // limit.+ let mut search_after: Option<Value> = None;- let batch_size = results.hits.len();- if batch_size == 0 {- break;- }+ loop {+ let mut search_body_val = json!({+ "query": effective_query.clone(),+ "size": page_size,+ "sort": [{ "_id": "asc" }],+ // Reindex copies documents verbatim, so it must always read the+ // COMPLETE `_source` — including engine-generated embedding+ // companions. Omitting `_source` would inherit the search+ // default, which deliberately hides those companions from+ // ordinary API responses; inheriting it here would silently+ // drop embeddings from every reindexed document.+ "_source": true,+ });+ if let Some(ref sa) = search_after {+ search_body_val["search_after"] = sa.clone();+ }- batches += 1;- total_fetched += batch_size;+ let search_req = match xerj_query::parse_request(&search_body_val)+ .map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))+ {+ Ok(r) => r,+ Err(e) => return ApiError::new(e).into_response(),+ };- // Capture the keyset cursor before the `for` loop consumes `results.hits`.- let last_id = results.hits.last().map(|h| h.id.clone());+ let results = match source_idx.search(&search_req).await {+ Ok(r) => r,+ Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),+ };+ // A script resource limit in `source.query` makes matching fail-closed,+ // so this batch is a subset of the documents the caller asked to copy.+ // Reporting a completed reindex over a silently truncated source is the+ // same class of defect as a silently wrong score.+ if let Some(reason) = &results.script_failure {+ return script_limit_response(reason);+ }- for hit in results.hits {- if !hit.source.is_null() {- // `dest.pipeline`, if the request named one. Already known to- // exist and to be runnable (checked before any copy started),- // so anything that goes wrong here is a per-document failure- // and is reported as one — never a pass-through of the- // untransformed source.- let doc_source = match dest_pipeline.as_deref() {- None => hit.source,- Some(p) => match state.engine.process_through_pipeline(p, vec![hit.source]) {- Ok(mut results) if !results.is_empty() => {- let (action, transformed) = results.remove(0);- if matches!(action, xerj_wasm::pipeline::ProcessAction::Drop) {- // ES: a pipeline that drops the document does- // not write it, and the run reports a noop.- noops += 1;+ let batch_size = results.hits.len();+ if batch_size == 0 {+ break;+ }++ batches += 1;+ total_fetched += batch_size;++ // Capture the keyset cursor before the `for` loop consumes `results.hits`.+ let last_id = results.hits.last().map(|h| h.id.clone());++ for hit in results.hits {+ if !hit.source.is_null() {+ // `dest.pipeline`, if the request named one. Already known to+ // exist and to be runnable (checked before any copy started),+ // so anything that goes wrong here is a per-document failure+ // and is reported as one — never a pass-through of the+ // untransformed source.+ let doc_source = match dest_pipeline.as_deref() {+ None => hit.source,+ Some(p) => match state.engine.process_through_pipeline(p, vec![hit.source])+ {+ Ok(mut results) if !results.is_empty() => {+ let (action, transformed) = results.remove(0);+ if matches!(action, xerj_wasm::pipeline::ProcessAction::Drop) {+ // ES: a pipeline that drops the document does+ // not write it, and the run reports a noop.+ noops += 1;+ continue;+ }+ transformed+ }+ Ok(_) => {+ failures.push(json!({+ "id": hit.id,+ "cause": {+ "type": "reindex_error",+ "reason": format!(+ "pipeline [{p}] returned no document for [{}]",+ hit.id+ ),+ },+ }));continue;}- transformed- }+ Err(e) => {+ failures.push(json!({+ "id": hit.id,+ "cause": {+ "type": "reindex_error",+ "reason": format!("pipeline [{p}] failed: {e}"),+ },+ }));+ continue;+ }+ },+ };+ // Check if doc already exists in dest to track created vs updated.+ let exists = dest_idx+ .get_document(&hit.id)+ .await+ .ok()+ .flatten()+ .is_some();+ match dest_idx+ .index_document(Some(hit.id.clone()), doc_source)+ .await+ {Ok(_) => {- failures.push(json!({- "id": hit.id,- "cause": {- "type": "reindex_error",- "reason": format!(- "pipeline [{p}] returned no document for [{}]",- hit.id- ),- },- }));- continue;+ if exists {+ updated += 1;+ } else {+ created += 1;+ }}Err(e) => {failures.push(json!({"id": hit.id,- "cause": {- "type": "reindex_error",- "reason": format!("pipeline [{p}] failed: {e}"),- },+ "cause": { "type": "reindex_error", "reason": e.to_string() },}));- continue;- }- },- };- // Check if doc already exists in dest to track created vs updated.- let exists = dest_idx- .get_document(&hit.id)- .await- .ok()- .flatten()- .is_some();- match dest_idx- .index_document(Some(hit.id.clone()), doc_source)- .await- {- Ok(_) => {- if exists {- updated += 1;- } else {- created += 1;}}- Err(e) => {- failures.push(json!({- "id": hit.id,- "cause": { "type": "reindex_error", "reason": e.to_string() },- }));- }}}- }- // Advance the keyset cursor to the last `_id` of this page.- search_after = last_id.map(|id| json!([id]));+ // Advance the keyset cursor to the last `_id` of this page.+ search_after = last_id.map(|id| json!([id]));++ // Stop if we've reached the safety backstop or fetched fewer docs than+ // requested (meaning we hit the end of the source).+ if batch_size < page_size || total_fetched >= max_total {+ break;+ }+ }- // Stop if we've reached the safety backstop or fetched fewer docs than- // requested (meaning we hit the end of the source).- if batch_size < page_size || total_fetched >= max_total {+ if total_fetched >= max_total {break;}}diff --git a/engine/crates/xerj-api/tests/reindex_alias_semantics.rs b/engine/crates/xerj-api/tests/reindex_alias_semantics.rsnew file mode 100644index 000000000..24fad14df--- /dev/null+++ b/engine/crates/xerj-api/tests/reindex_alias_semantics.rs@@ -0,0 +1,244 @@+//! `_reindex` must honour aliases on both sides.+//!+//! Elasticsearch accepts an index, alias, or data stream as `source.index`.+//! A multi-index alias is searched across every backing index, and a filtered+//! alias adds its filter to that search. The destination may be an alias too;+//! writes route to its single write index, and an ambiguous alias is refused.+//!+//! Before this change `_reindex` called `get_index(source)` (which resolves an+//! alias to its FIRST backing index) and `get_or_create_index(dest)` (same+//! first-member rule). A reindex from a filtered two-index alias therefore+//! copied only the first index and ignored the filter, and a reindex into an+//! alias with `is_write_index` on the second member wrote the first member+//! anyway. Both answered 200, so the wrong data was silent.+//!+//! 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_keyword_index(app: &axum::Router, index: &str) {+ let (status, body) = call(+ app,+ "PUT",+ &format!("/{index}"),+ json!({"mappings": {"properties": {"k": {"type": "keyword"}}}}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+}++async fn doc(app: &axum::Router, index: &str, id: &str, k: &str) {+ let (status, body) = call(app, "PUT", &format!("/{index}/_doc/{id}"), json!({"k": k})).await;+ assert_eq!(status, StatusCode::CREATED, "{body}");+}++async fn alias(app: &axum::Router, index: &str, name: &str, body: Value) {+ let (status, response) = call(app, "PUT", &format!("/{index}/_alias/{name}"), body).await;+ assert_eq!(status, StatusCode::OK, "{response}");+}++async fn ids(app: &axum::Router, index: &str) -> Vec<String> {+ let (status, body) = call(app, "POST", &format!("/{index}/_refresh"), Value::Null).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let (status, body) = call(+ app,+ "POST",+ &format!("/{index}/_search"),+ json!({"size": 100}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let mut ids: Vec<String> = body["hits"]["hits"]+ .as_array()+ .unwrap()+ .iter()+ .map(|hit| hit["_id"].as_str().unwrap_or_default().to_string())+ .collect();+ ids.sort();+ ids+}++async fn count(app: &axum::Router, index: &str, query: Value) -> u64 {+ let (status, body) = call(app, "POST", &format!("/{index}/_refresh"), Value::Null).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let (status, body) = call(+ app,+ "POST",+ &format!("/{index}/_count"),+ json!({"query": query}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ body["count"].as_u64().unwrap_or(0)+}++async fn reindex(app: &axum::Router, source: &str, dest: &str) -> (StatusCode, Value) {+ call(+ app,+ "POST",+ "/_reindex",+ json!({"source": {"index": source}, "dest": {"index": dest}}),+ )+ .await+}++#[tokio::test]+async fn source_alias_reads_every_member_and_applies_each_members_filter() {+ let (app, _dir) = app().await;+ for index in ["i1", "i2"] {+ create_keyword_index(&app, index).await;+ }+ doc(&app, "i1", "1", "a").await;+ doc(&app, "i1", "2", "b").await;+ doc(&app, "i2", "3", "a").await;+ doc(&app, "i2", "4", "b").await;++ // Same alias, different filter per backing index: the source view is the+ // union of each member's own filtered subset.+ alias(&app, "i1", "mixed", json!({"filter": {"term": {"k": "a"}}})).await;+ alias(&app, "i2", "mixed", json!({"filter": {"term": {"k": "b"}}})).await;++ let (status, body) = reindex(&app, "mixed", "dst_mixed").await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["total"], 2, "{body}");+ assert_eq!(body["created"], 2, "{body}");+ assert_eq!(body["failures"], json!([]), "{body}");+ assert_eq!(ids(&app, "dst_mixed").await, vec!["1", "4"]);++ // A filter is applied to a one-index alias too: the old path used the+ // concrete index and copied every document.+ alias(+ &app,+ "i2",+ "only_b",+ json!({"filter": {"term": {"k": "b"}}}),+ )+ .await;+ let (status, body) = reindex(&app, "only_b", "dst_one").await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["total"], 1, "{body}");+ assert_eq!(ids(&app, "dst_one").await, vec!["4"]);+}++#[tokio::test]+async fn unfiltered_alias_reads_every_member() {+ let (app, _dir) = app().await;+ for index in ["i1", "i2"] {+ create_keyword_index(&app, index).await;+ }+ doc(&app, "i1", "1", "a").await;+ doc(&app, "i1", "2", "b").await;+ doc(&app, "i2", "3", "a").await;+ doc(&app, "i2", "4", "b").await;+ alias(&app, "i1", "all", json!({})).await;+ alias(&app, "i2", "all", json!({})).await;++ let (status, body) = reindex(&app, "all", "dst_all").await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["total"], 4, "{body}");+ assert_eq!(ids(&app, "dst_all").await, vec!["1", "2", "3", "4"]);+}++#[tokio::test]+async fn destination_alias_writes_its_write_index() {+ let (app, _dir) = app().await;+ create_keyword_index(&app, "source").await;+ doc(&app, "source", "1", "a").await;+ doc(&app, "source", "2", "b").await;+ for index in ["d1", "d2"] {+ create_keyword_index(&app, index).await;+ }+ let (status, body) = call(+ &app,+ "POST",+ "/_aliases",+ json!({"actions": [+ {"add": {"index": "d1", "alias": "dst"}},+ {"add": {"index": "d2", "alias": "dst", "is_write_index": true}},+ ]}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");++ let (status, body) = reindex(&app, "source", "dst").await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["total"], 2, "{body}");+ assert_eq!(body["created"], 2, "{body}");+ assert_eq!(count(&app, "d1", json!({"match_all": {}})).await, 0);+ assert_eq!(count(&app, "d2", json!({"match_all": {}})).await, 2);+ let (status, body) = call(&app, "GET", "/d2/_doc/1", Value::Null).await;+ assert_eq!(status, StatusCode::OK, "{body}");+}++#[tokio::test]+async fn ambiguous_destination_alias_is_refused_before_any_copy() {+ let (app, _dir) = app().await;+ create_keyword_index(&app, "source").await;+ doc(&app, "source", "1", "a").await;+ for index in ["d1", "d2"] {+ create_keyword_index(&app, index).await;+ }+ let (status, body) = call(+ &app,+ "POST",+ "/_aliases",+ json!({"actions": [+ {"add": {"index": "d1", "alias": "amb"}},+ {"add": {"index": "d2", "alias": "amb"}},+ ]}),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");++ let (status, body) = reindex(&app, "source", "amb").await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");+ assert_eq!(+ body.pointer("/error/type").and_then(Value::as_str),+ Some("illegal_argument_exception"),+ "{body}"+ );+ let reason = body+ .pointer("/error/root_cause/0/reason")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ reason.contains("no write index is defined for alias [amb]"),+ "{body}"+ );+ assert_eq!(count(&app, "d1", json!({"match_all": {}})).await, 0);+ assert_eq!(count(&app, "d2", json!({"match_all": {}})).await, 0);+}