simraft-core 0.2.0

Sans-I/O Raft consensus core with Pre-Vote, fast log backup, ReadIndex, snapshots, and single-server membership
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
//! Commitment properties (invariants S-05 and S-06): the Figure 8
//! rule and same-index same-entry apply consistency.

#[allow(
    dead_code,
    reason = "each test file uses a different subset of the shared driver helpers"
)]
mod common;

use proptest::prelude::*;
use simraft_core::{
    Action, ClientId, ClusterConfig, Config, EntryKind, Event, HardState, LogEntry, LogIndex,
    Message, Node, NodeId, PersistKind, SnapshotMeta, Term,
};
use std::collections::{BTreeMap, BTreeSet, VecDeque};

/// A cluster driver with a two-cell partition filter: sends are
/// delivered only within a cell, modelling a network partition.
struct Filtered {
    nodes: BTreeMap<NodeId, Node>,
    applies: BTreeMap<NodeId, Vec<(LogIndex, LogEntry)>>,
}

impl Filtered {
    fn new(ids: &[u64], seed: u64) -> Self {
        Self {
            applies: ids.iter().map(|&i| (NodeId(i), Vec::new())).collect(),
            nodes: common::build_nodes(ids, seed),
        }
    }

    fn step(&mut self, id: NodeId, event: Event, partition: Option<(&[u64], &[u64])>) {
        // A send is delivered only when sender and recipient sit in
        // the same partition cell. None connects everyone.
        let cells: Option<(BTreeSet<NodeId>, BTreeSet<NodeId>)> = partition.map(|(a, b)| {
            (
                a.iter().map(|&i| NodeId(i)).collect(),
                b.iter().map(|&i| NodeId(i)).collect(),
            )
        });
        let mut queue: VecDeque<(NodeId, Event)> = VecDeque::new();
        queue.push_back((id, event));
        while let Some((node_id, ev)) = queue.pop_front() {
            let actions = self.nodes.get_mut(&node_id).expect("cluster node").step(ev);
            for action in actions {
                match action {
                    Action::Send { to, msg } => {
                        let connected = cells.as_ref().is_none_or(|(a, b)| {
                            (a.contains(&node_id) && a.contains(&to))
                                || (b.contains(&node_id) && b.contains(&to))
                        });
                        if connected {
                            queue.push_back((to, Event::Message { from: node_id, msg }));
                        }
                    }
                    Action::PersistHardState { .. } => queue.push_back((
                        node_id,
                        Event::Persisted {
                            kind: PersistKind::HardState,
                            up_to_index: LogIndex::ZERO,
                        },
                    )),
                    Action::PersistEntries {
                        from_index,
                        entries,
                    } => {
                        let up_to = if entries.is_empty() {
                            LogIndex(from_index.0.saturating_sub(1))
                        } else {
                            LogIndex(from_index.0 + entries.len() as u64 - 1)
                        };
                        queue.push_back((
                            node_id,
                            Event::Persisted {
                                kind: PersistKind::Entries,
                                up_to_index: up_to,
                            },
                        ));
                    }
                    Action::Apply { index, entry } => {
                        self.applies
                            .get_mut(&node_id)
                            .expect("cluster node")
                            .push((index, entry));
                    }
                    Action::ClientResponse { .. }
                    | Action::StepDown { .. }
                    | Action::ReadReady { .. }
                    | Action::ReadRejected { .. }
                    | Action::ConfigResponse { .. }
                    | Action::PersistSnapshot { .. }
                    | Action::LoadSnapshot { .. } => {}
                }
            }
        }
    }
}

#[test]
fn figure8_old_term_entry_not_committed_by_counting() {
    let cluster = common::all_voters(&[1, 2, 3, 4, 5]);
    let mut leader = Node::new(NodeId(1), simraft_core::Config::default(), cluster, 31).unwrap();
    let _ = leader.step(Event::Restored {
        hard_state: HardState {
            current_term: Term(1),
            voted_for: None,
        },
        entries: vec![LogEntry {
            term: Term(1),
            kind: EntryKind::Command {
                client_id: ClientId(1),
                seq: 1,
                payload: b"old".to_vec(),
            },
        }],
        snapshot: None,
    });
    let _ = common::elect(&mut leader, &[NodeId(2), NodeId(3), NodeId(4)]);
    let _ = leader.step(Event::Persisted {
        kind: PersistKind::Entries,
        up_to_index: LogIndex(2),
    });
    assert_eq!(leader.current_term(), Term(2));
    assert_eq!(leader.log().last_index(), LogIndex(2));

    for peer in [2_u64, 3] {
        let _ = leader.step(Event::Message {
            from: NodeId(peer),
            msg: Message::AppendEntriesResponse {
                term: Term(2),
                success: true,
                match_index: LogIndex(1),
                conflict_index: LogIndex(0),
                conflict_term: Term(0),
                read_round: 0,
            },
        });
    }
    assert_eq!(
        leader.commit_index(),
        LogIndex(0),
        "a majority holding only a previous-term entry must not commit it (Figure 8)"
    );

    for peer in [2_u64, 3] {
        let _ = leader.step(Event::Message {
            from: NodeId(peer),
            msg: Message::AppendEntriesResponse {
                term: Term(2),
                success: true,
                match_index: LogIndex(2),
                conflict_index: LogIndex(0),
                conflict_term: Term(0),
                read_round: 0,
            },
        });
    }
    assert_eq!(leader.commit_index(), LogIndex(2));
}

