openraft 0.10.2

Advanced Raft consensus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
//! Raft runtime configuration.

use std::ops::Deref;
use std::ops::RangeInclusive;
use std::time::Duration;

use backoff_series::BackoffSeries;
#[cfg(feature = "clap")]
use clap::Parser;
use openraft_macros::since;
use rand::RngExt;

use crate::AsyncRuntime;
use crate::LogId;
use crate::LogIdOptionExt;
use crate::config::StepDownPolicy;
use crate::config::error::ConfigError;
#[cfg(feature = "clap")]
use crate::config::parser::parse_bytes_with_unit;
#[cfg(feature = "clap")]
use crate::config::parser::parse_snapshot_policy;
#[cfg(feature = "clap")]
use crate::config::parser::parse_step_down_policy;
use crate::network::Backoff;
use crate::raft_state::LogStateReader;
use crate::vote::RaftCommittedLeaderId;

/// Default values for [`Config`] fields.
///
/// Shared between the [`Default`] impl and (when enabled) the clap
/// `default_value_t` / `default_value` attributes, so the two stay in sync.
pub(crate) struct Defaults {
    pub cluster_name: &'static str,
    pub election_timeout_min: u64,
    pub election_timeout_max: u64,
    pub heartbeat_interval: u64,
    pub heartbeat_min_interval: u64,
    pub install_snapshot_timeout: u64,
    pub max_payload_entries: u64,
    pub max_append_entries: u64,
    pub replication_lag_threshold: u64,
    pub snapshot_policy: SnapshotPolicy,
    pub snapshot_max_chunk_size: u64,
    pub max_in_snapshot_log_to_keep: u64,
    pub purge_batch_size: u64,
    pub api_channel_size: u64,
    pub api_batch_capacity: u64,
    pub api_batch_linger_ms: u64,
    pub notification_channel_size: u64,
    pub state_machine_channel_size: u64,
    pub backoff: &'static str,
    pub enable_tick: bool,
    pub enable_heartbeat: bool,
    pub enable_elect: bool,
    pub removed_leader_step_down: StepDownPolicy,
    pub quorum_loss_probe_interval: Option<u64>,
    pub enable_pre_vote: Option<bool>,
}

pub(crate) const DEFAULTS: Defaults = Defaults {
    cluster_name: "foo",
    election_timeout_min: 150,
    election_timeout_max: 300,
    heartbeat_interval: 50,
    heartbeat_min_interval: 0,
    install_snapshot_timeout: 200,
    max_payload_entries: 300,
    max_append_entries: 4096,
    replication_lag_threshold: 5000,
    snapshot_policy: SnapshotPolicy::LogsSinceLast(5000),
    snapshot_max_chunk_size: 3 * 1024 * 1024,
    max_in_snapshot_log_to_keep: 1000,
    purge_batch_size: 1,
    api_channel_size: 65536,
    api_batch_capacity: 4096,
    api_batch_linger_ms: 0,
    notification_channel_size: 65536,
    state_machine_channel_size: 1024,
    backoff: "200ms",
    enable_tick: true,
    enable_heartbeat: true,
    enable_elect: true,
    removed_leader_step_down: StepDownPolicy::After(150),
    quorum_loss_probe_interval: None,
    enable_pre_vote: None,
};

/// The serde default for [`Config::removed_leader_step_down`]: it is used when the field is
/// absent, so that config files written before this field existed keep the default behavior.
#[cfg(feature = "serde")]
fn default_removed_leader_step_down() -> StepDownPolicy {
    DEFAULTS.removed_leader_step_down.clone()
}

/// Log compaction and snapshot policy.
///
/// This governs when periodic snapshots will be taken. It does not decide when a leader sends a
/// follower a snapshot instead of log entries: the leader does that when the entries the follower
/// needs are already purged. See [snapshot replication].
///
/// [snapshot replication]: crate::docs::protocol::replication::snapshot_replication
///
/// Additional policies may become available in the future.
#[derive(Clone, Debug)]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum SnapshotPolicy {
    /// A snapshot will be generated once the log has grown the specified number of logs since
    /// the last snapshot.
    ///
    /// The threshold must be at least 1, and validation rejects 0. `LogsSinceLast(1)` attempts a
    /// snapshot once the committed log grows past the last snapshot or attempt; an attempt that
    /// completes or is refused at a committed position is not repeated there. To turn automatic
    /// snapshots off, use [`Never`](Self::Never).
    LogsSinceLast(u64),

    /// Openraft will never trigger a snapshot building.
    /// With this option, the application calls
    /// [`Raft::trigger().snapshot()`](`crate::raft::trigger::Trigger::snapshot`) to manually
    /// trigger a snapshot.
    Never,
}

impl SnapshotPolicy {
    pub(crate) fn should_snapshot<CLID>(
        &self,
        state: &impl Deref<Target = impl LogStateReader<CLID>>,
        last_tried_at: Option<&LogId<CLID>>,
    ) -> Option<LogId<CLID>>
    where
        CLID: RaftCommittedLeaderId,
    {
        match self {
            SnapshotPolicy::LogsSinceLast(threshold) => {
                let committed_next = state.committed().next_index();
                let base_log_id = last_tried_at.max(state.snapshot_last_log_id());

                if committed_next >= base_log_id.next_index().saturating_add(*threshold) {
                    state.committed().cloned()
                } else {
                    None
                }
            }
            SnapshotPolicy::Never => None,
        }
    }
}

