Raft consensus internals

This page describes the Raft implementation in src/distributed/raft.rs and src/distributed/raft_storage.rs as of main @ 8a689c5c (2026-11-30). The operator view (how to configure a cluster, what the failover battery measured) is in 4. Operations, section 2. The network transport and the write path that feeds Raft are in Cluster RPC, replication and leader routing.

SynergyDB runs one Raft group per cluster. Every node holds the full keyspace. There is no sharding on this path (see Sharding and 2PC for the unwired sharding code).

Contents

  1. Components and tasks
  2. Configuration and defaults
  3. In-memory state
  4. Log entries
  5. Elections, including PreVote
  6. Heartbeats and AppendEntries
  7. Commit and apply
  8. Snapshots and log compaction
  9. Crash recovery and the read gate
  10. Membership
  11. On-disk format (raft_storage.rs)
  12. Tests
  13. Known limits and observations

1. Components and tasks

Piece Type Role
RaftNode src/distributed/raft.rs Holds RaftState behind a tokio::sync::RwLock, the persistent storage handle, commit waiters and notifiers. Implements the RPC handlers (handle_request_vote, handle_pre_vote, handle_append_entries, handle_install_snapshot) and the leader-side bookkeeping.
RaftStorage trait src/distributed/raft.rs Persistence contract: term/vote, log append/truncate, snapshots, sync, stats.
FileBasedRaftStorage src/distributed/raft_storage.rs The only RaftStorage implementation.
RaftCluster src/distributed/rpc.rs Owns the node, the per-peer RPC clients and the background tasks below.
Election timer RaftNode::run_election_timer Polls every 50 ms.
Election driver task spawned in RaftCluster::start Polls every 25 ms; runs PreVote and RequestVote rounds.
Per-peer replicator one task per peer, RaftCluster::start Sends AppendEntries or InstallSnapshot.
Commit advancer task in RaftCluster::start Recomputes commit_index, wakes commit waiters.
Quorum monitor task in RaftCluster::start Demotes a leader that has lost contact with a majority.
Apply loop spawn_apply_loop, src/distributed/replication.rs Applies committed entries to the local storage engine on every node.
Snapshot policy spawn_snapshot_policy, src/distributed/replication.rs Takes a snapshot and truncates the log every snapshot_threshold applied entries.
Status watcher task in Server::init_cluster, src/server/mod.rs Every 50 ms publishes the role to node_role and writes <data_dir>/raft/<node_id>.role on change.

(source: the files and symbols named)

Lock order inside RaftNode is state then last_snapshot. The code comments state this order is used everywhere to avoid deadlock (source: src/distributed/raft.rs, RaftNode::install_local_snapshot).

2. Configuration and defaults

RaftConfig::default() (source: src/distributed/raft.rs, impl Default for RaftConfig):

Field Default Override
election_timeout 3,000 to 6,000 ms (randomised per check) SYNERGYDB_RAFT_ELECTION_TIMEOUT_MS = min,max, or min alone (then max = 2 x min). Values must be > 0 and max > min, otherwise ignored
heartbeat_interval 300 ms SYNERGYDB_RAFT_HEARTBEAT_MS
commit_timeout 30 s SYNERGYDB_RAFT_COMMIT_TIMEOUT_MS
max_entries_per_append 1,000 none
max_bytes_per_append 1 MiB (1,048,576) SYNERGYDB_RAFT_MAX_APPEND_BYTES
storage RaftStorageConfig::default() see below

RaftStorageConfig::default(): log_dir = ./raft, snapshot_threshold = 10000, sync_mode = WalSyncMode::EveryWrite, max_log_file_size = 64 MiB (source: src/distributed/raft.rs, impl Default for RaftStorageConfig).

How the server fills these in (source: src/server/mod.rs, Server::init_cluster, apply_raft_env_overrides):

  • log_dir is <storage.data_dir>/raft/<node_id>/.
  • [cluster] snapshot_threshold replaces the storage default when it is greater than 0. The config default is 0, so the effective default is 10,000 entries (source: src/config.rs, ClusterConfig::default).
  • sync_mode is always EveryWrite: the server does not copy [storage] wal_sync_mode into the Raft storage config. Every Raft log append is followed by flush and sync_all.
  • The environment overrides are read once, at cluster start. Unset, empty, zero or unparsable values keep the defaults. The effective values are printed in one line starting Raft timing:.

The defaults are larger than the textbook 150 to 300 ms. The comment in RaftConfig::default gives the reason: on a slow host a leader's heartbeat can stall for a second or more during startup, and a tight timeout made followers depose a healthy leader repeatedly (source: src/distributed/raft.rs, impl Default for RaftConfig).

3. In-memory state

RaftState (source: src/distributed/raft.rs):

Field Meaning
current_term, voted_for Persistent state (saved through RaftStorage::save_state).
log: Vec<LogEntry> The whole uncompacted log, in memory. Entries are always looked up by index, never by position.
commit_index, last_applied Volatile. Not persisted: persist_commit_index is a no-op.
role Follower, Candidate or Leader (RaftRole).
leader_id Last known leader.
next_index, match_index Leader-only, per peer.
snapshot_index, snapshot_term Mirror of the current snapshot point, updated in the same critical section that prunes log.

last_log_index() and last_log_term() fall back to snapshot_index / snapshot_term when compaction has emptied log, so the next append after a full compaction does not restart at index 1 (source: src/distributed/raft.rs, RaftState::last_log_index).

Quorum is (peers + 1) / 2 + 1, where peers is the number of configured peers that resolved at startup (source: src/distributed/raft.rs, RaftNode::quorum; src/server/mod.rs, Server::init_cluster).

4. Log entries

pub struct LogEntry { pub term: u64, pub index: u64, pub data: Vec<u8> }

(source: src/distributed/raft.rs, LogEntry)

data is one of:

  • Empty: a control entry. The new leader's no-op is empty, and the apply path treats empty data as nothing to apply but still advances last_applied (source: src/distributed/replication.rs, apply_log_entry).
  • A bincode-encoded ReplicatedWrite { entries: Vec<(Vec<u8>, Option<Vec<u8>>)>, timestamp }: the resolved storage mutations of one StorageEngine::write_batch call (Some = put, None = tombstone) and the MVCC commit timestamp the leader assigned (source: src/distributed/replication.rs, ReplicatedWrite).

Replicating resolved key/value mutations rather than SQL text means now(), random(), sequence values and trigger effects are computed once on the leader (source: src/distributed/replication.rs, module docs). One statement is one log entry; a large statement is not split. Entries larger than the authenticated RPC frame cap (512 MiB) cannot be replicated (source: src/distributed/rpc.rs, MAX_AUTHED_RPC_FRAME_BYTES; docs/status/2026-11-29-raft-large-entry-frames.md).

5. Elections, including PreVote

5.1 Election timer

run_election_timer wakes every 50 ms, draws a random timeout in [min, max) and compares it with the time since last_heartbeat (source: src/distributed/raft.rs, RaftNode::run_election_timer).

  • PreVote on (always, in a networked cluster). RaftCluster::start calls enable_pre_vote() before starting the node. On expiry, a non-leader sets the election_due flag and changes nothing else.
  • PreVote off (only a RaftNode started outside RaftCluster, for example in unit tests). On expiry, a non-leader increments current_term, becomes Candidate, votes for itself and resets last_heartbeat so it waits a full timeout before trying again. With no peers it becomes leader at once.

last_heartbeat is refreshed by a valid AppendEntries, by an InstallSnapshot that is not stale, and by granting a vote.

5.2 PreVote round

The election driver (in RaftCluster::start) polls every 25 ms. When take_election_due() returns true, the node is not leader and the PreVote back-off has passed, it sends PreVote to every peer in parallel with an 800 ms timeout each. The request carries term = current_term + 1 and the node's real last log index and term (source: src/distributed/rpc.rs, RaftCluster::start).

A peer answers in handle_pre_vote and changes no state. It refuses when:

  • the proposed term is not greater than its own term;
  • it is the leader;
  • it knows a leader and has heard from it within the minimum election timeout;
  • the asker's log is less up to date (last term lower, or same term and lower index).

(source: src/distributed/raft.rs, RaftNode::handle_pre_vote)

With a majority of grants (self included), the driver calls begin_candidacy, which re-checks that the node is not leader and has not heard from a leader recently, then increments the term, votes for itself, clears leader_id, becomes Candidate and resets the election clock. If the round fails, the next PreVote waits a fresh random interval between the minimum and maximum election timeout.