#[test]
fn current_term_entry_commits_by_counting() {
    let mut harness = common::Harness::new(&[1, 2, 3], 77);
    harness.run_until(3_000, 25);
    let leader_id = harness.leaders()[0].0;
    harness.step_node(
        leader_id,
        Event::Propose {
            client_id: ClientId(3),
            seq: 1,
            payload: b"v".to_vec(),
        },
    );
    harness.run_until(400, 25);
    for node in harness.nodes.values() {
        assert_eq!(
            node.commit_index(),
            LogIndex(2),
            "every node commits the index-2 entry once a majority holds it"
        );
    }
}

#[test]
fn figure8_overwritten_entry_never_applies() {
    // The full Figure 8 staging on five nodes. Roles are picked from
    // whoever wins each election, so the test does not depend on which
    // node a seed happens to elect first.
    let all = [1_u64, 2, 3, 4, 5];
    let mut fc = Filtered::new(&all, 55);
    let tick_all = |fc: &mut Filtered, now: u64, partition: Option<(&[u64], &[u64])>| {
        for &id in &all {
            fc.step(NodeId(id), Event::Tick { now }, partition);
        }
    };
    // Phase 1: full delivery until some node leads term 1.
    let mut now = 0_u64;
    let mut leader_a = None;
    while now <= 6_000 {
        tick_all(&mut fc, now, None);
        let leaders: Vec<NodeId> = fc
            .nodes
            .values()
            .filter(|n| n.role() == simraft_core::Role::Leader)
            .map(simraft_core::Node::id)
            .collect();
        if leaders.len() == 1 {
            leader_a = Some(leaders[0]);
            break;
        }
        now += 25;
    }
    let leader_a = leader_a.expect("a term-1 leader emerges");
    let others: Vec<u64> = all
        .iter()
        .copied()
        .filter(|&i| NodeId(i) != leader_a)
        .collect();
    let f1 = others[0];
    // Phase 2: the leader proposes X at index 2; only one follower
    // receives it. Two of five replicas: X stays uncommitted.
    let side_a: Vec<u64> = vec![leader_a.0, f1];
    let side_b: Vec<u64> = others[1..].to_vec();
    fc.step(
        leader_a,
        Event::Propose {
            client_id: ClientId(1),
            seq: 1,
            payload: b"x".to_vec(),
        },
        Some((&side_a, &side_b)),
    );
    assert!(
        fc.nodes[&leader_a].commit_index() < LogIndex(2),
        "X at index 2 has two of five replicas and must not commit"
    );
    // Phase 3: the other three nodes are isolated with the first two
    // and elect their own leader in term 2, committing its term-2 NoOp
    // at index 2 by counting.
    let group: Vec<u64> = others[1..].to_vec();
    assert_eq!(group.len(), 3);
    let mut leader_b = None;
    while now <= 12_000 {
        tick_all(&mut fc, now, Some((&side_a, &side_b)));
        for &g in &group {
            if fc.nodes[&NodeId(g)].role() == simraft_core::Role::Leader {
                leader_b = Some(NodeId(g));
            }
        }
        if leader_b.is_some() {
            break;
        }
        now += 25;
    }
    let leader_b = leader_b.expect("the isolated group elects a term-2 leader");
    assert_eq!(fc.nodes[&leader_b].current_term(), Term(2));
    assert_eq!(
        fc.nodes[&leader_b].commit_index(),
        LogIndex(2),
        "the term-2 entry at index 2 commits on its own replicas"
    );
    // Phase 4: heal. The old leader is overwritten at index 2.
    for _ in 0..20 {
        now += 25;
        tick_all(&mut fc, now, None);
    }
    let overwritten = &fc.nodes[&leader_a].log().entries()[1];
    assert_eq!(
        overwritten.term,
        Term(2),
        "index 2 on the old leader must be the term-2 entry"
    );
    assert_eq!(overwritten.kind, EntryKind::NoOp);
    for (id, applies) in &fc.applies {
        for (_, entry) in applies {
            if let EntryKind::Command { payload, .. } = &entry.kind {
                assert_ne!(payload, b"x", "node {id} applied the overwritten entry");
            }
        }
    }
}

