Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

feat(cluster): route _bulk and _update writes to the shard primary (#2344)

xerj-org3d879c224aa7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 48426721c..89ff434fa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- With `[cluster] enabled = true`, `POST /_bulk`, `POST /{index}/_bulk`, and
+ `POST /{index}/_update/{id}` run on the shard primary, whichever member
+ accepted the request. A bulk body is split by primary. An action whose
+ primary is another member is forwarded there and is not indexed on the
+ receiver. The primary then copies the stored document (or the delete)
+ onto the in-sync replicas and acknowledges it with the same quorum as
+ `PUT /{index}/_doc/{id}`. `_bulk` covers index, create, update, and
+ delete. `_update` covers a partial document and a script; the script
+ runs on the primary, where the current source is. A missing `_id` on
+ index or create is chosen before the owner is selected, so the stored
+ id is the id that was routed. An update that does not change the source
+ is not copied again. A copy that misses quorum is
+ `503 replica_not_acknowledged` for that item: the primary has the write.
+ `_update_by_query` and native `/v1` 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)).
+
- `xerj corpus add --own` and `xerj corpus own <name>` (`--off` clears it)
mark a corpus as your own first-party code (`"own": true` in its
`corpus.json`). `xerj code` and MCP `xerj_code_search` still name an
diff --git a/engine/crates/xerj-api/src/cluster_shard.rs b/engine/crates/xerj-api/src/cluster_shard.rs
index 15b6cd958..e87df1b80 100644
--- a/engine/crates/xerj-api/src/cluster_shard.rs
+++ b/engine/crates/xerj-api/src/cluster_shard.rs
@@ -2,9 +2,11 @@
//!
//! With a cluster handle attached, a replicated index carries a primary plan
//! in the same Raft entry as the create. [`dispatch_index`] forwards a
-//! document to the owner [`Engine::route_write`] names. The primary then
-//! copies an index or delete onto the in-sync replicas and acknowledges the
-//! caller when a quorum of the copies has confirmed. A replica that does not
+//! document to the owner [`Engine::route_write`] names. [`dispatch_update`]
+//! and [`bulk_on_primaries`] send `_update` and `_bulk` to that same owner.
+//! 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 not
//! confirm is dropped from the in-sync set when the rest already make a
//! quorum. That replica copies the primary's live documents when it can
//! answer again, and the primary then publishes it back into the in-sync
@@ -17,7 +19,7 @@
//! a primary search does not count them twice. The owner's handler does not
//! route a `replica` apply again.
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -28,8 +30,8 @@ use serde_json::{json, Value};
use xerj_cluster::{ApplyEffect, ClusterCommand, ShardOp, ShardResult};
use crate::es_compat::{
- apply_get_doc_source_filter, search_shard_local, EsSearchBody, EsSearchJson,
- EsSearchQueryParams, GetDocParams,
+ apply_get_doc_source_filter, apply_local_update, search_shard_local, EsSearchBody,
+ EsSearchJson, EsSearchQueryParams, EsUpdateBody, GetDocParams, UpdateDocParams,
};
use crate::responses::{EsDeleteDocResponse, EsDocResponse, EsGetResponse};
use crate::state::AppState;
@@ -251,6 +253,60 @@ pub(crate) async fn dispatch_delete(
Dispatch::Done(forward_retrying(state, &owner, op).await)
}
+/// Route one `_update` to the shard primary. The primary applies the partial
+/// document or the script and copies the stored source onto the in-sync replicas.
+///
+/// [`Dispatch::Local`] is only an index with no shard plan. Single-node mode
+/// does not call this.
+pub(crate) async fn dispatch_update(
+ state: &AppState,
+ index: &str,
+ id: &str,
+ body: &EsUpdateBody,
+ params: &UpdateDocParams,
+) -> Dispatch {
+ if !state.engine.has_cluster() {
+ return Dispatch::Local;
+ }
+ let concrete = match ensure_concrete_index(state, index).await {
+ Ok(name) => name,
+ Err(err) => return Dispatch::Done(ensure_fail_response(index, err)),
+ };
+ let body_json = match serde_json::to_string(body) {
+ Ok(json) => json,
+ Err(err) => {
+ return Dispatch::Done(
+ (
+ StatusCode::BAD_REQUEST,
+ Json(json!({
+ "error": {
+ "type": "parsing_exception",
+ "reason": format!("update body could not be forwarded: {err}")
+ },
+ "status": 400
+ })),
+ )
+ .into_response(),
+ );
+ }
+ };
+ let params_json = serde_json::to_string(params).unwrap_or_else(|_| "{}".to_string());
+ if state.engine.owns_shard(&concrete, id) {
+ let result = local_update(state, index, id, &body_json, &params_json).await;
+ return Dispatch::Done(http_result(result));
+ }
+ let Some(owner) = state.engine.route_write(&concrete, id) else {
+ return Dispatch::Local;
+ };
+ let op = ShardOp::UpdateDoc {
+ index: index.to_string(),
+ id: id.to_string(),
+ body_json,
+ params_json,
+ };
+ Dispatch::Done(forward_retrying(state, &owner, op).await)
+}
+
fn cluster_search_unsupported(feature: &str) -> Response {
let reason = format!(
"cluster search does not merge {feature} across shards yet; the request was not executed"
@@ -579,6 +635,40 @@ impl xerj_cluster::ShardHandler for ApiShardHandler {
)
.await
}
+ ShardOp::UpdateDoc {
+ index,
+ id,
+ body_json,
+ params_json,
+ } => {
+ let concrete = concrete_index_name(&self.state.engine, &index);
+ if self.state.engine.get_index(&concrete).is_err() {
+ return ShardResult::http(503, shard_not_ready_body(&index));
+ }
+ if !self.state.engine.owns_shard(&concrete, &id) {
+ if let Some(owner) = self.state.engine.route_write(&concrete, &id) {
+ return not_this_primary(&index, &owner);
+ }
+ }
+ local_update(&self.state, &index, &id, &body_json, &params_json).await
+ }
+ ShardOp::Bulk {
+ body,
+ default_index,
+ require_alias,
+ default_pipeline,
+ default_source_req_json,
+ } => {
+ handle_bulk(
+ &self.state,
+ &body,
+ default_index.as_deref(),
+ require_alias,
+ default_pipeline,
+ default_source_req_json,
+ )
+ .await
+ }
ShardOp::Search {
index,
body_json,
@@ -1465,3 +1555,1009 @@ async fn local_search(
};
response_to_result(response).await
}
+
+// ── `_update` and `_bulk` on the primary ────────────────────────────────────
+
+/// Backing index when `name` is an alias, otherwise `name`.
+///
+/// `Engine::get_index` writes an alias through its first backing index. Routing
+/// has to use that same name, or the shard plan (which lives on the concrete
+/// index) is invisible and the write stays on the node that received it.
+fn concrete_index_name(engine: &xerj_engine::Engine, name: &str) -> String {
+ engine
+ .aliases
+ .get(name)
+ .and_then(|names| names.first().cloned())
+ .filter(|backing| !backing.is_empty())
+ .unwrap_or_else(|| name.to_string())
+}
+
+enum EnsureFail {
+ Engine(xerj_engine::EngineError),
+ Unavailable(String),
+}
+
+fn ensure_fail_response(index: &str, err: EnsureFail) -> Response {
+ match err {
+ EnsureFail::Engine(err) => engine_error_response(err),
+ EnsureFail::Unavailable(reason) => (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(json!({
+ "error": {
+ "type": "shard_not_ready",
+ "reason": format!("index [{index}] is not on this shard yet: {reason}")
+ },
+ "status": 503
+ })),
+ )
+ .into_response(),
+ }
+}
+
+fn ensure_fail_status(err: EnsureFail) -> (u16, String) {
+ match err {
+ EnsureFail::Engine(err) => {
+ let common = xerj_common::XerjError::from(err);
+ let status = common.http_status();
+ (status, common.to_string())
+ }
+ EnsureFail::Unavailable(reason) => (503, reason),
+ }
+}
+
+async fn wait_index_open(state: &AppState, name: &str) -> bool {
+ let deadline = Instant::now() + OWNER_READY_WAIT;
+ loop {
+ if state.engine.get_index(name).is_ok() {
+ return true;
+ }
+ if Instant::now() >= deadline {
+ return false;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+}
+
+/// Open `name`, creating it through the Raft log when it is not an alias and
+/// this node does not have it yet. Does not write a document.
+async fn ensure_concrete_index(state: &AppState, name: &str) -> Result<String, EnsureFail> {
+ let concrete = concrete_index_name(&state.engine, name);
+ if concrete != name {
+ if state.engine.get_index(&concrete).is_err() {
+ return Err(EnsureFail::Unavailable(format!(
+ "alias [{name}] does not point at an open index"
+ )));
+ }
+ return Ok(concrete);
+ }
+ if state.engine.get_index(&concrete).is_err() {
+ state
+ .engine
+ .ensure_replicated_index(&concrete)
+ .await
+ .map_err(EnsureFail::Engine)?;
+ }
+ if !wait_index_open(state, &concrete).await {
+ return Err(EnsureFail::Unavailable(format!(
+ "index [{concrete}] was not open after the create committed"
+ )));
+ }
+ Ok(concrete)
+}
+
+fn not_this_primary(index: &str, owner: &str) -> ShardResult {
+ ShardResult::http(
+ 409,
+ json!({
+ "error": {
+ "type": "shard_not_primary",
+ "reason": format!("[{index}] is owned by [{owner}], not this node")
+ },
+ "status": 409
+ })
+ .to_string(),
+ )
+}
+
+async fn local_update(
+ state: &AppState,
+ index: &str,
+ id: &str,
+ body_json: &str,
+ params_json: &str,
+) -> ShardResult {
+ let concrete = concrete_index_name(&state.engine, index);
+ if state.engine.get_index(&concrete).is_err() {
+ return ShardResult::http(503, shard_not_ready_body(index));
+ }
+ let body: EsUpdateBody = match serde_json::from_str(body_json) {
+ Ok(body) => body,
+ Err(err) => {
+ return ShardResult::http(
+ 400,
+ json!({
+ "error": {
+ "type": "parsing_exception",
+ "reason": format!("forwarded update body is not JSON: {err}")
+ },
+ "status": 400
+ })
+ .to_string(),
+ );
+ }
+ };
+ let params: UpdateDocParams = serde_json::from_str(params_json).unwrap_or_default();
+ let applied = apply_local_update(state, index, id, body, &params).await;
+ if !applied.replicate {
+ return response_to_result(applied.response).await;
+ }
+ let copy = match state.engine.get_index(&concrete) {
+ Ok(idx) => match idx.get_document(id).await {
+ Ok(Some(doc)) => match serde_json::to_string(&doc) {
+ Ok(source_json) => ShardOp::IndexDoc {
+ index: concrete.clone(),
+ id: id.to_string(),
+ source_json,
+ op: "index".to_string(),
+ if_seq_no: None,
+ if_primary_term: None,
+ version: None,
+ version_type: None,
+ replica: false,
+ shard: 0,
+ },
+ Err(err) => {
+ return ShardResult::http(
+ 503,
+ json!({
+ "error": {
+ "type": "replica_not_acknowledged",
+ "reason": format!(
+ "primary applied the update on [{index}] but document [{id}] could not be copied: {err}"
+ )
+ },
+ "status": 503
+ })
+ .to_string(),
+ );
+ }
+ },
+ Ok(None) => ShardOp::DeleteDoc {
+ index: concrete.clone(),
+ id: id.to_string(),
+ if_seq_no: None,
+ if_primary_term: None,
+ replica: false,
+ shard: 0,
+ },
+ Err(err) => {
+ return ShardResult::http(
+ 503,
+ json!({
+ "error": {
+ "type": "replica_not_acknowledged",
+ "reason": format!(
+ "primary applied the update on [{index}] but document [{id}] could not be read for the replica copy: {err}"
+ )
+ },
+ "status": 503
+ })
+ .to_string(),
+ );
+ }
+ },
+ Err(err) => {
+ return ShardResult::http(
+ 503,
+ json!({
+ "error": {
+ "type": "replica_not_acknowledged",
+ "reason": format!(
+ "primary applied the update on [{index}] but [{concrete}] is not open for the replica copy: {err}"
+ )
+ },
+ "status": 503
+ })
+ .to_string(),
+ );
+ }
+ };
+ if let Err(nack) = replicate_write(state, &concrete, id, copy).await {
+ return nack;
+ }
+ response_to_result(applied.response).await
+}
+
+/// One parsed bulk action, in request order.
+struct BulkPiece {
+ action: String,
+ /// Name the caller used. The bulk pipeline reports this on the item.
+ index: String,
+ id: String,
+ action_line: String,
+ source_line: Option<String>,
+ /// Set when this action is already an error and must not be written.
+ preset: Option<xerj_engine::bulk::BulkItemResult>,
+ concrete: String,
+}
+
+fn bulk_item_error(
+ action: &str,
+ index: &str,
+ id: &str,
+ status: u16,
+ error: impl Into<String>,
+) -> xerj_engine::bulk::BulkItemResult {
+ xerj_engine::bulk::BulkItemResult {
+ action: action.to_string(),
+ index: index.to_string(),
+ id: id.to_string(),
+ status,
+ result: None,
+ error: Some(error.into()),
+ get_source: None,
+ }
+}
+
+/// Same pairing rule as the bulk engine: a delete action has no source line.
+/// The two parsers have to agree, or a delete swallows the next action.
+fn bulk_action_line_is_delete(line: &str) -> bool {
+ let b = line.as_bytes();
+ let mut p = 0usize;
+ while p < b.len() && (b[p] == b' ' || b[p] == b'\t') {
+ p += 1;
+ }
+ if p >= b.len() || b[p] != b'{' {
+ return false;
+ }
+ p += 1;
+ while p < b.len() && (b[p] == b' ' || b[p] == b'\t') {
+ p += 1;
+ }
+ if p >= b.len() || b[p] != b'"' {
+ return false;
+ }
+ p += 1;
+ let start = p;
+ while p < b.len() && b[p] != b'"' {
+ p += 1;
+ }
+ p < b.len() && &b[start..p] == b"delete"
+}
+
+fn json_meta_id(meta: &Value) -> Option<String> {
+ match meta.get("_id")? {
+ Value::String(s) => Some(s.clone()),
+ Value::Number(n) => Some(n.to_string()),
+ Value::Bool(b) => Some(b.to_string()),
+ _ => None,
+ }
+}
+
+fn split_bulk_pieces(body: &str, default_index: Option<&str>) -> Vec<BulkPiece> {
+ let lines: Vec<&str> = body
+ .lines()
+ .filter(|line| !line.trim().is_empty())
+ .collect();
+ let mut pieces = Vec::new();
+ let mut i = 0usize;
+ while i < lines.len() {
+ let raw_action = lines[i];
+ let is_delete = bulk_action_line_is_delete(raw_action);
+ let source_line = if !is_delete && i + 1 < lines.len() {
+ let source = lines[i + 1];
+ i += 2;
+ Some(source.to_string())
+ } else {
+ i += 1;
+ None
+ };
+ let action_val: Value = match serde_json::from_str(raw_action) {
+ Ok(value) => value,
+ Err(err) => {
+ pieces.push(BulkPiece {
+ action: "unknown".to_string(),
+ index: default_index.unwrap_or("_unknown").to_string(),
+ id: String::new(),
+ action_line: String::new(),
+ source_line: None,
+ preset: Some(bulk_item_error(
+ "unknown",
+ default_index.unwrap_or("_unknown"),
+ "",
+ 400,
+ format!("failed to parse action line: {err}"),
+ )),
+ concrete: String::new(),
+ });
+ continue;
+ }
+ };
+ let (action, meta) = if let Some(meta) = action_val.get("index") {
+ ("index", meta)
+ } else if let Some(meta) = action_val.get("create") {
+ ("create", meta)
+ } else if let Some(meta) = action_val.get("update") {
+ ("update", meta)
+ } else if let Some(meta) = action_val.get("delete") {
+ ("delete", meta)
+ } else {
+ pieces.push(BulkPiece {
+ action: "unknown".to_string(),
+ index: default_index.unwrap_or("_unknown").to_string(),
+ id: String::new(),
+ action_line: String::new(),
+ source_line: None,
+ preset: Some(bulk_item_error(
+ "unknown",
+ default_index.unwrap_or("_unknown"),
+ "",
+ 400,
+ "unknown action type",
+ )),
+ concrete: String::new(),
+ });
+ continue;
+ };
+ let mut meta = if meta.is_object() {
+ meta.clone()
+ } else {
+ json!({})
+ };
+ let index = meta
+ .get("_index")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .or_else(|| default_index.map(str::to_string))
+ .unwrap_or_else(|| "_unknown".to_string());
+ if meta.get("_index").and_then(Value::as_str).is_none() {
+ meta["_index"] = json!(index);
+ }
+ if let Some(id) = json_meta_id(&meta) {
+ if id.is_empty() {
+ pieces.push(BulkPiece {
+ action: action.to_string(),
+ index: index.clone(),
+ id: String::new(),
+ action_line: String::new(),
+ source_line: None,
+ preset: Some(bulk_item_error(
+ action,
+ &index,
+ "",
+ 400,
+ "if _id is specified it must not be empty",
+ )),
+ concrete: String::new(),
+ });
+ continue;
+ }
+ }
+ let id = match json_meta_id(&meta) {
+ Some(id) => id,
+ None if action == "index" || action == "create" => {
+ let id = uuid::Uuid::new_v4().to_string();
+ meta["_id"] = json!(id);
+ id
+ }
+ None => {
+ let reason = if action == "update" {
+ "update action requires _id"
+ } else {
+ "delete action requires _id"
+ };
+ pieces.push(BulkPiece {
+ action: action.to_string(),
+ index: index.clone(),
+ id: String::new(),
+ action_line: String::new(),
+ source_line: None,
+ preset: Some(bulk_item_error(action, &index, "", 400, reason)),
+ concrete: String::new(),
+ });
+ continue;
+ }
+ };
+ if action != "delete" && source_line.is_none() {
+ pieces.push(BulkPiece {
+ action: action.to_string(),
+ index: index.clone(),
+ id: id.clone(),
+ action_line: String::new(),
+ source_line: None,
+ preset: Some(bulk_item_error(
+ action,
+ &index,
+ &id,
+ 400,
+ "missing document body",
+ )),
+ concrete: String::new(),
+ });
+ continue;
+ }
+ let mut action_obj = serde_json::Map::new();
+ action_obj.insert(action.to_string(), meta);
+ let action_line = serde_json::to_string(&Value::Object(action_obj))
+ .unwrap_or_else(|_| raw_action.to_string());
+ pieces.push(BulkPiece {
+ action: action.to_string(),
+ index,
+ id,
+ action_line,
+ source_line: if action == "delete" {
+ None
+ } else {
+ source_line
+ },
+ preset: None,
+ concrete: String::new(),
+ });
+ }
+ pieces
+}
+
+fn group_ndjson(pieces: &[BulkPiece], which: &[usize]) -> String {
+ let mut body = String::new();
+ for &at in which {
+ body.push_str(&pieces[at].action_line);
+ body.push('\n');
+ if let Some(source) = &pieces[at].source_line {
+ body.push_str(source);
+ body.push('\n');
+ }
+ }
+ body
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct BulkWire {
+ version: u64,
+ seq_no: u64,
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct PrimaryBulkReply {
+ took_ms: u64,
+ errors: bool,
+ items: Vec<xerj_engine::bulk::BulkItemResult>,
+ wire: Vec<Option<BulkWire>>,
+}
+
+fn nack_reason(result: &ShardResult) -> String {
+ serde_json::from_str::<Value>(&result.body)
+ .ok()
+ .and_then(|value| {
+ value
+ .pointer("/error/reason")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ })
+ .unwrap_or_else(|| result.body.clone())
+}
+
+fn mark_bulk_nack(item: &mut xerj_engine::bulk::BulkItemResult, nack: &ShardResult) {
+ item.status = nack.status;
+ item.result = None;
+ item.get_source = None;
+ item.error = Some(nack_reason(nack));
+}
+
+fn wire_of(engine: &xerj_engine::Engine, index: &str, id: &str) -> Option<(u64, u64)> {
+ let idx = engine.get_index(index).ok()?;
+ Some((
+ idx.lookup_version(id).unwrap_or(1),
+ idx.lookup_seq_no(id).unwrap_or(0),
+ ))
+}
+
+/// Run the local bulk pipeline, then copy each success onto the in-sync replicas.
+///
+/// A noop update is not copied: the source did not change. A failed item is
+/// not copied. A copy that misses quorum replaces that item's success with
+/// the same `replica_not_acknowledged` a single-document write returns. The
+/// primary already has the write.
+async fn replicate_bulk_result(
+ state: &AppState,
+ mut result: xerj_engine::bulk::BulkResult,
+) -> (xerj_engine::bulk::BulkResult, Vec<Option<(u64, u64)>>) {
+ let mut wire = Vec::with_capacity(result.items.len());
+ // `item` borrows `result.items`, so the flag is applied after the loop.
+ let mut copy_failed = false;
+ for item in &mut result.items {
+ let failed = item.error.is_some() || !(200..300).contains(&item.status);
+ if failed || item.id.is_empty() {
+ if !failed && item.id.is_empty() {
+ item.status = 503;
+ item.result = None;
+ item.error = Some(
+ "bulk item was acknowledged without an id, so it was not copied".to_string(),
+ );
+ copy_failed = true;
+ }
+ wire.push(None);
+ continue;
+ }
+ let concrete = concrete_index_name(&state.engine, &item.index);
+ if item.action == "delete" {
+ let index = concrete.clone();
+ let id = item.id.clone();
+ let op = ShardOp::DeleteDoc {
+ index: index.clone(),
+ id: id.clone(),
+ if_seq_no: None,
+ if_primary_term: None,
+ replica: false,
+ shard: 0,
+ };
+ if let Err(nack) = replicate_write(state, &index, &id, op).await {
+ mark_bulk_nack(item, &nack);
+ copy_failed = true;
+ }
+ wire.push(None);
+ continue;
+ }
+ if item.result.as_deref() == Some("noop") {
+ wire.push(wire_of(&state.engine, &concrete, &item.id));
+ continue;
+ }
+ let op = match state.engine.get_index(&concrete) {
+ Ok(idx) => match idx.get_document(&item.id).await {
+ Ok(Some(doc)) => match serde_json::to_string(&doc) {
+ Ok(source_json) => ShardOp::IndexDoc {
+ index: concrete.clone(),
+ id: item.id.clone(),
+ source_json,
+ op: "index".to_string(),
+ if_seq_no: None,
+ if_primary_term: None,
+ version: None,
+ version_type: None,
+ replica: false,
+ shard: 0,
+ },
+ Err(err) => {
+ mark_bulk_nack(
+ item,
+ &ShardResult::http(
+ 503,
+ json!({
+ "error": {
+ "type": "replica_not_acknowledged",
+ "reason": format!(
+ "primary applied the bulk item on [{concrete}] but document [{}] is not JSON: {err}",
+ item.id
+ )
+ },
+ "status": 503
+ })
+ .to_string(),
+ ),
+ );
+ copy_failed = true;
+ wire.push(None);
+ continue;
+ }
+ },
+ Ok(None) => ShardOp::DeleteDoc {
+ index: concrete.clone(),
+ id: item.id.clone(),
+ if_seq_no: None,
+ if_primary_term: None,
+ replica: false,
+ shard: 0,
+ },
+ Err(err) => {
+ mark_bulk_nack(
+ item,
+ &ShardResult::http(
+ 503,
+ json!({
+ "error": {
+ "type": "replica_not_acknowledged",
+ "reason": format!(
+ "primary applied the bulk item on [{concrete}] but document [{}] could not be read: {err}",
+ item.id
+ )
+ },
+ "status": 503
+ })
+ .to_string(),
+ ),
+ );
+ copy_failed = true;
+ wire.push(None);
+ continue;
+ }
+ },
+ Err(err) => {
+ mark_bulk_nack(
+ item,
+ &ShardResult::http(
+ 503,
+ json!({
+ "error": {
+ "type": "replica_not_acknowledged",
+ "reason": format!(
+ "primary applied the bulk item but [{concrete}] is not open: {err}"
+ )
+ },
+ "status": 503
+ })
+ .to_string(),
+ ),
+ );
+ copy_failed = true;
+ wire.push(None);
+ continue;
+ }
+ };
+ let index = op_index(&op).to_string();
+ if let Err(nack) = replicate_write(state, &index, &item.id, op).await {
+ mark_bulk_nack(item, &nack);
+ copy_failed = true;
+ wire.push(None);
+ continue;
+ }
+ wire.push(wire_of(&state.engine, &concrete, &item.id));
+ }
+ if copy_failed {
+ result.errors = true;
+ }
+ (result, wire)
+}
+
+fn op_index(op: &ShardOp) -> &str {
+ match op {
+ ShardOp::IndexDoc { index, .. }
+ | ShardOp::DeleteDoc { index, .. }
+ | ShardOp::UpdateDoc { index, .. } => index,
+ _ => "",
+ }
+}
+
+fn bulk_opts_from_parts(
+ require_alias: Option<bool>,
+ default_pipeline: Option<String>,
+ default_source_req_json: Option<String>,
+) -> xerj_engine::bulk::BulkOpts {
+ xerj_engine::bulk::BulkOpts {
+ require_alias,
+ default_pipeline,
+ default_source_req: default_source_req_json
+ .and_then(|json| serde_json::from_str(&json).ok()),
+ }
+}
+
+async fn run_primary_bulk(
+ state: &AppState,
+ body: &str,
+ default_index: Option<&str>,
+ opts: xerj_engine::bulk::BulkOpts,
+) -> (xerj_engine::bulk::BulkResult, Vec<Option<(u64, u64)>>) {
+ let result =
+ xerj_engine::bulk::process_bulk_with_opts(&state.engine, default_index, body, opts).await;
+ replicate_bulk_result(state, result).await
+}
+
+/// Refuse a forwarded bulk that names a shard this node does not own, and
+/// wait until every named index is open. Either check happens before any
+/// document is written.
+fn bulk_refused_here(state: &AppState, pieces: &[BulkPiece]) -> Option<ShardResult> {
+ let me = state.engine.routing_node_id();
+ for piece in pieces {
+ if piece.preset.is_some() {
+ continue;
+ }
+ let concrete = concrete_index_name(&state.engine, &piece.index);
+ if state.engine.get_index(&concrete).is_err() {
+ return Some(ShardResult::http(503, shard_not_ready_body(&piece.index)));
+ }
+ if state.engine.owns_shard(&concrete, &piece.id) {
+ continue;
+ }
+ if let Some(owner) = state.engine.route_write(&concrete, &piece.id) {
+ if owner != me {
+ return Some(not_this_primary(&piece.index, &owner));
+ }
+ }
+ }
+ None
+}
+
+async fn handle_bulk(
+ state: &AppState,
+ body: &str,
+ default_index: Option<&str>,
+ require_alias: Option<bool>,
+ default_pipeline: Option<String>,
+ default_source_req_json: Option<String>,
+) -> ShardResult {
+ let pieces = split_bulk_pieces(body, default_index);
+ if let Some(refused) = bulk_refused_here(state, &pieces) {
+ return refused;
+ }
+ let opts = bulk_opts_from_parts(require_alias, default_pipeline, default_source_req_json);
+ let (result, wire) = run_primary_bulk(state, body, default_index, opts).await;
+ let reply = PrimaryBulkReply {
+ took_ms: result.took_ms,
+ errors: result.errors,
+ items: result.items,
+ wire: wire
+ .into_iter()
+ .map(|item| item.map(|(version, seq_no)| BulkWire { version, seq_no }))
+ .collect(),
+ };
+ let body = serde_json::to_string(&reply).unwrap_or_else(|_| {
+ json!({
+ "took_ms": 0,
+ "errors": true,
+ "items": [],
+ "wire": []
+ })
+ .to_string()
+ });
+ ShardResult::http(200, body)
+}
+
+struct OwnerGroup {
+ remote: bool,
+ owner: String,
+ pieces: Vec<usize>,
+}
+
+fn spread_group_failure(
+ pieces: &[BulkPiece],
+ which: &[usize],
+ status: u16,
+ error: String,
+) -> (
+ Vec<xerj_engine::bulk::BulkItemResult>,
+ Vec<Option<(u64, u64)>>,
+) {
+ let items = which
+ .iter()
+ .map(|&at| {
+ bulk_item_error(
+ &pieces[at].action,
+ &pieces[at].index,
+ &pieces[at].id,
+ status,
+ error.clone(),
+ )
+ })
+ .collect();
+ (items, vec![None; which.len()])
+}
+
+async fn execute_owner_group(
+ state: &AppState,
+ pieces: &[BulkPiece],
+ group: &OwnerGroup,
+ opts: &xerj_engine::bulk::BulkOpts,
+ default_index: Option<&str>,
+) -> (
+ Vec<xerj_engine::bulk::BulkItemResult>,
+ Vec<Option<(u64, u64)>>,
+) {
+ let body = group_ndjson(pieces, &group.pieces);
+ if !group.remote {
+ let (result, wire) = run_primary_bulk(state, &body, default_index, opts.clone()).await;
+ return align_group(pieces, &group.pieces, result, wire);
+ }
+ let op = ShardOp::Bulk {
+ body,
+ default_index: default_index.map(str::to_string),
+ require_alias: opts.require_alias,
+ default_pipeline: opts.default_pipeline.clone(),
+ default_source_req_json: opts
+ .default_source_req
+ .as_ref()
+ .and_then(|value| serde_json::to_string(value).ok()),
+ };
+ let deadline = Instant::now() + OWNER_READY_WAIT;
+ loop {
+ match state.engine.forward_shard(&group.owner, op.clone()).await {
+ Ok(result) if is_shard_not_ready(&result) && Instant::now() < deadline => {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ Ok(result) if (200..300).contains(&result.status) => {
+ match serde_json::from_str::<PrimaryBulkReply>(&result.body) {
+ Ok(reply) => {
+ let wire = reply
+ .wire
+ .into_iter()
+ .map(|item| item.map(|wire| (wire.version, wire.seq_no)))
+ .collect();
+ let result = xerj_engine::bulk::BulkResult {
+ took_ms: reply.took_ms,
+ errors: reply.errors,
+ items: reply.items,
+ };
+ return align_group(pieces, &group.pieces, result, wire);
+ }
+ Err(err) => {
+ return spread_group_failure(
+ pieces,
+ &group.pieces,
+ 503,
+ format!("primary bulk response was not usable: {err}"),
+ );
+ }
+ }
+ }
+ Ok(result) => {
+ return spread_group_failure(
+ pieces,
+ &group.pieces,
+ result.status,
+ nack_reason(&result),
+ );
+ }
+ Err(err) => {
+ return spread_group_failure(pieces, &group.pieces, 503, err.to_string());
+ }
+ }
+ }
+}
+
+fn align_group(
+ pieces: &[BulkPiece],
+ which: &[usize],
+ mut result: xerj_engine::bulk::BulkResult,
+ mut wire: Vec<Option<(u64, u64)>>,
+) -> (
+ Vec<xerj_engine::bulk::BulkItemResult>,
+ Vec<Option<(u64, u64)>>,
+) {
+ if result.items.len() == which.len() {
+ if wire.len() < which.len() {
+ wire.resize(which.len(), None);
+ }
+ wire.truncate(which.len());
+ return (result.items, wire);
+ }
+ if result.items.len() == 1 && result.errors {
+ let err = result.items.pop().expect("length checked");
+ let reason = err
+ .error
+ .unwrap_or_else(|| "bulk request failed".to_string());
+ return spread_group_failure(pieces, which, err.status, reason);
+ }
+ spread_group_failure(
+ pieces,
+ which,
+ 500,
+ format!(
+ "primary returned {} bulk items for {} actions",
+ result.items.len(),
+ which.len()
+ ),
+ )
+}
+
+/// Route a bulk body to each action's primary and copy the successes.
+///
+/// [`crate::es_compat`] calls this only when a cluster handle is attached.
+/// The returned wire versions are the primary's. The accepting node does not
+/// have the document, so a local lookup would report a fresh id.
+pub(crate) async fn bulk_on_primaries(
+ state: &AppState,
+ default_index: Option<&str>,
+ body: &str,
+ opts: xerj_engine::bulk::BulkOpts,
+) -> (xerj_engine::bulk::BulkResult, Vec<Option<(u64, u64)>>) {
+ let started = Instant::now();
+ let line_count = body.lines().filter(|line| !line.trim().is_empty()).count();
+ let max_actions = state.engine.config().limits.max_actions_per_bulk;
+ if line_count == 0 || (max_actions > 0 && line_count > max_actions.saturating_mul(2)) {
+ let result =
+ xerj_engine::bulk::process_bulk_with_opts(&state.engine, default_index, body, opts)
+ .await;
+ let wire = vec![None; result.items.len()];
+ return (result, wire);
+ }
+
+ let mut pieces = split_bulk_pieces(body, default_index);
+ let mut ensured: HashMap<String, Result<String, (u16, String)>> = HashMap::new();
+ for piece in &mut pieces {
+ if piece.preset.is_some() {
+ continue;
+ }
+ let outcome = if let Some(cached) = ensured.get(&piece.index) {
+ cached.clone()
+ } else {
+ let outcome = match ensure_concrete_index(state, &piece.index).await {
+ Ok(name) => Ok(name),
+ Err(err) => Err(ensure_fail_status(err)),
+ };
+ ensured.insert(piece.index.clone(), outcome.clone());
+ outcome
+ };
+ match outcome {
+ Ok(name) => piece.concrete = name,
+ Err((status, reason)) => {
+ piece.preset = Some(bulk_item_error(
+ &piece.action,
+ &piece.index,
+ &piece.id,
+ status,
+ reason,
+ ));
+ }
+ }
+ }
+
+ let mut groups: Vec<OwnerGroup> = Vec::new();
+ for (at, piece) in pieces.iter().enumerate() {
+ if piece.preset.is_some() {
+ continue;
+ }
+ let remote = if state.engine.owns_shard(&piece.concrete, &piece.id) {
+ None
+ } else {
+ state.engine.route_write(&piece.concrete, &piece.id)
+ };
+ let owner = remote.clone().unwrap_or_default();
+ if let Some(group) = groups
+ .iter_mut()
+ .find(|group| group.remote == remote.is_some() && group.owner == owner)
+ {
+ group.pieces.push(at);
+ } else {
+ groups.push(OwnerGroup {
+ remote: remote.is_some(),
+ owner,
+ pieces: vec![at],
+ });
+ }
+ }
+
+ let mut items: Vec<Option<xerj_engine::bulk::BulkItemResult>> =
+ pieces.iter().map(|piece| piece.preset.clone()).collect();
+ let mut wire = vec![None; pieces.len()];
+ for group in &groups {
+ let (group_items, group_wire) =
+ execute_owner_group(state, &pieces, group, &opts, default_index).await;
+ for (slot, (item, item_wire)) in group
+ .pieces
+ .iter()
+ .zip(group_items.into_iter().zip(group_wire))
+ {
+ items[*slot] = Some(item);
+ wire[*slot] = item_wire;
+ }
+ }
+ let items: Vec<_> = items
+ .into_iter()
+ .enumerate()
+ .map(|(at, item)| {
+ item.unwrap_or_else(|| {
+ bulk_item_error(
+ pieces
+ .get(at)
+ .map(|piece| piece.action.as_str())
+ .unwrap_or("index"),
+ pieces
+ .get(at)
+ .map(|piece| piece.index.as_str())
+ .unwrap_or(""),
+ pieces.get(at).map(|piece| piece.id.as_str()).unwrap_or(""),
+ 500,
+ "bulk item was not executed",
+ )
+ })
+ })
+ .collect();
+ let errors = items
+ .iter()
+ .any(|item| item.error.is_some() || !(200..300).contains(&item.status));
+ (
+ xerj_engine::bulk::BulkResult {
+ took_ms: started.elapsed().as_millis() as u64,
+ errors,
+ items,
+ },
+ wire,
+ )
+}
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 4dddc4284..aba56139c 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -20449,9 +20449,19 @@ async fn process_bulk_body(
)
});
- let result =
- xerj_engine::bulk::process_bulk_with_opts(&state.engine, default_index, text_ref, opts)
- .await;
+ // Cluster mode routes each action to its shard primary and copies the
+ // stored document. No cluster handle: the local bulk pipeline, unchanged.
+ // `wire` is the primary's `_version` / `_seq_no`. The accepting node does
+ // not have the document, so the lookup below would report a fresh id.
+ let (result, wire) = if state.engine.has_cluster() {
+ crate::cluster_shard::bulk_on_primaries(state, default_index, text_ref, opts).await
+ } else {
+ (
+ xerj_engine::bulk::process_bulk_with_opts(&state.engine, default_index, text_ref, opts)
+ .await,
+ Vec::new(),
+ )
+ };
let took_ms = result.took_ms;
let errors = result.errors;
@@ -20476,7 +20486,7 @@ async fn process_bulk_body(
let mut audited_index_names: std::collections::BTreeSet<String> =
std::collections::BTreeSet::new();
let mut items: Vec<EsBulkItem> = Vec::with_capacity(result.items.len());
- for item in result.items {
+ for (ordinal, item) in result.items.into_iter().enumerate() {
let failed = item.error.is_some() || !(200..300).contains(&item.status);
if failed {
failed_items += 1;
@@ -20498,6 +20508,13 @@ async fn process_bulk_body(
// `status: 400` reads as "this write landed".
let (version, seq_no, primary_term, shards) = if failed {
(None, None, None, None)
+ } else if let Some((version, seq_no)) = wire.get(ordinal).copied().flatten() {
+ (
+ Some(version),
+ Some(seq_no),
+ Some(1),
+ Some(crate::responses::EsShards::single_success()),
+ )
} else {
let (version, seq_no) = state
.engine
@@ -23056,7 +23073,7 @@ fn format_date(dt: chrono::DateTime<chrono::Utc>, fmt: &str) -> String {
// POST /{index}/_update/{id}
// ─────────────────────────────────────────────────────────────────────────────
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Serialize, Deserialize)]
pub struct EsUpdateBody {
/// Partial document fields to merge into existing source.
pub doc: Option<Value>,
@@ -23076,7 +23093,7 @@ pub struct EsUpdateBody {
}
/// Query parameters for the `_update` endpoint.
-#[derive(Debug, Default, Deserialize)]
+#[derive(Debug, Default, Serialize, Deserialize)]
pub struct UpdateDocParams {
/// `refresh=true|wait_for` — accepted without error; memtable is always visible.
pub refresh: Option<String>,
@@ -23162,6 +23179,13 @@ pub(crate) fn parse_update_body(body: &[u8]) -> Result<EsUpdateBody, xerj_common
})
}
+pub(crate) struct LocalUpdate {
+ pub response: axum::response::Response,
+ /// The primary stored a new source. A cluster caller copies it. A noop,
+ /// a miss, and every error leave this false.
+ pub replicate: bool,
+}
+
pub async fn update_doc(
State(state): State<AppState>,
Path((index, id)): Path<(String, String)>,
@@ -23174,9 +23198,36 @@ pub async fn update_doc(
Ok(body) => body,
Err(e) => return ApiError::new(e).into_response(),
};
- let idx = match state.engine.get_or_create_index(&index) {
+ if state.engine.has_cluster() {
+ match crate::cluster_shard::dispatch_update(&state, &index, &id, &body, &query_params).await
+ {
+ crate::cluster_shard::Dispatch::Done(response) => return response,
+ crate::cluster_shard::Dispatch::Local => {}
+ }
+ }
+ apply_local_update(&state, &index, &id, body, &query_params)
+ .await
+ .response
+}
+
+pub(crate) async fn apply_local_update(
+ state: &AppState,
+ index: &str,
+ id: &str,
+ body: EsUpdateBody,
+ query_params: &UpdateDocParams,
+) -> LocalUpdate {
+ fn settled(response: impl IntoResponse, replicate: bool) -> LocalUpdate {
+ LocalUpdate {
+ response: response.into_response(),
+ replicate,
+ }
+ }
+ let idx = match state.engine.get_or_create_index(index) {
Ok(i) => i,
- Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),
+ Err(e) => {
+ return settled(ApiError::new(xerj_common::XerjError::from(e)), false);
+ }
};
// ── Scripted update path ────────────────────────────────────────────────
@@ -23186,7 +23237,10 @@ pub async fn update_doc(
if let Some(script_val) = body.script.as_ref() {
let (src, params) = extract_update_script(script_val);
if src.is_empty() {
- return update_script_bad_request("script source is required".to_string());
+ return settled(
+ update_script_bad_request("script source is required".to_string()),
+ false,
+ );
}
let upsert_body = body.upsert.clone().or_else(|| {
if body.doc_as_upsert {
@@ -23202,7 +23256,7 @@ pub async fn update_doc(
let (transformed, fault) = xerj_engine::painless::with_script_fault_capture(
xerj_engine::painless::with_script_deadline(
deadline,
- idx.transform_document_serialized(&id, upsert_body, move |mut current| {
+ idx.transform_document_serialized(id, upsert_body, move |mut current| {
apply_painless_update(&mut current, &src, &params)?;
Ok::<_, String>(current)
}),
@@ -23210,65 +23264,66 @@ pub async fn update_doc(
)
.await;
if let Some(reason) = fault {
- return script_limit_response(&reason);
+ return settled(script_limit_response(&reason), false);
}
match transformed {
Ok(Ok(Some(outcome))) => {
- state.metrics.record_doc_indexed(&index);
+ state.metrics.record_doc_indexed(index);
let resp = outcome.response;
let mut er = if outcome.created {
crate::responses::EsDocResponse::created(
- &index,
+ index,
&resp.id,
resp.version,
resp.seq_no.saturating_sub(1),
)
} else {
crate::responses::EsDocResponse::updated(
- &index,
+ index,
&resp.id,
resp.version,
resp.seq_no.saturating_sub(1),
)
};
- if update_wants_get(&query_params) {
- er.get = Some(build_update_get_field(&idx, &resp.id, &query_params).await);
+ if update_wants_get(query_params) {
+ er.get = Some(build_update_get_field(&idx, &resp.id, query_params).await);
}
- return Json(er).into_response();
+ return settled(Json(er), true);
}
Ok(Ok(None)) => {
- let e = xerj_common::XerjError::document_not_found(&id, &index);
- return ApiError::new(e).into_response();
+ let e = xerj_common::XerjError::document_not_found(id, index);
+ return settled(ApiError::new(e), false);
}
- Ok(Err(error)) => return update_script_bad_request(error),
+ Ok(Err(error)) => return settled(update_script_bad_request(error), false),
Err(error) => {
- return ApiError::new(xerj_common::XerjError::from(error)).into_response();
+ return settled(ApiError::new(xerj_common::XerjError::from(error)), false);
}
}
}
match idx
- .update_document_with_upsert(&id, body.doc, body.upsert, body.doc_as_upsert)
+ .update_document_with_upsert(id, body.doc, body.upsert, body.doc_as_upsert)
.await
{
Ok(Some(resp)) => {
- state.metrics.record_doc_indexed(&index);
+ let replicate = resp.result != "noop";
+ state.metrics.record_doc_indexed(index);
let mut er = crate::responses::EsDocResponse::updated(
- &index,
+ index,
&resp.id,
resp.version,
resp.seq_no.saturating_sub(1),
);
- if update_wants_get(&query_params) {
- er.get = Some(build_update_get_field(&idx, &resp.id, &query_params).await);
+ if update_wants_get(query_params) {
+ er.get = Some(build_update_get_field(&idx, &resp.id, query_params).await);
}
- Json(er).into_response()
+ settled(Json(er), replicate)
}
Ok(None) => {
- let e = xerj_common::XerjError::document_not_found(&id, &index);
- ApiError::new(e).into_response()
+ let e = xerj_common::XerjError::document_not_found(id, index);
+ settled(ApiError::new(e), false)
}
- Err(e) => ApiError::new(xerj_common::XerjError::from(e)).into_response(),
+ Err(e) => settled(ApiError::new(xerj_common::XerjError::from(e)), false),
}
}
diff --git a/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs b/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs
index e31368a16..4a344e10d 100644
--- a/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs
+++ b/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs
@@ -115,6 +115,17 @@ async fn post_json(app: &Router, path: &str, body: Value) -> (StatusCode, Value)
.await
}
+async fn post_ndjson(app: &Router, path: &str, body: &str) -> (StatusCode, Value) {
+ send(
+ app,
+ Request::post(path)
+ .header("content-type", "application/x-ndjson")
+ .body(Body::from(body.to_string()))
+ .expect("request"),
+ )
+ .await
+}
+
async fn get(app: &Router, path: &str) -> (StatusCode, Value) {
send(
app,
@@ -355,6 +366,44 @@ async fn cluster_disabled_create_stays_on_the_node_that_received_it() {
Some(1),
"single-node search stays one document: {body}"
);
+
+ let (status, body) = post_ndjson(
+ &a,
+ "/local/_bulk",
+ "{\"index\":{\"_id\":\"b1\"}}\n{\"title\":\"bulk\"}\n",
+ )
+ .await;
+ assert!(status.is_success(), "single-node bulk: {status} {body}");
+ assert_eq!(
+ body.pointer("/errors").and_then(|v| v.as_bool()),
+ Some(false),
+ "{body}"
+ );
+ let (status, got) = get(&a, "/local/_doc/b1").await;
+ assert_eq!(status, StatusCode::OK, "{got}");
+ let (status, _) = get(&b, "/local/_doc/b1").await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ let (status, body) = post_json(
+ &a,
+ "/local/_update/b1",
+ json!({ "doc": { "title": "patched" } }),
+ )
+ .await;
+ assert!(status.is_success(), "single-node update: {status} {body}");
+ let (status, got) = get(&a, "/local/_doc/b1").await;
+ assert_eq!(status, StatusCode::OK, "{got}");
+ assert_eq!(
+ got.pointer("/_source/title").and_then(|v| v.as_str()),
+ Some("patched")
+ );
+ let (status, _) = get(&b, "/local/_doc/b1").await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ let (status, _) = get(&a, "/.xerj_replica_local_0/_doc/b1").await;
+ assert_eq!(
+ status,
+ StatusCode::NOT_FOUND,
+ "single-node bulk and update do not open a replica store"
+ );
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
@@ -1885,3 +1934,365 @@ async fn a_restarted_replica_is_refilled_to_the_primary_live_set_before_it_rejoi
create_replicated_orders(&members).await;
refill_after_missed_writes(members, Some(&bus)).await;
}
+
+fn bulk_item(body: &Value, at: usize) -> &Value {
+ let item = body
+ .pointer(&format!("/items/{at}"))
+ .unwrap_or_else(|| panic!("bulk response has no item {at}: {body}"));
+ item.as_object()
+ .and_then(|obj| obj.values().next())
+ .unwrap_or_else(|| panic!("bulk item {at} has no action: {item}"))
+}
+
+async fn user_source(member: &Member, id: &str) -> Option<Value> {
+ member
+ .engine
+ .get_index("orders")
+ .expect("orders is open")
+ .get_document(id)
+ .await
+ .expect("get")
+}
+
+async fn replica_source(member: &Member, shard: u32, id: &str) -> Option<Value> {
+ let store = xerj_cluster::replica_index_name("orders", shard).expect("store name");
+ member
+ .engine
+ .get_index(&store)
+ .unwrap_or_else(|_| panic!("replica store {store} is not open"))
+ .get_document(id)
+ .await
+ .expect("replica get")
+}
+
+/// `_bulk` and `_update` accepted by a node that does not own the id are
+/// applied on the primary and copied onto the in-sync replica. The receiving
+/// node's user index does not keep them.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn bulk_and_update_from_a_non_owner_write_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!("b{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 bulk = format!(
+ "{{\"index\":{{\"_index\":\"orders\",\"_id\":\"{id_a}\"}}}}\n\
+ {{\"title\":\"bulk\",\"n\":1}}\n\
+ {{\"create\":{{\"_index\":\"orders\",\"_id\":\"{id_b}\"}}}}\n\
+ {{\"title\":\"other\"}}\n\
+ {{\"update\":{{\"_index\":\"orders\",\"_id\":\"{id_a}\"}}}}\n\
+ {{\"doc\":{{\"via\":\"bulk-update\"}}}}\n\
+ {{\"index\":{{\"_index\":\"orders\"}}}}\n\
+ {{\"title\":\"auto\"}}\n"
+ );
+ let (status, body) = post_ndjson(&members[writer].app, "/_bulk", &bulk).await;
+ assert!(status.is_success(), "bulk from non-owner: {status} {body}");
+ assert_eq!(
+ body.pointer("/errors").and_then(|v| v.as_bool()),
+ Some(false),
+ "{body}"
+ );
+ assert_eq!(
+ bulk_item(&body, 0).get("result").and_then(|v| v.as_str()),
+ Some("created"),
+ "{body}"
+ );
+ assert_eq!(
+ bulk_item(&body, 1).get("result").and_then(|v| v.as_str()),
+ Some("created"),
+ "{body}"
+ );
+ assert_eq!(
+ bulk_item(&body, 2).get("result").and_then(|v| v.as_str()),
+ Some("updated"),
+ "bulk update merged on the primary: {body}"
+ );
+ let auto_id = bulk_item(&body, 3)
+ .get("_id")
+ .and_then(|v| v.as_str())
+ .unwrap_or_else(|| panic!("auto id: {body}"))
+ .to_string();
+ assert!(!auto_id.is_empty());
+
+ let on_primary = user_source(&members[primary_a], &id_a).await;
+ assert_eq!(
+ on_primary
+ .as_ref()
+ .and_then(|doc| doc.get("via"))
+ .and_then(|v| v.as_str()),
+ Some("bulk-update"),
+ "primary has the bulk update: {on_primary:?}"
+ );
+ let on_replica = replica_source(&members[replica_a], shard_a, &id_a).await;
+ assert_eq!(
+ on_replica
+ .as_ref()
+ .and_then(|doc| doc.get("title"))
+ .and_then(|v| v.as_str()),
+ Some("bulk"),
+ "replica copied the bulk update: {on_replica:?}"
+ );
+ assert_eq!(
+ on_replica
+ .as_ref()
+ .and_then(|doc| doc.get("via"))
+ .and_then(|v| v.as_str()),
+ Some("bulk-update")
+ );
+ for (at, member) in members.iter().enumerate() {
+ if at == primary_a {
+ continue;
+ }
+ assert!(
+ user_source(member, &id_a).await.is_none(),
+ "node {at} user index stored {id_a}"
+ );
+ }
+ let on_b = replica_source(&members[replica_b], shard_b, &id_b).await;
+ assert_eq!(
+ on_b.as_ref()
+ .and_then(|doc| doc.get("title"))
+ .and_then(|v| v.as_str()),
+ Some("other"),
+ "create in the same bulk reached the other primary's replica: {on_b:?}"
+ );
+ assert!(
+ user_source(&members[writer], &id_b).await.is_none(),
+ "the receiver stored {id_b}"
+ );
+
+ let mut holders = Vec::new();
+ for (at, member) in members.iter().enumerate() {
+ if user_source(member, &auto_id).await.is_some() {
+ holders.push(at);
+ }
+ }
+ assert_eq!(
+ holders,
+ vec![members
+ .iter()
+ .position(|member| member.engine.owns_shard("orders", &auto_id))
+ .expect("auto-id has a primary")],
+ "an id assigned before routing has one user-index copy"
+ );
+ let auto_primary = holders[0];
+ let (auto_shard, _) = members[auto_primary]
+ .engine
+ .primary_of("orders", &auto_id)
+ .expect("auto placement");
+ let auto_replicas = members[auto_primary]
+ .engine
+ .replica_nodes("orders", auto_shard);
+ assert_eq!(auto_replicas.len(), 1);
+ let auto_replica = members
+ .iter()
+ .position(|member| member.handle.node_id() == auto_replicas[0])
+ .expect("auto replica");
+ let auto_copy = replica_source(&members[auto_replica], auto_shard, &auto_id).await;
+ assert_eq!(
+ auto_copy
+ .as_ref()
+ .and_then(|doc| doc.get("title"))
+ .and_then(|v| v.as_str()),
+ Some("auto"),
+ "{auto_copy:?}"
+ );
+
+ let overwrite = format!(
+ "{{\"index\":{{\"_index\":\"orders\",\"_id\":\"{id_a}\"}}}}\n\
+ {{\"title\":\"from-primary\",\"n\":1}}\n"
+ );
+ let (status, body) = post_ndjson(&members[primary_a].app, "/orders/_bulk", &overwrite).await;
+ assert!(status.is_success(), "bulk on the primary: {status} {body}");
+ assert_eq!(
+ body.pointer("/errors").and_then(|v| v.as_bool()),
+ Some(false),
+ "{body}"
+ );
+ let on_replica = replica_source(&members[replica_a], shard_a, &id_a).await;
+ assert_eq!(
+ on_replica
+ .as_ref()
+ .and_then(|doc| doc.get("title"))
+ .and_then(|v| v.as_str()),
+ Some("from-primary"),
+ "a bulk the primary itself accepts is still copied: {on_replica:?}"
+ );
+
+ let (status, body) = post_json(
+ &members[writer].app,
+ &format!("/orders/_update/{id_a}"),
+ json!({ "doc": { "extra": "yes", "n": 2 } }),
+ )
+ .await;
+ assert!(
+ status.is_success(),
+ "update from non-owner: {status} {body}"
+ );
+ assert_eq!(
+ body.get("result").and_then(|v| v.as_str()),
+ Some("updated"),
+ "{body}"
+ );
+ let on_primary = user_source(&members[primary_a], &id_a)
+ .await
+ .expect("primary");
+ assert_eq!(
+ on_primary.get("extra").and_then(|v| v.as_str()),
+ Some("yes"),
+ "{on_primary}"
+ );
+ assert_eq!(on_primary.get("n").and_then(|v| v.as_u64()), Some(2));
+ let on_replica = replica_source(&members[replica_a], shard_a, &id_a)
+ .await
+ .expect("replica");
+ assert_eq!(
+ on_replica.get("extra").and_then(|v| v.as_str()),
+ Some("yes")
+ );
+ assert_eq!(
+ on_replica.get("title").and_then(|v| v.as_str()),
+ Some("from-primary")
+ );
+ assert!(user_source(&members[writer], &id_a).await.is_none());
+
+ let (status, body) = post_json(
+ &members[writer].app,
+ &format!("/orders/_update/{id_a}"),
+ json!({ "script": { "source": "ctx._source.title = 'scripted'" } }),
+ )
+ .await;
+ assert!(
+ status.is_success(),
+ "scripted update from non-owner: {status} {body}"
+ );
+ let on_primary = user_source(&members[primary_a], &id_a)
+ .await
+ .expect("primary");
+ assert_eq!(
+ on_primary.get("title").and_then(|v| v.as_str()),
+ Some("scripted"),
+ "the script ran where the document is: {on_primary}"
+ );
+ assert_eq!(
+ on_primary.get("extra").and_then(|v| v.as_str()),
+ Some("yes")
+ );
+ let on_replica = replica_source(&members[replica_a], shard_a, &id_a)
+ .await
+ .expect("replica");
+ assert_eq!(
+ on_replica.get("title").and_then(|v| v.as_str()),
+ Some("scripted"),
+ "{on_replica}"
+ );
+
+ let deletion = format!("{{\"delete\":{{\"_index\":\"orders\",\"_id\":\"{id_b}\"}}}}\n");
+ let (status, body) = post_ndjson(&members[writer].app, "/_bulk", &deletion).await;
+ assert!(status.is_success(), "bulk delete: {status} {body}");
+ assert_eq!(
+ body.pointer("/errors").and_then(|v| v.as_bool()),
+ Some(false),
+ "{body}"
+ );
+ assert!(user_source(&members[primary_b], &id_b).await.is_none());
+ assert!(
+ replica_source(&members[replica_b], shard_b, &id_b)
+ .await
+ .is_none(),
+ "the replica still has the deleted document"
+ );
+ let (status, body) = get(&members[writer].app, &format!("/orders/_doc/{id_b}")).await;
+ assert_eq!(status, StatusCode::NOT_FOUND, "{body}");
+
+ members[primary_a].handle.clear_shard_handler();
+ let (status, body) = get(&members[writer].app, &format!("/orders/_doc/{id_a}")).await;
+ assert!(
+ status.is_success(),
+ "GET after the primary stops reads the copy: {status} {body}"
+ );
+ assert_eq!(
+ body.pointer("/_source/title").and_then(|v| v.as_str()),
+ Some("scripted"),
+ "{body}"
+ );
+ let again = format!(
+ "{{\"index\":{{\"_index\":\"orders\",\"_id\":\"{id_a}\"}}}}\n\
+ {{\"title\":\"no-primary\"}}\n"
+ );
+ let (status, body) = post_ndjson(&members[writer].app, "/_bulk", &again).await;
+ assert!(status.is_success(), "bulk HTTP status: {status} {body}");
+ assert_eq!(
+ body.pointer("/errors").and_then(|v| v.as_bool()),
+ Some(true),
+ "{body}"
+ );
+ assert_eq!(
+ bulk_item(&body, 0).get("status").and_then(|v| v.as_u64()),
+ Some(503),
+ "a bulk write still needs the primary: {body}"
+ );
+ let on_replica = replica_source(&members[replica_a], shard_a, &id_a)
+ .await
+ .expect("replica");
+ assert_eq!(
+ on_replica.get("title").and_then(|v| v.as_str()),
+ Some("scripted"),
+ "the refused bulk did not change the copy: {on_replica}"
+ );
+
+ for member in &members {
+ let _ = member.shutdown.send(true);
+ }
+}
diff --git a/engine/crates/xerj-cluster/src/shard.rs b/engine/crates/xerj-cluster/src/shard.rs
index 312c94972..a630aa2ff 100644
--- a/engine/crates/xerj-cluster/src/shard.rs
+++ b/engine/crates/xerj-cluster/src/shard.rs
@@ -225,6 +225,33 @@ pub enum ShardOp {
#[serde(default)]
shard: u32,
},
+ /// Partial or scripted update. The primary applies it, then copies the
+ /// stored document onto the in-sync replicas the same way an index does.
+ ///
+ /// `index` is the name the caller used. An alias is resolved on the
+ /// primary before the write is placed.
+ UpdateDoc {
+ index: String,
+ id: String,
+ /// JSON update body (`doc`, `upsert`, `doc_as_upsert`, `script`).
+ body_json: String,
+ /// JSON update query params (`refresh`, `_source`, includes, excludes).
+ params_json: String,
+ },
+ /// A bulk body whose actions belong to shards this node owns.
+ ///
+ /// The coordinating node assigns missing ids and groups actions by
+ /// primary. This node runs the local bulk pipeline, then copies each
+ /// successful index, create, update, and delete onto the in-sync replicas.
+ Bulk {
+ /// NDJSON. Action lines name `_index` and `_id`.
+ body: String,
+ default_index: Option<String>,
+ require_alias: Option<bool>,
+ default_pipeline: Option<String>,
+ /// JSON value of the URL-level `_source` filter, when one was set.
+ default_source_req_json: Option<String>,
+ },
/// Search this member's local shard only. The caller merges hits.
Search {
index: String,
diff --git a/landing/docs/clustering.html b/landing/docs/clustering.html
index 195d3f673..b6363d09e 100644
--- a/landing/docs/clustering.html
+++ b/landing/docs/clustering.html
@@ -234,12 +234,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>, or <code class="inline">PUT /{index}/_create</code> is stored on the member that owns its shard, whichever node accepted the call. <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">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">Single-document routing only<span class="dsc"><code class="inline">_bulk</code>, <code class="inline">_update</code>, update-by-query, and the native <code class="inline">/v1</code> ingest paths still write on the node that received them. They do not consult the shard plan.</span></div>
+ <div class="item">Update-by-query and native ingest stay on the receiver<span class="dsc"><code class="inline">_update_by_query</code> and 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">_bulk</code> (index, create, update, and delete) and <code class="inline">POST /{index}/_update/{id}</code> run on the primary, and the primary copies the resulting document or delete to the in-sync replicas.</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>
@@ -253,7 +253,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">GET</code> and <code class="inline">DELETE /{index}/_doc/{id}</code> run on the primary. The primary copies an index or delete 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">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. The primary copies an index, a delete, or the document an update 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>
@@ -321,10 +321,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> 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. 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. 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><code class="inline">_bulk</code>, <code class="inline">_update</code>, and the native ingest API</strong> do not route or replicate. A bulk body accepted by one member is indexed there, even when the shard plan says another member owns the id. For a copy of those writes, point the <a href="/docs/config#wal_tap">WAL tap</a> at another XERJ or any ES-compatible target.</li>
+ <li><strong><code class="inline">_update_by_query</code> and the native <code class="inline">/v1</code> ingest API</strong> do not route or replicate. <code class="inline">_bulk</code> and <code class="inline">_update</code> do. 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>
@@ -339,7 +339,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 single-document write 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>, or <code class="inline">_update</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>