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): install a compacted Raft snapshot on a lagging member (#2320)

xerj-org8ee548ab0221
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aa1d9d309..df42558c8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- With `[cluster] enabled = true`, a member compacts its Raft log once
+ 64 metadata entries have been applied since the previous snapshot.
+ The compacted prefix is stored in `{data_dir}/_raft/snapshot.meta` and
+ removed from `raft.log`. A peer whose log does not overlap that prefix
+ receives InstallSnapshot and applies those commands, which installs the
+ same index metadata an AppendEntries catch-up would have. The snapshot
+ is that command prefix, not a smaller folded image and not the
+ documents. A history that does not fit in 8 MiB stays in the log.
+ Restart replays the snapshot and then the entries after it. A node
+ that never stored a document still does not receive it, and a replica
+ removed from the in-sync set stays out (part of
+ [#1170](https://github.com/xerj-org/xerj/issues/1170)).
+
- With `[cluster] enabled = true`, a single-document index or delete is
acknowledged when a quorum of the shard's copies has confirmed, not only
when every placed replica has. Copies are the primary plus the replicas
@@ -34,9 +47,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
starts with an empty log copies the leader's log and applies it, which
installs index metadata (and an empty replica store when this node is
a replica). It does not copy documents written before it joined. A
- replica removed from the in-sync set is not filled in. The log is not
- compacted; there is no InstallSnapshot. Term and vote are stored with
- the log, so a restarted node does not grant a second vote in the same
+ replica removed from the in-sync set is not filled in. Term and vote are
+ stored with the log, so a restarted node does not grant a second vote in the same
term. `[cluster] enabled = false` does not open the log (part of
[#1170](https://github.com/xerj-org/xerj/issues/1170)).
diff --git a/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs b/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs
index 70e8dde3c..60a732736 100644
--- a/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs
+++ b/engine/crates/xerj-api/tests/cluster_metadata_replicates.rs
@@ -1015,3 +1015,157 @@ async fn restart_reloads_the_shard_plan_and_still_routes_the_document() {
let _ = member.shutdown.send(true);
}
}
+
+async fn open_durable_member(
+ id: &str,
+ ids: &[&str],
+ bus: &InMemoryBus,
+ dir: tempfile::TempDir,
+ snapshot_every: u64,
+) -> Member {
+ 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");
+ let state = xerj_api::state::AppState::new(config, engine, metrics);
+ let peers: Vec<String> = ids
+ .iter()
+ .filter(|peer| **peer != id)
+ .map(|peer| (*peer).to_string())
+ .collect();
+ let transport = InMemoryTransport::new(id.to_string(), bus.clone()).await;
+ let raft_dir = xerj_cluster::raft_log::raft_storage_dir(dir.path());
+ let mut node = ClusterNode::with_storage(id.to_string(), peers, Box::new(transport), &raft_dir)
+ .expect("open raft log");
+ node.set_snapshot_every(snapshot_every);
+ node.set_applier(std::sync::Arc::new(EngineMetadataApplier {
+ engine: std::sync::Arc::clone(&state.engine),
+ }));
+ let handle = node.handle();
+ state.engine.attach_cluster(handle.clone());
+ handle.set_shard_handler(std::sync::Arc::new(ApiShardHandler::new(state.clone())));
+ node.replay_committed().await;
+ let engine = std::sync::Arc::clone(&state.engine);
+ let (shutdown, shutdown_rx) = watch::channel(false);
+ let mut runner = ClusterRunner::new(node, Duration::from_millis(5), shutdown_rx);
+ let task = tokio::spawn(async move {
+ runner.run().await;
+ });
+ let app = xerj_api::router::build_es_compat_router(state.clone());
+ Member {
+ app,
+ state,
+ engine,
+ shutdown,
+ handle,
+ _node: None,
+ runner: Some(task),
+ _dir: dir,
+ }
+}
+
+async fn wait_compacted(member: &Member) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ if member.handle.snapshot_index() >= 1 && member.handle.log_len() == 0 {
+ return;
+ }
+ if Instant::now() > deadline {
+ panic!(
+ "leader log was not compacted: snapshot={} log_len={}",
+ member.handle.snapshot_index(),
+ member.handle.log_len()
+ );
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+}
+
+/// The create is compacted out of the leader's log before the third member
+/// starts. That member still gets the index, and a document written afterwards
+/// is readable from a member that was already up.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_late_member_installs_a_compacted_create_and_routes_a_later_write() {
+ let ids = ["n1", "n2", "n3"];
+ let bus = InMemoryBus::new();
+ let mut members = Vec::new();
+ for id in ["n1", "n2"] {
+ let dir = tempfile::tempdir().expect("tempdir");
+ members.push(open_durable_member(id, &ids, &bus, dir, 1).await);
+ }
+ let dead = [false, false];
+ let leader = wait_leader(&members, &dead).await;
+
+ let (status, body) = put_json(
+ &members[0].app,
+ "/orders",
+ json!({ "mappings": { "properties": { "title": { "type": "text" } } } }),
+ )
+ .await;
+ assert!(status.is_success(), "create: {status} {body}");
+ wait_compacted(&members[leader]).await;
+ assert_eq!(
+ members[leader].handle.log_len(),
+ 0,
+ "the create must not still be an AppendEntries payload"
+ );
+
+ let dir = tempfile::tempdir().expect("tempdir");
+ members.push(open_durable_member("n3", &ids, &bus, dir, 64).await);
+ let mapping = wait_body_contains(&members[2].app, "/orders/_mapping", "title").await;
+ assert!(
+ mapping.to_string().contains("title"),
+ "n3 must apply the compacted create: {mapping}"
+ );
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ if members[2].handle.snapshot_index() >= 1 {
+ break;
+ }
+ if Instant::now() > deadline {
+ panic!(
+ "n3 did not install the snapshot: snapshot={} log_len={}",
+ members[2].handle.snapshot_index(),
+ members[2].handle.log_len()
+ );
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+
+ let (status, body) = put_json(
+ &members[2].app,
+ "/orders/_mapping",
+ json!({ "properties": { "note": { "type": "keyword" } } }),
+ )
+ .await;
+ assert!(
+ status.is_success(),
+ "mapping after snapshot: {status} {body}"
+ );
+ for member in &members {
+ wait_body_contains(&member.app, "/orders/_mapping", "note").await;
+ }
+
+ let (status, body) = put_json(
+ &members[2].app,
+ "/orders/_doc/1",
+ json!({ "title": "after" }),
+ )
+ .await;
+ assert!(
+ status.is_success(),
+ "write from the late member: {status} {body}"
+ );
+ for member in &members {
+ let (status, body) = get(&member.app, "/orders/_doc/1").await;
+ assert!(
+ status.is_success(),
+ "doc readable on {}: {status} {body}",
+ member.handle.node_id()
+ );
+ }
+
+ for member in &members {
+ let _ = member.shutdown.send(true);
+ }
+}
diff --git a/engine/crates/xerj-cluster/src/node.rs b/engine/crates/xerj-cluster/src/node.rs
index 3c8aae835..9689e856d 100644
--- a/engine/crates/xerj-cluster/src/node.rs
+++ b/engine/crates/xerj-cluster/src/node.rs
@@ -95,6 +95,8 @@ impl ClusterNode {
node_id: id.clone(),
state: RaftState::Follower,
leader_id: None,
+ snapshot_index: 0,
+ log_len: 0,
}));
let shard = transport.shard_rpc();
let mut members = peers.clone();
@@ -162,6 +164,22 @@ impl ClusterNode {
self.applier = Some(applier);
}
+ /// See [`crate::raft::RaftNode::set_snapshot_every`].
+ pub fn set_snapshot_every(&mut self, every: u64) {
+ self.raft.set_snapshot_every(every);
+ }
+
+ /// Snapshot the applied prefix now. The run loop also does this after
+ /// [`crate::raft::DEFAULT_SNAPSHOT_EVERY`] new applied entries.
+ pub fn compact_applied(&mut self) -> bool {
+ self.raft.compact_applied()
+ }
+
+ /// Index covered by the snapshot. 0 when this node has not compacted.
+ pub fn snapshot_index(&self) -> u64 {
+ self.raft.snapshot_index()
+ }
+
/// Tick the Raft state machine and dispatch any outbound messages.
///
/// Call this periodically (e.g. every 10 ms) from the cluster run loop.
@@ -289,30 +307,40 @@ impl ClusterNode {
///
/// The engine applier runs before the waiting caller is released, so a
/// successful return means this node has the metadata locally and a
- /// majority has the log entry.
+ /// majority has the log entry. A snapshot installed since the last call
+ /// is applied first: those commands are no longer in the log.
async fn apply_ready(&mut self) {
+ let installed = self.raft.take_installed_entries();
+ for entry in installed {
+ self.apply_entry(entry).await;
+ }
let entries = self.raft.ready();
for entry in entries {
- debug!(
- node = %self.raft.id,
- index = entry.index,
- term = entry.term,
- "Applying committed entry"
- );
- self.metadata.apply(entry.index, &entry.command);
- let effect = if let Some(applier) = &self.applier {
- applier.apply_metadata(&entry.command).await
- } else {
- ApplyEffect::Applied
- };
- // Request ids are per accepting node. A leader applying a
- // forwarded entry must not complete its own waiter that happens
- // to share the number.
- if entry.command.client_origin() == Some(self.raft.id.as_str()) {
- if let Some(request_id) = entry.command.client_request_id() {
- if let Some(waiter) = self.waiters.remove(&request_id) {
- let _ = waiter.ack.send(Ok(effect));
- }
+ self.apply_entry(entry).await;
+ }
+ self.raft.maybe_compact();
+ }
+
+ async fn apply_entry(&mut self, entry: crate::raft::LogEntry) {
+ debug!(
+ node = %self.raft.id,
+ index = entry.index,
+ term = entry.term,
+ "Applying committed entry"
+ );
+ self.metadata.apply(entry.index, &entry.command);
+ let effect = if let Some(applier) = &self.applier {
+ applier.apply_metadata(&entry.command).await
+ } else {
+ ApplyEffect::Applied
+ };
+ // Request ids are per accepting node. A leader applying a
+ // forwarded entry must not complete its own waiter that happens
+ // to share the number.
+ if entry.command.client_origin() == Some(self.raft.id.as_str()) {
+ if let Some(request_id) = entry.command.client_request_id() {
+ if let Some(waiter) = self.waiters.remove(&request_id) {
+ let _ = waiter.ack.send(Ok(effect));
}
}
}
@@ -322,6 +350,8 @@ impl ClusterNode {
let mut view = self.view.write().unwrap_or_else(|e| e.into_inner());
view.state = self.raft.state().clone();
view.leader_id = self.raft.leader_id().map(|s| s.to_string());
+ view.snapshot_index = self.raft.snapshot_index();
+ view.log_len = self.raft.log_len();
}
async fn accept_proposal(&mut self, req: ProposalRequest) {
diff --git a/engine/crates/xerj-cluster/src/propose.rs b/engine/crates/xerj-cluster/src/propose.rs
index a57fedb6b..baa93e7db 100644
--- a/engine/crates/xerj-cluster/src/propose.rs
+++ b/engine/crates/xerj-cluster/src/propose.rs
@@ -54,6 +54,10 @@ pub struct ClusterView {
pub node_id: String,
pub state: RaftState,
pub leader_id: Option<String>,
+ /// Highest index in this node's snapshot. 0 when it has not compacted.
+ pub snapshot_index: u64,
+ /// Log entries that are not covered by the snapshot.
+ pub log_len: usize,
}
/// A metadata command waiting to be proposed or forwarded by the run loop.
@@ -155,6 +159,17 @@ impl ClusterHandle {
self.view().leader_id
}
+ /// Highest snapshotted index, or 0. Updated by the run loop, so a caller
+ /// can see it only after the next step.
+ pub fn snapshot_index(&self) -> u64 {
+ self.view().snapshot_index
+ }
+
+ /// Entries still in the log, not counting a compacted prefix.
+ pub fn log_len(&self) -> usize {
+ self.view().log_len
+ }
+
fn view(&self) -> ClusterView {
self.inner
.view
diff --git a/engine/crates/xerj-cluster/src/raft.rs b/engine/crates/xerj-cluster/src/raft.rs
index 88a34e01e..1438c7ae6 100644
--- a/engine/crates/xerj-cluster/src/raft.rs
+++ b/engine/crates/xerj-cluster/src/raft.rs
@@ -5,15 +5,19 @@
//!
//! Safety properties upheld:
//! - Election Safety: at most one leader per term
-//! - Leader Append-Only: a leader never overwrites or deletes entries in its log
+//! - Leader Append-Only: a leader never overwrites a log prefix with different
+//! commands. Compaction replaces an applied prefix with a snapshot of those
+//! same commands; it does not rewrite them.
//! - Log Matching: if two logs contain an entry with the same index and term,
//! the logs are identical in all entries up through that index
//! - Leader Completeness: if a log entry is committed in a given term, that entry
-//! will be present in the logs of all leaders for all higher-numbered terms
+//! will be present in the logs of all leaders for all higher-numbered terms.
+//! A compacted prefix counts: it is in the snapshot, and `last_log_index` /
+//! `last_log_term` include that snapshot.
//! - State Machine Safety: if a server has applied a log entry at a given index,
//! no other server will ever apply a different log entry for that same index
-use std::collections::HashMap;
+use std::collections::{BTreeMap, HashMap};
use std::time::{Duration, Instant};
use anyhow::{bail, Result};
@@ -135,6 +139,32 @@ impl ClusterCommand {
}
}
+/// How many applied entries sit past the snapshot before the prefix is compacted.
+///
+/// Zero would snapshot on every apply. 64 keeps the on-disk log to a short
+/// suffix without snapshotting a cluster that has only created a handful of
+/// indices. Tests that need a snapshot sooner call [`RaftNode::compact_applied`]
+/// or [`RaftNode::set_snapshot_every`].
+pub const DEFAULT_SNAPSHOT_EVERY: u64 = 64;
+
+/// InstallSnapshot has to fit in one cluster frame (10 MiB). Above this the
+/// prefix stays in the log and catch-up keeps using AppendEntries.
+const MAX_SNAPSHOT_BYTES: usize = 8 * 1024 * 1024;
+
+/// Committed metadata prefix that the log no longer stores entry by entry.
+///
+/// `entries` are the commands with index `<= last_included_index`, in index
+/// order. A member that never stored them applies this list. The bytes are
+/// the commands, not a folded image and not document bodies: replaying them
+/// is what recreates index metadata. A history that does not fit in 8 MiB
+/// is left in the log.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RaftSnapshot {
+ pub last_included_index: u64,
+ pub last_included_term: u64,
+ pub entries: Vec<LogEntry>,
+}
+
/// A single entry in the Raft replicated log.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogEntry {
@@ -211,6 +241,25 @@ pub enum RaftMessage {
request_id: u64,
result: ShardResult,
},
+ /// Leader → follower: the log prefix at or below `last_included_index`
+ /// has been compacted. `data` is a [`RaftSnapshot`]. The follower applies
+ /// any command in it that it has not applied, then discards its own
+ /// prefix through that index.
+ InstallSnapshot {
+ term: u64,
+ leader_id: String,
+ last_included_index: u64,
+ last_included_term: u64,
+ data: Vec<u8>,
+ },
+ /// Follower → leader: response to [`RaftMessage::InstallSnapshot`].
+ InstallSnapshotResponse {
+ from: String,
+ term: u64,
+ /// Snapshot index the follower has stored. 0 when `success` is false.
+ last_included_index: u64,
+ success: bool,
+ },
}
fn message_term(msg: &RaftMessage) -> u64 {
@@ -220,7 +269,9 @@ fn message_term(msg: &RaftMessage) -> u64 {
| RaftMessage::RequestVote { term, .. }
| RaftMessage::RequestVoteResponse { term, .. }
| RaftMessage::ForwardProposal { term, .. }
- | RaftMessage::ForwardRejected { term, .. } => *term,
+ | RaftMessage::ForwardRejected { term, .. }
+ | RaftMessage::InstallSnapshot { term, .. }
+ | RaftMessage::InstallSnapshotResponse { term, .. } => *term,
// Not a Raft term. A shard frame that reaches the state machine must
// not step a leader down.
RaftMessage::ShardRequest { .. } | RaftMessage::ShardResponse { .. } => 0,
@@ -254,6 +305,16 @@ pub struct RaftNode {
/// When `Some`, every `propose()` / `handle_append_entries` call
/// persists the entry before committing to the in-memory `log` Vec.
persistent: Option<crate::raft_log::FileRaftLog>,
+ /// Applied prefix that has been removed from `log`. `None` until the
+ /// first compaction. `last_log_index` / `last_log_term` fall back to it
+ /// when the in-memory log is empty.
+ snapshot: Option<RaftSnapshot>,
+ /// A snapshot received or loaded from disk that [`RaftNode::take_installed_entries`]
+ /// has not handed to the applier yet.
+ pending_snapshot: Option<RaftSnapshot>,
+ /// Applied entries past the snapshot before [`RaftNode::maybe_compact`]
+ /// runs. Zero disables that automatic compaction.
+ snapshot_every: u64,
// ── Volatile state ───────────────────────────────────────────────────────
state: RaftState,
@@ -306,6 +367,9 @@ impl RaftNode {
voted_for: None,
log: vec![],
persistent: None,
+ snapshot: None,
+ pending_snapshot: None,
+ snapshot_every: DEFAULT_SNAPSHOT_EVERY,
state: RaftState::Follower,
commit_index: 0,
last_applied: 0,
@@ -334,11 +398,31 @@ impl RaftNode {
let mut flog = crate::raft_log::FileRaftLog::open(&storage_dir)
.map_err(|e| anyhow::anyhow!("opening raft log: {e}"))?;
+ if let Some(bytes) = flog.snapshot_bytes() {
+ let snap: RaftSnapshot = serde_json::from_slice(bytes)
+ .map_err(|e| anyhow::anyhow!("decode raft snapshot: {e}"))?;
+ if snap.last_included_term > node.current_term {
+ node.current_term = snap.last_included_term;
+ }
+ // Replay applies this before the log suffix. A restart has an
+ // empty metadata store; the commands in the snapshot are what
+ // put it back.
+ node.pending_snapshot = Some(snap.clone());
+ node.snapshot = Some(snap);
+ }
+ let covered = node.snapshot_index();
+
// Replay every persisted entry into the in-memory log. The
// in-memory log is kept 1-indexed (sentinel at index 0) to
- // match the rest of this file.
+ // match the rest of this file. Indexes the snapshot already
+ // covers are not loaded: the file may still hold them if a
+ // rewrite did not finish, and applying them twice is the
+ // applier's job only for the pending snapshot.
let last = flog.last_index();
for idx in 1..=last {
+ if idx <= covered {
+ continue;
+ }
if let Some((term, payload)) = flog
.read(idx)
.map_err(|e| anyhow::anyhow!("read raft entry: {e}"))?
@@ -356,6 +440,9 @@ impl RaftNode {
}
}
node.commit_index = flog.commit_index();
+ if node.commit_index < covered {
+ node.commit_index = covered;
+ }
// A vote is only valid in the term it was cast. A hard-state term
// ahead of the log (we campaigned or stepped down without appending)
// wins; a missing hard state leaves the term reconstructed from the log.
@@ -504,6 +591,34 @@ impl RaftNode {
// The transport answers these on the connection that carried
// them. They are not log entries.
}
+ RaftMessage::InstallSnapshot {
+ term,
+ leader_id,
+ last_included_index,
+ last_included_term,
+ data,
+ } => {
+ out.extend(self.handle_install_snapshot(
+ term,
+ leader_id,
+ last_included_index,
+ last_included_term,
+ data,
+ ));
+ }
+ RaftMessage::InstallSnapshotResponse {
+ from,
+ term,
+ last_included_index,
+ success,
+ } => {
+ out.extend(self.handle_install_snapshot_response(
+ from,
+ term,
+ last_included_index,
+ success,
+ ));
+ }
}
out
}
@@ -630,6 +745,112 @@ impl RaftNode {
self.commit_index
}
+ /// Index covered by the snapshot. 0 when this node has not compacted.
+ pub fn snapshot_index(&self) -> u64 {
+ self.snapshot
+ .as_ref()
+ .map(|snap| snap.last_included_index)
+ .unwrap_or(0)
+ }
+
+ /// Applied entries past the snapshot before automatic compaction.
+ /// Zero disables it. The default is [`DEFAULT_SNAPSHOT_EVERY`].
+ pub fn set_snapshot_every(&mut self, every: u64) {
+ self.snapshot_every = every;
+ }
+
+ /// Commands from a snapshot that this process has not applied yet.
+ ///
+ /// Advances `last_applied` through the snapshot index so [`RaftNode::ready`]
+ /// does not look for those commands in the log. Empty when nothing is pending.
+ pub fn take_installed_entries(&mut self) -> Vec<LogEntry> {
+ let Some(snap) = self.pending_snapshot.take() else {
+ return Vec::new();
+ };
+ let from = self.last_applied;
+ if snap.last_included_index > self.last_applied {
+ self.last_applied = snap.last_included_index;
+ }
+ let mut entries: Vec<LogEntry> = snap
+ .entries
+ .into_iter()
+ .filter(|entry| entry.index > from)
+ .collect();
+ entries.sort_by_key(|entry| entry.index);
+ entries
+ }
+
+ /// Replace the applied prefix with a snapshot and drop it from the log.
+ ///
+ /// No-op when nothing has been applied or the snapshot already covers
+ /// `last_applied`. Returns false when the snapshot could not be made
+ /// durable; the log is unchanged in that case.
+ pub fn compact_applied(&mut self) -> bool {
+ let through = self.last_applied;
+ if through == 0 || self.snapshot_index() >= through {
+ return false;
+ }
+ let mut by_index: BTreeMap<u64, LogEntry> = BTreeMap::new();
+ if let Some(prev) = &self.snapshot {
+ for entry in &prev.entries {
+ if entry.index <= through {
+ by_index.insert(entry.index, entry.clone());
+ }
+ }
+ }
+ for entry in &self.log {
+ if entry.index > 0 && entry.index <= through {
+ by_index.insert(entry.index, entry.clone());
+ }
+ }
+ let Some(term) = by_index.get(&through).map(|entry| entry.term) else {
+ warn!(
+ node = %self.id,
+ through,
+ "cannot compact: the applied index is not in the log or the snapshot"
+ );
+ return false;
+ };
+ let snap = RaftSnapshot {
+ last_included_index: through,
+ last_included_term: term,
+ entries: by_index.into_values().collect(),
+ };
+ if !self.persist_snapshot(&snap) {
+ return false;
+ }
+ // The snapshot is durable. Drop the prefix even if rewriting the
+ // file fails: the next open ignores indexes the snapshot covers.
+ if !self.discard_file_prefix(through) && self.persistent.is_some() {
+ warn!(
+ node = %self.id,
+ through,
+ "raft snapshot is stored but the log file still has the prefix"
+ );
+ }
+ self.log.retain(|entry| entry.index > through);
+ info!(
+ node = %self.id,
+ through,
+ entries = snap.entries.len(),
+ "compacted raft log prefix into a snapshot"
+ );
+ self.snapshot = Some(snap);
+ true
+ }
+
+ /// Compact when the applied prefix past the snapshot reaches
+ /// [`RaftNode::set_snapshot_every`].
+ pub fn maybe_compact(&mut self) {
+ if self.snapshot_every == 0 {
+ return;
+ }
+ let covered = self.snapshot_index();
+ if self.last_applied.saturating_sub(covered) >= self.snapshot_every {
+ let _ = self.compact_applied();
+ }
+ }
+
/// Term of the log entry at `index`, if that entry is still present.
///
/// A waiting proposer uses this to notice that its uncommitted entry was
@@ -748,11 +969,19 @@ impl RaftNode {
}
fn last_log_index(&self) -> u64 {
- self.log.last().map(|e| e.index).unwrap_or(0)
+ self.log
+ .last()
+ .map(|e| e.index)
+ .unwrap_or_else(|| self.snapshot_index())
}
fn last_log_term(&self) -> u64 {
- self.log.last().map(|e| e.term).unwrap_or(0)
+ self.log.last().map(|e| e.term).unwrap_or_else(|| {
+ self.snapshot
+ .as_ref()
+ .map(|snap| snap.last_included_term)
+ .unwrap_or(0)
+ })
}
/// Retrieve a log entry by its 1-based Raft index.
@@ -764,12 +993,88 @@ impl RaftNode {
self.log.iter().find(|e| e.index == index)
}
- /// Term of the log entry at `index`, or 0 if `index == 0`.
+ /// Term of the log entry at `index`, the snapshot's term when `index`
+ /// falls inside a compacted prefix, or 0 when this node does not have it.
fn log_term_at(&self, index: u64) -> u64 {
+ self.term_at(index).unwrap_or(0)
+ }
+
+ fn term_at(&self, index: u64) -> Option<u64> {
if index == 0 {
- return 0;
+ return Some(0);
+ }
+ if let Some(entry) = self.log_entry(index) {
+ return Some(entry.term);
+ }
+ let snap = self.snapshot.as_ref()?;
+ if index > snap.last_included_index {
+ return None;
+ }
+ if index == snap.last_included_index {
+ return Some(snap.last_included_term);
+ }
+ snap.entries
+ .iter()
+ .find(|entry| entry.index == index)
+ .map(|entry| entry.term)
+ }
+
+ fn persist_snapshot(&mut self, snap: &RaftSnapshot) -> bool {
+ let bytes = match serde_json::to_vec(snap) {
+ Ok(bytes) => bytes,
+ Err(e) => {
+ warn!(node = %self.id, error = %e, "encode raft snapshot");
+ return false;
+ }
+ };
+ if bytes.len() > MAX_SNAPSHOT_BYTES {
+ warn!(
+ node = %self.id,
+ bytes = bytes.len(),
+ "raft snapshot exceeds 8 MiB; leaving the log prefix in place"
+ );
+ return false;
+ }
+ let Some(flog) = self.persistent.as_mut() else {
+ return true;
+ };
+ match flog.save_snapshot(&bytes) {
+ Ok(()) => true,
+ Err(e) => {
+ warn!(node = %self.id, error = %e, "failed to persist raft snapshot");
+ false
+ }
+ }
+ }
+
+ fn discard_file_prefix(&mut self, through: u64) -> bool {
+ let Some(flog) = self.persistent.as_mut() else {
+ return true;
+ };
+ match flog.rewrite_without_prefix(through) {
+ Ok(()) => true,
+ Err(e) => {
+ warn!(node = %self.id, error = %e, through, "failed to rewrite raft log");
+ false
+ }
}
- self.log_entry(index).map(|e| e.term).unwrap_or(0)
+ }
+
+ fn snapshot_response(
+ &self,
+ to: String,
+ last_included_index: u64,
+ success: bool,
+ ) -> Vec<OutboundMessage> {
+ vec![OutboundMessage {
+ to,
+ msg: RaftMessage::InstallSnapshotResponse {
+ from: self.id.clone(),
+ term: self.current_term,
+ last_included_index,
+ success,
+ },
+ }]
}
fn random_election_timeout() -> Duration {
@@ -863,9 +1168,31 @@ impl RaftNode {
out
}
- /// Build an AppendEntries RPC for the given peer.
+ /// Build an AppendEntries RPC for the given peer, or an InstallSnapshot
+ /// when the peer's next index falls inside the compacted prefix.
fn build_append_entries(&self, peer: &str) -> Option<OutboundMessage> {
let next_idx = *self.next_index.get(peer).unwrap_or(&1);
+ if let Some(snap) = &self.snapshot {
+ if next_idx <= snap.last_included_index {
+ let data = match serde_json::to_vec(snap) {
+ Ok(data) => data,
+ Err(e) => {
+ warn!(node = %self.id, error = %e, "encode raft snapshot for install");
+ return None;
+ }
+ };
+ return Some(OutboundMessage {
+ to: peer.to_string(),
+ msg: RaftMessage::InstallSnapshot {
+ term: self.current_term,
+ leader_id: self.id.clone(),
+ last_included_index: snap.last_included_index,
+ last_included_term: snap.last_included_term,
+ data,
+ },
+ });
+ }
+ }
let prev_log_index = next_idx.saturating_sub(1);
let prev_log_term = self.log_term_at(prev_log_index);
@@ -922,9 +1249,30 @@ impl RaftNode {
self.leader_id = Some(leader_id.clone());
}
+ // A prev index inside the compacted prefix is not a missing entry.
+ // The leader should send InstallSnapshot; tell it how far this
+ // node already is so it stops walking backwards.
+ if let Some(snap) = &self.snapshot {
+ if prev_log_index > 0 && prev_log_index < snap.last_included_index {
+ return vec![OutboundMessage {
+ to: leader_id,
+ msg: RaftMessage::AppendEntriesResponse {
+ from: self.id.clone(),
+ term: self.current_term,
+ success: false,
+ match_index: self.last_log_index(),
+ },
+ }];
+ }
+ }
+ let matched_snapshot = self.snapshot.as_ref().is_some_and(|snap| {
+ prev_log_index == snap.last_included_index && prev_log_term == snap.last_included_term
+ });
+
// 2. Reply false if log doesn't contain an entry at prevLogIndex
- // whose term matches prevLogTerm (§5.3)
- if prev_log_index > 0 {
+ // whose term matches prevLogTerm (§5.3). The snapshot boundary
+ // counts as that entry.
+ if prev_log_index > 0 && !matched_snapshot {
match self.log_entry(prev_log_index) {
None => {
return vec![OutboundMessage {
@@ -959,8 +1307,16 @@ impl RaftNode {
}
}
- // 4. Append any new entries not already in the log
+ // 4. Append any new entries not already in the log. Commands the
+ // snapshot already covers are not appended again.
for entry in &entries {
+ if self
+ .snapshot
+ .as_ref()
+ .is_some_and(|snap| entry.index <= snap.last_included_index)
+ {
+ continue;
+ }
// If we already have this index check for conflicts
if let Some(existing) = self.log_entry(entry.index) {
if existing.term != entry.term {
@@ -1069,9 +1425,22 @@ impl RaftNode {
return self.send_heartbeats();
}
} else {
- // Decrement next_index and retry
+ // A follower that already snapshotted past `next_index` reports
+ // its real log end. Jump forward to that. A follower with nothing
+ // that sits behind our snapshot lands on the snapshot index so
+ // the retry is InstallSnapshot, not a walk back to index 1.
+ // Anything else keeps the one-step decrement this node used
+ // before snapshots existed.
+ let reported = match_index.saturating_add(1).max(1);
+ let floor = self.snapshot_index();
let ni = self.next_index.entry(from.clone()).or_insert(1);
- *ni = ni.saturating_sub(1).max(1);
+ if reported > *ni {
+ *ni = reported;
+ } else if floor > 0 && match_index < floor {
+ *ni = floor;
+ } else {
+ *ni = ni.saturating_sub(1).max(1);
+ }
// Retry immediately with the updated next_index
if let Some(msg) = self.build_append_entries(&from) {
@@ -1081,6 +1450,115 @@ impl RaftNode {
vec![]
}
+ fn handle_install_snapshot(
+ &mut self,
+ term: u64,
+ leader_id: String,
+ last_included_index: u64,
+ last_included_term: u64,
+ data: Vec<u8>,
+ ) -> Vec<OutboundMessage> {
+ if term < self.current_term {
+ return self.snapshot_response(leader_id, 0, false);
+ }
+
+ self.last_heartbeat = Instant::now();
+ if self.state != RaftState::Follower {
+ self.become_follower(Some(leader_id.clone()));
+ } else {
+ self.leader_id = Some(leader_id.clone());
+ }
+
+ if self.snapshot_index() >= last_included_index && last_included_index > 0 {
+ return self.snapshot_response(leader_id, self.snapshot_index(), true);
+ }
+
+ let snap: RaftSnapshot = match serde_json::from_slice(&data) {
+ Ok(snap) => snap,
+ Err(e) => {
+ warn!(node = %self.id, error = %e, "raft snapshot payload is not decodable");
+ return self.snapshot_response(leader_id, 0, false);
+ }
+ };
+ if snap.last_included_index != last_included_index
+ || snap.last_included_term != last_included_term
+ || !snap
+ .entries
+ .iter()
+ .any(|entry| entry.index == last_included_index && entry.term == last_included_term)
+ {
+ warn!(
+ node = %self.id,
+ last_included_index,
+ "raft snapshot payload does not match its index and term"
+ );
+ return self.snapshot_response(leader_id, 0, false);
+ }
+
+ let already_applied = self.last_applied >= last_included_index
+ && self.term_at(last_included_index) == Some(last_included_term);
+ let boundary_matches = self
+ .log_entry(last_included_index)
+ .is_some_and(|entry| entry.term == last_included_term);
+
+ if !self.persist_snapshot(&snap) {
+ return self.snapshot_response(leader_id, 0, false);
+ }
+
+ if boundary_matches {
+ self.log.retain(|entry| entry.index > last_included_index);
+ } else {
+ // The snapshot is a committed prefix. A local tail that does not
+ // contain that index and term is not part of this leader's log.
+ self.log.clear();
+ }
+ self.snapshot = Some(snap.clone());
+ if self.commit_index < last_included_index {
+ self.commit_index = last_included_index;
+ self.persist_commit_index();
+ }
+ if !already_applied {
+ self.pending_snapshot = Some(snap);
+ }
+ // Logical end first, so a crash cannot resurrect a conflicting tail,
+ // then drop the bytes the snapshot replaced.
+ if !self.mirror_log() {
+ warn!(node = %self.id, "installed raft snapshot but the log suffix did not persist");
+ return self.snapshot_response(leader_id, 0, false);
+ }
+ if !self.discard_file_prefix(last_included_index) && self.persistent.is_some() {
+ warn!(
+ node = %self.id,
+ last_included_index,
+ "raft snapshot is stored but the log file still has the prefix"
+ );
+ }
+ info!(
+ node = %self.id,
+ last_included_index,
+ "installed raft snapshot"
+ );
+ self.snapshot_response(leader_id, last_included_index, true)
+ }
+
+ fn handle_install_snapshot_response(
+ &mut self,
+ from: String,
+ term: u64,
+ last_included_index: u64,
+ success: bool,
+ ) -> Vec<OutboundMessage> {
+ if self.state != RaftState::Leader || term < self.current_term || !success {
+ return vec![];
+ }
+ self.match_index
+ .entry(from.clone())
+ .and_modify(|m| *m = (*m).max(last_included_index))
+ .or_insert(last_included_index);
+ *self.next_index.entry(from.clone()).or_insert(1) = last_included_index.saturating_add(1);
+ self.build_append_entries(&from).into_iter().collect()
+ }
+
fn handle_request_vote(
&mut self,
term: u64,
@@ -1434,4 +1912,61 @@ mod tests {
});
assert!(result.is_err(), "propose on follower must fail");
}
+
+ /// n3 is in the membership but not in the simulation until after the
+ /// prefix is compacted, so the create is not in any log it can copy.
+ #[test]
+ fn compacted_prefix_installs_on_a_peer_that_has_no_log() {
+ let peers = |exclude: &str| -> Vec<String> {
+ vec!["n1", "n2", "n3"]
+ .into_iter()
+ .filter(|&id| id != exclude)
+ .map(String::from)
+ .collect()
+ };
+ let mut nodes = vec![
+ RaftNode::new("n1".to_string(), peers("n1")),
+ RaftNode::new("n2".to_string(), peers("n2")),
+ ];
+ nodes[0].last_heartbeat = Instant::now() - Duration::from_millis(500);
+ drive_until_leader(&mut nodes, 100);
+ let leader = nodes.iter().position(|n| n.is_leader()).expect("leader");
+ nodes[leader]
+ .propose(ClusterCommand::CreateIndex {
+ name: "orders".to_string(),
+ schema_json: "{}".to_string(),
+ })
+ .expect("propose");
+ simulate_rounds(&mut nodes, 20);
+ for node in &mut nodes {
+ assert!(!node.ready().is_empty(), "{} did not apply", node.id);
+ assert!(node.compact_applied(), "{} did not compact", node.id);
+ assert_eq!(
+ node.log_len(),
+ 0,
+ "{} still has the create in its log",
+ node.id
+ );
+ assert!(node.snapshot_index() >= 1, "{}", node.id);
+ }
+
+ nodes.push(RaftNode::new("n3".to_string(), peers("n3")));
+ simulate_rounds(&mut nodes, 30);
+ let late = nodes.iter_mut().find(|n| n.id == "n3").expect("n3");
+ assert!(
+ late.snapshot_index() >= 1,
+ "a peer with an empty log must install the snapshot, not copy a log entry"
+ );
+ assert_eq!(late.log_len(), 0);
+ let installed = late.take_installed_entries();
+ assert!(
+ installed.iter().any(|entry| {
+ matches!(
+ &entry.command,
+ ClusterCommand::CreateIndex { name, .. } if name == "orders"
+ )
+ }),
+ "the snapshot must carry the create: {installed:?}"
+ );
+ }
}
diff --git a/engine/crates/xerj-cluster/src/raft_log.rs b/engine/crates/xerj-cluster/src/raft_log.rs
index b55b9ef44..4ff039b4b 100644
--- a/engine/crates/xerj-cluster/src/raft_log.rs
+++ b/engine/crates/xerj-cluster/src/raft_log.rs
@@ -54,7 +54,7 @@ use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use anyhow::{anyhow, Context, Result};
-use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
+use byteorder::{LittleEndian, ReadBytesExt};
use crc32fast::Hasher as Crc32;
/// Magic for the raft log file format. Distinct from the WAL magic so
@@ -64,11 +64,50 @@ const HARD_MAGIC: u32 = 0x5A52_4853; // "ZRHS"
const LOG_FILE: &str = "raft.log";
const COMMIT_FILE: &str = "commit.meta";
const HARD_FILE: &str = "hard.meta";
+const SNAPSHOT_FILE: &str = "snapshot.meta";
+const SNAPSHOT_MAGIC: u32 = 0x5A52_534E; // "ZRSN"
/// Directory name under the node's data dir. Not a valid index name, so a
/// user index cannot occupy the same path and take the log with it on delete.
pub const RAFT_DIR_NAME: &str = "_raft";
+/// One on-disk log record. `append` and log compaction both use this so a
+/// rewritten file scans the same way as a file that was only appended to.
+fn encode_entry(term: u64, index: u64, payload: &[u8]) -> Vec<u8> {
+ let payload_len = payload.len() as u64;
+ // Entry length covers everything after the len field up to the CRC,
+ // inclusive — useful for future forward-compatible skipping.
+ let entry_len: u64 = 8 + 8 + 1 + 8 + payload_len + 4;
+ let kind = EntryKind::ClusterCommand as u8;
+ let mut h = Crc32::new();
+ h.update(&MAGIC.to_le_bytes());
+ h.update(&entry_len.to_le_bytes());
+ h.update(&term.to_le_bytes());
+ h.update(&index.to_le_bytes());
+ h.update(&[kind]);
+ h.update(&payload_len.to_le_bytes());
+ h.update(payload);
+ let crc = h.finalize();
+
+ let mut buf = Vec::with_capacity(4 + entry_len as usize);
+ buf.extend_from_slice(&MAGIC.to_le_bytes());
+ buf.extend_from_slice(&entry_len.to_le_bytes());
+ buf.extend_from_slice(&term.to_le_bytes());
+ buf.extend_from_slice(&index.to_le_bytes());
+ buf.push(kind);
+ buf.extend_from_slice(&payload_len.to_le_bytes());
+ buf.extend_from_slice(payload);
+ buf.extend_from_slice(&crc.to_le_bytes());
+ buf
+}
+
+fn sync_dir(dir: &Path) -> Result<()> {
+ let file = File::open(dir).with_context(|| format!("opening {dir:?} to sync"))?;
+ file.sync_all()
+ .with_context(|| format!("syncing raft dir {dir:?}"))?;
+ Ok(())
+}
+
/// `{data_dir}/_raft`, where the server opens [`FileRaftLog`].
pub fn raft_storage_dir(data_dir: impl AsRef<Path>) -> PathBuf {
data_dir.as_ref().join(RAFT_DIR_NAME)
@@ -119,6 +158,10 @@ pub struct FileRaftLog {
/// Logical end of the log. `None` means `hard.meta` did not record one
/// and the scan is authoritative. `Some(0)` is an empty log.
log_end: Option<u64>,
+ /// Raw snapshot payload from `snapshot.meta`, when that file exists.
+ /// The Raft node decodes it. A missing file is a log that has not been
+ /// compacted. A truncated or checksum-mismatched file fails the open.
+ snapshot: Option<Vec<u8>>,
}
impl FileRaftLog {
@@ -225,6 +268,7 @@ impl FileRaftLog {
seek_table.retain(|&idx, _| idx <= end);
last_index = seek_table.keys().next_back().copied().unwrap_or(0);
}
+ let snapshot = Self::load_snapshot(&dir)?;
Ok(Self {
dir,
@@ -235,6 +279,7 @@ impl FileRaftLog {
hard_term,
hard_vote,
log_end,
+ snapshot,
})
}
@@ -253,38 +298,119 @@ impl FileRaftLog {
/// [`FileRaftLog::fsync`] after a batch to make the entries durable.
pub fn append(&mut self, term: u64, index: u64, payload: &[u8]) -> Result<()> {
let header_offset = self.current_offset()?;
- let payload_len = payload.len() as u64;
- // Entry length covers everything after the len field up to the CRC,
- // inclusive — useful for future forward-compatible skipping.
- let entry_len: u64 = 8 + 8 + 1 + 8 + payload_len + 4;
-
- let mut h = Crc32::new();
- h.update(&MAGIC.to_le_bytes());
- h.update(&entry_len.to_le_bytes());
- h.update(&term.to_le_bytes());
- h.update(&index.to_le_bytes());
- h.update(&[EntryKind::ClusterCommand as u8]);
- h.update(&payload_len.to_le_bytes());
- h.update(payload);
- let crc = h.finalize();
-
- self.writer.write_u32::<LittleEndian>(MAGIC)?;
- self.writer.write_u64::<LittleEndian>(entry_len)?;
- self.writer.write_u64::<LittleEndian>(term)?;
- self.writer.write_u64::<LittleEndian>(index)?;
- self.writer.write_u8(EntryKind::ClusterCommand as u8)?;
- self.writer.write_u64::<LittleEndian>(payload_len)?;
- self.writer.write_all(payload)?;
- self.writer.write_u32::<LittleEndian>(crc)?;
+ let record = encode_entry(term, index, payload);
+ self.writer.write_all(&record)?;
self.seek_table
- .insert(index, (term, header_offset, payload_len));
+ .insert(index, (term, header_offset, payload.len() as u64));
if index > self.last_index {
self.last_index = index;
}
Ok(())
}
+ /// Bytes of `snapshot.meta`, if a snapshot has been saved.
+ pub fn snapshot_bytes(&self) -> Option<&[u8]> {
+ self.snapshot.as_deref()
+ }
+
+ /// Replace `snapshot.meta`. The in-memory copy updates only after the
+ /// rename and directory sync, so a failed write leaves the previous
+ /// snapshot in place.
+ pub fn save_snapshot(&mut self, payload: &[u8]) -> Result<()> {
+ let path = self.dir.join(SNAPSHOT_FILE);
+ let tmp = self.dir.join("snapshot.meta.tmp");
+ let mut buf = Vec::with_capacity(16 + payload.len() + 4);
+ buf.extend_from_slice(&SNAPSHOT_MAGIC.to_le_bytes());
+ buf.extend_from_slice(&1u32.to_le_bytes());
+ let len = u64::try_from(payload.len()).context("raft snapshot longer than u64")?;
+ buf.extend_from_slice(&len.to_le_bytes());
+ buf.extend_from_slice(payload);
+ let mut h = Crc32::new();
+ h.update(&buf);
+ buf.extend_from_slice(&h.finalize().to_le_bytes());
+ {
+ let mut file = OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .open(&tmp)
+ .with_context(|| format!("writing {tmp:?}"))?;
+ file.write_all(&buf)
+ .with_context(|| format!("writing {tmp:?}"))?;
+ file.sync_all()
+ .with_context(|| format!("syncing {tmp:?}"))?;
+ }
+ std::fs::rename(&tmp, &path).with_context(|| format!("replacing {path:?}"))?;
+ sync_dir(&self.dir)?;
+ self.snapshot = Some(payload.to_vec());
+ Ok(())
+ }
+
+ /// Rewrite `raft.log` so it contains only entries with `index > through`.
+ ///
+ /// The new file is synced and renamed over the old one before the seek
+ /// table drops the prefix. A failed write leaves the previous file, and
+ /// its entries, in place.
+ pub fn rewrite_without_prefix(&mut self, through: u64) -> Result<()> {
+ if self.seek_table.keys().all(|idx| *idx > through) {
+ return Ok(());
+ }
+ self.writer
+ .flush()
+ .context("flush raft log before compaction")?;
+ let kept_idx: Vec<u64> = self
+ .seek_table
+ .keys()
+ .copied()
+ .filter(|idx| *idx > through)
+ .collect();
+ let mut kept = Vec::with_capacity(kept_idx.len());
+ for idx in kept_idx {
+ let (term, payload) = self.read(idx)?.ok_or_else(|| {
+ anyhow!("raft entry {idx} disappeared while compacting the log prefix")
+ })?;
+ kept.push((term, idx, payload));
+ }
+
+ let new_path = self.dir.join("raft.log.new");
+ let mut new_table: BTreeMap<u64, (u64, u64, u64)> = BTreeMap::new();
+ {
+ let mut file = OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .open(&new_path)
+ .with_context(|| format!("writing {new_path:?}"))?;
+ let mut offset = 0u64;
+ for (term, index, payload) in &kept {
+ let record = encode_entry(*term, *index, payload);
+ file.write_all(&record)
+ .with_context(|| format!("writing {new_path:?}"))?;
+ new_table.insert(*index, (*term, offset, payload.len() as u64));
+ offset += record.len() as u64;
+ }
+ file.sync_all()
+ .with_context(|| format!("syncing {new_path:?}"))?;
+ }
+ let final_path = self.dir.join(LOG_FILE);
+ std::fs::rename(&new_path, &final_path)
+ .with_context(|| format!("replacing {final_path:?}"))?;
+ sync_dir(&self.dir)?;
+
+ let file = OpenOptions::new()
+ .create(true)
+ .append(true)
+ .read(false)
+ .open(&final_path)
+ .with_context(|| format!("reopening {final_path:?} after compaction"))?;
+ self.writer = BufWriter::with_capacity(64 * 1024, file);
+ self.seek_table = new_table;
+ self.last_index = self.seek_table.keys().next_back().copied().unwrap_or(0);
+ self.set_log_end(self.last_index)?;
+ Ok(())
+ }
+
/// Force durability — flushes buffered writes and `fsync`s the
/// underlying file. Callers should batch appends and then fsync
/// at the end of the batch.
@@ -438,10 +564,7 @@ impl FileRaftLog {
std::fs::rename(&tmp, &path).with_context(|| format!("replacing {path:?}"))?;
// The rename is the publication. Sync the directory so a crash cannot
// lose the directory entry that names the new file.
- let dir =
- File::open(&self.dir).with_context(|| format!("opening {:?} to sync", self.dir))?;
- dir.sync_all()
- .with_context(|| format!("syncing raft dir {:?}", self.dir))?;
+ sync_dir(&self.dir)?;
Ok(())
}
@@ -488,6 +611,43 @@ impl FileRaftLog {
Ok((term, vote, log_end))
}
+ fn load_snapshot(dir: &Path) -> Result<Option<Vec<u8>>> {
+ let path = dir.join(SNAPSHOT_FILE);
+ if !path.exists() {
+ return Ok(None);
+ }
+ let bytes = std::fs::read(&path).with_context(|| format!("reading {path:?}"))?;
+ if bytes.len() < 4 + 4 + 8 + 4 {
+ return Err(anyhow!("raft snapshot {path:?} is truncated"));
+ }
+ let magic = u32::from_le_bytes(bytes[0..4].try_into().expect("4 bytes"));
+ if magic != SNAPSHOT_MAGIC {
+ return Err(anyhow!("raft snapshot {path:?} has a bad magic"));
+ }
+ let version = u32::from_le_bytes(bytes[4..8].try_into().expect("4 bytes"));
+ if version != 1 {
+ return Err(anyhow!(
+ "raft snapshot {path:?} has version {version}, want 1"
+ ));
+ }
+ let len = usize::try_from(u64::from_le_bytes(
+ bytes[8..16].try_into().expect("8 bytes"),
+ ))
+ .context("raft snapshot length does not fit usize")?;
+ let header = 16;
+ let crc_at = header + len;
+ if bytes.len() != crc_at + 4 {
+ return Err(anyhow!("raft snapshot {path:?} is truncated"));
+ }
+ let expected = u32::from_le_bytes(bytes[crc_at..crc_at + 4].try_into().expect("4 bytes"));
+ let mut h = Crc32::new();
+ h.update(&bytes[..crc_at]);
+ if h.finalize() != expected {
+ return Err(anyhow!("raft snapshot {path:?} has a bad checksum"));
+ }
+ Ok(Some(bytes[header..crc_at].to_vec()))
+ }
+
/// Highest log index appended so far (0 if the log is empty).
pub fn last_index(&self) -> u64 {
self.last_index
@@ -640,4 +800,55 @@ mod tests {
Ok(_) => panic!("corrupt hard state opened"),
}
}
+
+ #[test]
+ fn snapshot_roundtrip_and_a_bad_checksum_refuses_to_open() {
+ let dir = tempdir().unwrap();
+ let mut log = FileRaftLog::open(dir.path()).unwrap();
+ assert!(log.snapshot_bytes().is_none());
+ log.save_snapshot(b"commands").unwrap();
+ assert_eq!(log.snapshot_bytes(), Some(b"commands".as_slice()));
+ drop(log);
+
+ let log2 = FileRaftLog::open(dir.path()).unwrap();
+ assert_eq!(log2.snapshot_bytes(), Some(b"commands".as_slice()));
+
+ let path = dir.path().join(SNAPSHOT_FILE);
+ let mut bytes = std::fs::read(&path).unwrap();
+ let last = bytes.len() - 1;
+ bytes[last] ^= 0xff;
+ std::fs::write(&path, bytes).unwrap();
+ match FileRaftLog::open(dir.path()) {
+ Err(err) => assert!(
+ err.to_string().contains("checksum"),
+ "a torn snapshot must not open as an empty one: {err}"
+ ),
+ Ok(_) => panic!("corrupt snapshot opened"),
+ }
+ }
+
+ #[test]
+ fn rewrite_drops_the_prefix_and_keeps_the_suffix() {
+ let dir = tempdir().unwrap();
+ let mut log = FileRaftLog::open(dir.path()).unwrap();
+ for i in 1..=5 {
+ log.append(1, i, format!("{i}").as_bytes()).unwrap();
+ }
+ log.fsync().unwrap();
+ log.save_snapshot(b"snap").unwrap();
+ log.rewrite_without_prefix(3).unwrap();
+ assert_eq!(log.len(), 2);
+ assert!(log.read(1).unwrap().is_none());
+ assert!(log.read(3).unwrap().is_none());
+ assert_eq!(log.read(4).unwrap().unwrap().1, b"4");
+ assert_eq!(log.read(5).unwrap().unwrap().1, b"5");
+ drop(log);
+
+ let mut log2 = FileRaftLog::open(dir.path()).unwrap();
+ assert_eq!(log2.snapshot_bytes(), Some(b"snap".as_slice()));
+ assert_eq!(log2.len(), 2);
+ assert_eq!(log2.last_index(), 5);
+ assert!(log2.read(2).unwrap().is_none());
+ assert_eq!(log2.read(5).unwrap().unwrap().1, b"5");
+ }
}
diff --git a/engine/crates/xerj-cluster/tests/log_catchup.rs b/engine/crates/xerj-cluster/tests/log_catchup.rs
index b7bc59d72..527b71f95 100644
--- a/engine/crates/xerj-cluster/tests/log_catchup.rs
+++ b/engine/crates/xerj-cluster/tests/log_catchup.rs
@@ -234,3 +234,114 @@ async fn an_empty_member_installs_the_leader_log_and_keeps_it_across_restart() {
"the caught-up log must restore metadata with the peers stopped from helping"
);
}
+
+#[tokio::test]
+async fn a_compacted_prefix_installs_on_an_empty_member_and_survives_restart() {
+ let ids = ["n1", "n2", "n3"];
+ let held = fresh_dirs(3);
+ let paths: Vec<PathBuf> = held.iter().map(|(_, path)| path.clone()).collect();
+ let bus = InMemoryBus::new();
+ let mut nodes = vec![
+ open_node("n1", &ids, &bus, &paths[0]).await,
+ open_node("n2", &ids, &bus, &paths[1]).await,
+ ];
+ pump_until(&mut nodes, |nodes| {
+ nodes.iter().filter(|n| n.is_leader()).count() == 1
+ })
+ .await;
+ let leader = nodes.iter().position(|n| n.is_leader()).expect("leader");
+ nodes[leader]
+ .propose(ClusterCommand::CreateIndex {
+ name: "orders".into(),
+ schema_json: "{}".into(),
+ })
+ .expect("propose create");
+ nodes[leader]
+ .propose(ClusterCommand::SetShardInSync {
+ index: "orders".into(),
+ shard: 0,
+ nodes: vec!["n2".into()],
+ })
+ .expect("propose in-sync");
+ pump_until(&mut nodes, |nodes| nodes.iter().all(has_orders)).await;
+
+ for node in &mut nodes {
+ assert!(node.compact_applied(), "{} did not compact", node.raft.id);
+ assert_eq!(
+ node.raft.log_len(),
+ 0,
+ "{} still has log entries after compacting the prefix",
+ node.raft.id
+ );
+ assert!(
+ node.snapshot_index() >= 2,
+ "{} snapshot does not cover both entries",
+ node.raft.id
+ );
+ }
+ let leader_id = nodes[leader].raft.id.clone();
+ let leader_path = if leader_id == "n1" {
+ paths[0].clone()
+ } else {
+ paths[1].clone()
+ };
+ let flog = xerj_cluster::raft_log::FileRaftLog::open(&leader_path).expect("reopen log");
+ assert_eq!(flog.len(), 0, "raft.log must not keep the compacted prefix");
+ assert!(
+ flog.snapshot_bytes().is_some(),
+ "the prefix has to be in snapshot.meta"
+ );
+ drop(flog);
+
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let mut late = open_node("n3", &ids, &bus, &paths[2]).await;
+ late.set_applier(Arc::new(RecordingApplier {
+ events: Arc::clone(&events),
+ }));
+ nodes.push(late);
+ pump_until(&mut nodes, |nodes| nodes.iter().all(has_orders)).await;
+ let late = nodes.last().expect("n3");
+ assert_eq!(late.raft.id, "n3");
+ assert!(
+ late.snapshot_index() >= 2,
+ "n3 must install the snapshot; copying the log cannot work, it was compacted"
+ );
+ let caught_up = events.lock().expect("events").clone();
+ assert!(
+ caught_up.iter().any(|e| e == "create:orders"),
+ "applying the snapshot must run the create applier: {caught_up:?}"
+ );
+ assert!(
+ caught_up.iter().any(|e| e == "insync:orders:0"),
+ "applying the snapshot must run the in-sync applier: {caught_up:?}"
+ );
+
+ let leader = nodes.iter().position(|n| n.is_leader()).expect("leader");
+ nodes[leader]
+ .propose(ClusterCommand::UpdateConfig {
+ key: "after".into(),
+ value: "1".into(),
+ })
+ .expect("propose after the snapshot");
+ pump_until(&mut nodes, |nodes| {
+ nodes
+ .iter()
+ .all(|node| node.metadata.config.get("after").map(String::as_str) == Some("1"))
+ })
+ .await;
+
+ let late = nodes.pop().expect("n3");
+ assert_eq!(late.raft.id, "n3");
+ drop(late);
+ let mut restarted = open_node("n3", &ids, &bus, &paths[2]).await;
+ restarted.replay_committed().await;
+ assert!(
+ has_orders(&restarted),
+ "restart must restore the compacted prefix from snapshot.meta"
+ );
+ assert_eq!(
+ restarted.metadata.config.get("after").map(String::as_str),
+ Some("1"),
+ "restart must also replay the entry that landed after the snapshot"
+ );
+}
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 4aa83a954..974c45044 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -4272,6 +4272,7 @@ async fn async_main() -> Result<()> {
dir = %raft_dir.display(),
commit = node.raft.commit_index(),
entries = node.raft.log_len(),
+ snapshot = node.raft.snapshot_index(),
"opened on-disk raft log"
);
cluster_transport_outcome = xerj_api::state::ClusterTransportStatus::Running;
diff --git a/landing/docs/clustering.html b/landing/docs/clustering.html
index 5e606888d..2acc29a30 100644
--- a/landing/docs/clustering.html
+++ b/landing/docs/clustering.html
@@ -234,14 +234,14 @@
<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, install committed metadata from the on-disk Raft log. Documents that member never stored are not copied (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>, 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. Documents that member never stored are not copied (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. Nothing replays the writes it missed, so it stays out. 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">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 document backfill<span class="dsc">A restarted member reopens <code class="inline">{data_dir}/_raft</code> and applies the committed log before it serves, so the shard plan and the in-sync set come back and later writes are routed. A member that joins with an empty log copies that log from the leader and applies it, which creates the index metadata and an empty replica store when this node is a replica. It does not copy documents written before it joined. A replica removed from the in-sync set is not filled in. The log is not compacted; there is no InstallSnapshot.</span></div>
+ <div class="item">No document backfill<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 and later writes are routed. After 64 applied metadata entries the prefix is snapshotted: <code class="inline">raft.log</code> drops it, and a member whose log does not overlap receives InstallSnapshot and applies those commands. That creates the index metadata and an empty replica store when this node is a replica. The snapshot is the commands, not the documents. A member does not copy documents written before it joined. A replica removed from the in-sync set is not filled in. A metadata history bigger than 8 MiB stays in the log instead of being snapshotted.</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>
</div>
<p>With <code class="inline">number_of_replicas</code> at 0, a document has one home and losing that member loses it. With a replica placed at create, a GET or a search of that shard falls back to an in-sync copy when the primary does not answer. A copy that missed an acknowledged write is not in that set. A write still needs the primary: there is no promotion. Index metadata is on every member that applied the log. A restart replays the prefix that member had already stored. A new metadata change still needs a leader who can commit.</p>
@@ -254,7 +254,7 @@
<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>On-disk Raft log</strong> — cluster mode opens <code class="inline">{data_dir}/_raft</code> (<code class="inline">raft.log</code> 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 committed prefix 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 is empty copies the leader's log and applies it. The log is not compacted.</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>
<h2>Bootstrapping a 3-node cluster</h2>
@@ -335,7 +335,7 @@ INFO xerj_cluster::raft: Became leader node=10.0.0.12:9300 term=1</pre>
<div class="item">Leader crash<span class="dsc">Followers time out and elect a new leader — measured ~250 ms on a 3-node loopback ring, including one split-vote retry. The ring stays stable with the dead member absent. Metadata already applied on the survivors stays. The dead member's log is under its data directory; a restart replays it.</span></div>
<div class="item">Hung or dead peer<span class="dsc">One WARN on the down transition, then quiet: retries back off 100 ms → 6.4 s, and messages to live peers are never delayed behind a dead one. A peer that answers again logs "peer reachable again" at INFO.</span></div>
<div class="item">Minority partition<span class="dsc">The minority side cannot reach quorum and its elections never conclude; the majority side keeps its leader. Raft safety holds — at most one leader per term.</span></div>
- <div class="item">Node rejoin<span class="dsc">Restart with the same data directory reloads the log and the shard plan. A metadata entry committed while this node was down is installed from a peer that still has it, once this node is back. Documents this node never stored are not copied. A wiped <code class="inline">_raft</code> directory catches metadata up the same way and starts with empty indices. There is no InstallSnapshot (<a href="https://github.com/xerj-org/xerj/issues/1170">#1170</a>).</span></div>
+ <div class="item">Node rejoin<span class="dsc">Restart with the same data directory reloads the snapshot, the log suffix, and the shard plan. A metadata entry committed while this node was down is installed from a peer that still has it, or from that peer's snapshot once the log prefix has been compacted. Documents this node never stored are not copied. A wiped <code class="inline">_raft</code> directory catches metadata up the same way and starts with empty indices (<a href="https://github.com/xerj-org/xerj/issues/1170">#1170</a>).</span></div>
</div>
<h2>When not to cluster</h2>