/// Runtime configuration for a Raft node.
///
/// `Config` controls tunable parameters for Raft operation including election timeouts, heartbeat
/// intervals, replication settings, snapshot policies, and log compaction behavior.
///
/// # Usage
///
/// Create a configuration, optionally customize fields, validate it, and pass to [`Raft::new`]:
///
/// ```ignore
/// use openraft::Config;
/// use std::sync::Arc;
///
/// let config = Config {
///     cluster_name: "my-cluster".to_string(),
///     heartbeat_interval: 50,
///     election_timeout_min: 150,
///     election_timeout_max: 300,
///     ..Default::default()
/// };
///
/// let config = Arc::new(config.validate()?);
/// let raft = Raft::new(node_id, config, network, log_store, state_machine).await?;
/// ```
///
/// # Timing Constraints
///
/// Follow the Raft timing inequality: `broadcastTime ≪ electionTimeout ≪ MTBF`
///
/// **Rule of thumb**: Set `heartbeat_interval ≈ election_timeout / 3` and ensure election timeout
/// is 10-20× your typical network round-trip time.
///
/// # See Also
///
/// - [Raft specification §5.6](https://raft.github.io/raft.pdf) for timing guidance
/// - [`SnapshotPolicy`] for snapshot triggering strategies
///
/// [`Raft::new`]: crate::Raft::new
#[since(
    version = "0.10.1",
    change = "`enable_tick` no longer stops elections; `enable_elect` controls them"
)]
#[since(version = "0.10.1", change = "add opt-in relaxed leader reads")]
#[since(
    version = "0.10.0",
    change = "made `api_batch_capacity`, `api_batch_linger_ms` and `backoff` optional"
)]
#[since(
    version = "0.10.0",
    change = "removed `send_snapshot_timeout`, deprecated since 0.9.0"
)]
#[since(version = "0.10.0", change = "add opt-in local lease reads")]
#[since(version = "0.10.0", change = "add opt-in unbounded state-machine buffering")]
#[since(version = "0.10.0", change = "added broadcast_submitted_on_append option")]
#[since(version = "0.10.0", change = "added reset_backoff_on_transfer_leader option")]
#[since(version = "0.10.0", change = "added opt-in quorum-loss inactivity setting")]
#[derive(Clone, Debug)]
#[cfg_attr(feature = "clap", derive(Parser))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Config {
    /// The application-specific name of this Raft cluster
    #[cfg_attr(feature = "clap", clap(long, default_value = DEFAULTS.cluster_name))]
    pub cluster_name: String,

    /// The minimum election timeout in milliseconds
    #[cfg_attr(feature = "clap", clap(long, default_value_t = DEFAULTS.election_timeout_min))]
    pub election_timeout_min: u64,

    /// The maximum election timeout in milliseconds
    #[cfg_attr(feature = "clap", clap(long, default_value_t = DEFAULTS.election_timeout_max))]
    pub election_timeout_max: u64,

    /// The heartbeat interval in milliseconds at which leaders will send heartbeats to followers
    ///
    /// A leader's heartbeat timer fires this interval after the previous round of heartbeats, and
    /// the next round goes out then. Replication also uses it as the deadline of an RPC.
    ///
    /// It must be at least 1, and validation rejects 0, even with heartbeats turned off: a runtime
    /// switch can turn them on later. To turn automatic heartbeats off, use
    /// [`enable_heartbeat`](Self::enable_heartbeat) or
    /// [`RuntimeConfigHandle::heartbeat()`](crate::raft::RuntimeConfigHandle::heartbeat).
    #[since(
        version = "0.10.1",
        change = "heartbeats go out at their deadline, not at the next tick"
    )]
    #[cfg_attr(feature = "clap", clap(long, default_value_t = DEFAULTS.heartbeat_interval))]
    pub heartbeat_interval: u64,

    /// The minimum interval in milliseconds between two heartbeats to the same follower.
    ///
    /// A successful replication response proves the same liveness facts as a heartbeat response
    /// and also updates the leader lease clock. When a follower has acknowledged an RPC
    /// (replication or heartbeat) that was sent within the last `heartbeat_min_interval`
    /// milliseconds, the periodic heartbeat to this follower is suppressed, since it would be
    /// redundant. Under sustained writes this eliminates most heartbeat RPCs; heartbeats resume
    /// automatically once replication idles.
    ///
    /// A suppressed heartbeat resumes at the first round of heartbeats after the suppression ends,
    /// so it must hold that `heartbeat_interval + heartbeat_min_interval` is smaller than
    /// `election_timeout_min`, so that suppression can never delay a heartbeat past a follower's
    /// election timeout.
    ///
    /// Defaults to 0, which disables suppression: every round sends a heartbeat to every follower.
    #[since(version = "0.10.1", change = "the bound no longer adds a tick interval")]
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long, default_value = "0"))]
    pub heartbeat_min_interval: Option<u64>,

    /// The timeout for sending then installing a snapshot, in milliseconds.
    #[cfg_attr(feature = "clap", clap(long, default_value_t = DEFAULTS.install_snapshot_timeout))]
    pub install_snapshot_timeout: u64,

    /// The maximum number of entries per payload allowed to be transmitted during replication
    ///
    /// If this is too low, it will take longer for the nodes to be brought up to
    /// consistency with the rest of the cluster.
    #[cfg_attr(feature = "clap", clap(long, default_value_t = DEFAULTS.max_payload_entries))]
    pub max_payload_entries: u64,

    /// The maximum number of log entries that merging puts into one append I/O operation.
    ///
    /// When multiple `AppendEntries` commands are queued, Openraft can merge adjacent ones into a
    /// single storage write to improve throughput. It merges the next command only while the total
    /// stays within this limit, to prevent excessively large writes that could cause high storage
    /// latency.
    ///
    /// It limits merging, not each storage write: a command that already holds more entries, such
    /// as a multi-entry client write, is appended whole. With a limit of 1, a two-entry command is
    /// still one two-entry append.
    ///
    /// This is separate from `max_payload_entries` which controls network replication payload size.
    /// Storage typically has higher throughput than network, so this value can be larger.
    ///
    /// Defaults to 4096.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long, default_value = "4096"))]
    pub max_append_entries: Option<u64>,

    /// How far behind the leader's last log a new learner may be when a blocking
    /// [`Raft::add_learner`](crate::Raft::add_learner) returns.
    ///
    /// With `blocking` set, `add_learner` waits until the learner has replicated the membership log
    /// that adds it, and is at most this many log entries behind the leader's last log.
    ///
    /// It does not decide whether a follower gets log entries or a snapshot. The leader sends a
    /// snapshot when the entries a follower needs are already purged; see
    /// [snapshot replication](crate::docs::protocol::replication::snapshot_replication).
    #[cfg_attr(feature = "clap", clap(long, default_value_t = DEFAULTS.replication_lag_threshold))]
    pub replication_lag_threshold: u64,

    /// The snapshot policy to use for a Raft node.
    #[cfg_attr(feature = "clap", clap(
        long,
        default_value = "since_last:5000",
        value_parser=parse_snapshot_policy
    ))]
    pub snapshot_policy: SnapshotPolicy,

    /// The maximum snapshot chunk size allowed when transmitting snapshots (in bytes)
    ///
    /// It must be at least 1 and at most `isize::MAX`, the largest byte buffer this target can
    /// allocate; validation rejects other values. The default is 3 MiB.
    #[cfg_attr(feature = "clap", clap(long, default_value = "3MiB", value_parser=parse_bytes_with_unit))]
    pub snapshot_max_chunk_size: u64,

    /// The maximum number of logs to keep that are already included in **snapshot**.
    ///
    /// Logs that are not in a snapshot will never be purged.
    #[cfg_attr(feature = "clap", clap(long, default_value_t = DEFAULTS.max_in_snapshot_log_to_keep))]
    pub max_in_snapshot_log_to_keep: u64,

    /// The minimal number of applied logs to purge in a batch.
    #[cfg_attr(feature = "clap", clap(long, default_value_t = DEFAULTS.purge_batch_size))]
    pub purge_batch_size: u64,

    /// The size of the bounded API channel for sending messages to RaftCore.
    ///
    /// This controls backpressure for client requests. When the channel is full,
    /// new API calls will block until space becomes available.
    ///
    /// The runtime's channels must accept the size, as given by
    /// [`Mpsc::buffer_size_range()`](crate::async_runtime::Mpsc::buffer_size_range): the
    /// Tokio-backed runtimes accept 1 to `tokio::sync::Semaphore::MAX_PERMITS`. For a size outside
    /// it, [`Raft::new`](crate::Raft::new) returns [`ConfigError::ChannelSizeOutOfRange`] instead
    /// of starting.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long, default_value = "65536"))]
    pub api_channel_size: Option<u64>,

    /// `RaftMsg::ClientWrite` batch before it is processed.
    /// Then the batched `ClientWrite` requests will be submitted to `RaftStorage` in one shot.
    ///
    /// Defaults to 4096 if not specified.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long, default_value = "4096"))]
    pub api_batch_capacity: Option<u64>,

    /// Maximum amount of milliseconds to wait for additional client requests before
    /// flushing a partially filled batch.
    ///
    /// Defaults to 0 if not specified.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long, default_value = "0"))]
    pub api_batch_linger_ms: Option<u64>,
    /// The size of the bounded notification channel for internal events.
    ///
    /// This channel carries internal notifications like IO completion, replication progress,
    /// and tick events. When full, internal components will block until space is available.
    ///
    /// The runtime's channels must accept the size, as given by
    /// [`Mpsc::buffer_size_range()`](crate::async_runtime::Mpsc::buffer_size_range): the
    /// Tokio-backed runtimes accept 1 to `tokio::sync::Semaphore::MAX_PERMITS`. For a size outside
    /// it, [`Raft::new`](crate::Raft::new) returns [`ConfigError::ChannelSizeOutOfRange`] instead
    /// of starting.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long, default_value = "65536"))]
    pub notification_channel_size: Option<u64>,

    /// The size of the bounded channel for sending commands to the state machine worker.
    ///
    /// This channel carries commands like Apply, BuildSnapshot, and InstallSnapshot.
    /// By default, a full channel applies backpressure to RaftCore while it keeps receiving
    /// notifications. With
    /// [`enable_unbounded_state_machine_buffer`](Self::enable_unbounded_state_machine_buffer),
    /// this setting bounds only the input channel, not the number of pending commands.
    ///
    /// The runtime's channels must accept the size, as given by
    /// [`Mpsc::buffer_size_range()`](crate::async_runtime::Mpsc::buffer_size_range): the
    /// Tokio-backed runtimes accept 1 to `tokio::sync::Semaphore::MAX_PERMITS`. For a size outside
    /// it, [`Raft::new`](crate::Raft::new) returns [`ConfigError::ChannelSizeOutOfRange`] instead
    /// of starting.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long, default_value = "1024"))]
    pub state_machine_channel_size: Option<u64>,

    /// Buffer state-machine commands without a backlog limit in a background receiver task.
    ///
    /// Defaults to `None`, which evaluates to `false`: the bounded worker channel applies
    /// backpressure to RaftCore.
    /// Enabling this lets RaftCore process other requests while the state machine is busy,
    /// at the cost of an extra task handoff and memory growth when commands outpace the worker.
    ///
    /// In a local `benchmarks/minimal` release benchmark on an Apple M3 Max, enabling this
    /// setting changed performance as shown below. The changes compare medians of five
    /// interleaved runs on the same build, using `false` as the baseline. The benchmark used
    /// in-memory storage, no I/O delays, batch size 1, one client thread, and four server threads.
    ///
    /// | Nodes | Clients | Throughput change | Median write latency change |
    /// | --- | --- | --- | --- |
    /// | 1 | 1 | -13.4% | +1.92 µs |
    /// | 3 | 1 | -8.2% | +1.58 µs |
    /// | 1 | 1,024 | +10.2% | -6.75 µs |
    /// | 3 | 1,024 | -3.5% | -1.75 µs |
    ///
    /// These results depend on workload and scheduling; concurrent runs showed wide variation.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub enable_unbounded_state_machine_buffer: Option<bool>,

    /// The capacity of the ring buffer used to track lifecycle latency per stage.
    ///
    /// Each of the 6 lifecycle stages (proposed, received, submitted, persisted,
    /// committed, applied) maintains a fixed-capacity ring buffer of this size.
    /// Only used when the `runtime-stats` feature is enabled.
    ///
    /// Must be greater than 0, and fit in `usize` on this target; validation rejects other
    /// values. Defaults to 1024 if not specified.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long))]
    pub log_stage_capacity: Option<u64>,

    /// Publish submitted logs to replication as soon as [`RaftLogStorage::append`] returns.
    ///
    /// Also yield message draining to ready notifications after at least one Raft message.
    /// Disabled by default because earlier scheduling can reduce batch sizes and throughput.
    ///
    /// [`RaftLogStorage::append`]: crate::storage::RaftLogStorage::append
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub broadcast_submitted_on_append: Option<bool>,

    /// Enable or disable a leader's heartbeat timer.
    ///
    /// If it is disabled, a leader won't send heartbeats on its own.
    ///
    /// Elections do not depend on this timer: they run on a separate election timer that
    /// [`enable_elect`](Self::enable_elect) controls. To stop every automatic election, disable
    /// `enable_elect` as well.
    ///
    /// This flag is mainly used for testing, or to drive the heartbeats of many nodes from one
    /// application timer through [`Trigger::tick`].
    /// The value of this config is evaluated as follows:
    /// - being absent: true
    /// - `--enable-tick`: true
    /// - `--enable-tick=true`: true
    /// - `--enable-tick=false`: false
    ///
    /// [`Trigger::tick`]: crate::raft::trigger::Trigger::tick
    // clap 4 requires `num_args = 0..=1`, or it complains about missing arg error
    // https://github.com/clap-rs/clap/discussions/4374
    #[since(version = "0.10.1", change = "controls the heartbeat timer that replaces the ticker")]
    #[cfg_attr(feature = "clap", clap(long,
           default_value_t = true,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub enable_tick: bool,

    /// Whether a leader sends heartbeat logs to following nodes, i.e., followers and learners.
    // clap 4 requires `num_args = 0..=1`, or it complains about missing arg error
    // https://github.com/clap-rs/clap/discussions/4374
    #[cfg_attr(feature = "clap", clap(long,
           default_value_t = true,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub enable_heartbeat: bool,

    /// Whether a follower will enter candidate state if it does not receive any messages from the
    /// leader for a while.
    ///
    /// When enabled (`true`), followers automatically trigger elections by entering the `Candidate`
    /// state when they don't receive `AppendEntries` messages (heartbeats) from the leader for
    /// longer than `election_timeout_max`. This is essential for automatic failover when a leader
    /// becomes unavailable.
    ///
    /// When disabled (`false`), followers will never initiate elections, even if the leader fails.
    /// This setting is primarily for testing or building custom consensus systems.
    ///
    /// Automatic elections run on their own election timer, which this setting controls whatever
    /// [`enable_tick`](Self::enable_tick) says. It covers a follower's or a learner's election
    /// after its leader lease expires, a candidate's retry, and the election of a leader whose
    /// leadership transfer timed out.
    // clap 4 requires `num_args = 0..=1`, or it complains about missing arg error
    // https://github.com/clap-rs/clap/discussions/4374
    #[cfg_attr(feature = "clap", clap(long,
           default_value_t = true,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub enable_elect: bool,

    /// Whether [`Raft::get_local_read_linearizer`] may use the published leader snapshot.
    ///
    /// `None` (the default) and `Some(false)` make that method use the core path.
    /// `Some(true)` permits caller-side lease checks; cache misses still use the core path.
    /// [`Raft::get_read_linearizer`] and [`Raft::ensure_linearizable`] always use the core path.
    ///
    /// The cache costs work on the leader: with `Some(true)`, RaftCore rebuilds and compares the
    /// snapshot after every notification and command batch, and allocates a new one whenever the
    /// quorum acknowledgement time or the commit index changes.
    ///
    /// [`Raft::get_local_read_linearizer`]: crate::Raft::get_local_read_linearizer
    /// [`Raft::get_read_linearizer`]: crate::Raft::get_read_linearizer
    /// [`Raft::ensure_linearizable`]: crate::Raft::ensure_linearizable
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub enable_local_lease_read: Option<bool>,

    /// Enable relaxed reads requested with [`LinearizerOption::with_relaxed`]. Only `Some(true)`
    /// enables them; `None` is the default. Otherwise a relaxed request gets the standard barrier.
    /// Existing read-barrier APIs are unchanged, and follower reads with the standard barrier from
    /// [`Raft::get_read_linearizer`] remain correct.
    ///
    /// # Optimization
    ///
    /// Standard reads wait for `max(noop_log_id, committed)` to be applied. Relaxed reads wait
    /// only for the current leadership's no-op. This reduces latency when apply lags behind
    /// replication. It cannot bypass query locks or I/O and helps little without an apply backlog.
    ///
    /// Completed writes are already visible to state-machine reads. Previous leaders' committed
    /// entries precede the no-op. Unfinished writes may follow an overlapping read without
    /// violating linearizability. Quorum confirmation and lease assumptions stay unchanged.
    /// [`Self::enable_local_lease_read`] independently enables lease checks outside RaftCore.
    ///
    /// # Replication change
    ///
    /// A leader with this setting sends followers its applied log ID, instead of its committed log
    /// ID, as `leader_commit`: the bound they may apply up to. It sends the bound again whenever
    /// its state machine applies more entries. No node then applies an entry before the leader
    /// does. Otherwise a follower, including a leader that stepped down during a read, could
    /// expose an entry the current leader has not applied, and a later relaxed read would return
    /// older state. Commitment is unchanged; followers only apply later, and their reported
    /// cluster-committed log ID lags the quorum-granted commit.
    ///
    /// This delays followers by about one leader apply plus one round of propagation, and
    /// standard follower reads wait as long. After a failover, the new leader has applied less
    /// as a follower, so it has more entries to apply before its no-op and its first reads wait
    /// longer.
    ///
    /// # Safety requirements
    ///
    /// - Enable this on every node before any node serves relaxed reads. A leader without it lets
    ///   followers apply ahead of it. This setting both bounds followers and lets a leader grant
    ///   relaxed requests, so roll it out in two steps: restart every node with the setting, and
    ///   only then let the application call [`LinearizerOption::with_relaxed`] with `true`.
    /// - A successful write response must mean that later state-machine reads include the write.
    ///   `ApplyResponder::send` can complete `client_write` before `apply()` returns. If the store
    ///   publishes a transaction at the end of `apply()`, delay responses or the client-visible
    ///   acknowledgement until publication.
    ///
    /// See [ReadIndex: Less Latency through Relaxed Ordering] for the rationale and the
    /// [Openraft read protocol] for details.
    ///
    /// [`LinearizerOption::with_relaxed`]: crate::raft::linearizable_read::LinearizerOption::with_relaxed
    /// [`Raft::get_read_linearizer`]: crate::Raft::get_read_linearizer
    /// [ReadIndex: Less Latency through Relaxed Ordering]: https://github.com/drmingdrmer/consensus-essence/blob/main/src/list/raft-read-index-relaxed-order/raft-read-index-relaxed-order.md
    /// [Openraft read protocol]: crate::docs::protocol::read
    #[since(version = "0.10.1")]
    #[cfg_attr(feature = "clap", clap(long,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub enable_relaxed_read: Option<bool>,

    /// The policy for stepping down a Leader that is removed from a committed membership config.
    ///
    /// - [`After(ms)`](StepDownPolicy::After): wait `ms` milliseconds after the membership config
    ///   that removes this Leader is committed. During that delay, the Leader keeps serving so that
    ///   in-flight requests and the membership commit notification can still reach the followers.
    ///   If the node is still a removed Leader after the delay, it attempts to transfer leadership
    ///   to the most up-to-date voter, if one is available. With or without a target, it waits one
    ///   more [`heartbeat_interval`](Self::heartbeat_interval) before requesting a fallback role
    ///   refresh to become a learner. The refresh does nothing if the vote or effective membership
    ///   has changed since the removal was rechecked. `After(0)` skips only the initial delay.
    /// - [`Never`](StepDownPolicy::Never): the removed Leader keeps leading, until the application
    ///   reverts it manually with [`Trigger::refresh_server_state()`].
    ///
    /// In CLI it is either a "never" literal (`never`, `no`, `none`, `off` or `false`,
    /// case-insensitive) or the number of milliseconds, e.g.,
    /// `--removed-leader-step-down=never` or `--removed-leader-step-down=150`.
    ///
    /// Defaults to `After(150)`.
    ///
    /// [`Trigger::refresh_server_state()`]: crate::raft::trigger::Trigger::refresh_server_state
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long, default_value = "150", value_parser = parse_step_down_policy))]
    #[cfg_attr(feature = "serde", serde(default = "default_removed_leader_step_down"))]
    pub removed_leader_step_down: StepDownPolicy,

    /// Duration in milliseconds of each suppression or send phase after quorum loss.
    ///
    /// `None` preserves existing behavior. `Some(R)` starts with a suppression phase after the
    /// Leader lease expires, then alternates suppression and send phases of length `R`. Before the
    /// first quorum acknowledgement, the current Vote's last-modified time is used. A suppression
    /// phase holds back heartbeats, log replication and snapshot transmission.
    ///
    /// `R` must be at least `leader_lease + election_timeout_max`. See
    /// [`CheckQuorum`](crate::docs::protocol::check_quorum).
    #[since(version = "0.10.0", change = "suppress log replication and snapshots too")]
    #[since(version = "0.10.0", change = "added quorum-loss heartbeat phase interval")]
    #[cfg_attr(feature = "clap", clap(long))]
    #[cfg_attr(feature = "serde", serde(default))]
    pub quorum_loss_probe_interval: Option<u64>,

    /// Whether a follower runs a Pre-Vote round before incrementing its term and starting a real
    /// election.
    ///
    /// When enabled (`Some(true)`), a follower whose election timer fires first asks peers whether
    /// they *would* grant it a vote at `term + 1`, without persisting any vote or bumping its term.
    /// Only after a quorum would grant does it run the real election. This prevents a node that
    /// cannot currently win — e.g. one that was partitioned, restarted, or has a stale log — from
    /// inflating its term and disrupting a healthy leader once it reconnects.
    ///
    /// When disabled (`Some(false)`), a follower increments its term and votes for itself
    /// immediately on election timeout, the historical Openraft behavior. The leader-lease already
    /// rejects such a candidate's vote requests, so Pre-Vote is an optional refinement rather than
    /// a correctness requirement.
    ///
    /// `None` (the default) leaves the choice to Openraft, which currently treats it as disabled.
    /// Leaving it unset lets a future release change this default without breaking configs that
    /// never opted in.
    ///
    /// Pre-Vote uses a separate network RPC
    /// ([`RaftNetworkV2::pre_vote`](crate::network::v2::RaftNetworkV2::pre_vote)). A peer whose
    /// network does not implement it is counted as granting the Pre-Vote, so a cluster mid-upgrade
    /// stays live.
    #[since(version = "0.10.0")]
    // clap 4 requires `num_args = 0..=1`, or it complains about missing arg error
    // https://github.com/clap-rs/clap/discussions/4374
    #[cfg_attr(feature = "clap", clap(long,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub enable_pre_vote: Option<bool>,

    /// Default backoff policy used when
    /// [`RaftNetworkV2::backoff`](crate::network::RaftNetworkV2::backoff) returns `None`.
    ///
    /// Defaults to `"200ms"` if not specified.
    ///
    /// The string lists the first few retry delays explicitly. After those, the sequence
    /// continues automatically — smoothly extended from **at most the last three explicit
    /// delays** by either an exponential `k · aˣ + t` or linear `k · x + t` form, whichever
    /// fits the tail. A trailing `..<max>` or `...<max>` caps every extrapolated delay at
    /// `<max>` (defaults to `1000ms`).
    ///
    /// # Syntax
    ///
    /// `<dur>` values separated by `,` or whitespace; an optional `..` or `...` before the
    /// last value marks it as the **max cap**. `<dur>` is a number with a unit suffix:
    /// `ns`, `us`, `ms`, `s`, `m`, `h`.
    ///
    /// # Examples
    ///
    /// **Doubling from a single anchor** — this is the default, `"200ms"`:
    ///
    /// ```text
    /// 200  400  800  1000  1000  1000  …    (ms; cap = 1000)
    /// ```
    ///
    /// **Exponential growth**, `"100ms 200ms 400ms ...5s"`:
    ///
    /// ```text
    /// 100  200  400  800  1600  3200  5000  5000  …    (ms; cap = 5000)
    /// ```
    ///
    /// **Linear growth**, `"1ms 2ms 3ms ...1500ms"` — the tail has constant difference, so the
    /// sequence continues that line until it hits the cap:
    ///
    /// ```text
    /// 1  2  3  4  5  6  …  1499  1500  1500  1500  …    (ms; cap = 1500)
    /// ```
    ///
    /// **Constant delay**, `"500ms 500ms 500ms"` — a flat tail stays flat:
    ///
    /// ```text
    /// 500  500  500  500  …    (ms)
    /// ```
    ///
    /// **Short warm-up, then extrapolate**, `"10ms 20ms ...2s"` — two anchors imply a doubling
    /// rate, extended automatically:
    ///
    /// ```text
    /// 10  20  40  80  160  320  640  1280  2000  2000  …    (ms; cap = 2000)
    /// ```
    ///
    /// Because only the last few explicit delays shape what follows, you can prepend any
    /// number of custom warm-up values without changing the long-run behavior.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long, default_value = DEFAULTS.backoff))]
    pub backoff: Option<String>,

    /// Whether transferring leadership resets the target's active replication backoff.
    ///
    /// `None` (the default) enables the reset. Set this to `Some(false)` to keep the target's
    /// current backoff delay during a leadership transfer.
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub reset_backoff_on_transfer_leader: Option<bool>,

    /// Whether to allow to reset the replication progress to `None`, when the
    /// follower's log is found reverted to an early state. **Do not enable this in production**
    /// unless you know what you are doing.
    ///
    /// Although log state reversion is typically seen as a bug, enabling it can be
    /// useful for testing or other special scenarios. It only lets the replication progress reset:
    /// it adds no quorum-safety check and no recovery, so it does not make erasing a node's data
    /// safe. For the narrow case where erasing one voter cannot lose committed data, see the
    /// [FAQ][wipe-one-node].
    ///
    /// For one-shot log reversion, use
    /// [`Raft::trigger().allow_next_revert()`](crate::raft::trigger::Trigger::allow_next_revert).
    ///
    /// [wipe-one-node]: crate::docs::faq#can-i-wipe-out-the-data-of-one-node-and-wait-for-the-leader-to-replicate-all-data-to-it-again
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub allow_log_reversion: Option<bool>,

    /// Whether a restarted former leader immediately campaigns to regain leadership.
    ///
    /// Enabled by default. A node whose saved vote identifies it as the former leader starts an
    /// election in a higher term if its membership permits campaigning. It becomes leader only
    /// after winning the election quorum. The campaign follows the usual log-freshness and
    /// leader-lease checks, so voters may reject it.
    ///
    /// This startup campaign runs independently of [`enable_tick`](Self::enable_tick) and
    /// [`enable_elect`](Self::enable_elect), without waiting for an election timeout. When disabled
    /// (`false`), the former leader starts as a follower or learner and follows normal election
    /// timing. The setting leaves follower, learner, and unfinished-candidate startup unchanged.
    ///
    /// The higher term prevents reuse of a log ID for different entries if the old leader
    /// replicated an entry but crashed before its local flush. Winning the election appends a
    /// blank entry in the new term, increasing the log index before the next client write. See
    /// [issue #2167](https://github.com/databendlabs/openraft/issues/2167) and
    /// [PR #2172](https://github.com/databendlabs/openraft/pull/2172).
    /// [`RaftLogStorage::append`] may still return before local persistence completes; its
    /// completion callback reports durability.
    ///
    /// **State-machine recovery**: If [`RaftStateMachine::apply`] does not flush state and the last
    /// committed log ID is not persisted, restart may restore an older state machine. Persist the
    /// committed log ID through [`RaftLogStorage::save_committed`], or call
    /// [`Raft::wait_for_recovery`] before serving reads. See [`docs::data::log_pointers`].
    ///
    /// [`Raft::wait_for_recovery`]: `crate::Raft::wait_for_recovery`
    /// [`RaftLogStorage::append`]: `crate::storage::RaftLogStorage::append`
    /// [`RaftLogStorage::save_committed`]: `crate::storage::RaftLogStorage::save_committed`
    /// [`RaftStateMachine::apply`]: `crate::storage::RaftStateMachine::apply`
    /// [`docs::data::log_pointers`]: `crate::docs::data::log_pointers#optionally-persisted-committed`
    // clap 4 requires `num_args = 0..=1`, or it complains about missing arg error
    // https://github.com/clap-rs/clap/discussions/4374
    #[since(version = "0.10.0", change = "restore leadership through a higher-term election")]
    #[since(version = "0.10.0")]
    #[cfg_attr(feature = "clap", clap(long,
           action = clap::ArgAction::Set,
           num_args = 0..=1,
           default_missing_value = "true"
    ))]
    pub enable_leader_restore: Option<bool>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            cluster_name: DEFAULTS.cluster_name.to_string(),
            election_timeout_min: DEFAULTS.election_timeout_min,
            election_timeout_max: DEFAULTS.election_timeout_max,
            heartbeat_interval: DEFAULTS.heartbeat_interval,
            heartbeat_min_interval: Some(DEFAULTS.heartbeat_min_interval),
            install_snapshot_timeout: DEFAULTS.install_snapshot_timeout,
            max_payload_entries: DEFAULTS.max_payload_entries,
            max_append_entries: Some(DEFAULTS.max_append_entries),
            replication_lag_threshold: DEFAULTS.replication_lag_threshold,
            snapshot_policy: DEFAULTS.snapshot_policy.clone(),
            snapshot_max_chunk_size: DEFAULTS.snapshot_max_chunk_size,
            max_in_snapshot_log_to_keep: DEFAULTS.max_in_snapshot_log_to_keep,
            purge_batch_size: DEFAULTS.purge_batch_size,
            api_channel_size: Some(DEFAULTS.api_channel_size),
            api_batch_capacity: Some(DEFAULTS.api_batch_capacity),
            api_batch_linger_ms: Some(DEFAULTS.api_batch_linger_ms),
            notification_channel_size: Some(DEFAULTS.notification_channel_size),
            state_machine_channel_size: Some(DEFAULTS.state_machine_channel_size),
            enable_unbounded_state_machine_buffer: None,
            log_stage_capacity: None,
            broadcast_submitted_on_append: None,
            enable_tick: DEFAULTS.enable_tick,
            enable_heartbeat: DEFAULTS.enable_heartbeat,
            enable_elect: DEFAULTS.enable_elect,
            enable_local_lease_read: None,
            enable_relaxed_read: None,
            removed_leader_step_down: DEFAULTS.removed_leader_step_down.clone(),
            quorum_loss_probe_interval: DEFAULTS.quorum_loss_probe_interval,
            enable_pre_vote: DEFAULTS.enable_pre_vote,
            backoff: Some(DEFAULTS.backoff.to_string()),
            reset_backoff_on_transfer_leader: None,
            allow_log_reversion: None,
            enable_leader_restore: None,
        }
    }
}

