Multi-Agent Consensus Protocol

Hard
Agents

Implement simplified Raft consensus for agent coordination:

Raft Basics:

  • Leader election for coordination
  • Log replication for consistency
  • Safety: committed entries are durable

States:

  • Follower: Passive, responds to requests
  • Candidate: Seeking votes for election
  • Leader: Handles all client requests

Methods:

  1. request_vote(term, candidate_id, ...): Vote for candidate
    • Grant vote if term >= current and log is up-to-date
  2. append_entries(...): Replicate log/heartbeat
  3. start_election(): Become candidate, request votes
  4. become_leader(): Transition to leader
  5. replicate_log(entry): Send to followers
  6. is_consensus_reached(responses): Majority?

Log Entry: {'term': ..., 'index': ..., 'command': ...}

Majority: len(acceptances) > len(all_nodes) / 2

Examples

Example 1:
Input: cp = ConsensusProtocol('node1', ['node1', 'node2', 'node3']); cp.state
Output: 'follower'
Explanation: Initial state is follower

Starter Code

class ConsensusProtocol:
    """
    Raft-inspired consensus protocol for distributed agent coordination.
    """
    
    def __init__(self, node_id, peers):
        self.node_id = node_id
        self.peers = peers
        self.state = 'follower'  # follower, candidate, leader
        self.current_term = 0
        self.voted_for = None
        self.log = []
        self.commit_index = 0
        self.last_applied = 0
    
    def request_vote(self, term, candidate_id, last_log_index, last_log_term):
        """Handle vote request from candidate"""
        # Your implementation here
        pass
    
    def append_entries(self, term, leader_id, prev_log_index, prev_log_term, entries, leader_commit):
        """Handle heartbeat/log replication from leader"""
        # Your implementation here
        pass
    
    def start_election(self):
        """Transition to candidate and start election"""
        # Your implementation here
        pass
    
    def become_leader(self):
        """Transition to leader state"""
        # Your implementation here
        pass
    
    def replicate_log(self, entry):
        """Leader replicates entry to followers"""
        # Your implementation here
        pass
    
    def is_consensus_reached(self, responses):
        """Check if majority accepted"""
        # Your implementation here
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews