reddb_server/replication/election.rs
1//! Term-based, quorum-gated automatic election (issue #834, PRD #819, ADR 0030).
2//!
3//! This is the consensus core that turns a primary loss into an automatic,
4//! *safe* promotion. It lives in the first-party-but-decoupled control-plane
5//! supervisor (ADR 0030) — distinct from the data path — and reuses the two
6//! pieces the rest of replication already built:
7//!
8//! * the **commit watermark** ([`super::commit_waiter`] / [`super::quorum`]) —
9//! the highest LSN durably replicated to a quorum that intersects every
10//! possible election majority. Nothing at or below it may ever be rolled
11//! back; and
12//! * the **FAILOVER handover machinery** ([`super::failover`]) — once a
13//! candidate wins, promotion is driven through the same coordinated
14//! role-swap, not a parallel state machine.
15//!
16//! ## The five hard requirements (ADR 0030, issue #834)
17//!
18//! 1. **Dry-run probe.** A candidate first asks "*would* you vote for me?"
19//! without bumping any term. Only a real election bumps the term. This
20//! keeps a flapping candidate from burning through terms and lets the
21//! supervisor probe liveness cheaply.
22//! 2. **Durable last-vote.** A voter persists `(term, voted_for)` *before*
23//! acknowledging a grant, so a voter that crashes and restarts mid-term
24//! never double-votes — the second request in the same term for a
25//! different candidate is refused from disk.
26//! 3. **Watermark vote rule (the safety core).** A voter MUST refuse any
27//! candidate whose log does not cover the commit watermark. An
28//! acknowledged synchronous write sits at or below the watermark, so a
29//! winner necessarily carries it — the write provably survives the
30//! failover. This is the one rule that may not be relaxed.
31//! 4. **Randomized election timeouts.** Candidates wait a randomized
32//! interval before standing, so split votes are rare and self-correcting.
33//! 5. **Membership rules.** A quorum is a *majority of voting members*.
34//! **Witness** members ([#836]) hold no data but vote, so `2 data + 1
35//! witness` is a valid HA shape. A **catching-up** replica is
36//! *non-voting* until it reaches a healthy state — it neither votes nor
37//! stands.
38//!
39//! ## No two primaries in a term
40//!
41//! This invariant is structural, not probabilistic:
42//!
43//! * a win requires a strict majority of voting members, and two strict
44//! majorities of the same set always intersect; and
45//! * the shared voter in any two majorities votes at most once per term
46//! (durable last-vote), so it cannot grant two different candidates the
47//! same term.
48//!
49//! Therefore at most one candidate can collect a majority in a given term,
50//! even under an arbitrary network partition. The partition tests exercise
51//! exactly this.
52//!
53//! ## Module shape
54//!
55//! Like [`super::failover`], the candidate-side [`ElectionCoordinator::run`]
56//! is a **pure state machine**: the clock, the per-peer vote RPC, the
57//! durable term bump, and the promotion are injected behind
58//! [`ElectionTransport`], so the whole election is exercised
59//! deterministically with a scripted fake — no clock, no network, no engine.
60//! The voter-side [`Voter`] wraps a [`LastVoteStore`] (durable on disk in
61//! production, in-memory in tests) and applies the vote rule.
62//!
63//! [#836]: https://github.com/reddb-io/reddb/issues/836
64
65use std::time::Duration;
66
67pub use reddb_file::FileLastVoteStore;
68
69// ---------------------------------------------------------------
70// Membership model
71// ---------------------------------------------------------------
72
73/// Whether a member holds data (and can therefore be promoted to primary)
74/// or is a vote-only witness (ADR 0030 — "a node that runs only the
75/// supervisor module").
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum MemberKind {
78 /// Holds data; can vote and can stand for election.
79 Data,
80 /// Vote-only witness ([#836]); counts toward quorum, never primary.
81 ///
82 /// [#836]: https://github.com/reddb-io/reddb/issues/836
83 Witness,
84}
85
86/// Whether a member currently participates in voting.
87///
88/// A data replica that is still catching up (has not reached a healthy,
89/// watermark-covering state) is [`VotingState::CatchingUp`] and is excluded
90/// from the voter set entirely — it neither votes nor counts toward the
91/// majority denominator. Once healthy it becomes [`VotingState::Voting`].
92/// Witnesses are always [`VotingState::Voting`].
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum VotingState {
95 /// Healthy member that participates in quorum.
96 Voting,
97 /// Replica still syncing; non-voting until healthy.
98 CatchingUp,
99}
100
101/// A cluster member as seen by the supervisor's membership view.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct Member {
104 /// Stable node identity (matches the replica registry / ack id).
105 pub id: String,
106 pub kind: MemberKind,
107 pub state: VotingState,
108}
109
110impl Member {
111 pub fn data_voting(id: impl Into<String>) -> Self {
112 Self {
113 id: id.into(),
114 kind: MemberKind::Data,
115 state: VotingState::Voting,
116 }
117 }
118
119 pub fn data_catching_up(id: impl Into<String>) -> Self {
120 Self {
121 id: id.into(),
122 kind: MemberKind::Data,
123 state: VotingState::CatchingUp,
124 }
125 }
126
127 pub fn witness(id: impl Into<String>) -> Self {
128 Self {
129 id: id.into(),
130 kind: MemberKind::Witness,
131 state: VotingState::Voting,
132 }
133 }
134
135 /// Does this member count toward quorum? Only healthy members vote;
136 /// a catching-up replica is non-voting (ADR 0030).
137 pub fn is_voter(&self) -> bool {
138 matches!(self.state, VotingState::Voting)
139 }
140
141 /// May this member stand for election? Only a healthy, data-bearing
142 /// member can become primary — a witness holds no data and a
143 /// catching-up replica is not healthy.
144 pub fn is_electable(&self) -> bool {
145 self.kind == MemberKind::Data && self.is_voter()
146 }
147}
148
149/// Quorum threshold for a set of members: a strict majority of the
150/// *voting* members. Witnesses count; catching-up replicas do not.
151///
152/// For `n` voting members the threshold is `floor(n/2) + 1`, the smallest
153/// count such that two qualifying sets always intersect — the structural
154/// basis for "no two primaries in a term".
155pub fn quorum_threshold(members: &[Member]) -> usize {
156 let voters = members.iter().filter(|m| m.is_voter()).count();
157 voters / 2 + 1
158}
159
160// ---------------------------------------------------------------
161// Durable last-vote
162// ---------------------------------------------------------------
163
164/// A node's durable voting record: the highest term it has participated in
165/// and who, if anyone, it granted that term. Persisted so a restart cannot
166/// erase the fact that a vote was already cast (requirement 2).
167#[derive(Debug, Clone, PartialEq, Eq, Default)]
168pub struct LastVote {
169 /// Highest term this node has observed in a (real) vote request.
170 pub term: u64,
171 /// Who this node granted `term` to, if anyone yet.
172 pub voted_for: Option<String>,
173}
174
175impl LastVote {
176 fn from_file(value: reddb_file::DurableLastVote) -> Self {
177 Self {
178 term: value.term,
179 voted_for: value.voted_for,
180 }
181 }
182
183 fn to_file(&self) -> reddb_file::DurableLastVote {
184 reddb_file::DurableLastVote::new(self.term, self.voted_for.clone())
185 }
186}
187
188#[derive(Debug)]
189pub enum LastVoteError {
190 Io(std::io::Error),
191 InvalidFormat(String),
192}
193
194impl std::fmt::Display for LastVoteError {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 match self {
197 Self::Io(err) => write!(f, "last-vote io error: {err}"),
198 Self::InvalidFormat(msg) => write!(f, "invalid last-vote format: {msg}"),
199 }
200 }
201}
202
203impl std::error::Error for LastVoteError {}
204
205impl From<reddb_file::RdbFileError> for LastVoteError {
206 fn from(value: reddb_file::RdbFileError) -> Self {
207 match value {
208 reddb_file::RdbFileError::Io(err) => Self::Io(err),
209 reddb_file::RdbFileError::InvalidOperation(msg) => Self::InvalidFormat(msg),
210 // The zone message names the zone and points at scrub/salvage
211 // (ADR 0074 §2/§4); keep it verbatim rather than flattening it.
212 err @ (reddb_file::RdbFileError::ZoneUnrecoverable { .. }
213 | reddb_file::RdbFileError::ReadLimitExceeded { .. }) => {
214 Self::InvalidFormat(err.to_string())
215 }
216 }
217 }
218}
219
220/// Durable store for a node's last vote. The contract is narrow on purpose:
221/// `load` returns the persisted record (or the default `term 0, voted_for
222/// None` when nothing was ever written), and `persist` makes a record
223/// durable *before* the caller acknowledges a grant.
224pub trait LastVoteStore {
225 fn load(&self) -> Result<LastVote, LastVoteError>;
226 fn persist(&self, vote: &LastVote) -> Result<(), LastVoteError>;
227}
228
229/// In-memory last-vote store for tests and witnesses that do not need
230/// cross-restart durability. (A witness *should* still persist in
231/// production; the file store is used there.)
232#[derive(Debug, Default)]
233pub struct MemoryLastVoteStore {
234 inner: std::sync::Mutex<LastVote>,
235}
236
237impl MemoryLastVoteStore {
238 pub fn new() -> Self {
239 Self::default()
240 }
241
242 /// Seed an initial record — used by tests to simulate a node that
243 /// already voted before a restart.
244 pub fn seeded(vote: LastVote) -> Self {
245 Self {
246 inner: std::sync::Mutex::new(vote),
247 }
248 }
249}
250
251impl LastVoteStore for MemoryLastVoteStore {
252 fn load(&self) -> Result<LastVote, LastVoteError> {
253 Ok(self.inner.lock().expect("last-vote mutex").clone())
254 }
255
256 fn persist(&self, vote: &LastVote) -> Result<(), LastVoteError> {
257 *self.inner.lock().expect("last-vote mutex") = vote.clone();
258 Ok(())
259 }
260}
261
262impl LastVoteStore for FileLastVoteStore {
263 fn load(&self) -> Result<LastVote, LastVoteError> {
264 self.load_file()
265 .map(LastVote::from_file)
266 .map_err(LastVoteError::from)
267 }
268
269 fn persist(&self, vote: &LastVote) -> Result<(), LastVoteError> {
270 self.persist_file(&vote.to_file())
271 .map_err(LastVoteError::from)
272 }
273}
274
275// ---------------------------------------------------------------
276// Vote request / decision
277// ---------------------------------------------------------------
278
279/// A request for a vote, sent by a candidate to a voter.
280#[derive(Debug, Clone, PartialEq, Eq)]
281pub struct VoteRequest {
282 /// The candidate's stable identity.
283 pub candidate_id: String,
284 /// The term the candidate is standing for. For a real election this is
285 /// `current_term + 1`; for a dry-run probe it is the *prospective* term
286 /// the candidate would stand for, evaluated without committing to it.
287 pub term: u64,
288 /// The candidate's log frontier — the highest LSN durably in its log.
289 /// The watermark rule compares this against the commit watermark.
290 pub last_log_lsn: u64,
291 /// A dry-run probe gathers a would-be vote without persisting it or
292 /// advancing the voter's term (requirement 1). A real election sets
293 /// this `false`, which is the only path that persists a last-vote.
294 pub dry_run: bool,
295}
296
297impl VoteRequest {
298 pub fn probe(candidate_id: impl Into<String>, term: u64, last_log_lsn: u64) -> Self {
299 Self {
300 candidate_id: candidate_id.into(),
301 term,
302 last_log_lsn,
303 dry_run: true,
304 }
305 }
306
307 pub fn real(candidate_id: impl Into<String>, term: u64, last_log_lsn: u64) -> Self {
308 Self {
309 candidate_id: candidate_id.into(),
310 term,
311 last_log_lsn,
312 dry_run: false,
313 }
314 }
315}
316
317/// Why a voter refused a candidate.
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub enum RefusalReason {
320 /// The candidate's log does not cover the commit watermark, so an
321 /// acknowledged synchronous write could be lost — the safety core
322 /// refuses (requirement 3).
323 WatermarkNotCovered { candidate_lsn: u64, watermark: u64 },
324 /// The candidate's term is not newer than a term this voter already
325 /// participated in, and the voter already granted that term to someone
326 /// else (durable double-vote guard, requirement 2).
327 AlreadyVoted { term: u64, voted_for: String },
328 /// The candidate's term is older than the voter's current term — a
329 /// stale candidate from a superseded term.
330 StaleTerm {
331 candidate_term: u64,
332 voter_term: u64,
333 },
334}
335
336/// The outcome of a voter considering a [`VoteRequest`].
337#[derive(Debug, Clone, PartialEq, Eq)]
338pub enum VoteDecision {
339 /// Vote granted. For a real (non-dry-run) request the grant has already
340 /// been persisted durably before this value was produced.
341 Granted,
342 /// Vote refused, with the reason.
343 Refused(RefusalReason),
344}
345
346impl VoteDecision {
347 pub fn is_granted(&self) -> bool {
348 matches!(self, VoteDecision::Granted)
349 }
350}
351
352// ---------------------------------------------------------------
353// Voter (voter-side vote rule)
354// ---------------------------------------------------------------
355
356/// A voting member. Wraps the durable [`LastVoteStore`] and applies the
357/// vote rule. The voter is the seat of correctness: the watermark rule and
358/// the durable double-vote guard both live here.
359pub struct Voter<S: LastVoteStore> {
360 id: String,
361 store: S,
362}
363
364impl<S: LastVoteStore> Voter<S> {
365 pub fn new(id: impl Into<String>, store: S) -> Self {
366 Self {
367 id: id.into(),
368 store,
369 }
370 }
371
372 pub fn id(&self) -> &str {
373 &self.id
374 }
375
376 /// This voter's current term — the highest term it has durably recorded.
377 pub fn current_term(&self) -> Result<u64, LastVoteError> {
378 Ok(self.store.load()?.term)
379 }
380
381 /// Consider a vote request against the current `commit_watermark`.
382 ///
383 /// The decision order is deliberate:
384 ///
385 /// 1. **Watermark first** — the safety core. A candidate that cannot
386 /// carry an acknowledged write is refused regardless of term, so the
387 /// durability guarantee can never be traded away for liveness.
388 /// 2. **Stale term** — reject candidates from a superseded term.
389 /// 3. **Double-vote guard** — within a term, a voter grants exactly one
390 /// candidate; a re-ask by the *same* candidate is idempotently
391 /// re-granted.
392 ///
393 /// For a real (non-dry-run) grant, the new `(term, candidate)` is
394 /// persisted **before** `Granted` is returned, so the durability holds
395 /// across a crash at any point after the caller observes the grant.
396 pub fn consider(
397 &self,
398 req: &VoteRequest,
399 commit_watermark: u64,
400 ) -> Result<VoteDecision, LastVoteError> {
401 // 1. Watermark rule — never relaxed, checked before anything else.
402 if req.last_log_lsn < commit_watermark {
403 return Ok(VoteDecision::Refused(RefusalReason::WatermarkNotCovered {
404 candidate_lsn: req.last_log_lsn,
405 watermark: commit_watermark,
406 }));
407 }
408
409 let last = self.store.load()?;
410
411 // 2. Stale term — the candidate is behind a term we already moved past.
412 if req.term < last.term {
413 return Ok(VoteDecision::Refused(RefusalReason::StaleTerm {
414 candidate_term: req.term,
415 voter_term: last.term,
416 }));
417 }
418
419 // 3. Double-vote guard within the *same* term.
420 if req.term == last.term {
421 match &last.voted_for {
422 // Already voted for someone else this term — refuse.
423 Some(other) if other != &req.candidate_id => {
424 return Ok(VoteDecision::Refused(RefusalReason::AlreadyVoted {
425 term: last.term,
426 voted_for: other.clone(),
427 }));
428 }
429 // Already voted for this same candidate — idempotent re-grant.
430 Some(_) => return Ok(VoteDecision::Granted),
431 // Same term observed but no vote cast yet — fall through to grant.
432 None => {}
433 }
434 }
435
436 // Grant. A dry-run probe must not persist or advance the term
437 // (requirement 1); a real grant persists durably before acking.
438 if !req.dry_run {
439 self.store.persist(&LastVote {
440 term: req.term,
441 voted_for: Some(req.candidate_id.clone()),
442 })?;
443 }
444 Ok(VoteDecision::Granted)
445 }
446}
447
448// ---------------------------------------------------------------
449// Randomized election timeout
450// ---------------------------------------------------------------
451
452/// A randomized election timeout in `[base, base + jitter)`.
453///
454/// Randomization keeps candidates from standing in lockstep, which is what
455/// makes split votes rare and self-correcting (requirement 4). The function
456/// is pure in `seed` so tests pin a deterministic value; production passes
457/// an entropy-derived seed.
458pub fn randomized_election_timeout(base: Duration, jitter: Duration, seed: u64) -> Duration {
459 if jitter.is_zero() {
460 return base;
461 }
462 let jitter_ms = jitter.as_millis().max(1) as u64;
463 base + Duration::from_millis(seed % jitter_ms)
464}
465
466// ---------------------------------------------------------------
467// ElectionCoordinator (candidate-side state machine)
468// ---------------------------------------------------------------
469
470/// A request to run an election on behalf of `candidate`.
471#[derive(Debug, Clone, PartialEq, Eq)]
472pub struct ElectionRequest {
473 /// The candidate standing for election. Must be electable (a healthy,
474 /// data-bearing member) or [`ElectionCoordinator::run`] refuses up front.
475 pub candidate: Member,
476 /// The term the cluster is serving now. A real election stands for
477 /// `current_term + 1`.
478 pub current_term: u64,
479 /// The candidate's log frontier — the highest LSN durably in its log.
480 pub last_log_lsn: u64,
481 /// The commit watermark the candidate believes is in force. The
482 /// candidate must itself cover it to be electable; voters re-check
483 /// against their own watermark view.
484 pub commit_watermark: u64,
485}
486
487impl ElectionRequest {
488 /// The term a successful election produces.
489 pub fn new_term(&self) -> u64 {
490 self.current_term + 1
491 }
492}
493
494/// The result of an election attempt.
495#[derive(Debug, Clone, PartialEq, Eq)]
496pub enum ElectionOutcome {
497 /// Won a majority and was promoted under `term`. `votes`/`needed` record
498 /// the tally (including the candidate's self-vote).
499 Elected {
500 term: u64,
501 votes: usize,
502 needed: usize,
503 },
504 /// The dry-run probe did not reach a majority, so no term was bumped and
505 /// no real election was attempted (requirement 1).
506 ProbeFailed { votes: usize, needed: usize },
507 /// A real election was attempted (term bumped) but did not reach a
508 /// majority — e.g. votes split or peers came online between probe and
509 /// election. The term has advanced; a later attempt stands for a higher
510 /// term.
511 Lost {
512 term: u64,
513 votes: usize,
514 needed: usize,
515 },
516 /// The candidate is not electable (a witness, or a catching-up replica,
517 /// or its own log does not cover the watermark). No probe was sent.
518 NotElectable,
519 /// The election ran past its randomized timeout before collecting a
520 /// majority. No promotion happened.
521 TimedOut { votes: usize, needed: usize },
522}
523
524impl ElectionOutcome {
525 pub fn is_elected(&self) -> bool {
526 matches!(self, ElectionOutcome::Elected { .. })
527 }
528}
529
530/// Cluster operations the candidate drives, injected so the state machine
531/// stays pure and deterministically testable. Production backs these onto
532/// the membership view, the per-peer vote RPC, the durable term store, and
533/// the FAILOVER handover; tests back them onto a scripted fake.
534pub trait ElectionTransport {
535 /// The candidate's current view of cluster membership. The denominator
536 /// for the majority is the *voting* members of this set.
537 fn members(&self) -> Vec<Member>;
538
539 /// Ask one peer for its vote. The candidate never asks itself (it always
540 /// self-grants). Implementors route this to the peer's [`Voter`].
541 fn request_vote(&mut self, peer_id: &str, req: &VoteRequest) -> VoteDecision;
542
543 /// Time elapsed since the election began, so the coordinator enforces
544 /// the randomized timeout without owning a clock.
545 fn elapsed(&self) -> Duration;
546
547 /// Durably advance this node's current term to `new_term`. Called once,
548 /// only when a real election begins (never for a dry-run). Persisted
549 /// alongside the node's other durable replication state.
550 fn bump_term(&mut self, new_term: u64);
551
552 /// Promote the candidate to primary under `new_term`, reusing the
553 /// FAILOVER handover machinery ([`super::failover`]). Called only after
554 /// a majority is collected in the real election.
555 fn promote(&mut self, new_term: u64);
556}
557
558/// The quorum-gated election state machine.
559pub struct ElectionCoordinator;
560
561impl ElectionCoordinator {
562 /// Run an election for `req`, driving the cluster through `tx`, bounded
563 /// by `timeout` (use [`randomized_election_timeout`]).
564 ///
565 /// The flow is: electability guard → dry-run probe (no term bump) →
566 /// real election (bump term, collect votes) → promote on majority. See
567 /// the module docs for the full contract.
568 pub fn run(
569 req: &ElectionRequest,
570 tx: &mut dyn ElectionTransport,
571 timeout: Duration,
572 ) -> ElectionOutcome {
573 // Electability guard. A witness or catching-up replica may not
574 // stand; nor may a candidate whose own log does not cover the
575 // watermark (it would violate the safety core the instant it won).
576 if !req.candidate.is_electable() || req.last_log_lsn < req.commit_watermark {
577 return ElectionOutcome::NotElectable;
578 }
579
580 let members = tx.members();
581 let needed = quorum_threshold(&members);
582 let new_term = req.new_term();
583
584 // The peers we ask: every *other* voting member. The candidate
585 // self-grants, so it is one vote without an RPC.
586 let peers: Vec<String> = members
587 .iter()
588 .filter(|m| m.is_voter() && m.id != req.candidate.id)
589 .map(|m| m.id.clone())
590 .collect();
591
592 // ---- Phase 1: dry-run probe (does NOT bump the term) ----
593 let probe = VoteRequest::probe(&req.candidate.id, new_term, req.last_log_lsn);
594 let probe_votes = match Self::collect(tx, &peers, &probe, needed, timeout) {
595 CollectResult::Reached(v) => v,
596 CollectResult::Exhausted(v) => {
597 return ElectionOutcome::ProbeFailed { votes: v, needed }
598 }
599 CollectResult::TimedOut(v) => return ElectionOutcome::TimedOut { votes: v, needed },
600 };
601 debug_assert!(probe_votes >= needed);
602
603 // ---- Phase 2: real election (bumps the term, then collects) ----
604 tx.bump_term(new_term);
605 let ballot = VoteRequest::real(&req.candidate.id, new_term, req.last_log_lsn);
606 match Self::collect(tx, &peers, &ballot, needed, timeout) {
607 CollectResult::Reached(votes) => {
608 tx.promote(new_term);
609 ElectionOutcome::Elected {
610 term: new_term,
611 votes,
612 needed,
613 }
614 }
615 CollectResult::Exhausted(votes) => ElectionOutcome::Lost {
616 term: new_term,
617 votes,
618 needed,
619 },
620 CollectResult::TimedOut(votes) => ElectionOutcome::TimedOut { votes, needed },
621 }
622 }
623
624 /// Collect votes from `peers`, starting at 1 for the candidate's
625 /// self-vote, until `needed` is reached, the peers are exhausted, or the
626 /// timeout elapses. Stops early on success — no need to ask the rest.
627 fn collect(
628 tx: &mut dyn ElectionTransport,
629 peers: &[String],
630 req: &VoteRequest,
631 needed: usize,
632 timeout: Duration,
633 ) -> CollectResult {
634 let mut votes = 1usize; // self-vote
635 if votes >= needed {
636 return CollectResult::Reached(votes);
637 }
638 for peer in peers {
639 if tx.elapsed() >= timeout {
640 return CollectResult::TimedOut(votes);
641 }
642 if tx.request_vote(peer, req).is_granted() {
643 votes += 1;
644 if votes >= needed {
645 return CollectResult::Reached(votes);
646 }
647 }
648 }
649 CollectResult::Exhausted(votes)
650 }
651}
652
653enum CollectResult {
654 Reached(usize),
655 Exhausted(usize),
656 TimedOut(usize),
657}
658
659#[cfg(test)]
660mod tests;