Implement Raft consensus focusing on log replication. The leader sends AppendEntries RPCs, followers check prevLogIndex and prevLogTerm, and on conflict the leader decrements nextIndex for that follower and retries until consistency.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm producing a Python code snippet implementing core Raft log replication logic with a leader and followers, including AppendEntries handling, conflict detection, and leader retry with nextIndex decrement until logs are consistent. The code simulates a leader replicating entries to followers and resolving conflicts by adjusting nextIndex.
python
from dataclasses import dataclass
from typing import List, Dict, Optional
@dataclass
class LogEntry:
term: int
command: str
class RaftNode:
def __init__(self, node_id: int):
self.id = node_id
self.current_term: int = 0
self.voted_for: Optional[int] = None
# Index 0 is a dummy to make log indices 1-based
self.log: List[Optional[LogEntry]] = [None]
self.commit_index: int = 0
self.last_applied: int = 0
def append_entries(self,
term: int,
leader_id: int,
prev_log_index: int,
prev_log_term: int,
entries: List[LogEntry],
leader_commit: int) -> bool:
"""
Implementation of the AppendEntries RPC on a follower.
Returns True if successful, False if there is a log inconsistency.
"""
# If leader's term is stale, reject
if term < self.current_term:
return False
# Update current term and convert to follower if needed
self.current_term = term
# Check if log is long enough for prev_log_index
if prev_log_index >= len(self.log):
# Follower is missing entries; signal failure
return False
# If prev_log_index > 0, verify term matches
if prev_log_index > 0 and self.log[prev_log_index].term != prev_log_term:
# Log inconsistency
return False
# Delete existing entries that conflict with new ones
index = prev_log_index + 1
for i, entry in enumerate(entries):
# If existing entry at index conflicts (different term), delete the rest
if index < len(self.log):
if self.log[index].term != entry.term:
# Delete from index onwards
self.log = self.log[:index]
break
else:
# We're past the end of the log
break
index += 1
# Append any new entries not already in the log
for entry in entries[(len(self.log) - prev_log_index - 1):]:
self.log.append(entry)
# Update commit index
if leader_commit > self.commit_index:
self.commit_index = min(leader_commit, len(self.log) - 1)
return True
def __repr__(self):
return f"Node(id={self.id}, term={self.current_term}, log={[e.term if e else None for e in self.log]}, commit_index={self.commit_index})"
class RaftLeader(RaftNode):
def __init__(self, node_id: int, followers: List[RaftNode]):
super().__init__(node_id)
self.followers = followers
# nextIndex and matchIndex are 1-based, like log indices
self.next_index: Dict[int, int] = {f.id: 1 for f in followers}
self.match_index: Dict[int, int] = {f.id: 0 for f in followers}
def append_new_command(self, command: str):
"""
Called by a client to append a new command to the leader's log.
"""
self.log.append(LogEntry(term=self.current_term, command=command))
def replicate_log(self, follower: RaftNode):
"""
Try to replicate log entries to a single follower.
If the follower reports inconsistency, decrement next_index and retry.
"""
fid = follower.id
while True:
next_idx = self.next_index[fid]
prev_log_index = next_idx - 1
prev_log_term = self.log[prev_log_index].term if prev_log_index > 0 else 0
# Entries to send start at next_idx
entries = self.log[next_idx:]
success = follower.append_entries(
term=self.current_term,
leader_id=self.id,
prev_log_index=prev_log_index,
prev_log_term=prev_log_term,
entries=entries,
leader_commit=self.commit_index
)
if success:
# Update next_index and match_index
self.match_index[fid] = prev_log_index + len(entries)
self.next_index[fid] = self.match_index[fid] + 1
break
else:
# Decrement next_index and retry
if self.next_index[fid] > 1:
self.next_index[fid] -= 1
else:
# We've backed up all the way to the start
break
def replicate_to_all(self):
for follower in self.followers:
self.replicate_log(follower)
def maybe_advance_commit_index(self):
"""
Advance commit_index if a majority of match_index[i] >= N for some N > commit_index.
"""
# collect match indices (including leader itself)
match_indices = [len(self.log) - 1] # leader's own last index
match_indices.extend(self.match_index.values())
match_indices.sort()
# majority position
majority_pos = len(match_indices) // 2
majority_index = match_indices[majority_pos]
if majority_index > self.commit_index and self.log[majority_index].term == self.current_term:
self.commit_index = majority_index
def __repr__(self):
base = super().__repr__()
return f"{base}, next_index={self.next_index}, match_index={self.match_index}"
# Example usage:
if __name__ == "__main__":
# Create followers with divergent logs to demonstrate conflict resolution
follower1 = RaftNode(2)
follower2 = RaftNode(3)
# Preload follower1 with a conflicting entry
follower1.log.append(LogEntry(term=1, command="old_cmd"))
follower1.commit_index = 1
# Create a leader with term 2 and two new entries
leader = RaftLeader(1, [follower1, follower2])
leader.current_term = 2
leader.append_new_command("set x=1")
leader.append_new_command("set y=2")
# Initialize next_index for each follower to leader's last log index + 1
last_index = len(leader.log) - 1
for fid in leader.next_index:
leader.next_index[fid] = last_index + 1
# Replicate logs
leader.replicate_to_all()
leader.maybe_advance_commit_index()
print("Leader:", leader)
print("Follower1:", follower1)
print("Follower2:", follower2)