本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 3 · 本科三年级
32Project: A Replicated Key-Value Store
The key-value server of the Year 2 volume keeps its map on one machine: when that machine stops, the service stops, and when its disk dies, the data dies with it. This chapter builds the same kind of server again, in Rust with the standard library only, and runs it as three replicas that agree on every write through Raft. It survives the crash of any one replica, a crash in the middle of a write to the disk, and a leader killed while clients are writing; a recorded history of the clients’ operations is then checked for linearisability. The work is done in six milestones, each with its code, its output and its tests, and ends with a measurement.
You already know
Raft (Definition 26.8): election terms, leader election, the replicated log, the commitment rule for entries of the leader’s own election term, log matching (Theorem 26.9) and leader completeness. Linearisability and the brute-force checker that tries every allowed order (Definition 13.12). The write-ahead log, whose records reach the disk before the changes they describe are relied upon (Definition 23.9). The crash failures of Definition 25.2. From the Year 2 volume: the line-based key-value protocol over TCP, which must frame its messages because TCP carries a stream of bytes; threads and channels in Rust; the CRC-32, which detects every burst of errors up to 32 bits long.
Specification. The store keeps a map from keys to values, both words without spaces. A client opens a TCP connection to a replica and sends one command per line, SET key value, GET key or DEL key, and receives one line for each: OK, VALUE v, NOTFOUND, ERR with a reason, or REDIRECT n when replica should be asked instead; two more commands, STATUS and DUMP, report a replica’s role and its whole map, for testing. The three replicas listen on 127.0.0.1:24321 to 24323. Every write goes through the Raft leader and is acknowledged only once it is committed, so writes are linearisable; reads are answered by the leader from its map. Every replica forces its Raft state to a write-ahead log before it acts on it, so a replica that restarts, after a crash at any byte of a write, recovers everything it acknowledged. Any one replica may crash at any time; the store keeps answering, and the replica catches up when it comes back.
OK. A follower asked by a client redirects it to the leader.The code is one Cargo crate, store, of about 1,400 lines in eight modules: protocol (the client protocol), wal (the log file), raft (the consensus algorithm), sim (a simulated network for testing raft), node (a replica as a process), client, lincheck (the linearisability checker) and main (the command line). One binary, store, runs a replica with store node 2 and serves as a client and a tool with its other subcommands.
32.1 Milestone 1: one node and its protocol
A command is one line of text: words separated by spaces, ended by a newline. The newline is the framing: TCP may deliver a line in several pieces or several lines in one piece, and the server reads bytes until it has a whole line before it parses anything. The parser turns a line into a command or into the reason it is not one; the reason goes back to the client after ERR.
/// One line, without its newline, to a command, or the reason it is not one.
pub fn parse(line: &str) -> Result<Command, String> {
if line.len() > MAX_LINE {
return Err(format!("line longer than {MAX_LINE} bytes"));
}
let words: Vec<&str> = line.split(' ').filter(|w| !w.is_empty()).collect();
if words.get(1).is_some_and(|key| key.contains('=')) {
return Err("a key may not contain =".to_string()); // DUMP prints key=value
}
match words.as_slice() {
[] => Err("empty line".to_string()),
["SET", key, value] => Ok(Command::Set(key.to_string(), value.to_string())),
["GET", key] => Ok(Command::Get(key.to_string())),
["DEL", key] => Ok(Command::Del(key.to_string())),
["STATUS"] => Ok(Command::Status),
["DUMP"] => Ok(Command::Dump),
["SET", ..] => Err("SET takes a key and a value".to_string()),
["GET" | "DEL", ..] => Err(format!("{} takes one key", words[0])),
["STATUS" | "DUMP", ..] => Err(format!("{} takes no argument", words[0])),
[word, ..] => Err(format!("unknown command {word}")),
}
}
=, because DUMP prints its pairs as key=value; a line longer than 1,024 bytes is refused before it is split. code/bachelor-3/32-project-replicated-store/listings/store/src/protocol.rsEach connection is served by its own thread, which reads lines, parses them, and hands every valid command to the replica’s main loop together with a channel on which to receive the reply. The thread never touches the map; only the main loop does, so the map needs no lock. The same port also receives the other replicas’ messages: a connection whose first line is PEER n comes from replica , and from then on carries Raft messages.
/// A connection: a peer announces itself with "PEER n"; anything else is a client.
fn serve(stream: TcpStream, events: Sender<Event>) {
let mut out = stream.try_clone().expect("clone");
let mut reader = BufReader::new(stream);
let mut line = String::new();
while matches!(reader.read_line(&mut line), Ok(n) if n > 0) {
if let Some(peer) =
line.strip_prefix("PEER ").and_then(|p| p.trim().parse().ok())
{
while let Some(msg) = decode(&mut reader) {
if events.send(Event::Peer(peer, msg)).is_err() {
return;
}
}
return;
}
let reply = match parse(line.trim_end()) {
Err(reason) => Reply::Err(reason),
Ok(command) => {
let (tx, rx) = channel();
if events.send(Event::Client(command, tx)).is_err() {
return;
}
rx.recv().unwrap_or(Reply::Err("node stopping".to_string()))
}
};
if writeln!(out, "{reply}").is_err() {
return;
}
line.clear();
}
}
read_line returns only at a newline or at the end of the stream; a client’s line goes to the main loop as an event, and the thread waits for the reply on its own channel. code/bachelor-3/32-project-replicated-store/listings/store/src/node.rsA cluster of one replica is already a Raft cluster: its majority is one, so it elects itself as soon as its election timeout expires, and it commits an entry as soon as the entry is in its own log file. The session below starts such a replica and talks to it twice: first through a raw TCP connection opened by the shell, then with the store send client.
$ (./store node 1 --nodes 1 > node1.log &)
$ ./store wait-leader --nodes 1
leader: node 1
$ exec 3<>/dev/tcp/127.0.0.1/24321
$ printf 'SET colour red\nGET colour\nDEL colour\nGET colour\nPUT colour blue\nSET colour\n' >&3
$ head -n 6 <&3
OK
VALUE red
OK
NOTFOUND
ERR unknown command PUT
ERR SET takes a key and a value
$ ./store send 1 SET town Kelsford --nodes 1
node 1: OK
$ ./store send 1 GET town --nodes 1
node 1: VALUE Kelsford
$ cat node1.log
node 1: up, 0 entries in its log, term 0
node 1: leader in term 1
$ kill $(cat node1/pid)
The client of store send opens a connection, writes the command, reads one line, and prints which replica answered. When the answer is REDIRECT n, it asks replica in turn, at most four times; the output then shows every replica on the way. The tests of this milestone print every command and every reply and parse them back, and check the error message of malformed lines.
32.2 Milestone 2: the write-ahead log
Raft keeps three things across a crash: the current election term, the server it voted for in that term, and its log; the Raft paper requires them to be updated on stable storage before the server responds to any message. The store writes them as records appended to one file per replica, wal.log. A vote record holds an election term and a vote; an entry record holds an index, an election term and a command. Each record starts with the length of its payload and the CRC-32 of the payload, both as 4-byte little-endian integers.
pub fn encode(record: &Record) -> Vec<u8> {
let mut payload = Vec::new();
match record {
Record::Vote { term, voted_for } => {
payload.push(b'V');
payload.extend(term.to_le_bytes());
payload.extend(voted_for.to_le_bytes());
}
Record::Entry { index, term, command } => {
payload.push(b'E');
payload.extend(index.to_le_bytes());
payload.extend(term.to_le_bytes());
payload.extend(command.as_bytes());
}
}
let mut out = (payload.len() as u32).to_le_bytes().to_vec();
out.extend(crc32(&payload).to_le_bytes());
out.extend(payload);
out
}
pub fn decode_all(bytes: &[u8]) -> (Vec<Record>, usize) {
let (mut records, mut at) = (Vec::new(), 0);
while let Some(header) = bytes.get(at..at + 8) {
let len = u32::from_le_bytes(header[0..4].try_into().unwrap()) as usize;
let crc = u32::from_le_bytes(header[4..8].try_into().unwrap());
let Some(payload) = bytes.get(at + 8..at + 8 + len) else {
break;
};
if crc32(payload) != crc {
break;
}
let Some(record) = decode_payload(payload) else {
break;
};
records.push(record);
at += 8 + len;
}
(records, at)
}
A crash in the middle of an append leaves a torn record at the end of the file: its header, part of its payload, or nothing at all. The length field alone would not notice the case of a record whose payload is all there but whose bytes are not those written, for instance after a sector was written only in part; the checksum notices it (exercise 32.5 breaks the decoder in the other way).
Proposition 32.1 (Replay of a torn log)
Let a log file be the encodings of records , and let be any prefix of it, of length . Then decode_all on returns and the length , where is the largest number with .
Proof. Facts used: decode_payload inverts the payload part of encode; the checksum of an unchanged payload matches. By induction on , after steps the decoder has returned and stands at offset : for , the record lies wholly inside , so its header and its payload are read in full, its checksum matches, and its payload decodes to . At offset either fewer than 8 bytes remain, and the header cannot be read, or the header of is there but the bytes of its payload are not all in , since does not end inside ; in both cases the loop stops. ∎
On start, Wal::open reads the file, keeps the good records and cuts the file at the end of the last one, so that the next record is appended right after it rather than after the torn bytes, where no replay would ever reach it. An append is one write_all of all the step’s records followed by sync_all, which returns only once the file’s data and metadata have been sent to the disk.
impl Wal {
/// Opens (or creates) the log, returns its good records, and cuts off a torn tail
/// so that the next record is appended right after the last good one.
pub fn open(path: &Path) -> io::Result<(Wal, Vec<Record>)> {
let mut file =
OpenOptions::new().read(true).append(true).create(true).open(path)?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)?;
let (records, good) = decode_all(&bytes);
if good < bytes.len() {
file.set_len(good as u64)?;
file.sync_all()?;
}
Ok((Wal { file }, records))
}
/// Appends the records and forces them to the disk: one write, one fsync.
pub fn append(&mut self, records: &[Record]) -> io::Result<()> {
if records.is_empty() {
return Ok(());
}
let bytes: Vec<u8> = records.iter().flat_map(encode).collect();
self.file.write_all(&bytes)?;
self.file.sync_all()
}
}
The session writes twice, shows the beginning of the log file in hexadecimal, stops the replica, and cuts the last 5 bytes off the file. A real crash can only tear a record whose sync_all had not returned, so a record whose client never received OK; the session tears an acknowledged record only because a shell cannot crash a process in the middle of a write on cue.
$ (./store node 1 --nodes 1 > node1.log &)
$ ./store wait-leader --nodes 1
leader: node 1
$ ./store send 1 SET bridge open --nodes 1
node 1: OK
$ ./store send 1 SET bridge closed --nodes 1
node 1: OK
$ od -A d -t x1 -w16 node1/wal.log | head -n 6
0000000 0d 00 00 00 24 85 02 85 56 01 00 00 00 00 00 00
0000016 00 01 00 00 00 15 00 00 00 bb 9f 83 da 45 01 00
0000032 00 00 00 00 00 00 01 00 00 00 00 00 00 00 4e 4f
0000048 4f 50 20 00 00 00 eb 27 c7 ed 45 02 00 00 00 00
0000064 00 00 00 01 00 00 00 00 00 00 00 53 45 54 20 62
0000080 72 69 64 67 65 20 6f 70 65 6e 22 00 00 00 9b a0
$ stat -c %s node1/wal.log
132
$ kill $(cat node1/pid); sleep 0.2
$ truncate -s -5 node1/wal.log
$ (./store node 1 --nodes 1 >> node1.log &)
$ ./store wait-leader --nodes 1
leader: node 1
$ ./store send 1 GET bridge --nodes 1
node 1: VALUE open
$ stat -c %s node1/wal.log
140
$ cat node1.log
node 1: up, 0 entries in its log, term 0
node 1: leader in term 1
node 1: up, 2 entries in its log, term 1
node 1: leader in term 2
$ kill $(cat node1/pid)
NOOP, then the two writes, 21, 29, 40 and 42 bytes, 132 in all. Cut to 127 bytes, the file replays to three records; the replica cuts it to 90 bytes, wins election term 2 and appends a vote and a new empty entry: . The torn write is gone and the earlier one is read back.The tests of this milestone cut a file of six records at every one of its bytes and check that Wal::open returns exactly the whole records before the cut, leaves the file at their length, and accepts a new record after them; they flip each byte of the file in turn and check that the replay stops at the record holding it; and they check the CRC-32 against its standard check value, 0xCBF43926 for the ASCII string 123456789.
32.3 Milestone 3: Raft as a pure state machine
A Raft node reacts to three things: time passing, a message arriving, and a client’s command. In raft.rs each is a method call, tick, receive and propose, and none of them reads a clock, a socket or a file. Each fills an Output with what the node must do next: the records to force to the log file, the messages to send, and the entries newly committed, to apply. The order is part of the contract: the records first, then the messages. Because the module does nothing else, it can run unchanged inside a test, on a simulated network, or inside a process on a real one.
pub fn tick(&mut self, out: &mut Output) {
self.elapsed += 1;
if self.role == Role::Leader {
if self.elapsed >= HEARTBEAT {
self.replicate(out);
}
} else if self.elapsed >= self.timeout {
self.start_election(out);
}
}
fn start_election(&mut self, out: &mut Output) {
self.term += 1;
(self.role, self.voted_for, self.leader) = (Role::Candidate, self.id, 0);
self.votes = vec![self.id];
out.persist.push(Record::Vote { term: self.term, voted_for: self.id });
self.reset_timer();
if self.votes.len() >= self.majority() {
return self.become_leader(out); // a cluster of one
}
let (last_index, last_term) = self.last();
for &p in &self.peers {
out.send.push((
p,
Msg::RequestVote { term: self.term, last_index, last_term },
));
}
}
fn become_leader(&mut self, out: &mut Output) {
(self.role, self.leader) = (Role::Leader, self.id);
for &p in &self.peers {
self.next.insert(p, self.log.len() as u64 + 1);
self.matched.insert(p, 0);
}
// An entry of the new term, so that the entries before it can be committed.
self.propose("NOOP".to_string(), out);
}
HEARTBEAT ticks. A new leader at once proposes an empty entry. code/bachelor-3/32-project-replicated-store/listings/store/src/raft.rsThe empty entry NOOP is the device of the Raft paper: a new leader does not know which entries of its log are committed, and the commitment rule lets it commit only entries of its own election term, so it commits an empty one and the earlier entries with it. The vote follows the election restriction of Chapter 26: a candidate gets a vote only if its log is at least as up to date as the voter’s, compared by the election term of the last entry first and then by the length.
pub fn receive(&mut self, from: u32, msg: Msg, out: &mut Output) {
if msg.term() > self.term {
self.step_down(msg.term(), out);
}
match msg {
Msg::RequestVote { term, last_index, last_term } => {
// the election restriction: the candidate's log is as up to date
let up_to_date =
(last_term, last_index) >= (self.last().1, self.last().0);
let free = self.voted_for == 0 || self.voted_for == from;
let granted = term == self.term && free && up_to_date;
if granted && self.voted_for != from {
self.voted_for = from;
out.persist.push(Record::Vote { term, voted_for: from });
}
if granted {
self.reset_timer();
}
out.send.push((from, Msg::Vote { term: self.term, granted }));
}
(self.role, self.leader) = (Role::Follower, from);
self.reset_timer();
if prev_index > self.log.len() as u64 || self.term_at(prev_index) != prev_term
{
// no entry at prev_index with the leader's term: refuse, with a hint
let hint = (self.log.len() as u64).min(prev_index.saturating_sub(1));
out.send.push((
from,
Msg::Appended { term, success: false, match_index: hint },
));
return;
}
let count = entries.len() as u64;
for (k, entry) in (prev_index + 1..).zip(entries) {
if k <= self.log.len() as u64 && self.term_at(k) != entry.term {
self.log.truncate(k as usize - 1); // a conflicting suffix is removed
}
if k > self.log.len() as u64 {
let record = Record::Entry {
index: k,
term: entry.term,
command: entry.command.clone(),
};
out.persist.push(record);
self.log.push(entry);
}
}
let new_commit = commit.min(prev_index + count);
if new_commit > self.commit {
self.commit = new_commit;
self.apply(out);
}
out.send.push((
from,
Msg::Appended { term, success: true, match_index: prev_index + count },
));
}
prev_index with the leader’s election term there, and its answer tells the leader where to try next; otherwise it removes a conflicting suffix and appends the new entries. code/bachelor-3/32-project-replicated-store/listings/store/src/raft.rs /// The commitment rule: an entry of the current term held by a majority is
/// committed, and every entry before it with it.
fn advance_leader_commit(&mut self, out: &mut Output) {
for i in (self.commit + 1..=self.log.len() as u64).rev() {
let copies = 1 + self.matched.values().filter(|&&m| m >= i).count();
if self.term_at(i) == self.term && copies >= self.majority() {
self.commit = i;
self.apply(out);
break;
}
}
}
Testing this code on real processes would find few bugs: real networks lose few messages, and crashes happen when the tester decides. The simulator of sim.rs runs three nodes in one process, on a network of its own. Time advances in ticks. A message is delivered 1 to 3 ticks after it is sent, or lost with a given probability; at each tick each node crashes with a given probability, stays down 20 to 59 ticks, and restarts from the records it had forced to its simulated disk, nothing else. The leader proposes a new command every 2 ticks. Every random choice comes from one generator seeded by the run’s number, so a run that fails can be replayed exactly.
for &id in &ids {
let i = id as usize - 1;
if c.rafts[i].is_none() && now >= c.down_until[i] {
if s.forget_votes {
c.disks[i].retain(|r| matches!(r, Record::Entry { .. }));
}
c.rafts[i] = Some(Raft::new(
id,
peers(id),
&c.disks[i],
TIMEOUTS,
rng.next_u64(),
));
c.report.events.push(format!("t={now:<4} node {id} restarts"));
} else if c.rafts[i].is_some() && rng.below(1000) < s.crash_permille {
c.rafts[i] = None; // its volatile state is lost; its disk is not
if s.lose_unsynced {
let keep = c.disks[i].len() - c.last_write[i];
c.disks[i].truncate(keep);
}
c.down_until[i] = now + 20 + rng.below(40) as u32;
c.report.crashes += 1;
c.report.events.push(format!("t={now:<4} node {id} crashes"));
continue;
}
if let Some(raft) = c.rafts[i].as_mut() {
let (was, mut out) = (raft.role == Role::Leader, Output::default());
raft.tick(&mut out);
if now % 2 == 0 && raft.role == Role::Leader {
raft.propose(
format!("SET k{} {}", next_command % 7, next_command),
&mut out,
);
next_command += 1;
}
c.handle(now, id, out, was, &mut rng, s);
}
}
After every step the simulator checks the safety properties of Raft. Election safety: no election term has two leaders. Leader completeness: a node that becomes leader holds every entry already applied anywhere. State machine safety: no index is ever applied with two different entries. At the end of the run, log matching: two logs that agree on the election term at some index agree on everything up to it.
$ ./store trace 3 --ticks 200
t=13 node 1 leads term 1
t=25 node 1 crashes
t=44 node 3 leads term 2
t=68 node 1 restarts
t=107 node 2 crashes
t=159 node 2 restarts
84 entries committed, safety violations: 0
$ ./store sim --runs 1000 --ticks 400 --loss 50 --crash 2
1000 runs of 400 ticks, 3 nodes, 5 % of messages lost:
2217 crashes, 1699 leaders elected, 182137 entries committed
safety violations: 0
A run with no violation proves nothing about the next, but the simulator does catch broken implementations. Two faults can be switched on in it, and crashes made more frequent, 0.5 % per node and tick: a node that loses its vote records at restart, and a crash that loses the records of the node’s last step, as if the node had sent its messages before forcing its log. Out of 2,000 runs, the first breaks safety in 107 and the second in 18, while the correct code breaks it in none (exercise 32.11).
32.4 Milestone 4: three processes
A replica is a process with three kinds of threads. The listener accepts connections and starts a thread for each (Listing 32.2). For each other replica a sender thread owns the connection to it: it receives Raft messages on a channel, writes them, and reconnects when the connection breaks; a message that cannot be written is dropped, which Raft tolerates, since the leader sends again at its next heartbeat. The main loop owns everything else: the Raft node, the map and the log file. Every input reaches it as an event on one channel, so it handles one input at a time and needs no lock.
Raft messages travel as lines of text, as client commands do:
| line | message |
|---|---|
VOTE? t last_index last_term | request for a vote in election term |
VOTE t g | the answer, if granted |
APPEND t prev prev_term commit n | entries after index prev; the next lines are the entries, each term command |
APPENDED t s match | the answer, on success; match is the last index known to agree |
loop {
let mut out = Output::default();
let mut events = Vec::new();
match inbox.recv_timeout(next_tick.saturating_duration_since(Instant::now()))
{
Ok(event) => events.push(event),
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => return Ok(()),
}
if Instant::now() >= next_tick {
// time passes even when events never stop coming
raft.tick(&mut out);
next_tick += cfg.tick;
}
while cfg.batch && events.len() < 256 {
match inbox.try_recv() {
Ok(event) => events.push(event),
Err(_) => break,
}
}
--batch it also takes every other event already waiting, for the measurement at the end of the chapter. code/bachelor-3/32-project-replicated-store/listings/store/src/node.rs for event in events {
match event {
Event::Peer(from, msg) => raft.receive(from, msg, &mut out),
Event::Client(command, reply) => {
let answer = match (&command, raft.role) {
(Command::Status, _) => Some(Reply::Status(
format!("{:?}", raft.role).to_lowercase(),
raft.leader,
)),
(Command::Dump, _) => Some(Reply::Dump(
map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
)),
(_, r) if r != Role::Leader => {
Some(Reply::Redirect(raft.leader))
}
(Command::Get(k), _) => Some(
map.get(k)
.map_or(Reply::NotFound, |v| Reply::Value(v.clone())),
),
_ => {
let index =
raft.propose(command.to_string(), &mut out).unwrap();
pending.insert(index, (raft.term, reply.clone()));
None
}
};
if let Some(a) = answer {
let _ = reply.send(a);
}
}
}
}
pending under the entry’s index; a read is answered at once from the map; a follower answers with the leader it knows. code/bachelor-3/32-project-replicated-store/listings/store/src/node.rsThe election timeouts of a replica are drawn between 15 and 30 ticks of 10 ms, 150 to 300 ms, the interval the Raft paper gives as an example. For the sessions of this chapter the flag --stagger gives replica a timeout of about ms instead, so that replica 1 is the first to stand and the sessions can be rerun with the same leader. Each replica writes to its own directory, node1 to node3, its log file and a file pid holding its process number, which the sessions use to stop it.
$ for n in 1 2 3; do (./store node $n --stagger > node$n.log &); done
$ ./store wait-leader
leader: node 1
$ for n in 1 2 3; do ./store send $n STATUS; done
node 1: STATUS leader 1
node 2: STATUS follower 1
node 3: STATUS follower 1
$ ./store send 3 SET ferry 8h15
node 3: REDIRECT 1
node 1: OK
$ ./store send 2 GET ferry
node 2: REDIRECT 1
node 1: VALUE 8h15
$ ./store caught-up 3
node 3 holds the same 1 keys as the leader, node 1
$ ./store dump 3
node 3: ferry=8h15
$ cat node1.log node2.log node3.log
node 1: up, 0 entries in its log, term 0
node 1: candidate in term 1
node 1: leader in term 1
node 2: up, 0 entries in its log, term 0
node 3: up, 0 entries in its log, term 0
$ kill $(cat node1/pid node2/pid node3/pid)
32.5 Milestone 5: killing the leader
The session of this milestone writes five keys through replica 1 and then kills it with kill -9, which gives the process no chance to do anything more: its threads, its connections and its map vanish, and only its log file remains.
$ for n in 1 2 3; do (./store node $n --stagger > node$n.log &); done
$ ./store wait-leader
leader: node 1
$ for k in a b c d e; do ./store send 1 SET $k 1 > /dev/null; done
$ kill -9 $(cat node1/pid)
$ ./store wait-leader
leader: node 2
$ ./store send 3 GET c
node 3: REDIRECT 2
node 2: VALUE 1
$ ./store send 3 SET f 2
node 3: REDIRECT 2
node 2: OK
$ (./store node 1 --stagger >> node1.log &)
$ ./store caught-up 1
node 1 holds the same 6 keys as the leader, node 2
$ ./store dump 1
node 1: a=1 b=1 c=1 d=1 e=1 f=2
$ cat node1.log node2.log node3.log
node 1: up, 0 entries in its log, term 0
node 1: candidate in term 1
node 1: leader in term 1
node 1: up, 6 entries in its log, term 1
node 2: up, 0 entries in its log, term 0
node 2: candidate in term 2
node 2: leader in term 2
node 3: up, 0 entries in its log, term 0
$ kill $(cat node1/pid node2/pid node3/pid)
NOOP, entry 8 the write of f.None of the five acknowledged writes can be lost. Each was acknowledged only once it was on the log files of a majority, replica 1 and at least one of the others; any new leader needs the vote of one of those two replicas besides its own, and the election restriction makes that replica refuse a candidate whose log lacks the entry. This is leader completeness, recalled above; the session only shows one case of it, and the test kill_the_leader of the crate repeats it with twenty writes spread over the three replicas.
A client whose write was in flight when the leader died is in a different position: its connection breaks, or its reply never comes, and it cannot tell whether its write was committed. The new leader may hold the entry and commit it, or not hold it. When a replica that was leader loses its role, it answers every write still pending with ERR unknown outcome, the only truthful answer; the same happens to a write whose index was later filled by another leader’s entry.
wal.append(&out.persist)?; // on the disk before any message leaves
for (to, msg) in out.send {
let _ = outbox[&to].send(msg);
}
for (index, entry) in out.apply {
let result = apply(&mut map, &entry.command);
if let Some((term, client)) = pending.remove(&index) {
let ok = term == entry.term;
let _ = client.send(if ok {
result
} else {
Reply::Err("unknown outcome".to_string())
});
}
}
if raft.role != role {
role = raft.role;
println!(
"node {}: {} in term {}",
cfg.id,
format!("{role:?}").to_lowercase(),
raft.term
);
if role != Role::Leader {
for (_, (_, client)) in std::mem::take(&mut pending) {
let _ = client.send(Reply::Err("unknown outcome".to_string()));
}
}
}
32.6 Milestone 6: the consistency check
The command store load runs four client threads, each sending 150 random commands on three keys and recording each one as a line: the client, the times at which the request was sent and the reply received, in microseconds on one clock shared by the threads, the key, and the result. A request whose reply never came, or came as an error, is recorded with ? in place of its end and of any result it would have had: it may or may not have taken effect, at any time after it started.
The checker treats each key as a register, a value that a write replaces, a read returns and a delete empties, and searches as in Chapter 13: pick an operation that may come first, that is one that started before every remaining operation with a reply had ended; apply it to the register if its recorded result matches; recurse. It remembers the states it has already refuted, a set of remaining operations with a register value, so that it never explores them twice. Operations without a reply may be left out at the end.
fn step(value: &Option<String>, op: &Op) -> Option<Option<String>> {
match &op.kind {
Kind::Set(v) => Some(Some(v.clone())),
Kind::Get(read) => (read == value).then(|| value.clone()),
Kind::Del(found) => match found {
Some(f) if *f != value.is_some() => None,
_ => Some(None),
},
}
}
fn search(
ops: &[Op],
left: &mut Vec<bool>,
value: Option<String>,
seen: &mut HashSet<(Vec<bool>, Option<String>)>,
) -> bool {
// Done when every operation left lacks a reply: those may never have happened.
if ops.iter().zip(left.iter()).all(|(op, &l)| !l || op.end.is_none()) {
return true;
}
if !seen.insert((left.clone(), value.clone())) {
return false; // this state was already explored and refuted
}
let first_end =
(0..ops.len()).filter(|&i| left[i]).filter_map(|i| ops[i].end).min();
for i in 0..ops.len() {
if !left[i] || ops[i].start > first_end.unwrap() {
continue; // done, or began after an operation that has ended
}
if let Some(next) = step(&value, &ops[i]) {
left[i] = false;
let found = search(ops, left, next, seen);
left[i] = true;
if found {
return true;
}
}
}
false
}
step says how the register changes if the operation takes effect now, or that it cannot, because its result would differ. code/bachelor-3/32-project-replicated-store/listings/store/src/lincheck.rsa, the read of a, the write of b, the read of b, and then the delete, which may also never have happened. The last read may therefore return b or nothing, and the checker accepts both; it refuses a, which was overwritten before that read began.Checking each key on its own is enough, because linearisability is local.
Proposition 32.2 (Locality)
A history of operations on several keys is linearisable if the operations on each key, taken alone, form a linearisable history.
Proof. Facts used: Definition 13.12. Fix for each key a linearisation, an order of its operations that is a correct history of a register and keeps the real-time order. Give each operation the time . Then , and : if some with started after ended, would precede in real time and come before it in the order, so , a contradiction. The times never decrease along the order. Now sort all the operations of all keys by time, and operations of one key with equal times by their place in that key’s order. The result keeps each key’s order, so each key sees a correct register history, and the operations on different keys do not interact. It keeps the real-time order: if ended before started, then . ∎
The session runs the load against three replicas and kills the leader 0.4 seconds into it, then checks the history.
$ for n in 1 2 3; do (./store node $n --stagger > node$n.log &); done
$ ./store wait-leader
leader: node 1
$ (./store load history.txt --clients 4 --ops 150 > load.log &)
$ sleep 0.4; kill -9 $(cat node1/pid)
$ while ! [ -s load.log ]; do sleep 0.1; done
$ cat load.log
600 operations by 4 clients on 3 keys recorded in history.txt
$ ./store wait-leader
leader: node 2
$ ./store check history.txt
600 operations on 3 keys: linearisable: yes
$ wc -l < history.txt
600
$ kill $(cat node2/pid node3/pid)
A history found linearisable shows only that this run did nothing wrong. The store’s reads are in fact not always linearisable: a leader answers a read from its map, and in two situations its map is behind the committed state (exercise 32.7). The Raft paper’s remedy is that a leader must make sure it has not been deposed before it answers a read, by exchanging heartbeats with a majority first; a lease based on heartbeats avoids the exchange but makes safety depend on bounded clock drift. The crate’s tests cover the six milestones:
| test file | what it checks |
|---|---|
lincheck.rs | the protocol printed and parsed back; the checker on hand-made histories, among them that of the figure above, a stale read, and unanswered writes and deletes |
wal_crash.rs | a cut at every byte (Proposition 32.1); every flipped byte stops the replay at its record; the CRC-32 check value |
raft_sim.rs | 2,000 simulated runs with no safety violation; the summary of Output 32.3; both faults caught; the election restriction; a stale read by a deposed leader |
cluster.rs | three processes: the leader killed, every acknowledged write read back from the new leader, the old leader caught up; a history under a kill checked linearisable |
32.7 Measurement
Replication has a price. The command store bench runs 16 clients that send SET commands to the leader for 3 seconds, each waiting for its reply before sending the next, and counts the acknowledged writes. The flag --batch makes the main loop take every event already waiting, up to 256, before it forces the log, so that one sync_all covers the writes of many clients.
$ for b in "" --batch; do (./store node 1 --nodes 1 --base 24340 --dir single $b > single.log &); ./store bench --nodes 1 --base 24340 --clients 16 --seconds 3; kill $(cat single/pid); sleep 0.3; done
1 replica(s), 16 clients, 3 s: 772 writes, 257 writes per second
1 replica(s), 16 clients, 3 s: 4984 writes, 1661 writes per second
$ for n in 1 2 3; do (./store node $n --stagger > node$n.log &); done
$ ./store bench --clients 16 --seconds 3
3 replica(s), 16 clients, 3 s: 463 writes, 154 writes per second
$ kill $(cat node1/pid node2/pid node3/pid); sleep 0.3
$ for n in 1 2 3; do (./store node $n --stagger --batch --dir batch$n > batch$n.log &); done
$ ./store bench --clients 16 --seconds 3
3 replica(s), 16 clients, 3 s: 1225 writes, 408 writes per second
$ kill $(cat batch1/pid batch2/pid batch3/pid)
Without batching each write costs a forced flush of the log at the leader, and with three replicas a second one at a follower before the leader can count a majority: one replica acknowledges about 260 writes a second, three about 150. With batching the writes waiting at the same moment share their flushes, and the gain is large, more than sixfold for one replica and more than twofold for three. Exercise 32.12 builds a model of these numbers.
In practice
Three things a store for real use needs are left out of this one. Pipelining: the leader may send new entries to a follower before the previous ones are acknowledged, so that the network and the disks work at once. A bound on the log, which here grows forever: a replica can write a snapshot of its map from time to time and delete the log before it, and send the snapshot to a follower too far behind (exercise 32.9 only compacts the file). Changes to the set of replicas, which Chapter 26 mentions: adding a replica must never let the old and the new sets form two majorities at once.
32.8 Exercises
Exercise 32.1 ★
Write the bytes a client sends to set the key ferry to 8h15, and count them. Then give the reply of the server to each of the lines SET a=b 1, SET a b=c, GET a b, DEL ␣ ␣a (two spaces), status, and to the three bytes GET sent with no newline just before the client closes the connection.
Solution
Solution of Exercise 32.1.
The client sends SET ferry 8h15 followed by a newline: bytes. The replies: SET a=b 1 gets ERR a key may not contain =; SET a b=c gets OK, since only keys are restricted (DUMP prints a=b=c, and a reader that splits at the first = gets the pair back); GET a b gets ERR GET takes one key; DEL with two spaces before a is DEL a, because the parser drops empty words, and gets OK here, since a was just set; status gets ERR unknown command status, because commands are case-sensitive. The three bytes GET wait in the server’s buffer: read_line cannot know whether more of the line will come until a newline or the end of the stream arrives. When the client closes, read_line returns the partial line, which is parsed and answered with ERR GET takes one key, written to a connection nobody reads. The test exercise_1_lines checks each case.
Exercise 32.2 ★
The replica of Output 32.2 crashes when exactly 100 bytes of its log file have reached the disk. Which records does it find at restart, how long is the file after Wal::open, and which value of bridge can a client read? Which clients may have received OK?
Solution
Solution of Exercise 32.2.
The records are 21, 29, 40 and 42 bytes long and end at offsets 21, 50, 90 and 132. At 100 bytes, three records are whole: the vote, the NOOP and SET bridge open; the fourth has its 8-byte header and 2 bytes of its 34-byte payload. By Proposition 32.1 the replay returns the three, and Wal::open cuts the file to 90 bytes. A client reads VALUE open. The client of SET bridge open may have received OK: its record was forced before the next one was written, and the reply was sent just after; whether it left before the crash depends on the timing. The client of SET bridge closed cannot have received OK, which is sent only after sync_all returns on the whole record. The test exercise_2_a_crash_after_100_bytes checks the sizes and the replay.
Exercise 32.3 ★
Three replicas hold logs whose entries have the election terms S1: 1, 1, 2; S2: 1, 1, 3; S3: 1, 1. All three are in election term 3 and none has voted in it. Which of them can win election term 4? If S1 wins, what happens to the third entry of S2, and why does that lose no acknowledged write?
Solution
Solution of Exercise 32.3.
A voter compares the pair (election term of the last entry, length): S1 has , S2 has , S3 has . A candidate needs two votes, its own and one more. S1 gets S3’s vote, since , and not S2’s: it can win. S2 gets both: it can win. S3 gets neither: it cannot. If S1 wins election term 4, its first append to S2 carries its third entry, of election term 2; S2 finds election term 3 at that index, removes its entry and takes S1’s. That entry of election term 3 was held by S2 alone, one replica out of three, so it was never committed, and no client was told OK for it. The test exercise_3_who_can_lead replays the six requests for a vote and finds the winners S1 and S2.
Exercise 32.4 ★
Three replicas are started with --stagger, and the session runs store send 1 SET x 1, kills replica 2 with kill -9, runs store send 3 SET y 2, kills replica 3 the same way, and runs store send 1 SET z 3, store send 1 GET x and store send 1 STATUS. Predict every line the commands print, and explain the third one.
Solution
Solution of Exercise 32.4.
$ for n in 1 2 3; do (./store node $n --stagger > node$n.log &); done
$ ./store wait-leader
leader: node 1
$ ./store send 1 SET x 1
node 1: OK
$ kill -9 $(cat node2/pid)
$ ./store send 3 SET y 2
node 3: REDIRECT 1
node 1: OK
$ kill -9 $(cat node3/pid)
$ ./store send 1 SET z 3
node 1: no answer
$ ./store send 1 GET x
node 1: VALUE 1
$ ./store send 1 STATUS
node 1: STATUS leader 1
$ kill $(cat node1/pid)
With replica 2 dead, replicas 1 and 3 are still a majority, so SET y 2 is redirected and committed. With replica 3 dead too, replica 1 is alone. It never hears a larger election term, so it still believes it leads: it appends SET z 3 and forces it, but no other replica answers, and the entry is never committed. The client gives up after its read timeout of 2 seconds and prints no answer; the write stays pending, and the client cannot tell whether it will ever take effect. The read is still answered from the map, and STATUS still says leader: a replica cannot tell that it is alone from what it receives, only from what it does not receive.
Exercise 32.5 ★★
A first version of decode_all trusted the length field: it took the bytes from the end of the header to min(at + 8 + len, bytes.len()) as the payload, without checking the checksum. Cut the log file of the two writes SET bridge open and SET bridge closed 5 bytes before its end and show what this version replays. Fix it, and test the fix at every cut.
Solution
Solution of Exercise 32.5.
The file holds two records of and bytes, 82 in all; cut at 77, the second record has its header, whose length says 34, but only 29 bytes of payload. The trusting version takes those 29 bytes as the payload, so the command is its last bytes, SET bridge c: the replica replays a write that no client ever made, and GET bridge returns c. The fix is the code of Listing 32.3: take the payload only if all len bytes are there, and accept it only if its checksum matches. The test ex5_torn_test.rs shows the invented value with the trusting version, then cuts the file at each of its 83 positions and checks that the fixed decoder returns a prefix of the records and the length of their encodings; a flipped bit in the last command, which no length check can see, stops the replay at that record.
Exercise 32.6 ★★
Add a command CAS key old new, which sets key to new if it holds old, replies OK if it did, VALUE v with the value found if it did not, and NOTFOUND if the key is absent. Should the leader decide it when it receives it, or when it applies it? Implement the decision and test that every replica gives the same answers on a log of four commands.
Solution
Solution of Exercise 32.6.
When it applies it. On receipt, the leader’s map does not yet contain the writes before the CAS in the log that are not committed yet, so the comparison would be made against the wrong state; and the followers, which see only the log, must reach the same answer from it. So CAS is proposed like SET, and its result is computed by apply, from the map as it is just before the entry, in log order:
- value equal to
old: setnew, replyOK; - another value : reply
VALUE v; - no value: reply
NOTFOUND.
The replica that proposed it sends that reply to the client, as for any write. The test ex6_cas_test.rs applies the log SET seat free, CAS seat free ada, CAS seat free bob, CAS desk free ada on three replicas, which all answer OK, OK, VALUE ada, NOTFOUND and end with seat holding ada; a CAS with two words is refused by the parser.
Exercise 32.7 ★★
Show two runs in which a GET answered by the store returns a value that a history cannot linearise: one with a leader cut off from the two other replicas, one with a leader just elected. Then describe a read index: what the leader records on receiving a GET, what it waits for, and why each of the two runs is then answered correctly or not at all.
Solution
Solution of Exercise 32.7.
A leader cut off. Replica 1 leads election term 1, and a is 1. The network cuts replica 1 off; replicas 2 and 3 elect replica 2 in election term 2, which commits SET a 2 and replies OK. A client then sends GET a to replica 1, which has heard of no larger election term, still leads in its own eyes, and answers VALUE 1. The read started after a write of 2 had returned, so every linearisation places it after that write, and it should return 2: the history is not linearisable. The test a_deposed_leader_reads_stale builds this run.
A leader just elected. Replica 1 commits SET a 2 with replica 2, replies OK, and crashes before its next append tells replica 2 that the entry is committed. Replica 2 is elected (its log is as up to date as replica 3’s or more), but its commit index is still below that entry, so its map still has the old value, and a GET a answered at once returns it.
A read index. On a GET, the leader waits until an entry of its own election term is committed, its NOOP, then records its commit index as the read’s index. It sends an append to every follower and waits for a majority to answer it in its current election term, which shows that no other leader had been elected when the read arrived. It then waits until it has applied index , and answers from its map. Every write acknowledged before the read arrived is committed, so its index is at most , and the answer includes it. In the first run, replica 1’s appends reach nobody, and the GET gets no answer; the client retries elsewhere and reaches replica 2. In the second, replica 2 answers only after its NOOP is committed, which commits SET a 2 with it, and it returns 2. This is the check of the Raft paper.
Exercise 32.8 ★★
With three replicas, no loss and no other traffic, count the Raft messages from the moment the leader proposes a write to the moment it applies it, and the messages from which the followers learn that the write is committed. What are the counts for replicas?
Solution
Solution of Exercise 32.8.
The leader forces the entry and sends one append to each follower: 2 messages. Each follower forces it and answers: 2 more. The first answer already gives a majority, the leader and one follower, so the leader commits and applies the entry: 4 messages, of which the leader needed 3 before committing. The followers learn that the entry is committed from the commit index carried by the leader’s next append, a heartbeat or the next write, so this costs no message of its own. The test messages_per_write counts the messages, and finds the leader’s commit index at 2 and the followers’ still at 1. With replicas: appends and answers, messages, and the leader commits after answers. Add the client’s request and reply: 2 more.
Exercise 32.9 ★★
The log file only grows: every vote record stays, and so does every entry later replaced by a different one. Write a function that compacts a list of records into the shortest list that replays to the same election term, vote and log, and test that the two replay to the same state on a log that starts with an empty entry at index 1, then has 20 election terms in which each term writes a vote record and five entries from index on. How many of its 121 records remain?
Solution
Solution of Exercise 32.9.
Replay the records into the state they describe, the election term, the vote and the log, then write that state back: one vote record, then one entry record per entry of the log, with indices . Replaying the result gives the same election term and vote (the only vote record) and the same log (each entry record extends the log by one). In the test’s log, the empty entry holds index 1, the last term writes indices 40 to 44, and the entries at indices 2 to 39 are the last ones written there, so the log has 44 entries and the compacted file 45 records out of 121, less than half the bytes. The test ex9_compact_test.rs checks that both replay to the same state. In a replica the compacted file must replace the old one in a single step, so that a crash at any moment leaves one of the two files whole, never a mix.
Exercise 32.10 ★★★
Prove that the search of Listing 32.13 returns true if and only if the history of the key has a linearisation from which some operations without a reply have been removed. Prove first that an operation can be the first of such a linearisation only if it started before every operation with a reply had ended, then that remembering refuted states changes no result.
Solution
Solution of Exercise 32.10.
Facts used: Definition 13.12; an operation without a reply has no end, so no operation follows it in real time. Call a solution of a set of remaining operations from a value an order of a subset of that contains every operation of with a reply, keeps the real-time order, and is a correct register history starting from . The search is called with all the operations and the empty register, and must return true exactly when a solution exists. (Reads without a reply were removed before: they change nothing, and their result is unknown.)
The first operation. If comes first in a solution, then for every with a reply: otherwise ended before started, must come before it, and is in the solution, since it has a reply. Conversely, if satisfies this, placing first breaks no real-time constraint with any operation of . So the operations the search tries, those not skipped, are exactly the possible first ones.
Without the memory, by induction on . If every operation of lacks a reply, the empty order is a solution and the search returns true. Otherwise every solution is non-empty. If the search returns true, it chose a possible first whose step from succeeded, giving , and found a solution of from ; putting in front gives a solution of from . If a solution exists, let be its first operation: it is a possible first, step succeeds on it, and the rest is a solution of from , so by induction the call on returns true, and the search does too.
The memory. The result of a call depends only on the pair (remaining set, value), since the operations are fixed. Each call removes one operation, so a pair cannot reappear inside its own call. When a pair is met a second time, its first call has returned: if it had returned true, the whole search would have returned true at once, and the second meeting would not occur; so it returned false, and returning false again is correct.
Exercise 32.11 ★★★
The simulator’s first fault restarts a node without its vote records; the second loses, at a crash, the records of the node’s last step, after its messages were sent. For each, explain which safety property breaks and how, and construct a short run that breaks it. Of 2,000 runs with 5 % loss and 0.5 % crashes per node and tick, the first fault breaks safety in 107 runs, 106 of them first through election safety, and the second in 18 runs, 17 of them first through leader completeness. Why does each fault break that property most often?
Solution
Solution of Exercise 32.11.
Lost vote records. The vote records hold the election term as well as the vote, so the restarted node is back in election term 0 with no vote. It can vote a second time in an election term in which it has already voted, and two candidates can then each count a majority in the same election term. A short run: node 1 leads election term 1 and writes entries; all three nodes crash and restart without their vote records; whichever wins the next election leads election term 1 again, with a log that may differ from the first leadership’s at the same indices, so the basis of log matching, one entry per index and election term, is gone. Election safety is the property that the checker sees break, and it breaks first in 106 runs out of 107. Every election after such restarts reuses election term numbers that were already used, and the checker notices at the first leader elected; the other properties need a later, more particular sequence of events.
Records lost after sending. A follower appends an entry, sends its success, and crashes before the record is on its disk. The leader counts it, commits the entry and applies it, then crashes. The follower restarts without the entry, and it and the third node, which never received it, form a majority: one of them is elected with the other’s vote, and the new leader lacks an applied entry. That is leader completeness, which breaks first in 17 runs out of 18, and then state machine safety, when the new leader’s own entry is applied at the same index. Followers write an entry record in almost every step, and a vote record only at elections, so the lost records are almost always entries. The store’s main loop rules this fault out by forcing out.persist before the first message leaves (Listing 32.12). The test faults_are_caught checks the counts and the first seed of each fault, 21 and 25, and that the correct code breaks nothing in the same 2,000 runs.
Exercise 32.12 ★★★
From Output 32.7, estimate the time of one forced flush on the author’s laptop. Build a model of the four numbers, with the flush time and the number of writes waiting when the main loop takes its events, and say what bounds the gain of batching with 16 clients. Why is the gain smaller with three replicas than with one?
Solution
Solution of Exercise 32.12.
With one replica and no batching, each write waits for its own flush, and the main loop does one at a time. The time of a flush is then about s, so ms; the rest of the work, parsing and loopback messages, is small beside it.
The model. If the loop finds writes waiting each time it takes its events, it acknowledges writes per flush, about per second. With batching, the 1,661 writes per second give . The gain is bounded by the number of clients: each client has at most one write outstanding, so , and the throughput is at most writes per second. It stays far below, because a client is not waiting in the queue while its reply travels back and its next request travels in. The same count follows from Little’s law: with 16 clients and 1,661 writes per second, a write takes ms, about , from the client’s sending to its receiving.
Three replicas. Each write needs two flushes in series, the leader’s and then a follower’s, plus two message hops. Without batching, the model predicts at least writes per second. The measured 154 is above it, because the leader forces the next entry while a follower forces the previous one. With batching, a write takes ms, about four times the time with one replica, where the two flushes in series only explain twice. The rest comes from the setup: the three processes share one disk, so the followers’ flushes and the leader’s wait for one another. On three machines each flush would have a disk of its own. The bench does not record the flush times of each process, so this explanation is not measured here.