13-03

Chapter 13 · Distributed systems, honestly

Leader election, simplified

  • 42 min core
  • Core track
  • Skills: intent, hostile-env

00Recall

One card from 13-02 (why overlap alone is not enough), one from 13-01 (why a yes vote blocks) and one from 09-01 (the prefix judge).

13-02-a from Agree on one value

Two majorities of the same acceptors always share a member. Why is that not enough to keep two ballots from choosing different values?

Show answer

The shared acceptor's old vote must change what the new leader proposes. Without the rule that the leader adopts its quorum's newest vote, nobody listens to it.

13-01-a from 2PC and the coordinator crash

Why may a two-phase commit participant that voted yes not abort when the coordinator goes quiet?

Show answer

The coordinator may already have decided to commit and told another participant. Its yes vote was a promise to follow the decision, so it must wait.

09-01-a from The prefix judge

What makes a property a safety property, and what makes it a liveness property?

Show answer

Safety: every violating behavior has a finite prefix that already violates it, whatever comes next. Liveness: every finite prefix can still be continued into a behavior that satisfies it.

Skip recall Recall is never required.

01Commit

The last lesson left one problem open: two leaders starting newer and newer ballots can block each other for ever. So real systems first elect one leader, and let it run the show until it fails.

specs/LeaderElection.tla is the election in its simplest honest form. Time is cut into numbered terms. A server that has heard nothing for too long starts the next term as a candidate and votes for itself. Every server votes at most once per term, and a newer term wipes its old vote. A candidate with votes from a majority becomes the leader of its term. A vote is delivered in the step that casts it; a lost vote is a vote never cast, which the model already allows.

The claim every design doc makes is "there is only ever one leader":

TLA+
AtMostOneLeader is defined as
    for all s, t in Servers : role[s] = "leader" and role[t] = "leader" implies s = t

Commit a

LeaderElection.global.cfg checks AtMostOneLeader with three servers and at most two terms. What does TLC report?

  1. No violation. One vote per server per term and majorities that overlap leave room for only one leader.
  2. A violation: two servers are leaders at the same time.
  3. A violation, but only because two terms is too small a model to be realistic.

Answer A violation: two servers are leaders at the same time.

Commit b

The protocol's own claim is AtMostOneLeaderPerTerm: never two leaders of the same term. Same model. Does TLC find a violation?

  1. No violation, and the last term does get a leader.
  2. Yes. A server that votes in term 1 and again in term 2 can help two leaders of the same term.
  3. No violation, but only because no server ever times out twice.

Answer No violation, and the last term does get a leader.

02Lab