PreVote and PreVoteResponse were appended to RpcMessageType, so older discriminants keep their values. An older node fails to decode PreVote, and the asker counts that as "no" (source: src/distributed/rpc.rs, RpcMessageType; docs/status/2026-11-29-raft-pre-vote.md).

5.3 RequestVote round

When the driver sees role == Candidate at a term it has not run an election for:

  1. It calls persist_candidacy() (saves term and vote). On failure it skips the round and retries on the next tick. This ordering keeps a crash between sending votes and persisting from producing two votes in one term (source: src/distributed/raft.rs, RaftNode::persist_candidacy).
  2. It sends RequestVote to all peers in parallel, 800 ms timeout each, with the real last log index and term (last_log_index_and_term).
  3. If any response carries a higher term, it calls step_down(highest) and abandons the round.
  4. With a majority, it calls become_leader(term).

A voter (handle_request_vote) adopts a higher term and becomes follower, refuses an older term, grants only if it has not voted for someone else this term and the candidate's log is at least as up to date (snapshot point used when the log is empty), and persists term and vote before replying (source: src/distributed/raft.rs, RaftNode::handle_request_vote).

5.4 Becoming leader

become_leader(expected_term) re-checks under the state lock that the node is still Candidate and that current_term == expected_term. It then sets next_index[p] = last_log_index + 1 and match_index[p] = 0 for every peer and appends an empty no-op entry in the new term, persists it and wakes the replicators (source: src/distributed/raft.rs, RaftNode::become_leader). The no-op lets the new leader commit entries from earlier terms, because the commit rule only counts current-term entries (section 7).

5.5 Stepping down

Path Term change Waiters
Any RPC handler sees a higher term adopts it, clears vote, becomes follower, persists failed if it was leader
step_down(new_term) (higher term in a response) adopts it if higher, persists failed
step_down_to_follower(reason) (quorum monitor) none failed
Candidate receives AppendEntries of the same or higher term none; becomes follower none

(source: src/distributed/raft.rs, the functions named)

The quorum monitor ticks every heartbeat_interval. When the node becomes leader it resets every peer's "last success" time and waits one tick. Afterwards, if fewer than a quorum of nodes (self counts) have had a successful AppendEntries or InstallSnapshot within 10 x election_timeout max (60 s with the defaults), it steps down to follower at the same term (source: src/distributed/rpc.rs, quorum monitor in RaftCluster::start). A leader cut off from the majority therefore keeps the leader role for up to that window, but it cannot commit, so its writes time out after commit_timeout.

6. Heartbeats and AppendEntries

6.1 Per-peer replicator loop

Each peer has one long-lived task (source: src/distributed/rpc.rs, RaftCluster::start):

  1. Wait for new_entry_notify or heartbeat_interval, whichever comes first.
  2. Skip if not leader.
  3. Build a ReplicationPayload under the state lock (replication_payload_for_peer).
  4. If needs_snapshot, run a chunked InstallSnapshot transfer (section 8.3) and continue.
  5. Otherwise send AppendEntries. An empty entry list is the heartbeat.
  6. On a reply with a higher term: step_down. On success: record_successful_replication(peer, last index in the batch), reset back-off, and wake itself again if more log remains. On success = false: decrement next_index by one and retry immediately. On a transport error: sleep, doubling the back-off from heartbeat_interval up to election_timeout max.

A new client entry wakes all replicators through notify_waiters() in append_and_register_waiter, so a write does not wait for the next heartbeat tick (source: src/distributed/raft.rs, RaftNode::append_and_register_waiter).

next_index and match_index only move forward in record_successful_replication and record_snapshot_installed, so a late reply cannot roll them back. Conflicts walk next_index back one entry per round trip; there is no conflict-term hint (source: src/distributed/raft.rs, record_conflict_decrement).

6.2 Batching and byte cap

replication_payload_for_peer collects entries with index >= next_index, up to max_entries_per_append entries, and stops adding entries once the running total of data.len() + 16 bytes per entry would exceed max_bytes_per_append. The first entry is always included, however large (source: src/distributed/raft.rs, RaftNode::replication_payload_for_peer). Tested by append_batches_are_capped_by_bytes.

prev_log_index / prev_log_term come from the entry before next_index, from the snapshot point when that entry is the snapshot edge, or (0, 0) at the start of the log. If the predecessor was compacted away and is not the snapshot edge, the payload sets needs_snapshot = true.

6.3 Follower side

