TASK
Implementation
Implement the Election Restriction to ensure safety:
A candidate must have an "up-to-date" log to win election:
- Voter compares own log to candidate's
- If candidate lastLogTerm > voter lastLogTerm: candidate is ahead
- If same term, compare lastLogIndex
- Only grant vote if candidate is at least as up-to-date
This ensures the elected leader has all committed entries.
Sample Test Cases
Grant vote to higher termTimeout: 5000ms
Input
{"src":"c0","dest":"n2","body":{"type":"init","msg_id":1,"node_id":"n2","node_ids":["n1","n2","n3"]}}
{"src":"c0","dest":"n2","body":{"type":"set_term","msg_id":2,"term":2}}
{"src":"n1","dest":"n2","body":{"type":"request_vote","msg_id":3,"term":3,"candidate_id":"n1","last_log_index":0,"last_log_term":0}}
Expected Output
{"src":"n2","dest":"c0","body":{"type":"init_ok","in_reply_to":1,"msg_id":0}}
{"src":"n2","dest":"c0","body":{"type":"set_term_ok","in_reply_to":2,"msg_id":1}}
{"src":"n2","dest":"n1","body":{"type":"request_vote_ok","in_reply_to":3,"msg_id":2,"term":3,"vote_granted":true}}
Hints
Hint 1▾
Voter checks candidate log is up-to-date
Hint 2▾
Compare last log term first, then index
Hint 3▾
Reject vote if candidate log is behind
OVERVIEW
Theoretical Hub
Election Restriction
This is the key safety property of Raft. By only electing candidates with up-to-date logs, we ensure no committed entries are lost. The leader completeness property follows from this.
Comparison Logic
Higher term always wins. If same term, longer log wins. This captures "more up-to-date" precisely. A leader elected under these rules has everything committed before it.
Key Concepts
election restrictionsafetyup-to-date
main.py
python
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
#!/usr/bin/env python3
import sys
import json
class Voter:
def __init__(self, log, current_term, voted_for):
self.log = log
self.current_term = current_term
self.voted_for = voted_for
def is_candidate_up_to_date(self, candidate_last_term,
candidate_last_index):
# TODO: Compare candidate log to own
pass
def handle_request_vote(self, rv):
# rv = {term, candidate_id, last_log_index, last_log_term}
# TODO: Check term
# TODO: Check if already voted
# TODO: Check if candidate is up-to-date
# TODO: Grant or reject vote
pass
def compare_logs(term1, idx1, term2, idx2):
# TODO: Return True if (term1, idx1) >= (term2, idx2)
pass