impl Config {
    /// Generate a new random election timeout within the configured min and max values.
    pub fn new_rand_election_timeout<RT: AsyncRuntime>(&self) -> u64 {
        RT::thread_rng().random_range(self.election_timeout_min..self.election_timeout_max)
    }

    /// Get the timeout for sending and installing the last snapshot segment.
    pub fn install_snapshot_timeout(&self) -> Duration {
        Duration::from_millis(self.install_snapshot_timeout)
    }

    /// Whether to allow the replication to reset the state to `None` when a log state reversion is
    /// detected.
    ///
    /// By default, it does not allow log reversion, because it might indicate a bug in the system.
    #[since(version = "0.10.0")]
    pub(crate) fn get_allow_log_reversion(&self) -> bool {
        self.allow_log_reversion.unwrap_or(false)
    }

    /// Whether a former leader starts a higher-term election immediately after restart.
    ///
    /// Enabled by default; leadership still requires election quorum approval.
    #[since(version = "0.10.0")]
    pub(crate) fn enable_leader_restore(&self) -> bool {
        self.enable_leader_restore.unwrap_or(true)
    }

    /// Whether a leadership transfer resets the target's active replication backoff.
    pub(crate) fn get_reset_backoff_on_transfer_leader(&self) -> bool {
        self.reset_backoff_on_transfer_leader.unwrap_or(true)
    }

