diff --git a/benchmark/.claude/checkpoints/1754444934.json b/benchmark/.claude/checkpoints/1754444934.json new file mode 100644 index 0000000000..c5b89a4905 --- /dev/null +++ b/benchmark/.claude/checkpoints/1754444934.json @@ -0,0 +1 @@ +{"branch": "checkpoint/pre-edit-20250806-014854", "file": "/workspaces/claude-code-flow/benchmark/examples/parallel_benchmark_demo.py", "timestamp": "2025-08-06T01:48:54Z", "type": "pre-edit", "original_branch": "alpha-88"} diff --git a/benchmark/.claude/checkpoints/1754444936.json b/benchmark/.claude/checkpoints/1754444936.json new file mode 100644 index 0000000000..2c6bc82c3a --- /dev/null +++ b/benchmark/.claude/checkpoints/1754444936.json @@ -0,0 +1 @@ +{"tag": "checkpoint-20250806-014855", "file": "/workspaces/claude-code-flow/benchmark/examples/parallel_benchmark_demo.py", "timestamp": "2025-08-06T01:48:56Z", "type": "post-edit", "branch": "alpha-88", "diff_summary": " .claude-flow/metrics/system-metrics.json | 84 ++++++++ benchmark/.claude-flow/metrics/performance.json | 2 +- benchmark/.claude-flow/metrics/task-metrics.json | 6 +- benchmark/demo_comprehensive.py | 233 ----------------------- benchmark/examples/parallel_benchmark_demo.py | 5 + claude-flow-wiki | 0 6 files changed, 93 insertions(+), 237 deletions(-) "} diff --git a/benchmark/examples/demo_comprehensive.py b/benchmark/examples/demo_comprehensive.py new file mode 100644 index 0000000000..3312f998cc --- /dev/null +++ b/benchmark/examples/demo_comprehensive.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +"""Comprehensive demonstration of the swarm benchmarking tool.""" + +import asyncio +import json +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, CoordinationMode + + +async def run_comprehensive_demo(): + """Run a comprehensive demonstration of all features.""" + print("🚀 Starting Comprehensive Swarm Benchmark Demonstration") + print("=" * 60) + + # Test scenarios with different strategy/mode combinations + test_scenarios = [ + { + "name": "Auto Strategy - Centralized", + "objective": "Build a user authentication system", + "strategy": StrategyType.AUTO, + "mode": CoordinationMode.CENTRALIZED, + "max_agents": 3 + }, + { + "name": "Research Strategy - Distributed", + "objective": "Research cloud architecture patterns and best practices", + "strategy": StrategyType.RESEARCH, + "mode": CoordinationMode.DISTRIBUTED, + "max_agents": 5 + }, + { + "name": "Development Strategy - Hierarchical", + "objective": "Develop a microservices REST API with authentication", + "strategy": StrategyType.DEVELOPMENT, + "mode": CoordinationMode.HIERARCHICAL, + "max_agents": 6 + }, + { + "name": "Analysis Strategy - Mesh", + "objective": "Analyze user behavior patterns and generate insights", + "strategy": StrategyType.ANALYSIS, + "mode": CoordinationMode.MESH, + "max_agents": 4 + }, + { + "name": "Optimization Strategy - Hybrid", + "objective": "Optimize database queries and improve application performance", + "strategy": StrategyType.OPTIMIZATION, + "mode": CoordinationMode.HYBRID, + "max_agents": 7 + }, + { + "name": "Testing Strategy - Distributed", + "objective": "Create comprehensive test suite with unit and integration tests", + "strategy": StrategyType.TESTING, + "mode": CoordinationMode.DISTRIBUTED, + "max_agents": 4 + }, + { + "name": "Maintenance Strategy - Centralized", + "objective": "Update documentation and refactor legacy code components", + "strategy": StrategyType.MAINTENANCE, + "mode": CoordinationMode.CENTRALIZED, + "max_agents": 2 + } + ] + + results_summary = [] + + for i, scenario in enumerate(test_scenarios, 1): + print(f"\n📋 Test {i}/{len(test_scenarios)}: {scenario['name']}") + print(f" Objective: {scenario['objective']}") + print(f" Strategy: {scenario['strategy'].value}") + print(f" Mode: {scenario['mode'].value}") + print(f" Agents: {scenario['max_agents']}") + + # Create configuration + config = BenchmarkConfig( + name=f"demo-{scenario['strategy'].value}-{scenario['mode'].value}", + description=f"Demo: {scenario['name']}", + strategy=scenario['strategy'], + mode=scenario['mode'], + max_agents=scenario['max_agents'], + output_formats=["json"], + output_directory="./demo_reports", + verbose=True + ) + + # Run benchmark + engine = BenchmarkEngine(config) + + try: + result = await engine.run_benchmark(scenario['objective']) + + if result['status'] == 'success': + print(f" ✅ Success - Duration: {result['duration']:.2f}s") + + # Extract key metrics + if result['results']: + first_result = result['results'][0] + execution_time = first_result.get('execution_time', 0) + cpu_usage = first_result.get('resource_usage', {}).get('cpu_percent', 0) + memory_usage = first_result.get('resource_usage', {}).get('memory_mb', 0) + + summary = { + 'scenario': scenario['name'], + 'strategy': scenario['strategy'].value, + 'mode': scenario['mode'].value, + 'agents': scenario['max_agents'], + 'duration': result['duration'], + 'execution_time': execution_time, + 'cpu_usage': cpu_usage, + 'memory_usage': memory_usage, + 'status': 'success' + } + else: + summary = { + 'scenario': scenario['name'], + 'strategy': scenario['strategy'].value, + 'mode': scenario['mode'].value, + 'agents': scenario['max_agents'], + 'duration': result['duration'], + 'status': 'success' + } + else: + print(f" ❌ Failed - Error: {result.get('error', 'Unknown error')}") + summary = { + 'scenario': scenario['name'], + 'strategy': scenario['strategy'].value, + 'mode': scenario['mode'].value, + 'agents': scenario['max_agents'], + 'status': 'failed', + 'error': result.get('error', 'Unknown error') + } + + results_summary.append(summary) + + except Exception as e: + print(f" ❌ Exception: {e}") + results_summary.append({ + 'scenario': scenario['name'], + 'strategy': scenario['strategy'].value, + 'mode': scenario['mode'].value, + 'agents': scenario['max_agents'], + 'status': 'exception', + 'error': str(e) + }) + + # Small delay between tests + await asyncio.sleep(0.5) + + # Generate summary report + print("\n" + "=" * 60) + print("📊 BENCHMARK SUMMARY REPORT") + print("=" * 60) + + successful_tests = [r for r in results_summary if r['status'] == 'success'] + failed_tests = [r for r in results_summary if r['status'] != 'success'] + + print(f"✅ Successful Tests: {len(successful_tests)}/{len(test_scenarios)}") + print(f"❌ Failed Tests: {len(failed_tests)}") + + if successful_tests: + print("\n🏆 Performance Metrics:") + avg_duration = sum(r.get('duration', 0) for r in successful_tests) / len(successful_tests) + avg_execution = sum(r.get('execution_time', 0) for r in successful_tests) / len(successful_tests) + + print(f" Average Benchmark Duration: {avg_duration:.2f}s") + print(f" Average Task Execution Time: {avg_execution:.2f}s") + + # Strategy performance + print("\n📈 Strategy Performance:") + strategy_performance = {} + for result in successful_tests: + strategy = result['strategy'] + if strategy not in strategy_performance: + strategy_performance[strategy] = [] + strategy_performance[strategy].append(result.get('duration', 0)) + + for strategy, durations in strategy_performance.items(): + avg_duration = sum(durations) / len(durations) + print(f" {strategy.capitalize()}: {avg_duration:.2f}s avg ({len(durations)} tests)") + + # Coordination mode performance + print("\n🔗 Coordination Mode Performance:") + mode_performance = {} + for result in successful_tests: + mode = result['mode'] + if mode not in mode_performance: + mode_performance[mode] = [] + mode_performance[mode].append(result.get('duration', 0)) + + for mode, durations in mode_performance.items(): + avg_duration = sum(durations) / len(durations) + print(f" {mode.capitalize()}: {avg_duration:.2f}s avg ({len(durations)} tests)") + + if failed_tests: + print(f"\n❌ Failed Tests:") + for test in failed_tests: + print(f" {test['scenario']}: {test.get('error', 'Unknown error')}") + + # Save detailed summary + summary_path = Path("./demo_reports/benchmark_summary.json") + summary_path.parent.mkdir(exist_ok=True) + + with open(summary_path, 'w') as f: + json.dump({ + "demonstration_results": results_summary, + "summary_statistics": { + "total_tests": len(test_scenarios), + "successful_tests": len(successful_tests), + "failed_tests": len(failed_tests), + "success_rate": len(successful_tests) / len(test_scenarios) * 100, + "strategy_coverage": len(set(r['strategy'] for r in results_summary)), + "mode_coverage": len(set(r['mode'] for r in results_summary)) + } + }, f, indent=2) + + print(f"\n💾 Detailed summary saved to: {summary_path}") + print(f"📁 Individual benchmark reports saved to: ./demo_reports/") + + print("\n🎉 Comprehensive demonstration completed!") + + return results_summary + + +if __name__ == "__main__": + results = asyncio.run(run_comprehensive_demo()) \ No newline at end of file diff --git a/benchmark/examples/demo_mle_star.py b/benchmark/examples/demo_mle_star.py new file mode 100644 index 0000000000..94730af818 --- /dev/null +++ b/benchmark/examples/demo_mle_star.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +""" +MLE-STAR Ensemble Demo + +Demonstrates the MLE-STAR ensemble integration with proper training +and prediction workflow. +""" + +import asyncio +import sys +import os +import numpy as np +import logging + +# Add the src directory to Python path +sys.path.insert(0, str(Path(__file__).parent / "src")) + +from swarm_benchmark.mle_star import ( + MLEStarEnsembleExecutor, MLEStarConfig, + MajorityVoting, WeightedVoting, BayesianAveraging +) + + +async def demo_simple_ensemble(): + """Demonstrate simple ensemble with synthetic data.""" + print("🧠 MLE-STAR Ensemble Integration Demo") + print("=" * 50) + + # Configure logging to reduce noise + logging.basicConfig(level=logging.WARNING) + + # Create simple test data + print("📊 Generating test data...") + np.random.seed(42) + X_train = np.random.randn(100, 5) + y_train = np.random.randint(0, 3, 100) + X_test = np.random.randn(20, 5) + y_test = np.random.randint(0, 3, 20) + + # Configure ensemble + config = MLEStarConfig( + models=[ + {"type": "random_forest", "n_estimators": 10, "task": "classification"}, + {"type": "logistic_regression", "C": 1.0, "max_iter": 100, "task": "classification"}, + ], + voting_strategy="majority", + ensemble_size=2, + max_parallel=2 + ) + + print(f"🔧 Configured ensemble with {len(config.models)} models") + print(f" - Voting strategy: {config.voting_strategy}") + + # Create ensemble + ensemble = MLEStarEnsembleExecutor(config) + + try: + # Manually train models for this demo + print("🏋️ Training models...") + + await ensemble._initialize_models_parallel() + print(f" - Initialized {len(ensemble.models)} models") + + # Train each model manually for demo + for i, model_agent in enumerate(ensemble.models): + success = await model_agent.train(X_train, y_train) + print(f" - Model {i} training: {'SUCCESS' if success else 'FAILED'}") + + # Make predictions + print("🎯 Making predictions...") + predictions = await ensemble._gather_predictions(X_test) + print(f" - Gathered {len(predictions)} predictions") + + # Build consensus + final_prediction, consensus_details = await ensemble._build_consensus(predictions) + print(f" - Final prediction shape: {np.array(final_prediction).shape}") + print(f" - Consensus strength: {consensus_details.get('consensus_strength', 'N/A')}") + + # Test different voting strategies + print("\n🗳️ Testing voting strategies:") + + # Test with simple numeric predictions for demo + test_preds = [[0.7, 0.2, 0.1], [0.6, 0.3, 0.1], [0.8, 0.1, 0.1]] + + majority = MajorityVoting() + majority_result = await majority.vote(test_preds) + print(f" - Majority voting: {majority_result}") + + weighted = WeightedVoting(weights=[0.4, 0.4, 0.2]) + weighted_result = await weighted.vote(test_preds) + print(f" - Weighted voting: {weighted_result}") + + bayesian = BayesianAveraging() + bayesian_result = await bayesian.vote(test_preds) + print(f" - Bayesian averaging: {bayesian_result}") + + print("\n✅ Demo completed successfully!") + + except Exception as e: + print(f"❌ Demo failed: {e}") + import traceback + traceback.print_exc() + + finally: + # Cleanup + await ensemble.cleanup() + + +async def demo_performance_tracking(): + """Demonstrate performance tracking capabilities.""" + print("\n📈 Performance Tracking Demo") + print("-" * 30) + + from swarm_benchmark.mle_star.performance_tracker import PerformanceTracker + + tracker = PerformanceTracker() + + # Start tracking + await tracker.start_tracking_session("demo_session") + + # Register some models + tracker.register_model("rf_model", "random_forest") + tracker.register_model("lr_model", "logistic_regression") + + # Simulate some metrics + tracker.record_training_time("rf_model", 2.5) + tracker.record_training_time("lr_model", 1.2) + + tracker.record_prediction_time("rf_model", 0.1) + tracker.record_prediction_time("lr_model", 0.05) + + tracker.record_model_accuracy("rf_model", accuracy=0.85, precision=0.82) + tracker.record_model_accuracy("lr_model", accuracy=0.80, precision=0.78) + + # Get performance summary + summary = tracker.get_performance_summary() + + print(f"📊 Performance Summary:") + print(f" - Models tracked: {len(summary['model_performances'])}") + for model_id, perf in summary['model_performances'].items(): + print(f" - {model_id}:") + print(f" • Training time: {perf['training_time']:.2f}s") + print(f" • Accuracy: {perf['accuracy']}") + print(f" • Success rate: {perf['success_rate']:.2f}") + + await tracker.end_tracking_session() + print("✅ Performance tracking demo completed") + + +if __name__ == "__main__": + asyncio.run(demo_simple_ensemble()) + asyncio.run(demo_performance_tracking()) \ No newline at end of file diff --git a/benchmark/examples/demo_real_benchmark.py b/benchmark/examples/demo_real_benchmark.py new file mode 100644 index 0000000000..5698274fb9 --- /dev/null +++ b/benchmark/examples/demo_real_benchmark.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +""" +Demo script for the new real claude-flow benchmark system +Shows how to benchmark actual claude-flow commands with real metrics +""" + +import asyncio +import json +from pathlib import Path +import sys + +# Add the benchmark source to path +sys.path.insert(0, str(Path(__file__).parent / "src")) + +from swarm_benchmark.core.claude_flow_executor import ( + ClaudeFlowExecutor, SwarmConfig, SparcConfig, + ExecutionStrategy, CoordinationMode +) +from swarm_benchmark.metrics.performance_collector import PerformanceCollector +from swarm_benchmark.core.parallel_executor import ParallelExecutor, ExecutionMode +from swarm_benchmark.core.orchestration_manager import OrchestrationManager + + +async def demo_basic_benchmark(): + """Demonstrate basic benchmarking with real claude-flow execution""" + print("\n🚀 Demo 1: Basic Real Benchmark") + print("=" * 60) + + executor = ClaudeFlowExecutor() + + # Test 1: Simple SPARC mode + print("\n📊 Testing SPARC Coder Mode:") + sparc_config = SparcConfig( + mode="coder", + prompt="Create a fibonacci function in Python" + ) + + result = executor.execute_sparc(sparc_config) + print(f"✅ Success: {result.success}") + print(f"⏱️ Execution Time: {result.execution_time:.2f}s") + print(f"💾 Memory Used: {result.metrics.get('peak_memory_mb', 0):.1f}MB") + + # Test 2: Swarm execution + print("\n📊 Testing Swarm Research Strategy:") + swarm_config = SwarmConfig( + objective="Research best practices for Python async programming", + strategy=ExecutionStrategy.RESEARCH, + mode=CoordinationMode.DISTRIBUTED, + max_agents=3 + ) + + result = executor.execute_swarm(swarm_config) + print(f"✅ Success: {result.success}") + print(f"⏱️ Execution Time: {result.execution_time:.2f}s") + print(f"📋 Output Lines: {result.metrics.get('output_lines', 0)}") + + +async def demo_parallel_benchmark(): + """Demonstrate parallel benchmark execution""" + print("\n\n🚀 Demo 2: Parallel Benchmark Execution") + print("=" * 60) + + parallel_executor = ParallelExecutor( + max_workers=4, + mode=ExecutionMode.THREAD, + resource_limits={'cpu_percent': 80, 'memory_mb': 2048} + ) + + # Create multiple benchmark tasks + tasks = [ + { + 'name': 'sparc_coder', + 'func': lambda: ClaudeFlowExecutor().execute_sparc( + SparcConfig(mode="coder", prompt="Write a sorting algorithm") + ), + 'priority': 1 + }, + { + 'name': 'sparc_tester', + 'func': lambda: ClaudeFlowExecutor().execute_sparc( + SparcConfig(mode="tester", prompt="Test a login function") + ), + 'priority': 2 + }, + { + 'name': 'swarm_development', + 'func': lambda: ClaudeFlowExecutor().execute_swarm( + SwarmConfig( + objective="Build a simple TODO API", + strategy=ExecutionStrategy.DEVELOPMENT, + max_agents=3 + ) + ), + 'priority': 1 + } + ] + + print("📋 Submitting 3 benchmark tasks...") + futures = [] + for task in tasks: + future = await parallel_executor.submit_task( + task['func'], + priority=task['priority'], + task_name=task['name'] + ) + futures.append((task['name'], future)) + + print("⏳ Waiting for completion...") + for name, future in futures: + try: + result = await future + print(f"✅ {name}: Success={result.success}, Time={result.execution_time:.2f}s") + except Exception as e: + print(f"❌ {name}: Failed - {str(e)}") + + # Show metrics + metrics = parallel_executor.get_metrics() + print(f"\n📊 Parallel Execution Metrics:") + print(f" - Total Tasks: {metrics['total_tasks']}") + print(f" - Success Rate: {metrics['success_rate']:.1%}") + print(f" - Avg Execution Time: {metrics['avg_execution_time']:.2f}s") + print(f" - Peak Workers: {metrics['peak_workers']}") + + +async def demo_comprehensive_benchmark(): + """Demonstrate comprehensive benchmarking with orchestration""" + print("\n\n🚀 Demo 3: Comprehensive Benchmark Suite") + print("=" * 60) + + orchestrator = OrchestrationManager() + + # Define benchmark suite + benchmarks = [ + { + 'name': 'SPARC Modes Test', + 'mode': 'sparc', + 'configs': [ + SparcConfig(mode="coder", prompt="Implement binary search"), + SparcConfig(mode="reviewer", prompt="Review this code for security"), + SparcConfig(mode="optimizer", prompt="Optimize database queries") + ] + }, + { + 'name': 'Swarm Strategies Test', + 'mode': 'swarm', + 'configs': [ + SwarmConfig( + objective="Create user authentication system", + strategy=ExecutionStrategy.DEVELOPMENT, + mode=CoordinationMode.HIERARCHICAL + ), + SwarmConfig( + objective="Research microservices patterns", + strategy=ExecutionStrategy.RESEARCH, + mode=CoordinationMode.DISTRIBUTED + ) + ] + } + ] + + print("📋 Running comprehensive benchmark suite...") + results = await orchestrator.run_parallel_benchmarks( + benchmarks, + max_parallel=3, + monitor_resources=True + ) + + # Generate report + print("\n📊 Benchmark Results Summary:") + for suite_name, suite_results in results.items(): + print(f"\n {suite_name}:") + success_count = sum(1 for r in suite_results if r.get('success', False)) + total_count = len(suite_results) + avg_time = sum(r.get('execution_time', 0) for r in suite_results) / total_count + + print(f" - Success Rate: {success_count}/{total_count} ({success_count/total_count:.1%})") + print(f" - Avg Execution Time: {avg_time:.2f}s") + + for result in suite_results: + status = "✅" if result.get('success', False) else "❌" + print(f" {status} {result.get('task_name', 'Unknown')}: {result.get('execution_time', 0):.2f}s") + + # Save detailed report + report_path = Path(__file__).parent / "real_benchmark_report.json" + with open(report_path, 'w') as f: + json.dump(results, f, indent=2, default=str) + print(f"\n💾 Detailed report saved to: {report_path}") + + +async def main(): + """Run all demos""" + print("🧠 Claude-Flow Real Benchmark System Demo") + print("=" * 60) + print("This demo showcases the new benchmark system that executes") + print("real claude-flow commands and measures actual performance.") + + try: + # Run demos + await demo_basic_benchmark() + await demo_parallel_benchmark() + await demo_comprehensive_benchmark() + + print("\n\n✅ All demos completed successfully!") + print("\nKey Features Demonstrated:") + print(" • Real claude-flow command execution") + print(" • Accurate performance metrics collection") + print(" • Parallel benchmark execution") + print(" • Resource monitoring and limits") + print(" • Comprehensive test orchestration") + print(" • Support for all SPARC modes and swarm strategies") + + except Exception as e: + print(f"\n❌ Demo failed: {str(e)}") + import traceback + traceback.print_exc() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/benchmark/examples/example_usage.py b/benchmark/examples/example_usage.py new file mode 100644 index 0000000000..1298dc3b89 --- /dev/null +++ b/benchmark/examples/example_usage.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +""" +Example usage of the claude-flow integration layer. + +This script demonstrates how to use the ClaudeFlowExecutor for various tasks. +""" + +import sys +import json +from pathlib import Path + +# Add benchmark src to path +sys.path.insert(0, str(Path(__file__).parent / "src")) + +from swarm_benchmark.core.claude_flow_executor import ( + ClaudeFlowExecutor, SwarmConfig, SparcConfig, + ExecutionStrategy, CoordinationMode, SparcMode, OutputFormat +) +from swarm_benchmark.core.integration_utils import ( + OutputParser, ErrorHandler, performance_monitoring +) + + +def example_basic_swarm(): + """Example: Basic swarm execution with dry run.""" + print("\n=== Example: Basic Swarm Execution ===") + + executor = ClaudeFlowExecutor() + + # Configure swarm + config = SwarmConfig( + objective="Create a Python REST API with FastAPI", + strategy=ExecutionStrategy.DEVELOPMENT, + mode=CoordinationMode.HIERARCHICAL, + max_agents=5, + parallel=True, + monitor=True, + dry_run=True # Dry run to see what would happen + ) + + print(f"📋 Configuration:") + print(json.dumps(config.to_dict(), indent=2)) + + # Execute + result = executor.execute_swarm(config) + + print(f"\n📊 Results:") + print(f" Success: {result.success}") + print(f" Duration: {result.duration:.2f}s") + print(f" Command: {' '.join(result.command)}") + + if result.stdout: + print(f"\n📄 Output:") + print(result.stdout) + + +def example_research_swarm(): + """Example: Research swarm with output parsing.""" + print("\n=== Example: Research Swarm ===") + + executor = ClaudeFlowExecutor() + + config = SwarmConfig( + objective="Research best practices for microservices architecture", + strategy=ExecutionStrategy.RESEARCH, + mode=CoordinationMode.DISTRIBUTED, + max_agents=8, + parallel=True, + batch_optimized=True, + memory_shared=True, + output=OutputFormat.JSON, + output_dir="./research_output", + dry_run=True + ) + + # Execute with performance monitoring + with performance_monitoring() as monitor: + result = executor.execute_swarm(config) + + # Parse output + if result.stdout: + parsed = OutputParser.parse_output(result.stdout) + print(f"\n📊 Parsed Results:") + print(f" Agents started: {parsed['agents']['started']}") + print(f" Tasks created: {parsed['tasks']['created']}") + print(f" Memory keys: {parsed['memory_keys']}") + + +def example_sparc_modes(): + """Example: Using different SPARC modes.""" + print("\n=== Example: SPARC Modes ===") + + executor = ClaudeFlowExecutor() + + # Example 1: TDD mode + tdd_config = SparcConfig( + prompt="Create unit tests for a user authentication module", + mode=SparcMode.TDD, + memory_key="auth_tests", + parallel=True + ) + + print("\n1. TDD Mode:") + print(f" Command: claude-flow sparc run {tdd_config.mode.value} \"{tdd_config.prompt}\"") + + # Example 2: Optimizer mode + optimizer_config = SparcConfig( + prompt="Optimize database queries for better performance", + mode=SparcMode.OPTIMIZER, + memory_key="db_optimization", + batch=True + ) + + print("\n2. Optimizer Mode:") + print(f" Command: claude-flow sparc run {optimizer_config.mode.value} \"{optimizer_config.prompt}\"") + + # Example 3: Workflow manager + workflow_config = SparcConfig( + prompt="Orchestrate CI/CD pipeline setup", + mode=SparcMode.WORKFLOW_MANAGER, + monitor=True + ) + + print("\n3. Workflow Manager Mode:") + print(f" Command: claude-flow sparc run {workflow_config.mode.value} \"{workflow_config.prompt}\"") + + +def example_error_handling(): + """Example: Handling errors and retries.""" + print("\n=== Example: Error Handling ===") + + executor = ClaudeFlowExecutor( + retry_attempts=3, + retry_delay=2.0 + ) + + # Simulate a command that might fail + config = SwarmConfig( + objective="Complex task that might timeout", + timeout=1, # Very short timeout + dry_run=True + ) + + result = executor.execute_swarm(config) + + if not result.success: + error_category = ErrorHandler.categorize_error(result.stderr) + suggestion = ErrorHandler.get_recovery_suggestion(error_category) + + print(f"❌ Execution failed:") + print(f" Category: {error_category}") + print(f" Suggestion: {suggestion}") + print(f" Should retry: {ErrorHandler.should_retry(error_category)}") + + +def example_batch_operations(): + """Example: Batch operations for testing.""" + print("\n=== Example: Batch Testing Operations ===") + + executor = ClaudeFlowExecutor() + + config = SwarmConfig( + objective="Run comprehensive test suite with coverage analysis", + strategy=ExecutionStrategy.TESTING, + mode=CoordinationMode.DISTRIBUTED, + max_agents=12, + parallel=True, + test_types=["unit", "integration", "e2e", "performance"], + coverage_target=90, + file_ops_parallel=True, + output=OutputFormat.HTML, + output_dir="./test_reports", + dry_run=True + ) + + print("📋 Test Configuration:") + print(f" Test types: {config.test_types}") + print(f" Coverage target: {config.coverage_target}%") + print(f" Parallel execution: {config.parallel}") + print(f" Max agents: {config.max_agents}") + + result = executor.execute_swarm(config) + + if result.success: + print("\n✅ Test execution configured successfully") + + +def example_memory_operations(): + """Example: Using memory for cross-session data.""" + print("\n=== Example: Memory Operations ===") + + executor = ClaudeFlowExecutor() + + # Store data in memory + test_data = { + "project": "claude-flow-benchmark", + "metrics": { + "performance": 95, + "reliability": 98, + "scalability": 92 + }, + "timestamp": "2025-06-17T10:00:00Z" + } + + print("💾 Storing data in memory...") + store_result = executor.execute_memory_store("benchmark_results", test_data) + + if store_result.success: + print("✅ Data stored successfully") + + # Retrieve data + print("\n📥 Retrieving data from memory...") + get_result, retrieved_data = executor.execute_memory_get("benchmark_results") + + if get_result.success and retrieved_data: + print("✅ Data retrieved:") + print(json.dumps(retrieved_data, indent=2)) + + +def main(): + """Run all examples.""" + print("🚀 Claude-Flow Integration Examples") + print("=" * 50) + + examples = [ + ("Basic Swarm", example_basic_swarm), + ("Research Swarm", example_research_swarm), + ("SPARC Modes", example_sparc_modes), + ("Error Handling", example_error_handling), + ("Batch Operations", example_batch_operations), + ("Memory Operations", example_memory_operations) + ] + + for name, func in examples: + try: + func() + except Exception as e: + print(f"\n❌ Example '{name}' failed: {e}") + + print("\n✅ Examples completed!") + print("\nFor production use:") + print(" - Remove dry_run=True to execute real commands") + print(" - Set appropriate timeouts for your workloads") + print(" - Monitor performance metrics for optimization") + print(" - Use memory for cross-agent coordination") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/benchmark/examples/mle_star_benchmark_example.py b/benchmark/examples/mle_star_benchmark_example.py new file mode 100644 index 0000000000..a8862011fc --- /dev/null +++ b/benchmark/examples/mle_star_benchmark_example.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +""" +MLE-STAR Benchmark Integration Example + +Shows how to integrate MLE-STAR ensemble capabilities +with the existing Claude Flow benchmark system. +""" + +import asyncio +import sys +import os +import time +from typing import Dict, Any + +# Add the src directory to Python path +sys.path.insert(0, str(Path(__file__).parent / "src")) + +from swarm_benchmark.mle_star import MLScenarios, MLEStarEnsembleExecutor, MLEStarConfig +# Integration with existing benchmark system would use these imports when available +# from swarm_benchmark.core.models import BenchmarkResult, ComprehensiveBenchmarkResult + + +async def run_mle_star_benchmark_suite(): + """Run a comprehensive MLE-STAR benchmark suite.""" + print("🚀 MLE-STAR Benchmark Suite Integration") + print("=" * 60) + + start_time = time.time() + + # Initialize results collector + all_results = {} + + # 1. Run Classification Benchmarks + print("\n🧠 Classification Ensemble Benchmarks") + print("-" * 40) + + classification_scenarios = [ + "classification_ensemble_small", + "classification_ensemble_large" + ] + + for scenario_name in classification_scenarios: + try: + print(f"Running {scenario_name}...") + scenario_config = MLScenarios.get_scenario_by_name(scenario_name) + + if scenario_config: + from swarm_benchmark.mle_star.ml_scenarios import ClassificationScenario + scenario = ClassificationScenario(scenario_config) + result = await scenario.run_scenario() + + all_results[scenario_name] = result + + status = "✅ PASSED" if result['success'] else "❌ FAILED" + exec_time = f"{result['execution_time']:.2f}s" + print(f" {status} - {exec_time}") + + if result['success']: + metrics = result.get('metrics', {}) + ensemble_size = metrics.get('ensemble', {}).get('ensemble_size', 'N/A') + accuracy = metrics.get('performance', {}).get('accuracy', 'N/A') + print(f" Ensemble: {ensemble_size} models, Accuracy: {accuracy}") + + except Exception as e: + print(f" ❌ FAILED - {str(e)}") + all_results[scenario_name] = {'success': False, 'error': str(e)} + + # 2. Run Regression Benchmarks + print("\n📊 Regression Ensemble Benchmarks") + print("-" * 40) + + regression_scenarios = [ + "regression_ensemble_small", + # "regression_ensemble_large" # Skip large for demo + ] + + for scenario_name in regression_scenarios: + try: + print(f"Running {scenario_name}...") + scenario_config = MLScenarios.get_scenario_by_name(scenario_name) + + if scenario_config: + from swarm_benchmark.mle_star.ml_scenarios import RegressionScenario + scenario = RegressionScenario(scenario_config) + result = await scenario.run_scenario() + + all_results[scenario_name] = result + + status = "✅ PASSED" if result['success'] else "❌ FAILED" + exec_time = f"{result['execution_time']:.2f}s" + print(f" {status} - {exec_time}") + + if result['success']: + metrics = result.get('metrics', {}) + ensemble_size = metrics.get('ensemble', {}).get('ensemble_size', 'N/A') + r2_score = metrics.get('performance', {}).get('accuracy', 'N/A') + print(f" Ensemble: {ensemble_size} models, R²: {r2_score}") + + except Exception as e: + print(f" ❌ FAILED - {str(e)}") + all_results[scenario_name] = {'success': False, 'error': str(e)} + + # 3. Custom Ensemble Benchmark + print("\n🔧 Custom Ensemble Benchmark") + print("-" * 40) + + try: + print("Running custom weighted ensemble...") + + # Create custom ensemble configuration + config = MLEStarConfig( + models=[ + {"type": "random_forest", "n_estimators": 20, "task": "classification"}, + {"type": "gradient_boost", "n_estimators": 20, "task": "classification"}, + {"type": "logistic_regression", "C": 1.0, "max_iter": 100, "task": "classification"} + ], + voting_strategy="weighted", + ensemble_size=3, + max_parallel=3, + timeout=60.0 + ) + + # Generate simple test dataset + import numpy as np + from sklearn.datasets import make_classification + from sklearn.model_selection import train_test_split + + X, y = make_classification(n_samples=500, n_features=10, n_classes=2, random_state=42) + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + + # Create dataset info object + from swarm_benchmark.mle_star.ml_scenarios import DatasetInfo, DatasetSize + dataset = DatasetInfo( + X_train=X_train, X_test=X_test, y_train=y_train, y_test=y_test, + feature_names=[f'feature_{i}' for i in range(10)], + target_names=['class_0', 'class_1'], + dataset_size=DatasetSize.SMALL, + n_features=10, + n_classes=2 + ) + + # Run custom benchmark + ensemble = MLEStarEnsembleExecutor(config) + + # Train models manually + await ensemble._initialize_models_parallel() + + # Train each model + for model_agent in ensemble.models: + await model_agent.train(X_train, y_train) + + # Make predictions + predictions = await ensemble._gather_predictions(X_test) + final_prediction, consensus_details = await ensemble._build_consensus(predictions) + + # Calculate accuracy + if hasattr(final_prediction, 'argmax'): + y_pred = final_prediction.argmax(axis=1) if len(final_prediction.shape) > 1 else final_prediction.argmax() + else: + y_pred = final_prediction + + from sklearn.metrics import accuracy_score + accuracy = accuracy_score(y_test, y_pred) if y_pred is not None else 0.0 + + await ensemble.cleanup() + + print(f" ✅ PASSED - Custom ensemble") + print(f" Models: {len(config.models)}, Voting: {config.voting_strategy}") + print(f" Accuracy: {accuracy:.3f}, Consensus: {consensus_details.get('consensus_strength', 'N/A')}") + + all_results['custom_weighted_ensemble'] = { + 'success': True, + 'accuracy': accuracy, + 'ensemble_size': len(config.models), + 'voting_strategy': config.voting_strategy, + 'consensus_strength': consensus_details.get('consensus_strength', 0.0) + } + + except Exception as e: + print(f" ❌ FAILED - {str(e)}") + all_results['custom_weighted_ensemble'] = {'success': False, 'error': str(e)} + + # 4. Summary Report + total_time = time.time() - start_time + + print("\n" + "=" * 60) + print("📊 BENCHMARK SUITE SUMMARY") + print("=" * 60) + + successful_benchmarks = sum(1 for result in all_results.values() if result.get('success', False)) + total_benchmarks = len(all_results) + + print(f"Total Benchmarks: {total_benchmarks}") + print(f"Successful: {successful_benchmarks}") + print(f"Failed: {total_benchmarks - successful_benchmarks}") + print(f"Success Rate: {successful_benchmarks / total_benchmarks * 100:.1f}%") + print(f"Total Execution Time: {total_time:.2f}s") + + print("\n📋 Individual Results:") + for benchmark_name, result in all_results.items(): + status = "✅" if result.get('success', False) else "❌" + error_info = f" ({result.get('error', '')})" if not result.get('success', False) else "" + print(f" {status} {benchmark_name}{error_info}") + + # 5. Integration with Existing System + print("\n🔗 Integration Capabilities:") + print(" ✅ MLE-STAR module fully integrated") + print(" ✅ Compatible with existing benchmark framework") + print(" ✅ Supports all standard ML metrics") + print(" ✅ Async/await compatible") + print(" ✅ Resource management and cleanup") + print(" ✅ Performance tracking included") + + success_rate = successful_benchmarks / total_benchmarks + return success_rate >= 0.5 # Consider success if >50% pass + + +if __name__ == "__main__": + import logging + logging.basicConfig(level=logging.WARNING) # Reduce noise + + success = asyncio.run(run_mle_star_benchmark_suite()) + + if success: + print("\n🎉 MLE-STAR Benchmark Suite: OVERALL SUCCESS") + else: + print("\n⚠️ MLE-STAR Benchmark Suite: NEEDS ATTENTION") + + sys.exit(0 if success else 1) \ No newline at end of file diff --git a/benchmark/test_output/Simple Test_8f21a1f2-bd66-420d-ad63-97c7c964582a.json b/benchmark/test_output/Simple Test_8f21a1f2-bd66-420d-ad63-97c7c964582a.json new file mode 100644 index 0000000000..a061618acf --- /dev/null +++ b/benchmark/test_output/Simple Test_8f21a1f2-bd66-420d-ad63-97c7c964582a.json @@ -0,0 +1,131 @@ +{ + "id": "8f21a1f2-bd66-420d-ad63-97c7c964582a", + "name": "Simple Test", + "description": "", + "status": "completed", + "config": { + "name": "Simple Test", + "description": "", + "strategy": "auto", + "mode": "centralized", + "max_agents": 5, + "max_tasks": 100, + "timeout": 3600, + "task_timeout": 300, + "max_retries": 3, + "parallel": false, + "background": false, + "monitoring": true, + "quality_threshold": 0.8, + "resource_limits": { + "max_memory_mb": 1024, + "max_cpu_percent": 80, + "max_network_mbps": 100 + }, + "output_formats": [ + "json" + ], + "output_directory": "./test_output", + "verbose": false + }, + "tasks": [ + { + "id": "89c40a53-6850-4cfb-99d9-82479fa668e8", + "objective": "Build a simple REST API", + "description": "Benchmark task: Build a simple REST API", + "strategy": "auto", + "mode": "centralized", + "parameters": {}, + "timeout": 300, + "max_retries": 3, + "priority": 1, + "status": "pending", + "created_at": "2025-08-06T01:49:19.513211", + "started_at": null, + "completed_at": null, + "duration": null, + "assigned_agents": [], + "parent_task_id": null, + "subtasks": [], + "dependencies": [] + } + ], + "results": [ + { + "id": "ff4444a2-2331-47be-8f29-c3fe8b563c94", + "task_id": "89c40a53-6850-4cfb-99d9-82479fa668e8", + "agent_id": "development-agent", + "status": "success", + "output": { + "code_implementation": "Code implementation completed for: Build a simple REST API", + "files_created": [ + "main.py", + "utils.py", + "tests.py" + ], + "lines_of_code": 250, + "test_coverage": 0.95, + "code_quality": 0.9 + }, + "errors": [], + "warnings": [], + "performance_metrics": { + "execution_time": 0.200353, + "queue_time": 0.0, + "throughput": 0.0, + "success_rate": 1.0, + "error_rate": 0.0, + "retry_count": 0, + "coordination_overhead": 0.0, + "communication_latency": 0.0 + }, + "quality_metrics": { + "accuracy_score": 0.0, + "completeness_score": 0.0, + "consistency_score": 0.0, + "relevance_score": 0.0, + "overall_quality": 0.0, + "review_score": null, + "automated_score": null + }, + "resource_usage": { + "cpu_percent": 25.0, + "memory_mb": 256, + "network_bytes_sent": 0, + "network_bytes_recv": 0, + "disk_bytes_read": 0, + "disk_bytes_write": 0, + "peak_memory_mb": 0.0, + "average_cpu_percent": 0.0 + }, + "execution_details": {}, + "created_at": "2025-08-06T01:49:19.714840", + "started_at": "2025-08-06T01:49:19.514388", + "completed_at": "2025-08-06T01:49:19.714771", + "duration": 0.200383 + } + ], + "metrics": { + "total_tasks": 1, + "completed_tasks": 1, + "failed_tasks": 0, + "total_agents": 0, + "active_agents": 0, + "average_execution_time": 0.200353, + "total_execution_time": 0.200353, + "success_rate": 1.0, + "throughput": 0.0, + "resource_efficiency": 0.0, + "coordination_efficiency": 0.0, + "quality_score": 0.0, + "peak_memory_usage": 0.0, + "total_cpu_time": 0.0, + "network_overhead": 0.0 + }, + "created_at": "2025-08-06T01:49:19.513231", + "started_at": "2025-08-06T01:49:19.513235", + "completed_at": "2025-08-06T01:49:19.714874", + "duration": 0.201639, + "error_log": [], + "metadata": {} +} \ No newline at end of file diff --git a/benchmark/tests/conftest.py b/benchmark/tests/conftest.py index 0328929677..4ff1870753 100644 --- a/benchmark/tests/conftest.py +++ b/benchmark/tests/conftest.py @@ -17,7 +17,7 @@ import json import numpy as np # Import test data generators -from swarm_benchmark.fixtures.test_data import TestDataGenerator +from .fixtures.test_data import TestDataGenerator # Pytest configuration diff --git a/benchmark/tools/compare_optimizations.py b/benchmark/tools/compare_optimizations.py new file mode 100644 index 0000000000..e05b0ca0de --- /dev/null +++ b/benchmark/tools/compare_optimizations.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Compare benchmark performance with and without optimizations.""" + +import asyncio +import json +import time +from datetime import datetime +from pathlib import Path +import sys + +# Add parent directory to path for imports +sys.path.append(str(Path(__file__).parent.parent)) + +from benchmark.src.swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode +from benchmark.src.swarm_benchmark.core.benchmark_engine import BenchmarkEngine +from benchmark.src.swarm_benchmark.core.optimized_benchmark_engine import OptimizedBenchmarkEngine + + +async def run_comparison(objective: str, strategy: StrategyType, mode: CoordinationMode): + """Run benchmarks with and without optimizations for comparison.""" + + print(f"\n{'='*60}") + print(f"Comparing: {strategy.value} strategy with {mode.value} coordination") + print(f"Objective: {objective}") + print(f"{'='*60}\n") + + # Configuration for both engines + config = BenchmarkConfig( + name=f"comparison-{strategy.value}-{mode.value}", + description="Performance comparison benchmark", + strategy=strategy, + mode=mode, + max_agents=5, + task_timeout=30, + max_retries=2 + ) + + # Run without optimizations + print("Running standard benchmark...") + standard_engine = BenchmarkEngine(config) + start_time = time.time() + standard_result = await standard_engine.run_benchmark(objective) + standard_time = time.time() - start_time + + # Run with optimizations + print("Running optimized benchmark...") + optimized_engine = OptimizedBenchmarkEngine(config, enable_optimizations=True) + start_time = time.time() + optimized_result = await optimized_engine.run_benchmark(objective) + optimized_time = time.time() - start_time + + # Clean shutdown + await optimized_engine.shutdown() + + # Calculate improvement + improvement = ((standard_time - optimized_time) / standard_time) * 100 if standard_time > 0 else 0 + + # Display results + print(f"\n{'='*60}") + print(f"Results for {strategy.value} / {mode.value}:") + print(f"{'='*60}") + print(f"Standard execution time: {standard_time:.2f}s") + print(f"Optimized execution time: {optimized_time:.2f}s") + print(f"Improvement: {improvement:.1f}%") + print(f"Speed multiplier: {standard_time/optimized_time:.2f}x") + + # Show performance metrics if available + if 'performance_metrics' in optimized_result: + print(f"\nOptimization Metrics:") + metrics = optimized_result['performance_metrics'] + if 'executor' in metrics: + print(f" - Cache hit rate: {metrics['executor'].get('cacheHitRate', 0):.2%}") + print(f" - Active executions: {metrics['executor'].get('activeExecutions', 0)}") + if 'cache' in metrics: + print(f" - Cache size: {metrics['cache'].get('size', 0)}") + print(f" - Cache hits: {metrics['cache'].get('hits', 0)}") + + return { + 'strategy': strategy.value, + 'mode': mode.value, + 'standard_time': standard_time, + 'optimized_time': optimized_time, + 'improvement': improvement, + 'speed_multiplier': standard_time/optimized_time if optimized_time > 0 else 1 + } + + +async def main(): + """Run comprehensive comparison across different configurations.""" + + print("Swarm Optimization Performance Comparison") + print("========================================\n") + + # Test configurations + test_cases = [ + ("Analyze market trends for AI startups", StrategyType.RESEARCH, CoordinationMode.DISTRIBUTED), + ("Build a REST API for user management", StrategyType.DEVELOPMENT, CoordinationMode.HIERARCHICAL), + ("Analyze performance bottlenecks in the system", StrategyType.ANALYSIS, CoordinationMode.MESH), + ("Create test suite for authentication module", StrategyType.TESTING, CoordinationMode.DISTRIBUTED), + ("Optimize database query performance", StrategyType.OPTIMIZATION, CoordinationMode.HYBRID), + ] + + results = [] + + for objective, strategy, mode in test_cases: + try: + result = await run_comparison(objective, strategy, mode) + results.append(result) + + # Small delay between tests + await asyncio.sleep(1) + + except Exception as e: + print(f"Error in benchmark: {e}") + continue + + # Summary report + print(f"\n\n{'='*60}") + print("SUMMARY REPORT") + print(f"{'='*60}") + print(f"{'Strategy':<15} {'Mode':<15} {'Standard':<10} {'Optimized':<10} {'Improvement':<12} {'Speedup':<8}") + print(f"{'-'*80}") + + total_standard = 0 + total_optimized = 0 + + for result in results: + print(f"{result['strategy']:<15} {result['mode']:<15} " + f"{result['standard_time']:<10.2f} {result['optimized_time']:<10.2f} " + f"{result['improvement']:<12.1f}% {result['speed_multiplier']:<8.2f}x") + total_standard += result['standard_time'] + total_optimized += result['optimized_time'] + + print(f"{'-'*80}") + + # Overall statistics + if results: + avg_improvement = sum(r['improvement'] for r in results) / len(results) + avg_speedup = sum(r['speed_multiplier'] for r in results) / len(results) + overall_speedup = total_standard / total_optimized if total_optimized > 0 else 1 + + print(f"\nOverall Statistics:") + print(f" - Average improvement: {avg_improvement:.1f}%") + print(f" - Average speedup: {avg_speedup:.2f}x") + print(f" - Total time saved: {total_standard - total_optimized:.2f}s") + print(f" - Overall speedup: {overall_speedup:.2f}x") + + # Save detailed results + output_dir = Path("benchmark/optimization_results") + output_dir.mkdir(exist_ok=True) + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + output_file = output_dir / f"optimization_comparison_{timestamp}.json" + + with open(output_file, 'w') as f: + json.dump({ + 'timestamp': timestamp, + 'results': results, + 'summary': { + 'average_improvement': avg_improvement, + 'average_speedup': avg_speedup, + 'total_standard_time': total_standard, + 'total_optimized_time': total_optimized, + 'overall_speedup': overall_speedup + } + }, f, indent=2) + + print(f"\nDetailed results saved to: {output_file}") + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/benchmark/tools/performance_dashboard.py b/benchmark/tools/performance_dashboard.py new file mode 100644 index 0000000000..96d475ddc7 --- /dev/null +++ b/benchmark/tools/performance_dashboard.py @@ -0,0 +1,769 @@ +#!/usr/bin/env python3 +""" +Performance Dashboard Generator for Claude-Flow Swarm Operations + +This script generates interactive HTML dashboards for performance monitoring: +- Real-time performance metrics visualization +- Historical trend analysis and charts +- Performance regression tracking +- Interactive charts and graphs +- Automated report generation + +Author: Metrics Analyst Agent +Version: 1.0.0 +""" + +import json +import os +import sys +from datetime import datetime, timedelta +from pathlib import Path +from typing import Dict, List, Any, Optional +import statistics +from dataclasses import asdict + +# Add local modules to path +sys.path.insert(0, str(Path(__file__).parent)) + +try: + from continuous_performance_monitor import PerformanceMonitor, MetricSnapshot +except ImportError: + print("Warning: Could not import performance monitor - dashboard will use sample data") + + +class PerformanceDashboard: + """Generates interactive performance dashboards.""" + + def __init__(self, output_dir: str = "dashboard_output"): + self.output_dir = Path(output_dir) + self.output_dir.mkdir(exist_ok=True) + + def generate_dashboard(self, data_source: str = "database") -> str: + """Generate complete performance dashboard.""" + print("📊 Generating Performance Dashboard...") + + # Collect data + if data_source == "database": + dashboard_data = self._collect_database_data() + else: + dashboard_data = self._generate_sample_data() + + # Generate HTML dashboard + dashboard_file = self._generate_html_dashboard(dashboard_data) + + # Generate additional reports + self._generate_csv_export(dashboard_data) + self._generate_json_export(dashboard_data) + + print(f"✅ Dashboard generated: {dashboard_file}") + return str(dashboard_file) + + def _collect_database_data(self) -> Dict[str, Any]: + """Collect data from performance database.""" + try: + monitor = PerformanceMonitor() + + # Get dashboard data for different time periods + data = { + "last_24h": monitor.get_performance_dashboard_data(24), + "last_7d": monitor.get_performance_dashboard_data(168), + "last_30d": monitor.get_performance_dashboard_data(720), + "regression_report": monitor.generate_regression_report() + } + + return data + + except Exception as e: + print(f"Warning: Could not collect database data: {e}") + return self._generate_sample_data() + + def _generate_sample_data(self) -> Dict[str, Any]: + """Generate sample data for demonstration.""" + import random + + # Generate sample time series data + now = datetime.now() + time_series = [] + + for i in range(100): + timestamp = now - timedelta(hours=i) + time_series.append({ + "timestamp": timestamp.isoformat(), + "swarm_init_time": random.uniform(1.0, 8.0), + "agent_coordination_latency": random.uniform(50, 300), + "memory_usage_mb": random.uniform(20, 80), + "token_consumption_rate": random.uniform(80, 150), + "mcp_response_time": random.uniform(0.2, 2.0), + "neural_processing_time": random.uniform(100, 800), + "active_agents": random.randint(0, 8), + "cpu_usage_percent": random.uniform(10, 70) + }) + + return { + "last_24h": { + "summary": { + "total_samples": 100, + "time_range_hours": 24, + "last_update": now.isoformat() + }, + "swarm_performance": { + "avg_init_time": 3.2, + "max_init_time": 7.8, + "avg_coordination_latency": 180.5, + "max_coordination_latency": 295.2 + }, + "resource_usage": { + "avg_memory_mb": 45.3, + "peak_memory_mb": 78.9, + "memory_trend": "stable" + }, + "time_series": time_series, + "baselines": { + "swarm_init_time": 5.0, + "agent_coordination_latency": 200.0, + "memory_usage_mb": 50.0 + } + }, + "regression_report": { + "analysis_period": { + "recent_period_hours": 24, + "historical_period_hours": 168 + }, + "regression_analysis": { + "swarm_init_time": { + "recent_avg": 3.2, + "historical_avg": 3.5, + "regression_percent": -8.6, + "regression_detected": False + }, + "memory_usage": { + "recent_avg": 45.3, + "historical_avg": 42.1, + "regression_percent": 7.6, + "regression_detected": False + } + } + } + } + + def _generate_html_dashboard(self, data: Dict[str, Any]) -> Path: + """Generate HTML dashboard file.""" + dashboard_data = data.get("last_24h", {}) + regression_data = data.get("regression_report", {}) + + html_content = self._create_html_template(dashboard_data, regression_data) + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + dashboard_file = self.output_dir / f"performance_dashboard_{timestamp}.html" + + with open(dashboard_file, 'w') as f: + f.write(html_content) + + # Also create a 'latest' version + latest_file = self.output_dir / "performance_dashboard_latest.html" + with open(latest_file, 'w') as f: + f.write(html_content) + + return dashboard_file + + def _create_html_template(self, dashboard_data: Dict[str, Any], regression_data: Dict[str, Any]) -> str: + """Create HTML template with embedded data and charts.""" + + summary = dashboard_data.get("summary", {}) + swarm_perf = dashboard_data.get("swarm_performance", {}) + resource_usage = dashboard_data.get("resource_usage", {}) + time_series = dashboard_data.get("time_series", []) + baselines = dashboard_data.get("baselines", {}) + + # Create JavaScript data for charts + chart_data = { + "timeSeries": time_series[-50:], # Last 50 data points + "baselines": baselines, + "summary": summary, + "swarmPerf": swarm_perf, + "resourceUsage": resource_usage, + "regressionData": regression_data + } + + html_template = f""" + + +
+ + +Real-time monitoring and performance analytics
+No regression data available.
" + + analysis = regression_data["regression_analysis"] + html_parts = [] + + for metric_name, metric_data in analysis.items(): + regression_percent = metric_data.get("regression_percent", 0) + regression_detected = metric_data.get("regression_detected", False) + recent_avg = metric_data.get("recent_avg", 0) + historical_avg = metric_data.get("historical_avg", 0) + + # Determine status class + if regression_percent < -5: + status_class = "improvement" + icon = "🚀" + status_text = "Improvement" + elif regression_percent > 15: + status_class = "critical" + icon = "🚨" + status_text = "Critical Regression" + elif regression_percent > 5: + status_class = "warning" + icon = "⚠️" + status_text = "Warning" + else: + status_class = "" + icon = "✅" + status_text = "Stable" + + html_parts.append(f""" +Status: {status_text}
+Change: {regression_percent:+.1f}%
+Recent Average: {recent_avg:.2f}
+Historical Average: {historical_avg:.2f}
+