kividb 1.2.2

A fast Redis®-compatible in-memory store written in Rust
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
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
// src/cluster/bus/heartbeat.rs
//
// The cluster's periodic work: heartbeats, failure detection, elections, and
// keeping the replication client pointed where the cluster says it should be.
//
// Every HEARTBEAT_INTERVAL we walk every known peer and send them a PING. The
// PING carries gossip and our slot claims; the receiver merges both into its
// routing table.
//
// Why every peer every tick rather than a sample: in small clusters
// (2-10 nodes) the bandwidth is negligible (~2 KiB per ping), and
// pinging every peer keeps the failure-detection signal (ping_sent_ms /
// pong_received_ms) fresh on every node.

use crate::cluster::ClusterState;
use crate::cluster::bus::BusMessage;
use crate::cluster::bus::dialer;
use crate::cluster::node::{NodeFlags, NodeId, node_id_str};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;

pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);

/// Run the heartbeat loop forever. Spawned once at startup if cluster
/// mode is enabled.
pub async fn run_heartbeat_loop(state: Arc<ClusterState>) {
    log_info!("Cluster: Heartbeat loop started (interval {HEARTBEAT_INTERVAL:?})");
    let mut ticker = tokio::time::interval(HEARTBEAT_INTERVAL);
    // Skip the immediate first tick — give the bus listener a moment to bind.
    ticker.tick().await;

    loop {
        ticker.tick().await;
        send_one_round(&state).await;
    }
}

/// PING every peer once.
///
/// Failed nodes are pinged too. They used to be skipped, on the reasoning
/// that there was no point — but a node only stops being FAIL when it is
/// heard from, and a node that restarted without its nodes.conf, or whose
/// only route back is our reaching out, was never heard from again.
pub(crate) async fn send_one_round(state: &Arc<ClusterState>) {
    if test_bus_muted() {
        return;
    }
    // Snapshot the peer list so we don't hold the lock during async I/O.
    let peers: Vec<(NodeId, String, u16)> = {
        let nodes = state.nodes.read();
        nodes
            .values()
            .filter(|n| {
                n.id != state.myself()
                    // Skip handshake-only entries — we don't know their real
                    // id yet, and the dialer task is already mid-conversation.
                    && !n.flags.contains(NodeFlags::HANDSHAKE)
                    && !n.ip.is_empty()
                    && n.cluster_port != 0
            })
            .map(|n| (n.id, n.ip.clone(), n.cluster_port))
            .collect()
    };

    let pinged: Vec<String> = peers
        .iter()
        .map(|(_, ip, port)| format!("{ip}:{port}"))
        .collect();
    dialer::prune_ping_links(state, &pinged);
    for (peer_id, ip, bus_port) in peers {
        let state = Arc::clone(state);
        tokio::spawn(async move {
            if let Err(e) = dialer::send_ping(state, ip.clone(), bus_port).await {
                // Only log if this isn't a routine "connection refused" from
                // a peer that's between heartbeats and being marked PFAIL.
                // The failure-detection loop is the canonical place to learn
                // a peer is down — heartbeat errors are just symptoms.
                if !e.contains("refused") && !e.contains("timed out") {
                    log_verbose!(
                        "Cluster: Heartbeat to {} ({ip}:{bus_port}) failed: {e}",
                        node_id_str(&peer_id)
                    );
                }
            }
        });
    }
}

pub const FAILURE_DETECTION_INTERVAL: Duration = Duration::from_millis(100);

/// When the failure-detection loop last began a tick (Unix ms; 0 before the
/// first). It runs every 100 ms on the bus thread, so a time long past means
/// the bus is stuck. See [`spawn_bus_watchdog`].
static BUS_TICKED_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// How long the bus may go without a tick before the watchdog says so.
const BUS_STALL_WARN: Duration = Duration::from_secs(10);

/// Log when the bus has stopped running, and when it runs again. A bus
/// stuck on a lock answers no peer and is failed over, and everything on
/// the node that reads the topology waits with it; nothing else said so in
/// the log. A thread of its own, so that it is not stuck with the bus.
pub(crate) fn spawn_bus_watchdog() {
    let spawned = std::thread::Builder::new()
        .name("kividb-bus-watch".into())
        .spawn(|| {
            let mut stalled = false;
            loop {
                std::thread::sleep(Duration::from_secs(1));
                let ticked = BUS_TICKED_MS.load(Ordering::Relaxed);
                if ticked == 0 {
                    continue;
                }
                let silent = now_ms_local().saturating_sub(ticked);
                if !stalled && silent > BUS_STALL_WARN.as_millis() as u64 {
                    stalled = true;
                    log_warn!(
                        "Cluster: The cluster bus has not run for {} s: this node is not \
                         heartbeating, and commands that read the cluster topology may not \
                         be answered",
                        silent / 1000
                    );
                } else if stalled && silent < 1_000 {
                    stalled = false;
                    log_warn!("Cluster: The cluster bus is running again");
                }
            }
        });
    if let Err(e) = spawned {
        log_warn!("Cluster: could not start the bus watchdog: {e}");
    }
}