    /// Whether a follower runs a Pre-Vote round before starting a real election.
    ///
    /// Evaluates the [`enable_pre_vote`](Self::enable_pre_vote) option: `None` is treated as
    /// disabled (`false`), the current default.
    pub(crate) fn get_enable_pre_vote(&self) -> bool {
        self.enable_pre_vote.unwrap_or(false)
    }

    /// Whether to enable caller-side lease reads from the published leader state.
    pub(crate) fn get_enable_local_lease_read(&self) -> bool {
        self.enable_local_lease_read.unwrap_or(false)
    }

    /// Whether to permit local reads using the current leadership's no-op barrier.
    pub(crate) fn get_enable_relaxed_read(&self) -> bool {
        self.enable_relaxed_read.unwrap_or(false)
    }

    /// Get the API channel size for bounded MPSC channel.
    ///
    /// Defaults to 65536 if not specified.
    pub(crate) fn api_channel_size(&self) -> usize {
        saturating_usize(self.api_channel_size.unwrap_or(65536))
    }

    /// Get the maximum number of client writes that RaftCore merges into one batch.
    ///
    /// Defaults to 4096 if not specified.
    pub(crate) fn api_batch_capacity(&self) -> u64 {
        self.api_batch_capacity.unwrap_or(DEFAULTS.api_batch_capacity)
    }

