ai_data_scientist / shared /parallel_processor.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
33.9 kB
"""
Parallel processing system for independent operations.
Provides task parallelization, worker management, and load balancing.
"""
import asyncio
import logging
import time
import multiprocessing
from typing import Any, Dict, List, Optional, Callable, Union, Tuple, Awaitable
from dataclasses import dataclass, field
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, Future, as_completed
from queue import Queue, Empty
import threading
from contextlib import asynccontextmanager
import pickle
import traceback
from enum import Enum
from .monitoring import monitoring_system
from .memory_manager import memory_manager, MemoryStats
logger = logging.getLogger(__name__)
class TaskPriority(Enum):
"""Task priority levels."""
LOW = 1
NORMAL = 2
HIGH = 3
CRITICAL = 4
class TaskStatus(Enum):
"""Task execution status."""
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
@dataclass
class Task:
"""Represents a task for parallel execution."""
task_id: str
func: Callable
args: Tuple = field(default_factory=tuple)
kwargs: Dict[str, Any] = field(default_factory=dict)
priority: TaskPriority = TaskPriority.NORMAL
timeout_seconds: Optional[int] = None
retry_count: int = 0
max_retries: int = 3
created_at: datetime = field(default_factory=datetime.utcnow)
started_at: Optional[datetime] = None
completed_at: Optional[datetime] = None
status: TaskStatus = TaskStatus.PENDING
result: Any = None
error: Optional[str] = None
worker_id: Optional[str] = None
def __post_init__(self):
if not self.task_id:
self.task_id = f"task_{int(time.time() * 1000000)}"
def to_dict(self) -> Dict[str, Any]:
return {
'task_id': self.task_id,
'priority': self.priority.name,
'status': self.status.value,
'created_at': self.created_at.isoformat(),
'started_at': self.started_at.isoformat() if self.started_at else None,
'completed_at': self.completed_at.isoformat() if self.completed_at else None,
'retry_count': self.retry_count,
'max_retries': self.max_retries,
'worker_id': self.worker_id,
'error': self.error,
'duration_ms': self.get_duration_ms()
}
def get_duration_ms(self) -> Optional[float]:
"""Get task duration in milliseconds."""
if self.started_at and self.completed_at:
return (self.completed_at - self.started_at).total_seconds() * 1000
return None
@dataclass
class WorkerStats:
"""Worker statistics."""
worker_id: str
worker_type: str # 'thread' or 'process'
tasks_completed: int
tasks_failed: int
total_execution_time_ms: float
avg_execution_time_ms: float
current_task: Optional[str]
is_busy: bool
created_at: datetime
last_activity: datetime
def to_dict(self) -> Dict[str, Any]:
return {
'worker_id': self.worker_id,
'worker_type': self.worker_type,
'tasks_completed': self.tasks_completed,
'tasks_failed': self.tasks_failed,
'total_execution_time_ms': self.total_execution_time_ms,
'avg_execution_time_ms': self.avg_execution_time_ms,
'current_task': self.current_task,
'is_busy': self.is_busy,
'created_at': self.created_at.isoformat(),
'last_activity': self.last_activity.isoformat()
}
class TaskQueue:
"""Priority-based task queue."""
def __init__(self):
self._queues = {
TaskPriority.CRITICAL: asyncio.Queue(),
TaskPriority.HIGH: asyncio.Queue(),
TaskPriority.NORMAL: asyncio.Queue(),
TaskPriority.LOW: asyncio.Queue()
}
self._tasks: Dict[str, Task] = {}
self._lock = asyncio.Lock()
async def put(self, task: Task):
"""Add task to queue."""
async with self._lock:
self._tasks[task.task_id] = task
await self._queues[task.priority].put(task)
async def get(self) -> Optional[Task]:
"""Get next task from queue (highest priority first)."""
for priority in [TaskPriority.CRITICAL, TaskPriority.HIGH, TaskPriority.NORMAL, TaskPriority.LOW]:
try:
task = self._queues[priority].get_nowait()
return task
except asyncio.QueueEmpty:
continue
return None
async def get_blocking(self, timeout: Optional[float] = None) -> Optional[Task]:
"""Get next task, blocking until one is available."""
start_time = time.time()
while True:
task = await self.get()
if task:
return task
if timeout and (time.time() - start_time) > timeout:
return None
await asyncio.sleep(0.1)
def get_task(self, task_id: str) -> Optional[Task]:
"""Get task by ID."""
return self._tasks.get(task_id)
def update_task(self, task: Task):
"""Update task in storage."""
self._tasks[task.task_id] = task
def get_pending_count(self) -> int:
"""Get number of pending tasks."""
return sum(queue.qsize() for queue in self._queues.values())
def get_all_tasks(self) -> List[Task]:
"""Get all tasks."""
return list(self._tasks.values())
class WorkerPool:
"""Manages a pool of workers for task execution."""
def __init__(
self,
name: str,
max_workers: int = None,
worker_type: str = "thread", # 'thread' or 'process'
task_timeout: int = 300
):
self.name = name
self.max_workers = max_workers or min(32, (multiprocessing.cpu_count() or 1) + 4)
self.worker_type = worker_type
self.task_timeout = task_timeout
if worker_type == "thread":
self.executor = ThreadPoolExecutor(max_workers=self.max_workers, thread_name_prefix=f"{name}_worker")
else:
self.executor = ProcessPoolExecutor(max_workers=self.max_workers)
self._workers: Dict[str, WorkerStats] = {}
self._active_futures: Dict[str, Future] = {}
self._running = False
self._worker_counter = 0
def start(self):
"""Start the worker pool."""
self._running = True
logger.info(f"Worker pool '{self.name}' started with {self.max_workers} {self.worker_type} workers")
def stop(self):
"""Stop the worker pool."""
self._running = False
# Cancel active tasks
for future in self._active_futures.values():
future.cancel()
# Shutdown executor
self.executor.shutdown(wait=True)
logger.info(f"Worker pool '{self.name}' stopped")
async def submit_task(self, task: Task) -> str:
"""Submit task for execution."""
if not self._running:
raise RuntimeError(f"Worker pool '{self.name}' is not running")
worker_id = f"{self.name}_worker_{self._worker_counter}"
self._worker_counter += 1
# Create worker stats
self._workers[worker_id] = WorkerStats(
worker_id=worker_id,
worker_type=self.worker_type,
tasks_completed=0,
tasks_failed=0,
total_execution_time_ms=0,
avg_execution_time_ms=0,
current_task=task.task_id,
is_busy=True,
created_at=datetime.utcnow(),
last_activity=datetime.utcnow()
)
# Submit task to executor
loop = asyncio.get_event_loop()
if asyncio.iscoroutinefunction(task.func):
# For async functions, run in thread pool with asyncio.run
future = self.executor.submit(self._run_async_task, task.func, task.args, task.kwargs)
else:
# For sync functions, run directly
future = self.executor.submit(self._run_sync_task, task.func, task.args, task.kwargs)
self._active_futures[task.task_id] = future
task.worker_id = worker_id
task.started_at = datetime.utcnow()
task.status = TaskStatus.RUNNING
return worker_id
def _run_sync_task(self, func: Callable, args: Tuple, kwargs: Dict[str, Any]) -> Any:
"""Run synchronous task."""
try:
return func(*args, **kwargs)
except Exception as e:
logger.error(f"Task execution failed: {e}")
raise
def _run_async_task(self, func: Callable, args: Tuple, kwargs: Dict[str, Any]) -> Any:
"""Run asynchronous task."""
try:
# Create new event loop for this thread
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(func(*args, **kwargs))
finally:
loop.close()
except Exception as e:
logger.error(f"Async task execution failed: {e}")
raise
def get_task_result(self, task_id: str) -> Tuple[bool, Any, Optional[str]]:
"""Get task result if completed."""
future = self._active_futures.get(task_id)
if not future:
return False, None, "Task not found"
if not future.done():
return False, None, None
try:
result = future.result()
return True, result, None
except Exception as e:
return True, None, str(e)
def cancel_task(self, task_id: str) -> bool:
"""Cancel a running task."""
future = self._active_futures.get(task_id)
if future:
return future.cancel()
return False
def get_worker_stats(self) -> List[WorkerStats]:
"""Get statistics for all workers."""
return list(self._workers.values())
def get_pool_stats(self) -> Dict[str, Any]:
"""Get pool statistics."""
active_tasks = sum(1 for future in self._active_futures.values() if not future.done())
completed_tasks = sum(worker.tasks_completed for worker in self._workers.values())
failed_tasks = sum(worker.tasks_failed for worker in self._workers.values())
return {
'pool_name': self.name,
'worker_type': self.worker_type,
'max_workers': self.max_workers,
'active_workers': len([w for w in self._workers.values() if w.is_busy]),
'total_workers': len(self._workers),
'active_tasks': active_tasks,
'completed_tasks': completed_tasks,
'failed_tasks': failed_tasks,
'success_rate': completed_tasks / (completed_tasks + failed_tasks) if (completed_tasks + failed_tasks) > 0 else 0
}
class ParallelProcessor:
"""Main parallel processing coordinator."""
def __init__(self):
self.task_queue = TaskQueue()
self.worker_pools: Dict[str, WorkerPool] = {}
self._running = False
self._dispatcher_task: Optional[asyncio.Task] = None
self._monitor_task: Optional[asyncio.Task] = None
self._completed_tasks: Dict[str, Task] = {}
# Default pools
self._initialize_default_pools()
def _initialize_default_pools(self):
"""Initialize default worker pools."""
# CPU-intensive tasks (data processing, ML)
self.worker_pools['cpu_intensive'] = WorkerPool(
name='cpu_intensive',
max_workers=multiprocessing.cpu_count(),
worker_type='process',
task_timeout=600 # 10 minutes
)
# I/O-intensive tasks (database, API calls)
self.worker_pools['io_intensive'] = WorkerPool(
name='io_intensive',
max_workers=20,
worker_type='thread',
task_timeout=300 # 5 minutes
)
# General purpose tasks
self.worker_pools['general'] = WorkerPool(
name='general',
max_workers=10,
worker_type='thread',
task_timeout=180 # 3 minutes
)
async def start(self):
"""Start the parallel processor."""
if self._running:
return
self._running = True
# Start worker pools
for pool in self.worker_pools.values():
pool.start()
# Start dispatcher and monitor
self._dispatcher_task = asyncio.create_task(self._dispatch_loop())
self._monitor_task = asyncio.create_task(self._monitor_loop())
logger.info("Parallel processor started")
async def stop(self):
"""Stop the parallel processor."""
self._running = False
# Cancel background tasks
if self._dispatcher_task:
self._dispatcher_task.cancel()
if self._monitor_task:
self._monitor_task.cancel()
# Stop worker pools
for pool in self.worker_pools.values():
pool.stop()
logger.info("Parallel processor stopped")
async def submit_task(
self,
func: Callable,
args: Tuple = (),
kwargs: Dict[str, Any] = None,
task_id: str = None,
priority: TaskPriority = TaskPriority.NORMAL,
pool_name: str = 'general',
timeout_seconds: int = None,
max_retries: int = 3
) -> str:
"""Submit a task for parallel execution."""
task = Task(
task_id=task_id or f"task_{int(time.time() * 1000000)}",
func=func,
args=args,
kwargs=kwargs or {},
priority=priority,
timeout_seconds=timeout_seconds,
max_retries=max_retries
)
# Add pool preference to task
task.pool_preference = pool_name
await self.task_queue.put(task)
logger.debug(f"Submitted task {task.task_id} to {pool_name} pool with priority {priority.name}")
return task.task_id
async def get_task_result(self, task_id: str, timeout: Optional[float] = None) -> Any:
"""Get task result, waiting if necessary."""
start_time = time.time()
while True:
# Check if task is completed
if task_id in self._completed_tasks:
task = self._completed_tasks[task_id]
if task.status == TaskStatus.COMPLETED:
return task.result
elif task.status == TaskStatus.FAILED:
raise Exception(f"Task failed: {task.error}")
elif task.status == TaskStatus.CANCELLED:
raise Exception("Task was cancelled")
# Check timeout
if timeout and (time.time() - start_time) > timeout:
raise TimeoutError(f"Task {task_id} did not complete within {timeout} seconds")
await asyncio.sleep(0.1)
async def cancel_task(self, task_id: str) -> bool:
"""Cancel a task."""
task = self.task_queue.get_task(task_id)
if not task:
return False
if task.status == TaskStatus.PENDING:
task.status = TaskStatus.CANCELLED
self.task_queue.update_task(task)
return True
elif task.status == TaskStatus.RUNNING and task.worker_id:
# Find the pool and cancel
for pool in self.worker_pools.values():
if pool.cancel_task(task_id):
task.status = TaskStatus.CANCELLED
self.task_queue.update_task(task)
return True
return False
async def _dispatch_loop(self):
"""Main task dispatcher loop."""
while self._running:
try:
# Get next task
task = await self.task_queue.get_blocking(timeout=1.0)
if not task:
continue
# Check memory pressure
memory_stats = memory_manager.monitor.get_memory_stats()
if memory_stats.memory_pressure == 'critical':
logger.warning("Critical memory pressure, delaying task dispatch")
await asyncio.sleep(5)
await self.task_queue.put(task) # Put back in queue
continue
# Select appropriate pool
pool_name = getattr(task, 'pool_preference', 'general')
pool = self.worker_pools.get(pool_name, self.worker_pools['general'])
# Submit to worker pool
worker_id = await pool.submit_task(task)
# Start monitoring this task
asyncio.create_task(self._monitor_task_completion(task, pool))
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Task dispatch error: {e}")
async def _monitor_task_completion(self, task: Task, pool: WorkerPool):
"""Monitor a specific task for completion."""
try:
while task.status == TaskStatus.RUNNING:
# Check if task completed
is_done, result, error = pool.get_task_result(task.task_id)
if is_done:
task.completed_at = datetime.utcnow()
if error:
task.status = TaskStatus.FAILED
task.error = error
# Retry if possible
if task.retry_count < task.max_retries:
task.retry_count += 1
task.status = TaskStatus.PENDING
task.started_at = None
task.worker_id = None
await self.task_queue.put(task)
logger.info(f"Retrying task {task.task_id} (attempt {task.retry_count + 1})")
return
else:
task.status = TaskStatus.COMPLETED
task.result = result
# Store completed task
self._completed_tasks[task.task_id] = task
self.task_queue.update_task(task)
# Update worker stats
if task.worker_id and task.worker_id in pool._workers:
worker = pool._workers[task.worker_id]
worker.is_busy = False
worker.current_task = None
worker.last_activity = datetime.utcnow()
if task.status == TaskStatus.COMPLETED:
worker.tasks_completed += 1
else:
worker.tasks_failed += 1
duration = task.get_duration_ms() or 0
worker.total_execution_time_ms += duration
if worker.tasks_completed > 0:
worker.avg_execution_time_ms = worker.total_execution_time_ms / worker.tasks_completed
# Record metrics
monitoring_system.metrics_collector.record_metric(
"parallel_processor.task_completed",
1,
tags={
"pool": pool.name,
"status": task.status.value,
"priority": task.priority.name
}
)
if task.get_duration_ms():
monitoring_system.metrics_collector.record_metric(
"parallel_processor.task_duration_ms",
task.get_duration_ms(),
tags={"pool": pool.name}
)
break
await asyncio.sleep(0.5)
except Exception as e:
logger.error(f"Task monitoring error for {task.task_id}: {e}")
task.status = TaskStatus.FAILED
task.error = str(e)
task.completed_at = datetime.utcnow()
self._completed_tasks[task.task_id] = task
async def _monitor_loop(self):
"""Monitor system resources and worker pools."""
while self._running:
try:
await asyncio.sleep(30) # Monitor every 30 seconds
# Record pool metrics
for pool_name, pool in self.worker_pools.items():
stats = pool.get_pool_stats()
monitoring_system.metrics_collector.record_metric(
"parallel_processor.active_workers",
stats['active_workers'],
tags={"pool": pool_name}
)
monitoring_system.metrics_collector.record_metric(
"parallel_processor.active_tasks",
stats['active_tasks'],
tags={"pool": pool_name}
)
monitoring_system.metrics_collector.record_metric(
"parallel_processor.success_rate",
stats['success_rate'],
tags={"pool": pool_name}
)
# Record queue metrics
monitoring_system.metrics_collector.record_metric(
"parallel_processor.pending_tasks",
self.task_queue.get_pending_count()
)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Parallel processor monitoring error: {e}")
def get_system_stats(self) -> Dict[str, Any]:
"""Get comprehensive system statistics."""
pool_stats = {}
for name, pool in self.worker_pools.items():
pool_stats[name] = pool.get_pool_stats()
all_tasks = self.task_queue.get_all_tasks()
completed_tasks = list(self._completed_tasks.values())
return {
'timestamp': datetime.utcnow().isoformat(),
'pools': pool_stats,
'queue': {
'pending_tasks': self.task_queue.get_pending_count(),
'total_tasks': len(all_tasks),
'completed_tasks': len(completed_tasks),
'running_tasks': len([t for t in all_tasks if t.status == TaskStatus.RUNNING])
},
'performance': {
'avg_task_duration_ms': sum(t.get_duration_ms() or 0 for t in completed_tasks) / len(completed_tasks) if completed_tasks else 0,
'success_rate': len([t for t in completed_tasks if t.status == TaskStatus.COMPLETED]) / len(completed_tasks) if completed_tasks else 0
}
}
# Convenience methods for common parallel patterns
async def map_parallel(
self,
func: Callable,
items: List[Any],
pool_name: str = 'general',
max_concurrent: int = None
) -> List[Any]:
"""Apply function to list of items in parallel."""
if max_concurrent:
semaphore = asyncio.Semaphore(max_concurrent)
else:
semaphore = None
async def process_item(item):
if semaphore:
async with semaphore:
task_id = await self.submit_task(func, args=(item,), pool_name=pool_name)
return await self.get_task_result(task_id)
else:
task_id = await self.submit_task(func, args=(item,), pool_name=pool_name)
return await self.get_task_result(task_id)
tasks = [process_item(item) for item in items]
return await asyncio.gather(*tasks)
async def batch_process(
self,
func: Callable,
items: List[Any],
batch_size: int = 100,
pool_name: str = 'general'
) -> List[Any]:
"""Process items in batches."""
results = []
for i in range(0, len(items), batch_size):
batch = items[i:i + batch_size]
task_id = await self.submit_task(func, args=(batch,), pool_name=pool_name)
batch_result = await self.get_task_result(task_id)
results.extend(batch_result)
return results
async def adaptive_parallel_process(
self,
func: Callable,
items: List[Any],
initial_batch_size: int = 100,
pool_name: str = 'general',
target_duration_seconds: float = 2.0
) -> List[Any]:
"""Process items with adaptive batch sizing based on performance."""
if not items:
return []
results = []
current_batch_size = initial_batch_size
performance_history = []
for i in range(0, len(items), current_batch_size):
batch = items[i:i + current_batch_size]
start_time = time.time()
task_id = await self.submit_task(func, args=(batch,), pool_name=pool_name)
batch_result = await self.get_task_result(task_id)
duration = time.time() - start_time
results.extend(batch_result)
performance_history.append((len(batch), duration))
# Adapt batch size based on performance
if len(performance_history) >= 2:
# Calculate throughput (items per second)
recent_throughput = len(batch) / duration if duration > 0 else 0
if duration > target_duration_seconds * 1.5:
# Too slow, reduce batch size
current_batch_size = max(10, int(current_batch_size * 0.7))
elif duration < target_duration_seconds * 0.5:
# Too fast, increase batch size
current_batch_size = min(len(items), int(current_batch_size * 1.3))
logger.debug(f"Adaptive processing: batch_size={current_batch_size}, duration={duration:.2f}s, throughput={recent_throughput:.1f} items/s")
return results
async def pipeline_process(
self,
pipeline_stages: List[Tuple[str, Callable]],
initial_data: Any,
pool_preferences: Dict[str, str] = None
) -> Any:
"""Process data through a pipeline of stages."""
current_data = initial_data
pool_preferences = pool_preferences or {}
for stage_name, stage_func in pipeline_stages:
pool_name = pool_preferences.get(stage_name, 'general')
logger.info(f"Processing pipeline stage: {stage_name}")
task_id = await self.submit_task(
stage_func,
args=(current_data,),
pool_name=pool_name,
priority=TaskPriority.HIGH # Pipeline stages are high priority
)
current_data = await self.get_task_result(task_id)
logger.info(f"Completed pipeline stage: {stage_name}")
return current_data
async def parallel_reduce(
self,
map_func: Callable,
reduce_func: Callable,
items: List[Any],
chunk_size: int = None,
pool_name: str = 'cpu_intensive'
) -> Any:
"""Parallel map-reduce operation."""
if not items:
return None
# Determine optimal chunk size
if chunk_size is None:
num_workers = self.worker_pools[pool_name].max_workers
chunk_size = max(1, len(items) // (num_workers * 2))
# Map phase - process chunks in parallel
map_tasks = []
for i in range(0, len(items), chunk_size):
chunk = items[i:i + chunk_size]
task_id = await self.submit_task(
map_func,
args=(chunk,),
pool_name=pool_name
)
map_tasks.append(task_id)
# Collect map results
map_results = []
for task_id in map_tasks:
result = await self.get_task_result(task_id)
map_results.append(result)
# Reduce phase - combine results
while len(map_results) > 1:
reduce_tasks = []
# Process pairs of results
for i in range(0, len(map_results), 2):
if i + 1 < len(map_results):
# Pair available
task_id = await self.submit_task(
reduce_func,
args=(map_results[i], map_results[i + 1]),
pool_name=pool_name
)
reduce_tasks.append(task_id)
else:
# Odd one out, keep as is
reduce_tasks.append(map_results[i])
# Collect reduce results
new_results = []
for task_or_result in reduce_tasks:
if isinstance(task_or_result, str): # It's a task ID
result = await self.get_task_result(task_or_result)
new_results.append(result)
else: # It's already a result
new_results.append(task_or_result)
map_results = new_results
return map_results[0] if map_results else None
async def get_performance_recommendations(self) -> Dict[str, Any]:
"""Get performance recommendations for parallel processing."""
stats = self.get_system_stats()
recommendations = []
insights = []
# Analyze pool utilization
for pool_name, pool_stats in stats['pools'].items():
utilization = pool_stats['active_workers'] / pool_stats['max_workers'] if pool_stats['max_workers'] > 0 else 0
if utilization > 0.9:
insights.append(f"Pool '{pool_name}' is highly utilized ({utilization*100:.1f}%)")
recommendations.append(f"Consider increasing max_workers for pool '{pool_name}'")
elif utilization < 0.1 and pool_stats['active_workers'] > 0:
insights.append(f"Pool '{pool_name}' is underutilized ({utilization*100:.1f}%)")
recommendations.append(f"Consider reducing max_workers for pool '{pool_name}' to save resources")
# Analyze task success rates
for pool_name, pool_stats in stats['pools'].items():
if pool_stats['success_rate'] < 0.9:
insights.append(f"Pool '{pool_name}' has low success rate ({pool_stats['success_rate']*100:.1f}%)")
recommendations.append(f"Investigate task failures in pool '{pool_name}'")
recommendations.append(f"Consider increasing timeout or retry settings for pool '{pool_name}'")
# Analyze queue backlog
if stats['queue']['pending_tasks'] > 100:
insights.append(f"Large task queue backlog: {stats['queue']['pending_tasks']} pending tasks")
recommendations.append("Consider increasing worker capacity or optimizing task processing")
# Memory pressure analysis
try:
import psutil
memory_percent = psutil.virtual_memory().percent
if memory_percent > 85:
insights.append(f"High system memory usage: {memory_percent:.1f}%")
recommendations.append("Consider using process-based workers instead of threads for memory-intensive tasks")
recommendations.append("Implement memory cleanup between tasks")
except:
pass
return {
'timestamp': datetime.utcnow().isoformat(),
'insights': insights,
'recommendations': recommendations,
'current_stats': stats
}
# Global parallel processor instance
parallel_processor = ParallelProcessor()