"""
Streaming Consensus Protocol Simulator for Education
=====================================================
A comprehensive simulator demonstrating distributed consensus concepts:
- Message scheduling with configurable delays
- Failure injection (crash, network partition, message loss)
- Real-time visualization of protocol state
- Verification of consensus properties (safety & liveness)
"""
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.patches import FancyBboxPatch, Circle, Rectangle, FancyArrowPatch
from matplotlib.collections import PatchCollection
import matplotlib.patches as mpatches
import numpy as np
import random
import threading
import time
from collections import defaultdict
from enum import Enum, auto
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Set, Tuple, Any, Callable
import heapq
from datetime import datetime
import colorsys
# ==================== PROTOCOL DEFINITIONS ====================
class NodeState(Enum):
FOLLOWER = "Follower"
CANDIDATE = "Candidate"
LEADER = "Leader"
CRASHED = "Crashed"
class MessageType(Enum):
APPEND_ENTRIES = "AppendEntries"
APPEND_ENTRIES_RESPONSE = "AppendEntriesResp"
REQUEST_VOTE = "RequestVote"
REQUEST_VOTE_RESPONSE = "RequestVoteResp"
HEARTBEAT = "Heartbeat"
CLIENT_REQUEST = "ClientRequest"
@dataclass
class LogEntry:
"""Represents a log entry in the replicated log"""
term: int
index: int
command: str
committed: bool = False
def __repr__(self):
status = "✓" if self.committed else "·"
return f"[T{self.term}:I{self.index}:{status}] {self.command}"
@dataclass
class Message:
"""Represents a message in the consensus protocol"""
msg_type: MessageType
src: int
dst: int
term: int
timestamp: float
data: Dict = field(default_factory=dict)
delivered: bool = False
def __repr__(self):
return f"{self.msg_type.value} {self.src}→{self.dst} (T{self.term})"
class Event:
"""Scheduled event in the simulator"""
def __init__(self, time: float, callback: Callable, description: str = ""):
self.time = time
self.callback = callback
self.description = description
def __lt__(self, other):
return self.time < other.time
# ==================== CONSENSUS NODE ====================
class ConsensusNode:
"""
Implements a Raft-like consensus node with:
- Leader election
- Log replication
- Safety guarantees
"""
def __init__(self, node_id: int, cluster_size: int):
self.node_id = node_id
self.cluster_size = cluster_size
self.quorum = (cluster_size // 2) + 1
# Persistent state
self.current_term = 0
self.voted_for: Optional[int] = None
self.log: List[LogEntry] = []
# Volatile state
self.commit_index = 0
self.last_applied = 0
self.state = NodeState.FOLLOWER
# Leader state (reinitialized after election)
self.next_index: Dict[int, int] = {}
self.match_index: Dict[int, int] = {}
# Election state
self.votes_received: Set[int] = set()
self.last_heartbeat = time.time()
self.election_timeout = random.uniform(1.5, 3.0)
# Statistics
self.total_messages_sent = 0
self.total_messages_received = 0
self.leader_periods = 0
def reset_election_timer(self):
"""Reset election timeout with random jitter"""
self.election_timeout = random.uniform(1.5, 3.0)
self.last_heartbeat = time.time()
def become_follower(self, term: int):
"""Transition to follower state"""
self.state = NodeState.FOLLOWER
self.current_term = term
self.voted_for = None
self.votes_received.clear()
self.reset_election_timer()
def become_candidate(self) -> Message:
"""Transition to candidate state and start election"""
self.state = NodeState.CANDIDATE
self.current_term += 1
self.voted_for = self.node_id
self.votes_received = {self.node_id}
self.reset_election_timer()
# Create RequestVote message
last_log_term = self.log[-1].term if self.log else 0
last_log_index = len(self.log)
return Message(
msg_type=MessageType.REQUEST_VOTE,
src=self.node_id,
dst=-1, # Broadcast
term=self.current_term,
timestamp=time.time(),
data={
'last_log_term': last_log_term,
'last_log_index': last_log_index
}
)
def become_leader(self) -> List[Message]:
"""Transition to leader state"""
self.state = NodeState.LEADER
self.leader_periods += 1
# Initialize leader state
self.next_index = {i: len(self.log) + 1 for i in range(self.cluster_size)}
self.match_index = {i: 0 for i in range(self.cluster_size)}
# Send initial heartbeats
return self.create_heartbeats()
def create_heartbeats(self) -> List[Message]:
"""Create heartbeat messages for all followers"""
messages = []
for node_id in range(self.cluster_size):
if node_id != self.node_id:
messages.append(Message(
msg_type=MessageType.HEARTBEAT,
src=self.node_id,
dst=node_id,
term=self.current_term,
timestamp=time.time(),
data={
'prev_log_index': len(self.log),
'prev_log_term': self.log[-1].term if self.log else 0,
'commit_index': self.commit_index
}
))
return messages
def handle_request_vote(self, msg: Message) -> Optional[Message]:
"""Handle incoming RequestVote message"""
# Update term if necessary
if msg.term > self.current_term:
self.become_follower(msg.term)
vote_granted = False
if msg.term == self.current_term:
# Check if we can vote
if self.voted_for is None or self.voted_for == msg.src:
# Check log is at least as up-to-date
last_log_term = self.log[-1].term if self.log else 0
last_log_index = len(self.log)
candidate_last_term = msg.data.get('last_log_term', 0)
candidate_last_index = msg.data.get('last_log_index', 0)
log_ok = (candidate_last_term > last_log_term or
(candidate_last_term == last_log_term and
candidate_last_index >= last_log_index))
if log_ok:
vote_granted = True
self.voted_for = msg.src
self.reset_election_timer()
if vote_granted:
return Message(
msg_type=MessageType.REQUEST_VOTE_RESPONSE,
src=self.node_id,
dst=msg.src,
term=self.current_term,
timestamp=time.time(),
data={'vote_granted': True}
)
return None
def handle_vote_response(self, msg: Message) -> Optional[List[Message]]:
"""Handle vote response"""
if self.state != NodeState.CANDIDATE:
return None
if msg.term > self.current_term:
self.become_follower(msg.term)
return None
if msg.term == self.current_term and msg.data.get('vote_granted', False):
self.votes_received.add(msg.src)
# Check if we have quorum
if len(self.votes_received) >= self.quorum:
return self.become_leader()
return None
def handle_append_entries(self, msg: Message) -> Optional[Message]:
"""Handle AppendEntries/Heartbeat from leader"""
# Update term if necessary
if msg.term > self.current_term:
self.become_follower(msg.term)
success = False
if msg.term >= self.current_term:
self.reset_election_timer()
if self.state == NodeState.CANDIDATE:
self.become_follower(msg.term)
# Check log consistency
prev_log_index = msg.data.get('prev_log_index', 0)
if prev_log_index == 0 or (prev_log_index <= len(self.log) and
(prev_log_index == 0 or self.log[prev_log_index - 1].term ==
msg.data.get('prev_log_term', 0))):
success = True
# Append new entries (if any)
if 'entries' in msg.data:
for entry in msg.data['entries']:
if entry.index <= len(self.log):
if self.log[entry.index - 1].term != entry.term:
# Delete conflicting entries
self.log = self.log[:entry.index - 1]
self.log.append(entry)
else:
self.log.append(entry)
# Update commit index
if msg.data.get('commit_index', 0) > self.commit_index:
self.commit_index = min(
msg.data['commit_index'],
len(self.log)
)
self.commit_entries()
return Message(
msg_type=MessageType.APPEND_ENTRIES_RESPONSE,
src=self.node_id,
dst=msg.src,
term=self.current_term,
timestamp=time.time(),
data={
'success': success,
'match_index': len(self.log)
}
)
def handle_append_entries_response(self, msg: Message) -> Optional[List[Message]]:
"""Handle response to AppendEntries"""
if self.state != NodeState.LEADER:
return None
if msg.term > self.current_term:
self.become_follower(msg.term)
return None
if msg.data.get('success', False):
# Update match index
match_index = msg.data['match_index']
self.match_index[msg.src] = match_index
self.next_index[msg.src] = match_index + 1
# Check if we can advance commit index
for n in range(self.commit_index + 1, len(self.log) + 1):
if self.log[n - 1].term == self.current_term:
# Count replicas
replicas = sum(1 for i, m in self.match_index.items()
if m >= n and i != self.node_id)
if replicas + 1 >= self.quorum:
self.commit_index = n
self.commit_entries()
else:
# Decrement next index and retry
self.next_index[msg.src] = max(1, self.next_index[msg.src] - 1)
return None
def commit_entries(self):
"""Commit entries up to commit_index"""
while self.last_applied < self.commit_index:
self.last_applied += 1
if self.last_applied <= len(self.log):
self.log[self.last_applied - 1].committed = True
def create_append_entries(self, command: str) -> List[Message]:
"""Create AppendEntries messages for a new command"""
if self.state != NodeState.LEADER:
return []
# Append to local log
entry = LogEntry(
term=self.current_term,
index=len(self.log) + 1,
command=command
)
self.log.append(entry)
messages = []
for node_id in range(self.cluster_size):
if node_id != self.node_id:
prev_index = self.next_index[node_id] - 1
prev_term = self.log[prev_index - 1].term if prev_index > 0 else 0
messages.append(Message(
msg_type=MessageType.APPEND_ENTRIES,
src=self.node_id,
dst=node_id,
term=self.current_term,
timestamp=time.time(),
data={
'prev_log_index': prev_index,
'prev_log_term': prev_term,
'entries': [entry],
'commit_index': self.commit_index
}
))
return messages
def check_election_timeout(self) -> Optional[Message]:
"""Check if election timeout has elapsed"""
if self.state == NodeState.LEADER:
return None
if time.time() - self.last_heartbeat > self.election_timeout:
return self.become_candidate()
return None
# ==================== NETWORK SIMULATOR ====================
class NetworkSimulator:
"""
Simulates network behavior with:
- Configurable message delays
- Message loss
- Network partitions
- Message reordering
"""
def __init__(self):
self.messages: List[Message] = []
self.event_queue: List[Event] = []
self.current_time = 0.0
# Network settings
self.base_delay = 0.1
self.jitter = 0.05
self.loss_rate = 0.0
# Partition tracking
self.partitions: List[Set[int]] = []
# Message statistics
self.total_sent = 0
self.total_delivered = 0
self.total_lost = 0
def schedule_message(self, msg: Message, delay: float = None):
"""Schedule a message for delivery"""
if delay is None:
delay = self.base_delay + random.uniform(-self.jitter, self.jitter)
delay = max(0.01, delay)
self.messages.append(msg)
self.total_sent += 1
# Check for message loss
if random.random() < self.loss_rate:
self.total_lost += 1
return
# Check for network partition
if self._is_partitioned(msg.src, msg.dst):
self.total_lost += 1
return
# Schedule delivery event
delivery_time = self.current_time + delay
heapq.heappush(self.event_queue, Event(
delivery_time,
lambda m=msg: self._deliver_message(m),
f"Deliver {msg}"
))
def _deliver_message(self, msg: Message):
"""Mark message as delivered"""
msg.delivered = True
self.total_delivered += 1
def _is_partitioned(self, src: int, dst: int) -> bool:
"""Check if two nodes are in different partitions"""
if dst == -1: # Broadcast
return False
for partition in self.partitions:
src_in = src in partition
dst_in = dst in partition
if src_in != dst_in:
return True
return False
def create_partition(self, group1: Set[int], group2: Set[int]):
"""Create a network partition"""
self.partitions = [group1, group2]
def heal_partition(self):
"""Heal all network partitions"""
self.partitions.clear()
def get_pending_messages(self) -> List[Message]:
"""Get all pending (undelivered) messages"""
return [m for m in self.messages if not m.delivered]
def process_events(self, up_to_time: float) -> List[Message]:
"""Process all events up to a given time"""
delivered = []
while self.event_queue and self.event_queue[0].time <= up_to_time:
event = heapq.heappop(self.event_queue)
self.current_time = event.time
event.callback()
# Find the delivered message
for msg in self.messages:
if msg.delivered and msg not in delivered:
delivered.append(msg)
return delivered
def clear_messages(self):
"""Clear all messages (reset for new simulation)"""
self.messages.clear()
self.event_queue.clear()
self.current_time = 0.0
self.total_sent = 0
self.total_delivered = 0
self.total_lost = 0
# ==================== FAILURE INJECTOR ====================
class FailureInjector:
"""
Injects various failures into the system:
- Node crashes
- Network partitions
- Message loss
- Byzantine behavior (optional)
"""
def __init__(self, nodes: List[ConsensusNode], network: NetworkSimulator):
self.nodes = nodes
self.network = network
self.crashed_nodes: Set[int] = set()
self.scheduled_failures: List[Dict] = []
def crash_node(self, node_id: int):
"""Crash a node"""
if node_id < len(self.nodes):
self.nodes[node_id].state = NodeState.CRASHED
self.crashed_nodes.add(node_id)
def restart_node(self, node_id: int):
"""Restart a crashed node"""
if node_id in self.crashed_nodes:
node = self.nodes[node_id]
# Preserve persistent state (term, voted_for, log)
node.state = NodeState.FOLLOWER
node.reset_election_timer()
self.crashed_nodes.remove(node_id)
def create_partition(self, group1: Set[int], group2: Set[int]):
"""Create a network partition"""
self.network.create_partition(group1, group2)
def heal_partition(self):
"""Heal network partitions"""
self.network.heal_partition()
def set_loss_rate(self, rate: float):
"""Set message loss rate (0.0 to 1.0)"""
self.network.loss_rate = max(0.0, min(1.0, rate))
def schedule_failure(self, time: float, failure_type: str, **kwargs):
"""Schedule a failure event"""
self.scheduled_failures.append({
'time': time,
'type': failure_type,
'params': kwargs
})
def get_scheduled_failure(self, time: float) -> Optional[Dict]:
"""Get the next scheduled failure"""
for failure in self.scheduled_failures:
if failure['time'] <= time:
self.scheduled_failures.remove(failure)
return failure
return None
# ==================== VERIFICATION ENGINE ====================
class VerificationEngine:
"""
Verifies consensus properties:
- Election Safety: At most one leader per term
- Leader Append-Only: Leader never overwrites/deletes entries
- Log Matching: If two logs contain same index/term, all prior entries match
- Leader Completeness: Committed entries present in future leaders
- State Machine Safety: All nodes apply same commands at same index
"""
def __init__(self, nodes: List[ConsensusNode]):
self.nodes = nodes
self.violations: List[Dict] = []
self.checkpoints: List[Dict] = []
def verify_all(self) -> List[Dict]:
"""Run all verification checks"""
self.violations.clear()
self.check_election_safety()
self.check_log_matching()
self.check_state_machine_safety()
return self.violations
def check_election_safety(self):
"""Verify at most one leader per term"""
leaders_per_term: Dict[int, List[int]] = defaultdict(list)
for node in self.nodes:
if node.state == NodeState.LEADER:
leaders_per_term[node.current_term].append(node.node_id)
for term, leaders in leaders_per_term.items():
if len(leaders) > 1:
self.violations.append({
'type': 'ELECTION_SAFETY',
'message': f'Multiple leaders in term {term}: {leaders}',
'severity': 'CRITICAL'
})
def check_log_matching(self):
"""Verify log matching property"""
active_nodes = [n for n in self.nodes if n.state != NodeState.CRASHED]
for i, node1 in enumerate(active_nodes):
for node2 in active_nodes[i+1:]:
# Find common prefix
min_len = min(len(node1.log), len(node2.log))
for idx in range(min_len):
entry1 = node1.log[idx]
entry2 = node2.log[idx]
if entry1.term == entry2.term:
# Check all prior entries match
for j in range(idx):
if node1.log[j].term != node2.log[j].term:
self.violations.append({
'type': 'LOG_MATCHING',
'message': f'Log mismatch at index {j}: '
f'Node {node1.node_id} vs Node {node2.node_id}',
'severity': 'CRITICAL'
})
break
def check_state_machine_safety(self):
"""Verify all committed entries are identical across nodes"""
active_nodes = [n for n in self.nodes if n.state != NodeState.CRASHED]
# Get all committed indices
committed_entries: Dict[int, Dict[int, LogEntry]] = defaultdict(dict)
for node in active_nodes:
for entry in node.log:
if entry.committed:
committed_entries[entry.index][node.node_id] = entry
# Check all committed entries at same index are identical
for index, entries in committed_entries.items():
if len(entries) > 1:
terms = {e.term for e in entries.values()}
commands = {e.command for e in entries.values()}
if len(terms) > 1 or len(commands) > 1:
self.violations.append({
'type': 'STATE_MACHINE_SAFETY',
'message': f'Committed entry mismatch at index {index}',
'severity': 'CRITICAL'
})
def create_checkpoint(self) -> Dict:
"""Create a checkpoint of current state"""
checkpoint = {
'time': time.time(),
'nodes': []
}
for node in self.nodes:
checkpoint['nodes'].append({
'id': node.node_id,
'state': node.state.value,
'term': node.current_term,
'log_length': len(node.log),
'commit_index': node.commit_index,
'committed_count': sum(1 for e in node.log if e.committed)
})
self.checkpoints.append(checkpoint)
return checkpoint
def get_consensus_reached(self) -> bool:
"""Check if consensus has been reached on all committed entries"""
active_nodes = [n for n in self.nodes if n.state != NodeState.CRASHED]
if not active_nodes:
return False
# All active nodes should have same committed entries
committed_sets = []
for node in active_nodes:
committed = {(e.index, e.term, e.command)
for e in node.log if e.committed}
committed_sets.append(committed)
if not committed_sets:
return False
return all(s == committed_sets[0] for s in committed_sets)
# ==================== VISUALIZATION ====================
class ConsensusVisualizer:
"""
Real-time visualization of consensus protocol:
- Node states and terms
- Message flow
- Log visualization
- Timeline view
"""
def __init__(self, fig, nodes: List[ConsensusNode]):
self.fig = fig
self.nodes = nodes
self.n_nodes = len(nodes)
# Create subplots
self.ax_topology = fig.add_subplot(2, 2, 1)
self.ax_logs = fig.add_subplot(2, 2, 2)
self.ax_timeline = fig.add_subplot(2, 2, 3)
self.ax_stats = fig.add_subplot(2, 2, 4)
# Message history for visualization
self.message_history: List[Tuple[float, Message]] = []
self.timeline_events: List[Tuple[float, str, int, str]] = []
# Node positions (circular layout)
self.node_positions = self._calculate_positions()
# Colors
self.state_colors = {
NodeState.FOLLOWER: '#4CAF50', # Green
NodeState.CANDIDATE: '#FF9800', # Orange
NodeState.LEADER: '#2196F3', # Blue
NodeState.CRASHED: '#9E9E9E' # Gray
}
self.msg_colors = {
MessageType.APPEND_ENTRIES: '#E91E63',
MessageType.APPEND_ENTRIES_RESPONSE: '#9C27B0',
MessageType.REQUEST_VOTE: '#FF5722',
MessageType.REQUEST_VOTE_RESPONSE: '#795548',
MessageType.HEARTBEAT: '#00BCD4',
MessageType.CLIENT_REQUEST: '#8BC34A'
}
def _calculate_positions(self) -> Dict[int, Tuple[float, float]]:
"""Calculate circular node positions"""
positions = {}
for i in range(self.n_nodes):
angle = 2 * np.pi * i / self.n_nodes - np.pi/2
x = np.cos(angle)
y = np.sin(angle)
positions[i] = (x, y)
return positions
def update_topology(self, messages: List[Message] = None):
"""Update topology visualization"""
self.ax_topology.clear()
self.ax_topology.set_xlim(-1.5, 1.5)
self.ax_topology.set_ylim(-1.5, 1.5)
self.ax_topology.set_aspect('equal')
self.ax_topology.set_title('Network Topology', fontsize=12, fontweight='bold')
self.ax_topology.axis('off')
# Draw message arrows
if messages:
for msg in messages[-5:]: # Show last 5 messages
if msg.dst == -1: # Broadcast
for dst in range(self.n_nodes):
if dst != msg.src:
self._draw_message_arrow(msg.src, dst, msg.msg_type)
else:
self._draw_message_arrow(msg.src, msg.dst, msg.msg_type)
# Draw nodes
for node in self.nodes:
x, y = self.node_positions[node.node_id]
# Node circle
color = self.state_colors.get(node.state, '#9E9E9E')
circle = Circle((x, y), 0.2, facecolor=color, edgecolor='black', linewidth=2)
self.ax_topology.add_patch(circle)
# Node label
self.ax_topology.text(x, y + 0.02, f'N{node.node_id}',
ha='center', va='center', fontsize=10, fontweight='bold')
# State and term
state_text = f'{node.state.value}\nT{node.current_term}'
self.ax_topology.text(x, y - 0.35, state_text,
ha='center', va='top', fontsize=8)
# Legend
legend_patches = [mpatches.Patch(color=c, label=s.value)
for s, c in self.state_colors.items()]
self.ax_topology.legend(handles=legend_patches, loc='upper right', fontsize=8)
def _draw_message_arrow(self, src: int, dst: int, msg_type: MessageType):
"""Draw a message arrow between nodes"""
x1, y1 = self.node_positions[src]
x2, y2 = self.node_positions[dst]
# Shorten arrows to not overlap with nodes
dx, dy = x2 - x1, y2 - y1
length = np.sqrt(dx**2 + dy**2)
if length > 0:
dx, dy = dx/length, dy/length
x1 += dx * 0.22
y1 += dy * 0.22
x2 -= dx * 0.22
y2 -= dy * 0.22
color = self.msg_colors.get(msg_type, 'gray')
self.ax_topology.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color=color,
lw=1.5, alpha=0.7))
def update_logs(self):
"""Update log visualization"""
self.ax_logs.clear()
self.ax_logs.set_title('Replicated Logs', fontsize=12, fontweight='bold')
max_log_len = max(len(n.log) for n in self.nodes) if self.nodes else 0
max_log_len = max(max_log_len, 1)
for node in self.nodes:
y = self.n_nodes - node.node_id - 1
# Draw log entries
for i, entry in enumerate(node.log):
x = i + 0.5
color = '#4CAF50' if entry.committed else '#FFA726'
rect = Rectangle((x - 0.4, y - 0.4), 0.8, 0.8,
facecolor=color, edgecolor='black', alpha=0.8)
self.ax_logs.add_patch(rect)
# Term number
self.ax_logs.text(x, y, f'T{entry.term}',
ha='center', va='center', fontsize=7)
# Node label
self.ax_logs.text(-0.3, y, f'N{node.node_id}',
ha='right', va='center', fontsize=9, fontweight='bold')
# Commit index marker
if node.commit_index > 0:
self.ax_logs.axvline(x=node.commit_index + 0.5,
ymin=(y-0.5)/self.n_nodes,
ymax=(y+0.5)/self.n_nodes,
color='red', linestyle='--', linewidth=2)
self.ax_logs.set_xlim(-1, max_log_len + 2)
self.ax_logs.set_ylim(-0.5, self.n_nodes + 0.5)
self.ax_logs.set_xlabel('Log Index')
self.ax_logs.set_yticks([])
# Legend
committed_patch = mpatches.Patch(color='#4CAF50', label='Committed')
uncommitted_patch = mpatches.Patch(color='#FFA726', label='Uncommitted')
self.ax_logs.legend(handles=[committed_patch, uncommitted_patch],
loc='upper right', fontsize=8)
def update_timeline(self):
"""Update timeline visualization"""
self.ax_timeline.clear()
self.ax_timeline.set_title('Event Timeline', fontsize=12, fontweight='bold')
if not self.timeline_events:
self.ax_timeline.text(0.5, 0.5, 'No events yet',
ha='center', va='center', transform=self.ax_timeline.transAxes)
return
# Sort events by time
events = sorted(self.timeline_events[-50:], key=lambda x: x[0]) # Last 50 events
for i, (t, event_type, node_id, details) in enumerate(events):
y = i
# Color based on event type
colors = {
'election': '#FF9800',
'leader': '#2196F3',
'vote': '#9C27B0',
'append': '#E91E63',
'commit': '#4CAF50',
'crash': '#F44336',
'partition': '#795548'
}
color = colors.get(event_type, 'gray')
self.ax_timeline.barh(y, 1, left=0, height=0.8, color=color, alpha=0.7)
self.ax_timeline.text(0.05, y, f'T{t:.1f}: N{node_id} - {details}',
va='center', fontsize=8)
self.ax_timeline.set_xlim(0, 1)
self.ax_timeline.set_ylim(-1, len(events))
self.ax_timeline.axis('off')
def update_stats(self, verification: VerificationEngine = None):
"""Update statistics display"""
self.ax_stats.clear()
self.ax_stats.set_title('Statistics & Verification', fontsize=12, fontweight='bold')
self.ax_stats.axis('off')
# Collect statistics
stats_text = []
stats_text.append("=== Node Statistics ===")
for node in self.nodes:
committed = sum(1 for e in node.log if e.committed)
stats_text.append(f"N{node.node_id}: {node.state.value}, Term={node.current_term}, "
f"Log={len(node.log)}, Committed={committed}")
# Network statistics
stats_text.append("\n=== Network ===")
stats_text.append(f"Messages: Sent={0}, Delivered={0}, Lost={0}")
# Verification results
if verification:
stats_text.append("\n=== Verification ===")
violations = verification.violations
if violations:
for v in violations[:3]:
stats_text.append(f"⚠ {v['type']}: {v['message'][:30]}...")
else:
stats_text.append("✓ All safety properties satisfied")
if verification.get_consensus_reached():
stats_text.append("✓ Consensus reached!")
# Display text
self.ax_stats.text(0.05, 0.95, '\n'.join(stats_text),
transform=self.ax_stats.transAxes,
fontsize=9, verticalalignment='top',
fontfamily='monospace',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
def add_timeline_event(self, event_type: str, node_id: int, details: str):
"""Add an event to the timeline"""
self.timeline_events.append((time.time(), event_type, node_id, details))
# ==================== MAIN SIMULATOR GUI ====================
class ConsensusSimulatorGUI:
"""
Main GUI application for the consensus simulator
"""
def __init__(self):
self.root = tk.Tk()
self.root.title("Streaming Consensus Protocol Simulator - Educational Tool")
self.root.geometry("1400x900")
# Initialize components
self.n_nodes = 5
self.nodes: List[ConsensusNode] = []
self.network = NetworkSimulator()
self.failure_injector: Optional[FailureInjector] = None
self.verification: Optional[VerificationEngine] = None
self.visualizer: Optional[ConsensusVisualizer] = None
# Simulation state
self.running = False
self.sim_speed = 1.0
self.current_time = 0.0
self.step_mode = False
# Setup GUI
self._setup_gui()
self._initialize_simulation()
def _setup_gui(self):
"""Setup the GUI layout"""
# Main container
main_frame = ttk.Frame(self.root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Left panel - Controls
left_panel = ttk.Frame(main_frame, width=300)
left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=5)
left_panel.pack_propagate(False)
# Control buttons
ctrl_frame = ttk.LabelFrame(left_panel, text="Simulation Controls")
ctrl_frame.pack(fill=tk.X, pady=5)
btn_frame = ttk.Frame(ctrl_frame)
btn_frame.pack(fill=tk.X, pady=5)
self.start_btn = ttk.Button(btn_frame, text="▶ Start", command=self._toggle_simulation)
self.start_btn.pack(side=tk.LEFT, padx=2)
self.step_btn = ttk.Button(btn_frame, text="⏭ Step", command=self._step_simulation)
self.step_btn.pack(side=tk.LEFT, padx=2)
self.reset_btn = ttk.Button(btn_frame, text="↺ Reset", command=self._reset_simulation)
self.reset_btn.pack(side=tk.LEFT, padx=2)
# Speed control
speed_frame = ttk.Frame(ctrl_frame)
speed_frame.pack(fill=tk.X, pady=5)
ttk.Label(speed_frame, text="Speed:").pack(side=tk.LEFT)
self.speed_var = tk.DoubleVar(value=1.0)
speed_scale = ttk.Scale(speed_frame, from_=0.1, to=5.0,
variable=self.speed_var, orient=tk.HORIZONTAL)
speed_scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# Configuration
config_frame = ttk.LabelFrame(left_panel, text="Configuration")
config_frame.pack(fill=tk.X, pady=5)
ttk.Label(config_frame, text="Number of Nodes:").pack(anchor=tk.W)
self.nodes_var = tk.IntVar(value=5)
nodes_spin = ttk.Spinbox(config_frame, from_=3, to=9, textvariable=self.nodes_var, width=10)
nodes_spin.pack(anchor=tk.W, pady=2)
ttk.Label(config_frame, text="Network Delay (ms):").pack(anchor=tk.W)
self.delay_var = tk.DoubleVar(value=100)
delay_spin = ttk.Spinbox(config_frame, from_=10, to=1000, textvariable=self.delay_var, width=10)
delay_spin.pack(anchor=tk.W, pady=2)
ttk.Label(config_frame, text="Message Loss Rate:").pack(anchor=tk.W)
self.loss_var = tk.DoubleVar(value=0.0)
loss_scale = ttk.Scale(config_frame, from_=0.0, to=0.5,
variable=self.loss_var, orient=tk.HORIZONTAL)
loss_scale.pack(fill=tk.X, pady=2)
# Failure Injection
fail_frame = ttk.LabelFrame(left_panel, text="Failure Injection")
fail_frame.pack(fill=tk.X, pady=5)
ttk.Label(fail_frame, text="Select Node:").pack(anchor=tk.W)
self.fail_node_var = tk.IntVar(value=0)
self.fail_node_combo = ttk.Combobox(fail_frame, textvariable=self.fail_node_var, width=10)
self.fail_node_combo['values'] = list(range(self.n_nodes))
self.fail_node_combo.pack(anchor=tk.W, pady=2)
fail_btn_frame = ttk.Frame(fail_frame)
fail_btn_frame.pack(fill=tk.X, pady=5)
ttk.Button(fail_btn_frame, text="💥 Crash",
command=self._crash_node).pack(side=tk.LEFT, padx=2)
ttk.Button(fail_btn_frame, text="🔄 Restart",
command=self._restart_node).pack(side=tk.LEFT, padx=2)
ttk.Separator(fail_frame, orient=tk.HORIZONTAL).pack(fill=tk.X, pady=5)
ttk.Label(fail_frame, text="Network Partition:").pack(anchor=tk.W)
partition_frame = ttk.Frame(fail_frame)
partition_frame.pack(fill=tk.X, pady=2)
ttk.Button(partition_frame, text="Create Partition",
command=self._create_partition).pack(side=tk.LEFT, padx=2)
ttk.Button(partition_frame, text="Heal Partition",
command=self._heal_partition).pack(side=tk.LEFT, padx=2)
# Client Operations
client_frame = ttk.LabelFrame(left_panel, text="Client Operations")
client_frame.pack(fill=tk.X, pady=5)
ttk.Label(client_frame, text="Command:").pack(anchor=tk.W)
self.command_var = tk.StringVar(value="SET x=1")
ttk.Entry(client_frame, textvariable=self.command_var).pack(fill=tk.X, pady=2)
ttk.Button(client_frame, text="📤 Submit Command",
command=self._submit_command).pack(fill=tk.X, pady=5)
# Event Log
log_frame = ttk.LabelFrame(left_panel, text="Event Log")
log_frame.pack(fill=tk.BOTH, expand=True, pady=5)
self.log_text = scrolledtext.ScrolledText(log_frame, height=10, width=40,
font=('Courier', 8))
self.log_text.pack(fill=tk.BOTH, expand=True)
# Right panel - Visualization
right_panel = ttk.Frame(main_frame)
right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
# Matplotlib figure
self.fig = plt.Figure(figsize=(10, 8), dpi=100)
self.canvas = FigureCanvasTkAgg(self.fig, master=right_panel)
self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
# Status bar
self.status_var = tk.StringVar(value="Ready")
status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN)
status_bar.pack(side=tk.BOTTOM, fill=tk.X)
def _initialize_simulation(self):
"""Initialize the simulation components"""
self.nodes = []
self.n_nodes = self.nodes_var.get()
# Create nodes
for i in range(self.n_nodes):
node = ConsensusNode(i, self.n_nodes)
self.nodes.append(node)
# Update combo box
self.fail_node_combo['values'] = list(range(self.n_nodes))
# Initialize network
self.network = NetworkSimulator()
self.network.base_delay = self.delay_var.get() / 1000.0
# Initialize failure injector
self.failure_injector = FailureInjector(self.nodes, self.network)
# Initialize verification engine
self.verification = VerificationEngine(self.nodes)
# Initialize visualizer
self.visualizer = ConsensusVisualizer(self.fig, self.nodes)
# Clear event log
self.log_text.delete(1.0, tk.END)
# Update visualization
self._update_visualization()
self._log_event("Simulation initialized with {} nodes".format(self.n_nodes))
def _toggle_simulation(self):
"""Start/stop the simulation"""
self.running = not self.running
if self.running:
self.start_btn.config(text="⏸ Pause")
self._log_event("Simulation started")
threading.Thread(target=self._run_simulation, daemon=True).start()
else:
self.start_btn.config(text="▶ Start")
self._log_event("Simulation paused")
def _step_simulation(self):
"""Execute one simulation step"""
self._simulation_step()
self._update_visualization()
def _run_simulation(self):
"""Main simulation loop"""
while self.running:
self._simulation_step()
self._update_visualization()
time.sleep(0.1 / self.speed_var.get())
def _simulation_step(self):
"""Execute one step of the simulation"""
current_time = time.time()
# Process network events
delivered = self.network.process_events(current_time)
# Handle delivered messages
for msg in delivered:
if msg.dst == -1: # Broadcast
for node in self.nodes:
if node.node_id != msg.src and node.state != NodeState.CRASHED:
self._handle_message(msg, node)
else:
if msg.dst < len(self.nodes):
node = self.nodes[msg.dst]
if node.state != NodeState.CRASHED:
self._handle_message(msg, node)
# Check election timeouts and generate messages
for node in self.nodes:
if node.state != NodeState.CRASHED:
msg = node.check_election_timeout()
if msg:
self._schedule_message(msg)
self._log_event(f"N{node.node_id} starting election for term {node.current_term}")
self.visualizer.add_timeline_event('election', node.node_id,
f'Election T{node.current_term}')
# Process scheduled failures
if self.failure_injector:
failure = self.failure_injector.get_scheduled_failure(self.current_time)
if failure:
self._process_failure(failure)
# Run verification
if self.verification:
self.verification.verify_all()
self.current_time += 0.1
def _handle_message(self, msg: Message, node: ConsensusNode):
"""Handle a message at a node"""
node.total_messages_received += 1
response = None
if msg.msg_type == MessageType.REQUEST_VOTE:
response = node.handle_request_vote(msg)
if response and response.data.get('vote_granted'):
self._log_event(f"N{node.node_id} voted for N{msg.src} in T{msg.term}")
self.visualizer.add_timeline_event('vote', node.node_id,
f'Voted for N{msg.src}')
elif msg.msg_type == MessageType.REQUEST_VOTE_RESPONSE:
response = node.handle_vote_response(msg)
if response:
self._log_event(f"N{node.node_id} became LEADER in T{node.current_term}")
self.visualizer.add_timeline_event('leader', node.node_id,
f'Became Leader T{node.current_term}')
for m in response:
self._schedule_message(m)
return
elif msg.msg_type in [MessageType.APPEND_ENTRIES, MessageType.HEARTBEAT]:
response = node.handle_append_entries(msg)
if node.state == NodeState.LEADER and msg.msg_type == MessageType.HEARTBEAT:
self.visualizer.add_timeline_event('append', node.node_id, 'Heartbeat')
elif msg.msg_type == MessageType.APPEND_ENTRIES_RESPONSE:
response = node.handle_append_entries_response(msg)
if response:
for m in response:
self._schedule_message(m)
if response:
self._schedule_message(response)
def _schedule_message(self, msg: Message):
"""Schedule a message for delivery"""
self.network.schedule_message(msg)
self.nodes[msg.src].total_messages_sent += 1
def _update_visualization(self):
"""Update all visualizations"""
if self.visualizer:
pending = self.network.get_pending_messages()
self.visualizer.update_topology(pending)
self.visualizer.update_logs()
self.visualizer.update_timeline()
self.visualizer.update_stats(self.verification)
self.canvas.draw()
def _crash_node(self):
"""Crash the selected node"""
node_id = self.fail_node_var.get()
if self.failure_injector:
self.failure_injector.crash_node(node_id)
self._log_event(f"💥 Node {node_id} CRASHED")
self.visualizer.add_timeline_event('crash', node_id, 'Node crashed')
self._update_visualization()
def _restart_node(self):
"""Restart the selected node"""
node_id = self.fail_node_var.get()
if self.failure_injector:
self.failure_injector.restart_node(node_id)
self._log_event(f"🔄 Node {node_id} RESTARTED")
self._update_visualization()
def _create_partition(self):
"""Create a network partition"""
if self.failure_injector and self.n_nodes >= 4:
# Split nodes into two groups
group1 = set(range(self.n_nodes // 2 + 1))
group2 = set(range(self.n_nodes)) - group1
self.failure_injector.create_partition(group1, group2)
self._log_event(f"🔌 Network partition: {group1} | {group2}")
self.visualizer.add_timeline_event('partition', 0, 'Partition created')
self._update_visualization()
def _heal_partition(self):
"""Heal the network partition"""
if self.failure_injector:
self.failure_injector.heal_partition()
self._log_event("🔗 Network partition healed")
self._update_visualization()
def _submit_command(self):
"""Submit a client command"""
command = self.command_var.get()
# Find the leader
leader = None
for node in self.nodes:
if node.state == NodeState.LEADER:
leader = node
break
if leader:
messages = leader.create_append_entries(command)
for msg in messages:
self._schedule_message(msg)
self._log_event(f"📤 Command '{command}' submitted to leader N{leader.node_id}")
else:
self._log_event("⚠ No leader available - command rejected")
messagebox.showwarning("No Leader", "Cannot submit command - no leader elected yet")
def _process_failure(self, failure: Dict):
"""Process a scheduled failure"""
ftype = failure['type']
params = failure['params']
if ftype == 'crash':
self.failure_injector.crash_node(params['node_id'])
elif ftype == 'partition':
self.failure_injector.create_partition(params['group1'], params['group2'])
elif ftype == 'heal':
self.failure_injector.heal_partition()
def _reset_simulation(self):
"""Reset the simulation"""
self.running = False
self.start_btn.config(text="▶ Start")
self.current_time = 0.0
self._initialize_simulation()
self._log_event("Simulation reset")
def _log_event(self, message: str):
"""Log an event to the event log"""
timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
self.log_text.insert(tk.END, f"[{timestamp}] {message}\n")
self.log_text.see(tk.END)
self.status_var.set(message)
def run(self):
"""Run the GUI application"""
self.root.mainloop()
# ==================== TUTORIAL MODE ====================
class TutorialMode:
"""
Provides step-by-step tutorials for learning consensus concepts
"""
tutorials = {
"Leader Election": """
=== LEADER ELECTION TUTORIAL ===
1. All nodes start as FOLLOWERS
2. If a follower doesn't hear from a leader within election timeout:
- It becomes a CANDIDATE
- Increments its term
- Votes for itself
- Sends RequestVote to all other nodes
3. When a node receives RequestVote:
- If candidate's log is at least as up-to-date: grant vote
- Otherwise: reject vote
4. If candidate receives votes from majority:
- It becomes LEADER
- Sends heartbeats to establish authority
TRY IT:
- Click "Start" to begin simulation
- Watch nodes transition through states
- Green=Follower, Orange=Candidate, Blue=Leader
""",
"Log Replication": """
=== LOG REPLICATION TUTORIAL ===
1. Client sends command to the LEADER
2. Leader appends command to its log (uncommitted)
3. Leader sends AppendEntries to all followers
4. Followers append to their logs and respond
5. When majority acknowledge:
- Leader commits the entry
- Leader notifies followers to commit
SAFETY GUARANTEE:
- An entry is committed only if majority have it
- Committed entries are never overwritten
TRY IT:
- Wait for a leader to be elected
- Enter a command (e.g., "SET x=1")
- Click "Submit Command"
- Watch the log entries propagate
- Green boxes = committed entries
""",
"Failure Handling": """
=== FAILURE HANDLING TUTORIAL ===
NODE CRASHES:
- If follower crashes: system continues
- If leader crashes: new election after timeout
- Crash a node: Select it and click "💥 Crash"
NETWORK PARTITIONS:
- Nodes split into isolated groups
- Each group may elect its own leader
- Only majority partition can commit entries
- Create partition: Click "Create Partition"
- Heal partition: Click "Heal Partition"
MESSAGE LOSS:
- Adjust "Message Loss Rate" slider
- Higher loss = more retransmissions needed
TRY IT:
- Start simulation
- Wait for leader election
- Crash the leader (watch new election)
- Create partition (may see split-brain)
""",
"Verification": """
=== VERIFICATION TUTORIAL ===
The simulator continuously verifies:
1. ELECTION SAFETY
- At most one leader per term
- Violation = multiple leaders same term
2. LOG MATCHING
- If logs have same index/term, all prior entries match
- Violation = divergent logs
3. STATE MACHINE SAFETY
- All committed entries are identical
- Violation = different commands at same index
CHECK:
- Look at "Statistics & Verification" panel
- Green ✓ = property satisfied
- Red ⚠ = violation detected
"""
}
@classmethod
def show_tutorial(cls, tutorial_name: str):
"""Display a tutorial"""
return cls.tutorials.get(tutorial_name, "Tutorial not found")
# ==================== MAIN ENTRY POINT ====================
def main():
"""Main entry point"""
print("""
╔═══════════════════════════════════════════════════════════════╗
║ STREAMING CONSENSUS PROTOCOL SIMULATOR ║
║ Educational Tool for Distributed Systems ║
╠═══════════════════════════════════════════════════════════════╣
║ Features: ║
║ • Raft-like consensus protocol simulation ║
║ • Real-time visualization ║
║ • Message scheduling with delays ║
║ • Failure injection (crash, partition, loss) ║
║ • Safety property verification ║
╠═══════════════════════════════════════════════════════════════╣
║ Quick Start: ║
║ 1. Click "▶ Start" to begin simulation ║
║ 2. Watch leader election unfold ║
║ 3. Submit commands to the leader ║
║ 4. Inject failures to test resilience ║
╚═══════════════════════════════════════════════════════════════╝
""")
# Print tutorials
print("\n📚 Available Tutorials:")
for name in TutorialMode.tutorials:
print(f" • {name}")
print()
# Launch GUI
app = ConsensusSimulatorGUI()
app.run()
if __name__ == "__main__":
main()