shell
./tla check chapters/13-distributed-systems/specs/LeaderElection.global.cfg
Expected output 13-distributed-systems/specs/LeaderElection.global
13-distributed-systems/specs/LeaderElection.global  LeaderElection.global.cfg  (Servers={s1, s2, s3}, MaxTerm=2)
parse ok
model check: invariant AtMostOneLeader violated; trace has 7 states (6 steps); 243 distinct states
expected outcome met: violation AtMostOneLeader
trace (changed variables only; ./tla trace --full shows all):
  1  Init          term = (s1 :> 0 @@ s2 :> 0 @@ s3 :> 0), role = (s1 :> "follower" @@ s2 :> "follower" @@ s3 :> "follower"), votedFor = (s1 :> "none" @@ s2 :> "none" @@ s3 :> "none"), votes = (s1 :> {} @@ s2 :> {} @@ s3 :> {})
  2  Timeout       term: (s1 :> 0 @@ s2 :> 0 @@ s3 :> 0) -> (s1 :> 1 @@ s2 :> 0 @@ s3 :> 0), role: (s1 :> "follower" @@ s2 :> "follower" @@ s3 :> "follower") -> (s1 :> "candidate" @@ s2 :> "follower" @@ s3 :> "follower"), votedFor: (s1 :> "none" @@ s2 :> "none" @@ s3 :> "none") -> (s1 :> s1 @@ s2 :> "none" @@ s3 :> "none"), votes: (s1 :> {} @@ s2 :> {} @@ s3 :> {}) -> (s1 :> {s1} @@ s2 :> {} @@ s3 :> {})
  3  GrantVote     term: (s1 :> 1 @@ s2 :> 0 @@ s3 :> 0) -> (s1 :> 1 @@ s2 :> 1 @@ s3 :> 0), votedFor: (s1 :> s1 @@ s2 :> "none" @@ s3 :> "none") -> (s1 :> s1 @@ s2 :> s1 @@ s3 :> "none"), votes: (s1 :> {s1} @@ s2 :> {} @@ s3 :> {}) -> (s1 :> {s1, s2} @@ s2 :> {} @@ s3 :> {})
  4  Timeout       term: (s1 :> 1 @@ s2 :> 1 @@ s3 :> 0) -> (s1 :> 1 @@ s2 :> 2 @@ s3 :> 0), role: (s1 :> "candidate" @@ s2 :> "follower" @@ s3 :> "follower") -> (s1 :> "candidate" @@ s2 :> "candidate" @@ s3 :> "follower"), votedFor: (s1 :> s1 @@ s2 :> s1 @@ s3 :> "none") -> (s1 :> s1 @@ s2 :> s2 @@ s3 :> "none"), votes: (s1 :> {s1, s2} @@ s2 :> {} @@ s3 :> {}) -> (s1 :> {s1, s2} @@ s2 :> {s2} @@ s3 :> {})
  5  GrantVote     term: (s1 :> 1 @@ s2 :> 2 @@ s3 :> 0) -> (s1 :> 1 @@ s2 :> 2 @@ s3 :> 2), votedFor: (s1 :> s1 @@ s2 :> s2 @@ s3 :> "none") -> (s1 :> s1 @@ s2 :> s2 @@ s3 :> s2), votes: (s1 :> {s1, s2} @@ s2 :> {s2} @@ s3 :> {}) -> (s1 :> {s1, s2} @@ s2 :> {s2, s3} @@ s3 :> {})
  6  BecomeLeader  role: (s1 :> "candidate" @@ s2 :> "candidate" @@ s3 :> "follower") -> (s1 :> "leader" @@ s2 :> "candidate" @@ s3 :> "follower")
  7  BecomeLeader  role: (s1 :> "leader" @@ s2 :> "candidate" @@ s3 :> "follower") -> (s1 :> "leader" @@ s2 :> "leader" @@ s3 :> "follower")

Reveal for commit a

AtMostOneLeader is violated, with a trace of 7 states. In the last state two servers are leaders, and they lead different terms: the leader of the older term has not heard that a newer term has begun.

shell
./tla check chapters/13-distributed-systems/specs/LeaderElection.cfg
Expected output 13-distributed-systems/specs/LeaderElection
13-distributed-systems/specs/LeaderElection  LeaderElection.cfg  (Servers={s1, s2, s3}, MaxTerm=2)
parse ok
model check: no violation found in 282 distinct states (784 generated, depth 8)
expected outcome met: pass
coverage: all 3 actions fired
witness LeaderInLastTerm reached (trace of 5 states)

Reveal for commit b

No violation of AtMostOneLeaderPerTerm in 282 distinct states, every action fires, and LeaderInLastTerm is reached. Two leaders can exist at once, but never two of the same term.

03Reason

If you picked "no violation", you made the argument the protocol makes, and applied it to a claim the protocol does not make. Inside one term the argument is airtight. Across terms it says nothing.

Read the end of the trace. One server won the older term and is still a leader. Another server, which had voted for it but never learned that it won, timed out, started a newer term, and won it with a different majority. Both are leaders. Neither is wrong about its own term.

Write something before openingwhat would it take for the leader of the older term to find out it has been replaced?

A message from someone in the newer term. In this model, the only such contact is being asked for a vote: GrantVote moves the voter to the candidate's term and makes it a follower. In a real system it is a heartbeat or a reply carrying a higher term number. Until that message arrives, the old leader has no way to know. A network partition can delay it as long as it likes.

