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
Resolve reindex aliases and preflight every source before copying
xerj-org11adab4ef80d
diff --cc CHANGELOG.mdindex e23026de6,b3c0eed2d..d93c6a1e7--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,99 -7,6 +7,103 @@@ and this project adheres to [Semantic V## [Unreleased]+### Added++- Corpus Hub manifest `paths` entries may name regular files as well as+ directories (#2486). A file selection checks out that file without its+ siblings; symlinks and submodules are refused.++- MCP `xerj_status` reports node reachability, cluster health and visible+ indices before a search. It distinguishes a missing autoindex catalog from+ other indexed data and preserves failed or malformed probes as errors+ rather than reporting a successful empty node (#2515).++- Empty autoindex maps now explain that managed corpus slugs and autoindex+ dataset/index names belong to separate discovery surfaces. CLI diagnostics,+ MCP empty responses and the `xerj_map` description point to corpus discovery+ without claiming a corpus exists. Missing catalogs remain errors; auth+ refusals and successful dataset maps retain their behavior (#2412).++- Public Agent Skills Discovery v0.2.0 index and a documentation-routing skill+ at `/.well-known/agent-skills/`. The index is generated from the published+ skill's metadata and exact-byte SHA-256, with a CI drift check.++### Fixed+++- Reindex preflights every source alias member before creating or writing the++ destination. Aliases cannot hide a source/destination overlap; a missing++ source, invalid query or source flush failure leaves destination data intact.+++- Corpus cloning validates existing checkouts and serializes writers (#2453).+ New checkouts are staged before publication. Ambiguous existing directories+ are preserved for recovery rather than deleted or reset automatically.++- MCP `xerj_search` advertises plain text in `query` and structured clauses+ in `query_dsl`. Legacy object-valued `query` and omitted-query browsing+ remain supported; conflicting fields fail before HTTP requests (#2549).+- Search payloads and batch retrieval default to 8,000 UAX #29 words when+ `max_tokens` is absent or null (#2491). This is not a byte or model-token+ cap. Explicit larger budgets remain available; errors and mandatory+ search staleness hints stay outside the payload budget.+- GitHub field-report submission uses the supported explicit-repository+ `gh repo fork --clone=false` invocation and adds the fork remote itself+ (#2596). The rollback test now verifies that the report was committed+ before a failed push, rather than passing after an earlier fork failure.+- Local admin-key discovery reports the source of the selected key and warns+ when its directory is outside the working tree (#2578). Packaged installs+ have their own provenance, and MCP guidance names `XERJ_AUTH`. Discovery+ priority and explicit credential overrides are unchanged.++- `xerj autoindex` fails a run when one dataset index holds no documents+ although the journal says records were written to it, even when the other+ datasets are live (#2407, defect 2). The check summed live documents over+ every dataset, so a populated `-json` index let a re-run print `ok: indexed+ and searchable` over an empty `-docs` index. The error names each empty+ index and its contributing files; record totals are reported only when+ those files target that dataset alone. Unknown sibling counts do not hide+ independently confirmed missing data.+- SQL source extraction no longer slices statement heads inside a UTF-8+ character, so unrecognized CJK statement/comment heads do not panic (#2547).+- Short Markdown files with YAML frontmatter retain their prose body even+ when bullets or `Key: value` lines also parse as YAML (#2447). Existing+ frontmatter-title behavior and structured CSV/JSON body detection remain.+- Empty files keep separate inventory identities instead of being reported+ as content duplicates of unrelated paths (#2449). Non-empty byte-identical+ files still deduplicate.+- A search with both `query` and a top-level `knn` returns `size` hits, not+ `k` (#2561). The page was widened to `k`, so `size: 5, k: 20` returned+ 20 hits. `k` still sets how many nearest neighbours join the candidate+ set, and `from`/`size` page through the union, as in Elasticsearch.+- Index deletion no longer waits for unrelated index statistics while+ resolving its selectors. Index listings and health checks also release+ their index-map locks before awaiting statistics, so a stalled schema+ update does not hold those locks against DELETE (part of #2405; extracted+ from #2489). Merge/flush cancellation and the process memory cap remain+ separate follow-ups.+- `xerj autoindex` compresses per-file phase-B stages with zstd level 1 and+ uses temporary files cleaned up by the operating system when the client+ exits (#2493, part of #2427). It finishes buffered compression before+ deleting previous records, so a stage finalization error preserves the old+ records and an ordinary resume can complete the replacement. Compression+ savings depend on the data; this does not impose a disk or server-memory cap.+- `autoindex` bulk back-pressure patience is now measured since the last+ progress, not since the first round. A window the server drains a few+ records at a time (per-item 429 `resource_exhausted` on an embedding+ deadline or admission refusal) used to abort with `bulk backend failed`+ once the rounds together passed the 600 s `THROTTLE_PATIENCE`, even though+ every round settled records. Each round that settles at least one item now+ restarts the patience clock and the backoff; rounds that settle nothing+ still count, so a server that answers 429 forever fails at the same limits+ as before.+- `xerj autoindex` titles a prose file that opens with YAML frontmatter from+ its `title:` key, or from the first line after the closing `---` when there+ is none (#2556). Every such file (Jekyll, Hugo, Obsidian) used to be titled+ `---`, its opening fence. A leading `---` block that is not parseable+ frontmatter (unclosed, not a YAML mapping, over 64 KiB) takes the first line+ that is not a bare `---`; the body, the frontmatter text in it and+ `start_line` are unchanged. An unchanged file is not re-extracted, so re-index+ with `xerj autoindex --fresh` to retitle documents already in an index.+## [1.0.0-rc.100] - 2026-10-26**rc.100: faster autoindex and search, shaped by your field reports.** This@@@ -248,30 -147,12 +252,36 @@@ continues in #2427 and #1122, which sta### Fixed+- A `semantic_text` field declared without `dimensions` is now sized at the+ width the server's embedding backend actually produces, when that width is+ confirmed (#2407, defect 1). It used to be always 384, so behind a `proxy`+ returning another width (768, 1024, …) every document failed ingest with+ "embedding backend returned width N, mapping requires 384", and the new+ index stayed green with no semantic documents. Index creation,+ `PUT _mapping` and templates (including indices that `_bulk` creates+ automatically) write the width into the mapping, so `GET _mapping` shows it.+ An explicit `dimensions` still wins. Indices created before this change keep+ their stored 384 mapping. Re-declaring a bare `semantic_text` on one of them+ while running a backend of another width is now refused by the immutable+ embedding contract. When the width cannot be confirmed, the field is still+ sized at 384, and the server logs a warning.++- `xerj search` names an unknown flag on one line and exits 2 instead of+ following "unexpected argument" with the whole usage text (#2458). An+ agent that guessed `--index` and `--max-hits` read the help dump as the+ answer and gave up on the CLI. Those guesses, and `--size`, `--limit`,+ `--top`, `--top-k`, `-n` and `-i`, now point at `--prefix <P>` or+ `-k <N>`.+- `xerj_batch_search` (and `xerj batch-search`) accept a plain string in+ `queries` as shorthand for `{"query": <string>}` (#2497). A string item+ used to fail alone with "arguments must be a JSON object", so an agent+ that sent `["a", "b"]` lost a call; the advertised schema now allows it.+ - `_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 corpus add` accepts a local Windows path such as`F:\Projects\Foo` (#2472). The repo name was the text after the last `/`,diff --cc engine/crates/xerj-api/src/es_compat.rsindex 304dead05,063f2d322..a3bc15f4a--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@@ -28369,38 -28308,18 +28394,27 @@@ pub async fn reindex}};-- // Get or create destination index.- let dest_idx = match state.engine.get_or_create_index(dest_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(),-- };--- // Fetch all docs from source via paginated search_after to handle large indices.- let source_idx = match state.engine.get_index(source_name) {- Ok(i) => i,- Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).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);- // 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();++ // Compare concrete identities: aliases must not hide a self-copy, which++ // can rewrite source documents or copy earlier members into later ones.++ if source_members.contains(&dest_name) {++ let reason = format!("reindex cannot read and write the same index [{dest_name}]");++ return (++ StatusCode::BAD_REQUEST,++ Json(json!({++ "error": {"type": "illegal_argument_exception", "reason": reason,++ "root_cause": [{"type": "illegal_argument_exception", "reason": reason}]},++ "status": 400++ })),++ )++ .into_response();+ }+let query_val = body.source.query@@@ -28413,144 -28332,192 +28427,183 @@@// on a pathologically large source, well above any realistic reindex.let max_total = 10_000_000usize;-- let mut total_fetched = 0usize;-- let mut created = 0usize;-- let mut updated = 0usize;-- 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;-++ let mut prepared_sources = Vec::with_capacity(source_members.len());+ 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(),+ };- loop {- let mut search_body_val = json!({- "query": query_val,- // 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();- }-+ // 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(),+ };+- // 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;++ // Parse every member's effective query before any source flush or++ // destination creation. Keep that exact plan for its paging loop.++ let search_req = match xerj_query::parse_request(&json!({++ "query": effective_query,+ "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.++ // Copies must retain engine-generated vector companions too.+ "_source": true,- });- if let Some(ref sa) = search_after {- search_body_val["search_after"] = sa.clone();- }-- let search_req = match xerj_query::parse_request(&search_body_val)- .map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))++ }))++ .map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))+ {+ Ok(r) => r,+ Err(e) => return ApiError::new(e).into_response(),+ };-- 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);++ prepared_sources.push((source_member, source_idx, search_req));++ }+- 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();- }++ // Every member must be pageable before the first destination write. A++ // later member's flush failure must not leave an undisclosed partial copy.++ // A flush changes storage layout, not source documents; retry is safe.++ for (source_member, source_idx, _) in &prepared_sources {++ 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 \++ source member [{source_member}] failed ({e}); destination documents were \++ not changed; fix the source storage error and retry"++ )))++ .into_response();+ }++ }- let batch_size = results.hits.len();- if batch_size == 0 {- break;- }- 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(),- };++ // 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(),++ };+++ let mut total_fetched = 0usize;++ let mut created = 0usize;++ let mut updated = 0usize;++ let mut noops = 0usize;++ let mut failures: Vec<Value> = Vec::new();++ let mut batches = 0usize;++++ for (_, source_idx, mut search_req) in prepared_sources {++ // IDs are ordered only within one source member. Each parsed plan++ // starts with no cursor and advances after its own completed page.++ loop {+ 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);+ }- 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;+ 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]));++ search_req.search_after = last_id.map(|id| vec![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 --cc engine/crates/xerj-api/tests/reindex_alias_semantics.rsindex 000000000,24fad14df..9a0a79a4fmode 000000,100644..100644--- a/engine/crates/xerj-api/tests/reindex_alias_semantics.rs+++ b/engine/crates/xerj-api/tests/reindex_alias_semantics.rs@@@ -1,0 -1,244 +1,359 @@@+ //! `_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);+ }++++#[tokio::test]++async fn overlapping_alias_destination_is_refused_without_rewriting_source() {++ let (app, _dir) = app().await;++ for index in ["first", "second"] {++ create_keyword_index(&app, index).await;++ doc(&app, index, index, index).await;++ alias(&app, index, "both", json!({})).await;++ }++ alias(&app, "second", "write_second", json!({})).await;++ let before = call(&app, "GET", "/second/_doc/second", Value::Null).await;++ for (source, dest) in [++ ("both", "second"),++ ("both", "write_second"),++ ("second", "second"),++ ] {++ let (status, body) = reindex(&app, source, dest).await;++ assert_eq!(++ status,++ StatusCode::BAD_REQUEST,++ "{source} -> {dest}: {body}"++ );++ assert!(++ body["error"]["reason"]++ .as_str()++ .unwrap()++ .contains("same index"),++ "{body}"++ );++ assert_eq!(++ call(&app, "GET", "/second/_doc/second", Value::Null).await,++ before++ );++ assert_eq!(ids(&app, "second").await, vec!["second"]);++ }++ let (status, body) = reindex(&app, "both", "separate").await;++ assert_eq!(status, StatusCode::OK, "{body}");++ assert_eq!(ids(&app, "separate").await, vec!["first", "second"]);++}++++#[tokio::test]++async fn missing_source_or_invalid_query_does_not_create_destination() {++ let (app, _dir) = app().await;++ let (status, body) = reindex(&app, "missing", "new_destination").await;++ assert_eq!(status, StatusCode::NOT_FOUND, "{body}");++ assert_eq!(++ call(&app, "GET", "/new_destination", Value::Null).await.0,++ StatusCode::NOT_FOUND++ );++ create_keyword_index(&app, "source").await;++ doc(&app, "source", "one", "a").await;++ let (status, body) = call(++ &app,++ "POST",++ "/_reindex",++ json!({++ "source":{"index":"source", "query":{"not_a_query":{}}},++ "dest":{"index":"new_destination"}++ }),++ )++ .await;++ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");++ assert_eq!(++ call(&app, "GET", "/new_destination", Value::Null).await.0,++ StatusCode::NOT_FOUND++ );++ let (status, body) = reindex(&app, "source", "new_destination").await;++ assert_eq!(status, StatusCode::OK, "{body}");++ assert_eq!(ids(&app, "new_destination").await, vec!["one"]);++}++++#[tokio::test]++async fn later_member_flush_failure_keeps_destination_unchanged_and_can_retry() {++ let (app, dir) = app().await;++ for index in ["first", "second"] {++ create_keyword_index(&app, index).await;++ doc(&app, index, index, "a").await;++ alias(&app, index, "both", json!({})).await;++ }++ create_keyword_index(&app, "destination").await;++ doc(&app, "destination", "existing", "keep").await;++ let before = call(&app, "GET", "/destination/_doc/existing", Value::Null).await;++ // Real I/O refusal, independent of permissions and test-only failpoints.++ let segments = dir.path().join("second/segments");++ std::fs::remove_dir(&segments).unwrap();++ std::fs::write(&segments, b"not a directory").unwrap();++ let (status, body) = reindex(&app, "both", "destination").await;++ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}");++ assert!(body.to_string().contains("flushing"), "{body}");++ assert_eq!(++ ids(&app, "destination").await,++ vec!["existing"],++ "a failed preflight must not copy earlier members"++ );++ assert_eq!(++ call(&app, "GET", "/destination/_doc/existing", Value::Null).await,++ before++ );++ for index in ["first", "second"] {++ assert_eq!(++ call(&app, "GET", &format!("/{index}/_doc/{index}"), Value::Null)++ .await++ .0,++ StatusCode::OK++ );++ }++ std::fs::remove_file(&segments).unwrap();++ std::fs::create_dir(&segments).unwrap();++ let (status, body) = reindex(&app, "both", "destination").await;++ assert_eq!(status, StatusCode::OK, "{body}");++ assert_eq!(++ ids(&app, "destination").await,++ vec!["existing", "first", "second"]++ );++}