#[test]
fn same_index_applies_same_entry_on_all_nodes() {
    let mut harness = common::Harness::new(&[1, 2, 3], 78);
    harness.run_until(3_000, 25);
    let leader_id = harness.leaders()[0].0;
    for seq in 1_u64..=4 {
        harness.step_node(
            leader_id,
            Event::Propose {
                client_id: ClientId(3),
                seq,
                payload: vec![u8::try_from(seq).expect("seq fits")],
            },
        );
        harness.run_until(300, 25);
    }
    let reference = &harness.applies[&leader_id];
    assert!(reference.len() >= 5, "leader applied its entries");
    for (id, applies) in &harness.applies {
        assert_eq!(
            applies, reference,
            "node {id} applied a different history than the leader"
        );
    }
}

#[test]
fn append_below_base_never_commits_unverified_divergent_tail() {
    let cluster = ClusterConfig::new([NodeId(1), NodeId(2), NodeId(3)], Vec::new()).unwrap();
    let mut follower = Node::new(NodeId(2), Config::default(), cluster.clone(), 13).unwrap();
    // Snapshot covers through index 4 (term 2), plus an unverified divergent entry at index 5 (term 2).
    let _ = follower.step(Event::Restored {
        hard_state: HardState {
            current_term: Term(2),
            voted_for: None,
        },
        entries: vec![LogEntry {
            term: Term(2),
            kind: EntryKind::Command {
                client_id: ClientId(9),
                seq: 1,
                payload: b"divergent".to_vec(),
            },
        }],
        snapshot: Some(SnapshotMeta {
            last_included_index: LogIndex(4),
            last_included_term: Term(2),
            config: cluster,
        }),
    });
    assert_eq!(follower.commit_index(), LogIndex(4));
    assert_eq!(follower.log().last_index(), LogIndex(5));

    // A new leader in term 3 sends an AppendEntries starting below base_index (prev_log_index = 3)
    // with leader_commit = 5. Because index 5 was NOT verified by this message, commit_index must
    // remain bounded by base_index (4) and never apply the divergent entry at 5.
    let actions = follower.step(Event::Message {
        from: NodeId(1),
        msg: Message::AppendEntries {
            term: Term(3),
            prev_log_index: LogIndex(3),
            prev_log_term: Term(2),
            entries: Vec::new(),
            leader_commit: LogIndex(5),
            read_round: 0,
        },
    });
    assert_eq!(
        follower.commit_index(),
        LogIndex(4),
        "on_append_below_base must bound commit advancement by base_index"
    );
    assert!(
        !actions.iter().any(|a| matches!(a, Action::Apply { .. })),
        "unverified divergent entry above base must never apply"
    );
}

proptest! {
    #[test]
    fn heartbeat_never_commits_unverified_divergent_tail(
        shared_len in 1_u64..=6,
        divergent_len in 1_u64..=6,
        extra_commit in 1_u64..=10,
    ) {
        let cluster = common::all_voters(&[1, 2, 3]);
        let mut follower = Node::new(NodeId(2), Config::default(), cluster, 29).unwrap();
        let mut entries = Vec::new();
        for _ in 0..shared_len {
            entries.push(LogEntry {
                term: Term(1),
                kind: EntryKind::NoOp,
            });
        }
        for i in 0..divergent_len {
            entries.push(LogEntry {
                term: Term(2),
                kind: EntryKind::Command {
                    client_id: ClientId(55),
                    seq: i + 1,
                    payload: b"stale-divergent".to_vec(),
                },
            });
        }
        let _ = follower.step(Event::Restored {
            hard_state: HardState {
                current_term: Term(2),
                voted_for: None,
            },
            entries,
            snapshot: None,
        });

        // Term-3 leader sends an empty AppendEntries (heartbeat) verifying only `shared_len`,
        // while advertising `leader_commit = shared_len + extra_commit` (committed on another majority).
        let actions = follower.step(Event::Message {
            from: NodeId(1),
            msg: Message::AppendEntries {
                term: Term(3),
                prev_log_index: LogIndex(shared_len),
                prev_log_term: Term(1),
                entries: Vec::new(),
                leader_commit: LogIndex(shared_len + extra_commit),
                read_round: 0,
            },
        });
        prop_assert_eq!(
            follower.commit_index(),
            LogIndex(shared_len),
            "S-05: empty AppendEntries must never commit past prev_log_index"
        );
        for action in &actions {
            if let Action::Apply { index, .. } = action {
                prop_assert!(
                    *index <= LogIndex(shared_len),
                    "S-05: divergent tail entry at {index} was applied on heartbeat"
                );
            }
        }
    }
}