So without any bound on delay or clock drift, no protocol that can replace a leader it cannot reach can promise "at most one leader". What such a protocol can promise is per term, and it is the property Raft-style protocols rely on:

TLA+
AtMostOneLeaderPerTerm is defined as
    for all s, t in Servers :
        (role[s] = "leader" and role[t] = "leader" and term[s] = term[t]) implies s = t

Then how does a system with two leaders at once stay correct? By making the old leader harmless. Everything a leader does is stamped with its term, and a server that has seen a newer term refuses anything stamped with an older one. The old leader can still try; it cannot get a majority to agree. Lesson 13-05 builds on this: a follower that has seen a newer term refuses an older leader's entries, and a leader commits only entries of its own term. And if you truly need "only one acting leader at a time", for example to drive a disk that cannot take two writers, you need a bound on time, which is the next lesson.

Write something before openingin the trace, a candidate still counts a vote from a server that has since moved to a newer term. Is that a bug?

No. That vote was cast in the candidate's term, and it counts for that term only. Whether the voter has moved on does not change what happened in the old term. A server's vote count is a fact about its own term, which is why the per-term property needs nothing more.

Write something before openinga newer term wipes a server's vote. Why is that safe, when the Core exercise says forgetting a vote on restart is not?

A vote counts for one term only. When a server moves to a newer term, nobody in that term has received its vote yet, so it has one fresh vote to give, as every server does. Forgetting on restart is different: the term has not changed, the old vote may already be counted, and a second vote in the same term is the double vote that AtMostOneLeaderPerTerm cannot survive.

Write something before openingno liveness was checked. Can this election go on for ever without a leader?

In the protocol, yes, even if this bounded model runs out of terms first. Three servers can time out into the same term, each vote for itself, and nobody gets a majority; then all three time out again into the next term. Weak fairness does not help, and neither does strong fairness on BecomeLeader: in that loop it is never enabled. Strong fairness on granting votes would break the loop, but only by assuming that the split vote resolves. Raft's answer is timing, not logic: each server waits a random time before it starts an election, so one usually starts first and wins. That is a claim about probability, which TLC does not check.

This is the skill the chapter's goals call stating intent. The first claim was what people say. The second is what the system can do. A model that checks the first one fails, and the failure tells you which sentence in the design doc to rewrite.

04In your editor

Check this lesson's exercises, and the two models above, with:

shell
./tla check 13-03

When you write a property about leaders, first ask "at what time, and according to whom?" A property that silently assumes everyone sees the same moment is a property about a system without a network.

When an election trace fails, write each server's term and role in a row per state, and mark every vote with the term it was cast in. Two leaders of different terms are the protocol working. Two leaders of the same term mean some server voted twice in that term; find that vote.

The AI item 13-ai1 is an agent's refactor of GrantVote, and a message that says nothing changed. Run it with ./tla check 13-ai1 after this lesson.

05Practice

Warm-up. Candidates collect votes and nobody takes office. Write BecomeLeader, then try the threshold a tired engineer writes.

Core. Servers crash and restart. Decide what a server must keep on disk, write Restart, and write the model the cfg's checks run on.

13-03-ex1Warm-up5 min

13-03-ex1 · Count the votes

Tier: warm-up. Time: about 5 minutes.

LeaderElection.tla is the lesson's election with the last step missing: candidates collect votes, and nobody ever takes office.

  1. Run ./tla check 13-03-ex1. Both cfgs pass with a coverage gap. AtMostOneLeaderPerTerm holds in a cluster that never has a leader. That is the cheapest way to satisfy it.
  2. Fill gap g1 in LeaderElection.tla: a candidate whose votes come from a majority of the servers becomes the leader of its term. The module already defines Majority.
  3. Run the check until both cfgs pass with full coverage and LeaderInLastTerm reached.

LeaderElection.grader.cfg is the course's check of your BecomeLeader, with four servers: with three, "at least half" and "a majority" are the same number of votes. Leave it as it is.

Then try the threshold a tired engineer writes at the end of a long day: at least half the servers, rounded down. Predict the trace before you run it.

The lesson's specs/LeaderElection.tla has a BecomeLeader of its own; write yours before you open it.