/// Periodic task that checks for stale peers (no PONG in node_timeout_ms)
/// and applies PFAIL / FAIL flags. Runs ~10x per second so failures are
/// detected promptly once the timeout window has elapsed.
pub async fn run_failure_detection_loop(
    state: Arc<ClusterState>,
    repl_state: Arc<crate::replication::ReplState>,
) {
    log_info!(
        "Cluster: Failure detection started (interval {FAILURE_DETECTION_INTERVAL:?}, node_timeout {}ms)",
        state.node_timeout_ms
    );
    let mut ticker = tokio::time::interval(FAILURE_DETECTION_INTERVAL);
    ticker.tick().await;
    loop {
        ticker.tick().await;
        apply_test_bus_control();
        BUS_TICKED_MS.store(now_ms_local(), Ordering::Relaxed);
        let newly_failed = state.run_failure_detection_tick();
        for id in newly_failed {
            log_warn!("Cluster: Node {} marked FAIL by quorum", node_id_str(&id));
            // Tell everyone now. Replicas of the failed master start their
            // election on this; left to gossip they would wait for the
            // verdict to reach them a few random entries at a time.
            broadcast(
                &state,
                &BusMessage::Fail {
                    sender_id: state.myself(),
                    failed_id: id,
                },
                |_| true,
            );
        }
        state.check_lost_dataset_fence();
        check_election(&state, &repl_state).await;
        check_held_writes(&state);
        state.reconcile_replication();
    }
}

/// Queue `msg` for every member that `wanted` selects, over the long-lived
/// links. Fire-and-forget.
pub(crate) fn broadcast(
    state: &Arc<ClusterState>,
    msg: &BusMessage,
    wanted: impl Fn(&crate::cluster::ClusterNode) -> bool,
) {
    if test_bus_muted() {
        return;
    }
    let me = state.myself();
    let targets: Vec<String> = state
        .nodes
        .read()
        .values()
        .filter(|n| {
            n.id != me
                && !n.flags.contains(NodeFlags::HANDSHAKE)
                && !n.ip.is_empty()
                && n.cluster_port != 0
                && wanted(n)
        })
        .map(|n| format!("{}:{}", n.ip, n.cluster_port))
        .collect();
    if targets.is_empty() {
        return;
    }
    let frame = crate::cluster::bus::message::encode(msg);
    for addr in targets {
        dialer::send_frame(state, &addr, frame.clone());
    }
}

/// Forward a `PUBLISH` (or `SPUBLISH`) issued on this node to the rest of the
/// cluster, so subscribers connected to other nodes receive it.
///
/// A plain channel goes to every node. A shard channel goes only to the nodes
/// serving its slot — the owner and that owner's replicas.
pub fn forward_publish(state: &Arc<ClusterState>, channel: &[u8], payload: &[u8], sharded: bool) {
    if !state.enabled {
        return;
    }
    let msg = BusMessage::Publish {
        sender_id: state.myself(),
        channel: channel.to_vec(),
        payload: payload.to_vec(),
        sharded,
    };
    if sharded {
        let owner = state.slot_owner(crate::cluster::key_hash_slot(channel));
        broadcast(state, &msg, |n| {
            owner.is_some_and(|o| n.id == o || n.master_id == Some(o))
        });
    } else {
        // A failed node is not listening; do not queue for it.
        broadcast(state, &msg, |n| !n.flags.contains(NodeFlags::FAIL));
    }
}

