openraft 0.10.0

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
//! Raft runtime configuration.

use std::ops::Deref;
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, as well as the conditions which
/// would cause a leader to send an `InstallSnapshot` RPC to a follower based on replication lag.
///
/// 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.
    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.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 heartbeat is only sent when a tick fires, and the tick loop fires every
    /// `heartbeat_interval * 13 / 64` milliseconds, so a heartbeat goes out at the first tick at
    /// or after this interval, up to one tick interval later than it.
    #[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 tick at or after its deadline, so it must hold
    /// that `heartbeat_interval + heartbeat_min_interval` plus one tick 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 tick sends a heartbeat to every follower.
    #[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 per append I/O operation.
    ///
    /// When multiple `AppendEntries` commands are queued, Openraft can merge them into
    /// a single storage write to improve throughput. This setting limits the batch size
    /// to prevent excessively large writes that could cause high storage latency.
    ///
    /// 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>,

    /// The distance behind in log replication a follower must fall before it is considered lagging
    ///
    /// - Followers that fall behind this index are replicated with a snapshot.
    /// - Followers that fall within this index are replicated with log entries.
    ///
    /// This value should be greater than snapshot_policy.SnapshotPolicy.LogsSinceLast, otherwise
    /// transmitting a snapshot may not fix the lagging.
    #[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)
    #[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.
    #[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.
    #[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.
    #[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.
    ///
    /// 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 tick.
    ///
    /// If ticking is disabled, timeout-based events are all disabled:
    /// a follower won't wake up to enter candidate state,
    /// and a leader won't send heartbeat.
    ///
    /// **Critical for elections**: When `false`, followers cannot detect leader failures and will
    /// never trigger elections, even with `enable_elect = true`. The tick mechanism provides the
    /// timing infrastructure that allows followers to detect when `election_timeout_max` has passed
    /// without receiving heartbeats from the leader.
    ///
    /// This flag is mainly used for testing or to build a consensus system that does not depend on
    /// wall clock. The value of this config is evaluated as follows:
    /// - being absent: true
    /// - `--enable-tick`: true
    /// - `--enable-tick=true`: true
    /// - `--enable-tick=false`: false
    // 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_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.
    ///
    /// **Important**: This setting only works when `enable_tick` is also `true`. Elections require
    /// time-based events to detect leader absence.
    // 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>,

    /// The policy for stepping down a Leader that is removed from a committed membership config.
    ///
    /// - [`After(ms)`](StepDownPolicy::After): when the membership config that removes this Leader
    ///   is committed and `ms` milliseconds have elapsed, the Leader transfers leadership to the
    ///   most up-to-date voter, then reverts itself to a learner. During the delay it keeps serving
    ///   as a Leader, so that in-flight requests and the commit notification of the membership log
    ///   entry can still reach the followers.
    /// - [`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.
    /// For instance, in an even number nodes cluster, erasing a node's data and then
    /// rebooting it(log reverts to empty) will not result in data loss.
    ///
    /// For one-shot log reversion, use
    /// [`Raft::trigger().allow_next_revert()`](crate::raft::trigger::Trigger::allow_next_revert).
    #[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,
            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)
    }

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

    /// 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 {
        self.notification_channel_size.unwrap_or(65536) as usize
    }

    /// 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 {
        self.state_machine_channel_size.unwrap_or(1024) as usize
    }

    /// 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 {
        self.log_stage_capacity.unwrap_or(1024) as usize
    }

    /// 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 per 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)
    }

    /// Get the interval in milliseconds at which the tick loop fires.
    ///
    /// A heartbeat is only sent when a tick fires, so every heartbeat deadline is rounded up to
    /// this interval.
    pub(crate) fn tick_interval(&self) -> u64 {
        let interval = self.heartbeat_interval * 13 / 64;
        interval.max(1)
    }

    /// 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,
            });
        }

        // A heartbeat is sent at the first tick at or after its deadline, so heartbeats to a
        // suppressed follower are up to `heartbeat_min_interval + heartbeat_interval` plus one
        // tick interval apart.
        //
        // A `heartbeat_min_interval` of 0 disables suppression and leaves the heartbeat cadence
        // unchanged, so the constraint does not apply to it.
        let heartbeat_min_interval = self.heartbeat_min_interval();
        let suppression_enabled = heartbeat_min_interval > 0;
        let max_heartbeat_gap = heartbeat_min_interval + self.heartbeat_interval + self.tick_interval();

        if suppression_enabled && 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);
        }

        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)
    }

    /// 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())
    }
}