""" Performance benchmark tests for the MCP AI Data Scientist system. Tests caching, query optimization, memory management, and parallel processing. """ import asyncio import pytest import time import pandas as pd import numpy as np from typing import List, Dict, Any, Tuple import tempfile import os from concurrent.futures import ThreadPoolExecutor import psutil import gc from shared.caching import cache_manager, CacheManager from shared.connection_pool import resource_manager, SupabaseConnectionPool from shared.memory_manager import memory_manager, MemoryEfficientDataLoader, ChunkedDataProcessor from shared.query_optimizer import supabase_optimizer, QueryOptimizer from shared.parallel_processor import parallel_processor, TaskPriority from shared.config import settings class TestCachingPerformance: """Test caching system performance.""" @pytest.fixture async def cache_system(self): """Setup cache system for testing.""" test_cache = CacheManager() await test_cache.start() yield test_cache await test_cache.stop() @pytest.mark.asyncio async def test_cache_hit_performance(self, cache_system): """Test cache hit performance.""" # Warm up cache test_data = {"large_dataset": list(range(10000))} cache_system.set("test_key", test_data) # Benchmark cache hits start_time = time.time() iterations = 1000 for i in range(iterations): result = cache_system.get("test_key") assert result is not None end_time = time.time() avg_time_ms = ((end_time - start_time) / iterations) * 1000 # Cache hits should be very fast (< 1ms average) assert avg_time_ms < 1.0, f"Cache hit too slow: {avg_time_ms}ms" print(f"Cache hit performance: {avg_time_ms:.3f}ms average") @pytest.mark.asyncio async def test_cache_memory_efficiency(self, cache_system): """Test cache memory usage efficiency.""" initial_memory = psutil.Process().memory_info().rss / 1024 / 1024 # MB # Add large objects to cache large_objects = [] for i in range(100): data = {"id": i, "data": list(range(1000))} cache_system.set(f"large_object_{i}", data) large_objects.append(data) # Check memory usage peak_memory = psutil.Process().memory_info().rss / 1024 / 1024 # MB memory_increase = peak_memory - initial_memory # Clear cache cache_system.general_cache.clear() gc.collect() final_memory = psutil.Process().memory_info().rss / 1024 / 1024 # MB memory_recovered = peak_memory - final_memory print(f"Memory usage - Initial: {initial_memory:.1f}MB, Peak: {peak_memory:.1f}MB, Final: {final_memory:.1f}MB") print(f"Memory increase: {memory_increase:.1f}MB, Recovered: {memory_recovered:.1f}MB") # Should recover most memory recovery_rate = memory_recovered / memory_increase if memory_increase > 0 else 1 assert recovery_rate > 0.7, f"Poor memory recovery: {recovery_rate:.2f}" @pytest.mark.asyncio async def test_dataset_cache_performance(self, cache_system): """Test dataset-specific caching performance.""" user_id = "test_user" dataset_id = "test_dataset" # Create test dataset result test_result = pd.DataFrame({ 'col1': range(10000), 'col2': np.random.random(10000), 'col3': ['test'] * 10000 }) # Benchmark cache set start_time = time.time() cache_system.set_dataset_result(user_id, dataset_id, "cleaning", test_result) set_time = (time.time() - start_time) * 1000 # Benchmark cache get start_time = time.time() cached_result = cache_system.get_dataset_result(user_id, dataset_id, "cleaning") get_time = (time.time() - start_time) * 1000 assert cached_result is not None assert len(cached_result) == len(test_result) print(f"Dataset cache - Set: {set_time:.2f}ms, Get: {get_time:.2f}ms") # Should be reasonably fast assert set_time < 100, f"Dataset cache set too slow: {set_time}ms" assert get_time < 50, f"Dataset cache get too slow: {get_time}ms" class TestConnectionPoolPerformance: """Test connection pool performance.""" @pytest.mark.asyncio async def test_connection_pool_throughput(self): """Test connection pool throughput under load.""" await resource_manager.start() try: # Simulate concurrent connection requests async def get_connection_task(): async with resource_manager.get_supabase_connection() as conn: # Simulate work await asyncio.sleep(0.01) return True # Benchmark concurrent connections start_time = time.time() concurrent_tasks = 50 tasks = [get_connection_task() for _ in range(concurrent_tasks)] results = await asyncio.gather(*tasks) end_time = time.time() total_time = end_time - start_time throughput = concurrent_tasks / total_time assert all(results) print(f"Connection pool throughput: {throughput:.1f} connections/second") # Should handle reasonable throughput assert throughput > 20, f"Connection pool throughput too low: {throughput:.1f}/sec" finally: await resource_manager.stop() @pytest.mark.asyncio async def test_connection_pool_resource_usage(self): """Test connection pool resource efficiency.""" await resource_manager.start() try: initial_connections = 0 pool = resource_manager.get_pool("supabase") if pool: initial_connections = pool.get_stats().total_connections # Create many concurrent connections async def connection_task(): async with resource_manager.get_supabase_connection() as conn: await asyncio.sleep(0.1) # Run tasks in batches to test pooling for batch in range(5): tasks = [connection_task() for _ in range(10)] await asyncio.gather(*tasks) if pool: stats = pool.get_stats() print(f"Batch {batch + 1} - Total: {stats.total_connections}, Active: {stats.active_connections}") # Check final connection count final_stats = pool.get_stats() if pool else None if final_stats: # Should reuse connections efficiently connection_efficiency = initial_connections / max(final_stats.total_connections, 1) print(f"Connection efficiency: {connection_efficiency:.2f}") # Should not create excessive connections assert final_stats.total_connections < 20, f"Too many connections created: {final_stats.total_connections}" finally: await resource_manager.stop() class TestMemoryManagementPerformance: """Test memory management performance.""" @pytest.mark.asyncio async def test_large_dataset_processing(self): """Test processing of large datasets with memory management.""" await memory_manager.start() try: # Create large test dataset with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: # Write header f.write("id,value1,value2,text\n") # Write 100k rows for i in range(100000): f.write(f"{i},{np.random.random()},{np.random.random()},test_text_{i}\n") temp_file = f.name try: # Test chunked loading loader = MemoryEfficientDataLoader(memory_limit_mb=100) start_time = time.time() chunk_count = 0 total_rows = 0 async for chunk in loader.load_large_dataset(temp_file, chunk_size=10000): chunk_count += 1 total_rows += len(chunk) # Monitor memory during processing memory_stats = memory_manager.monitor.get_memory_stats() assert memory_stats.memory_pressure != 'critical', "Memory pressure too high during processing" end_time = time.time() processing_time = end_time - start_time print(f"Processed {total_rows} rows in {chunk_count} chunks in {processing_time:.2f}s") print(f"Processing rate: {total_rows / processing_time:.0f} rows/second") assert total_rows == 100000, f"Expected 100000 rows, got {total_rows}" assert processing_time < 30, f"Processing too slow: {processing_time:.2f}s" finally: os.unlink(temp_file) finally: await memory_manager.stop() @pytest.mark.asyncio async def test_memory_optimization(self): """Test DataFrame memory optimization.""" # Create inefficient DataFrame df = pd.DataFrame({ 'int_col': np.random.randint(0, 100, 10000).astype('int64'), 'float_col': np.random.random(10000).astype('float64'), 'category_col': np.random.choice(['A', 'B', 'C'], 10000).astype('object'), 'text_col': ['text_' + str(i) for i in range(10000)] }) original_memory = df.memory_usage(deep=True).sum() # Optimize memory optimized_df = memory_manager.optimizer.optimize_dataframe_memory(df.copy()) optimized_memory = optimized_df.memory_usage(deep=True).sum() memory_reduction = (original_memory - optimized_memory) / original_memory print(f"Memory optimization: {original_memory / 1024**2:.1f}MB -> {optimized_memory / 1024**2:.1f}MB") print(f"Reduction: {memory_reduction * 100:.1f}%") # Should achieve some memory reduction assert memory_reduction > 0.1, f"Insufficient memory optimization: {memory_reduction * 100:.1f}%" # Data should remain equivalent assert len(optimized_df) == len(df) assert list(optimized_df.columns) == list(df.columns) class TestQueryOptimizationPerformance: """Test query optimization performance.""" @pytest.fixture def query_optimizer(self): """Setup query optimizer for testing.""" return QueryOptimizer() def test_query_analysis_performance(self, query_optimizer): """Test query analysis performance.""" test_queries = [ "SELECT * FROM users WHERE created_at > '2023-01-01'", "SELECT id, name FROM products ORDER BY price DESC", "SELECT COUNT(*) FROM orders WHERE status = 'completed'", "SELECT u.name, p.title FROM users u JOIN posts p ON u.id = p.user_id WHERE p.published = true", "SELECT * FROM large_table WHERE description LIKE '%search term%'" ] start_time = time.time() for query in test_queries * 100: # Analyze each query 100 times analysis = query_optimizer.analyzer.analyze_query(query) assert 'query_hash' in analysis assert 'tables' in analysis end_time = time.time() total_time = end_time - start_time avg_time_ms = (total_time / (len(test_queries) * 100)) * 1000 print(f"Query analysis performance: {avg_time_ms:.3f}ms average") # Should be very fast assert avg_time_ms < 5, f"Query analysis too slow: {avg_time_ms:.3f}ms" def test_optimization_suggestions_performance(self, query_optimizer): """Test optimization suggestion generation performance.""" slow_queries = [ "SELECT * FROM large_table", "SELECT * FROM users WHERE name LIKE '%john%'", "SELECT * FROM orders ORDER BY created_at", "SELECT u.*, p.* FROM users u JOIN posts p ON u.id = p.user_id" ] start_time = time.time() total_suggestions = 0 for query in slow_queries: suggestions = query_optimizer.get_optimization_suggestions(query) total_suggestions += len(suggestions) end_time = time.time() total_time = end_time - start_time print(f"Generated {total_suggestions} suggestions in {total_time:.3f}s") # Should generate suggestions quickly assert total_time < 1, f"Optimization suggestion generation too slow: {total_time:.3f}s" assert total_suggestions > 0, "No optimization suggestions generated" class TestParallelProcessingPerformance: """Test parallel processing performance.""" @pytest.mark.asyncio async def test_parallel_task_throughput(self): """Test parallel task processing throughput.""" await parallel_processor.start() try: # Define test task def cpu_intensive_task(n: int) -> int: """Simulate CPU-intensive work.""" result = 0 for i in range(n): result += i ** 2 return result # Benchmark sequential processing start_time = time.time() sequential_results = [] for i in range(20): result = cpu_intensive_task(10000) sequential_results.append(result) sequential_time = time.time() - start_time # Benchmark parallel processing start_time = time.time() task_ids = [] for i in range(20): task_id = await parallel_processor.submit_task( cpu_intensive_task, args=(10000,), pool_name='cpu_intensive' ) task_ids.append(task_id) parallel_results = [] for task_id in task_ids: result = await parallel_processor.get_task_result(task_id) parallel_results.append(result) parallel_time = time.time() - start_time # Verify results are correct assert parallel_results == sequential_results # Calculate speedup speedup = sequential_time / parallel_time print(f"Sequential time: {sequential_time:.2f}s, Parallel time: {parallel_time:.2f}s") print(f"Speedup: {speedup:.2f}x") # Should achieve some speedup assert speedup > 1.5, f"Insufficient parallel speedup: {speedup:.2f}x" finally: await parallel_processor.stop() @pytest.mark.asyncio async def test_parallel_memory_efficiency(self): """Test parallel processing memory efficiency.""" await parallel_processor.start() try: initial_memory = psutil.Process().memory_info().rss / 1024 / 1024 # MB # Submit memory-intensive tasks def memory_task(size: int) -> int: # Create and process large list data = list(range(size)) return sum(data) task_ids = [] for i in range(10): task_id = await parallel_processor.submit_task( memory_task, args=(100000,), pool_name='cpu_intensive' ) task_ids.append(task_id) # Wait for completion results = [] for task_id in task_ids: result = await parallel_processor.get_task_result(task_id) results.append(result) peak_memory = psutil.Process().memory_info().rss / 1024 / 1024 # MB # Wait a bit for cleanup await asyncio.sleep(2) gc.collect() final_memory = psutil.Process().memory_info().rss / 1024 / 1024 # MB print(f"Memory usage - Initial: {initial_memory:.1f}MB, Peak: {peak_memory:.1f}MB, Final: {final_memory:.1f}MB") # Memory should not grow excessively memory_growth = peak_memory - initial_memory assert memory_growth < 200, f"Excessive memory growth: {memory_growth:.1f}MB" # Should clean up reasonably well memory_cleanup = peak_memory - final_memory cleanup_rate = memory_cleanup / memory_growth if memory_growth > 0 else 1 assert cleanup_rate > 0.5, f"Poor memory cleanup: {cleanup_rate:.2f}" finally: await parallel_processor.stop() @pytest.mark.asyncio async def test_task_priority_performance(self): """Test task priority handling performance.""" await parallel_processor.start() try: def timed_task(duration: float, task_id: str) -> Tuple[str, float]: start = time.time() time.sleep(duration) return task_id, time.time() - start # Submit mixed priority tasks task_submissions = [] # Submit low priority tasks first for i in range(5): task_id = await parallel_processor.submit_task( timed_task, args=(0.1, f"low_{i}"), priority=TaskPriority.LOW, pool_name='general' ) task_submissions.append(('low', task_id, time.time())) # Submit high priority tasks for i in range(3): task_id = await parallel_processor.submit_task( timed_task, args=(0.1, f"high_{i}"), priority=TaskPriority.HIGH, pool_name='general' ) task_submissions.append(('high', task_id, time.time())) # Collect results completion_times = [] for priority, task_id, submit_time in task_submissions: result = await parallel_processor.get_task_result(task_id) completion_time = time.time() completion_times.append((priority, task_id, completion_time - submit_time)) # Analyze priority handling high_priority_times = [t for p, _, t in completion_times if p == 'high'] low_priority_times = [t for p, _, t in completion_times if p == 'low'] avg_high_time = sum(high_priority_times) / len(high_priority_times) avg_low_time = sum(low_priority_times) / len(low_priority_times) print(f"Average completion time - High priority: {avg_high_time:.2f}s, Low priority: {avg_low_time:.2f}s") # High priority tasks should generally complete faster # (This is a loose check since timing can vary) assert avg_high_time <= avg_low_time * 1.5, "Priority handling not working effectively" finally: await parallel_processor.stop() class TestIntegratedPerformance: """Test integrated system performance.""" @pytest.mark.asyncio async def test_end_to_end_performance(self): """Test end-to-end system performance.""" # Start all systems await cache_manager.start() await resource_manager.start() await memory_manager.start() await parallel_processor.start() try: # Simulate complete data processing pipeline start_time = time.time() # 1. Data loading (simulated) test_data = pd.DataFrame({ 'id': range(10000), 'value': np.random.random(10000), 'category': np.random.choice(['A', 'B', 'C'], 10000) }) # 2. Parallel data processing def process_chunk(chunk_data): # Simulate processing return chunk_data.groupby('category').agg({'value': ['mean', 'sum']}).reset_index() # Split into chunks and process in parallel chunk_size = 2000 chunks = [test_data[i:i+chunk_size] for i in range(0, len(test_data), chunk_size)] processed_results = await parallel_processor.map_parallel( process_chunk, chunks, pool_name='cpu_intensive' ) # 3. Cache results cache_manager.set("processed_results", processed_results, ttl=3600) # 4. Retrieve from cache cached_results = cache_manager.get("processed_results") end_time = time.time() total_time = end_time - start_time print(f"End-to-end processing time: {total_time:.2f}s") print(f"Processed {len(test_data)} rows in {len(chunks)} chunks") # Verify results assert cached_results is not None assert len(cached_results) == len(chunks) # Should complete in reasonable time assert total_time < 10, f"End-to-end processing too slow: {total_time:.2f}s" finally: await parallel_processor.stop() await memory_manager.stop() await resource_manager.stop() await cache_manager.stop() @pytest.mark.asyncio async def test_system_resource_monitoring(self): """Test system resource monitoring during load.""" # Start monitoring systems await memory_manager.start() await parallel_processor.start() try: # Record initial state initial_stats = { 'memory': memory_manager.monitor.get_memory_stats(), 'parallel': parallel_processor.get_system_stats() } # Generate load def cpu_and_memory_task(size: int) -> int: # CPU and memory intensive task data = [i ** 2 for i in range(size)] return sum(data) # Submit multiple tasks task_ids = [] for i in range(20): task_id = await parallel_processor.submit_task( cpu_and_memory_task, args=(50000,), pool_name='cpu_intensive' ) task_ids.append(task_id) # Monitor during execution max_memory_usage = 0 max_active_tasks = 0 while any(not parallel_processor.get_task_result(tid)[0] for tid in task_ids if parallel_processor.task_queue.get_task(tid)): memory_stats = memory_manager.monitor.get_memory_stats() parallel_stats = parallel_processor.get_system_stats() max_memory_usage = max(max_memory_usage, memory_stats.percent_used) max_active_tasks = max(max_active_tasks, parallel_stats['queue']['running_tasks']) await asyncio.sleep(0.5) # Wait for all tasks to complete results = [] for task_id in task_ids: result = await parallel_processor.get_task_result(task_id) results.append(result) # Record final state final_stats = { 'memory': memory_manager.monitor.get_memory_stats(), 'parallel': parallel_processor.get_system_stats() } print(f"Resource usage during load:") print(f" Max memory usage: {max_memory_usage:.1f}%") print(f" Max active tasks: {max_active_tasks}") print(f" Tasks completed: {len([r for r in results if r is not None])}") # System should handle load without critical issues assert max_memory_usage < 95, f"Memory usage too high: {max_memory_usage:.1f}%" assert len(results) == len(task_ids), "Not all tasks completed" finally: await parallel_processor.stop() await memory_manager.stop() if __name__ == "__main__": # Run performance benchmarks pytest.main([__file__, "-v", "-s"])