/// Check if we should run for election (we're a replica and our master is FAIL).
/// If we should, drive the election state machine through one tick.
async fn check_election(
    state: &Arc<ClusterState>,
    repl_state: &Arc<crate::replication::ReplState>,
) {
    if !state.enabled {
        return;
    }

    // Are we a replica? What's our master?
    let (im_replica, master_id) = {
        let nodes = state.nodes.read();
        match nodes.get(&state.myself()) {
            Some(me) => (me.flags.contains(NodeFlags::REPLICA), me.master_id),
            None => (false, None),
        }
    };
    if !im_replica {
        return;
    }
    let master_id = match master_id {
        Some(id) => id,
        None => return,
    };

    // Is our master FAIL'd?
    let master_failed = {
        let nodes = state.nodes.read();
        nodes
            .get(&master_id)
            .map(|m| m.flags.contains(NodeFlags::FAIL))
            .unwrap_or(false)
    };

    let active_election = state.election.lock().clone();

    match (master_failed, active_election) {
        // Master alive, no election running — nothing to do.
        (false, None) => (),

        // Master alive and an election is running. An automatic one is stale —
        // the master came back — so abandon it. A manual one is the whole
        // point: the master is healthy and is being replaced deliberately.
        // This used to abandon both, on the next tick, so `CLUSTER FAILOVER`
        // against a healthy master never completed.
        (false, Some(election)) if !election.manual => {
            state.end_election();
        }

        // Master FAIL'd, no election yet — start one (after delay).
        (true, None) => {
            // A replica whose data is too old does not stand: it would win
            // the slots and lose whatever it never received (#107).
            if let Some(why) = too_stale_to_stand(state, repl_state) {
                let now = now_ms_local();
                if now.saturating_sub(LAST_STALE_LOG_MS.swap(now, Ordering::Relaxed)) >= 10_000 {
                    log_warn!(
                        "Cluster: Not standing for election for failed master {}: {why}",
                        node_id_str(&master_id)
                    );
                }
                return;
            }
            // Make sure we don't kick off concurrent election attempts.
            if state
                .election_pending
                .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
                .is_err()
            {
                return; // Another tick is already in the delay phase.
            }

            // The delay is spent in a task of its own: this loop also detects
            // failures and keeps replication pointed right, every 100 ms, and
            // a ranked delay can be seconds.
            let state = Arc::clone(state);
            let repl_state = Arc::clone(repl_state);
            tokio::spawn(async move {
                // The replicas that have read further go first, a second
                // apart, as in Redis: so the most up-to-date one normally
                // wins, and the others' writes are not lost to it (#107).
                let rank = replica_rank(&state, &repl_state, master_id).await;
                let delay_ms = 500 + (rand_u32() % 500) as u64 + 1000 * rank;
                if rank > 0 {
                    log_info!(
                        "Cluster: {rank} replica(s) of failed master {} have read further; \
                         standing for election in {delay_ms} ms",
                        node_id_str(&master_id)
                    );
                }
                tokio::time::sleep(Duration::from_millis(delay_ms)).await;

                // Re-check: still a replica of that master, it is still FAIL,
                // and no other replica has taken over meanwhile.
                let still_failed = {
                    let nodes = state.nodes.read();
                    let still_its_replica = nodes
                        .get(&state.myself())
                        .is_some_and(|me| me.master_id == Some(master_id));
                    still_its_replica
                        && nodes
                            .get(&master_id)
                            .map(|m| m.flags.contains(NodeFlags::FAIL))
                            .unwrap_or(false)
                };
                if !still_failed {
                    state.election_pending.store(false, Ordering::SeqCst);
                    return;
                }
                // And still fit to stand: a full sync may have begun in the
                // delay.
                if let Some(why) = too_stale_to_stand(&state, &repl_state) {
                    log_warn!(
                        "Cluster: Not standing for election for failed master {}: {why}",
                        node_id_str(&master_id)
                    );
                    state.election_pending.store(false, Ordering::SeqCst);
                    return;
                }

                let epoch = state.start_election(master_id, false, None);
                state.election_pending.store(false, Ordering::SeqCst);
                log_warn!(
                    "Cluster: Starting election for epoch {epoch} (failed master: {})",
                    node_id_str(&master_id)
                );
                broadcast_auth_request(&state, master_id, epoch, false).await;
            });
        }

        // Election running — check progress.
        (_, Some(election)) => {
            if election.completed {
                return;
            }
            let quorum = state.election_quorum(master_id);
            // A manual failover is won while the master still holds writes
            // for it, or not at all. Won later, the master has been taking
            // writes again, and those it acknowledged between our promotion
            // and its hearing of it are lost (#185). Given up, the master
            // holds writes until it has made sure it still owns its slots
            // (#242).
            if let Some(deadline) = election.deadline_ms
                && now_ms_local() >= deadline
            {
                log_warn!(
                    "Cluster: Manual failover abandoned: the election at epoch {} was not won \
                     in time ({} of {} votes)",
                    election.epoch,
                    election.votes_received.len(),
                    quorum
                );
                state.end_election();
                return;
            }
            if election.votes_received.len() >= quorum {
                log_info!(
                    "Cluster: Won election at epoch {} ({} votes, quorum {})",
                    election.epoch,
                    election.votes_received.len(),
                    quorum
                );
                promote(state, repl_state, master_id, election.epoch).await;
                return;
            }
            // Election timeout: 10 seconds. After that, abandon and re-start
            // next tick if master is still FAIL.
            let now = now_ms_local();
            if now.saturating_sub(election.started_at_ms)
                > crate::cluster::ELECTION_LIFETIME.as_millis() as u64
            {
                log_warn!(
                    "Cluster: Election at epoch {} timed out with {} of {} votes — abandoning",
                    election.epoch,
                    election.votes_received.len(),
                    quorum
                );
                state.end_election();
            }
        }
    }
}

/// When a too-stale replica last said it would not stand (logged at most
/// every 10 s; the check runs every 100 ms).
static LAST_STALE_LOG_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Why this replica may not stand for election, if it may not; see
/// [`stand_refusal`].
fn too_stale_to_stand(
    state: &ClusterState,
    repl_state: &crate::replication::ReplState,
) -> Option<String> {
    stand_refusal(
        repl_state.full_sync_unfinished.load(Ordering::SeqCst),
        repl_state.in_step_ms.load(Ordering::Relaxed),
        now_ms_local(),
        state.node_timeout_ms,
        repl_state.repl_ping_period_secs.load(Ordering::Relaxed) * 1000,
        state.replica_validity_factor(),
    )
}

/// Why a replica may not stand for election to replace its failed master,
/// if it may not.
///
/// * It is in a full sync: from the `+FULLRESYNC` until it has loaded the
///   dataset and streamed since (`full_sync_unfinished`). Meanwhile it may
///   hold part of the master's dataset or, with the default
///   `repl-diskless-load`, none of it. Whatever the validity factor: it
///   would take the slots and lose everything it does not have.
/// * Its data is too old (Redis's rule): older than
///   `node timeout × cluster-replica-validity-factor + repl-ping-replica-period`.
///   Its age counts from `in_step_ms`, the last moment it was streaming
///   with all the master had sent applied, not from the last time its link
///   came up: a replica whose full sync starts over and over has its link
///   come up after each load and is never caught up. 0, never since it
///   started, is too old. A factor of 0 lets it stand whatever its age.
fn stand_refusal(
    full_sync_unfinished: bool,
    in_step_ms: u64,
    now_ms: u64,
    node_timeout_ms: u64,
    ping_period_ms: u64,
    factor: u64,
) -> Option<String> {
    if full_sync_unfinished {
        return Some(
            "it has not finished loading its last full sync from the master and streamed since: \
             it may hold part of the master's data, or none of it"
                .to_string(),
        );
    }
    if factor == 0 {
        return None;
    }
    if in_step_ms == 0 {
        return Some(format!(
            "it has not been in step with its master since it started, so the age of its data \
             is not known (cluster-replica-validity-factor {factor}; 0 lets it stand)"
        ));
    }
    let age = now_ms.saturating_sub(in_step_ms);
    data_too_old(age, node_timeout_ms, ping_period_ms, factor).map(|(age, limit)| {
        format!(
            "its data is {} s old, counted from when it was last in step with its master, more \
             than the {} s cluster-replica-validity-factor {factor} allows",
            age / 1000,
            limit / 1000
        )
    })
}

