Correctness

Raft is easy to get almost right, and an almost-right consensus protocol loses data in the one interleaving nobody tested. clusterio checks itself in layers, from the model checker down to real processes on a real network. The specification is not a separate document: it is written on the code that runs, so what is checked is what runs.

1. The node is its own specification#

clusterio/raft.py holds Node, the Raft server that runs, written with Temporal Typing. Its fields are its state and its methods are its actions, and clauses on both say what each state and each step must keep:

python
@spec(
    log_in_term_order=Invariant(lambda s: all(t <= s.term for t in s.terms) and ...),
    leaders_lead=Invariant(lambda s: (s.role == "leader") == (s.leader == s.id)),
    one_vote_per_term=ActionInvariant(
        lambda s: implies(prime(s.term) == s.term and s.voted_for != NONE, prime(s.voted_for) == s.voted_for)
    ),
    leaders_commit_by_count_only_their_own_term=ActionInvariant(...),
    ...
)
@dataclass
class Node:
    id: Constant[str]
    term: State[int] = 0
    terms: State[list[int]] = field(default_factory=list)
    ...

    def receive_append_entries(self, term, source, prev_log_index, ...) -> Annotated[
        list[Message],
        Requires(lambda s, term, ...: well_formed(...) and keeps_committed(...)),
        # Figure 2: reply false if term < currentTerm, and change nothing.
        Action(lambda s, term, ...: implies(term < s.term, prime(s.terms) == s.terms and ...)),
    ]:
        ...

Tanny checks these bodies, the code that runs, against these clauses: it delivers every message a model's domains give, in every order, from every reachable state, and fails with the steps that lead to a state or step that breaks one. The node does no I/O and keeps no time, so nothing it does is out of the checker's reach; a Replica stores what it decides before sending what it says, and calls timeout and heartbeat when their time comes.

ModelBoundsStatesRun by
node_models.of_threea node of three, terms ≤ 2, logs ≤ 3 entries21,910make spec
node_models.alonea node alone, terms ≤ 3, logs ≤ 4 entries29make spec

A node alone cannot know what the rest of the cluster guarantees, so its actions Require it: messages are well formed, as a leader sends them, and no leader contradicts an entry the node counted committed. The second is Leader Completeness, which the model of a cluster checks.

2. A cluster is model-checked against Raft's safety properties#

Raft's decisions are pure functions over integers at the top of raft.py, the rules of Figure 2 of the Raft paper, and the node makes each decision with them:

python
def grant_vote(term, current_term, log_ok, free):
    """Whether to vote for a candidate; free says I have not voted for another in this term."""
    return term == current_term and log_ok and free

def new_commit_index(agreed, agreed_term, current_term, commit_index):
    """A leader counts replicas only of an entry of its own term (§5.4.2)."""
    return agreed if agreed > commit_index and agreed_term == current_term else commit_index

RaftSpec models a whole cluster with the same functions: every server, the actions that change them (time out, request a vote, append entries, crash and restart, ...) and a network that loses, repeats, delays and reorders messages. It states the five safety properties of the paper's Figure 3, each as its own invariant:

PropertyRaftSpec invariant
Election Safety: at most one leader can be elected in a given termelection_safety
Leader Append-Only: a leader never overwrites or deletes entries in its logleader_append_only (an action invariant)
Log Matching: if two logs contain an entry with the same index and term, the logs are identical up to that indexlog_matching
Leader Completeness: an entry committed in a term is in the logs of the leaders of all later termsleader_completeness
State Machine Safety: no two servers apply different entries at the same indexstate_machine_safety

Two ghost variables keep the history the properties speak of: who was elected in each term, and which entry each server counted as committed, in which term.

ModelBoundsStatesRun by
two_servers2 servers, terms ≤ 3, logs ≤ 2 entries, ≤ 8 messages1,085,393make spec, on every change
three_servers3 servers, terms ≤ 2, logs ≤ 1 entry, ≤ 8 messages772,417make spec-deep, before a release
two_servers_ten_messages2 servers, terms ≤ 3, logs ≤ 2 entries, ≤ 10 messages15,420,471make spec-deep

