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
feat(cluster): route native document writes to the shard primary (#2380)
xerj-org36c7a90879f0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ef5f93a8..07b2dacaa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- With `[cluster] enabled = true`, `POST /v1/indices/{name}/docs` (one+ document, or a JSON array with one document per element),+ `DELETE /v1/indices/{name}/docs/{id}`, and+ `POST /v1/indices/{name}/docs/_bulk` run on the shard primary, whichever+ member accepted the request. The primary copies the stored document or+ the delete onto the in-sync replicas and acknowledges it with the same+ quorum as `PUT /{index}/_doc/{id}`. The caller still gets the native+ envelope: `data.seq_no` is the engine's 1-based sequence (the ES+ `_seq_no` plus one), a successful index or update is HTTP 201, and a+ delete of a document that is already absent is HTTP 200 `deleted`. A+ primary that does not answer is the native error body with HTTP 503,+ and the accepting node does not store the document. A copy that misses+ quorum is HTTP 503 `replica_not_acknowledged`: the primary has the+ write. The index must already exist; this path does not create one.+ A JSON array on this endpoint is a batch. It used to be stored as one+ value, because the single-document shape was parsed first and accepts+ any JSON. `POST /v1/indices/{name}/ingest` is unchanged and still+ writes on the receiving node, as do logs, OTLP, syslog, and turbo.+ A write still needs the primary. `[cluster] enabled = false` does not+ take this path (part of+ [#1170](https://github.com/xerj-org/xerj/issues/1170); the issue stays+ open).+- `xerj autoindex` names a file family in the run summary when every file ofthat family was junked, or when junked files are a strict majority(`junk_files * 2 > files`; stale-plan skips are not counted). The human@@ -35,9 +58,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0refuses the request before any document is written. A copy that missesquorum is HTTP 503 `replica_not_acknowledged`: the primaries that ranhave the delete, and the response still reports `deleted` and- `failures`. `wait_for_completion=false` uses the same path. Native- `/v1` ingest still writes on the receiving node. A write still needs- the primary. `[cluster] enabled = false` does not take this path (part of+ `failures`. `wait_for_completion=false` uses the same path. Native `/v1` logs,+ OTLP, syslog, turbo, and pipeline ingest still write on the receiving+ node. A write still needs the primary. `[cluster] enabled = false` does+ not take this path (part of[#1170](https://github.com/xerj-org/xerj/issues/1170); the issue staysopen).@@ -456,13 +480,13 @@ samuelmbabhazi, elewashy, WYSTAF, kamwoh, mgtf, mariomarcolongo and Jun516.[#1170](https://github.com/xerj-org/xerj/issues/1170); the issue staysopen (PR [#2347](https://github.com/xerj-org/xerj/pull/2347)).- What #1170 still does not do: `wait_for_active_shards`; replica- promotion (a write still needs the primary); native `/v1` ingest and- `_delete_by_query` (they stay on the receiving node); replicating- pipelines; moving copies when membership changes; merging aggregations,- suggest, collapse, rescore, profile, `search_after` or scroll across- owners; node-lifecycle APIs. The snapshot is the command prefix, not- the documents, and a history that does not fit in 8 MiB stays in the- log.+ promotion (a write still needs the primary); native `/v1` logs, OTLP,+ syslog, turbo, and pipeline ingest (they stay on the receiving node);+ `_reindex`; replicating pipelines; moving copies when membership+ changes; merging aggregations, suggest, collapse, rescore, profile,+ `search_after` or scroll across owners; node-lifecycle APIs. The+ snapshot is the command prefix, not the documents, and a history that+ does not fit in 8 MiB stays in the log.- A DeepSeek Harness profile bundle in `dsh/` (`xerj-dsh`, Apache-2.0,version `1.0.0-rc.99`) inserts the README's `mcp-xerj` stdio row viadiff --git a/engine/crates/xerj-api/src/cluster_shard.rs b/engine/crates/xerj-api/src/cluster_shard.rsindex 468daa5b2..2739909f7 100644--- a/engine/crates/xerj-api/src/cluster_shard.rs+++ b/engine/crates/xerj-api/src/cluster_shard.rs@@ -7,7 +7,10 @@//! [`update_by_query_on_primaries`] runs `_update_by_query` on every primary//! and each primary copies the documents it changed.//! [`delete_by_query_on_primaries`] runs `_delete_by_query` on every primary-//! and each primary copies the deletes.+//! and each primary copies the deletes. Native `POST /v1/indices/{name}/docs`,+//! `DELETE /v1/indices/{name}/docs/{id}`, and+//! `POST /v1/indices/{name}/docs/_bulk` use the same primary. Logs, OTLP,+//! syslog, turbo, and pipeline ingest do not.//! The primary copies an index, delete, or the document an update stored//! onto the in-sync replicas and acknowledges the caller when a quorum of//! the copies has confirmed. A replica that does notdiff --git a/engine/crates/xerj-api/src/native.rs b/engine/crates/xerj-api/src/native.rsindex da09e1175..b13b2c3e5 100644--- a/engine/crates/xerj-api/src/native.rs+++ b/engine/crates/xerj-api/src/native.rs@@ -6,7 +6,7 @@ use axum::{body::Bytes,extract::{Path, State},http::StatusCode,- response::IntoResponse,+ response::{IntoResponse, Response},Json,};use chrono::{Datelike as _, Utc};@@ -297,6 +297,211 @@ pub async fn delete_index(// Handler: POST /v1/indices/{name}/docs — ingest doc(s)// ─────────────────────────────────────────────────────────────────────────────+/// Index one native document.+///+/// With a cluster handle and a shard plan, the document is stored on the+/// primary the plan names and copied to the in-sync replicas.+/// The caller still gets the native envelope: `seq_no` is the engine's+/// 1-based value, and a successful update is HTTP 201 with `result:+/// "updated"`, the same as a local write. No plan, and+/// `[cluster] enabled = false`, index on this node and do not replicate.+async fn index_one_doc(+ state: &AppState,+ idx: &xerj_engine::Index,+ name: &str,+ doc: Value,+ request_id: &str,+ started: Instant,+) -> Result<NativeIngestResponse, Response> {+ let id = extract_or_gen_id(&doc);+ match crate::cluster_shard::dispatch_index(+ state, name, &id, &doc, "index", None, None, None, None,+ )+ .await+ {+ crate::cluster_shard::Dispatch::Done(response) => {+ let (status, body) = read_dispatch_body(response).await;+ return native_ingest_from_es(name, status, &body).map_err(|(status, body)| {+ native_from_es_error(+ status,+ &body,+ request_id,+ started.elapsed().as_millis() as u64,+ )+ });+ }+ crate::cluster_shard::Dispatch::Local => {}+ }+ match idx.index_document(Some(id), doc).await {+ Ok(resp) => {+ state.metrics.record_doc_indexed(name);+ Ok(NativeIngestResponse {+ index: name.to_string(),+ id: resp.id,+ result: resp.result,+ seq_no: resp.seq_no,+ })+ }+ Err(e) => {+ let xerj_err: xerj_common::XerjError = e.into();+ Err(native_error(+ xerj_err,+ Some(request_id),+ started.elapsed().as_millis() as u64,+ )+ .into_response())+ }+ }+}++/// `Ok(())` when the primary applied the delete (including a document that+/// was already absent). Native delete has always answered 200 `deleted` for+/// that case. `Err` is an ES-shaped body to render as a native error.+async fn route_native_delete(+ state: &AppState,+ index: &str,+ id: &str,+) -> Option<Result<(), (StatusCode, Value)>> {+ match crate::cluster_shard::dispatch_delete(state, index, id, None, None).await {+ crate::cluster_shard::Dispatch::Local => None,+ crate::cluster_shard::Dispatch::Done(response) => {+ let (status, body) = read_dispatch_body(response).await;+ Some(native_delete_from_es(status, &body))+ }+ }+}++async fn read_dispatch_body(response: Response) -> (StatusCode, Value) {+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap_or_default();+ let body = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ (status, body)+}++/// Translate a primary's index response into the native ingest body.+///+/// ES `_seq_no` is the engine sequence minus one. This envelope returns the+/// engine sequence, which is what a local `index_document` puts in `seq_no`.+fn native_ingest_from_es(+ index: &str,+ status: StatusCode,+ body: &Value,+) -> Result<NativeIngestResponse, (StatusCode, Value)> {+ if status.is_success() {+ if let Some(id) = body.get("_id").and_then(Value::as_str) {+ let result = body+ .get("result")+ .and_then(Value::as_str)+ .unwrap_or("created");+ let seq_no = body+ .get("_seq_no")+ .and_then(Value::as_u64)+ .unwrap_or(0)+ .saturating_add(1);+ return Ok(NativeIngestResponse {+ index: index.to_string(),+ id: id.to_string(),+ result: result.to_string(),+ seq_no,+ });+ }+ }+ Err((status, body.clone()))+}++fn native_delete_from_es(status: StatusCode, body: &Value) -> Result<(), (StatusCode, Value)> {+ if status.is_success() {+ return Ok(());+ }+ // The ES delete of a missing document is 404 `result: not_found`, not an+ // error object. Native delete reports that as `deleted`.+ if status == StatusCode::NOT_FOUND+ && body.get("error").is_none()+ && body.get("result").and_then(Value::as_str) == Some("not_found")+ {+ return Ok(());+ }+ Err((status, body.clone()))+}++fn native_from_es_error(+ status: StatusCode,+ body: &Value,+ request_id: &str,+ took_ms: u64,+) -> Response {+ let error = body.get("error");+ let error_type = error+ .and_then(|value| value.get("type"))+ .and_then(Value::as_str)+ .unwrap_or("cluster_write_failed");+ let reason = error+ .and_then(|value| value.get("reason"))+ .and_then(Value::as_str)+ .map(str::to_owned)+ .unwrap_or_else(|| format!("document write failed with HTTP {}", status.as_u16()));+ (+ status,+ Json(crate::error::NativeErrorResponse {+ error: error_type.to_string(),+ reason,+ status: status.as_u16(),+ request_id: Some(request_id.to_string()),+ took_ms,+ }),+ )+ .into_response()+}++#[cfg(test)]+mod native_cluster_envelope {+ use super::*;++ #[test]+ fn engine_seq_no_is_the_es_wire_value_plus_one() {+ let body = serde_json::json!({"_id": "1", "result": "created", "_seq_no": 0});+ let got = native_ingest_from_es("orders", StatusCode::CREATED, &body).unwrap();+ assert_eq!(got.id, "1");+ assert_eq!(got.index, "orders");+ assert_eq!(got.result, "created");+ assert_eq!(got.seq_no, 1);+ }++ #[test]+ fn an_update_keeps_the_engine_sequence() {+ let body = serde_json::json!({"_id": "1", "result": "updated", "_seq_no": 4});+ let got = native_ingest_from_es("orders", StatusCode::OK, &body).unwrap();+ assert_eq!(got.result, "updated");+ assert_eq!(got.seq_no, 5);+ }++ #[test]+ fn a_quorum_miss_is_not_a_native_success() {+ let body = serde_json::json!({+ "error": {"type": "replica_not_acknowledged", "reason": "no"},+ "status": 503+ });+ assert!(native_ingest_from_es("orders", StatusCode::SERVICE_UNAVAILABLE, &body).is_err());+ }++ #[test]+ fn a_missing_document_delete_stays_success() {+ let body = serde_json::json!({"_index": "orders", "_id": "1", "result": "not_found"});+ assert!(native_delete_from_es(StatusCode::NOT_FOUND, &body).is_ok());+ }++ #[test]+ fn an_index_not_found_delete_is_an_error() {+ let body = serde_json::json!({+ "error": {"type": "index_not_found_exception", "reason": "no"},+ "status": 404+ });+ assert!(native_delete_from_es(StatusCode::NOT_FOUND, &body).is_err());+ }+}+pub async fn ingest_docs(State(state): State<AppState>,Path(name): Path<String>,@@ -318,75 +523,48 @@ pub async fn ingest_docs(}};- match req {+ // `Single` is deserialized first, and `Value` accepts an array, so a+ // JSON array arrives here rather than as `Batch`. It is still a batch:+ // one document per element, each routed by its own `_id`.+ let docs = match req {+ IngestRequest::Single(Value::Array(docs)) | IngestRequest::Batch(docs) => docs,IngestRequest::Single(doc) => {- let id = extract_or_gen_id(&doc);- match idx.index_document(Some(id.clone()), doc).await {- Ok(resp) => {+ return match index_one_doc(&state, &idx, &name, doc, &request_id, started).await {+ Ok(data) => {let took_ms = started.elapsed().as_millis() as u64;- state.metrics.record_doc_indexed(&name);- let response = NativeResponse::new(- NativeIngestResponse {- index: name,- id: resp.id,- result: resp.result,- seq_no: resp.seq_no,- },- took_ms,- &request_id,- );+ let response = NativeResponse::new(data, took_ms, &request_id);(StatusCode::CREATED, Json(response)).into_response()}- Err(e) => {- let xerj_err: xerj_common::XerjError = e.into();- native_error(- xerj_err,- Some(&request_id),- started.elapsed().as_millis() as u64,- )- .into_response()- }- }+ Err(response) => response,+ };}- IngestRequest::Batch(docs) => {- let count = docs.len() as u64;- let mut ids = Vec::with_capacity(docs.len());- let mut last_seq_no = 0u64;-- for doc in docs {- let id = extract_or_gen_id(&doc);- match idx.index_document(Some(id.clone()), doc).await {- Ok(r) => {- last_seq_no = r.seq_no;- ids.push(r.id);- state.metrics.record_doc_indexed(&name);- }- Err(e) => {- let xerj_err: xerj_common::XerjError = e.into();- return native_error(- xerj_err,- Some(&request_id),- started.elapsed().as_millis() as u64,- )- .into_response();- }- }+ };+ let count = docs.len() as u64;+ let mut ids = Vec::with_capacity(docs.len());+ let mut last_seq_no = 0u64;++ for doc in docs {+ match index_one_doc(&state, &idx, &name, doc, &request_id, started).await {+ Ok(data) => {+ last_seq_no = data.seq_no;+ ids.push(data.id);}-- let took_ms = started.elapsed().as_millis() as u64;- let resp = NativeResponse::new(- serde_json::json!({- "index": name,- "indexed": count,- "ids": ids,- "last_seq_no": last_seq_no,- }),- took_ms,- &request_id,- );- (StatusCode::CREATED, Json(resp)).into_response()+ Err(response) => return response,}}++ let took_ms = started.elapsed().as_millis() as u64;+ let resp = NativeResponse::new(+ serde_json::json!({+ "index": name,+ "indexed": count,+ "ids": ids,+ "last_seq_no": last_seq_no,+ }),+ took_ms,+ &request_id,+ );+ (StatusCode::CREATED, Json(resp)).into_response()}// ─────────────────────────────────────────────────────────────────────────────@@ -463,6 +641,26 @@ pub async fn delete_doc(}};+ if let Some(routed) = route_native_delete(&state, &name, &id).await {+ return match routed {+ Ok(()) => {+ let took_ms = started.elapsed().as_millis() as u64;+ let resp = NativeResponse::new(+ serde_json::json!({ "index": name, "id": id, "result": "deleted" }),+ took_ms,+ &request_id,+ );+ Json(resp).into_response()+ }+ Err((status, body)) => native_from_es_error(+ status,+ &body,+ &request_id,+ started.elapsed().as_millis() as u64,+ ),+ };+ }+match idx.delete_document(&id).await {Ok(_) => {let took_ms = started.elapsed().as_millis() as u64;@@ -1360,10 +1558,11 @@ pub async fn bulk_ingest(let mut indexed = 0u64;for doc in req.docs {- let id = extract_or_gen_id(&doc);- if idx.index_document(Some(id), doc).await.is_ok() {+ if index_one_doc(&state, &idx, &name, doc, &request_id, started)+ .await+ .is_ok()+ {indexed += 1;- state.metrics.record_doc_indexed(&name);}}diff --git a/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs b/engine/crates/xerj-api/tests/cluster_metadata_replicates.rsindex 052ea4e0d..b7ab06f0b 100644--- a/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs+++ b/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs@@ -3124,3 +3124,374 @@ async fn delete_by_query_from_a_non_owner_deletes_on_every_primary_and_replica()let _ = member.shutdown.send(true);}}++fn native_app(member: &Member) -> Router {+ xerj_api::router::build_native_router(member.state.clone())+}++fn title_of(doc: &Value) -> Option<&str> {+ doc.get("title").and_then(Value::as_str)+}++/// `POST /v1/indices/{name}/docs`, native `_bulk`, and+/// `DELETE /v1/indices/{name}/docs/{id}` accepted by a node that owns+/// neither id land on the primaries and the in-sync replicas. The+/// receiver's user index does not keep them. A primary that does not+/// answer refuses the write.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn native_doc_writes_from_a_non_owner_hit_the_primary_and_the_replica() {+ let members = ring(true).await;+ let _leader = wait_leader(&members, &[false, false, false]).await;++ let (status, body) = put_json(+ &members[0].app,+ "/orders",+ json!({+ "settings": { "index": { "number_of_replicas": 1 } },+ "mappings": { "properties": { "title": { "type": "text" } } }+ }),+ )+ .await;+ assert!(status.is_success(), "create: {status} {body}");+ for member in &members {+ wait_status(&member.app, "/orders", StatusCode::OK).await;+ }++ let mut placed: Vec<(String, usize, usize, u32)> = Vec::new();+ for n in 0..128 {+ let id = format!("n{n}");+ let Some(primary) = members+ .iter()+ .position(|member| member.engine.owns_shard("orders", &id))+ else {+ continue;+ };+ let (shard, _) = members[primary]+ .engine+ .primary_of("orders", &id)+ .expect("placement");+ let replicas = members[primary].engine.replica_nodes("orders", shard);+ if replicas.len() != 1 {+ continue;+ }+ let Some(replica) = members+ .iter()+ .position(|member| member.handle.node_id() == replicas[0])+ else {+ continue;+ };+ if placed.iter().any(|(_, owner, _, _)| *owner == primary) {+ continue;+ }+ placed.push((id, primary, replica, shard));+ if placed.len() == 2 {+ break;+ }+ }+ assert_eq!(placed.len(), 2, "two primaries: {placed:?}");+ let (id_a, primary_a, replica_a, shard_a) = placed[0].clone();+ let (id_b, primary_b, replica_b, shard_b) = placed[1].clone();+ assert_ne!(primary_a, primary_b);+ let writer = (0..3)+ .find(|n| *n != primary_a && *n != primary_b)+ .expect("a node that owns neither id");+ let native = native_app(&members[writer]);++ let (status, body) = post_json(+ &native,+ "/v1/indices/orders/docs",+ json!({ "_id": id_a, "title": "alpha" }),+ )+ .await;+ assert_eq!(status, StatusCode::CREATED, "native index: {status} {body}");+ assert_eq!(+ body.pointer("/data/id").and_then(Value::as_str),+ Some(id_a.as_str())+ );+ assert_eq!(+ body.pointer("/data/result").and_then(Value::as_str),+ Some("created")+ );+ assert!(+ body.pointer("/data/seq_no")+ .and_then(Value::as_u64)+ .unwrap_or(0)+ >= 1,+ "native seq_no is the engine sequence, not the ES wire value: {body}"+ );+ assert!(body+ .get("request_id")+ .and_then(Value::as_str)+ .is_some_and(|id| !id.is_empty()));+ assert!(+ user_source(&members[writer], &id_a).await.is_none(),+ "the receiver stored {id_a}"+ );+ assert_eq!(+ title_of(+ &user_source(&members[primary_a], &id_a)+ .await+ .expect("primary a")+ ),+ Some("alpha")+ );+ assert_eq!(+ title_of(+ &replica_source(&members[replica_a], shard_a, &id_a)+ .await+ .expect("replica a")+ ),+ Some("alpha")+ );+ let (status, got) = get(&members[writer].app, &format!("/orders/_doc/{id_a}")).await;+ assert_eq!(status, StatusCode::OK, "ES get of a native write: {got}");+ assert_eq!(+ got.pointer("/_source/title").and_then(Value::as_str),+ Some("alpha")+ );++ let first_seq = body+ .pointer("/data/seq_no")+ .and_then(Value::as_u64)+ .unwrap();+ let (status, body) = post_json(+ &native,+ "/v1/indices/orders/docs",+ json!({ "_id": id_a, "title": "beta" }),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::CREATED,+ "native update: {status} {body}"+ );+ assert_eq!(+ body.pointer("/data/result").and_then(Value::as_str),+ Some("updated")+ );+ assert!(+ body.pointer("/data/seq_no")+ .and_then(Value::as_u64)+ .unwrap_or(0)+ > first_seq,+ "an update advances seq_no: {body}"+ );+ assert_eq!(+ title_of(+ &replica_source(&members[replica_a], shard_a, &id_a)+ .await+ .expect("replica a")+ ),+ Some("beta")+ );++ let (status, body) = post_json(+ &native,+ "/v1/indices/orders/docs",+ json!([+ { "_id": id_a, "title": "array" },+ { "_id": id_b, "title": "array-b" }+ ]),+ )+ .await;+ assert_eq!(status, StatusCode::CREATED, "native array: {status} {body}");+ assert_eq!(+ body.pointer("/data/indexed").and_then(Value::as_u64),+ Some(2),+ "{body}"+ );+ assert_eq!(+ title_of(+ &user_source(&members[primary_a], &id_a)+ .await+ .expect("primary a")+ ),+ Some("array")+ );+ assert_eq!(+ title_of(+ &user_source(&members[primary_b], &id_b)+ .await+ .expect("primary b")+ ),+ Some("array-b")+ );+ assert_eq!(+ title_of(+ &replica_source(&members[replica_b], shard_b, &id_b)+ .await+ .expect("replica b")+ ),+ Some("array-b")+ );+ assert!(user_source(&members[writer], &id_b).await.is_none());++ let (status, body) = post_json(+ &native,+ "/v1/indices/orders/docs/_bulk",+ json!({ "docs": [{ "_id": id_b, "title": "bulk" }] }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "native bulk: {status} {body}");+ assert_eq!(+ body.pointer("/data/indexed").and_then(Value::as_u64),+ Some(1),+ "{body}"+ );+ assert_eq!(+ body.pointer("/data/errors").and_then(Value::as_bool),+ Some(false),+ "{body}"+ );+ assert_eq!(+ title_of(+ &user_source(&members[primary_b], &id_b)+ .await+ .expect("primary b")+ ),+ Some("bulk")+ );+ assert_eq!(+ title_of(+ &replica_source(&members[replica_b], shard_b, &id_b)+ .await+ .expect("replica b")+ ),+ Some("bulk")+ );++ let (status, body) = delete(&native, &format!("/v1/indices/orders/docs/{id_a}")).await;+ assert_eq!(status, StatusCode::OK, "native delete: {status} {body}");+ assert_eq!(+ body.pointer("/data/result").and_then(Value::as_str),+ Some("deleted")+ );+ assert!(user_source(&members[primary_a], &id_a).await.is_none());+ assert!(replica_source(&members[replica_a], shard_a, &id_a)+ .await+ .is_none());+ assert_eq!(+ title_of(+ &user_source(&members[primary_b], &id_b)+ .await+ .expect("primary b")+ ),+ Some("bulk")+ );+ let (status, got) = get(&members[writer].app, &format!("/orders/_doc/{id_a}")).await;+ assert_eq!(+ status,+ StatusCode::NOT_FOUND,+ "ES get after native delete: {got}"+ );++ let (status, body) = delete(&native, &format!("/v1/indices/orders/docs/{id_a}")).await;+ assert_eq!(+ status,+ StatusCode::OK,+ "a second delete of a missing document stays the native 200: {status} {body}"+ );++ members[primary_b].handle.clear_shard_handler();+ let (status, body) = post_json(+ &native,+ "/v1/indices/orders/docs",+ json!({ "_id": id_b, "title": "down" }),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::SERVICE_UNAVAILABLE,+ "a primary that does not answer is a native error: {status} {body}"+ );+ assert!(+ body.get("data").is_none(),+ "the error is not the success envelope: {body}"+ );+ assert!(+ body.get("error").and_then(Value::as_str).is_some(),+ "{body}"+ );+ assert!(user_source(&members[writer], &id_b).await.is_none());+ assert_eq!(+ title_of(+ &user_source(&members[primary_b], &id_b)+ .await+ .expect("primary b")+ ),+ Some("bulk"),+ "the down primary was not written"+ );+ assert_eq!(+ title_of(+ &replica_source(&members[replica_b], shard_b, &id_b)+ .await+ .expect("replica b")+ ),+ Some("bulk")+ );+ restore_shard_handler(&members[primary_b]);++ for member in &members {+ let _ = member.shutdown.send(true);+ }+}++/// Native document writes with no cluster handle stay on the node that+/// accepted them and do not open a replica store.+#[tokio::test]+async fn cluster_disabled_native_doc_stays_on_the_node_that_received_it() {+ async fn lone() -> (Router, Router, tempfile::TempDir) {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ assert!(!engine.has_cluster());+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ let native = xerj_api::router::build_native_router(state.clone());+ let es = xerj_api::router::build_es_compat_router(state);+ (es, native, dir)+ }++ let (es_a, native_a, _dir_a) = lone().await;+ let (es_b, _native_b, _dir_b) = lone().await;+ let (status, body) = put_json(&es_a, "/local", json!({})).await;+ assert!(status.is_success(), "{status} {body}");++ let (status, body) = post_json(+ &native_a,+ "/v1/indices/local/docs",+ json!({ "_id": "1", "title": "here" }),+ )+ .await;+ assert_eq!(status, StatusCode::CREATED, "{status} {body}");+ assert_eq!(body.pointer("/data/id").and_then(Value::as_str), Some("1"));+ assert_eq!(+ body.pointer("/data/result").and_then(Value::as_str),+ Some("created")+ );+ let (status, got) = get(&es_a, "/local/_doc/1").await;+ assert_eq!(status, StatusCode::OK, "{got}");+ assert_eq!(+ got.pointer("/_source/title").and_then(Value::as_str),+ Some("here")+ );+ let (status, _) = get(&es_b, "/local/_doc/1").await;+ assert_eq!(status, StatusCode::NOT_FOUND);+ let (status, _) = get(&es_a, "/.xerj_replica_local_0/_doc/1").await;+ assert_eq!(+ status,+ StatusCode::NOT_FOUND,+ "single-node native ingest does not open a replica store"+ );++ let (status, body) = delete(&native_a, "/v1/indices/local/docs/1").await;+ assert_eq!(status, StatusCode::OK, "{status} {body}");+ assert_eq!(+ body.pointer("/data/result").and_then(Value::as_str),+ Some("deleted")+ );+ let (status, _) = get(&es_a, "/local/_doc/1").await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex e2b87ff3b..1be4b60b1 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -940,7 +940,12 @@ pub struct Engine {/// leave `LockFileEx` stuck on the file; `node_lock` reclaims it when/// the PID it records is not running, and logs that reclaim. A live/// holder still blocks a second start.- _node_lock: Arc<std::fs::File>,+ ///+ /// Drop unlocks explicitly (`NodeLock`) before close. A `fork` in another+ /// thread inherits the descriptor until that child execs; close alone+ /// does not release `flock` across that window, so a second engine on+ /// this directory would refuse to start after the holder was dropped.+ _node_lock: Arc<crate::node_lock::NodeLock>,/// Serializes rewrites of `<data_dir>/cluster_state.json` (issue #203).///diff --git a/engine/crates/xerj-engine/src/node_lock.rs b/engine/crates/xerj-engine/src/node_lock.rsindex 05e8c7769..a4b77e66f 100644--- a/engine/crates/xerj-engine/src/node_lock.rs+++ b/engine/crates/xerj-engine/src/node_lock.rs@@ -56,11 +56,53 @@ enum Liveness {Unknown,}+/// Exclusive `<data_dir>/node.lock` held for the life of one engine.+///+/// Drop from the acquiring process issues `LOCK_UN` before the descriptor is+/// closed. `flock` lives on the open-file description, and `fork` duplicates+/// that description into the child: closing the parent's fd leaves the lock+/// held until the child execs and `O_CLOEXEC` closes the inherited fd. A concurrent+/// `Command::spawn` in the same process (the node-lock tests do this) hits+/// that window, and the next `Engine::new` on the directory fails even+/// though the holder is gone. `LOCK_UN` releases the description immediately.+///+/// The child must not unlock. Its copy of this value shares the description,+/// and `LOCK_UN` there would drop a parent that is still serving the+/// directory. Same rule as the autoindex journal lock+/// (`engine/crates/xerj-autoindex/src/state.rs` lines 809–827).+#[derive(Debug)]+pub(crate) struct NodeLock {+ file: File,+ owner_pid: u32,+}++impl NodeLock {+ fn new(file: File) -> Self {+ Self {+ file,+ owner_pid: std::process::id(),+ }+ }++ #[cfg(test)]+ fn as_file(&self) -> &File {+ &self.file+ }+}++impl Drop for NodeLock {+ fn drop(&mut self) {+ if std::process::id() == self.owner_pid {+ let _ = self.file.unlock();+ }+ }+}+/// Take the exclusive `<data_dir>/node.lock`, creating the file if needed.///-/// The returned file holds the lock until it is dropped. On success the file-/// contains this process's PID.-pub(crate) fn acquire(data_dir: &Path) -> Result<File> {+/// The returned lock holds the OS lock until it is dropped. On success the+/// file contains this process's PID.+pub(crate) fn acquire(data_dir: &Path) -> Result<NodeLock> {let lock_path = data_dir.join(LOCK_NAME);let mut reclaimed_from: Option<u32> = None;@@ -94,7 +136,7 @@ pub(crate) fn acquire(data_dir: &Path) -> Result<File> {if let Some(pid) = reclaimed_from.or_else(|| dead_other(previous)) {log_reclaim(&lock_path, pid);}- return Ok(file);+ return Ok(NodeLock::new(file));}Err(TryLockError::WouldBlock) => {drop(file);@@ -600,7 +642,7 @@ mod tests {let logs = capture_warns(|| {let file = acquire(dir.path()).expect("a dead pid with no os holder is stale");- let recorded = read_pid_from_file(&file);+ let recorded = read_pid_from_file(file.as_file());assert_eq!(recorded, Some(std::process::id()));let err = acquire(dir.path()).expect_err("the reclaimed lock is exclusive");assert!(err.to_string().contains("already in use"));@@ -633,7 +675,7 @@ mod tests {if readable {let file =result.expect("a readable dead pid is reclaimed even if try_lock is busy");- assert_eq!(read_pid_from_file(&file), Some(std::process::id()));+ assert_eq!(read_pid_from_file(file.as_file()), Some(std::process::id()));// Reclaim replaces the file. The same inode would mean// `try_lock` succeeded on the busy file and this did not// exercise the stuck-lock path.@@ -706,4 +748,105 @@ mod tests {});assert!(!data_dir_lock_held(dir.path()));}++ /// The integration test `second_engine_on_same_data_dir_fails_fast_with_holder_pid`+ /// failed under `--test-threads=2` because its sibling spawns `true` /+ /// `ps`. `fork` duplicates the held `node.lock` description into that+ /// child; `drop` of the engine only `close`d the parent's fd, so the+ /// reopen still saw the lock until the child exec'd.+ #[cfg(all(unix, not(miri)))]+ #[test]+ fn drop_unlocks_while_a_forked_child_holds_the_inherited_descriptor() {+ let _guard = serialize_tests();+ let dir = tempfile::tempdir().unwrap();+ let held = acquire(dir.path()).expect("first lock");++ let mut pipe_fds = [-1_i32; 2];+ if unsafe { libc::pipe(pipe_fds.as_mut_ptr()) } != 0 {+ panic!("pipe failed: {}", std::io::Error::last_os_error());+ }+ let child = unsafe { libc::fork() };+ if child < 0 {+ let error = std::io::Error::last_os_error();+ unsafe {+ libc::close(pipe_fds[0]);+ libc::close(pipe_fds[1]);+ }+ panic!("fork failed: {error}");+ }+ if child == 0 {+ unsafe {+ libc::close(pipe_fds[1]);+ let mut byte = 0_u8;+ loop {+ let n = libc::read(+ pipe_fds[0],+ (&mut byte as *mut u8).cast::<libc::c_void>(),+ 1,+ );+ if n == 0 {+ break;+ }+ if n < 0 && child_errno() == libc::EINTR {+ continue;+ }+ libc::_exit(3);+ }+ libc::close(pipe_fds[0]);+ libc::_exit(0);+ }+ }++ // The child is blocked in `read` with the inherited descriptor open.+ // Reap it on every exit path so a failed assertion cannot leave it+ // waiting on the pipe.+ let _child = ForkedHolder {+ child,+ release_fd: pipe_fds[1],+ };+ unsafe { libc::close(pipe_fds[0]) };++ drop(held);+ let reopened = acquire(dir.path());+ drop(_child);+ let again = reopened.expect(+ "dropping the holder must unlock while a forked child still has the inherited fd",+ );+ drop(again);+ }++ #[cfg(all(unix, not(miri)))]+ fn child_errno() -> libc::c_int {+ unsafe { *libc::__errno_location() }+ }++ #[cfg(all(unix, not(miri)))]+ struct ForkedHolder {+ child: libc::pid_t,+ release_fd: libc::c_int,+ }++ #[cfg(all(unix, not(miri)))]+ impl Drop for ForkedHolder {+ fn drop(&mut self) {+ if self.release_fd >= 0 {+ unsafe { libc::close(self.release_fd) };+ self.release_fd = -1;+ }+ if self.child > 0 {+ loop {+ let mut status = 0;+ let waited = unsafe { libc::waitpid(self.child, &mut status, 0) };+ if waited == self.child {+ break;+ }+ let error = std::io::Error::last_os_error();+ if error.kind() != std::io::ErrorKind::Interrupted {+ break;+ }+ }+ self.child = -1;+ }+ }+ }}diff --git a/landing/docs/clustering.html b/landing/docs/clustering.htmlindex fc43e202a..fee402dbe 100644--- a/landing/docs/clustering.html+++ b/landing/docs/clustering.html@@ -236,12 +236,12 @@<h1>Clustering</h1>- <p>XERJ ships an <strong>embedded Raft implementation</strong> — no etcd, no ZooKeeper, no Consul. One binary is still one binary; cluster mode is a config switch, not a separate process. <strong>Where the ring stands today, plainly:</strong> leader election, heartbeats, and the authenticated inter-node transport are real. <strong>Index metadata</strong> (create, delete, mapping, and settings) and the <strong>primary shard plan</strong> for that index are proposed through the Raft log and applied on every member. A document written with <code class="inline">PUT</code>, <code class="inline">POST /{index}/_doc</code>, <code class="inline">PUT /{index}/_create</code>, <code class="inline">POST /_bulk</code>, <code class="inline">POST /{index}/_bulk</code>, or <code class="inline">POST /{index}/_update/{id}</code> is stored on the member that owns its shard, whichever node accepted the call. <code class="inline">POST /{index}/_update_by_query</code> runs on every primary of that index and each primary copies the documents it updated. <code class="inline">POST /{index}/_delete_by_query</code> runs on every primary and each primary copies the deletes. <code class="inline">GET</code> and <code class="inline">DELETE /{index}/_doc/{id}</code> follow the same owner. <code class="inline">GET</code> or <code class="inline">POST /{index}/_search</code> fans out to every owner and merges hits. <code class="inline">index.number_of_replicas</code> set at create places that many copies. The write is acknowledged when a quorum of those copies, counting the primary, has confirmed; the default is 0, which keeps a single copy. A restarted member, and a member that starts with an empty log or behind a compacted prefix, installs committed metadata from the on-disk Raft log or from InstallSnapshot. A replica store that is missing the primary's live documents then copies them and rejoins the in-sync set (public tracking: <a href="https://github.com/xerj-org/xerj/issues/1170">xerj-org/xerj#1170</a>).</p>+ <p>XERJ ships an <strong>embedded Raft implementation</strong> — no etcd, no ZooKeeper, no Consul. One binary is still one binary; cluster mode is a config switch, not a separate process. <strong>Where the ring stands today, plainly:</strong> leader election, heartbeats, and the authenticated inter-node transport are real. <strong>Index metadata</strong> (create, delete, mapping, and settings) and the <strong>primary shard plan</strong> for that index are proposed through the Raft log and applied on every member. A document written with <code class="inline">PUT</code>, <code class="inline">POST /{index}/_doc</code>, <code class="inline">PUT /{index}/_create</code>, <code class="inline">POST /_bulk</code>, <code class="inline">POST /{index}/_bulk</code>, or <code class="inline">POST /{index}/_update/{id}</code> is stored on the member that owns its shard, whichever node accepted the call. <code class="inline">POST /{index}/_update_by_query</code> runs on every primary of that index and each primary copies the documents it updated. <code class="inline">POST /{index}/_delete_by_query</code> runs on every primary and each primary copies the deletes. <code class="inline">POST /v1/indices/{name}/docs</code>, <code class="inline">DELETE /v1/indices/{name}/docs/{id}</code>, and <code class="inline">POST /v1/indices/{name}/docs/_bulk</code> run on the primary for that id and copy the document or the delete. <code class="inline">GET</code> and <code class="inline">DELETE /{index}/_doc/{id}</code> follow the same owner. <code class="inline">GET</code> or <code class="inline">POST /{index}/_search</code> fans out to every owner and merges hits. <code class="inline">index.number_of_replicas</code> set at create places that many copies. The write is acknowledged when a quorum of those copies, counting the primary, has confirmed; the default is 0, which keeps a single copy. A restarted member, and a member that starts with an empty log or behind a compacted prefix, installs committed metadata from the on-disk Raft log or from InstallSnapshot. A replica store that is missing the primary's live documents then copies them and rejoins the in-sync set (public tracking: <a href="https://github.com/xerj-org/xerj/issues/1170">xerj-org/xerj#1170</a>).</p><h2>What cluster mode does not give you yet</h2><div class="enum-list"><div class="item">Replicas follow the create setting, not a later change<span class="dsc"><code class="inline">index.number_of_replicas</code> on <code class="inline">PUT /{index}</code> places that many copies of each primary, capped at one fewer than the member count. The default is 0. A later <code class="inline">PUT /{index}/_settings</code> stores a new number and does not move copies. There is no <code class="inline">wait_for_active_shards</code>. A write is acknowledged when a quorum of the copies has confirmed: copies are the primary plus the replicas placed at create, and a quorum is <code class="inline">copies / 2 + 1</code>. The primary already counts, so with two replicas one confirmation is enough and the caller still succeeds. The replica that did not confirm is removed from the in-sync set by a Raft entry, and later reads do not use it until it has copied the primary's live documents and that enlarged set has committed. If fewer replicas confirm than that quorum, the response is <code class="inline">503</code> <code class="inline">replica_not_acknowledged</code>: the primary has the write, and a retry of the index copies it to the replicas still in sync. <code class="inline">number_of_replicas</code> 0 or 1 does not loosen this: there is no replica to wait for, or that single replica must confirm.</span></div>- <div class="item">Native ingest stays on the receiver<span class="dsc">The native <code class="inline">/v1</code> ingest paths still write on the node that received them. They do not consult the shard plan. <code class="inline">POST /{index}/_delete_by_query</code> and <code class="inline">POST /{index}/_update_by_query</code> run on every primary. Each primary deletes or updates only the documents in its own shard and copies that change to the in-sync replicas. <code class="inline">max_docs</code> counts across those primaries, in node-id order. A primary that does not answer refuses the request before any document is written. A copy that misses quorum is <code class="inline">503</code> <code class="inline">replica_not_acknowledged</code>: the primary has the delete or the update. <code class="inline">?pipeline=</code> on an update-by-query runs on the primary. Pipelines are not replicated, so a pipeline that is not on that primary is <code class="inline">400</code> and writes nothing.</span></div>+ <div class="item">Some native ingest stays on the receiver<span class="dsc"><code class="inline">POST /v1/indices/{name}/docs</code>, <code class="inline">DELETE /v1/indices/{name}/docs/{id}</code>, and <code class="inline">POST /v1/indices/{name}/docs/_bulk</code> run on the shard primary and copy to the in-sync replicas. The response stays the native envelope. Logs, OTLP, syslog, turbo, and pipeline ingest still write on the node that received them. <code class="inline">POST /{index}/_delete_by_query</code> and <code class="inline">POST /{index}/_update_by_query</code> run on every primary. Each primary deletes or updates only the documents in its own shard and copies that change to the in-sync replicas. <code class="inline">max_docs</code> counts across those primaries, in node-id order. A primary that does not answer refuses the request before any document is written. A copy that misses quorum is <code class="inline">503</code> <code class="inline">replica_not_acknowledged</code>: the primary has the delete or the update. <code class="inline">?pipeline=</code> on an update-by-query runs on the primary. Pipelines are not replicated, so a pipeline that is not on that primary is <code class="inline">400</code> and writes nothing.</span></div><div class="item">Search merges hits, not every clause<span class="dsc">A query, including <code class="inline">match_all</code>, is run on each owner and the hits are merged by the per-shard score (not a global IDF), then <code class="inline">from</code>/<code class="inline">size</code> is applied. Aggregations, suggest, collapse, rescore, profile, <code class="inline">search_after</code>, and scroll are refused with <code class="inline">400</code> when the index has more than one owner — the response is not a partial merge. <code class="inline">/_search</code> with no index, and a comma-separated or wildcard index list, still search only the node that received them. The per-shard window is capped at 10,000 hits.</span></div><div class="item">No replica promotion<span class="dsc">A restarted member reopens <code class="inline">{data_dir}/_raft</code> and applies the snapshot plus the log suffix before it serves, so the shard plan and the in-sync set come back. After 64 applied metadata entries the prefix is snapshotted and a member whose log does not overlap receives InstallSnapshot. The snapshot is the metadata commands, not the documents. A placed replica that is missing those documents copies them from the primary and is published back into the in-sync set; a write still needs the primary, and there is no promotion. A metadata history bigger than 8 MiB stays in the log instead of being snapshotted. Changing membership does not move copies.</span></div><div class="item">No node-lifecycle APIs<span class="dsc">There is no drain / activate / remove endpoint and no region split-merge. Earlier revisions of this page documented them; the binary has never shipped them.</span></div>@@ -255,7 +255,7 @@<li><strong>Dead-peer isolation</strong> — a hung or dead peer costs one <code class="inline">WARN</code> on the transition and a retry ladder backing off 100 ms → 6.4 s; it never delays messages to live peers.</li><li><strong>Index metadata replication</strong> — <code class="inline">PUT /{index}</code>, <code class="inline">DELETE /{index}</code>, <code class="inline">PUT /{index}/_mapping</code>, and <code class="inline">PUT /{index}/_settings</code> are proposed on the member that received them. A follower forwards to the leader. The HTTP call succeeds only after the entry commits on a majority and this node has applied it. No elected leader, or a commit that does not land in time, is <code class="inline">503</code> and the change is not applied on the caller. With <code class="inline">[cluster] enabled = false</code> these calls stay local, as before.</li><li><strong>Primary shard plan</strong> — the create entry names one primary per member (member ids sorted, shard <code class="inline">i</code> on the <code class="inline">i</code>th) and, when <code class="inline">index.number_of_replicas</code> is set, the next members in that ring as replicas. <code class="inline">Engine::route_write</code> returns the primary, or nothing when this node is the primary or the index has no plan. Document id is the routing key (jump consistent hash).</li>- <li><strong>Document routing</strong> — <code class="inline">PUT</code>/<code class="inline">POST /{index}/_doc</code>, <code class="inline">PUT /{index}/_create/{id}</code>, <code class="inline">POST /_bulk</code>, <code class="inline">POST /{index}/_bulk</code>, <code class="inline">POST /{index}/_update/{id}</code>, <code class="inline">POST /{index}/_update_by_query</code>, <code class="inline">POST /{index}/_delete_by_query</code>, <code class="inline">GET</code> and <code class="inline">DELETE /{index}/_doc/{id}</code> run on the primary. A bulk body is split by primary; the receiver does not keep another member's actions. An update-by-query or a delete-by-query is sent to every primary, and each primary changes only the documents in its shard. The primary copies an index, a delete (one document or a delete-by-query), or the document an update or update-by-query stored to each in-sync replica and answers when a quorum of the copies has confirmed. A search of one concrete index fans out to every primary and merges hits, and reads an in-sync replica of a primary that does not answer. The copy is a hidden <code class="inline">.xerj_replica_{index}_{shard}</code> index on the replica node, not a second document in the user index, so a live primary search does not count it twice. Replica <code class="inline">_seq_no</code> and <code class="inline">_version</code> are that node's own. The owner is reached on the cluster port (authenticated, one request and one response per connection), not by writing the document into the Raft log.</li>+ <li><strong>Document routing</strong> — <code class="inline">PUT</code>/<code class="inline">POST /{index}/_doc</code>, <code class="inline">PUT /{index}/_create/{id}</code>, <code class="inline">POST /_bulk</code>, <code class="inline">POST /{index}/_bulk</code>, <code class="inline">POST /{index}/_update/{id}</code>, <code class="inline">POST /{index}/_update_by_query</code>, <code class="inline">POST /{index}/_delete_by_query</code>, <code class="inline">GET</code> and <code class="inline">DELETE /{index}/_doc/{id}</code>, <code class="inline">POST /v1/indices/{name}/docs</code>, <code class="inline">DELETE /v1/indices/{name}/docs/{id}</code>, and <code class="inline">POST /v1/indices/{name}/docs/_bulk</code> run on the primary. A bulk body is split by primary; the receiver does not keep another member's actions. An update-by-query or a delete-by-query is sent to every primary, and each primary changes only the documents in its shard. The primary copies an index, a delete (one document or a delete-by-query), or the document an update or update-by-query stored to each in-sync replica and answers when a quorum of the copies has confirmed. A search of one concrete index fans out to every primary and merges hits, and reads an in-sync replica of a primary that does not answer. The copy is a hidden <code class="inline">.xerj_replica_{index}_{shard}</code> index on the replica node, not a second document in the user index, so a live primary search does not count it twice. Replica <code class="inline">_seq_no</code> and <code class="inline">_version</code> are that node's own. The owner is reached on the cluster port (authenticated, one request and one response per connection), not by writing the document into the Raft log.</li><li><strong>On-disk Raft log</strong> — cluster mode opens <code class="inline">{data_dir}/_raft</code> (<code class="inline">raft.log</code>, <code class="inline">snapshot.meta</code> once the prefix has been compacted, plus the commit index, term, and vote). The directory name is not a valid index name, so deleting an index cannot delete the log. On startup the node replays the snapshot and then the committed suffix into the shard plan and the in-sync set before it serves. Indices and documents already in that data directory stay; the plan is what tells a later write where they live. A member whose log does not overlap the leader's copies the log, or installs the snapshot when the leader has compacted the prefix, and applies it.</li></ul>@@ -323,10 +323,10 @@ INFO xerj_cluster::raft: Became leader node=10.0.0.12:9300 term=1</pre><h2>What replicates, and what stays on one node</h2><p><code class="inline">PUT /orders</code> on any member — leader or follower — creates <code class="inline">orders</code> on every member, including its mapping, the settings and aliases in that request, and a primary on each member. <code class="inline">GET /orders</code> and <code class="inline">GET /orders/_mapping</code> on another member succeed after the call returns. <code class="inline">DELETE /orders</code> removes it on every member. A settings or mapping change is one log entry per concrete index. A follower that cannot reach a leader returns <code class="inline">503</code>; it does not create the index locally and report success.</p>- <p><code class="inline">PUT /orders/_doc/1</code>, <code class="inline">POST /orders/_update/1</code>, and each action in <code class="inline">POST /orders/_bulk</code> on any member stores the document on the primary for that id and on enough in-sync replicas to make a quorum of the copies. <code class="inline">POST /orders/_update_by_query</code> does the same for every document it changes. <code class="inline">POST /orders/_delete_by_query</code> deletes on every primary and copies each delete to the in-sync replicas. An action whose primary is another member is not written into the accepting node's index. With <code class="inline">number_of_replicas</code> 1 that is the one replica. With 2, one of the two is enough; the other is left out of the in-sync set until it copies the primary's live documents and the enlarged set commits, and a later read does not use it before that. <code class="inline">GET /orders/_doc/1</code> from any other member returns it, from the primary while that member answers and from an in-sync replica when it does not. <code class="inline">POST /orders/_search</code> from any member returns documents stored on the primaries, using an in-sync replica only for a primary that does not answer. An auto-created index (a document write that names an index which does not exist yet) proposes the create with an empty schema and <code class="inline">number_of_replicas</code> 0, then routes. With no elected leader that write is <code class="inline">503</code> and the index is not created. <code class="inline">[cluster] enabled = false</code> does not place replicas: the setting is stored, and the document stays on the node that received it.</p>+ <p><code class="inline">PUT /orders/_doc/1</code>, <code class="inline">POST /orders/_update/1</code>, and each action in <code class="inline">POST /orders/_bulk</code> on any member stores the document on the primary for that id and on enough in-sync replicas to make a quorum of the copies. <code class="inline">POST /orders/_update_by_query</code> does the same for every document it changes. <code class="inline">POST /orders/_delete_by_query</code> deletes on every primary and copies each delete to the in-sync replicas. <code class="inline">POST /v1/indices/orders/docs</code>, <code class="inline">DELETE /v1/indices/orders/docs/1</code>, and <code class="inline">POST /v1/indices/orders/docs/_bulk</code> do the same for one document: the primary stores it, or deletes it, and copies that to the in-sync replicas. The caller still receives the native envelope. An action whose primary is another member is not written into the accepting node's index. With <code class="inline">number_of_replicas</code> 1 that is the one replica. With 2, one of the two is enough; the other is left out of the in-sync set until it copies the primary's live documents and the enlarged set commits, and a later read does not use it before that. <code class="inline">GET /orders/_doc/1</code> from any other member returns it, from the primary while that member answers and from an in-sync replica when it does not. <code class="inline">POST /orders/_search</code> from any member returns documents stored on the primaries, using an in-sync replica only for a primary that does not answer. An auto-created index (a document write that names an index which does not exist yet) proposes the create with an empty schema and <code class="inline">number_of_replicas</code> 0, then routes. With no elected leader that write is <code class="inline">503</code> and the index is not created. <code class="inline">[cluster] enabled = false</code> does not place replicas: the setting is stored, and the document stays on the node that received it.</p><p>Several things around that path stay local, on purpose for this step:</p><ul>- <li><strong>The native <code class="inline">/v1</code> ingest API</strong> does not route or replicate. <code class="inline">_delete_by_query</code> and <code class="inline">_update_by_query</code> do: each runs on every primary and the primary copies the documents it deleted or changed. For a copy of the paths that still stay on the receiving node, point the <a href="/docs/config#wal_tap">WAL tap</a> at another XERJ or any ES-compatible target.</li>+ <li><strong>Native logs, OTLP, syslog, turbo, and pipeline ingest</strong> still write on the node that received them. <code class="inline">POST /v1/indices/{name}/docs</code>, <code class="inline">DELETE /v1/indices/{name}/docs/{id}</code>, and <code class="inline">POST /v1/indices/{name}/docs/_bulk</code> run on the primary, and the primary copies the document or the delete. <code class="inline">_delete_by_query</code> and <code class="inline">_update_by_query</code> run on every primary. For a copy of the paths that still stay on the receiving node, point the <a href="/docs/config#wal_tap">WAL tap</a> at another XERJ or any ES-compatible target.</li><li><strong>Index templates</strong> are not replicated. The accepting node applies its templates once and the effective schema is what the log carries.</li><li><strong>ILM/ISM attach</strong> from <code class="inline">index.lifecycle.name</code> runs on the accepting node only.</li><li><strong>Console system indices</strong> created at boot, before the ring is attached, have no shard plan and stay local.</li>@@ -341,7 +341,7 @@ INFO xerj_cluster::raft: Became leader node=10.0.0.12:9300 term=1</pre></div><h2>When not to cluster</h2>- <p>When you need a replica to accept writes after the primary is gone, or a search that aggregates across shards. Cluster mode keeps index metadata in step, places each document on one primary, acknowledges a document write (<code class="inline">PUT</code>/<code class="inline">POST</code> <code class="inline">_doc</code>, <code class="inline">_bulk</code>, <code class="inline">_update</code>, <code class="inline">_update_by_query</code>, or <code class="inline">_delete_by_query</code>) once a quorum of its copies has it, copies the primary's live documents onto a replica that joined late or missed a write, and reloads metadata when a member restarts. It does not promote a replica, and adding or removing a member does not move copies. One node avoids the forwarding hop and is trivial to back up. The default config ships with <code class="inline">[cluster] enabled = false</code>.</p>+ <p>When you need a replica to accept writes after the primary is gone, or a search that aggregates across shards. Cluster mode keeps index metadata in step, places each document on one primary, acknowledges a document write (<code class="inline">PUT</code>/<code class="inline">POST</code> <code class="inline">_doc</code>, <code class="inline">_bulk</code>, <code class="inline">_update</code>, <code class="inline">_update_by_query</code>, <code class="inline">_delete_by_query</code>, or native <code class="inline">/v1</code> document index, delete, and <code class="inline">_bulk</code>) once a quorum of its copies has it, copies the primary's live documents onto a replica that joined late or missed a write, and reloads metadata when a member restarts. It does not promote a replica, and adding or removing a member does not move copies. One node avoids the forwarding hop and is trivial to back up. The default config ships with <code class="inline">[cluster] enabled = false</code>.</p><p class="source-note">Source · engine/crates/xerj-cluster/src/raft.rs · engine/crates/xerj-cluster/src/transport.rs · engine/crates/xerj-cluster/src/runner.rs</p>