/// Redis's rule, in milliseconds: with the link to the master down for
/// `down_for`, the data's age and the limit it is over, if it is. The link
/// was down for at least the node timeout before the master could be marked
/// FAIL; that much does not count against the data.
fn data_too_old(
    down_for: u64,
    node_timeout: u64,
    ping_period: u64,
    factor: u64,
) -> Option<(u64, u64)> {
    let age = if down_for > node_timeout {
        down_for - node_timeout
    } else {
        down_for
    };
    let limit = node_timeout
        .saturating_mul(factor)
        .saturating_add(ping_period);
    (factor != 0 && age > limit).then_some((age, limit))
}

/// How many other replicas of `master_id` have read further than we have.
/// Each is asked (`OFFSET`); one that does not answer, an older version
/// among them, is not counted, so it never holds us back.
async fn replica_rank(
    state: &Arc<ClusterState>,
    repl_state: &crate::replication::ReplState,
    master_id: NodeId,
) -> u64 {
    let mine = repl_state.repl_offset.load(Ordering::Relaxed);
    let me = state.myself();
    let siblings: Vec<String> = {
        let nodes = state.nodes.read();
        nodes
            .values()
            .filter(|n| {
                n.id != me
                    && n.master_id == Some(master_id)
                    && !n.flags.contains(NodeFlags::FAIL)
                    && !n.flags.contains(NodeFlags::HANDSHAKE)
                    && !n.ip.is_empty()
                    && n.cluster_port != 0
            })
            .map(|n| format!("{}:{}", n.ip, n.cluster_port))
            .collect()
    };
    let mut asked = tokio::task::JoinSet::new();
    for addr in siblings {
        let state = Arc::clone(state);
        asked.spawn(async move {
            let ask = BusMessage::OffsetQuery { sender_id: me };
            dialer::exchange(&state, &addr, &ask, Duration::from_millis(500)).await
        });
    }
    let mut ahead = 0;
    while let Some(answer) = asked.join_next().await {
        if let Ok(Ok(Some(BusMessage::OffsetAck { offset, .. }))) = answer
            && offset > mine
        {
            ahead += 1;
        }
    }
    ahead
}

/// Take over from `old_master` at `epoch`: claim its slots, switch role in
/// both the cluster view and the replication layer, and tell everyone at once.
async fn promote(
    state: &Arc<ClusterState>,
    repl_state: &Arc<crate::replication::ReplState>,
    old_master: NodeId,
    epoch: u64,
) {
    let claimed = state.promote_self(old_master, epoch);
    // Flip our INFO replication role too — the cluster sees us as master,
    // repl_state needs to agree.
    repl_state.become_master();
    // A claim of some of the slots that came in between left their keys:
    // this node was a replica still to the replication layer.
    state.drop_slots_lost_while_promoting(&claimed);
    state.end_election();
    // Announce the new ownership now rather than on the next heartbeat tick:
    // until the others hear it they keep redirecting clients to the old
    // master, and its other replicas keep following a node that is gone.
    send_one_round(state).await;
}

/// Broadcast a FailoverAuthRequest to every known master.
pub(crate) async fn broadcast_auth_request(
    state: &Arc<ClusterState>,
    master_id: NodeId,
    epoch: u64,
    force: bool,
) {
    if test_bus_muted() {
        return;
    }
    let masters: Vec<(NodeId, String, u16)> = {
        let nodes = state.nodes.read();
        nodes
            .values()
            .filter(|n| {
                n.flags.contains(NodeFlags::MASTER)
                    && !n.flags.contains(NodeFlags::FAIL)
                    && n.id != state.myself()
                    && !n.ip.is_empty()
            })
            .map(|n| (n.id, n.ip.clone(), n.cluster_port))
            .collect()
    };

    let me = {
        let nodes = state.nodes.read();
        nodes.get(&state.myself()).cloned().unwrap_or_else(|| {
            crate::cluster::ClusterNode::new(state.myself(), String::new(), 0, 0)
        })
    };

    let msg = BusMessage::FailoverAuthRequest {
        sender_id: state.myself(),
        sender_ip: state.advertised_ip(&me.ip),
        sender_client_port: me.client_port,
        sender_cluster_port: me.cluster_port,
        request_epoch: epoch,
        master_id,
        force,
    };

    for (peer_id, ip, bus_port) in masters {
        let msg = msg.clone();
        let state = Arc::clone(state);
        tokio::spawn(async move {
            let addr = format!("{ip}:{bus_port}");
            // A master saves its vote, synced, before it answers: on a busy
            // disk that took longer than the two seconds this used to wait,
            // and the vote was lost though it had been given.
            let wait = Duration::from_millis(state.node_timeout_ms.max(2_000));
            match dialer::exchange(&state, &addr, &msg, wait).await {
                Ok(Some(BusMessage::FailoverAuthAck {
                    sender_id,
                    request_epoch,
                })) => {
                    if let Some(delay) = test_vote_delay() {
                        tokio::time::sleep(delay).await;
                    }
                    let count = state.record_vote(sender_id, request_epoch);
                    log_verbose!(
                        "Cluster: Got vote from {} for epoch {} (total: {})",
                        node_id_str(&sender_id),
                        request_epoch,
                        count,
                    );
                }
                // No reply is a declined vote, not a failure.
                Ok(other) => log_info!(
                    "Cluster: Election: {} gave no vote at epoch {epoch}: {}",
                    node_id_str(&peer_id),
                    match other {
                        None => "no answer".to_string(),
                        Some(m) => format!("answered {m:?}"),
                    }
                ),
                Err(e) => log_warn!(
                    "Cluster: Election: failed to ask {} ({addr}) for vote: {e}",
                    node_id_str(&peer_id)
                ),
            }
        });
    }
}

