Spaces:
Paused
Paused
Download shared/performance_init.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 21.2 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/performance_init.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/performance_init.py
-
curl -L -o performance_init.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/performance_init.py
21.2 kB
| """ | |
| Performance optimization initialization for MCP AI Data Scientist. | |
| Initializes and configures all performance optimization systems. | |
| """ | |
| import asyncio | |
| import logging | |
| from typing import Dict, Any, Optional | |
| from .caching import cache_manager | |
| from .connection_pool import resource_manager | |
| from .memory_manager import memory_manager | |
| from .query_optimizer import supabase_optimizer | |
| from .parallel_processor import parallel_processor | |
| from .performance_monitor import performance_monitor | |
| from .performance_config import ( | |
| get_optimized_settings_for_environment, | |
| apply_performance_optimizations, | |
| get_config_for_environment | |
| ) | |
| logger = logging.getLogger(__name__) | |
| class PerformanceOptimizationManager: | |
| """Manages initialization and coordination of all performance optimization systems.""" | |
| def __init__(self): | |
| self._initialized = False | |
| self._systems_started = False | |
| self._optimization_settings: Optional[Dict[str, Any]] = None | |
| self._performance_callbacks = [] | |
| async def initialize(self, environment: str = None) -> Dict[str, Any]: | |
| """Initialize all performance optimization systems.""" | |
| if self._initialized: | |
| logger.info("Performance optimization already initialized") | |
| return self._optimization_settings | |
| logger.info("Initializing performance optimization systems...") | |
| try: | |
| # Get optimized settings for current environment | |
| self._optimization_settings = get_optimized_settings_for_environment() | |
| env_config = get_config_for_environment(environment) | |
| # Apply environment-specific overrides | |
| self._apply_environment_config(env_config) | |
| # Configure individual systems | |
| await self._configure_cache_system() | |
| await self._configure_connection_pools() | |
| await self._configure_memory_management() | |
| await self._configure_query_optimization() | |
| await self._configure_parallel_processing() | |
| await self._configure_performance_monitoring() | |
| self._initialized = True | |
| logger.info("Performance optimization systems initialized successfully") | |
| return { | |
| 'status': 'initialized', | |
| 'settings': self._optimization_settings, | |
| 'environment_config': env_config | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to initialize performance optimization: {e}") | |
| raise | |
| async def start_all_systems(self) -> Dict[str, Any]: | |
| """Start all performance optimization systems.""" | |
| if not self._initialized: | |
| await self.initialize() | |
| if self._systems_started: | |
| logger.info("Performance optimization systems already started") | |
| return {'status': 'already_started'} | |
| logger.info("Starting performance optimization systems...") | |
| startup_results = {} | |
| try: | |
| # Start systems in order of dependency | |
| # 1. Start cache manager | |
| logger.info("Starting cache manager...") | |
| await cache_manager.start() | |
| startup_results['cache_manager'] = 'started' | |
| # 2. Start resource manager (connection pools) | |
| logger.info("Starting resource manager...") | |
| await resource_manager.start() | |
| startup_results['resource_manager'] = 'started' | |
| # 3. Start memory manager | |
| logger.info("Starting memory manager...") | |
| await memory_manager.start() | |
| startup_results['memory_manager'] = 'started' | |
| # 4. Start parallel processor | |
| logger.info("Starting parallel processor...") | |
| await parallel_processor.start() | |
| startup_results['parallel_processor'] = 'started' | |
| # 5. Start performance monitor (last, as it monitors other systems) | |
| logger.info("Starting performance monitor...") | |
| await performance_monitor.start() | |
| startup_results['performance_monitor'] = 'started' | |
| # Set up performance callbacks | |
| self._setup_performance_callbacks() | |
| self._systems_started = True | |
| logger.info("All performance optimization systems started successfully") | |
| return { | |
| 'status': 'started', | |
| 'systems': startup_results, | |
| 'timestamp': asyncio.get_event_loop().time() | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to start performance optimization systems: {e}") | |
| # Attempt to stop any systems that were started | |
| await self.stop_all_systems() | |
| raise | |
| async def stop_all_systems(self) -> Dict[str, Any]: | |
| """Stop all performance optimization systems.""" | |
| if not self._systems_started: | |
| logger.info("Performance optimization systems not started") | |
| return {'status': 'not_started'} | |
| logger.info("Stopping performance optimization systems...") | |
| shutdown_results = {} | |
| try: | |
| # Stop systems in reverse order | |
| # 1. Stop performance monitor | |
| try: | |
| await performance_monitor.stop() | |
| shutdown_results['performance_monitor'] = 'stopped' | |
| except Exception as e: | |
| logger.error(f"Error stopping performance monitor: {e}") | |
| shutdown_results['performance_monitor'] = f'error: {e}' | |
| # 2. Stop parallel processor | |
| try: | |
| await parallel_processor.stop() | |
| shutdown_results['parallel_processor'] = 'stopped' | |
| except Exception as e: | |
| logger.error(f"Error stopping parallel processor: {e}") | |
| shutdown_results['parallel_processor'] = f'error: {e}' | |
| # 3. Stop memory manager | |
| try: | |
| await memory_manager.stop() | |
| shutdown_results['memory_manager'] = 'stopped' | |
| except Exception as e: | |
| logger.error(f"Error stopping memory manager: {e}") | |
| shutdown_results['memory_manager'] = f'error: {e}' | |
| # 4. Stop resource manager | |
| try: | |
| await resource_manager.stop() | |
| shutdown_results['resource_manager'] = 'stopped' | |
| except Exception as e: | |
| logger.error(f"Error stopping resource manager: {e}") | |
| shutdown_results['resource_manager'] = f'error: {e}' | |
| # 5. Stop cache manager | |
| try: | |
| await cache_manager.stop() | |
| shutdown_results['cache_manager'] = 'stopped' | |
| except Exception as e: | |
| logger.error(f"Error stopping cache manager: {e}") | |
| shutdown_results['cache_manager'] = f'error: {e}' | |
| self._systems_started = False | |
| logger.info("Performance optimization systems stopped") | |
| return { | |
| 'status': 'stopped', | |
| 'systems': shutdown_results | |
| } | |
| except Exception as e: | |
| logger.error(f"Error during shutdown: {e}") | |
| return { | |
| 'status': 'error', | |
| 'error': str(e), | |
| 'systems': shutdown_results | |
| } | |
| def _apply_environment_config(self, env_config: Dict[str, Any]): | |
| """Apply environment-specific configuration overrides.""" | |
| if not env_config: | |
| return | |
| # Update cache settings | |
| if 'cache_max_size' in env_config: | |
| self._optimization_settings['cache'].max_size = env_config['cache_max_size'] | |
| # Update connection settings | |
| if 'supabase_max_connections' in env_config: | |
| self._optimization_settings['connections'].supabase_max_connections = env_config['supabase_max_connections'] | |
| # Update memory settings | |
| if 'memory_cleanup_threshold' in env_config: | |
| self._optimization_settings['memory'].cleanup_threshold = env_config['memory_cleanup_threshold'] | |
| logger.info(f"Applied environment configuration overrides: {list(env_config.keys())}") | |
| async def _configure_cache_system(self): | |
| """Configure cache system with optimized settings.""" | |
| cache_config = self._optimization_settings['cache'] | |
| # Configure cache manager settings | |
| cache_manager.general_cache.max_size = cache_config.max_size | |
| cache_manager.general_cache.default_ttl = cache_config.default_ttl | |
| cache_manager.dataset_cache.max_datasets = cache_config.dataset_max_count | |
| cache_manager.dataset_cache.max_size_bytes = cache_config.dataset_max_size_mb * 1024 * 1024 | |
| cache_manager.query_cache.cache.max_size = cache_config.query_max_entries | |
| cache_manager.query_cache.cache.default_ttl = cache_config.query_default_ttl | |
| cache_manager.model_cache.max_size = cache_config.model_max_count | |
| cache_manager.model_cache.default_ttl = cache_config.model_default_ttl | |
| logger.info(f"Configured cache system: max_size={cache_config.max_size}, dataset_max_size={cache_config.dataset_max_size_mb}MB") | |
| async def _configure_connection_pools(self): | |
| """Configure connection pools with optimized settings.""" | |
| conn_config = self._optimization_settings['connections'] | |
| # Connection pool settings will be applied when pools are created | |
| # This is handled in the resource manager initialization | |
| logger.info(f"Configured connection pools: supabase_max={conn_config.supabase_max_connections}, mcp_max={conn_config.mcp_max_connections}") | |
| async def _configure_memory_management(self): | |
| """Configure memory management with optimized settings.""" | |
| memory_config = self._optimization_settings['memory'] | |
| # Configure memory manager settings | |
| memory_manager._cleanup_threshold = memory_config.cleanup_threshold | |
| memory_manager.chunk_processor.chunk_size = memory_config.default_chunk_size | |
| memory_manager.chunk_processor.max_memory_mb = memory_config.max_memory_mb | |
| memory_manager.data_loader.memory_limit_mb = memory_config.loader_memory_limit_mb | |
| # Configure memory monitor thresholds | |
| memory_manager.monitor._thresholds['medium'] = memory_config.medium_pressure_threshold | |
| memory_manager.monitor._thresholds['high'] = memory_config.high_pressure_threshold | |
| memory_manager.monitor._thresholds['critical'] = memory_config.critical_pressure_threshold | |
| logger.info(f"Configured memory management: chunk_size={memory_config.default_chunk_size}, cleanup_threshold={memory_config.cleanup_threshold}%") | |
| async def _configure_query_optimization(self): | |
| """Configure query optimization with optimized settings.""" | |
| query_config = self._optimization_settings['query'] | |
| # Configure query optimizer settings | |
| supabase_optimizer._monitoring_enabled = query_config.enable_monitoring | |
| logger.info(f"Configured query optimization: monitoring={query_config.enable_monitoring}, caching={query_config.enable_query_caching}") | |
| async def _configure_parallel_processing(self): | |
| """Configure parallel processing with optimized settings.""" | |
| parallel_config = self._optimization_settings['parallel'] | |
| # Update worker pool configurations | |
| if 'cpu_intensive' in parallel_processor.worker_pools: | |
| pool = parallel_processor.worker_pools['cpu_intensive'] | |
| if parallel_config.cpu_intensive_max_workers: | |
| pool.max_workers = parallel_config.cpu_intensive_max_workers | |
| pool.task_timeout = parallel_config.default_task_timeout | |
| if 'io_intensive' in parallel_processor.worker_pools: | |
| pool = parallel_processor.worker_pools['io_intensive'] | |
| pool.max_workers = parallel_config.io_intensive_max_workers | |
| pool.task_timeout = parallel_config.default_task_timeout | |
| if 'general' in parallel_processor.worker_pools: | |
| pool = parallel_processor.worker_pools['general'] | |
| pool.max_workers = parallel_config.general_max_workers | |
| pool.task_timeout = parallel_config.default_task_timeout | |
| logger.info(f"Configured parallel processing: cpu_workers={parallel_config.cpu_intensive_max_workers}, io_workers={parallel_config.io_intensive_max_workers}") | |
| async def _configure_performance_monitoring(self): | |
| """Configure performance monitoring with optimized settings.""" | |
| monitor_config = self._optimization_settings['monitoring'] | |
| # Configure performance monitor thresholds | |
| performance_monitor.thresholds.memory_warning = monitor_config.memory_warning_threshold | |
| performance_monitor.thresholds.memory_critical = monitor_config.memory_critical_threshold | |
| performance_monitor.thresholds.cache_hit_rate_warning = monitor_config.cache_hit_rate_warning | |
| performance_monitor.thresholds.cache_hit_rate_critical = monitor_config.cache_hit_rate_critical | |
| performance_monitor.thresholds.query_duration_warning = monitor_config.query_duration_warning | |
| performance_monitor.thresholds.query_duration_critical = monitor_config.query_duration_critical | |
| logger.info(f"Configured performance monitoring: interval={monitor_config.monitoring_interval}s, alerts={monitor_config.enable_alerts}") | |
| def _setup_performance_callbacks(self): | |
| """Set up performance monitoring callbacks.""" | |
| # Memory pressure callback | |
| def memory_pressure_callback(memory_stats): | |
| if memory_stats.memory_pressure in ['high', 'critical']: | |
| logger.warning(f"Memory pressure detected: {memory_stats.memory_pressure} ({memory_stats.percent_used:.1f}%)") | |
| # Trigger cleanup | |
| asyncio.create_task(self._handle_memory_pressure(memory_stats)) | |
| memory_manager.add_memory_callback(memory_pressure_callback) | |
| # Performance alert callback | |
| def performance_alert_callback(alert): | |
| logger.warning(f"Performance alert: {alert.severity.upper()} - {alert.message}") | |
| # Handle critical alerts | |
| if alert.severity == 'critical': | |
| asyncio.create_task(self._handle_critical_alert(alert)) | |
| performance_monitor.add_alert_callback(performance_alert_callback) | |
| logger.info("Performance monitoring callbacks configured") | |
| async def _handle_memory_pressure(self, memory_stats): | |
| """Handle memory pressure situations.""" | |
| try: | |
| if memory_stats.memory_pressure == 'critical': | |
| logger.warning("Handling critical memory pressure") | |
| # Aggressive cleanup | |
| await memory_manager.trigger_memory_cleanup(aggressive=True) | |
| # Clear caches | |
| cache_manager.general_cache.clear() | |
| cache_manager.dataset_cache.cleanup_chunks() | |
| # Force garbage collection | |
| import gc | |
| gc.collect() | |
| elif memory_stats.memory_pressure == 'high': | |
| logger.info("Handling high memory pressure") | |
| # Standard cleanup | |
| await memory_manager.trigger_memory_cleanup(aggressive=False) | |
| # Reduce cache sizes temporarily | |
| original_size = cache_manager.general_cache.max_size | |
| cache_manager.general_cache.max_size = int(original_size * 0.7) | |
| except Exception as e: | |
| logger.error(f"Error handling memory pressure: {e}") | |
| async def _handle_critical_alert(self, alert): | |
| """Handle critical performance alerts.""" | |
| try: | |
| logger.critical(f"Handling critical alert: {alert.category} - {alert.message}") | |
| if alert.category == 'memory': | |
| await self._handle_memory_pressure(type('MemoryStats', (), { | |
| 'memory_pressure': 'critical', | |
| 'percent_used': alert.details.get('memory_percent', 95) | |
| })()) | |
| elif alert.category == 'connection': | |
| # Handle connection pool issues | |
| pool_name = alert.details.get('pool_name') | |
| if pool_name and pool_name in resource_manager.pools: | |
| logger.warning(f"Restarting connection pool: {pool_name}") | |
| pool = resource_manager.pools[pool_name] | |
| await pool.stop() | |
| await pool.start() | |
| elif alert.category == 'parallel': | |
| # Handle parallel processing issues | |
| logger.warning("Restarting parallel processor due to critical alert") | |
| await parallel_processor.stop() | |
| await parallel_processor.start() | |
| except Exception as e: | |
| logger.error(f"Error handling critical alert: {e}") | |
| def get_system_status(self) -> Dict[str, Any]: | |
| """Get current status of all performance optimization systems.""" | |
| return { | |
| 'initialized': self._initialized, | |
| 'systems_started': self._systems_started, | |
| 'optimization_settings': self._optimization_settings is not None, | |
| 'current_metrics': performance_monitor.get_current_metrics().to_dict() if performance_monitor.get_current_metrics() else None, | |
| 'active_alerts': len(performance_monitor.get_active_alerts()), | |
| 'system_health': performance_monitor.get_current_metrics().overall_health_score if performance_monitor.get_current_metrics() else None | |
| } | |
| async def get_comprehensive_report(self) -> Dict[str, Any]: | |
| """Get comprehensive performance report.""" | |
| if not self._systems_started: | |
| return {'error': 'Performance systems not started'} | |
| try: | |
| # Collect reports from all systems | |
| cache_stats = cache_manager.get_comprehensive_stats() | |
| connection_stats = resource_manager.get_resource_summary() | |
| memory_report = memory_manager.get_memory_report() | |
| query_report = await supabase_optimizer.get_optimization_report() | |
| parallel_stats = parallel_processor.get_system_stats() | |
| performance_summary = performance_monitor.get_performance_summary() | |
| return { | |
| 'timestamp': asyncio.get_event_loop().time(), | |
| 'system_status': self.get_system_status(), | |
| 'cache_statistics': cache_stats, | |
| 'connection_statistics': connection_stats, | |
| 'memory_report': memory_report, | |
| 'query_optimization': query_report, | |
| 'parallel_processing': parallel_stats, | |
| 'performance_monitoring': performance_summary, | |
| 'optimization_settings': self._optimization_settings | |
| } | |
| except Exception as e: | |
| logger.error(f"Error generating comprehensive report: {e}") | |
| return {'error': str(e)} | |
| # Global performance optimization manager | |
| performance_manager = PerformanceOptimizationManager() | |
| # Convenience functions for easy initialization | |
| async def initialize_performance_optimization(environment: str = None) -> Dict[str, Any]: | |
| """Initialize performance optimization systems.""" | |
| return await performance_manager.initialize(environment) | |
| async def start_performance_systems() -> Dict[str, Any]: | |
| """Start all performance optimization systems.""" | |
| return await performance_manager.start_all_systems() | |
| async def stop_performance_systems() -> Dict[str, Any]: | |
| """Stop all performance optimization systems.""" | |
| return await performance_manager.stop_all_systems() | |
| async def get_performance_report() -> Dict[str, Any]: | |
| """Get comprehensive performance report.""" | |
| return await performance_manager.get_comprehensive_report() | |
| def get_performance_status() -> Dict[str, Any]: | |
| """Get current performance system status.""" | |
| return performance_manager.get_system_status() |