3. Running nodes are checked against the same clauses#

tests/test_raft.py runs real nodes, with real SQLite stores, on a simulated network that loses, repeats and reorders messages, while nodes crash and restart. After every step of each of 240 seeded runs over clusters of 1, 2, 3 and 5 nodes it checks:

  • every clause declared on Node, read from its source and evaluated on each running node (tests/clauses.py);
  • the five safety properties, keeping the history they need;
  • that what each node stored is what it decided, so a restart resumes it.

Then it heals the network and checks that the cluster commits again. A scripted test reproduces the paper's Figure 8, where a leader must not commit an earlier term's entry by counting replicas.

4. The checks are checked#

tests/mutants.py plants known Raft bugs, one at a time, in the decision functions and in the node's bodies: vote twice in a term, vote for a stale log, commit an entry of an earlier term, follow the leader's commit index past what matched, commit without a majority, take half for a majority, append without the log check, keep a conflicting entry, forget a vote given, truncate a log's terms but not its values, follow a leader of an older term, back up one entry at a time after a rejection. make mutants fails unless the simulation or Tanny catches every one. The fault tests of the next section, alone, catch nine of the twelve; the three they miss need exact interleavings that the simulation and the model checker find.

5. Real clusters under faults, checked as Jepsen checks databases#

tests/test_faults.py runs three nodes over TCP while client threads on every node read, write and compare-and-set keys, and a nemesis partitions the network, isolates and crashes nodes, and drops, delays and repeats messages. Each operation's invocation, completion and result go into a history:

  • the history of each key, of reads, writes and compare-and-sets in transactions and of local reads after sync(), must be linearizable, which tests/linearizable.py decides by the search of Wing and Gong, counting an operation that timed out as one that may or may not have taken effect; the checker itself is tested against brute force on random histories;
  • every acknowledged append must be in the final list, and none twice;
  • after healing, every node must commit again and reach the same state.

This found a bug that no safety check could: a follower far behind took one round trip per entry to catch up, as the paper's basic rule has it. Followers now say where their log may match, as §5.3 suggests, and a regression test counts the round trips.

tests/test_durability.py runs three nodes as processes that write as fast as they can while one after another is killed with SIGKILL and restarted: of about 10,000 writes acknowledged in a run, none may be lost or applied twice. Twenty-four threads across three nodes increment one counter through transactions, and the count must be exact.

tests/test_wire.py feeds a node random and malformed messages: each is either refused, leaving the node unchanged, or accepted, keeping every clause of raft.Node. Garbage on a real node's port, and nodes configured with other peers, are refused. A malformed log entry is refused by the leader, and skipped alike by every node that finds one; no append-entries frame outgrows the network's limit, however large the entries.

6. The API is tested against Python#

Dict, List, Set and Queue run long random sequences of operations next to a dict, list, set and queue.Queue and must agree after each one, exceptions included; Lock, Semaphore, Event and Barrier are checked against their threading namesakes the same way. Real clusters over TCP are tested for replication, failover, restarts, every coordination type across nodes, and clusterio run with several processes. Every Python example in the README and in these docs runs in the tests.

7. Types and lint#

ty checks the types of the library, and ruff its style.

Running the checks#

sh
make check      # ruff, ty, the model check, the tests: before every push
make mutants    # each planted bug must be caught
make spec-deep  # larger models: before a release

What is not checked yet#

  • Liveness: that a cluster with a stable majority elects a leader and commits. The simulation's heal step and the fault tests' convergence test it; the model checker does not.
  • That a cluster of Nodes refines RaftSpec: the two share their decisions, and the simulation checks the five properties on running nodes, but the model checker does not yet run the node's bodies across a cluster.
  • The state machine above the log is tested, not model-checked: transactions, and the coordination types and their leases.
  • Larger models, and checking recorded traces of the node against the specification.