File size: 33,855 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
"""

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()