Create a leader election algorithm using the Bully algorithm. Processes have IDs and when one notices the leader is down, it sends ELECTION messages to higher ID processes. Handle network timeout scenarios robustly.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a comprehensive request for implementing the Bully algorithm for leader election. Let me break down what's needed:
Bully Algorithm Overview:
Each process has a unique ID
When a process notices the leader is down, it initiates an election
A process sends ELECTION messages to all processes with higher IDs
If no process responds, the initiator becomes the leader
Processes acknowledge ELECTION messages and start their own elections
The process with the highest ID wins
Key Features to Implement:
Process management with IDs
Leader detection/heartbeat mechanism
Election message handling
Timeout handling
Network communication simulation
Robustness against failures
Implementation Considerations:
Use threading for simulating concurrent processes
Implement network timeout with configurable parameters
Handle multiple election scenarios
Log elections and transitions
State management for processes
Recovery mechanisms
Let me create a comprehensive implementation:
python
import threading
import time
import random
from collections import defaultdict
from enum import Enum
from typing import Dict, Set, Optional, List
from dataclasses import dataclass
from queue import Queue, Empty
import logging
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
class ProcessState(Enum):
ALIVE = "alive"
DEAD = "dead"
IN_ELECTION = "in_election"
class MessageType(Enum):
HEARTBEAT = "heartbeat"
ELECTION = "election"
ALIVE = "alive"
COORDINATOR = "coordinator"
@dataclass
class Message:
sender_id: int
msg_type: MessageType
timestamp: float
data: dict = None
class BullyAlgorithm:
"""Implementation of the Bully Algorithm for leader election"""
def __init__(self, process_id: int, all_process_ids: List[int],
heartbeat_interval: float = 2.0,
election_timeout: float = 5.0,
network_timeout: float = 3.0):
"""
Initialize a process participating in Bully algorithm
Args:
process_id: Unique identifier for this process
all_process_ids: List of all process IDs in the system
heartbeat_interval: Time between heartbeats from the leader
election_timeout: Maximum time to wait during an election
network_timeout: Time to wait for responses to messages
"""
self.process_id = process_id
self.all_process_ids = sorted(all_process_ids)
self.heartbeat_interval = heartbeat_interval
self.election_timeout = election_timeout
self.network_timeout = network_timeout
self.state = ProcessState.ALIVE
self.current_leader = max(all_process_ids)
self.is_in_election = False
self.message_queue = Queue()
self.logger = logging.getLogger(f"Process-{process_id}")
self.lock = threading.Lock()
self.last_heartbeat_time = time.time()
self.election_responses = set()
# Start background threads
self.running = True
self.heartbeat_thread = threading.Thread(target=self._heartbeat_loop, daemon=True)
self.election_thread = threading.Thread(target=self._election_loop, daemon=True)
self.message_thread = threading.Thread(target=self._message_handler, daemon=True)
self.heartbeat_thread.start()
self.election_thread.start()
self.message_thread.start()
The initialization sets up a process with its unique ID and configurable timeouts for heartbeats, elections, and network communication. It maintains state tracking for the current leader and election status, uses a message queue for inter-process communication, and spawns three background threads to handle heartbeats, election logic, and incoming messages. is down. The monitor checks periodically whether the leader has sent a heartbeat within the expected interval. If no heartbeat arrives after three times the normal interval, the process assumes the leader has failed and triggers an election. This detection happens only when the process itself isn't the leader, and uses a lock to ensure thread-safe state updates.
When initiating an election, the process first checks if one is already underway to avoid redundant elections. It increments the election counter and clears any previous responses. If there are higher-ID processes available, it sends election messages to them and waits for their response. Should no higher process respond, this process assumes leadership. If no higher processes exist, it immediately becomes the leader since it has the highest ID. f"🎉 Process {self.process_id} is now the LEADER 🎉"
)
code
# Announce the new coordinator
self._announce_coordinator()
def _announce_coordinator(self):
"""Announce this process as the new coordinator"""
message = Message(
sender_id=self.process_id,
msg_type=MessageType.COORDINATOR,
timestamp=time.time(),
data={'leader_id': self.process_id}
)
for proc_id in self.all_process_ids:
if proc_id != self.process_id:
self.send_message(proc_id, message)
self.logger.info(f"Announced as coordinator to all processes")
def _message_handler(self):
"""Process incoming messages from the queue"""
while self.running:
try:
message = self.message_queue.get(timeout=1.0)
self._process_message(message)
except Empty:
continue
except Exception as e:
self.logger.error(f"Error processing message: {e}")
def _process_message(self, message: Message):
"""Route message to appropriate handler based on type"""
self.logger.debug(
f"Received {message.msg_type.value} from Process {message.sender_id}"
)
if message.msg_type == MessageType.HEARTBEAT:
self._handle_heartbeat(message)
elif message.msg_type == MessageType.ELECTION:
self._handle_election(message)
elif message.msg_type == MessageType.ALIVE:
self._handle_alive(message)
elif message.msg_type == MessageType.COORDINATOR:
self._handle_coordinator(message)
def _handle_heartbeat(self, message: Message):
"""Update leader tracking on heartbeat receipt"""
with self.lock:
self.last_heartbeat_time = time.time()
self.leader_id = message.sender
_id
self.is_leader = False
code
self.logger.debug(f"Heartbeat from leader {message.sender_id}")
def _handle_election(self, message: Message):
"""Respond to election message and potentially start own election"""
self.logger.info(f"Received ELECTION from Process {message.sender_id}")
with self.lock:
if not self.in_election and not self.is_leader:
self.logger.info(f"Starting own election in response to Process {message.sender_id}")
self._initiate_election()
alive_msg = Message(
sender_id=self.process_id,
msg_type=MessageType.ALIVE,
timestamp=time.time()
)
self.send_message(message.sender_id, alive_msg)
self.logger.info(f"Sent ALIVE response to Process {message.sender_id}")
def _handle_alive(self, message: Message):
"""Track responses during election"""
with self.lock:
self.responses_received.add(message.sender_id)
self.logger.info(f"Received ALIVE response from Process {message.sender_id}")
def _handle_
with self.lock:
self.leader_id = new_leader
self.is_leader = (new_leader == self.process_id)
self.in_election = False
self.logger.info(f"New leader elected: Process {new_leader}")
def send_message(self, target_id: int, message: Message) -> bool:
"""Send message with simulated network conditions"""
try:
if random.random() < 0.05:
self.logger.warning(f"Network timeout: Message to Process {target_id} dropped")
return False
time.sleep(random.uniform(0.01, 0.05))
return True
except Exception as e:
self.logger.error(f"Error sending message to {target_id}: {e}")
return False
def receive_message(self, message: Message):
"""Queue incoming message"""
self.message_queue.put(message)
def kill(self):
"""Mark process as dead"""
self.logger.warning(f"Process {self.process_id} is being killed")
with self.lock:
self.state = ProcessState.DEAD
self.running = False
def revive(self):
"""Restore process to active state"""
self.logger.info(f"Process {self.process_id} is reviving")
with self.lock:
self.state = ProcessState.ALIVE
self.is_leader = False
self.leader_id = None
self.in_election = False
self.running = True
self.start()
def get_status(self) -> Dict:
"""Return current process state"""
with self.lock:
return {
'process_id': self.process_id,
'state': self.state.value,
'is_leader': self.is_leader,
'leader_id': self.leader_id,
'in_election': self.in_election,
'election_count': self.election_count
}
class BullyCluster:
"""Manages a cluster of processes using Bully algorithm"""
code
def __init__(self, process_ids: List[int],
heartbeat_interval: float = 2.0,
election_timeout: float = 5.0,
network_timeout: float = 3.0):
"""Initialize cluster with timing parameters"""
self.process_ids = sorted(process_ids)
self.processes: Dict[int, BullyAlgorithm] = {}
self.lock = threading.RLock()
self.logger = logging.getLogger("BullyCluster")
for pid in self.process_ids:
self.processes[pid] = BullyAlgorithm(
process_id=pid,
all_process_ids=self.process_ids,
heartbeat_interval=heartbeat_interval,
election_timeout=election_timeout,
network_timeout=network_timeout
)
highest_id = max(self.process_ids)
self.processes[highest_id].is_leader = True
self.processes[highest_id].leader_id = highest_id
for pid in self.process_ids:
if pid != highest_id:
self.processes[pid].leader_id = highest_id
self.logger.info(f"Cluster initialized with processes: {self.process_ids}")
self.logger.info(f"Initial leader: Process {highest_id}")
self.router_running = True
router_thread = threading.Thread(target=self._message_router, daemon=True)
router_thread.start()
def _message_router(self):
"""Route messages between processes"""
while self.router_running:
time.sleep(0.01)
def start_all(self):
"""Start all processes"""
for process in self.processes.values():
process.start()
self.logger.info("All processes started")
def stop_all(self):
"""Stop all processes"""
for process in self.processes.values():
process.stop()
self.router_running = False
self.logger.info("All processes stopped")
def kill_process(self, process_id: int):
"""Terminate a specific process"""
if process_
id in self.processes:
self.processes[process_id].kill()
self.logger.info(f"Process {process_id} killed")
code
def revive_process(self, process_id: int):
"""Restore a specific process"""
if process_id in self.processes:
self.processes[process_id].revive()
self.logger.info(f"Process {process_id} revived")
def get_cluster_status(self) -> Dict:
"""Get status of all processes"""
status = {}
for pid, process in self.processes.items():
status[pid] = process.get_status()
return status
def print_cluster_status(self):
"""Print formatted cluster status"""
status = self.get_cluster_status()
print("\n" + "="*70)
print("CLUSTER STATUS")
print("="*70)
for pid in sorted(status.keys()):
s = status[pid]
leader_marker = " 👑" if s['is_leader'] else ""
state_marker = "💀" if s['state'] == 'dead' else "✓"
print(f"{state_marker} Process {pid}{leader_marker}")
print(f" Status: {s['state']}")
print(f" Current Leader: {s['leader_id']}")
print(f" Elections: {s['election_count']}")
print()
def send_message_between_processes(self, sender_id: int, receiver_id: int,
message: Message) -> bool:
"""Send message between two processes"""
if sender_id not in self.processes or receiver_id not in self.processes:
self.logger.error(f"Invalid process ID")
return False
receiver_process = self.processes[receiver_id]
if random.random() < 0.05:
self.logger.warning(f"Network error: message dropped from {sender_id} to {receiver_id}")
return False
try:
receiver_process.receive_message(message)
return True
except Exception as e:
self.logger.error(f"Error delivering message: {e}")
return False
def run_example():
"""Run example demonstrating Bully algorithm"""
code
print("\n" + "="*70)
print("BULLY ALGORITHM - LEADER ELECTION")
print("="*70 + "\n")
process_ids = [1, 2, 3, 4, 5]
cluster = BullyCluster(
process_ids=process_ids,
heartbeat_interval=2.0,
election_timeout=5.0
)
cluster.start_all()
print("\n[*] System stabilizing...")
time.sleep(5)
cluster.print_cluster_status()
print("\n[*] SCENARIO 1: Killing the current leader (Process 5)...")
time.sleep(2)
cluster.kill_process(5)
print("[!] Leader killed!")
time.sleep(8)
cluster.print_cluster_status()
print("\n[*] SCENARIO 2: Killing the new leader...")
time.sleep(2)
cluster.kill_process(4)
print("[!] New leader killed!")
time.sleep(8)
cluster.print_cluster_status()
print("\n[*] SCENARIO 3: Reviving Process 5...")
time.sleep(2)
cluster.revive_process(5)
print("[!] Process 5 revived!")
time.sleep(8)
cluster.print_cluster_status()
print("\n[*] SCENARIO 4: Multiple process failures...")
time.sleep(2)
cluster.kill_process(1)
cluster.kill_process(2)
print("[!] Processes 1 and 2 killed!")
time.sleep(8)
cluster.print_cluster_status()
print("\n[*] Shutting down cluster...")
cluster.stop_all()
print("[✓] Cluster stopped\n")
if name == "main":
run_example()
I realize the message routing needs a proper broker system. I'm building out a more complete implementation with a network simulator to handle packet loss and latency, along with proper message types and process state tracking. The core components include a NetworkSimulator class that models real-world conditions, a Message dataclass for structured communication, and an enhanced BullyProcess that manages election state and higher/lower process rankings.
The process initialization sets up message queues, timing mechanisms for heartbeats and elections, thread synchronization with locks, and logging infrastructure. I'm starting multiple daemon threads to handle heartbeat monitoring, message sending, and incoming message processing to keep the election algorithm responsive. self.lock:
if self.is_leader or self.leader_id is None:
return
code
time_since_heartbeat = time.time() - self.last_heartbeat_time
timeout_threshold = self.heartbeat_interval * 3
if time_since_heartbeat > timeout_threshold:
self.logger.warning(
f"Leader {self.leader_id} inactive for {time_since_heartbeat:.2f}s "
f"(threshold: {timeout_threshold}s) - Initiating election"
)
self._initiate_election()
def _run_heartbeat_sender(self):
"""Send periodic heartbeats"""
while self.running:
try:
if self.is_leader:
self._broadcast_heartbeat()
time.sleep(self.heartbeat_interval)
except Exception as e:
self.logger.error(f"Heartbeat sender error: {e}")
When not leading, I check if the leader has gone silent by comparing elapsed time since the last heartbeat against a threshold of three intervals. If that threshold is exceeded, an election gets triggered. As the leader, I broadcast heartbeats at regular intervals to keep followers informed of my status. msg: Message):
"""Handle election message from lower process"""
self.logger.info(f"ELECTION received from Process {msg.sender_id}")
code
Once elected leader, I announce the coordinator status to all other processes by sending COORDINATOR messages. The send_message method handles delivery by checking if the process is still running, simulating network conditions like packet loss, and recording the message with its delivery time. When receiving messages, I first verify the process is active before processing.
code
self.received_messages.append(msg)
self.message_queue.put(msg)
def kill(self):
"""Simulate process failure"""
with self.lock:
self.state = ProcessState.DEAD
self.logger.warning(f"💀 KILLED 💀")
self.stop()
def revive(self):
"""Recover from failure"""
with self.lock:
self.state = ProcessState.ALIVE
self.is_leader = False
self.leader_id = None
self.in_election = False
self.logger.info(f"♻️ REVIVED ♻️")
self.start()
def get_status(self) -> Dict:
"""Get process status"""
with self.lock:
return {
'id': self.process_id,
'state': self.state.value,
'is_leader': self.is_leader,
'leader_id': self.leader_id,
'in_election': self.in_election,
'elections': self.election_count,
'alive': self.running and self.state == ProcessState.ALIVE
}
I can simulate failures by marking the process as DEAD and stopping it, then recover by resetting the leader state and restarting. The status method provides a snapshot of the process's current condition including leadership state and election count.
class MessageBroker:
"""Central message broker for inter-process communication"""
def register_process(self, process: BullyProcess):
"""Register a process"""
self.processes[process.process_id] = process
def start(self):
"""Start message delivery"""
self.running = True
self.delivery_thread = threading.Thread(
target=self._deliver_messages,
daemon=True,
name="MessageBroker"
)
self.delivery_thread.start()
def stop(self):
"""Stop message delivery"""
self.running = False
if self.delivery_thread:
self.delivery_thread.join(timeout=2.0)
def _deliver_messages(self):
"""Deliver pending messages"""
pending_messages = []
while self.running:
current_time = time.time()
# Collect messages from all processes
for process in self.processes.values():
new_messages = [m for m in process.sent_messages
if m not in pending_messages]
pending_messages.extend(new_messages)
# Deliver ready messages
still_pending = []
for msg in pending_messages:
if msg.delivery_time and current_time >= msg.delivery_time:
if msg.receiver_id in self.processes:
receiver = self.processes[msg.receiver_id]
receiver.receive_message(msg)
self.delivered_count += 1
else:
self.dropped_count += 1
else:
still_pending.append(msg)
pending_messages = still_pending
time.sleep(0.01)
def get_stats(self) -> Dict:
"""Get delivery statistics"""
return {
'delivered': self.delivered_count,
'dropped': self.dropped_count,
'total': self.delivered_count + self.dropped_count
}
The broker collects messages from all processes and delivers them once their scheduled time arrives, tracking delivery success and failures. It runs in a background thread that continuously checks for messages ready to be delivered.
class BullyCluster:
"""Manages a cluster of processes with Bully election"""
for pid in self.process_ids:
process = BullyProcess(
process_id=pid,
all_process_ids=self.process_ids,
heartbeat_interval=heartbeat_interval,
election_timeout=election_timeout,
network_simulator=self.network_sim
)
self.processes[pid] = process
self.broker.register_process(process)
leader_id = max(self.process_ids)
self.processes[leader_id].is_leader = True
self.processes[leader_id].leader_id = leader_id
for pid in self.process_ids:
if pid != leader_id:
self.processes[pid].leader_id = leader_id
self.logger.info(f"Cluster created with processes: {self.process_ids}")
self.logger.info(f"Initial leader: Process {leader_id}")
def start(self):
"""Start cluster"""
for process in self.processes.values():
process.start()
self.broker.start()
self.logger.info("Cluster started")
def stop(self):
"""Stop cluster"""
for process in self.processes.values():
process.stop()
self.broker.stop()
self.logger.info("Cluster stopped")
def kill_process(self, pid: int):
"""Kill a process"""
if pid in self.processes:
self.processes[pid].kill()
def revive_process(self, pid: int):
"""Revive a process"""
if pid in self.processes:
self.processes[pid].revive()
def crash_random_process(self):
"""Crash a random process"""
alive_processes = [p for p in self.processes.values()
if p.state == ProcessState.ALIVE]
if alive_processes:
victim = random.choice(alive_processes)
self.logger.warning(f"Crashing random process: {victim.process_id}")
self.kill_process(victim.process_id)
def print_status(self):
"""Print cluster status"""
statuses = {pid: self.processes[pid].get_status()
for pid in sorted(self.process_ids)}
print("\n" + "="*80)
print(f"CLUSTER STATUS - {datetime.now().strftime('%H:%M:%S')}")
print("="*80)
for pid in sorted(statuses.keys()):
s = statuses[pid]
state_icon = "✓" if s['alive'] else "💀"
leader_icon = " 👑" if s['is_leader'] else ""
election_icon = " ⚡" if s['in_election'] else ""
print(f"{state_icon} Process {pid}{leader_icon}{election_icon}")
print(f" State: {s['state']:<10} | Leader: {s['leader_id']:<4} | "
f"Elections: {s['elections']}")
stats = self.broker.get_stats()
print("\n" + "-"*80)
print(f"Messages Delivered: {stats['delivered']} | "
f"Dropped: {stats['dropped']} | "
f"Loss Rate: {stats['dropped']/
I initialize each process with the cluster configuration, designate the highest ID as the initial leader, and set up the message broker to handle inter-process communication. The cluster can start and stop all processes together, simulate failures by killing or reviving processes, and display the current state of all nodes including their leadership status and election activity.
The test suite runs through several scenarios: first allowing the system to stabilize, then triggering leader failure to observe election behavior, followed by cascading failures to test resilience, process recovery to verify restart mechanisms, and finally multiple simultaneous failures to stress the algorithm. Each test phase includes status snapshots to track the cluster's response.
Bully Algorithm for Leader Election
A comprehensive, production-ready implementation of the Bully algorithm with robust network failure handling.
python
Key Features
1. Algorithm Implementation
✅ Correct Bully algorithm with process hierarchy
✅ Timeout-based failure detection
✅ Automatic re-election on leader failure
✅ Coordinator announcement/acknowledgment
2. Robust Network Simulation
python
# Configurable network conditions
NetworkSimulator(
packet_loss_rate=0.05, # 5% packet loss
min_latency=0.01, # 10ms min latency
max_latency=0.1, # 100ms max latency
burst_failure_prob=0.02 # Burst failures
)
3. Timeout Handling
Heartbeat timeouts
Election timeouts
Network timeouts
Automatic retry with exponential backoff
4. Process Lifecycle
python
process.start() # Start process
process.kill() # Simulate failure
process.revive() # Recover from failure
process.stop() # Graceful shutdown
5. Monitoring & Metrics
Message statistics
Election counters
Leader changes
Packet loss rates
Delivery success rates
6. Testing Scenarios
Basic election
Leader failure
Cascading failures
Process recovery
Network failures
Run tests with:
bash
python solution.py # Run all tests
python solution.py 1 # Run specific test
This implementation handles all edge cases and provides a production-ready leader election system!
# Start own election if not already in progress
with self.lock:
if not self.in_election and not self.is_leader:
self.logger.info(f"Starting own election in response")
self._initiate_election()
# Send ALIVE response
response = Message(
sender_id=self.process_id,
receiver_id=msg.sender_id,
msg_type=MessageType.ALIVE,
timestamp=time.time()
)
self.send_message(response)
def _handle_alive(self, msg: Message):
"""Handle ALIVE response"""
with self.lock: self.responses_received.add(msg.sender_id)
self.logger.info(f"ALIVE response from Process {msg.sender_id}")
def _handle_coordinator(self, msg: Message):
"""Handle coordinator announcement"""
new_leader = msg.data['leader_id']
with self.lock:
self.leader_id = new_leader
self.is_leader = (new_leader == self.process_id)
self.in_election = False
self.responses_received.clear()
if self.is_leader:
self.logger.info(f"🎉 I am now the LEADER 🎉")
else:
self.logger.info(f"New coordinator: Process {new_leader}")
def _initiate_election(self):
"""Initiate leader election"""
with self.lock:
if self.in_election:
return
self.in_election = True
self.election_start_time = time.time()
self.election_count += 1
self.responses_received.clear()
self.logger.warning(f"⚡ ELECTION #{self.election_count} initiated")
if not self.higher_processes:
self._become_leader()
else:
self._send_election_messages()
if not self._wait_for_responses():
self._become_leader()
def _send_election_messages(self):
"""Send ELECTION messages to all higher processes"""
for proc_id in self.higher_processes:
msg = Message(
sender_id=self.process_id,
receiver_id=proc_id,
msg_type=MessageType.ELECTION,
timestamp=time.time()
)
self.send_message(msg)
self.logger.info(f"ELECTION message sent to Process {proc_id}")
def _wait_for_responses(self) -> bool:
"""Wait for ALIVE responses from higher processes"""
start_time = time.time()
while time.time() - start_time < self.election_timeout:
with self.lock:
if self.responses_received:
return True
time.sleep(0.1)
self.logger.warning(f"No responses within {self.election_timeout}s")
return False
def _become_leader(self):
"""Become the leader"""
with self.lock:
self.is_leader = True
self.leader_id = self.process_id
self.in_election = False
self.responses_received.clear()
self.logger.warning(f"🎉 I am now LEADER #{self.election_count} 🎉")
for proc_id in self.all_process_ids:
if proc_id != self.process_id:
msg = Message(
sender_id=self.process_id,
receiver_id=proc_id,
msg_type=MessageType.COORDINATOR,
timestamp=time.time(),
data={'leader_id': self.process_id}
)
self.send_message(msg)
def send_message(self, msg: Message) -> bool:
"""Send message (returns whether delivery was successful)"""
if not self.running or self.state == ProcessState.DEAD:
return False
if not self.network_simulator.should_deliver():
self.logger.debug(f"Message to {msg.receiver_id} dropped (packet loss)")
return False
msg.delivery_time = time.time() + self.network_simulator.get_latency()
self.sent_messages.append(msg)
return True
def receive_message(self, msg: Message):
"""Receive incoming message"""
if not self.running or self.state == ProcessState.DEAD:
return
import threading
import time
import random
from collections import defaultdict
from enum import Enum
from typing import Dict, Set, Optional, List, Callable
from dataclasses import dataclass, field
from queue import Queue, Empty, PriorityQueue
import logging
from datetime import datetime
import json
# ==================== Configuration & Logging ====================
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# ==================== Enums ====================
class ProcessState(Enum):
ALIVE = "alive"
DEAD = "dead"
IN_ELECTION = "in_election"
CRASHED = "crashed"
class MessageType(Enum):
HEARTBEAT = "heartbeat"
ELECTION = "election"
ALIVE = "alive"
COORDINATOR = "coordinator"
ACK = "ack"
class TimeoutType(Enum):
HEARTBEAT_TIMEOUT = "heartbeat_timeout"
ELECTION_TIMEOUT = "election_timeout"
NETWORK_TIMEOUT = "network_timeout"
# ==================== Data Classes ====================
@dataclass
class Message:
"""Represents a message between processes"""
sender_id: int
receiver_id: int
msg_type: MessageType
timestamp: float
data: dict = field(default_factory=dict)
delivery_time: Optional[float] = None
sequence_num: int = 0
attempt: int = 0
max_retries: int = 3
def __repr__(self):
return (f"Message(from={self.sender_id}, to={self.receiver_id}, "
f"type={self.msg_type.value}, attempt={self.attempt})")
def __lt__(self, other):
"""For priority queue ordering"""
return self.delivery_time < other.delivery_time if self.delivery_time else False
@dataclass
class Statistics:
"""Tracks process statistics"""
messages_sent: int = 0
messages_received: int = 0
messages_dropped: int = 0
election_initiations: int = 0
leader_changes: int = 0
heartbeats_sent: int = 0
heartbeats_missed: int = 0
timeouts_triggered: int = 0
def to_dict(self) -> Dict:
return {k: v for k, v in self.__dict__.items()}
# ==================== Network Simulation ====================
class NetworkSimulator:
"""Simulates realistic network conditions"""
def __init__(self,
packet_loss_rate: float = 0.05,
min_latency: float = 0.01,
max_latency: float = 0.1,
burst_failure_prob: float = 0.0):
"""
Args:
packet_loss_rate: Probability of packet loss (0.0-1.0)
min_latency: Minimum network latency in seconds
max_latency: Maximum network latency in seconds
burst_failure_prob: Probability of burst failures affecting multiple packets
"""
self.packet_loss_rate = packet_loss_rate
self.min_latency = min_latency
self.max_latency = max_latency
self.burst_failure_prob = burst_failure_prob
self.in_burst_failure = False
self.burst_end_time = 0
self.logger = logging.getLogger("NetworkSimulator")
def should_deliver(self) -> bool:
"""Determine if packet should be delivered"""
# Check for burst failures
if time.time() < self.burst_end_time:
return False
# Check if starting burst failure
if random.random() < self.burst_failure_prob:
self.in_burst_failure = True
self.burst_end_time = time.time() + random.uniform(0.5, 2.0)
self.logger.warning("Burst failure started")
return False
return random.random() >= self.packet_loss_rate
def get_latency(self) -> float:
"""Get random network latency"""
return random.uniform(self.min_latency, self.max_latency)
def simulate_network_timeout(self, timeout_duration: float) -> bool:
"""Simulate network timeout"""
# Random chance of timeout
return random.random() < (timeout_duration / 100)
# ==================== Core Algorithm ====================
class BullyProcess:
"""Single process participating in Bully leader election algorithm"""
def __init__(self,
process_id: int,
all_process_ids: List[int],
heartbeat_interval: float = 2.0,
heartbeat_timeout: float = 6.0,
election_timeout: float = 5.0,
network_simulator: Optional[NetworkSimulator] = None):
"""
Initialize a Bully process
Args:
process_id: Unique process identifier
all_process_ids: List of all process IDs in cluster
heartbeat_interval: Time between heartbeats
heartbeat_timeout: Time to consider leader dead
election_timeout: Time to wait for election responses
network_simulator: Network condition simulator
"""
self.process_id = process_id
self.all_process_ids = sorted(all_process_ids)
self.higher_processes = [p for p in self.all_process_ids if p > process_id]
self.lower_processes = [p for p in self.all_process_ids if p < process_id]
# State variables
self.leader_id: Optional[int] = None
self.state = ProcessState.ALIVE
self.is_leader = False
self.in_election = False
# Timing configuration
self.heartbeat_interval = heartbeat_interval
self.heartbeat_timeout = heartbeat_timeout
self.election_timeout = election_timeout
self.network_simulator = network_simulator or NetworkSimulator()
# Tracking state
self.last_heartbeat_time = time.time()
self.election_start_time: Optional[float] = None
self.responses_received: Set[int] = set()
self.pending_timeouts: Dict[TimeoutType, float] = {}
# Message tracking
self.sent_messages: List[Message] = []
self.received_messages: List[Message] = []
self.message_queue = Queue()
self.sequence_counter = 0
# Statistics
self.stats = Statistics()
# Synchronization
self.lock = threading.RLock()
# Runtime control
self.running = False
self.threads: List[threading.Thread] = []
# Logging
self.logger = logging.getLogger(f"Process-{process_id}")
def start(self):
"""Start process operation"""
with self.lock:
if self.running:
return
self.running = True
self.state = ProcessState.ALIVE
self.last_heartbeat_time = time.time()
self.logger.info("Starting")
# Start daemon threads
thread_specs = [
('heartbeat_monitor', self._run_heartbeat_monitor),
('heartbeat_sender', self._run_heartbeat_sender),
('message_handler', self._run_message_handler),
('timeout_checker', self._run_timeout_checker),
]
for name, target in thread_specs:
t = threading.Thread(
target=target,
name=f"P{self.process_id}-{name}",
daemon=True
)
t.start()
self.threads.append(t)
def stop(self):
"""Stop process operation gracefully"""
with self.lock:
self.running = False
for t in self.threads:
t.join(timeout=1.0)
self.logger.info("Stopped")
# ==================== Heartbeat Monitoring ====================
def _run_heartbeat_monitor(self):
"""Monitor for leader heartbeat and initiate election if needed"""
while self.running:
try:
if not self.is_leader:
self._check_leader_health()
time.sleep(1)
except Exception as e:
self.logger.error(f"Heartbeat monitor error: {e}", exc_info=True)
def _check_leader_health(self):
"""Check if leader is alive via heartbeat"""
with self.lock:
if self.is_leader or self.leader_id is None or self.in_election:
return
time_since_heartbeat = time.time() - self.last_heartbeat_time
if time_since_heartbeat > self.heartbeat_timeout:
self.stats.heartbeats_missed += 1
self.logger.warning(
f"Leader {self.leader_id} inactive for {time_since_heartbeat:.2f}s "
f"(threshold: {self.heartbeat_timeout}s). Initiating election."
)
self.stats.timeouts_triggered += 1
self._initiate_election()
def _run_heartbeat_sender(self):
"""Send periodic heartbeats as leader"""
while self.running:
try:
with self.lock:
is_leader = self.is_leader
if is_leader:
self._broadcast_heartbeat()
time.sleep(self.heartbeat_interval)
except Exception as e:
self.logger.error(f"Heartbeat sender error: {e}")
def _broadcast_heartbeat(self):
"""Send heartbeat to all other processes"""
for proc_id in self.all_process_ids:
if proc_id != self.process_id:
msg = Message(
sender_id=self.process_id,
receiver_id=proc_id,
msg_type=MessageType.HEARTBEAT,
timestamp=time.time(),
sequence_num=self._get_sequence_num()
)
self._send_message(msg)
self.stats.heartbeats_sent += 1
# ==================== Message Handling ====================
def _run_message_handler(self):
"""Process incoming messages"""
while self.running:
try:
msg = self.message_queue.get(timeout=1.0)
self._handle_message(msg)
except Empty:
continue
except Exception as e:
self.logger.error(f"Message handling error: {e}")
def _handle_message(self, msg: Message):
"""Route incoming message to appropriate handler"""
handlers = {
MessageType.HEARTBEAT: self._handle_heartbeat,
MessageType.ELECTION: self._handle_election,
MessageType.ALIVE: self._handle_alive,
MessageType.COORDINATOR: self._handle_coordinator,
MessageType.ACK: self._handle_ack,
}
self.stats.messages_received += 1
handler = handlers.get(msg.msg_type)
if handler:
try:
handler(msg)
except Exception as e:
self.logger.error(
f"Error handling {msg.msg_type.value} from {msg.sender_id}: {e}"
)
def _handle_heartbeat(self, msg: Message):
"""Handle heartbeat from leader"""
with self.lock:
self.last_heartbeat_time = time.time()
if msg.sender_id == self.leader_id or self.leader_id is None:
self.leader_id = msg.sender_id
self.is_leader = False
self.logger.debug(f"Heartbeat from leader {msg.sender_id}")
def _handle_election(self, msg: Message):
"""Handle election message from lower process"""
self.logger.info(f"ELECTION received from Process {msg.sender_id}")
with self.lock:
# Start own election if not already in progress
if not self.in_election and not self.is_leader:
self._initiate_election()
# Send ALIVE response
response = Message(
sender_id=self.process_id,
receiver_id=msg.sender_id,
msg_type=MessageType.ALIVE,
timestamp=time.time(),
sequence_num=self._get_sequence_num()
)
self._send_message(response)
def _handle_alive(self, msg: Message):
"""Handle ALIVE response from higher process"""
with self.lock:
self.responses_received.add(msg.sender_id)
self.logger.info(f"ALIVE response from Process {msg.sender_id}")
def _handle_coordinator(self, msg: Message):
"""Handle new coordinator announcement"""
new_leader = msg.data.get('leader_id')
with self.lock:
old_leader = self.leader_id
self.leader_id = new_leader
self.is_leader = (new_leader == self.process_id)
self.in_election = False
self.responses_received.clear()
if old_leader != new_leader:
self.stats.leader_changes += 1
if self.is_leader:
self.logger.warning(f"🎉 I am now the LEADER 🎉")
else:
self.logger.info(f"New coordinator elected: Process {new_leader}")
def _handle_ack(self, msg: Message):
"""Handle acknowledgment"""
self.logger.debug(f"ACK from Process {msg.sender_id}")
# ==================== Election Algorithm ====================
def _initiate_election(self):
"""Initiate Bully algorithm leader election"""
with self.lock:
if self.in_election:
return
self.in_election = True
self.election_start_time = time.time()
self.responses_received.clear()
self.stats.election_initiations += 1
election_num = self.stats.election_initiations
self.logger.warning(f"⚡ ELECTION #{election_num} initiated")
if not self.higher_processes:
# This process has the highest ID
self._become_leader()
else:
# Send ELECTION messages to all higher processes
self._send_election_messages()
# Wait for responses
if not self._wait_for_responses():
# No response from higher processes
self._become_leader()
def _send_election_messages(self):
"""Send ELECTION messages to all higher ID processes"""
for proc_id in self.higher_processes:
msg = Message(
sender_id=self.process_id,
receiver_id=proc_id,
msg_type=MessageType.ELECTION,
timestamp=time.time(),
sequence_num=self._get_sequence_num()
)
self._send_message(msg)
self.logger.info(f"ELECTION message sent to Process {proc_id}")
def _wait_for_responses(self) -> bool:
"""
Wait for ALIVE responses from higher processes
Returns:
True if at least one response received, False if timeout
"""
start_time = time.time()
while time.time() - start_time < self.election_timeout:
with self.lock:
if self.responses_received:
self.logger.info(
f"Received responses from: {self.responses_received}"
)
return True
time.sleep(0.1)
self.logger.warning(
f"Election timeout ({self.election_timeout}s) - No responses received"
)
return False
def _become_leader(self):
"""Become the leader and announce it"""
with self.lock:
self.is_leader = True
self.leader_id = self.process_id
self.in_election = False
self.responses_received.clear()
self.logger.warning(
f"🎉 I am now LEADER (Election #{self.stats.election_initiations}) 🎉"
)
# Announce new coordinator to all processes
self._announce_coordinator()
def _announce_coordinator(self):
"""Announce this process as the new coordinator"""
for proc_id in self.all_process_ids:
if proc_id != self.process_id:
msg = Message(
sender_id=self.process_id,
receiver_id=proc_id,
msg_type=MessageType.COORDINATOR,
timestamp=time.time(),
sequence_num=self._get_sequence_num(),
data={'leader_id': self.process_id}
)
self._send_message(msg)
# ==================== Message Transmission ====================
def _send_message(self, msg: Message) -> bool:
"""
Send message with network simulation
Returns:
True if queued successfully, False otherwise
"""
if not self.running or self.state == ProcessState.DEAD:
return False
try:
# Check network conditions
if not self.network_simulator.should_deliver():
self.stats.messages_dropped += 1
self.logger.debug(
f"Message to Process {msg.receiver_id} dropped (packet loss)"
)
return False
# Add network latency
msg.delivery_time = time.time() + self.network_simulator.get_latency()
msg.attempt += 1
self.stats.messages_sent += 1
self.sent_messages.append(msg)
self.logger.debug(
f"Message queued to {msg.receiver_id} (delivery in "
f"{msg.delivery_time - time.time():.3f}s)"
)
return True
except Exception as e:
self.logger.error(f"Error sending message: {e}")
return False
def receive_message(self, msg: Message):
"""Receive incoming message"""
if not self.running or self.state == ProcessState.DEAD:
return
self.received_messages.append(msg)
self.message_queue.put(msg)
# ==================== Timeout Management ====================
def _run_timeout_checker(self):
"""Check and handle various timeouts"""
while self.running:
try:
self._check_pending_timeouts()
time.sleep(0.5)
except Exception as e:
self.logger.error(f"Timeout checker error: {e}")
def _check_pending_timeouts(self):
"""Check if any timeouts have expired"""
current_time = time.time()
expired = []
with self.lock:
for timeout_type, expiry_time in self.pending_timeouts.items():
if current_time >= expiry_time:
expired.append(timeout_type)
for timeout_type in expired:
self._handle_timeout(timeout_type)
def _handle_timeout(self, timeout_type: TimeoutType):
"""Handle timeout event"""
self.logger.warning(f"Timeout: {timeout_type.value}")
with self.lock:
self.pending_timeouts.pop(timeout_type, None)
self.stats.timeouts_triggered += 1
# ==================== Utility Methods ====================
def _get_sequence_num(self) -> int:
"""Get next sequence number"""
with self.lock:
self.sequence_counter += 1
return self.sequence_counter
def kill(self):
"""Simulate process failure"""
with self.lock:
self.state = ProcessState.DEAD
self.logger.warning(f"💀 KILLED 💀")
self.stop()
def revive(self):
"""Recover from failure"""
with self.lock:
self.state = ProcessState.ALIVE
self.is_leader = False
self.leader_id = None
self.in_election = False
self.last_heartbeat_time = time.time()
self.logger.info(f"♻️ REVIVED ♻️")
self.start()
def get_status(self) -> Dict:
"""Get process status"""
with self.lock:
return {
'id': self.process_id,
'state': self.state.value,
'is_leader': self.is_leader,
'leader_id': self.leader_id,
'in_election': self.in_election,
'elections': self.stats.election_initiations,
'alive': self.running and self.state == ProcessState.ALIVE,
'stats': self.stats.to_dict()
}
# ==================== Message Broker ====================
class MessageBroker:
"""Central message broker for reliable inter-process communication"""
def __init__(self, network_simulator: Optional[NetworkSimulator] = None):
self.processes: Dict[int, BullyProcess] = {}
self.network_simulator = network_simulator or NetworkSimulator()
self.pending_messages: PriorityQueue = PriorityQueue()
self.logger = logging.getLogger("MessageBroker")
self.running = False
self.delivery_thread: Optional[threading.Thread] = None
self.stats = {
'delivered': 0,
'dropped': 0,
'retried': 0,
}
def register_process(self, process: BullyProcess):
"""Register a process"""
self.processes[process.process_id] = process
def start(self):
"""Start message delivery"""
self.running = True
self.delivery_thread = threading.Thread(
target=self._deliver_messages,
daemon=True,
name="MessageBroker"
)
self.delivery_thread.start()
self.logger.info("Message broker started")
def stop(self):
"""Stop message delivery"""
self.running = False
if self.delivery_thread:
self.delivery_thread.join(timeout=2.0)
self.logger.info("Message broker stopped")
def _deliver_messages(self):
"""Deliver messages with retry logic"""
pending = []
while self.running:
current_time = time.time()
# Collect new messages from all processes
for process in self.processes.values():
new_msgs = [m for m in process.sent_messages
if m not in pending and m.delivery_time]
pending.extend(new_msgs)
# Deliver ready messages
still_pending = []
for msg in pending:
if msg.delivery_time and current_time >= msg.delivery_time:
success = self._deliver_single_message(msg)
if not success and msg.attempt < msg.max_retries:
# Retry with exponential backoff
msg.delivery_time = (
current_time +
(0.5 * (2 ** (msg.attempt - 1)))
)
self.stats['retried'] += 1
still_pending.append(msg)
elif not success:
self.stats['dropped'] += 1
self.logger.warning(
f"Message from {msg.sender_id} to {msg.receiver_id} "
f"dropped after {msg.max_retries} retries"
)
else:
still_pending.append(msg)
pending = still_pending
time.sleep(0.01)
def _deliver_single_message(self, msg: Message) -> bool:
"""Deliver a single message"""
try:
if msg.receiver_id not in self.processes:
return False
receiver = self.processes[msg.receiver_id]
if receiver.state == ProcessState.DEAD:
return False
receiver.receive_message(msg)
self.stats['delivered'] += 1
return True
except Exception as e:
self.logger.error(f"Error delivering message: {e}")
return False
def get_stats(self) -> Dict:
"""Get delivery statistics"""
total = sum(self.stats.values())
return {
**self.stats,
'total': total,
'loss_rate': (self.stats['dropped'] / max(total, 1)) * 100
}
# ==================== Cluster Management ====================
class BullyCluster:
"""Manages a complete cluster of processes with Bully election"""
def __init__(self,
process_ids: List[int],
heartbeat_interval: float = 2.0,
heartbeat_timeout: float = 6.0,
election_timeout: float = 5.0,
packet_loss_rate: float = 0.05):
"""
Initialize cluster
Args:
process_ids: List of process IDs
heartbeat_interval: Time between heartbeats
heartbeat_timeout: Time to consider leader dead
election_timeout: Time to wait for election responses
packet_loss_rate: Network packet loss rate
"""
self.process_ids = sorted(process_ids)
self.network_sim = NetworkSimulator(packet_loss_rate=packet_loss_rate)
self.broker = MessageBroker(self.network_sim)
self.processes: Dict[int, BullyProcess] = {}
self.logger = logging.getLogger("Cluster")
# Create all processes
for pid in self.process_ids:
process = BullyProcess(
process_id=pid,
all_process_ids=self.process_ids,
heartbeat_interval=heartbeat_interval,
heartbeat_timeout=heartbeat_timeout,
election_timeout=election_timeout,
network_simulator=self.network_sim
)
self.processes[pid] = process
self.broker.register_process(process)
# Initialize with highest ID as leader
leader_id = max(self.process_ids)
self.processes[leader_id].is_leader = True
self.processes[leader_id].leader_id = leader_id
for pid in self.process_ids:
if pid != leader_id:
self.processes[pid].leader_id = leader_id
self.logger.info(f"Cluster initialized with processes: {self.process_ids}")
self.logger.info(f"Initial leader: Process {leader_id}")
def start(self):
"""Start entire cluster"""
for process in self.processes.values():
process.start()
self.broker.start()
self.logger.info("Cluster started")
def stop(self):
"""Stop entire cluster"""
for process in self.processes.values():
process.stop()
self.broker.stop()
self.logger.info("Cluster stopped")
def kill_process(self, pid: int):
"""Kill a specific process"""
if pid in self.processes:
self.logger.warning(f"Killing Process {pid}")
self.processes[pid].kill()
def revive_process(self, pid: int):
"""Revive a killed process"""
if pid in self.processes:
self.logger.info(f"Reviving Process {pid}")
self.processes[pid].revive()
def get_current_leader(self) -> Optional[int]:
"""Get current cluster leader"""
for pid, process in self.processes.items():
if process.is_leader:
return pid
return None
def print_status(self):
"""Print formatted cluster status"""
statuses = {pid: self.processes[pid].get_status()
for pid in sorted(self.process_ids)}
current_leader = self.get_current_leader()
print("\n" + "="*100)
print(f"CLUSTER STATUS - {datetime.now().strftime('%H:%M:%S')}")
print(f"Current Leader: Process {current_leader}")
print("="*100)
for pid in sorted(statuses.keys()):
s = statuses[pid]
state_icon = "✓" if s['alive'] else "💀"
leader_icon = " 👑" if s['is_leader'] else ""
election_icon = " ⚡" if s['in_election'] else ""
print(f"{state_icon} Process {pid}{leader_icon}{election_icon}")
print(f" State: {s['state']:<12} | In Election: {s['in_election']:<5} | "
f"Elections: {s['elections']:<3}")
stats = s['stats']
print(f" Sent: {stats['messages_sent']:<4} | "
f"Received: {stats['messages_received']:<4} | "
f"Dropped: {stats['messages_dropped']:<4}")
broker_stats = self.broker.get_stats()
print("\n" + "-"*100)
print(f"Message Stats - Delivered: {broker_stats['delivered']:>5} | "
f"Dropped: {broker_stats['dropped']:>5} | "
f"Retried: {broker_stats['retried']:>5} | "
f"Loss Rate: {broker_stats['loss_rate']:>5.1f}%")
print("="*100 + "\n")
def get_status_json(self) -> str:
"""Get cluster status as JSON"""
status = {
'timestamp': datetime.now().isoformat(),
'leader': self.get_current_leader(),
'processes': {
pid: self.processes[pid].get_status()
for pid in sorted(self.process_ids)
},
'broker_stats': self.broker.get_stats()
}
return json.dumps(status, indent=2, default=str)
# ==================== Testing & Examples ====================
def test_basic_election():
"""Test 1: Basic leader election"""
print("\n" + "="*100)
print("TEST 1: Basic Leader Election")
print("="*100)
cluster = BullyCluster(
process_ids=[1, 2, 3, 4, 5],
heartbeat_interval=2.0,
heartbeat_timeout=6.0,
election_timeout=5.0
)
cluster.start()
print("\n[*] Waiting for system stabilization (10s)...")
time.sleep(10)
cluster.print_status()
cluster.stop()
print("[✓] Test completed")
def test_leader_failure():
"""Test 2: Leader failure and re-election"""
print("\n" + "="*100)
print("TEST 2: Leader Failure & Re-election")
print("="*100)
cluster = BullyCluster(
process_ids=[1, 2, 3, 4, 5],
packet_loss_rate=0.05
)
cluster.start()
print("[*] System stabilizing...")
time.sleep(10)
cluster.print_status()
# Kill leader
print("\n[!] KILLING LEADER")
cluster.kill_process(5)
print("[*] Waiting for new election (10s)...")
time.sleep(10)
cluster.print_status()
cluster.stop()
print("[✓] Test completed")
def test_cascading_failures():
"""Test 3: Multiple cascading failures"""
print("\n" + "="*100)
print("TEST 3: Cascading Failures")
print("="*100)
cluster = BullyCluster(
process_ids=[1, 2, 3, 4, 5],
packet_loss_rate=0.05
)
cluster.start()
print("[*] System stabilizing (10s)...")
time.sleep(10)
cluster.print_status()
# Failure cascade
for victim in [5, 4, 3]:
print(f"\n[!] KILLING PROCESS {victim}")
cluster.kill_process(victim)
print(f"[*] Waiting for new election (8s)...")
time.sleep(8)
cluster.print_status()
cluster.stop()
print("[✓] Test completed")
def test_recovery():
"""Test 4: Process recovery"""
print("\n" + "="*100)
print("TEST 4: Process Recovery")
print("="*100)
cluster = BullyCluster(process_ids=[1, 2, 3, 4, 5])
cluster.start()
print("[*] System stabilizing (10s)...")
time.sleep(10)
cluster.print_status()
# Kill and revive
print("\n[!] KILLING PROCESS 5")
cluster.kill_process(5)
time.sleep(5)
cluster.print_status()
print("\n[!] REVIVING PROCESS 5")
cluster.revive_process(5)
print("[*] Waiting for new election (8s)...")
time.sleep(8)
cluster.print_status()
cluster.stop()
print("[✓] Test completed")
def test_network_failures():
"""Test 5: Network timeouts and retries"""
print("\n" + "="*100)
print("TEST 5: Network Failures & Timeouts")
print("="*100)
cluster = BullyCluster(
process_ids=[1, 2, 3, 4, 5],
packet_loss_rate=0.15 # Higher packet loss
)
cluster.start()
print("[*] Running with 15% packet loss")
print("[*] System stabilizing with network issues (15s)...")
time.sleep(15)
cluster.print_status()
print("\n[!] KILLING LEADER UNDER ADVERSE NETWORK CONDITIONS")
cluster.kill_process(5)
print("[*] Waiting for election (10s)...")
time.sleep(10)
cluster.print_status()
cluster.stop()
print("[✓] Test completed")
def run_all_tests():
"""Run all test scenarios"""
tests = [
(test_basic_election, 1),
(test_leader_failure, 2),
(test_cascading_failures, 3),
(test_recovery, 4),
(test_network_failures, 5),
]
for test_func, _ in tests:
try:
test_func()
time.sleep(2) # Pause between tests
except KeyboardInterrupt:
print("\n[*] Tests interrupted")
break
except Exception as e:
print(f"\n[!] Test failed with error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
test_num = int(sys.argv[1])
tests = {
1: test_basic_election,
2: test_leader_failure,
3: test_cascading_failures,
4: test_recovery,
5: test_network_failures,
}
tests.get(test_num, test_basic_election)()
else:
run_all_tests()