/// For the tests of an election that runs long, and never set otherwise:
/// `KIVIDB_TEST_VOTE_DELAY_MS`, how long a vote this node was given is held
/// before it is counted. A voter syncs its vote to disk before it answers,
/// and on a disk every other test is syncing to as well that has taken
/// seconds (#185).
fn test_vote_delay() -> Option<Duration> {
    static DELAY: std::sync::OnceLock<Option<Duration>> = std::sync::OnceLock::new();
    *DELAY.get_or_init(|| {
        let ms: u64 = std::env::var("KIVIDB_TEST_VOTE_DELAY_MS")
            .ok()?
            .parse()
            .ok()?;
        Some(Duration::from_millis(ms))
    })
}

// ── Manual failover ──────────────────────────────────────────────────────────

/// How long a replica that asked its master to hold writes has, from asking,
/// to catch up and win its election; it gives the failover up if it has not.
///
/// The master holds writes for twice as long (`MANUAL_FAILOVER_PAUSE`), as
/// in Redis, so that a replica that takes over does so while they are still
/// held, and then until it has made sure it still owns its slots (#242).
/// Both used to be 5 s, and the election was not bounded at all: one
/// whose votes were slow in coming (a voter syncs its vote to disk before it
/// answers) was won after the master had begun taking writes again, and the
/// writes it acknowledged before it heard of the promotion were lost (#185).
pub const MANUAL_FAILOVER_TIMEOUT: Duration = Duration::from_secs(5);

/// How long a master holds writes for a replica that asked to take over
/// before it asks the cluster whether it still owns its slots. It holds them
/// until it knows: see `ClusterState::hold_writes_until_confirmed`.
const MANUAL_FAILOVER_PAUSE: Duration = Duration::from_secs(10);

/// The master's side of `CLUSTER FAILOVER`: stop accepting writes, and tell
/// the replica how far it has to read to have everything.
///
/// The offset is exact. Writes are paused, the write gate is cycled so every
/// write already in flight has queued its payload, and a hub barrier confirms
/// those payloads have been handed to the replica's link — so "what this
/// replica has been sent" is final when it is read.
pub(crate) async fn answer_mfstart(
    state: &Arc<ClusterState>,
    replica_id: NodeId,
) -> Option<BusMessage> {
    let hooks = state.hooks.get()?;
    let starter = &hooks.replica_starter;
    let repl_state = &starter.repl_state;

    // Only our own replica may ask, and only while we are a master.
    let replica_addr = {
        let nodes = state.nodes.read();
        let me = state.myself();
        if !nodes
            .get(&me)
            .is_some_and(|n| n.flags.contains(NodeFlags::MASTER))
        {
            return None;
        }
        let replica = nodes.get(&replica_id)?;
        if !replica.flags.contains(NodeFlags::REPLICA) || replica.master_id != Some(me) {
            return None;
        }
        (replica.ip.clone(), replica.client_port)
    };
    // Not while an atomic slot migration away from this node hands slots
    // over (#516): see `ClusterState::failover_may_begin`.
    if let Err(why) = state.failover_may_begin() {
        log_warn!(
            "Cluster: Manual failover requested by {} refused: {why}",
            node_id_str(&replica_id)
        );
        return None;
    }

    // Held until the replica has taken over (this node follows it then), or,
    // once the replica's time is up, until this node has made sure it still
    // owns its slots (#242).
    let already_held = state.writes_held();
    state.hold_writes_until_confirmed(
        crate::cluster::HoldReason::ManualFailover,
        now_ms_local() + MANUAL_FAILOVER_PAUSE.as_millis() as u64,
    );
    // Let writes that were already in the gate finish and queue. One that is
    // past the pause check but not yet in the gate waits for the failover
    // there, and is redirected (`pause::HANDOFF`).
    let _ = tokio::task::spawn_blocking(|| drop(crate::write_gate::cut())).await;
    let (barrier_tx, barrier_rx) = tokio::sync::oneshot::channel();
    if starter
        .hub_tx
        .send(crate::replication::HubMsg::Barrier(barrier_tx))
        .is_ok()
    {
        let _ = barrier_rx.await;
    }

    // Find this replica's replication link. The master lists a replica by the
    // IP its connection came from and the port it announced; the cluster
    // knows it by the address it advertises. Those agree on the port, and
    // usually on the IP — but not behind NAT or an announce address, so an
    // exact match is preferred and a port match accepted.
    let target = {
        let peers: Vec<(u64, String, u16)> = repl_state.replica_peers.lock().clone();
        let progress = repl_state.replica_progress.lock();
        let same_port = || peers.iter().filter(|(_, _, port)| *port == replica_addr.1);
        same_port()
            .find(|(_, ip, _)| *ip == replica_addr.0)
            .or_else(|| same_port().next())
            .and_then(|(id, _, _)| progress.get(id))
            .map(|p| p.base + p.sent.load(Ordering::Relaxed))
    };
    let Some(target_offset) = target else {
        // The replica is not attached; there is nothing to hand over.
        if !already_held {
            state.release_held_writes("the replica that asked for a failover is not attached");
        }
        return None;
    };
    log_info!(
        "Cluster: Manual failover requested by {} — writes paused, replica must reach offset {target_offset}",
        node_id_str(&replica_id)
    );
    Some(BusMessage::MfAck {
        sender_id: state.myself(),
        target_offset,
    })
}

