🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/mle_star_benchmark_example.py

This commit is contained in:
rUv committed 2025-08-06 01:48:34 +00:00
1 parent 1ece8f64a8
commit 31ee246137
7 files changed
+2992 -1

No files matched your search

@@ -0,0 +1,673 @@
#!/usr/bin/env python3
"""
Continuous Performance Monitoring System for Claude-Flow Swarm Operations
This system provides real-time performance monitoring and regression detection:
- Continuous metrics collection during swarm operations
- Real-time performance alerts and notifications
- Automatic baseline updating and trend analysis
- Integration with CI/CD pipelines for regression detection
- Performance dashboard data generation
Author: Metrics Analyst Agent
Version: 1.0.0
"""
import asyncio
import time
import json
import os
import sys
import threading
import subprocess
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Any, Optional, Callable
from dataclasses import dataclass, asdict
import psutil
import sqlite3
import logging
from contextlib import asynccontextmanager
import statistics
import warnings
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('performance_monitor.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
@dataclass
class PerformanceAlert:
"""Performance alert definition."""
metric_name: str
threshold_value: float
comparison: str # 'greater', 'less', 'equal'
severity: str # 'info', 'warning', 'critical'
message: str
timestamp: datetime
def should_trigger(self, current_value: float) -> bool:
"""Check if alert should trigger based on current value."""
if self.comparison == 'greater':
return current_value > self.threshold_value
elif self.comparison == 'less':
return current_value < self.threshold_value
elif self.comparison == 'equal':
return abs(current_value - self.threshold_value) < 0.01
return False
@dataclass
class MetricSnapshot:
"""Snapshot of performance metrics at a point in time."""
timestamp: datetime
swarm_init_time: float
agent_coordination_latency: float
memory_usage_mb: float
token_consumption_rate: float
mcp_response_time: float
neural_processing_time: float
active_agents: int
cpu_usage_percent: float
def to_dict(self) -> Dict[str, Any]:
return {
'timestamp': self.timestamp.isoformat(),
'swarm_init_time': self.swarm_init_time,
'agent_coordination_latency': self.agent_coordination_latency,
'memory_usage_mb': self.memory_usage_mb,
'token_consumption_rate': self.token_consumption_rate,
'mcp_response_time': self.mcp_response_time,
'neural_processing_time': self.neural_processing_time,
'active_agents': self.active_agents,
'cpu_usage_percent': self.cpu_usage_percent
}
class PerformanceDatabase:
"""SQLite database for storing performance metrics."""
def __init__(self, db_path: str = "performance_metrics.db"):
self.db_path = db_path
self._init_database()
def _init_database(self):
"""Initialize the performance metrics database."""
with sqlite3.connect(self.db_path) as conn:
conn.execute('''
CREATE TABLE IF NOT EXISTS metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
swarm_init_time REAL,
agent_coordination_latency REAL,
memory_usage_mb REAL,
token_consumption_rate REAL,
mcp_response_time REAL,
neural_processing_time REAL,
active_agents INTEGER,
cpu_usage_percent REAL,
session_id TEXT,
operation_type TEXT
)
''')
conn.execute('''
CREATE TABLE IF NOT EXISTS baselines (
metric_name TEXT PRIMARY KEY,
baseline_value REAL NOT NULL,
updated_at TEXT NOT NULL,
sample_count INTEGER DEFAULT 0
)
''')
conn.execute('''
CREATE TABLE IF NOT EXISTS alerts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
metric_name TEXT NOT NULL,
threshold_value REAL NOT NULL,
actual_value REAL NOT NULL,
severity TEXT NOT NULL,
message TEXT NOT NULL,
acknowledged BOOLEAN DEFAULT FALSE
)
''')
conn.commit()
def store_metrics(self, metrics: MetricSnapshot, session_id: str = None, operation_type: str = None):
"""Store metrics snapshot in database."""
with sqlite3.connect(self.db_path) as conn:
conn.execute('''
INSERT INTO metrics (
timestamp, swarm_init_time, agent_coordination_latency,
memory_usage_mb, token_consumption_rate, mcp_response_time,
neural_processing_time, active_agents, cpu_usage_percent,
session_id, operation_type
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
metrics.timestamp.isoformat(),
metrics.swarm_init_time,
metrics.agent_coordination_latency,
metrics.memory_usage_mb,
metrics.token_consumption_rate,
metrics.mcp_response_time,
metrics.neural_processing_time,
metrics.active_agents,
metrics.cpu_usage_percent,
session_id,
operation_type
))
conn.commit()
def get_recent_metrics(self, hours: int = 24) -> List[MetricSnapshot]:
"""Get metrics from the last N hours."""
cutoff = datetime.now() - timedelta(hours=hours)
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute('''
SELECT * FROM metrics
WHERE timestamp > ?
ORDER BY timestamp DESC
''', (cutoff.isoformat(),))
results = []
for row in cursor.fetchall():
results.append(MetricSnapshot(
timestamp=datetime.fromisoformat(row[1]),
swarm_init_time=row[2] or 0.0,
agent_coordination_latency=row[3] or 0.0,
memory_usage_mb=row[4] or 0.0,
token_consumption_rate=row[5] or 0.0,
mcp_response_time=row[6] or 0.0,
neural_processing_time=row[7] or 0.0,
active_agents=row[8] or 0,
cpu_usage_percent=row[9] or 0.0
))
return results
def update_baseline(self, metric_name: str, value: float):
"""Update baseline value for a metric."""
with sqlite3.connect(self.db_path) as conn:
conn.execute('''
INSERT OR REPLACE INTO baselines (metric_name, baseline_value, updated_at, sample_count)
VALUES (?, ?, ?, COALESCE((SELECT sample_count + 1 FROM baselines WHERE metric_name = ?), 1))
''', (metric_name, value, datetime.now().isoformat(), metric_name))
conn.commit()
def get_baseline(self, metric_name: str) -> Optional[float]:
"""Get baseline value for a metric."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute(
'SELECT baseline_value FROM baselines WHERE metric_name = ?',
(metric_name,)
)
result = cursor.fetchone()
return result[0] if result else None
def store_alert(self, alert: PerformanceAlert, actual_value: float):
"""Store performance alert in database."""
with sqlite3.connect(self.db_path) as conn:
conn.execute('''
INSERT INTO alerts (timestamp, metric_name, threshold_value, actual_value, severity, message)
VALUES (?, ?, ?, ?, ?, ?)
''', (
alert.timestamp.isoformat(),
alert.metric_name,
alert.threshold_value,
actual_value,
alert.severity,
alert.message
))
conn.commit()
class SwarmMetricsCollector:
"""Collects real-time metrics from swarm operations."""
def __init__(self):
self.is_collecting = False
self._collection_thread = None
self._metrics_callbacks: List[Callable[[MetricSnapshot], None]] = []
self.current_session_id = None
def start_collection(self, interval_seconds: float = 10.0, session_id: str = None):
"""Start continuous metrics collection."""
if self.is_collecting:
logger.warning("Metrics collection already running")
return
self.is_collecting = True
self.current_session_id = session_id or f"session_{int(time.time())}"
self._collection_thread = threading.Thread(
target=self._collect_metrics_loop,
args=(interval_seconds,),
daemon=True
)
self._collection_thread.start()
logger.info(f"Started metrics collection with {interval_seconds}s interval")
def stop_collection(self):
"""Stop metrics collection."""
self.is_collecting = False
if self._collection_thread:
self._collection_thread.join(timeout=5.0)
logger.info("Stopped metrics collection")
def add_metrics_callback(self, callback: Callable[[MetricSnapshot], None]):
"""Add callback to be called when new metrics are collected."""
self._metrics_callbacks.append(callback)
def _collect_metrics_loop(self, interval_seconds: float):
"""Main metrics collection loop."""
while self.is_collecting:
try:
metrics = self._collect_current_metrics()
# Call all registered callbacks
for callback in self._metrics_callbacks:
try:
callback(metrics)
except Exception as e:
logger.error(f"Error in metrics callback: {e}")
time.sleep(interval_seconds)
except Exception as e:
logger.error(f"Error in metrics collection: {e}")
time.sleep(interval_seconds)
def _collect_current_metrics(self) -> MetricSnapshot:
"""Collect current performance metrics."""
# System metrics
process = psutil.Process()
cpu_percent = process.cpu_percent(interval=0.1)
memory_mb = process.memory_info().rss / 1024 / 1024
# Swarm-specific metrics (these would be measured from actual operations)
swarm_init_time = self._measure_swarm_init_time()
agent_coordination_latency = self._measure_coordination_latency()
token_consumption_rate = self._estimate_token_consumption()
mcp_response_time = self._measure_mcp_response_time()
neural_processing_time = self._measure_neural_processing_time()
active_agents = self._count_active_agents()
return MetricSnapshot(
timestamp=datetime.now(),
swarm_init_time=swarm_init_time,
agent_coordination_latency=agent_coordination_latency,
memory_usage_mb=memory_mb,
token_consumption_rate=token_consumption_rate,
mcp_response_time=mcp_response_time,
neural_processing_time=neural_processing_time,
active_agents=active_agents,
cpu_usage_percent=cpu_percent
)
def _measure_swarm_init_time(self) -> float:
"""Measure current swarm initialization time."""
try:
start = time.time()
result = subprocess.run(
["node", "../cli.js", "swarm", "status"],
capture_output=True,
timeout=5,
cwd=str(Path(__file__).parent.parent)
)
return time.time() - start
except:
return 0.0
def _measure_coordination_latency(self) -> float:
"""Measure agent coordination latency."""
try:
start = time.time()
result = subprocess.run(
["node", "../cli.js", "swarm", "list"],
capture_output=True,
timeout=3,
cwd=str(Path(__file__).parent.parent)
)
return (time.time() - start) * 1000 # Convert to milliseconds
except:
return 0.0
def _estimate_token_consumption(self) -> float:
"""Estimate current token consumption rate."""
# This would integrate with actual token tracking
# For now, return a simulated value
return 100.0 # tokens per minute
def _measure_mcp_response_time(self) -> float:
"""Measure MCP tool response time."""
try:
start = time.time()
result = subprocess.run(
["node", "../cli.js", "mcp", "status"],
capture_output=True,
timeout=3,
cwd=str(Path(__file__).parent.parent)
)
return time.time() - start
except:
return 0.0
def _measure_neural_processing_time(self) -> float:
"""Measure neural pattern processing time."""
# This would measure actual neural processing
# For now, simulate based on system load
cpu_percent = psutil.cpu_percent(interval=0.1)
return cpu_percent * 10 # Simulated processing time in ms
def _count_active_agents(self) -> int:
"""Count currently active agents."""
try:
result = subprocess.run(
["node", "../cli.js", "swarm", "list"],
capture_output=True,
text=True,
timeout=3,
cwd=str(Path(__file__).parent.parent)
)
if result.returncode == 0:
# Count agents in output (this is a simplified parsing)
return result.stdout.count("agent") if result.stdout else 0
return 0
except:
return 0
class PerformanceMonitor:
"""Main performance monitoring system."""
def __init__(self, db_path: str = "performance_metrics.db"):
self.db = PerformanceDatabase(db_path)
self.collector = SwarmMetricsCollector()
self.alerts: List[PerformanceAlert] = []
self._setup_default_alerts()
# Register metrics callback
self.collector.add_metrics_callback(self._on_metrics_collected)
def _setup_default_alerts(self):
"""Setup default performance alerts."""
self.alerts = [
PerformanceAlert(
metric_name="swarm_init_time",
threshold_value=5.0,
comparison="greater",
severity="warning",
message="Swarm initialization time exceeded 5 seconds",
timestamp=datetime.now()
),
PerformanceAlert(
metric_name="agent_coordination_latency",
threshold_value=200.0,
comparison="greater",
severity="warning",
message="Agent coordination latency exceeded 200ms",
timestamp=datetime.now()
),
PerformanceAlert(
metric_name="memory_usage_mb",
threshold_value=100.0,
comparison="greater",
severity="critical",
message="Memory usage exceeded 100MB",
timestamp=datetime.now()
),
PerformanceAlert(
metric_name="mcp_response_time",
threshold_value=1.0,
comparison="greater",
severity="warning",
message="MCP response time exceeded 1 second",
timestamp=datetime.now()
)
]
def start_monitoring(self, interval_seconds: float = 10.0, session_id: str = None):
"""Start continuous performance monitoring."""
logger.info("Starting performance monitoring...")
self.collector.start_collection(interval_seconds, session_id)
def stop_monitoring(self):
"""Stop performance monitoring."""
logger.info("Stopping performance monitoring...")
self.collector.stop_collection()
def _on_metrics_collected(self, metrics: MetricSnapshot):
"""Handle newly collected metrics."""
# Store in database
self.db.store_metrics(
metrics,
session_id=self.collector.current_session_id,
operation_type="continuous_monitoring"
)
# Check alerts
self._check_alerts(metrics)
# Update baselines (every 100 samples)
if hash(metrics.timestamp) % 100 == 0:
self._update_baselines(metrics)
# Log summary
logger.info(f"Metrics collected - Memory: {metrics.memory_usage_mb:.1f}MB, "
f"CPU: {metrics.cpu_usage_percent:.1f}%, "
f"Agents: {metrics.active_agents}")
def _check_alerts(self, metrics: MetricSnapshot):
"""Check if any alerts should be triggered."""
metrics_dict = metrics.to_dict()
for alert in self.alerts:
if alert.metric_name in metrics_dict:
current_value = metrics_dict[alert.metric_name]
if isinstance(current_value, (int, float)) and alert.should_trigger(current_value):
# Store alert
self.db.store_alert(alert, current_value)
# Log alert
logger.warning(f"ALERT [{alert.severity.upper()}] {alert.message} "
f"(Value: {current_value}, Threshold: {alert.threshold_value})")
# Could send notifications here (email, slack, etc.)
self._send_notification(alert, current_value)
def _update_baselines(self, metrics: MetricSnapshot):
"""Update performance baselines with current metrics."""
metrics_dict = metrics.to_dict()
for metric_name, value in metrics_dict.items():
if isinstance(value, (int, float)) and metric_name != 'timestamp':
self.db.update_baseline(metric_name, value)
def _send_notification(self, alert: PerformanceAlert, actual_value: float):
"""Send performance alert notification."""
# This would integrate with notification systems
# For now, just log the notification
logger.info(f"NOTIFICATION: {alert.message} (Value: {actual_value})")
def get_performance_dashboard_data(self, hours: int = 24) -> Dict[str, Any]:
"""Get data for performance dashboard."""
recent_metrics = self.db.get_recent_metrics(hours)
if not recent_metrics:
return {"error": "No recent metrics available"}
# Calculate aggregated statistics
init_times = [m.swarm_init_time for m in recent_metrics if m.swarm_init_time > 0]
coordination_latencies = [m.agent_coordination_latency for m in recent_metrics if m.agent_coordination_latency > 0]
memory_usage = [m.memory_usage_mb for m in recent_metrics]
dashboard_data = {
"summary": {
"total_samples": len(recent_metrics),
"time_range_hours": hours,
"last_update": recent_metrics[0].timestamp.isoformat() if recent_metrics else None
},
"swarm_performance": {
"avg_init_time": statistics.mean(init_times) if init_times else 0,
"max_init_time": max(init_times) if init_times else 0,
"avg_coordination_latency": statistics.mean(coordination_latencies) if coordination_latencies else 0,
"max_coordination_latency": max(coordination_latencies) if coordination_latencies else 0
},
"resource_usage": {
"avg_memory_mb": statistics.mean(memory_usage) if memory_usage else 0,
"peak_memory_mb": max(memory_usage) if memory_usage else 0,
"memory_trend": "increasing" if len(memory_usage) > 1 and memory_usage[-1] > memory_usage[0] else "stable"
},
"time_series": [m.to_dict() for m in recent_metrics[-100:]], # Last 100 samples for charts
"baselines": {
"swarm_init_time": self.db.get_baseline("swarm_init_time"),
"agent_coordination_latency": self.db.get_baseline("agent_coordination_latency"),
"memory_usage_mb": self.db.get_baseline("memory_usage_mb")
}
}
return dashboard_data
def generate_regression_report(self) -> Dict[str, Any]:
"""Generate performance regression analysis report."""
recent_metrics = self.db.get_recent_metrics(24) # Last 24 hours
older_metrics = self.db.get_recent_metrics(168) # Last 7 days
if len(recent_metrics) < 10 or len(older_metrics) < 50:
return {"error": "Insufficient data for regression analysis"}
# Calculate recent vs historical averages
recent_avg_init = statistics.mean([m.swarm_init_time for m in recent_metrics if m.swarm_init_time > 0])
historical_avg_init = statistics.mean([m.swarm_init_time for m in older_metrics if m.swarm_init_time > 0])
recent_avg_memory = statistics.mean([m.memory_usage_mb for m in recent_metrics])
historical_avg_memory = statistics.mean([m.memory_usage_mb for m in older_metrics])
# Calculate regression percentages
init_regression = ((recent_avg_init - historical_avg_init) / historical_avg_init) * 100 if historical_avg_init > 0 else 0
memory_regression = ((recent_avg_memory - historical_avg_memory) / historical_avg_memory) * 100 if historical_avg_memory > 0 else 0
return {
"analysis_period": {
"recent_period_hours": 24,
"historical_period_hours": 168,
"recent_samples": len(recent_metrics),
"historical_samples": len(older_metrics)
},
"regression_analysis": {
"swarm_init_time": {
"recent_avg": recent_avg_init,
"historical_avg": historical_avg_init,
"regression_percent": init_regression,
"regression_detected": abs(init_regression) > 10 # 10% threshold
},
"memory_usage": {
"recent_avg": recent_avg_memory,
"historical_avg": historical_avg_memory,
"regression_percent": memory_regression,
"regression_detected": abs(memory_regression) > 15 # 15% threshold
}
},
"recommendations": self._generate_regression_recommendations(init_regression, memory_regression)
}
def _generate_regression_recommendations(self, init_regression: float, memory_regression: float) -> List[str]:
"""Generate recommendations based on regression analysis."""
recommendations = []
if init_regression > 10:
recommendations.append("Swarm initialization time has regressed by >10% - investigate startup optimizations")
if memory_regression > 15:
recommendations.append("Memory usage has increased by >15% - check for memory leaks")
if init_regression < -10:
recommendations.append("Swarm initialization time has improved significantly - consider documenting optimizations")
if not recommendations:
recommendations.append("No significant performance regressions detected")
return recommendations
async def run_continuous_monitoring(duration_minutes: int = 60, interval_seconds: float = 10.0):
"""Run continuous monitoring for specified duration."""
monitor = PerformanceMonitor()
try:
# Start monitoring
session_id = f"continuous_{int(time.time())}"
monitor.start_monitoring(interval_seconds, session_id)
logger.info(f"Running continuous monitoring for {duration_minutes} minutes...")
# Run for specified duration
await asyncio.sleep(duration_minutes * 60)
# Generate reports
dashboard_data = monitor.get_performance_dashboard_data()
regression_report = monitor.generate_regression_report()
# Save reports
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
dashboard_file = Path(f"dashboard_data_{timestamp}.json")
with open(dashboard_file, 'w') as f:
json.dump(dashboard_data, f, indent=2, default=str)
regression_file = Path(f"regression_report_{timestamp}.json")
with open(regression_file, 'w') as f:
json.dump(regression_report, f, indent=2, default=str)
logger.info(f"Reports saved: {dashboard_file}, {regression_file}")
return {
"monitoring_duration_minutes": duration_minutes,
"dashboard_data": dashboard_data,
"regression_report": regression_report
}
finally:
monitor.stop_monitoring()
def main():
"""Main entry point for continuous performance monitoring."""
import argparse
parser = argparse.ArgumentParser(description="Continuous Performance Monitor")
parser.add_argument("--duration", type=int, default=60, help="Monitoring duration in minutes")
parser.add_argument("--interval", type=float, default=10.0, help="Collection interval in seconds")
parser.add_argument("--dashboard", action="store_true", help="Generate dashboard data only")
parser.add_argument("--regression", action="store_true", help="Generate regression report only")
args = parser.parse_args()
if args.dashboard:
# Generate dashboard data
monitor = PerformanceMonitor()
data = monitor.get_performance_dashboard_data()
print(json.dumps(data, indent=2, default=str))
elif args.regression:
# Generate regression report
monitor = PerformanceMonitor()
report = monitor.generate_regression_report()
print(json.dumps(report, indent=2, default=str))
else:
# Run continuous monitoring
asyncio.run(run_continuous_monitoring(args.duration, args.interval))
if __name__ == "__main__":
main()
+902
View File
@@ -0,0 +1,902 @@
#!/usr/bin/env python3
"""
Hive Mind Load Testing Suite - Comprehensive Stress Testing
Benchmark-Tester Agent Implementation
This script executes comprehensive load and stress testing of the Hive Mind system,
testing scalability from 1 to 1000+ agents with various topologies and coordination modes.
"""
import os
import sys
import json
import time
import sqlite3
import threading
import subprocess
import psutil
import multiprocessing
from datetime import datetime
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import Dict, List, Any, Optional, Tuple
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
import statistics
@dataclass
class LoadTestConfig:
"""Configuration for load testing scenarios"""
name: str
description: str
agent_count: int
topology: str # hierarchical, mesh, ring, star
coordination: str # queen, consensus, hybrid, democracy
memory_type: str # sqlite, memory, distributed
concurrent_swarms: int = 1
task_complexity: str = "medium" # simple, medium, complex, enterprise
duration_seconds: int = 60
ramp_up_seconds: int = 10
expected_success_rate: float = 0.95
stress_mode: bool = False
@dataclass
class LoadTestResult:
"""Results from load testing"""
config: LoadTestConfig
start_time: str
end_time: str
total_duration: float
successful_agents: int
failed_agents: int
peak_memory_mb: float
peak_cpu_percent: float
average_response_time_ms: float
p95_response_time_ms: float
p99_response_time_ms: float
throughput_ops_per_sec: float
error_rate: float
coordination_failures: int
consensus_timeouts: int
memory_operations: int
database_locks: int
network_errors: int
recovery_time_seconds: float
breaking_point_reached: bool
system_stable: bool
resource_exhaustion: bool
error_messages: List[str]
class HiveMindLoadTester:
"""Comprehensive load testing for Hive Mind system"""
def __init__(self, output_dir: str = "load-test-results"):
self.output_dir = Path(output_dir)
self.output_dir.mkdir(exist_ok=True)
self.results: List[LoadTestResult] = []
self.cli_path = self._find_cli_path()
self.system_monitor = SystemMonitor()
def _find_cli_path(self) -> Path:
"""Find the claude-flow CLI executable"""
possible_paths = [
Path("../src/cli/simple-cli.js"),
Path("./src/cli/simple-cli.js"),
Path("./claude-flow"),
Path("../claude-flow")
]
for path in possible_paths:
if path.exists():
return path
# Fallback to system claude-flow
return Path("claude-flow")
def create_load_test_scenarios(self) -> List[LoadTestConfig]:
"""Create comprehensive load testing scenarios"""
scenarios = []
# Progressive scaling tests (1 -> 1000 agents)
scaling_tests = [
(1, "Baseline single agent", 30),
(5, "Small team coordination", 30),
(10, "Small organization", 45),
(25, "Medium team", 60),
(50, "Large team", 90),
(100, "Department scale", 120),
(250, "Enterprise division", 180),
(500, "Large enterprise", 240),
(1000, "Massive scale", 300)
]
for count, desc, duration in scaling_tests:
# Test optimal configuration for each scale
scenarios.append(LoadTestConfig(
name=f"scale_test_{count}_agents",
description=f"{desc} - {count} agents",
agent_count=count,
topology="hierarchical" if count <= 100 else "mesh",
coordination="queen" if count <= 50 else "consensus",
memory_type="sqlite" if count <= 100 else "distributed",
duration_seconds=duration,
ramp_up_seconds=max(5, count // 10)
))
# Topology stress tests
topologies = ["hierarchical", "mesh", "ring", "star"]
for topology in topologies:
scenarios.append(LoadTestConfig(
name=f"topology_stress_{topology}",
description=f"Stress test {topology} topology with 100 agents",
agent_count=100,
topology=topology,
coordination="consensus",
memory_type="distributed",
duration_seconds=120,
stress_mode=True
))
# Coordination mode stress tests
coordination_modes = ["queen", "consensus", "hybrid", "democracy"]
for mode in coordination_modes:
scenarios.append(LoadTestConfig(
name=f"coordination_stress_{mode}",
description=f"Stress test {mode} coordination with 50 agents",
agent_count=50,
topology="mesh",
coordination=mode,
memory_type="sqlite",
duration_seconds=90,
stress_mode=True
))
# Concurrent swarm tests
scenarios.extend([
LoadTestConfig(
name="concurrent_swarms_2",
description="2 concurrent swarms of 25 agents each",
agent_count=25,
topology="hierarchical",
coordination="queen",
memory_type="sqlite",
concurrent_swarms=2,
duration_seconds=90
),
LoadTestConfig(
name="concurrent_swarms_5",
description="5 concurrent swarms of 20 agents each",
agent_count=20,
topology="mesh",
coordination="consensus",
memory_type="memory",
concurrent_swarms=5,
duration_seconds=120
),
LoadTestConfig(
name="concurrent_swarms_10",
description="10 concurrent swarms of 10 agents each",
agent_count=10,
topology="star",
coordination="hybrid",
memory_type="distributed",
concurrent_swarms=10,
duration_seconds=180,
stress_mode=True
)
])
# Memory system stress tests
scenarios.extend([
LoadTestConfig(
name="memory_stress_sqlite",
description="SQLite memory stress with 200 agents",
agent_count=200,
topology="hierarchical",
coordination="queen",
memory_type="sqlite",
duration_seconds=150,
task_complexity="complex",
stress_mode=True
),
LoadTestConfig(
name="memory_stress_distributed",
description="Distributed memory stress with 500 agents",
agent_count=500,
topology="mesh",
coordination="consensus",
memory_type="distributed",
duration_seconds=200,
task_complexity="enterprise",
stress_mode=True
)
])
# Breaking point discovery tests
scenarios.extend([
LoadTestConfig(
name="breaking_point_1500",
description="Find breaking point at 1500 agents",
agent_count=1500,
topology="mesh",
coordination="consensus",
memory_type="distributed",
duration_seconds=300,
expected_success_rate=0.5,
stress_mode=True
),
LoadTestConfig(
name="breaking_point_2000",
description="Find breaking point at 2000 agents",
agent_count=2000,
topology="hierarchical",
coordination="queen",
memory_type="distributed",
duration_seconds=300,
expected_success_rate=0.3,
stress_mode=True
)
])
return scenarios
def run_hive_mind_command(self, command: List[str], timeout: int = 120) -> Dict[str, Any]:
"""Execute hive-mind command with performance monitoring"""
start_time = time.time()
try:
# Start system monitoring
monitor_process = self.system_monitor.start_monitoring()
# Execute command
result = subprocess.run(
["node", str(self.cli_path)] + command,
capture_output=True,
text=True,
timeout=timeout,
cwd=Path.cwd()
)
end_time = time.time()
duration = end_time - start_time
# Stop monitoring and get metrics
metrics = self.system_monitor.stop_monitoring(monitor_process)
return {
"success": result.returncode == 0,
"duration": duration,
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode,
"metrics": metrics
}
except subprocess.TimeoutExpired:
self.system_monitor.stop_monitoring(None)
return {
"success": False,
"duration": timeout,
"stdout": "",
"stderr": f"Command timed out after {timeout} seconds",
"returncode": -1,
"metrics": {}
}
except Exception as e:
self.system_monitor.stop_monitoring(None)
return {
"success": False,
"duration": time.time() - start_time,
"stdout": "",
"stderr": str(e),
"returncode": -1,
"metrics": {}
}
def run_single_swarm_load_test(self, config: LoadTestConfig, swarm_id: int = 0) -> Dict[str, Any]:
"""Run load test for a single swarm"""
print(f"🔥 Starting swarm {swarm_id} load test: {config.name}")
start_time = time.time()
response_times = []
errors = []
try:
# Initialize swarm
init_cmd = [
"hive-mind", "init",
"--test-mode",
"--swarm-id", f"{config.name}_swarm_{swarm_id}"
]
init_result = self.run_hive_mind_command(init_cmd, timeout=60)
if not init_result["success"]:
raise Exception(f"Swarm initialization failed: {init_result['stderr']}")
# Ramp up agents gradually
agents_spawned = 0
ramp_increment = max(1, config.agent_count // (config.ramp_up_seconds // 2))
while agents_spawned < config.agent_count:
batch_size = min(ramp_increment, config.agent_count - agents_spawned)
spawn_start = time.time()
spawn_cmd = [
"hive-mind", "spawn",
f"Load test batch {agents_spawned}-{agents_spawned + batch_size}",
"--topology", config.topology,
"--coordination", config.coordination,
"--memory", config.memory_type,
"--agents", str(batch_size),
"--stress-test" if config.stress_mode else "--load-test"
]
spawn_result = self.run_hive_mind_command(spawn_cmd, timeout=120)
spawn_time = time.time() - spawn_start
response_times.append(spawn_time * 1000) # Convert to ms
if not spawn_result["success"]:
errors.append(f"Agent spawn failed: {spawn_result['stderr']}")
break
agents_spawned += batch_size
# Brief pause between batches during ramp-up
if agents_spawned < config.agent_count:
time.sleep(1)
# Run sustained load for duration
test_start = time.time()
operations_completed = 0
while time.time() - test_start < config.duration_seconds:
# Execute coordination tasks
task_start = time.time()
task_cmd = [
"hive-mind", "task",
f"Load test operation {operations_completed}",
"--complexity", config.task_complexity,
"--timeout", "30"
]
task_result = self.run_hive_mind_command(task_cmd, timeout=30)
task_time = time.time() - task_start
response_times.append(task_time * 1000)
if not task_result["success"]:
errors.append(f"Task execution failed: {task_result['stderr']}")
operations_completed += 1
# Brief pause between operations
time.sleep(0.5)
# Cleanup swarm
cleanup_cmd = ["hive-mind", "cleanup", "--swarm-id", f"{config.name}_swarm_{swarm_id}"]
cleanup_result = self.run_hive_mind_command(cleanup_cmd, timeout=60)
total_duration = time.time() - start_time
return {
"swarm_id": swarm_id,
"success": len(errors) == 0,
"duration": total_duration,
"agents_spawned": agents_spawned,
"operations_completed": operations_completed,
"response_times": response_times,
"errors": errors,
"throughput": operations_completed / config.duration_seconds if config.duration_seconds > 0 else 0
}
except Exception as e:
return {
"swarm_id": swarm_id,
"success": False,
"duration": time.time() - start_time,
"agents_spawned": 0,
"operations_completed": 0,
"response_times": [],
"errors": [str(e)],
"throughput": 0
}
def run_load_test(self, config: LoadTestConfig) -> LoadTestResult:
"""Run comprehensive load test for a configuration"""
print(f"🚀 Running load test: {config.name}")
print(f" 📊 {config.agent_count} agents, {config.concurrent_swarms} swarms")
print(f" 🏗️ Topology: {config.topology}, Coordination: {config.coordination}")
print(f" 💾 Memory: {config.memory_type}, Duration: {config.duration_seconds}s")
start_time = datetime.now().isoformat()
test_start = time.time()
# Start system monitoring
system_monitor_process = self.system_monitor.start_monitoring()
try:
# Run concurrent swarms if specified
if config.concurrent_swarms > 1:
with ThreadPoolExecutor(max_workers=config.concurrent_swarms) as executor:
futures = {
executor.submit(self.run_single_swarm_load_test, config, i): i
for i in range(config.concurrent_swarms)
}
swarm_results = []
for future in as_completed(futures):
result = future.result()
swarm_results.append(result)
swarm_id = futures[future]
status = "✅" if result["success"] else "❌"
print(f" {status} Swarm {swarm_id}: {result['operations_completed']} ops")
else:
# Single swarm test
swarm_result = self.run_single_swarm_load_test(config, 0)
swarm_results = [swarm_result]
# Stop system monitoring and collect metrics
system_metrics = self.system_monitor.stop_monitoring(system_monitor_process)
# Aggregate results from all swarms
total_duration = time.time() - test_start
end_time = datetime.now().isoformat()
# Calculate aggregate metrics
all_response_times = []
all_errors = []
total_agents = 0
total_operations = 0
successful_swarms = 0
for result in swarm_results:
all_response_times.extend(result["response_times"])
all_errors.extend(result["errors"])
total_agents += result["agents_spawned"]
total_operations += result["operations_completed"]
if result["success"]:
successful_swarms += 1
# Calculate performance metrics
avg_response_time = statistics.mean(all_response_times) if all_response_times else 0
p95_response_time = statistics.quantiles(all_response_times, n=20)[18] if len(all_response_times) > 20 else 0
p99_response_time = statistics.quantiles(all_response_times, n=100)[98] if len(all_response_times) > 100 else 0
throughput = total_operations / config.duration_seconds if config.duration_seconds > 0 else 0
error_rate = len(all_errors) / (total_operations + len(all_errors)) if (total_operations + len(all_errors)) > 0 else 0
# Determine system stability
success_rate = successful_swarms / len(swarm_results) if swarm_results else 0
system_stable = success_rate >= config.expected_success_rate
breaking_point_reached = success_rate < 0.5
resource_exhaustion = system_metrics.get("peak_memory_mb", 0) > 8000 or system_metrics.get("peak_cpu_percent", 0) > 95
return LoadTestResult(
config=config,
start_time=start_time,
end_time=end_time,
total_duration=total_duration,
successful_agents=total_agents,
failed_agents=max(0, config.agent_count * config.concurrent_swarms - total_agents),
peak_memory_mb=system_metrics.get("peak_memory_mb", 0),
peak_cpu_percent=system_metrics.get("peak_cpu_percent", 0),
average_response_time_ms=avg_response_time,
p95_response_time_ms=p95_response_time,
p99_response_time_ms=p99_response_time,
throughput_ops_per_sec=throughput,
error_rate=error_rate,
coordination_failures=len([e for e in all_errors if "coordination" in e.lower()]),
consensus_timeouts=len([e for e in all_errors if "timeout" in e.lower()]),
memory_operations=total_operations * 3, # Estimated
database_locks=len([e for e in all_errors if "lock" in e.lower()]),
network_errors=len([e for e in all_errors if "network" in e.lower()]),
recovery_time_seconds=0, # Would need additional monitoring
breaking_point_reached=breaking_point_reached,
system_stable=system_stable,
resource_exhaustion=resource_exhaustion,
error_messages=all_errors[:10] # Keep first 10 errors
)
except Exception as e:
self.system_monitor.stop_monitoring(system_monitor_process)
return LoadTestResult(
config=config,
start_time=start_time,
end_time=datetime.now().isoformat(),
total_duration=time.time() - test_start,
successful_agents=0,
failed_agents=config.agent_count * config.concurrent_swarms,
peak_memory_mb=0,
peak_cpu_percent=0,
average_response_time_ms=0,
p95_response_time_ms=0,
p99_response_time_ms=0,
throughput_ops_per_sec=0,
error_rate=1.0,
coordination_failures=1,
consensus_timeouts=0,
memory_operations=0,
database_locks=0,
network_errors=0,
recovery_time_seconds=0,
breaking_point_reached=True,
system_stable=False,
resource_exhaustion=True,
error_messages=[str(e)]
)
def run_progressive_load_testing(self, scenarios: List[LoadTestConfig]) -> List[LoadTestResult]:
"""Run load tests progressively, stopping at breaking points"""
results = []
# Sort scenarios by agent count for progressive testing
sorted_scenarios = sorted(scenarios, key=lambda s: s.agent_count)
print("🎯 Starting Progressive Load Testing")
print("=" * 50)
for i, scenario in enumerate(sorted_scenarios):
print(f"\n📈 Test {i+1}/{len(sorted_scenarios)}: {scenario.name}")
result = self.run_load_test(scenario)
results.append(result)
# Report result
status = "✅" if result.system_stable else "❌"
print(f"{status} {scenario.name}: {result.successful_agents}/{scenario.agent_count * scenario.concurrent_swarms} agents")
print(f" ⚡ Throughput: {result.throughput_ops_per_sec:.1f} ops/sec")
print(f" 🧠 Memory: {result.peak_memory_mb:.1f}MB, CPU: {result.peak_cpu_percent:.1f}%")
print(f" 🎯 Response time: {result.average_response_time_ms:.1f}ms (P95: {result.p95_response_time_ms:.1f}ms)")
# Check if we should continue
if result.breaking_point_reached:
print(f"🚨 Breaking point reached at {scenario.agent_count} agents!")
if scenario.agent_count >= 500: # Continue testing if we've reached a reasonable scale
print(" Continuing with remaining tests for completeness...")
else:
print(" Stopping progressive testing due to early failure.")
break
# Brief pause between tests for system recovery
time.sleep(5)
return results
def analyze_load_test_results(self, results: List[LoadTestResult]) -> Dict[str, Any]:
"""Analyze load test results and generate insights"""
if not results:
return {"error": "No results to analyze"}
successful_results = [r for r in results if r.system_stable]
failed_results = [r for r in results if not r.system_stable]
breaking_points = [r for r in results if r.breaking_point_reached]
# Find scaling limits
max_stable_agents = max([r.successful_agents for r in successful_results], default=0)
breaking_point_agents = min([r.config.agent_count for r in breaking_points], default=None)
# Performance characteristics
performance_by_scale = {}
for result in successful_results:
scale = self._categorize_scale(result.config.agent_count)
if scale not in performance_by_scale:
performance_by_scale[scale] = []
performance_by_scale[scale].append({
"agents": result.config.agent_count,
"throughput": result.throughput_ops_per_sec,
"response_time": result.average_response_time_ms,
"memory_mb": result.peak_memory_mb,
"cpu_percent": result.peak_cpu_percent
})
# Topology performance comparison
topology_performance = {}
for result in successful_results:
topology = result.config.topology
if topology not in topology_performance:
topology_performance[topology] = []
topology_performance[topology].append({
"agents": result.config.agent_count,
"throughput": result.throughput_ops_per_sec,
"response_time": result.average_response_time_ms,
"coordination_failures": result.coordination_failures
})
# Resource utilization analysis
resource_analysis = {
"memory_efficiency": {},
"cpu_efficiency": {},
"breaking_points": {}
}
for result in results:
agent_count = result.config.agent_count
if result.successful_agents > 0:
memory_per_agent = result.peak_memory_mb / result.successful_agents
cpu_per_agent = result.peak_cpu_percent / result.successful_agents
resource_analysis["memory_efficiency"][agent_count] = memory_per_agent
resource_analysis["cpu_efficiency"][agent_count] = cpu_per_agent
if result.breaking_point_reached:
resource_analysis["breaking_points"][agent_count] = {
"error_rate": result.error_rate,
"resource_exhaustion": result.resource_exhaustion,
"coordination_failures": result.coordination_failures
}
# Recommendations
recommendations = []
if max_stable_agents < 100:
recommendations.append("System shows scaling issues below 100 agents. Consider optimizing coordination mechanisms.")
elif max_stable_agents < 500:
recommendations.append("Good performance up to medium scale. Consider distributed memory for larger deployments.")
else:
recommendations.append("Excellent scaling characteristics. System ready for enterprise deployment.")
if breaking_point_agents and breaking_point_agents < 1000:
recommendations.append(f"Breaking point identified at {breaking_point_agents} agents. Implement sharding or federation for larger scales.")
# Performance targets assessment
targets_met = {
"response_time_target": len([r for r in successful_results if r.average_response_time_ms < 1000]),
"throughput_target": len([r for r in successful_results if r.throughput_ops_per_sec > 10]),
"memory_target": len([r for r in successful_results if r.peak_memory_mb < 2000]),
"stability_target": len([r for r in successful_results if r.error_rate < 0.05])
}
return {
"summary": {
"total_tests": len(results),
"successful_tests": len(successful_results),
"failed_tests": len(failed_results),
"max_stable_agents": max_stable_agents,
"breaking_point_agents": breaking_point_agents,
"avg_throughput": statistics.mean([r.throughput_ops_per_sec for r in successful_results]) if successful_results else 0,
"avg_response_time_ms": statistics.mean([r.average_response_time_ms for r in successful_results]) if successful_results else 0,
"peak_memory_usage_mb": max([r.peak_memory_mb for r in results], default=0),
"peak_cpu_usage_percent": max([r.peak_cpu_percent for r in results], default=0)
},
"performance_by_scale": performance_by_scale,
"topology_performance": topology_performance,
"resource_analysis": resource_analysis,
"recommendations": recommendations,
"targets_assessment": targets_met,
"scaling_characteristics": {
"linear_scaling_limit": max_stable_agents,
"degradation_point": breaking_point_agents,
"resource_efficiency_curve": resource_analysis["memory_efficiency"]
}
}
def _categorize_scale(self, agent_count: int) -> str:
"""Categorize agent count into scale categories"""
if agent_count <= 10:
return "small"
elif agent_count <= 100:
return "medium"
elif agent_count <= 500:
return "large"
else:
return "enterprise"
def save_load_test_results(self, results: List[LoadTestResult], analysis: Dict[str, Any]):
"""Save load test results and analysis"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Save detailed results
results_file = self.output_dir / f"hive_mind_load_test_results_{timestamp}.json"
with open(results_file, 'w') as f:
json.dump([asdict(r) for r in results], f, indent=2)
# Save analysis
analysis_file = self.output_dir / f"hive_mind_load_test_analysis_{timestamp}.json"
with open(analysis_file, 'w') as f:
json.dump(analysis, f, indent=2)
# Save performance summary CSV
csv_file = self.output_dir / f"hive_mind_load_test_summary_{timestamp}.csv"
with open(csv_file, 'w') as f:
f.write("test_name,agent_count,concurrent_swarms,topology,coordination,memory_type,")
f.write("successful_agents,throughput_ops_sec,avg_response_ms,p95_response_ms,")
f.write("peak_memory_mb,peak_cpu_percent,error_rate,system_stable,breaking_point\\n")
for result in results:
config = result.config
f.write(f"{config.name},{config.agent_count},{config.concurrent_swarms},")
f.write(f"{config.topology},{config.coordination},{config.memory_type},")
f.write(f"{result.successful_agents},{result.throughput_ops_per_sec:.2f},")
f.write(f"{result.average_response_time_ms:.1f},{result.p95_response_time_ms:.1f},")
f.write(f"{result.peak_memory_mb:.1f},{result.peak_cpu_percent:.1f},")
f.write(f"{result.error_rate:.3f},{result.system_stable},{result.breaking_point_reached}\\n")
print(f"📊 Load test results saved:")
print(f" 📄 Detailed results: {results_file}")
print(f" 📈 Analysis: {analysis_file}")
print(f" 📋 Summary CSV: {csv_file}")
return {
"results_file": str(results_file),
"analysis_file": str(analysis_file),
"csv_file": str(csv_file)
}
def run_comprehensive_load_testing(self) -> Dict[str, Any]:
"""Run complete load testing suite"""
print("🔥 Hive Mind Comprehensive Load Testing Suite")
print("=" * 60)
print("🎯 Testing scalability from 1 to 1000+ agents")
print("🚀 Multiple topologies and coordination modes")
print("💾 Different memory backends")
print("🔍 Breaking point discovery")
print("=" * 60)
# Create test scenarios
scenarios = self.create_load_test_scenarios()
print(f"📋 Created {len(scenarios)} load test scenarios")
# Run progressive load testing
start_time = time.time()
results = self.run_progressive_load_testing(scenarios)
total_duration = time.time() - start_time
print(f"\\n⏱️ Total testing time: {total_duration:.1f} seconds")
# Analyze results
analysis = self.analyze_load_test_results(results)
# Save results
file_info = self.save_load_test_results(results, analysis)
# Add metadata
analysis["metadata"] = {
"total_duration_seconds": total_duration,
"test_time": datetime.now().isoformat(),
"scenario_count": len(scenarios),
"system_info": {
"cpu_count": multiprocessing.cpu_count(),
"memory_gb": psutil.virtual_memory().total / (1024**3),
"python_version": sys.version,
"platform": sys.platform
}
}
analysis["files"] = file_info
return analysis
class SystemMonitor:
"""Monitor system resources during load testing"""
def __init__(self):
self.monitoring = False
self.metrics = {
"cpu_samples": [],
"memory_samples": [],
"io_samples": []
}
def start_monitoring(self) -> threading.Thread:
"""Start monitoring system resources"""
self.monitoring = True
self.metrics = {"cpu_samples": [], "memory_samples": [], "io_samples": []}
def monitor():
while self.monitoring:
try:
# CPU usage
cpu_percent = psutil.cpu_percent(interval=1)
self.metrics["cpu_samples"].append(cpu_percent)
# Memory usage
memory = psutil.virtual_memory()
self.metrics["memory_samples"].append(memory.percent)
# I/O stats
io_counters = psutil.disk_io_counters()
if io_counters:
self.metrics["io_samples"].append({
"read_bytes": io_counters.read_bytes,
"write_bytes": io_counters.write_bytes
})
except Exception:
pass # Continue monitoring despite errors
time.sleep(1)
thread = threading.Thread(target=monitor)
thread.daemon = True
thread.start()
return thread
def stop_monitoring(self, thread: Optional[threading.Thread]) -> Dict[str, Any]:
"""Stop monitoring and return collected metrics"""
self.monitoring = False
if thread:
thread.join(timeout=2)
if not self.metrics["cpu_samples"]:
return {}
return {
"peak_cpu_percent": max(self.metrics["cpu_samples"]),
"avg_cpu_percent": statistics.mean(self.metrics["cpu_samples"]),
"peak_memory_percent": max(self.metrics["memory_samples"]),
"avg_memory_percent": statistics.mean(self.metrics["memory_samples"]),
"peak_memory_mb": max(self.metrics["memory_samples"]) * psutil.virtual_memory().total / (1024**2) / 100,
"sample_count": len(self.metrics["cpu_samples"])
}
def main():
"""Main load testing execution"""
import argparse
parser = argparse.ArgumentParser(description="Hive Mind Load Testing Suite")
parser.add_argument("--quick", action="store_true", help="Run quick load test with reduced scenarios")
parser.add_argument("--scale", type=int, help="Test specific agent scale")
parser.add_argument("--output", default="load-test-results", help="Output directory")
parser.add_argument("--max-agents", type=int, default=1000, help="Maximum agents to test")
args = parser.parse_args()
tester = HiveMindLoadTester(output_dir=args.output)
if args.quick:
# Quick test scenarios
scenarios = [
LoadTestConfig("quick_small", "Quick small scale test", 5, "hierarchical", "queen", "sqlite", duration_seconds=30),
LoadTestConfig("quick_medium", "Quick medium scale test", 25, "mesh", "consensus", "memory", duration_seconds=45),
LoadTestConfig("quick_large", "Quick large scale test", 100, "hierarchical", "queen", "distributed", duration_seconds=60)
]
print("🚀 Running quick load test...")
results = []
for scenario in scenarios:
result = tester.run_load_test(scenario)
results.append(result)
analysis = tester.analyze_load_test_results(results)
tester.save_load_test_results(results, analysis)
elif args.scale:
# Test specific scale
scenario = LoadTestConfig(
f"custom_scale_{args.scale}",
f"Custom scale test with {args.scale} agents",
args.scale,
"hierarchical" if args.scale <= 100 else "mesh",
"queen" if args.scale <= 50 else "consensus",
"sqlite" if args.scale <= 100 else "distributed",
duration_seconds=max(60, args.scale // 10)
)
print(f"🎯 Running custom scale test with {args.scale} agents...")
result = tester.run_load_test(scenario)
analysis = tester.analyze_load_test_results([result])
tester.save_load_test_results([result], analysis)
else:
# Full comprehensive load testing
analysis = tester.run_comprehensive_load_testing()
# Print summary
summary = analysis["summary"]
print("\\n🎯 LOAD TESTING SUMMARY")
print("=" * 50)
print(f"Total tests: {summary['total_tests']}")
print(f"Successful tests: {summary['successful_tests']}")
print(f"Max stable agents: {summary['max_stable_agents']}")
print(f"Breaking point: {summary['breaking_point_agents']} agents" if summary['breaking_point_agents'] else "No breaking point found")
print(f"Average throughput: {summary['avg_throughput']:.1f} ops/sec")
print(f"Average response time: {summary['avg_response_time_ms']:.1f}ms")
print(f"Peak memory usage: {summary['peak_memory_usage_mb']:.1f}MB")
print(f"Peak CPU usage: {summary['peak_cpu_usage_percent']:.1f}%")
# Print recommendations
if analysis["recommendations"]:
print("\\n💡 RECOMMENDATIONS")
for i, rec in enumerate(analysis["recommendations"], 1):
print(f"{i}. {rec}")
if __name__ == "__main__":
main()
+935
View File
@@ -0,0 +1,935 @@
#!/usr/bin/env python3
"""
Hive Mind Stress Testing Suite - Breaking Point Discovery
Specialized stress testing to find system limits and failure modes
This script pushes the Hive Mind system beyond normal operational limits
to discover breaking points, failure recovery patterns, and system resilience.
"""
import os
import sys
import json
import time
import psutil
import threading
import subprocess
import multiprocessing
from datetime import datetime
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import Dict, List, Any, Optional, Tuple
from concurrent.futures import ThreadPoolExecutor, as_completed
import statistics
import random
@dataclass
class StressTestConfig:
"""Configuration for stress testing scenarios"""
name: str
description: str
stress_type: str # memory, cpu, coordination, consensus, network, io
initial_agents: int
max_agents: int
increment_size: int
increment_interval: float # seconds between increments
failure_threshold: float = 0.5 # failure rate that indicates breaking point
resource_limit_mb: int = 8000 # memory limit before stopping
cpu_limit_percent: float = 95.0 # CPU limit before stopping
timeout_seconds: int = 300
chaos_mode: bool = False # inject random failures
@dataclass
class StressTestResult:
"""Results from stress testing"""
config: StressTestConfig
start_time: str
end_time: str
breaking_point_agents: int
max_stable_agents: int
failure_mode: str
total_duration: float
peak_memory_mb: float
peak_cpu_percent: float
coordination_failures: int
consensus_timeouts: int
network_errors: int
database_locks: int
recovery_attempts: int
successful_recoveries: int
degradation_curve: List[Dict[str, Any]]
error_patterns: Dict[str, int]
system_metrics: Dict[str, Any]
recommendations: List[str]
class HiveMindStressTester:
"""Specialized stress testing for Hive Mind system limits"""
def __init__(self, output_dir: str = "stress-test-results"):
self.output_dir = Path(output_dir)
self.output_dir.mkdir(exist_ok=True)
self.results: List[StressTestResult] = []
self.cli_path = self._find_cli_path()
self.active_processes: List[subprocess.Popen] = []
self.system_monitor = StressSystemMonitor()
def _find_cli_path(self) -> Path:
"""Find the claude-flow CLI executable"""
possible_paths = [
Path("../src/cli/simple-cli.js"),
Path("./src/cli/simple-cli.js"),
Path("./claude-flow"),
Path("../claude-flow")
]
for path in possible_paths:
if path.exists():
return path
return Path("claude-flow")
def create_stress_test_scenarios(self) -> List[StressTestConfig]:
"""Create comprehensive stress testing scenarios"""
scenarios = []
# Memory stress tests
scenarios.extend([
StressTestConfig(
name="memory_stress_progressive",
description="Progressive memory stress until exhaustion",
stress_type="memory",
initial_agents=50,
max_agents=2000,
increment_size=50,
increment_interval=10.0,
resource_limit_mb=6000
),
StressTestConfig(
name="memory_stress_rapid",
description="Rapid memory allocation stress",
stress_type="memory",
initial_agents=100,
max_agents=1000,
increment_size=100,
increment_interval=2.0,
resource_limit_mb=6000
)
])
# CPU stress tests
scenarios.extend([
StressTestConfig(
name="cpu_stress_coordination",
description="CPU stress through intensive coordination",
stress_type="cpu",
initial_agents=25,
max_agents=500,
increment_size=25,
increment_interval=5.0,
cpu_limit_percent=90.0
),
StressTestConfig(
name="cpu_stress_consensus",
description="CPU stress through consensus algorithms",
stress_type="cpu",
initial_agents=20,
max_agents=200,
increment_size=20,
increment_interval=8.0,
cpu_limit_percent=90.0
)
])
# Coordination stress tests
scenarios.extend([
StressTestConfig(
name="coordination_stress_mesh",
description="Coordination stress in mesh topology",
stress_type="coordination",
initial_agents=10,
max_agents=300,
increment_size=10,
increment_interval=5.0,
failure_threshold=0.3
),
StressTestConfig(
name="coordination_stress_hierarchical",
description="Coordination stress in hierarchical topology",
stress_type="coordination",
initial_agents=20,
max_agents=500,
increment_size=20,
increment_interval=5.0,
failure_threshold=0.3
)
])
# Consensus stress tests
scenarios.extend([
StressTestConfig(
name="consensus_stress_democracy",
description="Consensus stress in democratic coordination",
stress_type="consensus",
initial_agents=5,
max_agents=100,
increment_size=5,
increment_interval=10.0,
failure_threshold=0.4
),
StressTestConfig(
name="consensus_stress_hybrid",
description="Consensus stress in hybrid coordination",
stress_type="consensus",
initial_agents=10,
max_agents=150,
increment_size=10,
increment_interval=8.0,
failure_threshold=0.4
)
])
# Network stress tests
scenarios.extend([
StressTestConfig(
name="network_stress_distributed",
description="Network stress with distributed memory",
stress_type="network",
initial_agents=30,
max_agents=400,
increment_size=30,
increment_interval=6.0,
failure_threshold=0.4
)
])
# I/O stress tests
scenarios.extend([
StressTestConfig(
name="io_stress_sqlite",
description="I/O stress with SQLite backend",
stress_type="io",
initial_agents=40,
max_agents=600,
increment_size=40,
increment_interval=7.0,
failure_threshold=0.4
)
])
# Chaos engineering tests
scenarios.extend([
StressTestConfig(
name="chaos_random_failures",
description="Chaos engineering with random failures",
stress_type="chaos",
initial_agents=25,
max_agents=200,
increment_size=25,
increment_interval=10.0,
failure_threshold=0.6,
chaos_mode=True
)
])
return scenarios
def run_hive_mind_command_async(self, command: List[str], timeout: int = 120) -> subprocess.Popen:
"""Execute hive-mind command asynchronously"""
try:
process = subprocess.Popen(
["node", str(self.cli_path)] + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=Path.cwd()
)
self.active_processes.append(process)
return process
except Exception as e:
print(f"Failed to start command: {e}")
return None
def inject_chaos(self, chaos_type: str = "random"):
"""Inject chaos into the system for resilience testing"""
chaos_actions = [
self._kill_random_process,
self._corrupt_memory_operation,
self._simulate_network_delay,
self._force_database_lock,
self._simulate_consensus_failure
]
if chaos_type == "random":
action = random.choice(chaos_actions)
try:
action()
except Exception as e:
print(f"Chaos injection failed: {e}")
def _kill_random_process(self):
"""Kill a random active process"""
if self.active_processes:
process = random.choice(self.active_processes)
if process.poll() is None: # Still running
process.terminate()
print("🔥 Chaos: Killed random process")
def _corrupt_memory_operation(self):
"""Simulate memory corruption"""
print("🔥 Chaos: Simulating memory corruption")
# In a real implementation, this would interfere with memory operations
def _simulate_network_delay(self):
"""Simulate network delays"""
print("🔥 Chaos: Simulating network delay")
time.sleep(random.uniform(1, 3))
def _force_database_lock(self):
"""Force database contention"""
print("🔥 Chaos: Forcing database contention")
# In a real implementation, this would create database locks
def _simulate_consensus_failure(self):
"""Simulate consensus algorithm failure"""
print("🔥 Chaos: Simulating consensus failure")
# In a real implementation, this would interfere with consensus
def monitor_system_degradation(self, config: StressTestConfig) -> Tuple[bool, Dict[str, Any]]:
"""Monitor system for degradation indicators"""
metrics = self.system_monitor.get_current_metrics()
# Check resource limits
memory_exceeded = metrics.get("memory_mb", 0) > config.resource_limit_mb
cpu_exceeded = metrics.get("cpu_percent", 0) > config.cpu_limit_percent
# Check system responsiveness
load_average = os.getloadavg()[0] if hasattr(os, 'getloadavg') else 0
high_load = load_average > multiprocessing.cpu_count() * 2
# Check process health
dead_processes = len([p for p in self.active_processes if p.poll() is not None])
process_failure_rate = dead_processes / max(len(self.active_processes), 1)
degraded = memory_exceeded or cpu_exceeded or high_load or process_failure_rate > config.failure_threshold
return degraded, {
"memory_exceeded": memory_exceeded,
"cpu_exceeded": cpu_exceeded,
"high_load": high_load,
"process_failure_rate": process_failure_rate,
"metrics": metrics
}
def attempt_system_recovery(self) -> bool:
"""Attempt to recover system from degraded state"""
print("🔧 Attempting system recovery...")
recovery_successful = False
try:
# Clean up dead processes
dead_processes = [p for p in self.active_processes if p.poll() is not None]
for process in dead_processes:
self.active_processes.remove(process)
# Force garbage collection
import gc
gc.collect()
# Brief pause for system stabilization
time.sleep(5)
# Check if system is responsive
test_metrics = self.system_monitor.get_current_metrics()
if test_metrics.get("cpu_percent", 100) < 80:
recovery_successful = True
print("✅ System recovery successful")
else:
print("❌ System recovery failed")
except Exception as e:
print(f"❌ Recovery attempt failed: {e}")
return recovery_successful
def run_stress_test(self, config: StressTestConfig) -> StressTestResult:
"""Run a single stress test scenario"""
print(f"🔥 Starting stress test: {config.name}")
print(f" 📊 Type: {config.stress_type}")
print(f" 🎯 Range: {config.initial_agents} -> {config.max_agents} agents")
print(f" ⚡ Increment: {config.increment_size} every {config.increment_interval}s")
start_time = datetime.now().isoformat()
test_start = time.time()
# Start system monitoring
monitor_thread = self.system_monitor.start_monitoring()
# Initialize tracking variables
current_agents = config.initial_agents
breaking_point_agents = None
max_stable_agents = 0
failure_mode = "none"
degradation_curve = []
error_patterns = {}
recovery_attempts = 0
successful_recoveries = 0
try:
# Initialize Hive Mind system
init_cmd = ["hive-mind", "init", "--stress-test", "--test-mode"]
init_process = self.run_hive_mind_command_async(init_cmd)
if init_process:
init_process.wait(timeout=60)
if init_process.returncode != 0:
raise Exception("Failed to initialize Hive Mind system")
print(f"🚀 Starting with {current_agents} agents...")
# Progressive stress testing loop
while current_agents <= config.max_agents:
iteration_start = time.time()
# Spawn agent increment
spawn_cmd = [
"hive-mind", "spawn",
f"Stress test increment to {current_agents} agents",
"--agents", str(config.increment_size),
"--topology", self._get_optimal_topology(current_agents),
"--coordination", self._get_optimal_coordination(current_agents, config.stress_type),
"--memory", self._get_optimal_memory(current_agents),
"--stress-mode"
]
spawn_processes = []
for _ in range(config.increment_size // 10 + 1): # Batch spawning
process = self.run_hive_mind_command_async(spawn_cmd)
if process:
spawn_processes.append(process)
# Wait for spawning to complete or timeout
spawn_success = True
for process in spawn_processes:
try:
process.wait(timeout=30)
if process.returncode != 0:
spawn_success = False
except subprocess.TimeoutExpired:
process.terminate()
spawn_success = False
# Inject chaos if enabled
if config.chaos_mode:
self.inject_chaos()
# Monitor system state
degraded, degradation_info = self.monitor_system_degradation(config)
# Record metrics for this iteration
iteration_metrics = {
"agent_count": current_agents,
"timestamp": time.time() - test_start,
"spawn_success": spawn_success,
"system_degraded": degraded,
"metrics": degradation_info["metrics"],
"iteration_duration": time.time() - iteration_start
}
degradation_curve.append(iteration_metrics)
# Update tracking
if spawn_success and not degraded:
max_stable_agents = current_agents
print(f"✅ Stable at {current_agents} agents")
else:
if not breaking_point_agents:
breaking_point_agents = current_agents
# Determine failure mode
if degradation_info["memory_exceeded"]:
failure_mode = "memory_exhaustion"
elif degradation_info["cpu_exceeded"]:
failure_mode = "cpu_exhaustion"
elif degradation_info["high_load"]:
failure_mode = "system_overload"
elif degradation_info["process_failure_rate"] > config.failure_threshold:
failure_mode = "process_failures"
else:
failure_mode = "coordination_breakdown"
print(f"🚨 Breaking point reached at {current_agents} agents!")
print(f" Failure mode: {failure_mode}")
# Attempt recovery
if degraded:
recovery_attempts += 1
if self.attempt_system_recovery():
successful_recoveries += 1
else:
print("💥 System recovery failed, continuing test...")
# Check if we should continue
current_failure_rate = len([m for m in degradation_curve[-5:] if not m["spawn_success"]]) / min(5, len(degradation_curve))
if current_failure_rate > config.failure_threshold and breaking_point_agents:
print(f"🛑 Stopping test due to high failure rate: {current_failure_rate:.1%}")
break
# Resource safety checks
current_metrics = self.system_monitor.get_current_metrics()
if current_metrics.get("memory_mb", 0) > config.resource_limit_mb:
print(f"🛑 Stopping test due to memory limit: {current_metrics['memory_mb']:.1f}MB")
failure_mode = "memory_limit_reached"
break
if current_metrics.get("cpu_percent", 0) > config.cpu_limit_percent:
print(f"🛑 Stopping test due to CPU limit: {current_metrics['cpu_percent']:.1f}%")
failure_mode = "cpu_limit_reached"
break
# Increment for next iteration
current_agents += config.increment_size
# Wait before next increment
time.sleep(config.increment_interval)
# Cleanup all processes
for process in self.active_processes:
try:
if process.poll() is None:
process.terminate()
process.wait(timeout=10)
except Exception:
pass
self.active_processes.clear()
except Exception as e:
failure_mode = f"test_exception: {str(e)}"
print(f"❌ Stress test failed: {e}")
finally:
# Stop monitoring
system_metrics = self.system_monitor.stop_monitoring(monitor_thread)
total_duration = time.time() - test_start
end_time = datetime.now().isoformat()
# Generate recommendations based on results
recommendations = self._generate_stress_recommendations(
config, breaking_point_agents, max_stable_agents, failure_mode, degradation_curve
)
return StressTestResult(
config=config,
start_time=start_time,
end_time=end_time,
breaking_point_agents=breaking_point_agents or config.max_agents,
max_stable_agents=max_stable_agents,
failure_mode=failure_mode,
total_duration=total_duration,
peak_memory_mb=system_metrics.get("peak_memory_mb", 0),
peak_cpu_percent=system_metrics.get("peak_cpu_percent", 0),
coordination_failures=len([m for m in degradation_curve if not m.get("spawn_success", True)]),
consensus_timeouts=0, # Would need specific monitoring
network_errors=0, # Would need specific monitoring
database_locks=0, # Would need specific monitoring
recovery_attempts=recovery_attempts,
successful_recoveries=successful_recoveries,
degradation_curve=degradation_curve,
error_patterns=error_patterns,
system_metrics=system_metrics,
recommendations=recommendations
)
def _get_optimal_topology(self, agent_count: int) -> str:
"""Get optimal topology for agent count"""
if agent_count <= 50:
return "hierarchical"
elif agent_count <= 200:
return "mesh"
else:
return "distributed"
def _get_optimal_coordination(self, agent_count: int, stress_type: str) -> str:
"""Get optimal coordination mode for stress test"""
if stress_type == "consensus":
return "consensus"
elif agent_count <= 30:
return "queen"
elif agent_count <= 150:
return "hybrid"
else:
return "consensus"
def _get_optimal_memory(self, agent_count: int) -> str:
"""Get optimal memory backend for agent count"""
if agent_count <= 100:
return "sqlite"
else:
return "distributed"
def _generate_stress_recommendations(self, config: StressTestConfig, breaking_point: Optional[int],
max_stable: int, failure_mode: str, curve: List[Dict]) -> List[str]:
"""Generate recommendations based on stress test results"""
recommendations = []
if breaking_point and breaking_point < 100:
recommendations.append(f"System shows early breaking point at {breaking_point} agents. Consider optimizing {config.stress_type} handling.")
if failure_mode == "memory_exhaustion":
recommendations.append("Memory exhaustion detected. Implement memory pooling and garbage collection optimizations.")
elif failure_mode == "cpu_exhaustion":
recommendations.append("CPU exhaustion detected. Consider async processing and workload distribution.")
elif failure_mode == "coordination_breakdown":
recommendations.append("Coordination breakdown detected. Implement hierarchical coordination for better scaling.")
elif failure_mode == "process_failures":
recommendations.append("Process stability issues. Implement better error handling and process supervision.")
if max_stable > 500:
recommendations.append("Excellent scaling characteristics observed. System suitable for large deployments.")
elif max_stable > 100:
recommendations.append("Good scaling up to medium deployments. Consider sharding for larger scales.")
else:
recommendations.append("Limited scaling capacity. Requires significant optimization for production use.")
return recommendations
def run_comprehensive_stress_testing(self) -> Dict[str, Any]:
"""Run complete stress testing suite"""
print("💥 Hive Mind Comprehensive Stress Testing Suite")
print("=" * 60)
print("🎯 Finding breaking points and failure modes")
print("🔥 Testing system resilience and recovery")
print("📊 Analyzing degradation patterns")
print("=" * 60)
# Create stress test scenarios
scenarios = self.create_stress_test_scenarios()
print(f"📋 Created {len(scenarios)} stress test scenarios")
# Run stress tests
results = []
start_time = time.time()
for i, scenario in enumerate(scenarios):
print(f"\\n🔥 Running stress test {i+1}/{len(scenarios)}: {scenario.name}")
result = self.run_stress_test(scenario)
results.append(result)
# Report result
print(f"📊 Breaking point: {result.breaking_point_agents} agents")
print(f"📈 Max stable: {result.max_stable_agents} agents")
print(f"💥 Failure mode: {result.failure_mode}")
print(f"🔧 Recovery rate: {result.successful_recoveries}/{result.recovery_attempts}")
# Brief pause between tests for system cleanup
time.sleep(10)
total_duration = time.time() - start_time
print(f"\\n⏱️ Total stress testing time: {total_duration:.1f} seconds")
# Analyze results
analysis = self._analyze_stress_results(results)
# Save results
file_info = self._save_stress_results(results, analysis)
# Add metadata
analysis["metadata"] = {
"total_duration_seconds": total_duration,
"test_time": datetime.now().isoformat(),
"scenario_count": len(scenarios),
"system_info": {
"cpu_count": multiprocessing.cpu_count(),
"memory_gb": psutil.virtual_memory().total / (1024**3),
"platform": sys.platform
}
}
analysis["files"] = file_info
return analysis
def _analyze_stress_results(self, results: List[StressTestResult]) -> Dict[str, Any]:
"""Analyze stress test results"""
if not results:
return {"error": "No results to analyze"}
# Breaking point analysis
breaking_points = [r.breaking_point_agents for r in results if r.breaking_point_agents]
min_breaking_point = min(breaking_points) if breaking_points else None
avg_breaking_point = statistics.mean(breaking_points) if breaking_points else None
# Stability analysis
stable_points = [r.max_stable_agents for r in results]
max_stability = max(stable_points) if stable_points else 0
avg_stability = statistics.mean(stable_points) if stable_points else 0
# Failure mode analysis
failure_modes = {}
for result in results:
mode = result.failure_mode
failure_modes[mode] = failure_modes.get(mode, 0) + 1
# Recovery analysis
total_recovery_attempts = sum(r.recovery_attempts for r in results)
total_successful_recoveries = sum(r.successful_recoveries for r in results)
recovery_rate = total_successful_recoveries / total_recovery_attempts if total_recovery_attempts > 0 else 0
# Resource utilization analysis
peak_memory = max(r.peak_memory_mb for r in results)
peak_cpu = max(r.peak_cpu_percent for r in results)
return {
"summary": {
"total_tests": len(results),
"min_breaking_point": min_breaking_point,
"avg_breaking_point": avg_breaking_point,
"max_stable_agents": max_stability,
"avg_stable_agents": avg_stability,
"peak_memory_mb": peak_memory,
"peak_cpu_percent": peak_cpu,
"recovery_rate": recovery_rate
},
"failure_modes": failure_modes,
"breaking_points_by_stress_type": {
r.config.stress_type: r.breaking_point_agents
for r in results if r.breaking_point_agents
},
"stability_by_stress_type": {
r.config.stress_type: r.max_stable_agents
for r in results
},
"recommendations": self._generate_overall_recommendations(results)
}
def _generate_overall_recommendations(self, results: List[StressTestResult]) -> List[str]:
"""Generate overall recommendations from all stress tests"""
recommendations = []
# Collect all individual recommendations
all_recommendations = []
for result in results:
all_recommendations.extend(result.recommendations)
# Find common themes
if "memory" in " ".join(all_recommendations).lower():
recommendations.append("Memory optimization is critical across multiple stress scenarios.")
if "coordination" in " ".join(all_recommendations).lower():
recommendations.append("Coordination mechanisms need optimization for high-scale deployments.")
if "cpu" in " ".join(all_recommendations).lower():
recommendations.append("CPU utilization optimization required for sustained high loads.")
# Analyze breaking points
breaking_points = [r.breaking_point_agents for r in results if r.breaking_point_agents]
if breaking_points:
min_bp = min(breaking_points)
if min_bp < 100:
recommendations.append("Early breaking points indicate fundamental scaling issues that need addressing.")
elif min_bp < 500:
recommendations.append("Medium-scale breaking points suggest optimization opportunities for enterprise use.")
else:
recommendations.append("Strong scaling characteristics observed across stress scenarios.")
return recommendations
def _save_stress_results(self, results: List[StressTestResult], analysis: Dict[str, Any]) -> Dict[str, str]:
"""Save stress test results and analysis"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Save detailed results
results_file = self.output_dir / f"hive_mind_stress_test_results_{timestamp}.json"
with open(results_file, 'w') as f:
json.dump([asdict(r) for r in results], f, indent=2)
# Save analysis
analysis_file = self.output_dir / f"hive_mind_stress_test_analysis_{timestamp}.json"
with open(analysis_file, 'w') as f:
json.dump(analysis, f, indent=2)
# Save summary CSV
csv_file = self.output_dir / f"hive_mind_stress_test_summary_{timestamp}.csv"
with open(csv_file, 'w') as f:
f.write("test_name,stress_type,max_stable_agents,breaking_point_agents,failure_mode,")
f.write("peak_memory_mb,peak_cpu_percent,recovery_attempts,successful_recoveries,recovery_rate\\n")
for result in results:
config = result.config
recovery_rate = result.successful_recoveries / result.recovery_attempts if result.recovery_attempts > 0 else 0
f.write(f"{config.name},{config.stress_type},{result.max_stable_agents},")
f.write(f"{result.breaking_point_agents},{result.failure_mode},")
f.write(f"{result.peak_memory_mb:.1f},{result.peak_cpu_percent:.1f},")
f.write(f"{result.recovery_attempts},{result.successful_recoveries},{recovery_rate:.2f}\\n")
print(f"📊 Stress test results saved:")
print(f" 📄 Detailed results: {results_file}")
print(f" 📈 Analysis: {analysis_file}")
print(f" 📋 Summary CSV: {csv_file}")
return {
"results_file": str(results_file),
"analysis_file": str(analysis_file),
"csv_file": str(csv_file)
}
class StressSystemMonitor:
"""Enhanced system monitoring for stress testing"""
def __init__(self):
self.monitoring = False
self.metrics = {
"cpu_samples": [],
"memory_samples": [],
"load_samples": [],
"process_counts": []
}
def start_monitoring(self) -> threading.Thread:
"""Start enhanced monitoring"""
self.monitoring = True
self.metrics = {
"cpu_samples": [],
"memory_samples": [],
"load_samples": [],
"process_counts": []
}
def monitor():
while self.monitoring:
try:
# Enhanced metrics collection
cpu_percent = psutil.cpu_percent(interval=0.1)
memory = psutil.virtual_memory()
process_count = len(psutil.pids())
self.metrics["cpu_samples"].append(cpu_percent)
self.metrics["memory_samples"].append(memory.percent)
self.metrics["process_counts"].append(process_count)
# Load average (Unix only)
if hasattr(os, 'getloadavg'):
load_avg = os.getloadavg()[0]
self.metrics["load_samples"].append(load_avg)
except Exception:
pass
time.sleep(0.5) # Higher frequency monitoring for stress tests
thread = threading.Thread(target=monitor)
thread.daemon = True
thread.start()
return thread
def get_current_metrics(self) -> Dict[str, Any]:
"""Get current system metrics"""
try:
memory = psutil.virtual_memory()
return {
"cpu_percent": psutil.cpu_percent(),
"memory_percent": memory.percent,
"memory_mb": memory.used / (1024**2),
"available_memory_mb": memory.available / (1024**2),
"process_count": len(psutil.pids()),
"load_average": os.getloadavg()[0] if hasattr(os, 'getloadavg') else 0
}
except Exception:
return {}
def stop_monitoring(self, thread: Optional[threading.Thread]) -> Dict[str, Any]:
"""Stop monitoring and return comprehensive metrics"""
self.monitoring = False
if thread:
thread.join(timeout=2)
if not self.metrics["cpu_samples"]:
return {}
memory_gb = psutil.virtual_memory().total / (1024**3)
return {
"peak_cpu_percent": max(self.metrics["cpu_samples"]),
"avg_cpu_percent": statistics.mean(self.metrics["cpu_samples"]),
"peak_memory_percent": max(self.metrics["memory_samples"]),
"avg_memory_percent": statistics.mean(self.metrics["memory_samples"]),
"peak_memory_mb": max(self.metrics["memory_samples"]) * memory_gb * 1024 / 100,
"peak_process_count": max(self.metrics["process_counts"]) if self.metrics["process_counts"] else 0,
"peak_load_average": max(self.metrics["load_samples"]) if self.metrics["load_samples"] else 0,
"sample_count": len(self.metrics["cpu_samples"])
}
def main():
"""Main stress testing execution"""
import argparse
parser = argparse.ArgumentParser(description="Hive Mind Stress Testing Suite")
parser.add_argument("--quick", action="store_true", help="Run quick stress test")
parser.add_argument("--stress-type", choices=["memory", "cpu", "coordination", "consensus", "network", "io", "chaos"],
help="Run specific stress test type")
parser.add_argument("--max-agents", type=int, default=1000, help="Maximum agents to test")
parser.add_argument("--output", default="stress-test-results", help="Output directory")
args = parser.parse_args()
tester = HiveMindStressTester(output_dir=args.output)
if args.quick:
# Quick stress test
scenario = StressTestConfig(
name="quick_stress",
description="Quick stress test",
stress_type="memory",
initial_agents=10,
max_agents=100,
increment_size=10,
increment_interval=5.0
)
result = tester.run_stress_test(scenario)
analysis = tester._analyze_stress_results([result])
tester._save_stress_results([result], analysis)
elif args.stress_type:
# Specific stress type
scenarios = [s for s in tester.create_stress_test_scenarios() if s.stress_type == args.stress_type]
results = []
for scenario in scenarios:
result = tester.run_stress_test(scenario)
results.append(result)
analysis = tester._analyze_stress_results(results)
tester._save_stress_results(results, analysis)
else:
# Full comprehensive stress testing
analysis = tester.run_comprehensive_stress_testing()
# Print summary
summary = analysis["summary"]
print("\\n💥 STRESS TESTING SUMMARY")
print("=" * 50)
print(f"Total tests: {summary['total_tests']}")
print(f"Min breaking point: {summary['min_breaking_point']} agents" if summary['min_breaking_point'] else "No breaking point found")
print(f"Avg breaking point: {summary['avg_breaking_point']:.0f} agents" if summary['avg_breaking_point'] else "N/A")
print(f"Max stable agents: {summary['max_stable_agents']}")
print(f"Peak memory usage: {summary['peak_memory_mb']:.1f}MB")
print(f"Peak CPU usage: {summary['peak_cpu_percent']:.1f}%")
print(f"Recovery success rate: {summary['recovery_rate']:.1%}")
# Print failure modes
if analysis["failure_modes"]:
print("\\n💥 FAILURE MODES")
for mode, count in analysis["failure_modes"].items():
print(f" {mode}: {count} occurrences")
# Print recommendations
if analysis["recommendations"]:
print("\\n💡 RECOMMENDATIONS")
for i, rec in enumerate(analysis["recommendations"], 1):
print(f"{i}. {rec}")
if __name__ == "__main__":
main()
+479
View File
@@ -0,0 +1,479 @@
#!/usr/bin/env python3
"""
Hive Mind Load Test Orchestrator
Comprehensive testing orchestration for the Benchmark-Tester agent
This script runs the complete load testing suite including:
1. Progressive scaling tests (1 -> 1000+ agents)
2. Stress testing for breaking point discovery
3. Concurrent swarm testing
4. Resource exhaustion testing
5. Failure recovery testing
"""
import os
import sys
import json
import time
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Any
class LoadTestOrchestrator:
"""Orchestrates comprehensive load testing suite"""
def __init__(self):
self.benchmark_dir = Path(__file__).parent
self.results_dir = self.benchmark_dir / "test-results" / datetime.now().strftime("%Y%m%d_%H%M%S")
self.results_dir.mkdir(parents=True, exist_ok=True)
self.test_results = {}
def log(self, message: str, level: str = "INFO"):
"""Log messages with timestamp"""
timestamp = datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] {level}: {message}")
def run_command(self, command: List[str], cwd: Path = None) -> Dict[str, Any]:
"""Run a command and return results"""
self.log(f"Running: {' '.join(command)}")
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
cwd=cwd or self.benchmark_dir,
timeout=7200 # 2 hour timeout
)
return {
"success": result.returncode == 0,
"returncode": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr
}
except subprocess.TimeoutExpired:
return {
"success": False,
"returncode": -1,
"stdout": "",
"stderr": "Command timed out after 2 hours"
}
except Exception as e:
return {
"success": False,
"returncode": -1,
"stdout": "",
"stderr": str(e)
}
def run_load_testing(self) -> Dict[str, Any]:
"""Run comprehensive load testing"""
self.log("🔥 Starting Load Testing Phase", "INFO")
# Run quick load test first
self.log("Running quick load test for system validation...")
quick_result = self.run_command([
"python3", "hive-mind-load-test.py",
"--quick",
"--output", str(self.results_dir / "load-test-quick")
])
if not quick_result["success"]:
self.log("❌ Quick load test failed, aborting full test", "ERROR")
return {"success": False, "error": "Quick test failed", "details": quick_result}
self.log("✅ Quick load test passed, proceeding with full load testing")
# Run full load testing
self.log("Running comprehensive load testing...")
full_result = self.run_command([
"python3", "hive-mind-load-test.py",
"--output", str(self.results_dir / "load-test-full")
])
return {
"success": full_result["success"],
"quick_test": quick_result,
"full_test": full_result
}
def run_stress_testing(self) -> Dict[str, Any]:
"""Run stress testing for breaking point discovery"""
self.log("💥 Starting Stress Testing Phase", "INFO")
stress_types = ["memory", "cpu", "coordination", "consensus"]
stress_results = {}
for stress_type in stress_types:
self.log(f"Running {stress_type} stress test...")
result = self.run_command([
"python3", "hive-mind-stress-test.py",
"--stress-type", stress_type,
"--output", str(self.results_dir / f"stress-test-{stress_type}")
])
stress_results[stress_type] = result
if result["success"]:
self.log(f"✅ {stress_type} stress test completed")
else:
self.log(f"❌ {stress_type} stress test failed: {result['stderr'][:200]}", "ERROR")
# Run comprehensive stress testing
self.log("Running comprehensive stress testing...")
comprehensive_result = self.run_command([
"python3", "hive-mind-stress-test.py",
"--output", str(self.results_dir / "stress-test-comprehensive")
])
stress_results["comprehensive"] = comprehensive_result
return stress_results
def run_benchmark_suite(self) -> Dict[str, Any]:
"""Run existing benchmark suite"""
self.log("📊 Starting Benchmark Suite Phase", "INFO")
# Check if benchmark runner exists
benchmark_runner = self.benchmark_dir / "hive-mind-benchmarks" / "benchmark_runner.py"
if not benchmark_runner.exists():
self.log("⚠️ Benchmark runner not found, skipping benchmark suite", "WARN")
return {"success": False, "error": "Benchmark runner not found"}
# Run quick benchmark
self.log("Running quick benchmark...")
quick_result = self.run_command([
"python3", str(benchmark_runner),
"--quick"
], cwd=benchmark_runner.parent)
if quick_result["success"]:
self.log("✅ Quick benchmark completed")
else:
self.log(f"❌ Quick benchmark failed: {quick_result['stderr'][:200]}", "ERROR")
return {"quick_benchmark": quick_result}
def run_concurrent_swarm_tests(self) -> Dict[str, Any]:
"""Run concurrent swarm testing"""
self.log("🐝 Starting Concurrent Swarm Testing", "INFO")
concurrent_tests = [
(2, 25, "Two swarms test"),
(5, 20, "Five swarms test"),
(10, 10, "Ten swarms test")
]
results = {}
for swarm_count, agents_per_swarm, description in concurrent_tests:
self.log(f"Running {description}: {swarm_count} swarms x {agents_per_swarm} agents")
# Use load test with specific parameters
result = self.run_command([
"python3", "hive-mind-load-test.py",
"--scale", str(agents_per_swarm),
"--output", str(self.results_dir / f"concurrent-{swarm_count}x{agents_per_swarm}")
])
results[f"{swarm_count}x{agents_per_swarm}"] = result
if result["success"]:
self.log(f"✅ {description} completed")
else:
self.log(f"❌ {description} failed", "ERROR")
return results
def analyze_combined_results(self) -> Dict[str, Any]:
"""Analyze all test results and generate combined report"""
self.log("📈 Analyzing Combined Results", "INFO")
# Collect all result files
result_files = list(self.results_dir.glob("**/*.json"))
combined_analysis = {
"test_summary": {
"total_test_files": len(result_files),
"test_phases": list(self.test_results.keys()),
"overall_success": all(
result.get("success", False)
for result in self.test_results.values()
if isinstance(result, dict)
),
"test_duration": time.time() - self.start_time
},
"breaking_points": {},
"stability_limits": {},
"performance_metrics": {},
"recommendations": []
}
# Analyze each result file
for result_file in result_files:
try:
with open(result_file, 'r') as f:
data = json.load(f)
# Extract key metrics
if "summary" in data:
summary = data["summary"]
# Breaking points
if "breaking_point_agents" in summary:
test_name = result_file.stem
combined_analysis["breaking_points"][test_name] = summary["breaking_point_agents"]
# Stability limits
if "max_stable_agents" in summary:
test_name = result_file.stem
combined_analysis["stability_limits"][test_name] = summary["max_stable_agents"]
# Performance metrics
if "avg_throughput" in summary:
test_name = result_file.stem
combined_analysis["performance_metrics"][test_name] = {
"throughput": summary.get("avg_throughput", 0),
"response_time": summary.get("avg_response_time_ms", 0),
"memory_usage": summary.get("peak_memory_usage_mb", 0)
}
# Extract recommendations
if "recommendations" in data:
combined_analysis["recommendations"].extend(data["recommendations"])
except Exception as e:
self.log(f"⚠️ Failed to analyze {result_file}: {e}", "WARN")
# Generate overall recommendations
overall_recommendations = self._generate_overall_recommendations(combined_analysis)
combined_analysis["overall_recommendations"] = overall_recommendations
# Save combined analysis
analysis_file = self.results_dir / "combined_analysis.json"
with open(analysis_file, 'w') as f:
json.dump(combined_analysis, f, indent=2)
self.log(f"📊 Combined analysis saved to: {analysis_file}")
return combined_analysis
def _generate_overall_recommendations(self, analysis: Dict[str, Any]) -> List[str]:
"""Generate overall recommendations from combined analysis"""
recommendations = []
# Analyze breaking points
breaking_points = list(analysis["breaking_points"].values())
if breaking_points:
min_breaking_point = min(breaking_points)
avg_breaking_point = sum(breaking_points) / len(breaking_points)
if min_breaking_point < 100:
recommendations.append(
f"CRITICAL: Minimum breaking point at {min_breaking_point} agents indicates fundamental scaling issues."
)
elif avg_breaking_point < 500:
recommendations.append(
f"OPTIMIZATION NEEDED: Average breaking point at {avg_breaking_point:.0f} agents suggests medium-scale optimization opportunities."
)
else:
recommendations.append(
f"EXCELLENT: Strong scaling characteristics with average breaking point at {avg_breaking_point:.0f} agents."
)
# Analyze stability limits
stability_limits = list(analysis["stability_limits"].values())
if stability_limits:
max_stability = max(stability_limits)
if max_stability >= 1000:
recommendations.append("System demonstrates enterprise-scale stability (1000+ agents).")
elif max_stability >= 500:
recommendations.append("System suitable for large-scale deployments (500+ agents).")
elif max_stability >= 100:
recommendations.append("System suitable for medium-scale deployments (100+ agents).")
else:
recommendations.append("System requires optimization for production deployment.")
# Analyze test success rates
if not analysis["test_summary"]["overall_success"]:
recommendations.append("URGENT: Some test phases failed. Review error logs and address critical issues.")
return recommendations
def generate_summary_report(self, analysis: Dict[str, Any]):
"""Generate human-readable summary report"""
self.log("📋 Generating Summary Report", "INFO")
report_file = self.results_dir / "LOAD_TEST_SUMMARY.md"
with open(report_file, 'w') as f:
f.write("# Hive Mind Load Testing Summary Report\\n")
f.write(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n")
# Test Summary
f.write("## Test Summary\\n")
summary = analysis["test_summary"]
f.write(f"- **Total Test Duration**: {summary['test_duration']:.1f} seconds\\n")
f.write(f"- **Test Phases**: {len(summary['test_phases'])}\\n")
f.write(f"- **Overall Success**: {'✅ PASS' if summary['overall_success'] else '❌ FAIL'}\\n")
f.write(f"- **Result Files**: {summary['total_test_files']}\\n\\n")
# Breaking Points
if analysis["breaking_points"]:
f.write("## Breaking Points\\n")
for test_name, breaking_point in analysis["breaking_points"].items():
f.write(f"- **{test_name}**: {breaking_point} agents\\n")
f.write("\\n")
# Stability Limits
if analysis["stability_limits"]:
f.write("## Stability Limits\\n")
for test_name, stability_limit in analysis["stability_limits"].items():
f.write(f"- **{test_name}**: {stability_limit} agents\\n")
f.write("\\n")
# Performance Metrics
if analysis["performance_metrics"]:
f.write("## Performance Metrics\\n")
for test_name, metrics in analysis["performance_metrics"].items():
f.write(f"### {test_name}\\n")
f.write(f"- **Throughput**: {metrics['throughput']:.1f} ops/sec\\n")
f.write(f"- **Response Time**: {metrics['response_time']:.1f}ms\\n")
f.write(f"- **Memory Usage**: {metrics['memory_usage']:.1f}MB\\n\\n")
# Recommendations
if analysis["overall_recommendations"]:
f.write("## Recommendations\\n")
for i, rec in enumerate(analysis["overall_recommendations"], 1):
f.write(f"{i}. {rec}\\n")
f.write("\\n")
# Test Results Summary
f.write("## Test Results by Phase\\n")
for phase, result in self.test_results.items():
if isinstance(result, dict):
success = result.get("success", False)
f.write(f"- **{phase}**: {'✅ PASS' if success else '❌ FAIL'}\\n")
f.write("\\n")
# Files and Locations
f.write("## Generated Files\\n")
f.write(f"- **Results Directory**: `{self.results_dir}`\\n")
f.write(f"- **Combined Analysis**: `{self.results_dir}/combined_analysis.json`\\n")
f.write(f"- **This Report**: `{report_file}`\\n")
self.log(f"📋 Summary report saved to: {report_file}")
def run_comprehensive_testing(self) -> Dict[str, Any]:
"""Run the complete testing suite"""
self.log("🚀 Starting Comprehensive Hive Mind Load Testing", "INFO")
self.log("=" * 60)
self.start_time = time.time()
# Phase 1: Load Testing
self.log("Phase 1: Load Testing")
self.test_results["load_testing"] = self.run_load_testing()
# Phase 2: Stress Testing
self.log("Phase 2: Stress Testing")
self.test_results["stress_testing"] = self.run_stress_testing()
# Phase 3: Benchmark Suite
self.log("Phase 3: Benchmark Suite")
self.test_results["benchmark_suite"] = self.run_benchmark_suite()
# Phase 4: Concurrent Swarm Testing
self.log("Phase 4: Concurrent Swarm Testing")
self.test_results["concurrent_swarms"] = self.run_concurrent_swarm_tests()
# Phase 5: Analysis
self.log("Phase 5: Analysis and Reporting")
analysis = self.analyze_combined_results()
# Generate summary report
self.generate_summary_report(analysis)
total_duration = time.time() - self.start_time
self.log(f"🎯 Testing Complete! Total Duration: {total_duration:.1f} seconds")
self.log(f"📊 Results saved to: {self.results_dir}")
return {
"success": True,
"total_duration": total_duration,
"results_directory": str(self.results_dir),
"test_results": self.test_results,
"analysis": analysis
}
def main():
"""Main orchestrator execution"""
import argparse
parser = argparse.ArgumentParser(description="Hive Mind Load Testing Orchestrator")
parser.add_argument("--phase", choices=["load", "stress", "benchmark", "concurrent", "all"],
default="all", help="Run specific testing phase")
parser.add_argument("--quick", action="store_true", help="Run quick tests only")
args = parser.parse_args()
orchestrator = LoadTestOrchestrator()
try:
if args.phase == "all":
if args.quick:
# Quick testing mode
orchestrator.log("🚀 Running Quick Testing Mode")
result = orchestrator.run_command([
"python3", "hive-mind-load-test.py", "--quick"
])
print("Quick test result:", "SUCCESS" if result["success"] else "FAILED")
else:
# Full comprehensive testing
result = orchestrator.run_comprehensive_testing()
# Print summary
if result["success"]:
print("\\n🎯 COMPREHENSIVE TESTING SUMMARY")
print("=" * 50)
print(f"✅ Testing completed successfully!")
print(f"⏱️ Total duration: {result['total_duration']:.1f} seconds")
print(f"📁 Results directory: {result['results_directory']}")
print("\\n📊 Phase Results:")
for phase, phase_result in result["test_results"].items():
if isinstance(phase_result, dict):
success = phase_result.get("success", False)
print(f" {phase}: {'✅ PASS' if success else '❌ FAIL'}")
else:
print("❌ Testing failed!")
else:
# Run specific phase
orchestrator.log(f"Running specific phase: {args.phase}")
if args.phase == "load":
result = orchestrator.run_load_testing()
elif args.phase == "stress":
result = orchestrator.run_stress_testing()
elif args.phase == "benchmark":
result = orchestrator.run_benchmark_suite()
elif args.phase == "concurrent":
result = orchestrator.run_concurrent_swarm_tests()
print(f"{args.phase} phase result:", "SUCCESS" if result.get("success", False) else "FAILED")
except KeyboardInterrupt:
orchestrator.log("Testing interrupted by user", "WARN")
sys.exit(1)
except Exception as e:
orchestrator.log(f"Testing failed with error: {e}", "ERROR")
sys.exit(1)
if __name__ == "__main__":
main()