handle_append_entries (source: src/distributed/raft.rs):

  1. Adopt a higher term; reject an older term with (current_term, false, 0).
  2. A candidate becomes follower. Refresh last_heartbeat; record leader_id.
  3. Consistency check: if prev_log_index is the snapshot edge, the term must match snapshot_term; if it is below the snapshot point, it passes; otherwise the entry with that index must exist with the same term.
  4. For each entry: skip if covered by the snapshot; if an entry with the same index and a different term exists, truncate from there and append; if it exists with the same term, skip it as a duplicate; if absent, append only when it is exactly the next index, otherwise stop and return success = false.
  5. If successful, commit_index = min(leader_commit, last_log_index).
  6. Persist term changes, the truncation, and the new entries, then reply (term, success, last_log_index). match_index in the reply is 0 on failure.

The leader does not use the reply's match_index; it records the last index of the batch it sent (source: src/distributed/rpc.rs, per-peer task).

7. Commit and apply

7.1 Commit rule

maybe_advance_commit_index scans the leader's log from the end, considers only entries of the current term, counts the leader plus every peer whose match_index >= index, and sets commit_index to the first (highest) entry that reaches quorum (source: src/distributed/raft.rs, RaftNode::maybe_advance_commit_index). The commit advancer task runs it when a replicator signals progress and every 200 ms as a fallback, then resolves every waiter with index at or below the new commit index (drain_committed_waiters).

7.2 Client wait

RaftCluster::submit(data) (source: src/distributed/rpc.rs):

  • With no peers: append and return at once.
  • Otherwise: append_and_register_waiter, then wait up to commit_timeout for the waiter. Results: Ok(index); the error passed to fail_all_waiters (leader stepped down); or commit timeout: entry index N not replicated within ....

A timed-out entry stays in the log and may still commit later; the client cannot tell (source: docs/status/2026-11-30-raft-commit-timeout.md).

7.3 Apply loop

There is one applier per node, the apply loop, on the leader and on followers alike (source: src/distributed/replication.rs, spawn_apply_loop). It wakes on commit_changed_notify or every 100 ms and calls apply_committed_entries:

  1. Take apply_mutex (also taken by install_snapshot, so a snapshot restore never interleaves with an apply batch).
  2. Under a short read lock, copy entries last_applied + 1 ..= commit_index. Stop at the first index missing from the in-memory log.
  3. Apply them with no Raft lock held. On a multi-thread runtime this runs inside block_in_place.
  4. Advance last_applied (forward only) and fire applied_notify.
  5. A missing committed index is returned as an error after the contiguous prefix is applied; last_applied never skips it. The loop logs the error and retries after 50 ms.

(source: src/distributed/raft.rs, RaftNode::apply_committed_entries)

Each entry is decoded and written with StorageEngine::apply_replicated_batch, which bypasses the replication hook. If the entry was not submitted by this node, notify_replicated_apply tells wire-level listeners about it so they can refresh in-memory state. Own writes are recognised by an xxh3 hash of the payload in the process-wide LOCAL_PENDING map (capped at 2^20 entries, cleared when full) (source: src/distributed/replication.rs, apply_log_entry, mark_local, take_local).

The leader's write path waits for last_applied >= index (wait_applied, timeout commit_timeout + 2 s) before acknowledging the client (see Cluster RPC, replication and leader routing).

8. Snapshots and log compaction

8.1 Snapshot content

A snapshot's data is the bincode encoding of Vec<(key, value)>: every live key/value pair returned by StorageEngine::snapshot_keyspace, built fully in memory (source: src/distributed/replication.rs, serialize_keyspace_snapshot, spawn_snapshot_policy). The README and the readiness document both list snapshots as full in-memory copies, not streamed (source: test-scripts/cluster/RAFT_READINESS.md).

8.2 Snapshot policy (local compaction)

spawn_snapshot_policy runs on every node when snapshot_threshold > 0 (source: src/distributed/replication.rs):

  • Every 200 ms, if applied_index >= snapshot_index + snapshot_threshold, look up the term of the applied index (skip if it is no longer in the log), dump the keyspace on the blocking pool, serialize it and call install_local_snapshot(applied, term, data).
  • install_local_snapshot writes the snapshot through storage, then in one critical section updates the snapshot meta, the state mirror and drops in-memory entries <= last_index, then calls truncate_before(last_index) on storage (source: src/distributed/raft.rs, RaftNode::install_local_snapshot).