/// The replica's side of `CLUSTER FAILOVER` (without `FORCE`): have the master
/// pause, catch up to it, then run a forced election.
///
/// Returns an error describing why the failover did not start; on success the
/// election is under way and `check_election` drives it from here.
pub async fn run_manual_failover(
    state: Arc<ClusterState>,
    master_id: NodeId,
) -> Result<(), String> {
    let hooks = state.hooks.get().ok_or("cluster hooks are not installed")?;
    let repl_state = Arc::clone(&hooks.replica_starter.repl_state);

    let master_addr = {
        let nodes = state.nodes.read();
        let m = nodes
            .get(&master_id)
            .ok_or("master is not in the node table")?;
        format!("{}:{}", m.ip, m.cluster_port)
    };

    // From before the master is asked: it holds writes from a moment later,
    // for twice this.
    let deadline_ms = now_ms_local() + MANUAL_FAILOVER_TIMEOUT.as_millis() as u64;
    let reply = dialer::exchange(
        &state,
        &master_addr,
        &BusMessage::MfStart {
            sender_id: state.myself(),
        },
        MANUAL_FAILOVER_TIMEOUT,
    )
    .await?;
    let target_offset = match reply {
        Some(BusMessage::MfAck { target_offset, .. }) => target_offset,
        _ => {
            return Err(
                "the master did not acknowledge the failover request. It refuses one \
                        while an atomic slot migration away from it hands slots over, and for \
                        a few seconds after one, or while an import into it takes slots \
                        over; its log says why (\"Manual failover requested by ... refused\"). \
                        Ask again in a few seconds"
                    .into(),
            );
        }
    };

    // Catch up to the point the master stopped at.
    while repl_state.repl_offset.load(Ordering::Relaxed) < target_offset {
        if now_ms_local() >= deadline_ms {
            return Err(format!(
                "did not catch up with the master in time (at {} of {target_offset})",
                repl_state.repl_offset.load(Ordering::Relaxed)
            ));
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }

    // Won by the same deadline, or given up (`check_election`).
    start_forced_election(&state, master_id, Some(deadline_ms)).await;
    Ok(())
}

/// Start an election that does not require the master to be FAIL, to be won
/// by `deadline_ms` if there is one (see [`MANUAL_FAILOVER_TIMEOUT`]).
pub async fn start_forced_election(
    state: &Arc<ClusterState>,
    master_id: NodeId,
    deadline_ms: Option<u64>,
) {
    let epoch = state.start_election(master_id, true, deadline_ms);
    log_info!(
        "Cluster: Manual failover: starting election at epoch {epoch} to replace {}",
        node_id_str(&master_id)
    );
    broadcast_auth_request(state, master_id, epoch, true).await;
}

// ── Writes held until this master knows it still owns its slots ─────────────

/// What a peer's answer to our PING says, for [`still_owner`].
#[derive(Debug, Clone)]
pub(crate) struct Answer {
    pub from: NodeId,
    /// It says it is a master.
    pub master: bool,
    /// The master it says it follows.
    pub master_id: Option<NodeId>,
    /// It holds this node FAIL.
    pub holds_us_failed: bool,
}

/// Whether this master, `me`, can be sure from a round's `answers` that it
/// still owns its slots: a majority of the masters that own slots (`quorum`,
/// this one counted) have answered without holding it FAIL — no replica of
/// it can be elected without such a majority's votes, and a master votes
/// only for the replica of a master it holds FAIL — and every replica of it
/// that was asked (`replicas`) has answered, as its replica, without holding
/// it FAIL. A replica that has taken over answers as a master and claims the
/// slots, and this node follows it then.
pub(crate) fn still_owner(
    me: NodeId,
    quorum: usize,
    replicas: &[NodeId],
    answers: &[Answer],
) -> Result<(), String> {
    if let Some(a) = answers.iter().find(|a| a.holds_us_failed) {
        return Err(format!("{} still holds it FAIL", node_id_str(&a.from)));
    }
    for replica in replicas {
        match answers.iter().find(|a| a.from == *replica) {
            None => {
                return Err(format!(
                    "its replica {} has not answered",
                    node_id_str(replica)
                ));
            }
            Some(a) if a.master || a.master_id != Some(me) => {
                return Err(format!("{} is no longer its replica", node_id_str(replica)));
            }
            Some(_) => {}
        }
    }
    let masters = 1 + answers
        .iter()
        .filter(|a| a.master && !replicas.contains(&a.from))
        .count();
    if masters < quorum {
        return Err(format!(
            "{masters} of the {quorum} masters it needs have answered, itself counted"
        ));
    }
    Ok(())
}

/// From the failure detector: if this master holds writes until it knows it
/// still owns its slots, and it is time to ask, ask.
fn check_held_writes(state: &Arc<ClusterState>) {
    if !state.held_writes_due() {
        return;
    }
    let state = Arc::clone(state);
    tokio::spawn(async move {
        let answer = ask_whether_still_owner(&state).await;
        state.held_writes_answered(answer);
    });
}

/// One round of asking: PING every other master that owns slots, and every
/// replica of this one that has not failed, each over a connection of its
/// own, and see what their PONGs say ([`still_owner`]). A PONG is a reply,
/// made after our PING arrived, so it is no older than the round. Each is
/// taken in like any other: one from a replica that has taken over makes
/// this node follow it, and that lets the writes go.
async fn ask_whether_still_owner(state: &Arc<ClusterState>) -> Result<(), String> {
    if test_bus_muted() {
        return Err("(test) the bus is muted".into());
    }
    let me = state.myself();
    let master = state
        .nodes
        .read()
        .get(&me)
        .is_some_and(|n| n.flags.contains(NodeFlags::MASTER));
    if !master || !state.owns_any_slot(me) {
        // Nothing to hold writes for.
        return Ok(());
    }
    let owners: ahash::AHashSet<NodeId> = state.slots.read().iter().flatten().copied().collect();
    let (masters, replicas) = {
        let nodes = state.nodes.read();
        let reachable = |n: &&crate::cluster::ClusterNode| {
            n.id != me
                && !n.flags.contains(NodeFlags::HANDSHAKE)
                && !n.ip.is_empty()
                && n.cluster_port != 0
        };
        let address = |n: &crate::cluster::ClusterNode| (n.id, n.ip.clone(), n.cluster_port);
        let masters: Vec<(NodeId, String, u16)> = nodes
            .values()
            .filter(reachable)
            .filter(|n| n.flags.contains(NodeFlags::MASTER) && owners.contains(&n.id))
            .map(address)
            .collect();
        let replicas: Vec<(NodeId, String, u16)> = nodes
            .values()
            .filter(reachable)
            .filter(|n| n.master_id == Some(me) && !n.flags.contains(NodeFlags::FAIL))
            .map(address)
            .collect();
        (masters, replicas)
    };
    let quorum = state.election_quorum(me);
    let ping = dialer::our_ping(state);
    let wait = Duration::from_millis(state.node_timeout_ms.clamp(500, 5_000));
    let mut asked = tokio::task::JoinSet::new();
    for (id, ip, port) in masters.into_iter().chain(replicas.iter().cloned()) {
        let (state, ping) = (Arc::clone(state), ping.clone());
        asked.spawn(async move {
            let reply = dialer::exchange(&state, &format!("{ip}:{port}"), &ping, wait).await;
            (id, ip, reply)
        });
    }
    let mut answers = Vec::new();
    while let Some(joined) = asked.join_next().await {
        let Ok((id, ip, Ok(Some(reply)))) = joined else {
            continue;
        };
        if let BusMessage::Pong {
            sender_id,
            sender_flags,
            sender_master_id,
            gossip,
            ..
        } = &reply
            && *sender_id == id
        {
            answers.push(Answer {
                from: id,
                master: sender_flags.contains(NodeFlags::MASTER),
                master_id: *sender_master_id,
                holds_us_failed: gossip
                    .iter()
                    .any(|g| g.id == me && g.flags.contains(NodeFlags::FAIL)),
            });
        }
        crate::cluster::bus::listener::process_message(state, reply, dialer::peer_socket_addr(&ip));
    }
    let replicas: Vec<NodeId> = replicas.iter().map(|r| r.0).collect();
    still_owner(me, quorum, &replicas, &answers)
}

// ── For the tests of a bus that falls behind ─────────────────────────────────

/// `KIVIDB_TEST_BUS_CONTROL`, never set otherwise: a file, read on every
/// tick of the failure detector, that says what this node's bus is to do.
/// `stall`: stop, as a bus stuck behind a slow disk does — the bus thread
/// waits on the file, and nothing is sent, taken in or decided until it says
/// otherwise. `mute`: send nothing and answer nothing, but take in what
/// comes, as a node does whose answers come too late to count. Anything
/// else, or no file: run.
fn test_bus_control() -> Option<&'static std::path::Path> {
    static PATH: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
    PATH.get_or_init(|| std::env::var_os("KIVIDB_TEST_BUS_CONTROL").map(Into::into))
        .as_deref()
}