    /// Get the milliseconds to wait for more client writes before processing a partial batch.
    ///
    /// Defaults to 0 if not specified.
    pub(crate) fn api_batch_linger_ms(&self) -> u64 {
        self.api_batch_linger_ms.unwrap_or(DEFAULTS.api_batch_linger_ms)
    }

    /// Get the default backoff policy string.
    ///
    /// Defaults to `"200ms"` if not specified.
    pub(crate) fn get_backoff(&self) -> &str {
        self.backoff.as_deref().unwrap_or(DEFAULTS.backoff)
    }

    /// Get the notification channel size for bounded MPSC channel.
    ///
    /// Defaults to 65536 if not specified.
    pub(crate) fn notification_channel_size(&self) -> usize {
        saturating_usize(self.notification_channel_size.unwrap_or(65536))
    }

    /// Get the state machine command channel size for bounded MPSC channel.
    ///
    /// Defaults to 1024 if not specified.
    pub(crate) fn state_machine_channel_size(&self) -> usize {
        saturating_usize(self.state_machine_channel_size.unwrap_or(1024))
    }

    /// Whether to buffer state-machine commands without a backlog limit; defaults to `false`.
    pub(crate) fn enable_unbounded_state_machine_buffer(&self) -> bool {
        self.enable_unbounded_state_machine_buffer.unwrap_or(false)
    }