RaftNode::create_snapshot (snapshot at commit_index from a caller-supplied closure) and needs_snapshot (log longer than snapshot_threshold) exist but are not called by the server (source: src/distributed/raft.rs; no caller outside tests found by search).

8.3 InstallSnapshot transfer

Leader side, send_snapshot_to_peer (source: src/distributed/rpc.rs):

  • Reads the current snapshot from storage (CRC-checked). With none, returns NoSnapshot, and the replicator sleeps one heartbeat.
  • Sends 1 MiB chunks (MAX_SNAPSHOT_CHUNK) with offset, done, last_included_index/term. At least one chunk is sent, so an empty snapshot works.
  • A reply with a higher term returns HigherTerm; success = false aborts the attempt (the replicator backs off and restarts from offset 0); success on the final chunk calls record_snapshot_installed, which sets match_index and next_index and wakes the replicator so AppendEntries resumes from last_included_index + 1.

Follower side, handle_install_snapshot (source: src/distributed/raft.rs):

  1. Term handling as for AppendEntries; refresh last_heartbeat.
  2. Staleness guard: if last_included_index <= last_applied or <= the local snapshot point, reply success without buffering anything.
  3. Chunk reassembly into pending_snapshot: offset == 0 starts a new transfer; a chunk at exactly the buffered length is appended; an earlier offset is ignored; a gap, or a chunk for a different snapshot, drops the transfer and replies success = false.
  4. The reassembled buffer may not exceed MAX_SNAPSHOT_TRANSFER_BYTES (1 GiB); a larger transfer is aborted.
  5. On done, compute a CRC32 of the reassembled bytes and call install_snapshot.

install_snapshot takes apply_mutex, repeats the staleness guard, calls the registered SnapshotRestorer (which replaces the local keyspace through StorageEngine::restore_from_snapshot on the blocking pool, stamping rows with last_included_index as the MVCC timestamp, then calls notify_replicated_reset), persists the snapshot and truncates the stored log, then advances commit_index, last_applied and the snapshot point and drops covered log entries (source: src/distributed/raft.rs, RaftNode::install_snapshot; src/distributed/replication.rs, EngineSnapshotRestorer).

The follower computes the CRC over the bytes it received; the leader's checksum is not sent in the RPC, so the CRC does not detect corruption in transit. On an authenticated cluster, AES-GCM already rejects altered frames (see Cluster RPC).

9. Crash recovery and the read gate

RaftNode::with_storage calls recover_state (source: src/distributed/raft.rs):

  1. Load the snapshot meta and set the snapshot mirror.
  2. Load term and vote.
  3. Load every stored log entry into state.log.
  4. If there is a snapshot, set commit_index and last_applied to its index.
  5. Arm the read gate: if the last log index is greater than last_applied, store it in read_gate_target.

The reason for the gate (source: src/distributed/raft.rs, field read_gate_target): after a restart, last_applied falls back to the snapshot point while the storage engine already holds applies up to the crash. Re-applying the committed suffix writes old values with newer storage sequence numbers, which can shadow newer values until replay passes them. ready_to_serve() returns false until last_applied >= read_gate_target. A conflict truncation lowers the target, because truncated entries were never committed.

Only the PostgreSQL wire consults the gate: the simple-query path refuses statements classified as reads with SQLSTATE 25006 and the message "node is recovering and has not caught up; reads are temporarily unavailable", and the extended-protocol handler carries the same gate (source: src/protocol/postgres/mod.rs, set_read_gate; src/protocol/postgres/extended.rs, set_read_gate). Not verified: other wires do not check ready_to_serve, so they can serve such reads during catch-up; no test found covers other wires.

Tested by recovery_read_gate_blocks_until_reapply_catches_up and recovery_read_gate_lowers_on_conflict_truncation (src/distributed/raft.rs).

10. Membership

Membership is static. The peer list comes from [cluster] peers at startup; there is no AddServer/RemoveServer RPC, no joint consensus and no configuration entry in the log (source: src/distributed/raft.rs, src/distributed/rpc.rs; no membership-change code found by search). To change the set of nodes, every node must be reconfigured and restarted.