static TEST_BUS_MUTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Whether this node's bus is muted for a test (see [`test_bus_control`]).
#[inline]
pub(crate) fn test_bus_muted() -> bool {
    TEST_BUS_MUTED.load(Ordering::Relaxed)
}

/// Mute this node's bus, or let it run, for a test's failpoint (see
/// `migration::TEST_TAKEOVER_LOST`).
pub(crate) fn set_test_bus_muted(muted: bool) {
    TEST_BUS_MUTED.store(muted, Ordering::Relaxed);
}

fn apply_test_bus_control() {
    let Some(path) = test_bus_control() else {
        return;
    };
    let mode = || {
        std::fs::read_to_string(path)
            .unwrap_or_default()
            .trim()
            .to_string()
    };
    if mode() == "stall" {
        log_warn!("Cluster: (test) the bus is stalled");
        while mode() == "stall" {
            std::thread::sleep(Duration::from_millis(50));
        }
        log_warn!("Cluster: (test) the bus runs again");
    }
    TEST_BUS_MUTED.store(mode() == "mute", Ordering::Relaxed);
}

/// For the delay before a replica stands for election. It has to differ
/// between the replicas of one master, or they split the vote; the clock's
/// nanoseconds, which this used to be, come in steps of 100 on some systems.
fn rand_u32() -> u32 {
    rand::random()
}