    /// Get the lifecycle latency ring buffer capacity per stage.
    ///
    /// Defaults to 1024 if not specified.
    pub(crate) fn log_stage_capacity(&self) -> usize {
        saturating_usize(self.log_stage_capacity.unwrap_or(1024))
    }

    /// Whether to publish submitted logs after each append; defaults to `false`.
    pub(crate) fn broadcast_submitted_on_append(&self) -> bool {
        self.broadcast_submitted_on_append.unwrap_or(false)
    }

    /// Get the maximum number of log entries that merging puts into one append I/O operation.
    ///
    /// Defaults to 4096 if not specified.
    pub(crate) fn max_append_entries(&self) -> u64 {
        self.max_append_entries.unwrap_or(4096)
    }

    /// Get the minimum interval in milliseconds between two heartbeats to the same follower.
    ///
    /// Defaults to 0 if not specified, meaning heartbeat suppression is disabled.
    pub(crate) fn heartbeat_min_interval(&self) -> u64 {
        self.heartbeat_min_interval.unwrap_or(0)
    }

    /// Validate the state of this config.
    pub fn validate(self) -> Result<Config, ConfigError> {
        if self.election_timeout_min >= self.election_timeout_max {
            return Err(ConfigError::ElectionTimeout {
                min: self.election_timeout_min,
                max: self.election_timeout_max,
            });
        }

        if self.election_timeout_min <= self.heartbeat_interval {
            return Err(ConfigError::ElectionTimeoutLTHeartBeat {
                election_timeout_min: self.election_timeout_min,
                heartbeat_interval: self.heartbeat_interval,
            });
        }

        // An interval of 0 would make the heartbeat timer due at once after every round, and give
        // replication RPCs a deadline of 0.
        if self.heartbeat_interval == 0 {
            return Err(ConfigError::HeartbeatIntervalIs0);
        }

        // A round of heartbeats goes out every `heartbeat_interval`, so heartbeats to a suppressed
        // follower are up to `heartbeat_min_interval + heartbeat_interval` apart.
        //
        // A `heartbeat_min_interval` of 0 disables suppression and leaves the heartbeat cadence
        // unchanged, so the constraint does not apply to it.
        //
        // Widen both operands before addition so the sum cannot overflow.
        let heartbeat_min_interval = self.heartbeat_min_interval();
        let suppression_enabled = heartbeat_min_interval > 0;
        let max_heartbeat_gap = u128::from(heartbeat_min_interval) + u128::from(self.heartbeat_interval);

        if suppression_enabled && u128::from(self.election_timeout_min) <= max_heartbeat_gap {
            return Err(ConfigError::HeartbeatMinIntervalTooLarge {
                election_timeout_min: self.election_timeout_min,
                heartbeat_interval: self.heartbeat_interval,
                heartbeat_min_interval,
            });
        }

        if self.max_payload_entries == 0 {
            return Err(ConfigError::MaxPayloadIs0);
        }

        // A threshold of 0 would start another build at the same committed position each time the
        // previous one completes or is refused.
        if self.snapshot_policy == SnapshotPolicy::LogsSinceLast(0) {
            return Err(ConfigError::SnapshotLogsSinceLastIs0);
        }

        // A transport reads each chunk into a byte buffer, whose capacity is at most `isize::MAX`.
        // A chunk size of 0 would send empty chunks that never finish the snapshot.
        if self.snapshot_max_chunk_size == 0 {
            return Err(ConfigError::SnapshotMaxChunkSizeIs0);
        }
        let max_chunk_size = u64::try_from(isize::MAX).unwrap_or(u64::MAX);
        check_fits("snapshot_max_chunk_size", self.snapshot_max_chunk_size, max_chunk_size)?;

        if self.log_stage_capacity == Some(0) {
            return Err(ConfigError::LogStageCapacityIs0);
        }

        // A capacity that does not fit `usize` would be truncated, on a 32-bit target possibly to
        // 0, which the zero check above would then miss.
        if let Some(capacity) = self.log_stage_capacity {
            let max_usize = u64::try_from(usize::MAX).unwrap_or(u64::MAX);
            check_fits("log_stage_capacity", capacity, max_usize)?;
        }

        // A channel size that does not fit `usize` would be truncated, possibly to 0. Whether the
        // runtime's channels accept a size is checked by `validate_channel_sizes()`, which
        // `Raft::new` runs before it builds any channel.
        let max_usize = u64::try_from(usize::MAX).unwrap_or(u64::MAX);
        for (field, size) in [
            ("api_channel_size", self.api_channel_size),
            ("notification_channel_size", self.notification_channel_size),
            ("state_machine_channel_size", self.state_machine_channel_size),
        ] {
            if let Some(size) = size {
                check_fits(field, size, max_usize)?;
            }
        }

        if let Some(probe_interval) = self.quorum_loss_probe_interval {
            // The Leader lease currently uses election_timeout_max. Leave time for that lease
            // to expire, then for one maximum election timeout before allowing heartbeats again.
            // Widen both operands before addition so the sum cannot overflow.
            let leader_lease = self.election_timeout_max;
            let min_probe_interval = u128::from(leader_lease) + u128::from(self.election_timeout_max);
            if u128::from(probe_interval) < min_probe_interval {
                return Err(ConfigError::QuorumLossProbeIntervalTooSmall {
                    election_timeout_max: self.election_timeout_max,
                    probe_interval,
                });
            }
        }

        // Validate the backoff policy string up-front so build_backoff() can assume it parses.
        BackoffSeries::parse(self.get_backoff())?;

        Ok(self)
    }

