Spaces:
Paused
Paused
Download shared/performance_config.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/performance_config.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/performance_config.py
-
curl -L -o performance_config.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/performance_config.py
12.1 kB
| """ | |
| Performance optimization configuration for MCP AI Data Scientist. | |
| Provides centralized configuration for all performance-related settings. | |
| """ | |
| import os | |
| from typing import Dict, Any, Optional | |
| from dataclasses import dataclass | |
| from pydantic import Field | |
| from pydantic_settings import BaseSettings | |
| from .config import settings | |
| class CacheConfig: | |
| """Cache configuration settings.""" | |
| # General cache settings | |
| max_size: int = 2000 | |
| default_ttl: int = 3600 # 1 hour | |
| cleanup_interval: int = 300 # 5 minutes | |
| # Dataset cache settings | |
| dataset_max_count: int = 100 | |
| dataset_max_size_mb: int = 1000 | |
| # Query cache settings | |
| query_max_entries: int = 1000 | |
| query_default_ttl: int = 300 # 5 minutes | |
| # Model cache settings | |
| model_max_count: int = 50 | |
| model_default_ttl: int = 7200 # 2 hours | |
| class ConnectionPoolConfig: | |
| """Connection pool configuration settings.""" | |
| # Supabase connection pool | |
| supabase_max_connections: int = 20 | |
| supabase_min_connections: int = 5 | |
| supabase_max_idle_seconds: int = 600 # 10 minutes | |
| supabase_max_age_seconds: int = 7200 # 2 hours | |
| # MCP server connection pools | |
| mcp_max_connections: int = 5 | |
| mcp_min_connections: int = 1 | |
| mcp_max_idle_seconds: int = 300 # 5 minutes | |
| mcp_max_age_seconds: int = 3600 # 1 hour | |
| # Health check settings | |
| health_check_interval: int = 60 # 1 minute | |
| connection_timeout: int = 30 # 30 seconds | |
| class MemoryConfig: | |
| """Memory management configuration settings.""" | |
| # Memory monitoring | |
| monitoring_interval: int = 30 # 30 seconds | |
| cleanup_threshold: float = 85.0 # 85% memory usage | |
| # Memory pressure thresholds | |
| medium_pressure_threshold: float = 70.0 # 70% | |
| high_pressure_threshold: float = 85.0 # 85% | |
| critical_pressure_threshold: float = 95.0 # 95% | |
| # Chunked processing | |
| default_chunk_size: int = 10000 | |
| max_memory_mb: float = 500 | |
| # Data loader settings | |
| loader_memory_limit_mb: float = 1000 | |
| # Optimization settings | |
| enable_auto_optimization: bool = True | |
| optimization_interval: int = 300 # 5 minutes | |
| class QueryOptimizationConfig: | |
| """Query optimization configuration settings.""" | |
| # Query monitoring | |
| enable_monitoring: bool = True | |
| slow_query_threshold_ms: float = 1000 # 1 second | |
| # Query caching | |
| enable_query_caching: bool = True | |
| cache_ttl: int = 300 # 5 minutes | |
| # Index recommendations | |
| enable_auto_indexing: bool = False # Disabled by default for safety | |
| min_query_executions: int = 10 | |
| # Optimization suggestions | |
| enable_auto_optimization: bool = False # Disabled by default | |
| safe_optimizations_only: bool = True | |
| class ParallelProcessingConfig: | |
| """Parallel processing configuration settings.""" | |
| # Worker pool settings | |
| cpu_intensive_max_workers: Optional[int] = None # Will use CPU count | |
| io_intensive_max_workers: int = 20 | |
| general_max_workers: int = 10 | |
| # Task settings | |
| default_task_timeout: int = 300 # 5 minutes | |
| max_retries: int = 3 | |
| retry_delay: float = 1.0 # 1 second | |
| # Queue settings | |
| max_queue_size: int = 1000 | |
| priority_queue_enabled: bool = True | |
| # Performance settings | |
| enable_adaptive_batching: bool = True | |
| target_batch_duration: float = 2.0 # 2 seconds | |
| # Monitoring | |
| monitoring_interval: int = 30 # 30 seconds | |
| class PerformanceMonitoringConfig: | |
| """Performance monitoring configuration settings.""" | |
| # Monitoring settings | |
| enable_monitoring: bool = True | |
| monitoring_interval: int = 30 # 30 seconds | |
| metrics_history_size: int = 1000 | |
| # Alert settings | |
| enable_alerts: bool = True | |
| alert_cooldown: int = 300 # 5 minutes between same alerts | |
| # Thresholds | |
| memory_warning_threshold: float = 75.0 | |
| memory_critical_threshold: float = 90.0 | |
| cache_hit_rate_warning: float = 0.6 | |
| cache_hit_rate_critical: float = 0.4 | |
| query_duration_warning: float = 1000 # ms | |
| query_duration_critical: float = 5000 # ms | |
| connection_utilization_warning: float = 0.8 | |
| connection_utilization_critical: float = 0.95 | |
| task_failure_rate_warning: float = 0.1 | |
| task_failure_rate_critical: float = 0.2 | |
| # Reporting | |
| enable_performance_reports: bool = True | |
| report_interval: int = 3600 # 1 hour | |
| class PerformanceSettings(BaseSettings): | |
| """Performance settings loaded from environment variables.""" | |
| # Cache settings | |
| cache_max_size: int = Field(2000, env="CACHE_MAX_SIZE") | |
| cache_default_ttl: int = Field(3600, env="CACHE_DEFAULT_TTL") | |
| dataset_cache_max_size_mb: int = Field(1000, env="DATASET_CACHE_MAX_SIZE_MB") | |
| # Connection pool settings | |
| supabase_max_connections: int = Field(20, env="SUPABASE_MAX_CONNECTIONS") | |
| supabase_min_connections: int = Field(5, env="SUPABASE_MIN_CONNECTIONS") | |
| mcp_max_connections: int = Field(5, env="MCP_MAX_CONNECTIONS") | |
| # Memory settings | |
| memory_cleanup_threshold: float = Field(85.0, env="MEMORY_CLEANUP_THRESHOLD") | |
| chunk_size: int = Field(10000, env="DEFAULT_CHUNK_SIZE") | |
| memory_limit_mb: float = Field(1000, env="MEMORY_LIMIT_MB") | |
| # Query optimization settings | |
| enable_query_monitoring: bool = Field(True, env="ENABLE_QUERY_MONITORING") | |
| slow_query_threshold_ms: float = Field(1000, env="SLOW_QUERY_THRESHOLD_MS") | |
| enable_query_caching: bool = Field(True, env="ENABLE_QUERY_CACHING") | |
| # Parallel processing settings | |
| cpu_max_workers: Optional[int] = Field(None, env="CPU_MAX_WORKERS") | |
| io_max_workers: int = Field(20, env="IO_MAX_WORKERS") | |
| task_timeout: int = Field(300, env="TASK_TIMEOUT") | |
| # Performance monitoring settings | |
| enable_performance_monitoring: bool = Field(True, env="ENABLE_PERFORMANCE_MONITORING") | |
| monitoring_interval: int = Field(30, env="MONITORING_INTERVAL") | |
| enable_performance_alerts: bool = Field(True, env="ENABLE_PERFORMANCE_ALERTS") | |
| class Config: | |
| env_file = ".env" | |
| case_sensitive = False | |
| # Global performance settings | |
| perf_settings = PerformanceSettings() | |
| def get_cache_config() -> CacheConfig: | |
| """Get cache configuration.""" | |
| return CacheConfig( | |
| max_size=perf_settings.cache_max_size, | |
| default_ttl=perf_settings.cache_default_ttl, | |
| dataset_max_size_mb=perf_settings.dataset_cache_max_size_mb | |
| ) | |
| def get_connection_pool_config() -> ConnectionPoolConfig: | |
| """Get connection pool configuration.""" | |
| return ConnectionPoolConfig( | |
| supabase_max_connections=perf_settings.supabase_max_connections, | |
| supabase_min_connections=perf_settings.supabase_min_connections, | |
| mcp_max_connections=perf_settings.mcp_max_connections | |
| ) | |
| def get_memory_config() -> MemoryConfig: | |
| """Get memory management configuration.""" | |
| return MemoryConfig( | |
| cleanup_threshold=perf_settings.memory_cleanup_threshold, | |
| default_chunk_size=perf_settings.chunk_size, | |
| loader_memory_limit_mb=perf_settings.memory_limit_mb | |
| ) | |
| def get_query_optimization_config() -> QueryOptimizationConfig: | |
| """Get query optimization configuration.""" | |
| return QueryOptimizationConfig( | |
| enable_monitoring=perf_settings.enable_query_monitoring, | |
| slow_query_threshold_ms=perf_settings.slow_query_threshold_ms, | |
| enable_query_caching=perf_settings.enable_query_caching | |
| ) | |
| def get_parallel_processing_config() -> ParallelProcessingConfig: | |
| """Get parallel processing configuration.""" | |
| return ParallelProcessingConfig( | |
| cpu_intensive_max_workers=perf_settings.cpu_max_workers, | |
| io_intensive_max_workers=perf_settings.io_max_workers, | |
| default_task_timeout=perf_settings.task_timeout | |
| ) | |
| def get_performance_monitoring_config() -> PerformanceMonitoringConfig: | |
| """Get performance monitoring configuration.""" | |
| return PerformanceMonitoringConfig( | |
| enable_monitoring=perf_settings.enable_performance_monitoring, | |
| monitoring_interval=perf_settings.monitoring_interval, | |
| enable_alerts=perf_settings.enable_performance_alerts | |
| ) | |
| def get_optimized_settings_for_environment() -> Dict[str, Any]: | |
| """Get optimized settings based on current environment.""" | |
| import psutil | |
| # Detect system resources | |
| cpu_count = psutil.cpu_count() | |
| memory_gb = psutil.virtual_memory().total / (1024**3) | |
| # Optimize settings based on resources | |
| optimized = { | |
| 'cache': get_cache_config(), | |
| 'connections': get_connection_pool_config(), | |
| 'memory': get_memory_config(), | |
| 'query': get_query_optimization_config(), | |
| 'parallel': get_parallel_processing_config(), | |
| 'monitoring': get_performance_monitoring_config() | |
| } | |
| # Adjust based on system resources | |
| if memory_gb < 4: # Low memory system | |
| optimized['cache'].max_size = 1000 | |
| optimized['cache'].dataset_max_size_mb = 500 | |
| optimized['memory'].default_chunk_size = 5000 | |
| optimized['connections'].supabase_max_connections = 10 | |
| elif memory_gb > 16: # High memory system | |
| optimized['cache'].max_size = 5000 | |
| optimized['cache'].dataset_max_size_mb = 2000 | |
| optimized['memory'].default_chunk_size = 20000 | |
| optimized['connections'].supabase_max_connections = 30 | |
| if cpu_count <= 2: # Low CPU system | |
| optimized['parallel'].cpu_intensive_max_workers = 2 | |
| optimized['parallel'].io_intensive_max_workers = 10 | |
| elif cpu_count >= 8: # High CPU system | |
| optimized['parallel'].cpu_intensive_max_workers = cpu_count | |
| optimized['parallel'].io_intensive_max_workers = 30 | |
| return optimized | |
| def apply_performance_optimizations(): | |
| """Apply performance optimizations to all systems.""" | |
| optimized_settings = get_optimized_settings_for_environment() | |
| # Log optimization settings | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| logger.info("Applying performance optimizations:") | |
| logger.info(f" Cache max size: {optimized_settings['cache'].max_size}") | |
| logger.info(f" Dataset cache max size: {optimized_settings['cache'].dataset_max_size_mb}MB") | |
| logger.info(f" Supabase max connections: {optimized_settings['connections'].supabase_max_connections}") | |
| logger.info(f" Default chunk size: {optimized_settings['memory'].default_chunk_size}") | |
| logger.info(f" CPU workers: {optimized_settings['parallel'].cpu_intensive_max_workers}") | |
| logger.info(f" I/O workers: {optimized_settings['parallel'].io_intensive_max_workers}") | |
| return optimized_settings | |
| # Environment-specific configurations | |
| DEVELOPMENT_CONFIG = { | |
| 'cache_max_size': 1000, | |
| 'supabase_max_connections': 10, | |
| 'enable_performance_monitoring': True, | |
| 'monitoring_interval': 60, | |
| 'enable_query_caching': True, | |
| 'memory_cleanup_threshold': 80.0 | |
| } | |
| PRODUCTION_CONFIG = { | |
| 'cache_max_size': 5000, | |
| 'supabase_max_connections': 50, | |
| 'enable_performance_monitoring': True, | |
| 'monitoring_interval': 30, | |
| 'enable_query_caching': True, | |
| 'memory_cleanup_threshold': 85.0, | |
| 'enable_performance_alerts': True | |
| } | |
| TESTING_CONFIG = { | |
| 'cache_max_size': 100, | |
| 'supabase_max_connections': 5, | |
| 'enable_performance_monitoring': False, | |
| 'enable_query_caching': False, | |
| 'memory_cleanup_threshold': 90.0 | |
| } | |
| def get_config_for_environment(env: str = None) -> Dict[str, Any]: | |
| """Get configuration for specific environment.""" | |
| env = env or os.getenv('ENVIRONMENT', 'development').lower() | |
| if env == 'production': | |
| return PRODUCTION_CONFIG | |
| elif env == 'testing': | |
| return TESTING_CONFIG | |
| else: | |
| return DEVELOPMENT_CONFIG |