Peers are given as node-id@host:port. An entry without @, or one whose address does not resolve at startup, is skipped with a warning (source: src/server/mod.rs, Server::init_cluster). Because quorum is computed from the resolved peers, a node that skipped a peer computes a smaller majority than its neighbours. Not verified: no test covers a peer that fails to resolve at startup.

DistributedCoordinator::add_node / remove_node in src/distributed/mod.rs edit an in-memory map only and are not connected to Raft (source: src/distributed/mod.rs).

11. On-disk format

All integers are little-endian (source: src/distributed/raft_storage.rs).

11.1 Directory layout

<data_dir>/raft/<node_id>/
  state.bin            term and vote
  state.bin.tmp        written, fsynced, then renamed over state.bin
  log/<16-digit id>.log  log segments
  snapshot/meta.bin    names the live snapshot data file
  snapshot/data-<20-digit index>-<16 hex id>.bin
  snapshot/meta-<16 hex id>.bin.tmp   in-flight metadata
<data_dir>/raft/<node_id>.role   status line written by the server

(source: src/distributed/raft_storage.rs, FileBasedRaftStorage; src/server/mod.rs, Server::init_cluster)

The module doc comment shows segment names as 00000001.log; the code formats them with 16 digits ({:016}.log).

11.2 state.bin

Offset Size Field
0 4 magic 0x53544154 ("STAT")
4 4 version 1
8 4 CRC32 of the payload
12 4 payload length
16 n bincode PersistentState { current_term, voted_for }

Written to state.bin.tmp, sync_all, renamed over state.bin, then the directory is fsynced (best effort). A file shorter than 16 bytes is ignored; a bad magic, version or CRC is a Corruption error (source: save_state, load_state).

11.3 Log segments

Header: magic 0x52414654 ("RAFT"), then version. Version 1 stores payloads in plaintext. Version 2 stores payloads sealed with the at-rest keyring (Purpose::RaftLog, the entry index is bound into the seal). A new segment is version 2 when an at-rest key is configured. An existing segment keeps its version, and a version-2 segment with no key configured is a Config error (source: LOG_VERSION, LOG_VERSION_SEALED, LogSegmentWriter::open).

Each entry:

Size Field
4 CRC32 over everything after this field
4 payload length
8 index
8 term
n payload (sealed or plain)

There is no padding, despite the "Pad" column in the module doc comment (source: encode_log_entry).

Writes follow sync_mode: EveryWrite flushes and sync_alls per entry, Periodic flushes only, NoSync leaves it to the OS. A segment rotates when it reaches max_log_file_size (64 MiB). On every open, recovery starts a new segment numbered one above the highest existing one (source: LogSegmentWriter::append, maybe_rotate_segment, recover_log).

Recovery reads every segment in name order into an in-memory BTreeMap<index, LogEntry> (log_cache), skipping entries at or below the snapshot index. A torn header, a length over 1 GiB, a short read or a CRC mismatch ends that segment ("had corruption", logged) and the reader moves to the next segment. A sealed payload that no configured key opens fails the whole recovery, so a key problem never silently drops committed entries (source: read_segment, recover_log).

truncate_from(index) removes entries from the cache and lowers last_log_index; it does not modify the files (comment: "Entries will be overwritten on next append"). truncate_before(index) removes entries from the cache and deletes segment files whose entries are all at or below index, never the segment open for writing; if the open segment is fully compacted, it first rotates to a new one (source: truncate_from, truncate_before, cleanup_old_segments). Tested by truncate_at_tip_keeps_later_appends_across_restart.

11.4 Snapshot files

snapshot/meta.bin, version 2:

Size Field
4 magic 0x534E4150 ("SNAP")
4 version 2 (version 1, still read, implied data.bin)
4 CRC32 over the bincode meta and the data file name
4 meta length
n bincode SnapshotMeta { last_included_index, last_included_term, size, checksum, created_at }
4 data file name length
m data file name

The data file holds the snapshot bytes, or, with an at-rest key, the 16-byte prefix \0SYNERGYDB-SEAL1 followed by the sealed blob (Purpose::RaftSnapshot). SnapshotMeta.checksum is the CRC32 of the plaintext (source: seal_snapshot_data, write_snapshot_files, read_snapshot_meta).