    /// Checks that the runtime's channels accept every channel size, given the sizes they
    /// accept, [`Mpsc::buffer_size_range()`](crate::async_runtime::Mpsc::buffer_size_range).
    ///
    /// [`validate()`](Self::validate) cannot check this, because a `Config` does not know the
    /// runtime. `Raft::new` runs it before it builds any channel, because `channel()` panics on a
    /// size outside the range.
    pub(crate) fn validate_channel_sizes(&self, accepted: RangeInclusive<usize>) -> Result<(), ConfigError> {
        for (field, size) in [
            ("api_channel_size", self.api_channel_size()),
            ("notification_channel_size", self.notification_channel_size()),
            ("state_machine_channel_size", self.state_machine_channel_size()),
        ] {
            if !accepted.contains(&size) {
                return Err(ConfigError::ChannelSizeOutOfRange { field, size, accepted });
            }
        }
        Ok(())
    }

    /// Build a [`Backoff`] iterator from the [`backoff`](Self::backoff) policy string.
    ///
    /// Panics if the policy is invalid — callers should obtain `Config` through [`Config::build`]
    /// or [`Config::validate`], which reject invalid policies up-front.
    #[since(version = "0.10.0")]
    pub fn build_backoff(&self) -> Backoff {
        let series =
            BackoffSeries::parse(self.get_backoff()).expect("backoff policy must be validated by Config::validate");
        Backoff::new(series.build())
    }
}

/// Returns [`ConfigError::TooLarge`] when `value` is greater than `max`, the largest value that
/// this target accepts for the setting `field`.
pub(super) fn check_fits(field: &'static str, value: u64, max: u64) -> Result<(), ConfigError> {
    if value > max {
        return Err(ConfigError::TooLarge { field, value, max });
    }
    Ok(())
}

/// Converts a size setting to `usize`, saturating at `usize::MAX`.
///
/// Validation rejects a size that does not fit. An unvalidated one saturates rather than wraps,
/// so that a runtime that cannot build a channel that large rejects it, instead of building a
/// smaller one.
fn saturating_usize(value: u64) -> usize {
    usize::try_from(value).unwrap_or(usize::MAX)
}