Hints: HINTS.md, under "13-03-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/13-distributed-systems/exercises/03-ex1-count-the-votes/; open it after you have a passing answer of your own.

Both cfgs must meet their goal, "goal met: pass". If TLC finds no violation but an action never fires or a witness is not reached, ./tla prints "goal not met" and exits with code 1.

Done when: ./tla check 13-03-ex1 prints "goal met: pass".

./tla check 13-03-ex1

Repo chapters/13-distributed-systems/exercises/03-ex1-count-the-votes/

Hints

Hint 1

Who may take office? Read Majority and decide what it takes as its argument, and what role the server must have first.

Hint 2

Two guards: the server is a candidate, and the votes it has collected form a majority. Taking office changes only one variable.

Hint 3 (nearly the answer)

Guard on role[s] being "candidate" and on Majority of the right set of servers: which variable holds the servers that voted for s? Set role[s] to "leader" with EXCEPT, and leave the other variables unchanged.

13-03-ex2Core8 min

13-03-ex2 · Restart from disk

Tier: core. Time: about 8 minutes.

Servers crash. LeaderElection.tla now has a Restart(s) action, a crash followed at once by a restart, and it is a placeholder. The comments on the variables say which ones a server keeps on disk and which ones live only in memory.

  1. Run ./tla check 13-03-ex2. The grader passes with a coverage gap: Restart never fires. Your cfg stops with an error: a constant has no value.
  2. Fill gap g1 in LeaderElection.tla: what a restarted server still knows, and what it has forgotten. It comes back as a follower.
  3. Fill gap g1 in LeaderElection.cfg. Its checks are fixed below the gap; you write the model: the behavior spec, three servers, two terms, and your deadlock setting, with a comment that gives a reason about the system.
  4. Run the check until both cfgs pass with full coverage and every witness reached.

LeaderElection.grader.cfg is the course's check of your Restart. Beside AtMostOneLeaderPerTerm it checks FollowersHoldNoVotes, so a restart that keeps the votes it collected fails there. Leave it as it is. Then make the cheap mistake on purpose: let a restarted server forget whom it voted for. Read the trace and count how many times one server votes in one term.

Hints: HINTS.md, under "13-03-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/13-distributed-systems/exercises/03-ex2-restart-from-disk/; open it after you have a passing answer of your own.

Both cfgs must meet their goal, "goal met: pass". If TLC finds no violation but an action never fires or a witness is not reached, ./tla prints "goal not met" and exits with code 1.

Done when: ./tla check 13-03-ex2 prints "goal met: pass".

./tla check 13-03-ex2

Repo chapters/13-distributed-systems/exercises/03-ex2-restart-from-disk/

Hints

Hint 1

The comments on the variables say which ones are on disk and which are in memory. A restart is a crash followed by a start: what survives the crash?

Hint 2

term and votedFor are on disk; role and votes are in memory. A restarted server keeps the first two, and the other two go back to what a fresh server has.

Hint 3 (nearly the answer)

Set role[s] to "follower" with EXCEPT, decide what votes[s] holds for a server that has started afresh, and leave the on-disk variables unchanged. In the cfg, ask whether TLC can ever find a state with no step out of it once any server can restart at any time, and what that leaves the deadlock check to do.

06Explain it

Open NOTES.md and answer the three prompts under 13-03, about the Core exercise.

output
What I built, and why it is correct:
Which assumption, if false, breaks it:
What TLC did not check here:

Compare your answers with "13-03 check your explanation" in HINTS.md.

After you writeCheck your explanation

A good answer: "A restarted server keeps term and votedFor, which are on disk, and forgets its role and the votes it collected, so it cannot vote twice in a term. It assumes the vote reaches disk before the server answers the candidate; a server that acknowledges first and writes later breaks it. TLC found no violation of AtMostOneLeaderPerTerm with three servers and two terms, with every action firing and the witness reached; it did not check heartbeats, message delay, or liveness."

A weak answer: "Restart resets the server and it still works." It does not say what is kept, why it must be kept, or what the result covers.

Done?