fn now_ms_local() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::{Answer, data_too_old, stand_refusal, still_owner};
    use crate::cluster::node::{NODE_ID_ZERO, NodeId};

    fn id(n: u8) -> NodeId {
        let mut id = NODE_ID_ZERO;
        id[0] = b'0' + n;
        id
    }

    fn answer(from: u8, master: bool, master_id: Option<u8>, holds_us_failed: bool) -> Answer {
        Answer {
            from: id(from),
            master,
            master_id: master_id.map(id),
            holds_us_failed,
        }
    }

    #[test]
    fn a_master_is_sure_of_its_slots_once_a_majority_and_its_replicas_say_so() {
        // Three masters (1 is us), one replica of us (4): quorum 2.
        let (me, replicas) = (id(1), [id(4)]);
        let replica_ok = answer(4, false, Some(1), false);
        let all = [
            answer(2, true, None, false),
            answer(3, true, None, false),
            replica_ok.clone(),
        ];
        assert_eq!(still_owner(me, 2, &replicas, &all), Ok(()));
        // One other master is enough for a majority.
        assert!(still_owner(me, 2, &replicas, &all[1..]).is_ok());
        // None is not.
        assert!(still_owner(me, 2, &replicas, std::slice::from_ref(&replica_ok)).is_err());
        // A master that still holds us FAIL may have voted for our replica.
        let failed_by_3 = [
            answer(2, true, None, false),
            answer(3, true, None, true),
            replica_ok.clone(),
        ];
        assert!(still_owner(me, 2, &replicas, &failed_by_3).is_err());
        // So may a replica that holds us FAIL be standing.
        let replica_fails_us = [
            answer(2, true, None, false),
            answer(4, false, Some(1), true),
        ];
        assert!(still_owner(me, 2, &replicas, &replica_fails_us).is_err());
        // A replica that has not answered may have been promoted.
        assert!(still_owner(me, 2, &replicas, &all[..2]).is_err());
        // And one that answers as a master has been.
        let promoted = [answer(2, true, None, false), answer(4, true, None, false)];
        assert!(still_owner(me, 2, &replicas, &promoted).is_err());
        // A replica's answer does not count towards the masters.
        assert!(still_owner(me, 2, &replicas, &[replica_ok]).is_err());
        // No replica to ask, one master: only ourselves needed.
        assert_eq!(still_owner(me, 1, &[], &[]), Ok(()));
    }

    #[test]
    fn a_replica_too_long_without_its_master_does_not_stand() {
        // Node timeout 5 s, ping period 10 s, factor 10: 60 s of data age.
        let (timeout, ping) = (5_000, 10_000);
        // Just failed: down for about the node timeout.
        assert_eq!(data_too_old(6_000, timeout, ping, 10), None);
        // The node timeout itself does not count.
        assert_eq!(data_too_old(65_000, timeout, ping, 10), None);
        assert_eq!(
            data_too_old(65_001, timeout, ping, 10),
            Some((60_001, 60_000))
        );
        // Factor 0: always stand.
        assert_eq!(data_too_old(10_000_000, timeout, ping, 0), None);
        // Factor 1: 15 s.
        assert_eq!(
            data_too_old(21_000, timeout, ping, 1),
            Some((16_000, 15_000))
        );
    }

    #[test]
    fn a_replica_stands_only_once_its_full_sync_is_loaded_and_streamed() {
        let (timeout, ping, now) = (5_000, 10_000, 1_000_000_000);
        // In step a moment ago: stands, whatever the factor.
        for factor in [0, 1, 10] {
            assert_eq!(
                stand_refusal(false, now - 100, now, timeout, ping, factor),
                None
            );
        }
        // In a full sync, receiving or loading: never, not even with
        // factor 0. It may hold part of the data or none.
        for factor in [0, 1, 10] {
            let why = stand_refusal(true, 0, now, timeout, ping, factor).unwrap();
            assert!(why.contains("full sync"), "{why}");
        }
        // Age counts from the last moment in step, however recently the
        // link came up: a sync that keeps starting over is old data.
        let why = stand_refusal(false, now - 65_001, now, timeout, ping, 10).unwrap();
        assert!(why.contains("60 s old"), "{why}");
        assert_eq!(
            stand_refusal(false, now - 65_000, now, timeout, ping, 10),
            None
        );
        // Never in step since it started: its data's age is not known.
        assert!(stand_refusal(false, 0, now, timeout, ping, 10).is_some());
        // Factor 0 lets such a replica stand, as in Redis.
        assert_eq!(stand_refusal(false, 0, now, timeout, ping, 0), None);
    }
}