1use crate::action::{Action, ClientResult, ConfigResult};
16use crate::config::Config;
17use crate::error::{ConfigError, ProtocolError};
18use crate::event::{Event, PersistKind};
19use crate::ids::{ClientId, LogIndex, NodeId, Term, Tick};
20use crate::log::{EntryKind, Log, LogEntry};
21use crate::membership::{ClusterConfig, ConfigChange, ConfigState};
22use crate::message::Message;
23use crate::snapshot::{IncomingSnapshot, LoadedSnapshot, SnapshotMeta};
24use std::collections::{BTreeMap, BTreeSet};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Role {
30 Follower,
32 PreCandidate,
35 Candidate,
37 Leader,
39}
40
41#[derive(Debug, Clone, Copy, Default)]
43pub(crate) struct Progress {
44 pub next_index: LogIndex,
46 pub match_index: LogIndex,
49 pub snapshot: Option<(LogIndex, Term, u64)>,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct PeerStats {
60 pub next_index: LogIndex,
62 pub match_index: LogIndex,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct NodeStats {
73 pub role: Role,
75 pub current_term: Term,
77 pub leader: Option<NodeId>,
79 pub commit_index: LogIndex,
81 pub last_applied: LogIndex,
83 pub last_log_index: LogIndex,
85 pub snapshot_index: LogIndex,
87 pub peers: BTreeMap<NodeId, PeerStats>,
89}
90
91#[derive(Debug, Clone)]
94pub(crate) struct PendingAction {
95 pub need_hard_gen: u64,
97 pub need_entries_up_to: LogIndex,
99 pub term: Term,
104 pub action: Action,
106}
107
108#[derive(Debug, Clone)]
113pub(crate) struct ReadBatch {
114 pub round: u64,
116 pub gate_index: LogIndex,
118 pub acks: BTreeSet<NodeId>,
120 pub requests: Vec<(u64, Vec<u8>)>,
122}
123
124#[derive(Debug)]
126pub struct Node {
127 pub(crate) id: NodeId,
128 pub(crate) config: Config,
129 pub(crate) config_state: ConfigState,
130 pub(crate) initial_config: ClusterConfig,
131 pub(crate) base_config: ClusterConfig,
132 pub(crate) pending_config: Option<(LogIndex, ConfigChange)>,
133 pub(crate) pending_install: Option<SnapshotMeta>,
134 pub(crate) seed: u64,
135 pub(crate) role: Role,
136 pub(crate) current_term: Term,
137 pub(crate) voted_for: Option<NodeId>,
138 pub(crate) log: Log,
139 pub(crate) commit_index: LogIndex,
140 pub(crate) last_applied: LogIndex,
141 pub(crate) leader_id: Option<NodeId>,
142 pub(crate) now: Tick,
143 pub(crate) election_deadline: Tick,
144 pub(crate) heartbeat_deadline: Tick,
145 pub(crate) election_epoch: u64,
146 pub(crate) last_leader_contact: Option<Tick>,
147 pub(crate) prevote_term: Term,
148 pub(crate) prevotes_received: BTreeSet<NodeId>,
149 pub(crate) votes_received: BTreeSet<NodeId>,
150 pub(crate) progress: BTreeMap<NodeId, Progress>,
151 pub(crate) pending: Vec<PendingAction>,
152 pub(crate) read_round_counter: u64,
153 pub(crate) pending_reads: Option<ReadBatch>,
154 pub(crate) last_read_round: u64,
155 pub(crate) inflight: BTreeMap<(ClientId, u64), LogIndex>,
156 pub(crate) attached: BTreeMap<LogIndex, u64>,
157 pub(crate) incoming_snapshot: Option<IncomingSnapshot>,
158 pub(crate) loaded_snapshot: Option<LoadedSnapshot>,
159 pub(crate) hard_gen_sent: u64,
160 pub(crate) hard_gen_acked: u64,
161 pub(crate) entries_durable_up_to: LogIndex,
162 pub(crate) unacked_entry_persists: u64,
163 pub(crate) stale_entry_acks: u64,
164}
165
166impl Node {
167 pub fn new(
178 id: NodeId,
179 config: Config,
180 cluster: ClusterConfig,
181 seed: u64,
182 ) -> Result<Self, ConfigError> {
183 config.validate()?;
184 let mut node = Self {
185 id,
186 config,
187 config_state: ConfigState::new(cluster.clone()),
188 initial_config: cluster.clone(),
189 base_config: cluster,
190 pending_config: None,
191 pending_install: None,
192 seed,
193 role: Role::Follower,
194 current_term: Term::ZERO,
195 voted_for: None,
196 log: Log::new(),
197 commit_index: LogIndex::ZERO,
198 last_applied: LogIndex::ZERO,
199 leader_id: None,
200 now: 0,
201 election_deadline: 0,
202 heartbeat_deadline: 0,
203 election_epoch: 0,
204 last_leader_contact: None,
205 prevote_term: Term::ZERO,
206 prevotes_received: BTreeSet::new(),
207 votes_received: BTreeSet::new(),
208 progress: BTreeMap::new(),
209 pending: Vec::new(),
210 read_round_counter: 0,
211 pending_reads: None,
212 last_read_round: 0,
213 inflight: BTreeMap::new(),
214 attached: BTreeMap::new(),
215 incoming_snapshot: None,
216 loaded_snapshot: None,
217 hard_gen_sent: 0,
218 hard_gen_acked: 0,
219 entries_durable_up_to: LogIndex::ZERO,
220 unacked_entry_persists: 0,
221 stale_entry_acks: 0,
222 };
223 node.reset_election_deadline();
224 Ok(node)
225 }
226
227 #[must_use]
229 pub const fn id(&self) -> NodeId {
230 self.id
231 }
232
233 #[must_use]
235 pub const fn role(&self) -> Role {
236 self.role
237 }
238
239 #[must_use]
241 pub const fn current_term(&self) -> Term {
242 self.current_term
243 }
244
245 #[must_use]
247 pub const fn voted_for(&self) -> Option<NodeId> {
248 self.voted_for
249 }
250
251 #[must_use]
253 pub const fn commit_index(&self) -> LogIndex {
254 self.commit_index
255 }
256
257 #[must_use]
259 pub const fn last_applied(&self) -> LogIndex {
260 self.last_applied
261 }
262
263 #[must_use]
265 pub const fn log(&self) -> &Log {
266 &self.log
267 }
268
269 #[must_use]
271 pub const fn cluster(&self) -> &ClusterConfig {
272 &self.config_state.latest
273 }
274
275 #[must_use]
280 pub const fn last_config_index(&self) -> LogIndex {
281 self.config_state.last_config_index
282 }
283
284 #[must_use]
286 pub const fn leader_id(&self) -> Option<NodeId> {
287 self.leader_id
288 }
289
290 #[must_use]
294 pub fn progress(&self, peer: NodeId) -> Option<(LogIndex, LogIndex)> {
295 self.progress
296 .get(&peer)
297 .map(|p| (p.next_index, p.match_index))
298 }
299
300 #[must_use]
310 pub fn stats(&self) -> NodeStats {
311 let peers = if self.role == Role::Leader {
312 self.progress
313 .iter()
314 .map(|(peer, progress)| {
315 (
316 *peer,
317 PeerStats {
318 next_index: progress.next_index,
319 match_index: progress.match_index,
320 },
321 )
322 })
323 .collect()
324 } else {
325 BTreeMap::new()
326 };
327 NodeStats {
328 role: self.role,
329 current_term: self.current_term,
330 leader: self.leader_id,
331 commit_index: self.commit_index,
332 last_applied: self.last_applied,
333 last_log_index: self.log.last_index(),
334 snapshot_index: self.log.base_index(),
335 peers,
336 }
337 }
338
339 #[must_use]
344 pub const fn poll_timeout(&self) -> Option<Tick> {
345 match self.role {
346 Role::Leader => Some(self.heartbeat_deadline),
347 _ => Some(self.election_deadline),
348 }
349 }
350
351 pub fn step(&mut self, event: Event) -> Vec<Action> {
354 let mut out = Vec::new();
355 match event {
356 Event::Tick { now } => self.on_tick(now, &mut out),
357 Event::Propose {
358 client_id,
359 seq,
360 payload,
361 } => self.on_propose(client_id, seq, payload, &mut out),
362 Event::ReadIndex { request_id, key } => {
363 self.on_read_index(request_id, key, &mut out);
364 }
365 Event::ProposeConfig { change } => self.on_propose_config(change, &mut out),
366 Event::SnapshotLoaded { meta, data } => {
367 self.loaded_snapshot = Some(LoadedSnapshot { meta, data });
368 }
369 Event::SnapshotPersisted { meta } => self.on_snapshot_persisted(&meta),
370 Event::Message { from, msg } => self.on_message(from, msg, &mut out),
371 Event::Persisted { kind, up_to_index } => {
372 self.on_persisted(kind, up_to_index, &mut out);
373 }
374 Event::Restored {
375 hard_state,
376 entries,
377 snapshot,
378 } => self.on_restored(
379 hard_state.current_term,
380 hard_state.voted_for,
381 &entries,
382 snapshot.as_ref(),
383 ),
384 }
385 out
386 }
387
388 pub(crate) const fn timer_offset(&self) -> u64 {
393 let span = self
394 .config
395 .max_election_timeout
396 .saturating_sub(self.config.min_election_timeout);
397 if span == 0 {
398 return 0;
399 }
400 splitmix64(
401 self.seed
402 ^ self.id.0.wrapping_mul(0x9E37_79B9_7F4A_7C15)
403 ^ self.election_epoch.wrapping_mul(0xBF58_476D_1CE4_E5B9),
404 ) % span
405 }
406
407 pub(crate) const fn reset_election_deadline(&mut self) {
410 self.election_epoch += 1;
411 self.election_deadline = self
412 .now
413 .saturating_add(self.config.min_election_timeout)
414 .saturating_add(self.timer_offset());
415 }
416
417 fn emit_persist_hard(&mut self, out: &mut Vec<Action>) -> u64 {
422 self.hard_gen_sent += 1;
423 out.push(Action::PersistHardState {
424 current_term: self.current_term,
425 voted_for: self.voted_for,
426 });
427 self.hard_gen_sent
428 }
429
430 fn emit_persist_entries(
434 &mut self,
435 from_index: LogIndex,
436 entries: Vec<LogEntry>,
437 out: &mut Vec<Action>,
438 ) {
439 self.unacked_entry_persists += 1;
440 out.push(Action::PersistEntries {
441 from_index,
442 entries,
443 });
444 }
445
446 fn defer_or_emit(
449 &mut self,
450 out: &mut Vec<Action>,
451 action: Action,
452 need_hard_gen: u64,
453 need_entries_up_to: LogIndex,
454 ) {
455 if need_hard_gen <= self.hard_gen_acked && need_entries_up_to <= self.entries_durable_up_to
456 {
457 out.push(action);
458 } else {
459 self.pending.push(PendingAction {
460 need_hard_gen,
461 need_entries_up_to,
462 term: self.current_term,
463 action,
464 });
465 }
466 }
467
468 fn releasable(&self, held: &PendingAction) -> bool {
472 let stale_send =
473 matches!(held.action, Action::Send { .. }) && held.term != self.current_term;
474 !stale_send
475 && held.need_hard_gen <= self.hard_gen_acked
476 && held.need_entries_up_to <= self.entries_durable_up_to
477 }
478
479 fn flush_pending(&mut self, out: &mut Vec<Action>) {
495 let mut last_append: BTreeMap<NodeId, usize> = BTreeMap::new();
498 for (index, held) in self.pending.iter().enumerate() {
499 if !self.releasable(held) {
500 continue;
501 }
502 if let Action::Send {
503 to,
504 msg: Message::AppendEntries { .. },
505 } = &held.action
506 {
507 last_append.insert(*to, index);
508 }
509 }
510 let pending = std::mem::take(&mut self.pending);
511 for (index, held) in pending.into_iter().enumerate() {
512 if !self.releasable(&held) {
513 let stale_send =
514 matches!(held.action, Action::Send { .. }) && held.term != self.current_term;
515 if !stale_send {
516 self.pending.push(held);
517 }
518 continue;
519 }
520 let superseded_append = matches!(
521 &held.action,
522 Action::Send {
523 to,
524 msg: Message::AppendEntries { .. },
525 } if last_append.get(to) != Some(&index)
526 );
527 if superseded_append {
528 continue;
529 }
530 out.push(held.action);
531 }
532 }
533
534 fn on_persisted(&mut self, kind: PersistKind, up_to_index: LogIndex, out: &mut Vec<Action>) {
535 match kind {
536 PersistKind::HardState => {
537 self.hard_gen_acked = self
538 .hard_gen_acked
539 .saturating_add(1)
540 .min(self.hard_gen_sent);
541 }
542 PersistKind::Entries => {
543 if self.stale_entry_acks > 0 {
544 self.stale_entry_acks -= 1;
545 self.unacked_entry_persists = self.unacked_entry_persists.saturating_sub(1);
546 } else {
547 let capped = up_to_index.min(self.log.last_index());
548 if capped >= self.log.last_index() {
549 self.unacked_entry_persists = 0;
550 } else {
551 self.unacked_entry_persists = self.unacked_entry_persists.saturating_sub(1);
552 }
553 if capped > self.entries_durable_up_to {
554 self.entries_durable_up_to = capped;
555 }
556 }
557 }
558 }
559 self.flush_pending(out);
560 if self.role == Role::Leader {
561 self.advance_commit(out);
562 self.try_release_reads(out);
563 }
564 }
565
566 fn on_restored(
567 &mut self,
568 term: Term,
569 voted_for: Option<NodeId>,
570 entries: &[LogEntry],
571 snapshot: Option<&SnapshotMeta>,
572 ) {
573 self.current_term = term;
574 self.voted_for = voted_for;
575 self.log = Log::new();
576 if let Some(meta) = snapshot {
583 self.log
584 .advance_base(meta.last_included_index, meta.last_included_term);
585 }
586 self.log.append(entries);
587 self.role = Role::Follower;
588 self.commit_index = LogIndex::ZERO;
589 self.last_applied = LogIndex::ZERO;
590 self.leader_id = None;
591 self.last_leader_contact = None;
592 self.progress.clear();
593 self.pending.clear();
594 self.pending_reads = None;
595 self.last_read_round = 0;
596 self.inflight.clear();
597 self.attached.clear();
598 self.votes_received.clear();
599 self.prevotes_received.clear();
600 self.base_config = self.initial_config.clone();
601 self.pending_config = None;
602 self.pending_install = None;
603 self.incoming_snapshot = None;
604 self.loaded_snapshot = None;
605 self.recompute_config();
606 if let Some(meta) = snapshot {
614 self.install_snapshot(meta);
615 }
616 self.entries_durable_up_to = self.log.last_index();
617 self.unacked_entry_persists = 0;
618 self.stale_entry_acks = 0;
619 self.hard_gen_sent += 1;
620 self.hard_gen_acked = self.hard_gen_sent;
621 self.reset_election_deadline();
622 }
623
624 fn set_term(&mut self, term: Term, out: &mut Vec<Action>) {
629 if self.role == Role::Leader {
630 out.push(Action::StepDown { term });
631 self.fail_pending_reads(out);
632 }
633 self.role = Role::Follower;
634 self.current_term = term;
635 self.voted_for = None;
636 self.leader_id = None;
637 self.progress.clear();
638 self.votes_received.clear();
639 self.prevotes_received.clear();
640 self.inflight.clear();
641 self.attached.clear();
642 self.pending_config = None;
643 self.last_read_round = 0;
644 }
645
646 fn recompute_config(&mut self) {
653 let mut latest: &ClusterConfig = &self.base_config;
654 let mut committed: &ClusterConfig = &self.base_config;
655 let mut last_config_index = self.log.base_index();
656 let base = self.log.base_index().0;
657 for (offset, entry) in self.log.entries().iter().enumerate() {
658 if let EntryKind::Config { config } = &entry.kind {
659 let index = LogIndex(base + 1 + offset as u64);
660 latest = config;
661 last_config_index = index;
662 if index <= self.commit_index {
663 committed = config;
664 }
665 }
666 }
667 if self.config_state.latest == *latest
668 && self.config_state.committed == *committed
669 && self.config_state.last_config_index == last_config_index
670 {
671 return;
672 }
673 self.config_state = ConfigState {
674 latest: latest.clone(),
675 committed: committed.clone(),
676 last_config_index,
677 };
678 }
679
680 fn step_down_after_removal(&mut self, out: &mut Vec<Action>) {
684 out.push(Action::StepDown {
685 term: self.current_term,
686 });
687 self.fail_pending_reads(out);
688 self.role = Role::Follower;
689 self.leader_id = None;
690 self.progress.clear();
691 self.inflight.clear();
692 self.attached.clear();
693 }
694
695 fn on_config_applied(
699 &mut self,
700 index: LogIndex,
701 config: &ClusterConfig,
702 out: &mut Vec<Action>,
703 ) {
704 self.recompute_config();
705 if let Some((pending_index, change)) = self.pending_config.take() {
706 if pending_index == index {
707 self.defer_or_emit(
708 out,
709 Action::ConfigResponse {
710 change,
711 result: ConfigResult::Committed,
712 },
713 0,
714 index,
715 );
716 } else {
717 self.pending_config = Some((pending_index, change));
718 }
719 }
720 if self.role != Role::Leader {
721 return;
722 }
723 let next = self.log.last_index().next();
724 for member in config.members() {
725 if member != self.id && !self.progress.contains_key(&member) {
726 self.progress.insert(
727 member,
728 Progress {
729 next_index: next,
730 match_index: LogIndex::ZERO,
731 snapshot: None,
732 },
733 );
734 }
735 }
736 self.progress.retain(|peer, _| config.contains(*peer));
737 if !config.is_voter(self.id) {
738 self.step_down_after_removal(out);
739 }
740 }
741
742 fn fail_pending_reads(&mut self, out: &mut Vec<Action>) {
745 if let Some(batch) = self.pending_reads.take() {
746 for (request_id, _key) in batch.requests {
747 out.push(Action::ReadRejected {
748 request_id,
749 leader: None,
750 });
751 }
752 }
753 }
754
755 fn try_release_reads(&mut self, out: &mut Vec<Action>) {
760 if self.hard_gen_acked < self.hard_gen_sent {
761 return;
762 }
763 let Some(batch) = &self.pending_reads else {
764 return;
765 };
766 if batch.acks.len() < self.config_state.latest.quorum()
767 || self.commit_index < batch.gate_index
768 {
769 return;
770 }
771 let read_index = self.commit_index;
772 let batch = self.pending_reads.take().expect("batch checked above");
773 for (request_id, key) in batch.requests {
774 out.push(Action::ReadReady {
775 request_id,
776 key,
777 read_index,
778 });
779 }
780 }
781
782 fn log_up_to_date(&self, last_term: Term, last_index: LogIndex) -> bool {
785 let my_term = self.log.last_term();
786 last_term > my_term || (last_term == my_term && last_index >= self.log.last_index())
787 }
788
789 fn start_prevote(&mut self, out: &mut Vec<Action>) {
790 self.role = Role::PreCandidate;
791 self.leader_id = None;
792 self.prevote_term = self.current_term.next();
793 self.prevotes_received = BTreeSet::from([self.id]);
794 self.reset_election_deadline();
795 if self.prevotes_received.len() >= self.config_state.latest.quorum() {
796 self.start_election(out);
797 return;
798 }
799 let msg = Message::RequestPreVote {
800 term: self.prevote_term,
801 last_log_index: self.log.last_index(),
802 last_log_term: self.log.last_term(),
803 };
804 for voter in self.config_state.latest.voters.iter().copied() {
805 if voter != self.id {
806 out.push(Action::Send {
807 to: voter,
808 msg: msg.clone(),
809 });
810 }
811 }
812 }
813
814 fn start_election(&mut self, out: &mut Vec<Action>) {
815 self.role = Role::Candidate;
816 self.current_term = self.prevote_term;
817 self.voted_for = Some(self.id);
818 self.votes_received = BTreeSet::from([self.id]);
819 self.reset_election_deadline();
820 let generation = self.emit_persist_hard(out);
821 if self.votes_received.len() >= self.config_state.latest.quorum() {
822 self.become_leader(out);
823 return;
824 }
825 let msg = Message::RequestVote {
826 term: self.current_term,
827 last_log_index: self.log.last_index(),
828 last_log_term: self.log.last_term(),
829 };
830 let voters: Vec<NodeId> = self.config_state.latest.voters.iter().copied().collect();
831 for voter in voters {
832 if voter != self.id {
833 self.defer_or_emit(
834 out,
835 Action::Send {
836 to: voter,
837 msg: msg.clone(),
838 },
839 generation,
840 LogIndex::ZERO,
841 );
842 }
843 }
844 }
845
846 fn become_leader(&mut self, out: &mut Vec<Action>) {
847 self.role = Role::Leader;
848 self.leader_id = Some(self.id);
849 self.last_leader_contact = Some(self.now);
850 self.heartbeat_deadline = self.now.saturating_add(self.config.heartbeat_interval);
851 let next = self.log.last_index().next();
852 self.progress = self
853 .config_state
854 .latest
855 .members()
856 .filter(|&m| m != self.id)
857 .map(|m| {
858 (
859 m,
860 Progress {
861 next_index: next,
862 match_index: LogIndex::ZERO,
863 snapshot: None,
864 },
865 )
866 })
867 .collect();
868 let entries = vec![LogEntry {
871 term: self.current_term,
872 kind: EntryKind::NoOp,
873 }];
874 let first = self.log.append(&entries);
875 self.emit_persist_entries(first, entries, out);
876 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
877 for peer in peers {
878 self.send_append(peer, out);
879 }
880 }
881
882 fn on_tick(&mut self, now: Tick, out: &mut Vec<Action>) {
885 self.now = self.now.max(now);
886 match self.role {
887 Role::Leader => {
888 if self.now >= self.heartbeat_deadline {
889 self.heartbeat_deadline =
890 self.now.saturating_add(self.config.heartbeat_interval);
891 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
892 for peer in peers {
893 self.send_append(peer, out);
894 }
895 }
896 }
897 Role::Follower | Role::PreCandidate | Role::Candidate => {
898 if self.now >= self.election_deadline && self.config_state.latest.is_voter(self.id)
899 {
900 self.start_prevote(out);
901 }
902 }
903 }
904 }
905
906 fn on_read_index(&mut self, request_id: u64, key: Vec<u8>, out: &mut Vec<Action>) {
911 if self.role != Role::Leader {
912 out.push(Action::ReadRejected {
913 request_id,
914 leader: self.leader_id,
915 });
916 return;
917 }
918 if let Some(batch) = &mut self.pending_reads {
919 batch.requests.push((request_id, key));
920 return;
921 }
922 let Some(gate_index) = self.log.first_index_of_term(self.current_term) else {
923 out.push(Action::ReadRejected {
926 request_id,
927 leader: self.leader_id,
928 });
929 return;
930 };
931 self.read_round_counter += 1;
932 let mut acks = BTreeSet::new();
933 acks.insert(self.id);
934 self.pending_reads = Some(ReadBatch {
935 round: self.read_round_counter,
936 gate_index,
937 acks,
938 requests: vec![(request_id, key)],
939 });
940 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
941 for peer in peers {
942 self.send_append(peer, out);
943 }
944 self.try_release_reads(out);
945 }
946
947 fn on_propose(
948 &mut self,
949 client_id: ClientId,
950 seq: u64,
951 payload: Vec<u8>,
952 out: &mut Vec<Action>,
953 ) {
954 if self.role != Role::Leader {
955 out.push(Action::ClientResponse {
956 client_id,
957 seq,
958 result: ClientResult::NotLeader {
959 leader: self.leader_id,
960 },
961 });
962 return;
963 }
964 if let Some(&index) = self.inflight.get(&(client_id, seq))
968 && index > self.commit_index
969 {
970 *self.attached.entry(index).or_insert(0) += 1;
971 return;
972 }
973 let uncommitted =
974 usize::try_from(self.log.last_index().0.saturating_sub(self.commit_index.0))
975 .unwrap_or(usize::MAX);
976 if uncommitted >= self.config.max_uncommitted_entries {
977 out.push(Action::ClientResponse {
978 client_id,
979 seq,
980 result: ClientResult::Rejected {
981 error: ProtocolError::TooManyUncommitted {
982 uncommitted,
983 limit: self.config.max_uncommitted_entries,
984 },
985 },
986 });
987 return;
988 }
989 let entry = LogEntry {
990 term: self.current_term,
991 kind: EntryKind::Command {
992 client_id,
993 seq,
994 payload,
995 },
996 };
997 let entries = vec![entry];
998 let first = self.log.append(&entries);
999 self.inflight.insert((client_id, seq), first);
1000 self.emit_persist_entries(first, entries, out);
1001 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
1002 for peer in peers {
1003 self.send_append(peer, out);
1004 }
1005 }
1006
1007 fn build_append(&self, peer: NodeId, read_round: u64) -> Message {
1012 let next = self
1013 .progress
1014 .get(&peer)
1015 .map_or_else(|| self.log.last_index().next(), |p| p.next_index);
1016 let prev = LogIndex(next.0.saturating_sub(1));
1017 let prev_term = self.log.term_at(prev).unwrap_or(Term::ZERO);
1018 let entries = self.log.entries_from(
1019 next,
1020 self.config.max_entries_per_append,
1021 self.config.max_append_bytes,
1022 );
1023 Message::AppendEntries {
1024 term: self.current_term,
1025 prev_log_index: prev,
1026 prev_log_term: prev_term,
1027 entries,
1028 leader_commit: self.commit_index,
1029 read_round,
1030 }
1031 }
1032
1033 fn send_append(&mut self, peer: NodeId, out: &mut Vec<Action>) {
1036 let next = self
1040 .progress
1041 .get(&peer)
1042 .map_or_else(|| self.log.last_index().next(), |prog| prog.next_index);
1043 if self.log.base_index() > LogIndex::ZERO && next <= self.log.base_index() {
1044 self.send_snapshot_chunk(peer, out);
1045 return;
1046 }
1047 let round = self.pending_reads.as_ref().map_or(0, |batch| batch.round);
1048 let msg = self.build_append(peer, round);
1049 let need = if let Message::AppendEntries {
1050 prev_log_index,
1051 entries,
1052 ..
1053 } = &msg
1054 && !entries.is_empty()
1055 {
1056 LogIndex(prev_log_index.0 + entries.len() as u64)
1057 } else {
1058 LogIndex::ZERO
1059 };
1060 self.defer_or_emit(
1061 out,
1062 Action::Send { to: peer, msg },
1063 self.hard_gen_sent,
1064 need,
1065 );
1066 }
1067
1068 fn base_meta(&self) -> SnapshotMeta {
1070 SnapshotMeta {
1071 last_included_index: self.log.base_index(),
1072 last_included_term: self.log.base_term(),
1073 config: self.base_config.clone(),
1074 }
1075 }
1076
1077 fn send_snapshot_chunk(&mut self, peer: NodeId, out: &mut Vec<Action>) {
1088 let meta = self.base_meta();
1089 let Some(loaded) = &self.loaded_snapshot else {
1090 out.push(Action::LoadSnapshot { meta });
1091 return;
1092 };
1093 if loaded.meta != meta {
1094 out.push(Action::LoadSnapshot { meta });
1095 return;
1096 }
1097 let loaded = loaded.clone();
1098 let chunk = self.config.snapshot_chunk_bytes;
1099 let Some(prog) = self.progress.get_mut(&peer) else {
1100 return;
1101 };
1102 let offset = match prog.snapshot {
1103 Some((index, term, next_offset))
1104 if index == meta.last_included_index
1105 && term == meta.last_included_term
1106 && next_offset > 0
1107 && next_offset < loaded.data.len() as u64 =>
1108 {
1109 next_offset
1110 }
1111 _ => 0,
1112 };
1113 let start = usize::try_from(offset)
1114 .unwrap_or(usize::MAX)
1115 .min(loaded.data.len());
1116 let end = start.saturating_add(chunk).min(loaded.data.len());
1117 let done = end == loaded.data.len();
1118 prog.snapshot = Some((
1119 meta.last_included_index,
1120 meta.last_included_term,
1121 end as u64,
1122 ));
1123 out.push(Action::Send {
1124 to: peer,
1125 msg: Message::InstallSnapshot {
1126 term: self.current_term,
1127 last_included_index: meta.last_included_index,
1128 last_included_term: meta.last_included_term,
1129 config: meta.config,
1130 offset,
1131 data: loaded.data[start..end].to_vec(),
1132 done,
1133 },
1134 });
1135 }
1136
1137 #[allow(
1143 clippy::too_many_arguments,
1144 reason = "one argument per InstallSnapshot field keeps the handler aligned with the message layout"
1145 )]
1146 fn on_install_snapshot(
1147 &mut self,
1148 from: NodeId,
1149 term: Term,
1150 meta: SnapshotMeta,
1151 offset: u64,
1152 data: &[u8],
1153 done: bool,
1154 out: &mut Vec<Action>,
1155 ) {
1156 if term < self.current_term {
1157 out.push(Action::Send {
1158 to: from,
1159 msg: Message::InstallSnapshotResponse {
1160 term: self.current_term,
1161 match_index: self.log.base_index(),
1162 },
1163 });
1164 return;
1165 }
1166 let need_hard = if term > self.current_term {
1167 self.set_term(term, out);
1168 self.emit_persist_hard(out)
1169 } else if self.role == Role::Leader {
1170 out.push(Action::StepDown { term });
1171 self.fail_pending_reads(out);
1172 self.role = Role::Follower;
1173 self.progress.clear();
1174 self.inflight.clear();
1175 self.attached.clear();
1176 self.pending_config = None;
1177 0
1178 } else {
1179 self.role = Role::Follower;
1180 0
1181 };
1182 self.leader_id = Some(from);
1183 self.last_leader_contact = Some(self.now);
1184 self.reset_election_deadline();
1185
1186 if meta.last_included_index <= self.log.base_index() {
1188 let response = Action::Send {
1189 to: from,
1190 msg: Message::InstallSnapshotResponse {
1191 term: self.current_term,
1192 match_index: self.log.base_index(),
1193 },
1194 };
1195 self.defer_or_emit(out, response, need_hard, LogIndex::ZERO);
1196 return;
1197 }
1198 let fresh = self
1201 .incoming_snapshot
1202 .as_ref()
1203 .is_none_or(|incoming| incoming.meta != meta);
1204 if fresh {
1205 self.incoming_snapshot = Some(IncomingSnapshot::new(meta.clone()));
1206 }
1207 let expected = self
1208 .incoming_snapshot
1209 .as_ref()
1210 .map_or(0, IncomingSnapshot::expected_offset);
1211 if offset != expected {
1212 let response = Action::Send {
1218 to: from,
1219 msg: Message::InstallSnapshotResponse {
1220 term: self.current_term,
1221 match_index: self.log.base_index(),
1222 },
1223 };
1224 self.defer_or_emit(out, response, need_hard, LogIndex::ZERO);
1225 return;
1226 }
1227 if let Some(incoming) = &mut self.incoming_snapshot {
1228 incoming.data.extend_from_slice(data);
1229 }
1230 if done && let Some(incoming) = self.incoming_snapshot.take() {
1231 self.pending_install = Some(meta.clone());
1232 out.push(Action::PersistSnapshot {
1233 meta,
1234 data: incoming.data,
1235 });
1236 }
1237 let response = Action::Send {
1238 to: from,
1239 msg: Message::InstallSnapshotResponse {
1240 term: self.current_term,
1241 match_index: self.log.base_index(),
1242 },
1243 };
1244 self.defer_or_emit(out, response, need_hard, LogIndex::ZERO);
1245 }
1246
1247 fn on_snapshot_response(
1251 &mut self,
1252 from: NodeId,
1253 term: Term,
1254 match_index: LogIndex,
1255 out: &mut Vec<Action>,
1256 ) {
1257 if term > self.current_term {
1258 self.set_term(term, out);
1259 let _ = self.emit_persist_hard(out);
1260 return;
1261 }
1262 if self.role != Role::Leader || term < self.current_term {
1263 return;
1264 }
1265 let mut advance = false;
1266 if let Some(prog) = self.progress.get_mut(&from) {
1267 if match_index > prog.match_index {
1268 prog.match_index = match_index;
1269 advance = true;
1270 }
1271 if prog.next_index < prog.match_index.next() {
1272 prog.next_index = prog.match_index.next();
1273 }
1274 if match_index >= self.log.base_index() {
1275 prog.snapshot = None;
1276 }
1277 }
1278 if advance {
1279 self.advance_commit(out);
1280 }
1281 }
1282
1283 fn on_snapshot_persisted(&mut self, meta: &SnapshotMeta) {
1289 if self.pending_install.as_ref() == Some(meta) {
1290 self.pending_install = None;
1291 self.install_snapshot(meta);
1292 return;
1293 }
1294 if let Some(loaded) = &self.loaded_snapshot
1295 && loaded.meta == *meta
1296 && meta.last_included_index <= self.commit_index
1297 {
1298 self.install_snapshot(meta);
1299 }
1300 }
1301
1302 fn install_snapshot(&mut self, meta: &SnapshotMeta) {
1307 let index = meta.last_included_index;
1308 if index < self.log.base_index() {
1309 return;
1310 }
1311 if self.log.term_at(index) == Some(meta.last_included_term) {
1312 if self.entries_durable_up_to < index {
1313 self.entries_durable_up_to = index;
1314 }
1315 } else {
1316 self.log.clear_entries();
1317 self.entries_durable_up_to = index;
1318 self.stale_entry_acks = self.unacked_entry_persists;
1319 }
1320 self.log.advance_base(index, meta.last_included_term);
1321 if self.commit_index < index {
1322 self.commit_index = index;
1323 }
1324 if self.last_applied < index {
1325 self.last_applied = index;
1326 }
1327 self.base_config = meta.config.clone();
1328 self.inflight.retain(|_, entry_index| *entry_index > index);
1329 self.attached.retain(|entry_index, _| *entry_index > index);
1330 if let Some(incoming) = &self.incoming_snapshot
1331 && incoming.meta.last_included_index <= index
1332 {
1333 self.incoming_snapshot = None;
1334 }
1335 self.recompute_config();
1336 }
1337
1338 fn advance_commit(&mut self, out: &mut Vec<Action>) {
1342 if self.hard_gen_acked < self.hard_gen_sent {
1343 return;
1344 }
1345 let mut held: Vec<u64> = self
1346 .config_state
1347 .latest
1348 .voters
1349 .iter()
1350 .map(|&v| {
1351 if v == self.id {
1352 self.entries_durable_up_to.0
1353 } else {
1354 self.progress.get(&v).map_or(0, |p| p.match_index.0)
1355 }
1356 })
1357 .collect();
1358 held.sort_unstable();
1359 let quorum = self.config_state.latest.quorum();
1360 let candidate = LogIndex(held[held.len() - quorum]);
1361 if candidate > self.commit_index && self.log.term_at(candidate) == Some(self.current_term) {
1362 self.commit_index = candidate;
1363 self.emit_applies(out);
1364 self.try_release_reads(out);
1365 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
1366 for peer in peers {
1367 self.send_append(peer, out);
1368 }
1369 }
1370 }
1371
1372 fn emit_applies(&mut self, out: &mut Vec<Action>) {
1376 while self.last_applied < self.commit_index {
1377 self.last_applied = self.last_applied.next();
1378 let index = self.last_applied;
1379 let Some(entry) = self.log.entry_at(index).cloned() else {
1380 break;
1381 };
1382 let applied_config = match &entry.kind {
1383 EntryKind::Config { config } => Some(config.clone()),
1384 _ => None,
1385 };
1386 let applied_command = match &entry.kind {
1387 EntryKind::Command { client_id, seq, .. } => Some((*client_id, *seq)),
1388 _ => None,
1389 };
1390 self.defer_or_emit(out, Action::Apply { index, entry }, 0, index);
1391 if let Some(config) = applied_config {
1392 self.on_config_applied(index, &config, out);
1393 }
1394 if let Some((client_id, seq)) = applied_command {
1395 self.defer_or_emit(
1396 out,
1397 Action::ClientResponse {
1398 client_id,
1399 seq,
1400 result: ClientResult::Committed,
1401 },
1402 0,
1403 index,
1404 );
1405 self.inflight.remove(&(client_id, seq));
1410 if let Some(extra) = self.attached.remove(&index) {
1411 for _ in 0..extra {
1412 self.defer_or_emit(
1413 out,
1414 Action::ClientResponse {
1415 client_id,
1416 seq,
1417 result: ClientResult::Committed,
1418 },
1419 0,
1420 index,
1421 );
1422 }
1423 }
1424 }
1425 }
1426 }
1427
1428 fn on_message(&mut self, from: NodeId, msg: Message, out: &mut Vec<Action>) {
1431 match msg {
1432 Message::RequestVote {
1433 term,
1434 last_log_index,
1435 last_log_term,
1436 } => self.on_request_vote(from, term, last_log_index, last_log_term, out),
1437 Message::RequestVoteResponse { term, vote_granted } => {
1438 self.on_vote_response(from, term, vote_granted, out);
1439 }
1440 Message::RequestPreVote {
1441 term,
1442 last_log_index,
1443 last_log_term,
1444 } => self.on_request_prevote(from, term, last_log_index, last_log_term, out),
1445 Message::RequestPreVoteResponse { term, vote_granted } => {
1446 self.on_prevote_response(from, term, vote_granted, out);
1447 }
1448 Message::AppendEntries {
1449 term,
1450 prev_log_index,
1451 prev_log_term,
1452 entries,
1453 leader_commit,
1454 read_round,
1455 } => self.on_append_entries(
1456 from,
1457 term,
1458 prev_log_index,
1459 prev_log_term,
1460 entries,
1461 leader_commit,
1462 read_round,
1463 out,
1464 ),
1465 Message::AppendEntriesResponse {
1466 term,
1467 success,
1468 match_index,
1469 conflict_index,
1470 conflict_term,
1471 read_round,
1472 } => self.on_append_response(
1473 from,
1474 term,
1475 success,
1476 match_index,
1477 conflict_index,
1478 conflict_term,
1479 read_round,
1480 out,
1481 ),
1482 Message::InstallSnapshot {
1483 term,
1484 last_included_index,
1485 last_included_term,
1486 config,
1487 offset,
1488 data,
1489 done,
1490 } => self.on_install_snapshot(
1491 from,
1492 term,
1493 SnapshotMeta {
1494 last_included_index,
1495 last_included_term,
1496 config,
1497 },
1498 offset,
1499 &data,
1500 done,
1501 out,
1502 ),
1503 Message::InstallSnapshotResponse { term, match_index } => {
1504 self.on_snapshot_response(from, term, match_index, out);
1505 }
1506 }
1507 }
1508
1509 fn on_propose_config(&mut self, change: ConfigChange, out: &mut Vec<Action>) {
1517 let reject = |out: &mut Vec<Action>, error: ProtocolError| {
1518 out.push(Action::ConfigResponse {
1519 change,
1520 result: ConfigResult::Rejected { error },
1521 });
1522 };
1523 if self.role != Role::Leader {
1524 out.push(Action::ConfigResponse {
1525 change,
1526 result: ConfigResult::NotLeader {
1527 leader: self.leader_id,
1528 },
1529 });
1530 return;
1531 }
1532 if let Some(noop_index) = self.log.first_index_of_term(self.current_term)
1533 && self.commit_index < noop_index
1534 {
1535 reject(
1536 out,
1537 ProtocolError::LeaderNoopUncommitted {
1538 noop_index,
1539 commit_index: self.commit_index,
1540 },
1541 );
1542 return;
1543 }
1544 if self.config_state.last_config_index > self.commit_index {
1545 reject(
1546 out,
1547 ProtocolError::ConfigChangePending {
1548 last_config_index: self.config_state.last_config_index,
1549 commit_index: self.commit_index,
1550 },
1551 );
1552 return;
1553 }
1554 let new_config = match self.config_state.latest.apply_change(change) {
1555 Ok(config) => config,
1556 Err(error) => {
1557 reject(out, error);
1558 return;
1559 }
1560 };
1561 if let ConfigChange::PromoteVoter { node } = change {
1562 let matched = self
1563 .progress
1564 .get(&node)
1565 .map_or(LogIndex::ZERO, |prog| prog.match_index);
1566 if matched < self.commit_index {
1567 reject(
1568 out,
1569 ProtocolError::LearnerNotCaughtUp {
1570 node,
1571 match_index: matched,
1572 required: self.commit_index,
1573 },
1574 );
1575 return;
1576 }
1577 }
1578 let entries = vec![LogEntry {
1579 term: self.current_term,
1580 kind: EntryKind::Config { config: new_config },
1581 }];
1582 let first = self.log.append(&entries);
1583 self.pending_config = Some((first, change));
1584 self.emit_persist_entries(first, entries, out);
1585 self.recompute_config();
1586 let peers: Vec<NodeId> = self.progress.keys().copied().collect();
1587 for peer in peers {
1588 self.send_append(peer, out);
1589 }
1590 }
1591
1592 fn on_request_vote(
1593 &mut self,
1594 from: NodeId,
1595 term: Term,
1596 last_log_index: LogIndex,
1597 last_log_term: Term,
1598 out: &mut Vec<Action>,
1599 ) {
1600 if term < self.current_term {
1601 out.push(Action::Send {
1602 to: from,
1603 msg: Message::RequestVoteResponse {
1604 term: self.current_term,
1605 vote_granted: false,
1606 },
1607 });
1608 return;
1609 }
1610 let mut hard_changed = if term > self.current_term {
1611 self.set_term(term, out);
1612 true
1613 } else {
1614 false
1615 };
1616 if !self.config_state.latest.is_voter(self.id) {
1621 let response = Action::Send {
1622 to: from,
1623 msg: Message::RequestVoteResponse {
1624 term: self.current_term,
1625 vote_granted: false,
1626 },
1627 };
1628 if hard_changed {
1629 let generation = self.emit_persist_hard(out);
1630 self.defer_or_emit(out, response, generation, LogIndex::ZERO);
1631 } else {
1632 out.push(response);
1633 }
1634 return;
1635 }
1636 let grant = (self.voted_for.is_none() || self.voted_for == Some(from))
1637 && self.log_up_to_date(last_log_term, last_log_index);
1638 if grant {
1639 if self.voted_for != Some(from) {
1640 self.voted_for = Some(from);
1641 hard_changed = true;
1642 }
1643 self.reset_election_deadline();
1644 }
1645 let response = Action::Send {
1646 to: from,
1647 msg: Message::RequestVoteResponse {
1648 term: self.current_term,
1649 vote_granted: grant,
1650 },
1651 };
1652 if hard_changed {
1653 let generation = self.emit_persist_hard(out);
1654 self.defer_or_emit(out, response, generation, LogIndex::ZERO);
1655 } else {
1656 out.push(response);
1657 }
1658 }
1659
1660 fn on_vote_response(
1661 &mut self,
1662 from: NodeId,
1663 term: Term,
1664 vote_granted: bool,
1665 out: &mut Vec<Action>,
1666 ) {
1667 if term > self.current_term {
1668 self.set_term(term, out);
1669 let _ = self.emit_persist_hard(out);
1670 return;
1671 }
1672 if self.role == Role::Candidate
1673 && term == self.current_term
1674 && vote_granted
1675 && self.config_state.latest.is_voter(from)
1676 {
1677 self.votes_received.insert(from);
1678 if self.votes_received.len() >= self.config_state.latest.quorum() {
1679 self.become_leader(out);
1680 }
1681 }
1682 }
1683
1684 fn on_request_prevote(
1685 &self,
1686 from: NodeId,
1687 term: Term,
1688 last_log_index: LogIndex,
1689 last_log_term: Term,
1690 out: &mut Vec<Action>,
1691 ) {
1692 let leader_recent = self.role == Role::Leader
1695 || (self.leader_id.is_some()
1696 && self.last_leader_contact.is_some_and(|t| {
1697 self.now.saturating_sub(t) < self.config.min_election_timeout
1698 }));
1699 let granted = term > self.current_term
1700 && self.log_up_to_date(last_log_term, last_log_index)
1701 && !leader_recent;
1702 out.push(Action::Send {
1703 to: from,
1704 msg: Message::RequestPreVoteResponse {
1705 term: self.current_term,
1706 vote_granted: granted,
1707 },
1708 });
1709 }
1710
1711 fn on_prevote_response(
1712 &mut self,
1713 from: NodeId,
1714 term: Term,
1715 vote_granted: bool,
1716 out: &mut Vec<Action>,
1717 ) {
1718 if term > self.current_term {
1719 self.set_term(term, out);
1720 let _ = self.emit_persist_hard(out);
1721 return;
1722 }
1723 if self.role == Role::PreCandidate
1724 && vote_granted
1725 && self.config_state.latest.is_voter(from)
1726 {
1727 self.prevotes_received.insert(from);
1728 if self.prevotes_received.len() >= self.config_state.latest.quorum() {
1729 self.start_election(out);
1730 }
1731 }
1732 }
1733
1734 fn on_append_below_base(
1739 &mut self,
1740 from: NodeId,
1741 leader_commit: LogIndex,
1742 read_round: u64,
1743 hard_changed: bool,
1744 out: &mut Vec<Action>,
1745 ) {
1746 let new_commit = leader_commit.min(self.log.base_index());
1747 if new_commit > self.commit_index {
1748 self.commit_index = new_commit;
1749 self.emit_applies(out);
1750 }
1751 if read_round > self.last_read_round {
1752 self.last_read_round = read_round;
1753 }
1754 let response = Action::Send {
1755 to: from,
1756 msg: Message::AppendEntriesResponse {
1757 term: self.current_term,
1758 success: true,
1759 match_index: self.log.base_index(),
1760 conflict_index: LogIndex::ZERO,
1761 conflict_term: Term::ZERO,
1762 read_round: self.last_read_round,
1763 },
1764 };
1765 if hard_changed {
1766 let generation = self.emit_persist_hard(out);
1767 self.defer_or_emit(out, response, generation, LogIndex::ZERO);
1768 } else {
1769 out.push(response);
1770 }
1771 }
1772
1773 #[allow(
1774 clippy::too_many_arguments,
1775 reason = "one argument per AppendEntries field keeps the handler aligned with the message layout"
1776 )]
1777 fn on_append_entries(
1778 &mut self,
1779 from: NodeId,
1780 term: Term,
1781 prev_log_index: LogIndex,
1782 prev_log_term: Term,
1783 entries: Vec<LogEntry>,
1784 leader_commit: LogIndex,
1785 read_round: u64,
1786 out: &mut Vec<Action>,
1787 ) {
1788 if term < self.current_term {
1789 out.push(Action::Send {
1790 to: from,
1791 msg: Message::AppendEntriesResponse {
1792 term: self.current_term,
1793 success: false,
1794 match_index: LogIndex::ZERO,
1795 conflict_index: LogIndex::ZERO,
1796 conflict_term: Term::ZERO,
1797 read_round: 0,
1798 },
1799 });
1800 return;
1801 }
1802 let hard_changed = if term > self.current_term {
1803 self.set_term(term, out);
1804 true
1805 } else if self.role == Role::Leader {
1806 out.push(Action::StepDown { term });
1807 self.fail_pending_reads(out);
1808 self.role = Role::Follower;
1809 self.progress.clear();
1810 self.inflight.clear();
1811 self.attached.clear();
1812 self.pending_config = None;
1813 false
1814 } else {
1815 self.role = Role::Follower;
1816 false
1817 };
1818 self.leader_id = Some(from);
1819 self.last_leader_contact = Some(self.now);
1820 self.reset_election_deadline();
1821
1822 if prev_log_index < self.log.base_index() {
1826 self.on_append_below_base(from, leader_commit, read_round, hard_changed, out);
1827 return;
1828 }
1829
1830 let rejection = if prev_log_index > self.log.last_index() {
1832 Some((self.log.last_index().next(), Term::ZERO))
1833 } else if self.log.term_at(prev_log_index) != Some(prev_log_term) {
1834 let conflict_term = self.log.term_at(prev_log_index).unwrap_or(Term::ZERO);
1835 let conflict_index = self
1836 .log
1837 .first_index_of_term(conflict_term)
1838 .unwrap_or(prev_log_index);
1839 Some((conflict_index, conflict_term))
1840 } else {
1841 None
1842 };
1843 if let Some((conflict_index, conflict_term)) = rejection {
1844 let response = Action::Send {
1845 to: from,
1846 msg: Message::AppendEntriesResponse {
1847 term: self.current_term,
1848 success: false,
1849 match_index: LogIndex::ZERO,
1850 conflict_index,
1851 conflict_term,
1852 read_round: 0,
1853 },
1854 };
1855 if hard_changed {
1856 let generation = self.emit_persist_hard(out);
1857 self.defer_or_emit(out, response, generation, LogIndex::ZERO);
1858 } else {
1859 out.push(response);
1860 }
1861 return;
1862 }
1863
1864 let batch_len = entries.len() as u64;
1865 let need_entries = self.merge_and_commit(prev_log_index, entries, leader_commit, out);
1866
1867 if read_round > self.last_read_round {
1871 self.last_read_round = read_round;
1872 }
1873 let matched = LogIndex(prev_log_index.0 + batch_len);
1874 let response = Action::Send {
1875 to: from,
1876 msg: Message::AppendEntriesResponse {
1877 term: self.current_term,
1878 success: true,
1879 match_index: matched,
1880 conflict_index: LogIndex::ZERO,
1881 conflict_term: Term::ZERO,
1882 read_round: self.last_read_round,
1883 },
1884 };
1885 if hard_changed {
1886 let generation = self.emit_persist_hard(out);
1887 self.defer_or_emit(out, response, generation, need_entries);
1888 } else {
1889 self.defer_or_emit(out, response, 0, need_entries);
1890 }
1891 }
1892
1893 fn merge_and_commit(
1898 &mut self,
1899 prev_log_index: LogIndex,
1900 mut entries: Vec<LogEntry>,
1901 leader_commit: LogIndex,
1902 out: &mut Vec<Action>,
1903 ) -> LogIndex {
1904 let batch_len = entries.len() as u64;
1905 let mut changed_from: Option<(LogIndex, usize)> = None;
1908 for (offset, entry) in entries.iter().enumerate() {
1909 let index = LogIndex(prev_log_index.0 + 1 + offset as u64);
1910 match self.log.entry_at(index) {
1911 Some(existing) if existing.term == entry.term => {}
1912 Some(_) => {
1913 self.log.truncate_from(index);
1914 self.entries_durable_up_to =
1915 self.entries_durable_up_to.min(LogIndex(index.0 - 1));
1916 self.stale_entry_acks = self.unacked_entry_persists;
1917 self.log.append(&entries[offset..]);
1918 changed_from = Some((index, offset));
1919 break;
1920 }
1921 None => {
1922 self.log.append(&entries[offset..]);
1923 changed_from = Some((index, offset));
1924 break;
1925 }
1926 }
1927 }
1928 let mut need_entries = LogIndex::ZERO;
1929 if let Some((from_index, offset)) = changed_from {
1930 need_entries = self.log.last_index();
1931 if offset > 0 {
1932 entries.drain(..offset);
1933 }
1934 self.emit_persist_entries(from_index, entries, out);
1935 }
1936 let verified_up_to = LogIndex(prev_log_index.0 + batch_len);
1938 let new_commit = leader_commit.min(verified_up_to);
1939 if new_commit > self.commit_index {
1940 self.commit_index = new_commit;
1941 self.emit_applies(out);
1942 }
1943 self.recompute_config();
1944 need_entries
1945 }
1946
1947 #[allow(
1948 clippy::too_many_arguments,
1949 reason = "one argument per AppendEntriesResponse field keeps the handler aligned with the message layout"
1950 )]
1951 fn on_append_response(
1952 &mut self,
1953 from: NodeId,
1954 term: Term,
1955 success: bool,
1956 match_index: LogIndex,
1957 conflict_index: LogIndex,
1958 conflict_term: Term,
1959 read_round: u64,
1960 out: &mut Vec<Action>,
1961 ) {
1962 if term > self.current_term {
1963 self.set_term(term, out);
1964 let _ = self.emit_persist_hard(out);
1965 return;
1966 }
1967 if self.role != Role::Leader || term < self.current_term {
1968 return;
1969 }
1970 if success {
1971 let mut advance = false;
1972 if let Some(prog) = self.progress.get_mut(&from) {
1973 if match_index > prog.match_index {
1974 prog.match_index = match_index;
1975 advance = true;
1976 }
1977 if prog.next_index < prog.match_index.next() {
1978 prog.next_index = prog.match_index.next();
1979 }
1980 let cap = self.log.last_index().next();
1981 if prog.next_index > cap {
1982 prog.next_index = cap;
1983 }
1984 }
1985 if advance {
1986 self.advance_commit(out);
1987 }
1988 if read_round != 0
1992 && let Some(batch) = &mut self.pending_reads
1993 && batch.round == read_round
1994 && self.config_state.latest.is_voter(from)
1995 {
1996 batch.acks.insert(from);
1997 }
1998 self.try_release_reads(out);
1999 return;
2000 }
2001 if conflict_index == LogIndex::ZERO && conflict_term == Term::ZERO {
2005 return;
2006 }
2007 let candidate = if conflict_term > Term::ZERO {
2008 self.log
2009 .last_index_of_term(conflict_term)
2010 .map_or(conflict_index, LogIndex::next)
2011 } else {
2012 conflict_index
2013 };
2014 let mut retry = false;
2015 if let Some(prog) = self.progress.get_mut(&from) {
2016 let floor = prog.match_index.next();
2017 let cap = self.log.last_index().next();
2018 let new_next = candidate.max(floor).min(cap);
2019 if new_next < prog.next_index {
2020 prog.next_index = new_next;
2021 retry = true;
2022 }
2023 }
2024 if retry {
2025 self.send_append(from, out);
2026 }
2027 }
2028}
2029
2030pub(crate) const fn splitmix64(mut x: u64) -> u64 {
2034 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
2035 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
2036 x ^ (x >> 31)
2037}