From 153aaff03fa7bee8d8256ab7ee2d9792de575072 Mon Sep 17 00:00:00 2001 From: rUv Date: Wed, 6 Aug 2025 01:48:47 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=96=20Checkpoint:=20Edit=20/workspaces?= =?UTF-8?q?/claude-code-flow/benchmark/test=5Fsimple=5Frun.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- benchmark/.claude/checkpoints/1754444912.json | 1 + benchmark/.claude/checkpoints/1754444914.json | 1 + benchmark/scripts/simple-load-test.py | 322 +++++++ benchmark/scripts/swarm_performance_suite.py | 840 ++++++++++++++++++ benchmark/test_simple_run.py | 5 + 5 files changed, 1169 insertions(+) create mode 100644 benchmark/.claude/checkpoints/1754444912.json create mode 100644 benchmark/.claude/checkpoints/1754444914.json create mode 100644 benchmark/scripts/simple-load-test.py create mode 100644 benchmark/scripts/swarm_performance_suite.py diff --git a/benchmark/.claude/checkpoints/1754444912.json b/benchmark/.claude/checkpoints/1754444912.json new file mode 100644 index 0000000000..aa198d390d --- /dev/null +++ b/benchmark/.claude/checkpoints/1754444912.json @@ -0,0 +1 @@ +{"branch": "checkpoint/pre-edit-20250806-014832", "file": "/workspaces/claude-code-flow/benchmark/mle_star_benchmark_example.py", "timestamp": "2025-08-06T01:48:32Z", "type": "pre-edit", "original_branch": "alpha-88"} diff --git a/benchmark/.claude/checkpoints/1754444914.json b/benchmark/.claude/checkpoints/1754444914.json new file mode 100644 index 0000000000..6667c2f4cc --- /dev/null +++ b/benchmark/.claude/checkpoints/1754444914.json @@ -0,0 +1 @@ +{"tag": "checkpoint-20250806-014834", "file": "/workspaces/claude-code-flow/benchmark/mle_star_benchmark_example.py", "timestamp": "2025-08-06T01:48:34Z", "type": "post-edit", "branch": "alpha-88", "diff_summary": " .claude-flow/metrics/system-metrics.json | 72 +++ benchmark/.claude-flow/metrics/performance.json | 2 +- benchmark/.claude-flow/metrics/task-metrics.json | 6 +- benchmark/.claude/checkpoints/1754444893.json | 1 + benchmark/.claude/checkpoints/1754444895.json | 1 + benchmark/mle_star_benchmark_example.py | 2 +- benchmark/run_performance_tests.py | 550 --------------------- .../continuous_performance_monitor.py | 0 benchmark/{ => scripts}/hive-mind-load-test.py | 0 benchmark/{ => scripts}/hive-mind-stress-test.py | 0 benchmark/{ => scripts}/run-load-tests.py | 0 benchmark/test_mle_star_integration.py | 2 +- claude-flow-wiki | 0 13 files changed, 80 insertions(+), 556 deletions(-) "} diff --git a/benchmark/scripts/simple-load-test.py b/benchmark/scripts/simple-load-test.py new file mode 100644 index 0000000000..20cd2768bf --- /dev/null +++ b/benchmark/scripts/simple-load-test.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +""" +Simple Hive Mind Load Test +Quick validation of the system's load handling capabilities +""" + +import os +import sys +import json +import time +import psutil +import subprocess +from datetime import datetime +from pathlib import Path +from typing import Dict, List, Any + +class SimpleLoadTester: + """Simple load tester for basic validation""" + + def __init__(self): + self.cli_path = Path("../src/cli/simple-cli.js") + self.results = [] + + def run_cli_command(self, command: List[str], timeout: int = 30) -> Dict[str, Any]: + """Run a CLI command with timeout""" + start_time = time.time() + + try: + result = subprocess.run( + ["node", str(self.cli_path)] + command, + capture_output=True, + text=True, + timeout=timeout, + cwd=Path.cwd().parent + ) + + duration = time.time() - start_time + + return { + "success": result.returncode == 0, + "duration": duration, + "stdout": result.stdout, + "stderr": result.stderr, + "returncode": result.returncode + } + except subprocess.TimeoutExpired: + return { + "success": False, + "duration": timeout, + "stdout": "", + "stderr": f"Command timed out after {timeout} seconds", + "returncode": -1 + } + except Exception as e: + return { + "success": False, + "duration": time.time() - start_time, + "stdout": "", + "stderr": str(e), + "returncode": -1 + } + + def test_basic_commands(self) -> Dict[str, Any]: + """Test basic CLI commands""" + print("๐Ÿงช Testing basic CLI commands...") + + tests = [ + (["--help"], "Help command"), + (["--version"], "Version command"), + (["status"], "Status command") + ] + + results = {} + + for command, description in tests: + print(f" Testing: {description}") + result = self.run_cli_command(command, timeout=10) + results[description] = result + + if result["success"]: + print(f" โœ… {description}: {result['duration']:.2f}s") + else: + print(f" โŒ {description}: {result['stderr'][:100]}") + + return results + + def test_swarm_initialization(self) -> Dict[str, Any]: + """Test swarm initialization""" + print("๐Ÿ Testing swarm initialization...") + + # Test swarm init + result = self.run_cli_command(["swarm", "init", "--test"], timeout=30) + + if result["success"]: + print(" โœ… Swarm initialization: SUCCESS") + return {"swarm_init": result} + else: + print(f" โŒ Swarm initialization: FAILED - {result['stderr'][:100]}") + return {"swarm_init": result} + + def test_agent_spawning(self) -> Dict[str, Any]: + """Test agent spawning""" + print("๐Ÿค– Testing agent spawning...") + + agent_tests = [ + (["agent", "spawn", "researcher", "--test"], "Spawn researcher"), + (["agent", "spawn", "coder", "--test"], "Spawn coder"), + (["agent", "list"], "List agents") + ] + + results = {} + + for command, description in agent_tests: + print(f" Testing: {description}") + result = self.run_cli_command(command, timeout=20) + results[description] = result + + if result["success"]: + print(f" โœ… {description}: {result['duration']:.2f}s") + else: + print(f" โŒ {description}: {result['stderr'][:100]}") + + return results + + def test_memory_operations(self) -> Dict[str, Any]: + """Test memory operations""" + print("๐Ÿ’พ Testing memory operations...") + + memory_tests = [ + (["memory", "store", "test_key", "test_value"], "Store memory"), + (["memory", "retrieve", "test_key"], "Retrieve memory"), + (["memory", "list"], "List memory") + ] + + results = {} + + for command, description in memory_tests: + print(f" Testing: {description}") + result = self.run_cli_command(command, timeout=15) + results[description] = result + + if result["success"]: + print(f" โœ… {description}: {result['duration']:.2f}s") + else: + print(f" โŒ {description}: {result['stderr'][:100]}") + + return results + + def measure_system_resources(self) -> Dict[str, Any]: + """Measure current system resources""" + try: + memory = psutil.virtual_memory() + cpu_percent = psutil.cpu_percent(interval=1) + + return { + "memory_percent": memory.percent, + "memory_mb": memory.used / (1024**2), + "available_memory_mb": memory.available / (1024**2), + "cpu_percent": cpu_percent, + "process_count": len(psutil.pids()) + } + except Exception as e: + return {"error": str(e)} + + def run_load_simulation(self, operations: int = 10) -> Dict[str, Any]: + """Run a simple load simulation""" + print(f"โšก Running load simulation with {operations} operations...") + + start_time = time.time() + start_resources = self.measure_system_resources() + + successful_operations = 0 + failed_operations = 0 + response_times = [] + + for i in range(operations): + print(f" Operation {i+1}/{operations}") + + # Test a simple command + op_start = time.time() + result = self.run_cli_command(["status"], timeout=10) + op_duration = time.time() - op_start + + response_times.append(op_duration) + + if result["success"]: + successful_operations += 1 + else: + failed_operations += 1 + + # Brief pause between operations + time.sleep(0.5) + + total_duration = time.time() - start_time + end_resources = self.measure_system_resources() + + # Calculate metrics + avg_response_time = sum(response_times) / len(response_times) if response_times else 0 + throughput = successful_operations / total_duration if total_duration > 0 else 0 + success_rate = successful_operations / operations if operations > 0 else 0 + + return { + "total_operations": operations, + "successful_operations": successful_operations, + "failed_operations": failed_operations, + "total_duration": total_duration, + "avg_response_time": avg_response_time, + "throughput": throughput, + "success_rate": success_rate, + "start_resources": start_resources, + "end_resources": end_resources, + "response_times": response_times + } + + def run_simple_load_test(self) -> Dict[str, Any]: + """Run the complete simple load test""" + print("๐Ÿ”ฅ Simple Hive Mind Load Test") + print("=" * 40) + + start_time = datetime.now() + + # Test phases + results = { + "test_start_time": start_time.isoformat(), + "basic_commands": self.test_basic_commands(), + "swarm_initialization": self.test_swarm_initialization(), + "agent_spawning": self.test_agent_spawning(), + "memory_operations": self.test_memory_operations(), + "load_simulation": self.run_load_simulation(10), + "system_info": { + "cpu_count": psutil.cpu_count(), + "memory_gb": psutil.virtual_memory().total / (1024**3), + "platform": sys.platform + } + } + + end_time = datetime.now() + results["test_end_time"] = end_time.isoformat() + results["total_test_duration"] = (end_time - start_time).total_seconds() + + # Generate summary + self.generate_summary(results) + + return results + + def generate_summary(self, results: Dict[str, Any]): + """Generate test summary""" + print("\\n๐Ÿ“Š TEST SUMMARY") + print("=" * 40) + + # Basic command results + basic_success = sum(1 for r in results["basic_commands"].values() if r.get("success", False)) + basic_total = len(results["basic_commands"]) + print(f"Basic Commands: {basic_success}/{basic_total} passed") + + # Swarm initialization + swarm_success = results["swarm_initialization"]["swarm_init"]["success"] + print(f"Swarm Init: {'โœ… PASS' if swarm_success else 'โŒ FAIL'}") + + # Agent spawning + agent_success = sum(1 for r in results["agent_spawning"].values() if r.get("success", False)) + agent_total = len(results["agent_spawning"]) + print(f"Agent Operations: {agent_success}/{agent_total} passed") + + # Memory operations + memory_success = sum(1 for r in results["memory_operations"].values() if r.get("success", False)) + memory_total = len(results["memory_operations"]) + print(f"Memory Operations: {memory_success}/{memory_total} passed") + + # Load simulation + load_sim = results["load_simulation"] + print(f"Load Simulation:") + print(f" Success Rate: {load_sim['success_rate']:.1%}") + print(f" Throughput: {load_sim['throughput']:.2f} ops/sec") + print(f" Avg Response: {load_sim['avg_response_time']:.3f}s") + + # Overall assessment + total_tests = basic_total + 1 + agent_total + memory_total + total_passed = basic_success + (1 if swarm_success else 0) + agent_success + memory_success + overall_success_rate = total_passed / total_tests if total_tests > 0 else 0 + + print(f"\\n๐ŸŽฏ OVERALL RESULT:") + print(f"Tests Passed: {total_passed}/{total_tests} ({overall_success_rate:.1%})") + print(f"Duration: {results['total_test_duration']:.1f} seconds") + + if overall_success_rate >= 0.8: + print("โœ… SYSTEM READY FOR LOAD TESTING") + elif overall_success_rate >= 0.5: + print("โš ๏ธ SYSTEM PARTIALLY READY - Some issues detected") + else: + print("โŒ SYSTEM NOT READY - Multiple failures detected") + + # Save results + output_file = Path("simple_load_test_results.json") + with open(output_file, 'w') as f: + json.dump(results, f, indent=2) + + print(f"\\n๐Ÿ“„ Results saved to: {output_file}") + +def main(): + """Main execution""" + tester = SimpleLoadTester() + + try: + results = tester.run_simple_load_test() + + # Exit with appropriate code + load_sim = results["load_simulation"] + if load_sim["success_rate"] >= 0.8: + sys.exit(0) # Success + else: + sys.exit(1) # Failure + + except KeyboardInterrupt: + print("\\nโš ๏ธ Test interrupted by user") + sys.exit(1) + except Exception as e: + print(f"\\nโŒ Test failed: {e}") + sys.exit(1) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/benchmark/scripts/swarm_performance_suite.py b/benchmark/scripts/swarm_performance_suite.py new file mode 100644 index 0000000000..1c8373501b --- /dev/null +++ b/benchmark/scripts/swarm_performance_suite.py @@ -0,0 +1,840 @@ +#!/usr/bin/env python3 +""" +Comprehensive Performance Benchmarking Suite for Claude-Flow Swarm Operations + +This suite provides automated performance testing and monitoring for: +- Swarm initialization performance +- Agent coordination latency +- Memory usage patterns and leak detection +- Token consumption optimization +- Cross-session persistence overhead +- MCP tool response times +- Neural pattern processing speed + +Author: Metrics Analyst Agent +Version: 1.0.0 +""" + +import asyncio +import time +import json +import psutil +import subprocess +import os +import sys +from datetime import datetime, timedelta +from pathlib import Path +from typing import Dict, List, Any, Optional, Tuple +from dataclasses import dataclass, asdict +import threading +import tempfile +import signal +from contextlib import asynccontextmanager +import statistics + +# Add benchmark modules to path +sys.path.insert(0, str(Path(__file__).parent / "src")) + +from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine +from swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode +from swarm_benchmark.metrics.performance_collector import PerformanceCollector + + +@dataclass +class SwarmPerformanceTarget: + """Performance targets for swarm operations.""" + swarm_init_time_seconds: float = 5.0 + agent_coordination_latency_ms: float = 200.0 + memory_baseline_mb: float = 1.0 + token_reduction_percent: float = 32.3 + persistence_overhead_percent: float = 10.0 + mcp_response_time_seconds: float = 1.0 + neural_processing_time_ms: float = 500.0 + + +@dataclass +class SwarmBenchmarkResult: + """Result from a swarm performance benchmark.""" + test_name: str + start_time: datetime + end_time: datetime + duration_seconds: float + success: bool + metrics: Dict[str, Any] + target_met: bool + error_message: Optional[str] = None + + def to_dict(self) -> Dict[str, Any]: + return { + "test_name": self.test_name, + "start_time": self.start_time.isoformat(), + "end_time": self.end_time.isoformat(), + "duration_seconds": self.duration_seconds, + "success": self.success, + "metrics": self.metrics, + "target_met": self.target_met, + "error_message": self.error_message + } + + +class SwarmMemoryLeakDetector: + """Detects memory leaks in swarm operations.""" + + def __init__(self): + self.baseline_memory = 0.0 + self.peak_memory = 0.0 + self.samples = [] + self.sampling_interval = 0.5 # 500ms + self._stop_event = threading.Event() + self._monitor_thread = None + + def start_monitoring(self): + """Start memory monitoring.""" + self.baseline_memory = psutil.Process().memory_info().rss / 1024 / 1024 + self.peak_memory = self.baseline_memory + self.samples = [] + self._stop_event.clear() + + self._monitor_thread = threading.Thread(target=self._monitor_memory, daemon=True) + self._monitor_thread.start() + + def stop_monitoring(self) -> Dict[str, float]: + """Stop monitoring and return leak analysis.""" + self._stop_event.set() + if self._monitor_thread: + self._monitor_thread.join(timeout=5.0) + + current_memory = psutil.Process().memory_info().rss / 1024 / 1024 + memory_growth = current_memory - self.baseline_memory + + # Calculate memory growth trend + if len(self.samples) > 10: + # Use linear regression to detect steady growth + times = [s[0] for s in self.samples] + memories = [s[1] for s in self.samples] + n = len(samples) + + # Simple linear regression + sum_xy = sum(t * m for t, m in zip(times, memories)) + sum_x = sum(times) + sum_y = sum(memories) + sum_x2 = sum(t * t for t in times) + + slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x) if n * sum_x2 - sum_x * sum_x != 0 else 0 + growth_rate_mb_per_second = slope + else: + growth_rate_mb_per_second = 0 + + return { + "baseline_memory_mb": self.baseline_memory, + "final_memory_mb": current_memory, + "peak_memory_mb": self.peak_memory, + "memory_growth_mb": memory_growth, + "growth_rate_mb_per_second": growth_rate_mb_per_second, + "leak_detected": growth_rate_mb_per_second > 0.1, # >100KB/s growth = leak + "sample_count": len(self.samples) + } + + def _monitor_memory(self): + """Background memory monitoring thread.""" + start_time = time.time() + while not self._stop_event.is_set(): + try: + current_time = time.time() - start_time + current_memory = psutil.Process().memory_info().rss / 1024 / 1024 + + self.samples.append((current_time, current_memory)) + self.peak_memory = max(self.peak_memory, current_memory) + + # Keep only last 1000 samples to prevent memory bloat + if len(self.samples) > 1000: + self.samples = self.samples[-500:] + + time.sleep(self.sampling_interval) + except Exception: + break + + +class SwarmPerformanceBenchmark: + """Main performance benchmark suite for swarm operations.""" + + def __init__(self, output_dir: str = "performance_results"): + self.output_dir = Path(output_dir) + self.output_dir.mkdir(exist_ok=True) + self.targets = SwarmPerformanceTarget() + self.memory_detector = SwarmMemoryLeakDetector() + self.results: List[SwarmBenchmarkResult] = [] + + async def run_full_suite(self) -> Dict[str, Any]: + """Run the complete performance benchmark suite.""" + print("๐Ÿš€ Starting Comprehensive Swarm Performance Benchmark Suite") + print("=" * 60) + + suite_start = datetime.now() + + # Test categories + test_categories = [ + ("Startup Performance", self._test_startup_performance), + ("Coordination Efficiency", self._test_coordination_efficiency), + ("Memory Performance", self._test_memory_performance), + ("Network Performance", self._test_network_performance), + ("Scalability Tests", self._test_scalability), + ("Regression Tests", self._test_regression_detection) + ] + + category_results = {} + + for category_name, test_func in test_categories: + print(f"\n๐Ÿ“Š Running {category_name} Tests...") + try: + category_results[category_name] = await test_func() + passed = sum(1 for r in category_results[category_name] if r.target_met) + total = len(category_results[category_name]) + print(f"โœ… {category_name}: {passed}/{total} tests passed targets") + except Exception as e: + print(f"โŒ {category_name} failed: {e}") + category_results[category_name] = [] + + suite_end = datetime.now() + + # Generate comprehensive report + report = await self._generate_performance_report(category_results, suite_start, suite_end) + + # Save results + await self._save_results(report) + + return report + + async def _test_startup_performance(self) -> List[SwarmBenchmarkResult]: + """Test swarm initialization and ready state performance.""" + tests = [] + + # Test 1: Basic swarm initialization + result = await self._benchmark_operation( + "swarm_init_basic", + lambda: self._run_claude_flow_command(["swarm", "init", "--mode", "mesh", "--agents", "3"]), + target_time=self.targets.swarm_init_time_seconds + ) + tests.append(result) + + # Test 2: Large swarm initialization + result = await self._benchmark_operation( + "swarm_init_large", + lambda: self._run_claude_flow_command(["swarm", "init", "--mode", "hierarchical", "--agents", "8"]), + target_time=self.targets.swarm_init_time_seconds * 2 # Allow more time for larger swarms + ) + tests.append(result) + + # Test 3: Cold start vs warm start + # Cold start + result = await self._benchmark_operation( + "cold_start", + lambda: self._run_claude_flow_command(["swarm", "status"], clear_cache=True), + target_time=self.targets.swarm_init_time_seconds + ) + tests.append(result) + + # Warm start (immediate second call) + result = await self._benchmark_operation( + "warm_start", + lambda: self._run_claude_flow_command(["swarm", "status"]), + target_time=self.targets.swarm_init_time_seconds / 2 # Should be faster + ) + tests.append(result) + + return tests + + async def _test_coordination_efficiency(self) -> List[SwarmBenchmarkResult]: + """Test agent-to-agent coordination and communication.""" + tests = [] + + # Test 1: Agent spawn latency + result = await self._benchmark_operation( + "agent_spawn_latency", + lambda: self._measure_agent_spawn_time(), + target_time=self.targets.agent_coordination_latency_ms / 1000.0 + ) + tests.append(result) + + # Test 2: Inter-agent communication + result = await self._benchmark_operation( + "inter_agent_communication", + lambda: self._measure_agent_communication(), + target_time=self.targets.agent_coordination_latency_ms / 1000.0 + ) + tests.append(result) + + # Test 3: Task coordination overhead + result = await self._benchmark_operation( + "task_coordination_overhead", + lambda: self._measure_coordination_overhead(), + target_time=self.targets.agent_coordination_latency_ms / 1000.0 + ) + tests.append(result) + + return tests + + async def _test_memory_performance(self) -> List[SwarmBenchmarkResult]: + """Test memory usage patterns and leak detection.""" + tests = [] + + # Test 1: Memory leak detection + result = await self._benchmark_memory_operation( + "memory_leak_detection", + lambda: self._run_extended_swarm_operation(), + target_growth_mb=1.0 + ) + tests.append(result) + + # Test 2: Memory baseline measurement + result = await self._benchmark_operation( + "memory_baseline", + lambda: self._measure_baseline_memory(), + target_time=1.0, # Quick test + custom_metrics=True + ) + tests.append(result) + + # Test 3: Persistence overhead + result = await self._benchmark_operation( + "persistence_overhead", + lambda: self._measure_persistence_overhead(), + target_time=self.targets.persistence_overhead_percent / 100.0 # Convert to multiplier + ) + tests.append(result) + + return tests + + async def _test_network_performance(self) -> List[SwarmBenchmarkResult]: + """Test MCP tool response times and network efficiency.""" + tests = [] + + # Test 1: MCP tool response time + result = await self._benchmark_operation( + "mcp_response_time", + lambda: self._measure_mcp_response_time(), + target_time=self.targets.mcp_response_time_seconds + ) + tests.append(result) + + # Test 2: Neural pattern processing + result = await self._benchmark_operation( + "neural_pattern_processing", + lambda: self._measure_neural_processing(), + target_time=self.targets.neural_processing_time_ms / 1000.0 + ) + tests.append(result) + + return tests + + async def _test_scalability(self) -> List[SwarmBenchmarkResult]: + """Test performance under increasing loads.""" + tests = [] + + agent_counts = [1, 2, 4, 8, 16] + + for count in agent_counts: + result = await self._benchmark_operation( + f"scalability_agents_{count}", + lambda c=count: self._run_scalability_test(c), + target_time=self.targets.swarm_init_time_seconds * (1 + count / 10) # Linear scaling expectation + ) + tests.append(result) + + return tests + + async def _test_regression_detection(self) -> List[SwarmBenchmarkResult]: + """Test for performance regressions.""" + tests = [] + + # Load baseline metrics if available + baseline_file = self.output_dir / "baseline_metrics.json" + baseline_metrics = {} + + if baseline_file.exists(): + with open(baseline_file) as f: + baseline_metrics = json.load(f) + + # Test current performance against baseline + current_metrics = await self._measure_current_performance() + + for metric_name, current_value in current_metrics.items(): + if metric_name in baseline_metrics: + baseline_value = baseline_metrics[metric_name] + regression_threshold = 1.1 # 10% regression tolerance + + target_met = current_value <= baseline_value * regression_threshold + + result = SwarmBenchmarkResult( + test_name=f"regression_{metric_name}", + start_time=datetime.now(), + end_time=datetime.now(), + duration_seconds=0.0, + success=True, + metrics={ + "current_value": current_value, + "baseline_value": baseline_value, + "regression_percent": ((current_value - baseline_value) / baseline_value) * 100 + }, + target_met=target_met + ) + tests.append(result) + + # Save current metrics as new baseline + with open(baseline_file, 'w') as f: + json.dump(current_metrics, f, indent=2) + + return tests + + async def _benchmark_operation(self, test_name: str, operation, target_time: float, custom_metrics: bool = False) -> SwarmBenchmarkResult: + """Benchmark a single operation against performance targets.""" + start_time = datetime.now() + + # Start performance monitoring + collector = PerformanceCollector(sample_interval=0.1) + collector.start_collection() + + try: + operation_start = time.time() + result = await asyncio.get_event_loop().run_in_executor(None, operation) + operation_end = time.time() + + duration = operation_end - operation_start + performance_metrics = collector.stop_collection() + + end_time = datetime.now() + + # Check if target was met + target_met = duration <= target_time + + metrics = { + "duration_seconds": duration, + "target_seconds": target_time, + "execution_time": performance_metrics.execution_time, + "throughput": performance_metrics.throughput, + "success_rate": performance_metrics.success_rate, + "operation_result": str(result)[:200] if result else "N/A" + } + + return SwarmBenchmarkResult( + test_name=test_name, + start_time=start_time, + end_time=end_time, + duration_seconds=duration, + success=True, + metrics=metrics, + target_met=target_met + ) + + except Exception as e: + collector.stop_collection() + end_time = datetime.now() + + return SwarmBenchmarkResult( + test_name=test_name, + start_time=start_time, + end_time=end_time, + duration_seconds=(end_time - start_time).total_seconds(), + success=False, + metrics={"error": str(e)}, + target_met=False, + error_message=str(e) + ) + + async def _benchmark_memory_operation(self, test_name: str, operation, target_growth_mb: float) -> SwarmBenchmarkResult: + """Benchmark operation specifically for memory usage.""" + start_time = datetime.now() + + # Start memory leak detection + self.memory_detector.start_monitoring() + + try: + operation_start = time.time() + result = await asyncio.get_event_loop().run_in_executor(None, operation) + operation_end = time.time() + + # Stop memory monitoring and analyze + memory_metrics = self.memory_detector.stop_monitoring() + duration = operation_end - operation_start + end_time = datetime.now() + + # Check if memory growth target was met + target_met = memory_metrics["memory_growth_mb"] <= target_growth_mb and not memory_metrics["leak_detected"] + + metrics = { + "duration_seconds": duration, + "memory_metrics": memory_metrics, + "target_growth_mb": target_growth_mb, + "operation_result": str(result)[:200] if result else "N/A" + } + + return SwarmBenchmarkResult( + test_name=test_name, + start_time=start_time, + end_time=end_time, + duration_seconds=duration, + success=True, + metrics=metrics, + target_met=target_met + ) + + except Exception as e: + self.memory_detector.stop_monitoring() + end_time = datetime.now() + + return SwarmBenchmarkResult( + test_name=test_name, + start_time=start_time, + end_time=end_time, + duration_seconds=(end_time - start_time).total_seconds(), + success=False, + metrics={"error": str(e)}, + target_met=False, + error_message=str(e) + ) + + def _run_claude_flow_command(self, args: List[str], clear_cache: bool = False) -> str: + """Run a claude-flow command and return output.""" + if clear_cache: + # Clear any potential cache + cache_dirs = [ + Path.home() / ".claude-flow" / "cache", + Path.cwd() / ".cache", + Path("/tmp/claude-flow-cache") + ] + for cache_dir in cache_dirs: + if cache_dir.exists(): + import shutil + shutil.rmtree(cache_dir, ignore_errors=True) + + # Construct command + cmd = ["node", str(Path(__file__).parent / "../cli.js")] + args + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=30, + cwd=str(Path(__file__).parent.parent) + ) + return result.stdout + except subprocess.TimeoutExpired: + return "TIMEOUT" + except Exception as e: + return f"ERROR: {e}" + + def _measure_agent_spawn_time(self) -> float: + """Measure time to spawn a new agent.""" + start = time.time() + output = self._run_claude_flow_command(["swarm", "spawn", "researcher", "--name", "test-agent"]) + end = time.time() + return end - start + + def _measure_agent_communication(self) -> float: + """Measure inter-agent communication latency.""" + # This would measure actual communication between agents + # For now, simulate with a simple command + start = time.time() + output = self._run_claude_flow_command(["swarm", "status"]) + end = time.time() + return end - start + + def _measure_coordination_overhead(self) -> float: + """Measure task coordination overhead.""" + # Compare single agent vs multi-agent task execution + start = time.time() + output = self._run_claude_flow_command(["swarm", "task", "simple test task", "--agents", "3"]) + end = time.time() + return end - start + + def _run_extended_swarm_operation(self) -> str: + """Run an extended operation to test for memory leaks.""" + operations = [] + + # Run multiple operations that could cause memory leaks + for i in range(10): + output = self._run_claude_flow_command(["swarm", "init", "--mode", "mesh", "--agents", "2"]) + operations.append(output) + + output = self._run_claude_flow_command(["swarm", "spawn", "researcher"]) + operations.append(output) + + output = self._run_claude_flow_command(["swarm", "status"]) + operations.append(output) + + # Small delay to allow monitoring + time.sleep(0.1) + + return "\n".join(operations) + + def _measure_baseline_memory(self) -> str: + """Measure baseline memory usage.""" + process = psutil.Process() + return f"Baseline memory: {process.memory_info().rss / 1024 / 1024:.2f} MB" + + def _measure_persistence_overhead(self) -> float: + """Measure cross-session persistence overhead.""" + # Time operation with persistence vs without + start = time.time() + output = self._run_claude_flow_command(["swarm", "init", "--persist"]) + end = time.time() + return end - start + + def _measure_mcp_response_time(self) -> float: + """Measure MCP tool response time.""" + start = time.time() + output = self._run_claude_flow_command(["mcp", "status"]) + end = time.time() + return end - start + + def _measure_neural_processing(self) -> float: + """Measure neural pattern processing time.""" + start = time.time() + output = self._run_claude_flow_command(["sparc", "researcher", "quick test"]) + end = time.time() + return end - start + + def _run_scalability_test(self, agent_count: int) -> float: + """Run scalability test with specified agent count.""" + start = time.time() + output = self._run_claude_flow_command(["swarm", "init", "--agents", str(agent_count)]) + end = time.time() + return end - start + + async def _measure_current_performance(self) -> Dict[str, float]: + """Measure current performance metrics for regression testing.""" + metrics = {} + + # Swarm init time + start = time.time() + self._run_claude_flow_command(["swarm", "init", "--mode", "mesh", "--agents", "3"]) + metrics["swarm_init_time"] = time.time() - start + + # Agent spawn time + start = time.time() + self._run_claude_flow_command(["swarm", "spawn", "researcher"]) + metrics["agent_spawn_time"] = time.time() - start + + # Memory usage + process = psutil.Process() + metrics["memory_usage_mb"] = process.memory_info().rss / 1024 / 1024 + + return metrics + + async def _generate_performance_report(self, category_results: Dict[str, List[SwarmBenchmarkResult]], + suite_start: datetime, suite_end: datetime) -> Dict[str, Any]: + """Generate comprehensive performance report.""" + + # Aggregate all results + all_results = [] + for category_results_list in category_results.values(): + all_results.extend(category_results_list) + + # Calculate summary statistics + total_tests = len(all_results) + passed_tests = sum(1 for r in all_results if r.target_met) + failed_tests = sum(1 for r in all_results if not r.success) + + # Calculate performance score (0-100) + if total_tests > 0: + performance_score = (passed_tests / total_tests) * 100 + else: + performance_score = 0 + + # Identify critical issues + critical_issues = [] + for result in all_results: + if not result.target_met and result.success: + critical_issues.append({ + "test": result.test_name, + "issue": "Performance target not met", + "metrics": result.metrics + }) + elif not result.success: + critical_issues.append({ + "test": result.test_name, + "issue": "Test failed", + "error": result.error_message + }) + + # Generate recommendations + recommendations = self._generate_recommendations(all_results) + + report = { + "summary": { + "test_suite": "Swarm Performance Benchmark", + "version": "1.0.0", + "start_time": suite_start.isoformat(), + "end_time": suite_end.isoformat(), + "duration_minutes": (suite_end - suite_start).total_seconds() / 60, + "total_tests": total_tests, + "passed_tests": passed_tests, + "failed_tests": failed_tests, + "performance_score": performance_score + }, + "targets": asdict(self.targets), + "category_results": { + category: [result.to_dict() for result in results] + for category, results in category_results.items() + }, + "critical_issues": critical_issues, + "recommendations": recommendations, + "detailed_metrics": { + "memory_analysis": await self._analyze_memory_patterns(all_results), + "performance_trends": await self._analyze_performance_trends(all_results), + "bottleneck_analysis": await self._identify_bottlenecks(all_results) + } + } + + return report + + def _generate_recommendations(self, results: List[SwarmBenchmarkResult]) -> List[str]: + """Generate performance optimization recommendations.""" + recommendations = [] + + # Analyze results for common patterns + slow_startup_tests = [r for r in results if "init" in r.test_name and not r.target_met] + if slow_startup_tests: + recommendations.append("Consider optimizing swarm initialization by implementing connection pooling") + + memory_issues = [r for r in results if "memory" in r.test_name and not r.target_met] + if memory_issues: + recommendations.append("Memory usage exceeded targets - investigate memory leaks in agent cleanup") + + coordination_issues = [r for r in results if "coordination" in r.test_name and not r.target_met] + if coordination_issues: + recommendations.append("Agent coordination latency high - consider implementing async message passing") + + scalability_issues = [r for r in results if "scalability" in r.test_name and not r.target_met] + if scalability_issues: + recommendations.append("Scalability limits reached - implement load balancing and resource pooling") + + if not recommendations: + recommendations.append("All performance targets met - consider tightening targets for continued optimization") + + return recommendations + + async def _analyze_memory_patterns(self, results: List[SwarmBenchmarkResult]) -> Dict[str, Any]: + """Analyze memory usage patterns across tests.""" + memory_tests = [r for r in results if "memory" in r.metrics] + + if not memory_tests: + return {"analysis": "No memory data available"} + + memory_values = [] + for result in memory_tests: + if "memory_metrics" in result.metrics: + memory_values.append(result.metrics["memory_metrics"].get("peak_memory_mb", 0)) + + if memory_values: + return { + "peak_memory_mb": max(memory_values), + "average_memory_mb": statistics.mean(memory_values), + "memory_variance": statistics.variance(memory_values) if len(memory_values) > 1 else 0, + "trend": "increasing" if memory_values[-1] > memory_values[0] else "stable" + } + else: + return {"analysis": "No memory metrics collected"} + + async def _analyze_performance_trends(self, results: List[SwarmBenchmarkResult]) -> Dict[str, Any]: + """Analyze performance trends across test categories.""" + trends = {} + + # Group by test category + by_category = {} + for result in results: + category = result.test_name.split("_")[0] + if category not in by_category: + by_category[category] = [] + by_category[category].append(result.duration_seconds) + + for category, durations in by_category.items(): + if len(durations) > 1: + trends[category] = { + "average_duration": statistics.mean(durations), + "min_duration": min(durations), + "max_duration": max(durations), + "consistency": 1.0 - (statistics.stdev(durations) / statistics.mean(durations)) if statistics.mean(durations) > 0 else 0 + } + + return trends + + async def _identify_bottlenecks(self, results: List[SwarmBenchmarkResult]) -> List[Dict[str, Any]]: + """Identify performance bottlenecks from test results.""" + bottlenecks = [] + + # Find tests that significantly exceed targets + for result in results: + if result.success and not result.target_met: + if "target_seconds" in result.metrics and result.duration_seconds > result.metrics["target_seconds"] * 2: + bottlenecks.append({ + "test": result.test_name, + "severity": "high", + "actual_duration": result.duration_seconds, + "target_duration": result.metrics["target_seconds"], + "slowdown_factor": result.duration_seconds / result.metrics["target_seconds"] + }) + + # Sort by severity + bottlenecks.sort(key=lambda x: x.get("slowdown_factor", 1), reverse=True) + + return bottlenecks[:5] # Top 5 bottlenecks + + async def _save_results(self, report: Dict[str, Any]): + """Save benchmark results to files.""" + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + + # Save main report + report_file = self.output_dir / f"swarm_performance_report_{timestamp}.json" + with open(report_file, 'w') as f: + json.dump(report, f, indent=2, default=str) + + # Save CSV summary for spreadsheet analysis + csv_file = self.output_dir / f"swarm_performance_summary_{timestamp}.csv" + with open(csv_file, 'w') as f: + f.write("test_name,duration_seconds,target_met,success,category\n") + for category, results in report["category_results"].items(): + for result in results: + f.write(f"{result['test_name']},{result['duration_seconds']},{result['target_met']},{result['success']},{category}\n") + + print(f"\n๐Ÿ“Š Results saved to:") + print(f" Report: {report_file}") + print(f" CSV: {csv_file}") + + # Print summary + summary = report["summary"] + print(f"\n๐ŸŽฏ Performance Summary:") + print(f" Score: {summary['performance_score']:.1f}/100") + print(f" Tests: {summary['passed_tests']}/{summary['total_tests']} passed") + print(f" Duration: {summary['duration_minutes']:.1f} minutes") + + if report["critical_issues"]: + print(f"\nโš ๏ธ Critical Issues Found: {len(report['critical_issues'])}") + for issue in report["critical_issues"][:3]: # Show top 3 + print(f" - {issue['test']}: {issue['issue']}") + + +async def main(): + """Main entry point for the performance benchmark suite.""" + import argparse + + parser = argparse.ArgumentParser(description="Swarm Performance Benchmark Suite") + parser.add_argument("--output-dir", default="performance_results", help="Output directory for results") + parser.add_argument("--quick", action="store_true", help="Run quick subset of tests") + args = parser.parse_args() + + benchmark = SwarmPerformanceBenchmark(output_dir=args.output_dir) + + if args.quick: + # Run only essential tests for quick feedback + print("๐Ÿš€ Running Quick Performance Check...") + result = await benchmark._test_startup_performance() + print(f"Quick check completed: {len([r for r in result if r.target_met])}/{len(result)} targets met") + else: + # Run full suite + await benchmark.run_full_suite() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/benchmark/test_simple_run.py b/benchmark/test_simple_run.py index 58e2503948..4b9647c443 100644 --- a/benchmark/test_simple_run.py +++ b/benchmark/test_simple_run.py @@ -1,6 +1,11 @@ """Simple test to check if the benchmark engine works.""" import asyncio +import sys +from pathlib import Path + +# Add the src directory to Python path +sys.path.insert(0, str(Path(__file__).parent / "src")) from swarm_benchmark.core.benchmark_engine import BenchmarkEngine from swarm_benchmark.core.models import BenchmarkConfig, StrategyType