mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-23 21:59:14 +09:00
🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/tests/conftest.py
This commit is contained in:
1 parent
baf3513193
commit
ffd4fd4f4a
11 files changed
+2157
-1
No files matched your search
@@ -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"}
|
||||
@@ -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(-) "}
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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": {}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
@@ -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"""
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Claude-Flow Swarm Performance Dashboard</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
||||
<style>
|
||||
body {{
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
background-color: #f5f5f5;
|
||||
}}
|
||||
.container {{
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
overflow: hidden;
|
||||
}}
|
||||
.header {{
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 30px;
|
||||
text-align: center;
|
||||
}}
|
||||
.header h1 {{
|
||||
margin: 0;
|
||||
font-size: 2.5em;
|
||||
font-weight: 300;
|
||||
}}
|
||||
.header p {{
|
||||
margin: 10px 0 0;
|
||||
opacity: 0.9;
|
||||
font-size: 1.1em;
|
||||
}}
|
||||
.metrics-grid {{
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
padding: 30px;
|
||||
}}
|
||||
.metric-card {{
|
||||
background: white;
|
||||
border: 1px solid #e1e5e9;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
transition: transform 0.2s;
|
||||
}}
|
||||
.metric-card:hover {{
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
|
||||
}}
|
||||
.metric-value {{
|
||||
font-size: 2.5em;
|
||||
font-weight: bold;
|
||||
margin-bottom: 5px;
|
||||
}}
|
||||
.metric-label {{
|
||||
color: #666;
|
||||
font-size: 0.9em;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
}}
|
||||
.metric-target {{
|
||||
font-size: 0.8em;
|
||||
color: #999;
|
||||
margin-top: 5px;
|
||||
}}
|
||||
.status-good {{ color: #28a745; }}
|
||||
.status-warning {{ color: #ffc107; }}
|
||||
.status-critical {{ color: #dc3545; }}
|
||||
.charts-section {{
|
||||
padding: 30px;
|
||||
background: #fafafa;
|
||||
}}
|
||||
.chart-container {{
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
margin-bottom: 30px;
|
||||
border: 1px solid #e1e5e9;
|
||||
}}
|
||||
.chart-title {{
|
||||
font-size: 1.3em;
|
||||
font-weight: 600;
|
||||
margin-bottom: 20px;
|
||||
color: #333;
|
||||
}}
|
||||
.chart-canvas {{
|
||||
max-height: 400px;
|
||||
}}
|
||||
.regression-section {{
|
||||
padding: 30px;
|
||||
background: #f8f9fa;
|
||||
border-top: 1px solid #e1e5e9;
|
||||
}}
|
||||
.regression-item {{
|
||||
background: white;
|
||||
border-radius: 6px;
|
||||
padding: 15px;
|
||||
margin-bottom: 15px;
|
||||
border-left: 4px solid #007bff;
|
||||
}}
|
||||
.regression-item.warning {{ border-left-color: #ffc107; }}
|
||||
.regression-item.critical {{ border-left-color: #dc3545; }}
|
||||
.regression-item.improvement {{ border-left-color: #28a745; }}
|
||||
.footer {{
|
||||
background: #333;
|
||||
color: white;
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
font-size: 0.9em;
|
||||
}}
|
||||
.refresh-info {{
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
background: rgba(0,0,0,0.8);
|
||||
color: white;
|
||||
padding: 10px 15px;
|
||||
border-radius: 5px;
|
||||
font-size: 0.8em;
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="refresh-info">
|
||||
Last updated: {summary.get("last_update", datetime.now().isoformat())[:19]}
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>🚀 Claude-Flow Swarm Performance Dashboard</h1>
|
||||
<p>Real-time monitoring and performance analytics</p>
|
||||
</div>
|
||||
|
||||
<div class="metrics-grid">
|
||||
<div class="metric-card">
|
||||
<div class="metric-value status-{self._get_status(swarm_perf.get("avg_init_time", 0), baselines.get("swarm_init_time", 5.0))}">
|
||||
{swarm_perf.get("avg_init_time", 0):.2f}s
|
||||
</div>
|
||||
<div class="metric-label">Avg Swarm Init Time</div>
|
||||
<div class="metric-target">Target: < {baselines.get("swarm_init_time", 5.0)}s</div>
|
||||
</div>
|
||||
|
||||
<div class="metric-card">
|
||||
<div class="metric-value status-{self._get_status(swarm_perf.get("avg_coordination_latency", 0), baselines.get("agent_coordination_latency", 200.0))}">
|
||||
{swarm_perf.get("avg_coordination_latency", 0):.1f}ms
|
||||
</div>
|
||||
<div class="metric-label">Avg Coordination Latency</div>
|
||||
<div class="metric-target">Target: < {baselines.get("agent_coordination_latency", 200.0)}ms</div>
|
||||
</div>
|
||||
|
||||
<div class="metric-card">
|
||||
<div class="metric-value status-{self._get_status(resource_usage.get("avg_memory_mb", 0), baselines.get("memory_usage_mb", 50.0))}">
|
||||
{resource_usage.get("avg_memory_mb", 0):.1f}MB
|
||||
</div>
|
||||
<div class="metric-label">Avg Memory Usage</div>
|
||||
<div class="metric-target">Target: < {baselines.get("memory_usage_mb", 50.0)}MB</div>
|
||||
</div>
|
||||
|
||||
<div class="metric-card">
|
||||
<div class="metric-value status-good">
|
||||
{resource_usage.get("peak_memory_mb", 0):.1f}MB
|
||||
</div>
|
||||
<div class="metric-label">Peak Memory Usage</div>
|
||||
<div class="metric-target">Trend: {resource_usage.get("memory_trend", "unknown")}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="charts-section">
|
||||
<div class="chart-container">
|
||||
<div class="chart-title">📈 Performance Trends (Last 24 Hours)</div>
|
||||
<canvas id="performanceTrendChart" class="chart-canvas"></canvas>
|
||||
</div>
|
||||
|
||||
<div class="chart-container">
|
||||
<div class="chart-title">💾 Memory Usage Over Time</div>
|
||||
<canvas id="memoryUsageChart" class="chart-canvas"></canvas>
|
||||
</div>
|
||||
|
||||
<div class="chart-container">
|
||||
<div class="chart-title">🕒 Response Time Distribution</div>
|
||||
<canvas id="responseTimeChart" class="chart-canvas"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="regression-section">
|
||||
<h2>🔍 Performance Regression Analysis</h2>
|
||||
{self._generate_regression_html(regression_data)}
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
Generated by Claude-Flow Metrics Analyst Agent |
|
||||
Version 1.0.0 |
|
||||
{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Dashboard data
|
||||
const dashboardData = {json.dumps(chart_data, indent=2, default=str)};
|
||||
|
||||
// Initialize charts when page loads
|
||||
document.addEventListener('DOMContentLoaded', function() {{
|
||||
initializeCharts();
|
||||
}});
|
||||
|
||||
function initializeCharts() {{
|
||||
createPerformanceTrendChart();
|
||||
createMemoryUsageChart();
|
||||
createResponseTimeChart();
|
||||
}}
|
||||
|
||||
function createPerformanceTrendChart() {{
|
||||
const ctx = document.getElementById('performanceTrendChart').getContext('2d');
|
||||
const timeSeries = dashboardData.timeSeries;
|
||||
|
||||
new Chart(ctx, {{
|
||||
type: 'line',
|
||||
data: {{
|
||||
labels: timeSeries.map(d => new Date(d.timestamp).toLocaleTimeString()),
|
||||
datasets: [{{
|
||||
label: 'Swarm Init Time (s)',
|
||||
data: timeSeries.map(d => d.swarm_init_time),
|
||||
borderColor: 'rgb(75, 192, 192)',
|
||||
backgroundColor: 'rgba(75, 192, 192, 0.1)',
|
||||
tension: 0.1
|
||||
}}, {{
|
||||
label: 'Coordination Latency (ms)',
|
||||
data: timeSeries.map(d => d.agent_coordination_latency),
|
||||
borderColor: 'rgb(255, 99, 132)',
|
||||
backgroundColor: 'rgba(255, 99, 132, 0.1)',
|
||||
yAxisID: 'y1',
|
||||
tension: 0.1
|
||||
}}]
|
||||
}},
|
||||
options: {{
|
||||
responsive: true,
|
||||
interaction: {{
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
}},
|
||||
scales: {{
|
||||
x: {{
|
||||
display: true,
|
||||
title: {{
|
||||
display: true,
|
||||
text: 'Time'
|
||||
}}
|
||||
}},
|
||||
y: {{
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'left',
|
||||
title: {{
|
||||
display: true,
|
||||
text: 'Init Time (seconds)'
|
||||
}}
|
||||
}},
|
||||
y1: {{
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'right',
|
||||
title: {{
|
||||
display: true,
|
||||
text: 'Latency (ms)'
|
||||
}},
|
||||
grid: {{
|
||||
drawOnChartArea: false,
|
||||
}},
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}});
|
||||
}}
|
||||
|
||||
function createMemoryUsageChart() {{
|
||||
const ctx = document.getElementById('memoryUsageChart').getContext('2d');
|
||||
const timeSeries = dashboardData.timeSeries;
|
||||
|
||||
new Chart(ctx, {{
|
||||
type: 'area',
|
||||
data: {{
|
||||
labels: timeSeries.map(d => new Date(d.timestamp).toLocaleTimeString()),
|
||||
datasets: [{{
|
||||
label: 'Memory Usage (MB)',
|
||||
data: timeSeries.map(d => d.memory_usage_mb),
|
||||
borderColor: 'rgb(153, 102, 255)',
|
||||
backgroundColor: 'rgba(153, 102, 255, 0.2)',
|
||||
fill: true,
|
||||
tension: 0.1
|
||||
}}]
|
||||
}},
|
||||
options: {{
|
||||
responsive: true,
|
||||
plugins: {{
|
||||
title: {{
|
||||
display: true,
|
||||
text: 'Memory Usage Trend'
|
||||
}}
|
||||
}},
|
||||
scales: {{
|
||||
y: {{
|
||||
beginAtZero: true,
|
||||
title: {{
|
||||
display: true,
|
||||
text: 'Memory (MB)'
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}});
|
||||
}}
|
||||
|
||||
function createResponseTimeChart() {{
|
||||
const ctx = document.getElementById('responseTimeChart').getContext('2d');
|
||||
const timeSeries = dashboardData.timeSeries;
|
||||
|
||||
// Create histogram data
|
||||
const responseTimeBins = [0, 0.5, 1.0, 1.5, 2.0, 2.5];
|
||||
const binCounts = new Array(responseTimeBins.length - 1).fill(0);
|
||||
|
||||
timeSeries.forEach(d => {{
|
||||
const responseTime = d.mcp_response_time;
|
||||
for (let i = 0; i < responseTimeBins.length - 1; i++) {{
|
||||
if (responseTime >= responseTimeBins[i] && responseTime < responseTimeBins[i + 1]) {{
|
||||
binCounts[i]++;
|
||||
break;
|
||||
}}
|
||||
}}
|
||||
}});
|
||||
|
||||
new Chart(ctx, {{
|
||||
type: 'bar',
|
||||
data: {{
|
||||
labels: responseTimeBins.slice(0, -1).map((bin, i) =>
|
||||
`${{bin}}-${{responseTimeBins[i + 1]}}s`),
|
||||
datasets: [{{
|
||||
label: 'Response Time Distribution',
|
||||
data: binCounts,
|
||||
backgroundColor: 'rgba(54, 162, 235, 0.5)',
|
||||
borderColor: 'rgba(54, 162, 235, 1)',
|
||||
borderWidth: 1
|
||||
}}]
|
||||
}},
|
||||
options: {{
|
||||
responsive: true,
|
||||
plugins: {{
|
||||
title: {{
|
||||
display: true,
|
||||
text: 'MCP Response Time Distribution'
|
||||
}}
|
||||
}},
|
||||
scales: {{
|
||||
y: {{
|
||||
beginAtZero: true,
|
||||
title: {{
|
||||
display: true,
|
||||
text: 'Frequency'
|
||||
}}
|
||||
}},
|
||||
x: {{
|
||||
title: {{
|
||||
display: true,
|
||||
text: 'Response Time Range'
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}});
|
||||
}}
|
||||
</script>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
return html_template
|
||||
|
||||
def _get_status(self, value: float, target: float) -> str:
|
||||
"""Get status class based on value vs target."""
|
||||
if value <= target:
|
||||
return "good"
|
||||
elif value <= target * 1.2:
|
||||
return "warning"
|
||||
else:
|
||||
return "critical"
|
||||
|
||||
def _generate_regression_html(self, regression_data: Dict[str, Any]) -> str:
|
||||
"""Generate HTML for regression analysis section."""
|
||||
if not regression_data or "regression_analysis" not in regression_data:
|
||||
return "<p>No regression data available.</p>"
|
||||
|
||||
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"""
|
||||
<div class="regression-item {status_class}">
|
||||
<h4>{icon} {metric_name.replace('_', ' ').title()}</h4>
|
||||
<p><strong>Status:</strong> {status_text}</p>
|
||||
<p><strong>Change:</strong> {regression_percent:+.1f}%</p>
|
||||
<p><strong>Recent Average:</strong> {recent_avg:.2f}</p>
|
||||
<p><strong>Historical Average:</strong> {historical_avg:.2f}</p>
|
||||
</div>
|
||||
""")
|
||||
|
||||
return "".join(html_parts)
|
||||
|
||||
def _generate_csv_export(self, data: Dict[str, Any]):
|
||||
"""Generate CSV export of performance data."""
|
||||
dashboard_data = data.get("last_24h", {})
|
||||
time_series = dashboard_data.get("time_series", [])
|
||||
|
||||
if not time_series:
|
||||
return
|
||||
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
csv_file = self.output_dir / f"performance_data_{timestamp}.csv"
|
||||
|
||||
# Write CSV header and data
|
||||
with open(csv_file, 'w') as f:
|
||||
if time_series:
|
||||
# Write header
|
||||
headers = list(time_series[0].keys())
|
||||
f.write(",".join(headers) + "\n")
|
||||
|
||||
# Write data rows
|
||||
for row in time_series:
|
||||
values = [str(row.get(h, "")) for h in headers]
|
||||
f.write(",".join(values) + "\n")
|
||||
|
||||
print(f"📄 CSV export saved: {csv_file}")
|
||||
|
||||
def _generate_json_export(self, data: Dict[str, Any]):
|
||||
"""Generate JSON export of all dashboard data."""
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
json_file = self.output_dir / f"dashboard_data_{timestamp}.json"
|
||||
|
||||
with open(json_file, 'w') as f:
|
||||
json.dump(data, f, indent=2, default=str)
|
||||
|
||||
print(f"📋 JSON export saved: {json_file}")
|
||||
|
||||
|
||||
def create_dashboard_server():
|
||||
"""Create a simple HTTP server for the dashboard."""
|
||||
server_script = """#!/usr/bin/env python3
|
||||
import http.server
|
||||
import socketserver
|
||||
import webbrowser
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
PORT = 8000
|
||||
dashboard_dir = Path(__file__).parent / "dashboard_output"
|
||||
|
||||
class DashboardHandler(http.server.SimpleHTTPRequestHandler):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, directory=str(dashboard_dir), **kwargs)
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.chdir(dashboard_dir)
|
||||
|
||||
with socketserver.TCPServer(("", PORT), DashboardHandler) as httpd:
|
||||
print(f"🌐 Performance Dashboard Server started at http://localhost:{PORT}")
|
||||
print("📊 Available dashboards:")
|
||||
|
||||
for file in dashboard_dir.glob("*.html"):
|
||||
print(f" http://localhost:{PORT}/{file.name}")
|
||||
|
||||
try:
|
||||
# Try to open in browser
|
||||
webbrowser.open(f"http://localhost:{PORT}/performance_dashboard_latest.html")
|
||||
except:
|
||||
pass
|
||||
|
||||
print("\\nPress Ctrl+C to stop the server")
|
||||
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
print("\\n🛑 Dashboard server stopped")
|
||||
"""
|
||||
|
||||
server_file = Path("dashboard_server.py")
|
||||
with open(server_file, 'w') as f:
|
||||
f.write(server_script)
|
||||
|
||||
# Make executable
|
||||
os.chmod(server_file, 0o755)
|
||||
|
||||
print(f"✅ Dashboard server created: {server_file}")
|
||||
print(f" Run with: python {server_file}")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point for dashboard generation."""
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="Performance Dashboard Generator")
|
||||
parser.add_argument("--output-dir", default="dashboard_output", help="Output directory")
|
||||
parser.add_argument("--data-source", choices=["database", "sample"], default="database", help="Data source")
|
||||
parser.add_argument("--create-server", action="store_true", help="Create dashboard server script")
|
||||
parser.add_argument("--serve", action="store_true", help="Generate dashboard and start server")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.create_server:
|
||||
create_dashboard_server()
|
||||
return
|
||||
|
||||
# Generate dashboard
|
||||
dashboard = PerformanceDashboard(args.output_dir)
|
||||
dashboard_file = dashboard.generate_dashboard(args.data_source)
|
||||
|
||||
if args.serve:
|
||||
import subprocess
|
||||
import webbrowser
|
||||
import time
|
||||
|
||||
# Create server if it doesn't exist
|
||||
if not Path("dashboard_server.py").exists():
|
||||
create_dashboard_server()
|
||||
|
||||
print("🌐 Starting dashboard server...")
|
||||
|
||||
try:
|
||||
# Start server in background
|
||||
server_process = subprocess.Popen(
|
||||
["python", "dashboard_server.py"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE
|
||||
)
|
||||
|
||||
# Give server time to start
|
||||
time.sleep(2)
|
||||
|
||||
# Open in browser
|
||||
webbrowser.open("http://localhost:8000/performance_dashboard_latest.html")
|
||||
|
||||
print("Dashboard is now running at http://localhost:8000")
|
||||
print("Press Ctrl+C to stop...")
|
||||
|
||||
# Wait for user to stop
|
||||
server_process.wait()
|
||||
|
||||
except KeyboardInterrupt:
|
||||
if 'server_process' in locals():
|
||||
server_process.terminate()
|
||||
print("\n🛑 Dashboard server stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user