Write order: create and fsync the data file, write and fsync meta-<id>.bin.tmp, fsync the directory, rename over meta.bin (retried on Windows sharing violations, up to 12 attempts), fsync the directory again. The rename is the only step that changes the live snapshot. Files that are not the live snapshot are removed afterwards and at startup. A complete snapshot.tmp/ directory left by the older directory-swap layout is adopted if newer than the live snapshot (source: write_snapshot_files, remove_stale_snapshot_files, recover_snapshot_meta). The data file name is validated (data-...bin with only ASCII alphanumerics, - and ., or data.bin) so a damaged meta file cannot point outside the directory (source: is_snapshot_data_name).

Tested by repeated_snapshots_keep_exactly_one_live_copy, crash_before_the_meta_rename_keeps_the_previous_snapshot, interrupted_directory_swap_from_the_old_layout_is_recovered, version_one_snapshot_is_read_and_replaced, test_snapshot (src/distributed/raft_storage.rs).

12. Tests

Unit tests in the library (run with cargo test --lib distributed::):

File Tests
src/distributed/raft.rs waiter_does_not_self_resolve_without_replication, waiter_resolves_when_commit_index_advances, step_down_fails_pending_waiters, append_batches_are_capped_by_bytes, install_local_snapshot_truncates_log, install_snapshot_restores_state_and_advances_indices, handle_install_snapshot_reassembles_chunks, append_entries_with_stale_snapshot_base_does_not_alias, snapshot_meta_and_log_prune_are_atomic, candidacy_is_durable_before_vote_fanout, recovery_read_gate_blocks_until_reapply_catches_up, recovery_read_gate_lowers_on_conflict_truncation, stale_install_snapshot_is_a_noop, install_snapshot_chunk_gap_reports_failure, apply_loop_does_not_block_raft_state_lock, apply_refuses_to_skip_missing_committed_entry, become_leader_checks_term_and_appends_noop
src/distributed/raft_storage.rs test_state_persistence, test_log_persistence, test_snapshot, test_truncate_from, test_needs_compaction, plus the four snapshot-file tests in 11.4 and truncate_at_tip_keeps_later_appends_across_restart
src/distributed/rpc.rs pre_vote_keeps_a_lagging_follower_from_deposing_the_leader (3 nodes over loopback TCP), the authentication tests listed in Cluster RPC

tests/distributed_raft_test.rs does not exercise this code. It defines its own SimulatedRaftNode and LogEntry types and never imports synergydb; its "partition" helpers only log a message (source: tests/distributed_raft_test.rs, SimulatedRaftNode, TestCluster::partition_node). Its passing says nothing about src/distributed/.

End-to-end coverage is the Python harnesses under test-scripts/cluster/ (raft_net_test.py, multiwire_failover_test.py, haproxy_failover_test.py). They start real synergydb processes over loopback and are not run by cargo test. Their results are summarised in 4. Operations, section 2.1.

13. Known limits and observations

  • Whole log in memory, twice. RaftState.log and FileBasedRaftStorage.log_cache each hold every uncompacted entry, including payloads, until a snapshot truncates them (source: src/distributed/raft.rs, RaftState; src/distributed/raft_storage.rs, log_cache).
  • Snapshots are full in-memory copies on both sides, capped at 1 GiB on receive (source: MAX_SNAPSHOT_TRANSFER_BYTES).
  • No read index or leases. Followers serve reads from local state with no staleness bound (source: test-scripts/cluster/RAFT_READINESS.md; no read-index code found).
  • Commit index is not persisted. After a restart it is rebuilt from the snapshot point and from the leader's next AppendEntries.
  • Not verified: truncated log suffix across restart. truncate_from leaves truncated entries in the segment files. Recovery loads segments in order into a map keyed by index, so an entry that was truncated and not overwritten by a later append would, from reading the code, be loaded again at the next start. No test restarts after truncate_from (test_truncate_from checks the in-memory cache only). Raft's consistency check would make the leader overwrite such entries, but the recovered tail also feeds the read-gate target.
  • Not verified: peer resolution and quorum. See section 10.
  • Raft is not stopped on shutdown. Server::shutdown stops wire handlers and closes storage but never calls RaftCluster::stop (source: src/server/mod.rs, Server::shutdown).
  • replication_factor is not used by Raft. Every node holds every key. The value is only checked to be non-zero by config validation (source: src/config.rs; src/server/mod.rs, init_cluster).
  • mode = "Distributed" is the same as "Replicated". init_cluster only distinguishes Standalone from anything else (source: src/server/mod.rs, Server::init_cluster).