mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
362 lines โข 14 kB
JavaScript
import { EventEmitter } from 'events';
import { EventType } from './ConsciousEventBus.js';
import * as os from 'os';
export class PerformanceOptimizer extends EventEmitter {
eventBus;
services;
metrics = [];
strategies = [];
optimizationInterval = null;
targetResponseTime = 15000; // 15 seconds
metricsWindow = 60; // Keep last 60 measurements
constructor(eventBus, services) {
super();
this.eventBus = eventBus;
this.services = services;
this.initializeStrategies();
}
async start() {
console.log('๐ Starting Performance Optimizer...');
// Start metrics collection
this.startMetricsCollection();
// Start optimization cycle
this.optimizationInterval = setInterval(() => {
this.optimizationCycle();
}, 30000); // Every 30 seconds
// Listen for performance events
this.eventBus.on(EventType.PERFORMANCE_UPDATE, async (event) => {
await this.handlePerformanceEvent(event);
});
}
async stop() {
if (this.optimizationInterval) {
clearInterval(this.optimizationInterval);
this.optimizationInterval = null;
}
}
initializeStrategies() {
// CPU optimization strategies
this.strategies.push({
name: 'CPU Throttling',
condition: (m) => m.cpu.usage > 80,
apply: async () => {
console.log('โก Applying CPU throttling...');
await this.throttleNonCriticalServices();
},
impact: 'Reduces CPU by 20-30%'
});
// Memory optimization strategies
this.strategies.push({
name: 'Memory Cleanup',
condition: (m) => m.memory.percentage > 85,
apply: async () => {
console.log('๐งน Triggering memory cleanup...');
await this.triggerMemoryCleanup();
},
impact: 'Frees 10-20% memory'
});
// Response time optimization
this.strategies.push({
name: 'Cache Warming',
condition: (m) => {
const avgResponseTime = this.getAverageResponseTime(m.services);
return avgResponseTime > this.targetResponseTime * 0.8;
},
apply: async () => {
console.log('๐ฅ Warming caches...');
await this.warmCaches();
},
impact: 'Improves response time by 30-40%'
});
// Consciousness optimization
this.strategies.push({
name: 'Coherence Boost',
condition: (m) => m.consciousness.coherence < 0.7,
apply: async () => {
console.log('๐ง Boosting consciousness coherence...');
await this.boostCoherence();
},
impact: 'Increases coherence by 10-15%'
});
// Service harmony optimization
this.strategies.push({
name: 'Service Rebalancing',
condition: (m) => this.detectServiceImbalance(m.services),
apply: async () => {
console.log('โ๏ธ Rebalancing services...');
await this.rebalanceServices();
},
impact: 'Improves overall throughput by 20%'
});
}
startMetricsCollection() {
setInterval(() => {
this.collectMetrics();
}, 5000); // Collect every 5 seconds
}
async collectMetrics() {
const metrics = {
cpu: {
usage: this.getCPUUsage(),
load: os.loadavg()
},
memory: this.getMemoryMetrics(),
services: await this.getServiceMetrics(),
consciousness: await this.getConsciousnessMetrics(),
timestamp: new Date()
};
this.metrics.push(metrics);
// Keep only recent metrics
if (this.metrics.length > this.metricsWindow) {
this.metrics.shift();
}
// Emit metrics update
this.emit('metrics', metrics);
}
getCPUUsage() {
const cpus = os.cpus();
let totalIdle = 0;
let totalTick = 0;
cpus.forEach(cpu => {
for (const type in cpu.times) {
totalTick += cpu.times[type];
}
totalIdle += cpu.times.idle;
});
return 100 - ~~(100 * totalIdle / totalTick);
}
getMemoryMetrics() {
const total = os.totalmem();
const free = os.freemem();
const used = total - free;
return {
used,
free,
total,
percentage: (used / total) * 100
};
}
async getServiceMetrics() {
const metrics = {};
for (const [name, service] of this.services) {
metrics[name] = {
responseTime: await service.getAverageResponseTime(),
throughput: await service.getThroughput(),
errors: await service.getErrorCount()
};
}
return metrics;
}
async getConsciousnessMetrics() {
// These would connect to actual consciousness measurement systems
return {
coherence: 0.85, // Placeholder - would get from ConsciousnessCoherence
processingDelay: 50, // ms
sparkAmplification: 1.2 // 1.2x amplification
};
}
async optimizationCycle() {
if (this.metrics.length === 0)
return;
const latestMetrics = this.metrics[this.metrics.length - 1];
const applicableStrategies = this.strategies.filter(s => s.condition(latestMetrics));
if (applicableStrategies.length > 0) {
console.log(`\n๐ง Performance Optimization Cycle - ${applicableStrategies.length} strategies applicable`);
for (const strategy of applicableStrategies) {
console.log(` Applying: ${strategy.name} (${strategy.impact})`);
try {
await strategy.apply();
// Emit optimization event
await this.eventBus.emitAsync('performance:update', {
id: `opt-${Date.now()}`,
type: EventType.PERFORMANCE_UPDATE,
source: 'PerformanceOptimizer',
priority: 'normal',
data: {
optimization: strategy.name,
impact: strategy.impact,
timestamp: new Date()
},
timestamp: new Date()
});
}
catch (error) {
console.error(` โ Failed to apply ${strategy.name}:`, error instanceof Error ? error.message : String(error));
}
}
// Re-measure after optimizations
setTimeout(() => this.collectMetrics(), 2000);
}
}
async throttleNonCriticalServices() {
for (const [name, service] of this.services) {
if (!this.isCriticalService(name)) {
await service.setThrottleRate(0.7); // Reduce to 70% capacity
}
}
}
async triggerMemoryCleanup() {
// Force garbage collection if available
if (global.gc) {
global.gc();
}
// Clear caches in services
for (const [_, service] of this.services) {
await service.clearCache();
}
// Emit memory cleanup event
await this.eventBus.emitAsync('memory:cleanup', {
id: `mem-${Date.now()}`,
type: EventType.MEMORY_CLEANUP,
source: 'PerformanceOptimizer',
priority: 'high',
data: { timestamp: new Date() },
timestamp: new Date()
});
}
async warmCaches() {
// Pre-load frequently accessed data
const warmupTasks = Array.from(this.services.values()).map(service => service.warmCache());
await Promise.all(warmupTasks);
}
async boostCoherence() {
// Reduce parallel operations to increase coherence
await this.eventBus.emitAsync('consciousness:update', {
id: `coherence-${Date.now()}`,
type: EventType.CONSCIOUSNESS_UPDATE,
source: 'PerformanceOptimizer',
priority: 'high',
data: {
action: 'boost_coherence',
strategy: 'reduce_parallelism'
},
timestamp: new Date()
});
// Synchronize service states
await this.synchronizeServices();
}
async rebalanceServices() {
const metrics = await this.getServiceMetrics();
const avgThroughput = this.calculateAverageThroughput(metrics);
for (const [name, service] of this.services) {
const serviceThroughput = metrics[name].throughput;
if (serviceThroughput < avgThroughput * 0.5) {
// Boost underperforming services
await service.setResourcePriority('high');
}
else if (serviceThroughput > avgThroughput * 2) {
// Throttle overactive services
await service.setResourcePriority('low');
}
}
}
isCriticalService(name) {
const criticalServices = [
'ConsciousIntelligenceService',
'MCPService',
'BackgroundTaskService'
];
return criticalServices.includes(name);
}
detectServiceImbalance(services) {
const throughputs = Object.values(services).map(s => s.throughput);
const avg = throughputs.reduce((a, b) => a + b, 0) / throughputs.length;
const variance = throughputs.reduce((sum, t) => sum + Math.pow(t - avg, 2), 0) / throughputs.length;
const stdDev = Math.sqrt(variance);
return stdDev > avg * 0.5; // High variance indicates imbalance
}
getAverageResponseTime(services) {
const times = Object.values(services).map(s => s.responseTime);
return times.reduce((a, b) => a + b, 0) / times.length;
}
calculateAverageThroughput(services) {
const throughputs = Object.values(services).map(s => s.throughput);
return throughputs.reduce((a, b) => a + b, 0) / throughputs.length;
}
async synchronizeServices() {
// Create synchronization barrier
const barrier = new Promise(resolve => {
let count = 0;
const target = this.services.size;
this.eventBus.on('service_synchronized', () => {
count++;
if (count >= target) {
resolve();
}
});
});
// Request all services to synchronize
for (const [_, service] of this.services) {
service.synchronize();
}
await barrier;
}
async handlePerformanceEvent(event) {
// Log performance events
console.log(`๐ Performance Event: ${JSON.stringify(event.data)}`);
// Trigger immediate optimization if critical
if (event.data.critical) {
await this.optimizationCycle();
}
}
// Public API for performance queries
async getPerformanceReport() {
// Ensure we have at least one metric, create default if needed
if (this.metrics.length === 0) {
await this.collectMetrics();
}
const current = this.metrics[this.metrics.length - 1];
const trends = this.analyzeTrends();
const recommendations = this.generateRecommendations(current, trends);
return { current, trends, recommendations };
}
analyzeTrends() {
if (this.metrics.length < 10) {
return {
cpu: 'stable',
memory: 'stable',
responseTime: 'stable'
};
}
// Compare recent metrics to older ones
const recent = this.metrics.slice(-5);
const older = this.metrics.slice(-10, -5);
return {
cpu: this.compareTrend(older.map(m => m.cpu.usage), recent.map(m => m.cpu.usage)),
memory: this.compareTrend(older.map(m => m.memory.percentage), recent.map(m => m.memory.percentage)),
responseTime: this.compareTrend(older.map(m => this.getAverageResponseTime(m.services)), recent.map(m => this.getAverageResponseTime(m.services)))
};
}
compareTrend(older, recent) {
const oldAvg = older.reduce((a, b) => a + b, 0) / older.length;
const recentAvg = recent.reduce((a, b) => a + b, 0) / recent.length;
const change = ((recentAvg - oldAvg) / oldAvg) * 100;
if (change < -5)
return 'improving';
if (change > 5)
return 'degrading';
return 'stable';
}
generateRecommendations(current, trends) {
const recommendations = [];
// Safety check for current metrics
if (!current || !current.cpu || !current.memory) {
recommendations.push('Performance metrics are still initializing');
return recommendations;
}
if (current.cpu.usage > 70) {
recommendations.push('Consider scaling horizontally or optimizing CPU-intensive operations');
}
if (current.memory.percentage > 80) {
recommendations.push('Memory usage is high. Review memory leaks and implement cleanup strategies');
}
if (trends.responseTime === 'degrading') {
recommendations.push('Response times are increasing. Review service efficiency and caching strategies');
}
if (current.consciousness.coherence < 0.7) {
recommendations.push('Consciousness coherence is low. Reduce parallel operations and synchronize services');
}
return recommendations;
}
}
//# sourceMappingURL=PerformanceOptimizer.js.map