Skip to main content

link_cli/engine/
raft.rs

1//! A draft Raft replica that keeps the journals of an `AtomicJournalStore`.
2//!
3//! This is the algorithm etcd runs behind `EtcdJournalStore`, written as a
4//! pure state machine in the style of etcd's `raft` package: the node reads no
5//! clock, opens no socket and starts no thread. The caller passes the local
6//! time to [`RaftNode::tick`] and [`RaftNode::step`], delivers the messages
7//! from [`RaftNode::take_messages`] over any transport, and persists
8//! [`RaftNode::hard_state`] and the log before sending them. That makes the
9//! same code usable in a real deployment and in a deterministic simulation,
10//! where tests drive it with skewed and jumping clocks, lost and reordered
11//! messages, partitions and restarts (`engine_raft_simulation_tests.rs`).
12//!
13//! Safety (election safety, log matching, leader completeness and state
14//! machine safety) never depends on a clock: time only decides *when* a node
15//! starts an election or a leader sends heartbeats. Clocks matter for
16//! liveness, and two etcd options keep a cluster live under faults that a
17//! plain Raft does not survive:
18//!
19//! * **PreVote** — a node first asks whether it *could* win before raising
20//!   its term, so a member that can send but not receive cannot disrupt a
21//!   healthy leader over and over.
22//! * **CheckQuorum** — a leader that has not heard from a majority within an
23//!   election timeout steps down, and followers that heard from a leader
24//!   within that timeout refuse votes (leader stickiness). A leader that can
25//!   send but not receive therefore stops blocking an election.
26//!
27//! Reads are linearizable because they go through the log (as etcd's older
28//! quorum reads did): a read returns the state at its position in the
29//! committed order. No proposal is retried; a proposal lost on the way to the
30//! leader simply never commits, and the caller's deadline reports an unknown
31//! outcome, as `AtomicJournalStore` requires.
32//!
33//! This is a draft for users to try: membership changes, snapshots/log
34//! compaction and ReadIndex/lease reads are not implemented.
35use super::cluster::JournalVersion;
36use std::collections::{BTreeMap, BTreeSet};
37
38/// splitmix64, used only to randomize election timeouts.
39#[derive(Clone, Debug)]
40struct Jitter(u64);
41impl Jitter {
42    fn below(&mut self, bound: u64) -> u64 {
43        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
44        let mut z = self.0;
45        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
46        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
47        (z ^ (z >> 31)) % bound.max(1)
48    }
49}
50
51#[derive(Clone, Debug)]
52pub struct RaftConfig {
53    /// This node's index in `0..members`.
54    pub id: usize,
55    pub members: usize,
56    /// The base election timeout in local clock units; each election waits a
57    /// random time in `[election_timeout, 2 * election_timeout)`.
58    pub election_timeout: u64,
59    pub heartbeat_interval: u64,
60    pub pre_vote: bool,
61    pub check_quorum: bool,
62    /// Seeds the election jitter.
63    pub seed: u64,
64    /// The most entries one append message carries.
65    pub max_entries_per_message: usize,
66}
67impl RaftConfig {
68    pub fn new(id: usize, members: usize) -> Self {
69        Self {
70            id,
71            members,
72            election_timeout: 100,
73            heartbeat_interval: 10,
74            pre_vote: true,
75            check_quorum: true,
76            seed: id as u64 + 1,
77            max_entries_per_message: 32,
78        }
79    }
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
83pub enum RaftCommand {
84    /// Starts every term: commits the entries of earlier terms.
85    Noop,
86    Read {
87        id: u64,
88        keys: Vec<String>,
89    },
90    CompareExchange {
91        id: u64,
92        keys: Vec<String>,
93        expected: Vec<JournalVersion>,
94        updates: Vec<Option<Vec<String>>>,
95    },
96}
97impl RaftCommand {
98    pub fn id(&self) -> Option<u64> {
99        match self {
100            RaftCommand::Noop => None,
101            RaftCommand::Read { id, .. } | RaftCommand::CompareExchange { id, .. } => Some(*id),
102        }
103    }
104}
105
106#[derive(Clone, Debug, PartialEq, Eq)]
107pub struct RaftEntry {
108    pub term: u64,
109    pub command: RaftCommand,
110}
111
112#[derive(Clone, Debug, PartialEq, Eq)]
113pub enum RaftOutcome {
114    Read(Vec<JournalVersion>),
115    Exchanged(bool),
116}
117
118#[derive(Clone, Debug, PartialEq, Eq)]
119pub enum RaftMessage {
120    Vote {
121        pre: bool,
122        term: u64,
123        last_index: u64,
124        last_term: u64,
125    },
126    VoteReply {
127        pre: bool,
128        term: u64,
129        granted: bool,
130    },
131    Append {
132        term: u64,
133        prev_index: u64,
134        prev_term: u64,
135        entries: Vec<RaftEntry>,
136        commit: u64,
137    },
138    /// `index` is the last matching index on success and a hint otherwise.
139    AppendReply {
140        term: u64,
141        success: bool,
142        index: u64,
143    },
144    /// A follower forwards a proposal to the leader it knows.
145    Propose {
146        command: RaftCommand,
147    },
148}
149
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub struct RaftEnvelope {
152    pub from: usize,
153    pub to: usize,
154    pub message: RaftMessage,
155}
156
157#[derive(Clone, Copy, Debug, PartialEq, Eq)]
158pub enum RaftRole {
159    Follower,
160    PreCandidate,
161    Candidate,
162    Leader,
163}
164
165/// What must survive a restart: the term, the vote and the log.
166#[derive(Clone, Debug, Default, PartialEq, Eq)]
167pub struct RaftHardState {
168    pub term: u64,
169    pub voted_for: Option<usize>,
170}
171
172/// The replicated journals, as `AtomicJournalStore` exposes them.
173#[derive(Clone, Debug, Default, PartialEq, Eq)]
174pub struct JournalState {
175    /// Bumped by every successful compare-exchange; never reused.
176    pub revision: u64,
177    pub journals: BTreeMap<String, JournalVersion>,
178    /// `(revision, command id)` of every successful compare-exchange.
179    pub exchanges: Vec<(u64, u64)>,
180}
181impl JournalState {
182    fn apply(&mut self, command: &RaftCommand) -> Option<RaftOutcome> {
183        match command {
184            RaftCommand::Noop => None,
185            RaftCommand::Read { keys, .. } => Some(RaftOutcome::Read(
186                keys.iter()
187                    .map(|key| self.journals.get(key).cloned().unwrap_or_default())
188                    .collect(),
189            )),
190            RaftCommand::CompareExchange {
191                id,
192                keys,
193                expected,
194                updates,
195            } => {
196                if keys.len() != expected.len()
197                    || keys.len() != updates.len()
198                    || keys.iter().zip(expected).any(|(key, version)| {
199                        self.journals.get(key).map_or(0, |v| v.generation) != version.generation
200                    })
201                {
202                    return Some(RaftOutcome::Exchanged(false));
203                }
204                self.revision += 1;
205                for (key, update) in keys.iter().zip(updates) {
206                    if let Some(entries) = update {
207                        self.journals.insert(
208                            key.clone(),
209                            JournalVersion {
210                                generation: self.revision,
211                                entries: entries.clone(),
212                            },
213                        );
214                    }
215                }
216                self.exchanges.push((self.revision, *id));
217                Some(RaftOutcome::Exchanged(true))
218            }
219        }
220    }
221}
222
223#[derive(Clone, Debug)]
224pub struct RaftNode {
225    config: RaftConfig,
226    jitter: Jitter,
227    // Persistent.
228    hard: RaftHardState,
229    /// `log[0]` is a sentinel of term 0.
230    log: Vec<RaftEntry>,
231    // Volatile.
232    role: RaftRole,
233    leader: Option<usize>,
234    commit: u64,
235    applied: u64,
236    state: JournalState,
237    votes: BTreeSet<usize>,
238    next: Vec<u64>,
239    matched: Vec<u64>,
240    /// Peers heard from since the last quorum check.
241    active: BTreeSet<usize>,
242    election_due: u64,
243    heartbeat_due: u64,
244    quorum_due: u64,
245    /// When this node last heard from a current leader.
246    leader_heard: Option<u64>,
247    waiting: BTreeSet<u64>,
248    outcomes: BTreeMap<u64, RaftOutcome>,
249    outbox: Vec<RaftEnvelope>,
250}
251
252impl RaftNode {
253    pub fn new(config: RaftConfig, now: u64) -> Self {
254        assert!(config.id < config.members && config.members > 0);
255        assert!(config.election_timeout > config.heartbeat_interval);
256        let jitter = Jitter(config.seed);
257        let members = config.members;
258        let mut node = Self {
259            config,
260            jitter,
261            hard: RaftHardState::default(),
262            log: vec![RaftEntry {
263                term: 0,
264                command: RaftCommand::Noop,
265            }],
266            role: RaftRole::Follower,
267            leader: None,
268            commit: 0,
269            applied: 0,
270            state: JournalState::default(),
271            votes: BTreeSet::new(),
272            next: vec![1; members],
273            matched: vec![0; members],
274            active: BTreeSet::new(),
275            election_due: 0,
276            heartbeat_due: 0,
277            quorum_due: 0,
278            leader_heard: None,
279            waiting: BTreeSet::new(),
280            outcomes: BTreeMap::new(),
281            outbox: Vec::new(),
282        };
283        node.reset_election(now);
284        node
285    }
286
287    /// A process restart: the hard state and the log survive, everything
288    /// else (commit index, applied state, pending outcomes) is rebuilt.
289    pub fn restart(&mut self, now: u64) {
290        self.role = RaftRole::Follower;
291        self.leader = None;
292        self.commit = 0;
293        self.applied = 0;
294        self.state = JournalState::default();
295        self.votes.clear();
296        self.active.clear();
297        self.leader_heard = None;
298        self.waiting.clear();
299        self.outcomes.clear();
300        self.outbox.clear();
301        self.reset_election(now);
302    }
303
304    pub fn id(&self) -> usize {
305        self.config.id
306    }
307    pub fn role(&self) -> RaftRole {
308        self.role
309    }
310    pub fn term(&self) -> u64 {
311        self.hard.term
312    }
313    pub fn leader(&self) -> Option<usize> {
314        self.leader
315    }
316    pub fn hard_state(&self) -> &RaftHardState {
317        &self.hard
318    }
319    pub fn commit_index(&self) -> u64 {
320        self.commit
321    }
322    pub fn applied_index(&self) -> u64 {
323        self.applied
324    }
325    /// The whole log, sentinel included.
326    pub fn log(&self) -> &[RaftEntry] {
327        &self.log
328    }
329    pub fn state(&self) -> &JournalState {
330        &self.state
331    }
332    /// Messages to deliver; persist the hard state and log first.
333    pub fn take_messages(&mut self) -> Vec<RaftEnvelope> {
334        std::mem::take(&mut self.outbox)
335    }
336    /// The outcome of a command proposed on this node, once applied here.
337    pub fn take_outcome(&mut self, id: u64) -> Option<RaftOutcome> {
338        self.outcomes.remove(&id)
339    }
340    /// Gives up waiting for a command (its caller timed out).
341    pub fn forget(&mut self, id: u64) {
342        self.waiting.remove(&id);
343        self.outcomes.remove(&id);
344    }
345
346    /// Proposes a command. Returns false when no leader is known, so the
347    /// proposal went nowhere. Even on true the proposal may be lost.
348    pub fn propose(&mut self, now: u64, command: RaftCommand) -> bool {
349        let _ = now;
350        if let Some(id) = command.id() {
351            self.waiting.insert(id);
352        }
353        match (self.role, self.leader) {
354            (RaftRole::Leader, _) => {
355                self.append_local(command);
356                self.broadcast_append();
357                true
358            }
359            (_, Some(leader)) => {
360                self.send(leader, RaftMessage::Propose { command });
361                true
362            }
363            _ => false,
364        }
365    }
366
367    /// Advances timers to the local time `now`. A clock that jumps backward
368    /// only delays them.
369    pub fn tick(&mut self, now: u64) {
370        if self.role == RaftRole::Leader {
371            if self.config.check_quorum && now >= self.quorum_due {
372                self.quorum_due = now + self.config.election_timeout;
373                let heard = self.active.len() + 1;
374                self.active.clear();
375                if heard < self.quorum() {
376                    self.become_follower(now, self.hard.term, None);
377                    return;
378                }
379            }
380            if now >= self.heartbeat_due {
381                self.heartbeat_due = now + self.config.heartbeat_interval;
382                self.broadcast_append();
383            }
384        } else if now >= self.election_due {
385            self.campaign(now, self.config.pre_vote);
386        }
387    }
388
389    pub fn step(&mut self, now: u64, envelope: RaftEnvelope) {
390        let from = envelope.from;
391        if from >= self.config.members || from == self.config.id {
392            return;
393        }
394        let term = match &envelope.message {
395            RaftMessage::Vote { term, .. }
396            | RaftMessage::VoteReply { term, .. }
397            | RaftMessage::Append { term, .. }
398            | RaftMessage::AppendReply { term, .. } => Some(*term),
399            RaftMessage::Propose { .. } => None,
400        };
401        if let Some(term) = term {
402            if term > self.hard.term {
403                if matches!(envelope.message, RaftMessage::Vote { .. }) && self.in_lease(now) {
404                    // Leader stickiness: ignore disruptive campaigns.
405                    return;
406                }
407                let pre_request = matches!(envelope.message, RaftMessage::Vote { pre: true, .. });
408                let pre_grant = matches!(
409                    envelope.message,
410                    RaftMessage::VoteReply {
411                        pre: true,
412                        granted: true,
413                        ..
414                    }
415                );
416                if !pre_request && !pre_grant {
417                    let leader = match envelope.message {
418                        RaftMessage::Append { .. } => Some(from),
419                        _ => None,
420                    };
421                    self.become_follower(now, term, leader);
422                }
423            } else if term < self.hard.term {
424                match envelope.message {
425                    // Tell a stale leader or candidate about the newer term.
426                    RaftMessage::Append { .. } => self.send(
427                        from,
428                        RaftMessage::AppendReply {
429                            term: self.hard.term,
430                            success: false,
431                            index: 0,
432                        },
433                    ),
434                    RaftMessage::Vote { pre, .. } => self.send(
435                        from,
436                        RaftMessage::VoteReply {
437                            pre,
438                            term: self.hard.term,
439                            granted: false,
440                        },
441                    ),
442                    _ => {}
443                }
444                return;
445            }
446        }
447        match envelope.message {
448            RaftMessage::Vote {
449                pre,
450                term,
451                last_index,
452                last_term,
453            } => self.on_vote(now, from, pre, term, last_index, last_term),
454            RaftMessage::VoteReply { pre, term, granted } => {
455                self.on_vote_reply(now, from, pre, term, granted)
456            }
457            RaftMessage::Append {
458                prev_index,
459                prev_term,
460                entries,
461                commit,
462                ..
463            } => self.on_append(now, from, prev_index, prev_term, entries, commit),
464            RaftMessage::AppendReply { success, index, .. } => {
465                self.on_append_reply(from, success, index)
466            }
467            RaftMessage::Propose { command } => {
468                if self.role == RaftRole::Leader {
469                    self.append_local(command);
470                    self.broadcast_append();
471                }
472                // Otherwise the proposal is dropped: no proposal is retried.
473            }
474        }
475    }
476
477    fn quorum(&self) -> usize {
478        self.config.members / 2 + 1
479    }
480    fn last_index(&self) -> u64 {
481        self.log.len() as u64 - 1
482    }
483    fn last_term(&self) -> u64 {
484        self.log.last().map_or(0, |entry| entry.term)
485    }
486    fn in_lease(&self, now: u64) -> bool {
487        self.config.check_quorum
488            && match self.role {
489                RaftRole::Leader => true,
490                _ => {
491                    self.leader.is_some()
492                        && self
493                            .leader_heard
494                            .is_some_and(|heard| now < heard + self.config.election_timeout)
495                }
496            }
497    }
498    fn send(&mut self, to: usize, message: RaftMessage) {
499        self.outbox.push(RaftEnvelope {
500            from: self.config.id,
501            to,
502            message,
503        });
504    }
505    fn reset_election(&mut self, now: u64) {
506        self.election_due =
507            now + self.config.election_timeout + self.jitter.below(self.config.election_timeout);
508    }
509    fn become_follower(&mut self, now: u64, term: u64, leader: Option<usize>) {
510        if term > self.hard.term {
511            self.hard.term = term;
512            self.hard.voted_for = None;
513        }
514        self.role = RaftRole::Follower;
515        self.leader = leader;
516        self.votes.clear();
517        if leader.is_some() {
518            self.leader_heard = Some(now);
519        }
520        self.reset_election(now);
521    }
522    fn campaign(&mut self, now: u64, pre: bool) {
523        self.reset_election(now);
524        self.votes.clear();
525        self.votes.insert(self.config.id);
526        let term = if pre {
527            self.role = RaftRole::PreCandidate;
528            self.hard.term + 1
529        } else {
530            self.role = RaftRole::Candidate;
531            self.hard.term += 1;
532            self.hard.voted_for = Some(self.config.id);
533            self.hard.term
534        };
535        self.leader = None;
536        if self.votes.len() >= self.quorum() {
537            self.win(now, pre);
538            return;
539        }
540        let (last_index, last_term) = (self.last_index(), self.last_term());
541        for peer in 0..self.config.members {
542            if peer != self.config.id {
543                self.send(
544                    peer,
545                    RaftMessage::Vote {
546                        pre,
547                        term,
548                        last_index,
549                        last_term,
550                    },
551                );
552            }
553        }
554    }
555    fn win(&mut self, now: u64, pre: bool) {
556        if pre {
557            self.campaign(now, false);
558            return;
559        }
560        self.role = RaftRole::Leader;
561        self.leader = Some(self.config.id);
562        self.votes.clear();
563        self.active.clear();
564        let next = self.last_index() + 1;
565        self.next.iter_mut().for_each(|value| *value = next);
566        self.matched.iter_mut().for_each(|value| *value = 0);
567        self.quorum_due = now + self.config.election_timeout;
568        self.heartbeat_due = now + self.config.heartbeat_interval;
569        self.append_local(RaftCommand::Noop);
570        self.broadcast_append();
571    }
572    fn on_vote(
573        &mut self,
574        now: u64,
575        from: usize,
576        pre: bool,
577        term: u64,
578        last_index: u64,
579        last_term: u64,
580    ) {
581        let up_to_date = last_term > self.last_term()
582            || (last_term == self.last_term() && last_index >= self.last_index());
583        let granted = if pre {
584            // A pre-vote never changes this node's state.
585            term > self.hard.term && up_to_date && !self.in_lease(now)
586        } else {
587            term == self.hard.term
588                && up_to_date
589                && self.hard.voted_for.is_none_or(|voted| voted == from)
590        };
591        if granted && !pre {
592            self.hard.voted_for = Some(from);
593            self.reset_election(now);
594        }
595        let term = if pre && granted { term } else { self.hard.term };
596        self.send(from, RaftMessage::VoteReply { pre, term, granted });
597    }
598    fn on_vote_reply(&mut self, now: u64, from: usize, pre: bool, term: u64, granted: bool) {
599        let expected = match (self.role, pre) {
600            (RaftRole::PreCandidate, true) => self.hard.term + 1,
601            (RaftRole::Candidate, false) => self.hard.term,
602            _ => return,
603        };
604        if term != expected || !granted {
605            return;
606        }
607        self.votes.insert(from);
608        if self.votes.len() >= self.quorum() {
609            self.win(now, pre);
610        }
611    }
612    fn on_append(
613        &mut self,
614        now: u64,
615        from: usize,
616        prev_index: u64,
617        prev_term: u64,
618        entries: Vec<RaftEntry>,
619        commit: u64,
620    ) {
621        // The term equals ours here; a candidate of this term steps down.
622        if self.role != RaftRole::Follower || self.leader != Some(from) {
623            self.role = RaftRole::Follower;
624            self.leader = Some(from);
625            self.votes.clear();
626        }
627        self.leader_heard = Some(now);
628        self.reset_election(now);
629        if prev_index > self.last_index() || self.log[prev_index as usize].term != prev_term {
630            let hint = (prev_index.saturating_sub(1)).min(self.last_index());
631            self.send(
632                from,
633                RaftMessage::AppendReply {
634                    term: self.hard.term,
635                    success: false,
636                    index: hint,
637                },
638            );
639            return;
640        }
641        let mut index = prev_index;
642        for entry in entries {
643            index += 1;
644            if index <= self.last_index() {
645                if self.log[index as usize].term == entry.term {
646                    continue;
647                }
648                // A conflicting suffix was never committed: drop it.
649                assert!(
650                    index > self.commit,
651                    "a committed entry would be overwritten"
652                );
653                self.log.truncate(index as usize);
654            }
655            self.log.push(entry);
656        }
657        if commit > self.commit {
658            self.commit = commit.min(index);
659            self.apply();
660        }
661        self.send(
662            from,
663            RaftMessage::AppendReply {
664                term: self.hard.term,
665                success: true,
666                index,
667            },
668        );
669    }
670    fn on_append_reply(&mut self, from: usize, success: bool, index: u64) {
671        if self.role != RaftRole::Leader {
672            return;
673        }
674        self.active.insert(from);
675        if success {
676            if index > self.matched[from] {
677                self.matched[from] = index;
678            }
679            self.next[from] = self.next[from].max(index + 1);
680            self.advance_commit();
681            if self.next[from] <= self.last_index() {
682                self.send_append(from);
683            }
684        } else {
685            self.next[from] = (index + 1).min(self.next[from].saturating_sub(1)).max(1);
686            self.send_append(from);
687        }
688    }
689    fn append_local(&mut self, command: RaftCommand) {
690        let term = self.hard.term;
691        self.log.push(RaftEntry { term, command });
692        let id = self.config.id;
693        self.matched[id] = self.last_index();
694        self.next[id] = self.last_index() + 1;
695        self.advance_commit();
696    }
697    fn broadcast_append(&mut self) {
698        for peer in 0..self.config.members {
699            if peer != self.config.id {
700                self.send_append(peer);
701            }
702        }
703    }
704    fn send_append(&mut self, peer: usize) {
705        let prev_index = self.next[peer] - 1;
706        let prev_term = self.log[prev_index as usize].term;
707        let end =
708            (self.log.len()).min(prev_index as usize + 1 + self.config.max_entries_per_message);
709        let entries = self.log[prev_index as usize + 1..end].to_vec();
710        let message = RaftMessage::Append {
711            term: self.hard.term,
712            prev_index,
713            prev_term,
714            entries,
715            commit: self.commit,
716        };
717        self.send(peer, message);
718    }
719    fn advance_commit(&mut self) {
720        let mut matched = self.matched.clone();
721        matched.sort_unstable_by(|a, b| b.cmp(a));
722        let candidate = matched[self.quorum() - 1];
723        // Only entries of the current term commit by counting replicas.
724        if candidate > self.commit && self.log[candidate as usize].term == self.hard.term {
725            self.commit = candidate;
726            self.apply();
727        }
728    }
729    fn apply(&mut self) {
730        while self.applied < self.commit {
731            self.applied += 1;
732            let command = &self.log[self.applied as usize].command;
733            if let Some(outcome) = self.state.apply(command) {
734                let id = command.id().expect("only commands with ids have outcomes");
735                if self.waiting.remove(&id) {
736                    self.outcomes.insert(id, outcome);
737                }
738            }
739        }
740    }
741}
742
743#[cfg(test)]
744mod tests {
745    use super::*;
746
747    fn deliver(nodes: &mut [RaftNode], now: u64) {
748        loop {
749            let messages: Vec<RaftEnvelope> = nodes
750                .iter_mut()
751                .flat_map(|node| node.take_messages())
752                .collect();
753            if messages.is_empty() {
754                return;
755            }
756            for message in messages {
757                let to = message.to;
758                nodes[to].step(now, message);
759            }
760        }
761    }
762
763    fn cluster(pre_vote: bool, check_quorum: bool) -> Vec<RaftNode> {
764        (0..3)
765            .map(|id| {
766                let mut config = RaftConfig::new(id, 3);
767                config.pre_vote = pre_vote;
768                config.check_quorum = check_quorum;
769                RaftNode::new(config, 0)
770            })
771            .collect()
772    }
773
774    #[test]
775    fn a_single_member_elects_itself_and_commits() {
776        let mut node = RaftNode::new(RaftConfig::new(0, 1), 0);
777        node.tick(1000);
778        assert_eq!(node.role(), RaftRole::Leader);
779        assert!(node.propose(
780            1000,
781            RaftCommand::Read {
782                id: 7,
783                keys: vec!["a".into()]
784            }
785        ));
786        assert_eq!(
787            node.take_outcome(7),
788            Some(RaftOutcome::Read(vec![JournalVersion::default()]))
789        );
790    }
791
792    #[test]
793    fn a_leader_replicates_compare_exchange_to_every_member() {
794        let mut nodes = cluster(true, true);
795        nodes[0].tick(1000);
796        deliver(&mut nodes, 1000);
797        assert_eq!(nodes[0].role(), RaftRole::Leader);
798        let exchange = RaftCommand::CompareExchange {
799            id: 1,
800            keys: vec!["a".into()],
801            expected: vec![JournalVersion::default()],
802            updates: vec![Some(vec!["x".into()])],
803        };
804        assert!(nodes[1].propose(1001, exchange.clone()));
805        deliver(&mut nodes, 1001);
806        assert_eq!(nodes[0].commit_index(), 2);
807        // Followers learn the commit index from the next heartbeat.
808        assert_eq!(nodes[1].take_outcome(1), None);
809        nodes[0].tick(1011);
810        deliver(&mut nodes, 1011);
811        assert_eq!(nodes[1].take_outcome(1), Some(RaftOutcome::Exchanged(true)));
812        for node in &nodes {
813            assert_eq!(node.state().journals["a"].entries, vec!["x".to_string()]);
814        }
815        // The same compare-exchange again sees a newer generation.
816        let RaftCommand::CompareExchange {
817            keys,
818            expected,
819            updates,
820            ..
821        } = exchange
822        else {
823            unreachable!()
824        };
825        assert!(nodes[2].propose(
826            1012,
827            RaftCommand::CompareExchange {
828                id: 2,
829                keys,
830                expected,
831                updates
832            }
833        ));
834        deliver(&mut nodes, 1012);
835        nodes[0].tick(1022);
836        deliver(&mut nodes, 1022);
837        assert_eq!(
838            nodes[2].take_outcome(2),
839            Some(RaftOutcome::Exchanged(false))
840        );
841        assert_eq!(nodes[0].state().exchanges, vec![(1, 1)]);
842    }
843
844    #[test]
845    fn a_member_inside_a_leader_lease_ignores_a_disruptive_campaign() {
846        let mut nodes = cluster(true, true);
847        nodes[0].tick(1000);
848        deliver(&mut nodes, 1000);
849        // Node 2 cannot hear anything, times out and campaigns.
850        nodes[2].tick(5000);
851        let campaign = nodes[2].take_messages();
852        assert!(campaign
853            .iter()
854            .all(|m| matches!(m.message, RaftMessage::Vote { pre: true, .. })));
855        for message in campaign {
856            let to = message.to;
857            nodes[to].step(1005, message);
858        }
859        // Neither member replies or raises its term.
860        assert!(nodes[0].take_messages().is_empty() && nodes[1].take_messages().is_empty());
861        assert_eq!((nodes[0].term(), nodes[0].role()), (1, RaftRole::Leader));
862        assert_eq!(nodes[2].term(), 1);
863    }
864
865    #[test]
866    fn a_leader_that_hears_no_majority_steps_down_under_check_quorum() {
867        let mut nodes = cluster(true, true);
868        nodes[0].tick(1000);
869        deliver(&mut nodes, 1000);
870        nodes[0].tick(1100);
871        assert_eq!(nodes[0].role(), RaftRole::Leader);
872        nodes[0].take_messages();
873        nodes[0].tick(1200);
874        assert_eq!(nodes[0].role(), RaftRole::Follower);
875    }
876
877    #[test]
878    fn a_restarted_member_rebuilds_its_state_from_the_log() {
879        let mut nodes = cluster(false, false);
880        nodes[0].tick(1000);
881        deliver(&mut nodes, 1000);
882        assert_eq!(nodes[0].role(), RaftRole::Leader);
883        nodes[0].propose(
884            1000,
885            RaftCommand::CompareExchange {
886                id: 1,
887                keys: vec!["a".into()],
888                expected: vec![JournalVersion::default()],
889                updates: vec![Some(vec!["x".into()])],
890            },
891        );
892        deliver(&mut nodes, 1000);
893        nodes[1].restart(1001);
894        assert_eq!(nodes[1].state(), &JournalState::default());
895        nodes[0].tick(1011);
896        deliver(&mut nodes, 1011);
897        assert_eq!(nodes[1].state(), nodes[0].state());
898        assert_eq!(nodes[1].hard_state().term, 1);
899    }
900}