Coverage for /Users/les/Projects/crackerjack/crackerjack/core/timeout_manager.py: 0%
220 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1"""
2Comprehensive timeout management system for async operations.
4This module provides timeout handling, circuit breaker patterns, and
5graceful degradation for all async operations in crackerjack.
6"""
8import asyncio
9import builtins
10import logging
11import time
12import typing as t
13from contextlib import asynccontextmanager
14from dataclasses import dataclass, field
15from enum import Enum
16from functools import wraps
18logger = logging.getLogger("crackerjack.timeout_manager")
21class _DummyPerformanceMonitor:
22 """Dummy performance monitor to avoid circular import issues."""
24 def record_operation_start(self, operation: str) -> float:
25 return time.time()
27 def record_operation_success(self, operation: str, start_time: float) -> None:
28 pass
30 def record_operation_failure(self, operation: str, start_time: float) -> None:
31 pass
33 def record_operation_timeout(
34 self,
35 operation: str,
36 start_time: float,
37 timeout_value: float,
38 error_message: str,
39 ) -> None:
40 pass
42 def record_circuit_breaker_event(self, operation: str, opened: bool) -> None:
43 pass
46class TimeoutStrategy(Enum):
47 """Timeout handling strategies."""
49 FAIL_FAST = "fail_fast"
50 RETRY_WITH_BACKOFF = "retry_with_backoff"
51 CIRCUIT_BREAKER = "circuit_breaker"
52 GRACEFUL_DEGRADATION = "graceful_degradation"
55class CircuitBreakerState(Enum):
56 """Circuit breaker states."""
58 CLOSED = "closed" # Normal operation
59 OPEN = "open" # Failing fast
60 HALF_OPEN = "half_open" # Testing if service recovered
63@dataclass
64class TimeoutConfig:
65 """Configuration for timeout handling."""
67 # Basic timeout settings
68 default_timeout: float = 30.0
69 operation_timeouts: dict[str, float] = field(
70 default_factory=lambda: {
71 "fast_hooks": 60.0,
72 "comprehensive_hooks": 300.0,
73 "test_execution": 600.0,
74 "ai_agent_processing": 180.0,
75 "file_operations": 10.0,
76 "network_operations": 15.0,
77 "websocket_broadcast": 5.0,
78 "workflow_iteration": 900.0, # 15 minutes
79 "complete_workflow": 3600.0, # 1 hour
80 }
81 )
83 # Retry configuration
84 max_retries: int = 3
85 base_retry_delay: float = 1.0
86 max_retry_delay: float = 60.0
87 backoff_multiplier: float = 2.0
89 # Circuit breaker configuration
90 failure_threshold: int = 5
91 recovery_timeout: float = 60.0
92 half_open_max_calls: int = 3
95@dataclass
96class CircuitBreakerState:
97 """State of a circuit breaker."""
99 state: CircuitBreakerState = CircuitBreakerState.CLOSED
100 failure_count: int = 0
101 last_failure_time: float = 0.0
102 half_open_calls: int = 0
105class TimeoutError(Exception):
106 """Custom timeout error with context."""
108 def __init__(self, operation: str, timeout: float, elapsed: float = 0.0) -> None:
109 self.operation = operation
110 self.timeout = timeout
111 self.elapsed = elapsed
112 super().__init__(
113 f"Operation '{operation}' timed out after {timeout}s "
114 f"(elapsed: {elapsed:.1f}s)"
115 )
118class AsyncTimeoutManager:
119 """Comprehensive async timeout and circuit breaker manager."""
121 def __init__(self, config: TimeoutConfig | None = None) -> None:
122 self.config = config or TimeoutConfig()
123 self.circuit_breakers: dict[str, CircuitBreakerState] = {}
124 self.operation_stats: dict[str, list[float]] = {}
126 # Initialize performance monitor lazily to avoid circular imports
127 self._performance_monitor = None
129 def get_timeout(self, operation: str) -> float:
130 """Get timeout for specific operation."""
131 return self.config.operation_timeouts.get(
132 operation, self.config.default_timeout
133 )
135 @property
136 def performance_monitor(self):
137 """Lazy-load performance monitor to avoid circular imports."""
138 if self._performance_monitor is None:
139 try:
140 from .performance_monitor import get_performance_monitor
142 self._performance_monitor = get_performance_monitor()
143 except ImportError:
144 # If performance monitor is not available, create a dummy implementation
145 self._performance_monitor = _DummyPerformanceMonitor()
146 return self._performance_monitor
148 @asynccontextmanager
149 async def timeout_context(
150 self,
151 operation: str,
152 timeout: float | None = None,
153 strategy: TimeoutStrategy = TimeoutStrategy.FAIL_FAST,
154 ) -> t.AsyncIterator[None]:
155 """Context manager for timeout handling with strategy."""
156 timeout_value = timeout or self.get_timeout(operation)
157 start_time = self.performance_monitor.record_operation_start(operation)
159 # Add additional protection against very long operations
160 if timeout_value > 7200.0: # 2 hours maximum
161 logger.warning(
162 f"Capping excessive timeout for {operation}: {timeout_value}s -> 7200s"
163 )
164 timeout_value = 7200.0
166 try:
167 # Use asyncio.timeout for Python 3.11+ or asyncio.wait_for fallback
168 try:
169 async with asyncio.timeout(timeout_value):
170 yield
171 except AttributeError:
172 # Fallback for older Python versions without asyncio.timeout
173 task = asyncio.current_task()
174 if task:
175 try:
176 await asyncio.wait_for(
177 asyncio.shield(task), timeout=timeout_value
178 )
179 yield
180 except builtins.TimeoutError:
181 raise builtins.TimeoutError(f"Operation {operation} timed out")
182 else:
183 # Direct yield if no current task context
184 yield
186 # Record successful operation
187 self.performance_monitor.record_operation_success(operation, start_time)
188 elapsed = time.time() - start_time
189 self._record_success(operation, elapsed)
191 except (asyncio.TimeoutError, asyncio.CancelledError) as e:
192 elapsed = time.time() - start_time
193 self.performance_monitor.record_operation_timeout(
194 operation, start_time, timeout_value, str(e)
195 )
196 self._record_failure(operation, elapsed)
198 if strategy == TimeoutStrategy.CIRCUIT_BREAKER:
199 self._update_circuit_breaker(operation, False)
201 # Handle graceful degradation
202 if strategy == TimeoutStrategy.GRACEFUL_DEGRADATION:
203 logger.warning(
204 f"Operation {operation} timed out ({elapsed:.1f}s), continuing gracefully"
205 )
206 return # Exit gracefully without raising
208 raise TimeoutError(operation, timeout_value, elapsed) from e
209 except Exception:
210 self.performance_monitor.record_operation_failure(operation, start_time)
211 elapsed = time.time() - start_time
212 self._record_failure(operation, elapsed)
214 if strategy == TimeoutStrategy.CIRCUIT_BREAKER:
215 self._update_circuit_breaker(operation, False)
217 raise
219 async def with_timeout(
220 self,
221 operation: str,
222 coro: t.Awaitable[t.Any],
223 timeout: float | None = None,
224 strategy: TimeoutStrategy = TimeoutStrategy.FAIL_FAST,
225 ) -> t.Any:
226 """Execute coroutine with timeout and strategy."""
227 if strategy == TimeoutStrategy.CIRCUIT_BREAKER:
228 if not self._check_circuit_breaker(operation):
229 raise TimeoutError(operation, 0.0, 0.0)
231 timeout_value = timeout or self.get_timeout(operation)
232 start_time = self.performance_monitor.record_operation_start(operation)
234 try:
235 # Wrap coroutine execution with timeout protection
236 result = await asyncio.wait_for(coro, timeout=timeout_value)
238 # Record success
239 self.performance_monitor.record_operation_success(operation, start_time)
240 elapsed = time.time() - start_time
241 self._record_success(operation, elapsed)
243 if strategy == TimeoutStrategy.CIRCUIT_BREAKER:
244 self._update_circuit_breaker(operation, True)
246 return result
248 except builtins.TimeoutError as e:
249 elapsed = time.time() - start_time
250 self.performance_monitor.record_operation_timeout(
251 operation, start_time, timeout_value, str(e)
252 )
253 self._record_failure(operation, elapsed)
255 if strategy == TimeoutStrategy.CIRCUIT_BREAKER:
256 self._update_circuit_breaker(operation, False)
258 # Handle graceful degradation
259 if strategy == TimeoutStrategy.GRACEFUL_DEGRADATION:
260 logger.warning(
261 f"Operation {operation} timed out ({elapsed:.1f}s), returning None"
262 )
263 return None
265 raise TimeoutError(operation, timeout_value, elapsed) from e
267 except Exception:
268 self.performance_monitor.record_operation_failure(operation, start_time)
269 elapsed = time.time() - start_time
270 self._record_failure(operation, elapsed)
272 if strategy == TimeoutStrategy.CIRCUIT_BREAKER:
273 self._update_circuit_breaker(operation, False)
275 raise
277 async def _with_retry(
278 self,
279 operation: str,
280 coro_factory: t.Callable[[], t.Awaitable[t.Any]],
281 timeout: float | None = None,
282 ) -> t.Any:
283 """Execute with exponential backoff retry."""
284 last_exception = None
285 delay = self.config.base_retry_delay
287 for attempt in range(self.config.max_retries + 1):
288 try:
289 async with self.timeout_context(operation, timeout):
290 # Create a new coroutine for each attempt
291 return await coro_factory()
292 except (TimeoutError, Exception) as e:
293 last_exception = e
295 if attempt == self.config.max_retries:
296 break
298 logger.warning(
299 f"Attempt {attempt + 1}/{self.config.max_retries + 1} "
300 f"failed for {operation}: {e}, retrying in {delay}s"
301 )
303 await asyncio.sleep(delay)
304 delay = min(
305 delay * self.config.backoff_multiplier, self.config.max_retry_delay
306 )
308 raise last_exception
310 def _check_circuit_breaker(self, operation: str) -> bool:
311 """Check if circuit breaker allows operation."""
312 if operation not in self.circuit_breakers:
313 self.circuit_breakers[operation] = CircuitBreakerState()
314 return True
316 breaker = self.circuit_breakers[operation]
317 current_time = time.time()
319 if breaker.state == CircuitBreakerState.CLOSED:
320 return True
321 elif breaker.state == CircuitBreakerState.OPEN:
322 if current_time - breaker.last_failure_time > self.config.recovery_timeout:
323 breaker.state = CircuitBreakerState.HALF_OPEN
324 breaker.half_open_calls = 0
325 return True
326 return False
327 else: # HALF_OPEN
328 if breaker.half_open_calls < self.config.half_open_max_calls:
329 breaker.half_open_calls += 1
330 return True
331 return False
333 def _update_circuit_breaker(self, operation: str, success: bool) -> None:
334 """Update circuit breaker state based on operation result."""
335 if operation not in self.circuit_breakers:
336 self.circuit_breakers[operation] = CircuitBreakerState()
338 breaker = self.circuit_breakers[operation]
339 previous_state = breaker.state
341 if success:
342 if breaker.state == CircuitBreakerState.HALF_OPEN:
343 breaker.state = CircuitBreakerState.CLOSED
344 breaker.failure_count = 0
345 elif breaker.state == CircuitBreakerState.CLOSED:
346 breaker.failure_count = max(0, breaker.failure_count - 1)
347 else:
348 breaker.failure_count += 1
349 breaker.last_failure_time = time.time()
351 if breaker.failure_count >= self.config.failure_threshold:
352 breaker.state = CircuitBreakerState.OPEN
354 # Record circuit breaker event if state changed
355 if previous_state != CircuitBreakerState.OPEN:
356 self.performance_monitor.record_circuit_breaker_event(
357 operation, True
358 )
360 def _record_success(self, operation: str, elapsed: float) -> None:
361 """Record successful operation timing."""
362 if operation not in self.operation_stats:
363 self.operation_stats[operation] = []
365 stats = self.operation_stats[operation]
366 stats.append(elapsed)
368 # Keep only recent stats (last 100 operations)
369 if len(stats) > 100:
370 stats.pop(0)
372 if self.config.operation_timeouts.get(operation):
373 self._update_circuit_breaker(operation, True)
375 def _record_failure(self, operation: str, elapsed: float) -> None:
376 """Record failed operation timing."""
377 logger.warning(
378 f"Operation '{operation}' failed after {elapsed:.1f}s "
379 f"(timeout: {self.get_timeout(operation)}s)"
380 )
382 def get_stats(self, operation: str) -> dict[str, t.Any]:
383 """Get performance statistics for operation."""
384 stats = self.operation_stats.get(operation, [])
385 if not stats:
386 return {
387 "count": 0,
388 "avg_time": 0.0,
389 "min_time": 0.0,
390 "max_time": 0.0,
391 "success_rate": 0.0,
392 }
394 return {
395 "count": len(stats),
396 "avg_time": sum(stats) / len(stats),
397 "min_time": min(stats),
398 "max_time": max(stats),
399 "success_rate": len(stats)
400 / (
401 len(stats)
402 + self.circuit_breakers.get(
403 operation, CircuitBreakerState()
404 ).failure_count
405 ),
406 }
409def timeout_async(
410 operation: str,
411 timeout: float | None = None,
412 strategy: TimeoutStrategy = TimeoutStrategy.FAIL_FAST,
413) -> t.Callable[
414 [t.Callable[..., t.Awaitable[t.Any]]], t.Callable[..., t.Awaitable[t.Any]]
415]:
416 """Decorator for async functions with timeout handling."""
418 def decorator(
419 func: t.Callable[..., t.Awaitable[t.Any]],
420 ) -> t.Callable[..., t.Awaitable[t.Any]]:
421 @wraps(func)
422 async def wrapper(*args, **kwargs) -> t.Any:
423 manager = AsyncTimeoutManager()
424 return await manager.with_timeout(
425 operation, func(*args, **kwargs), timeout, strategy
426 )
428 return wrapper
430 return decorator
433# Global timeout manager instance
434_global_timeout_manager: AsyncTimeoutManager | None = None
437def get_timeout_manager() -> AsyncTimeoutManager:
438 """Get global timeout manager instance."""
439 global _global_timeout_manager
440 if _global_timeout_manager is None:
441 _global_timeout_manager = AsyncTimeoutManager()
442 return _global_timeout_manager
445def configure_timeouts(config: TimeoutConfig) -> None:
446 """Configure global timeout manager."""
447 global _global_timeout_manager
448 _global_timeout_manager = AsyncTimeoutManager(config)
451def get_performance_report() -> dict[str, t.Any]:
452 """Get comprehensive performance report."""
453 timeout_manager = get_timeout_manager()
454 monitor = timeout_manager.performance_monitor
456 return {
457 "summary": monitor.get_summary_stats(),
458 "metrics": {
459 name: {
460 "success_rate": m.success_rate,
461 "average_time": m.average_time,
462 "recent_average_time": m.recent_average_time,
463 "total_calls": m.total_calls,
464 "timeout_calls": m.timeout_calls,
465 }
466 for name, m in monitor.get_all_metrics().items()
467 },
468 "alerts": monitor.get_performance_alerts(),
469 "recent_timeouts": [
470 {
471 "operation": event.operation,
472 "expected_timeout": event.expected_timeout,
473 "actual_duration": event.actual_duration,
474 "timestamp": event.timestamp,
475 }
476 for event in monitor.get_recent_timeout_events(10)
477 ],
478 "circuit_breakers": {
479 operation: {
480 "state": breaker.state.value,
481 "failure_count": breaker.failure_count,
482 "last_failure_time": breaker.last_failure_time,
483 }
484 for operation, breaker in timeout_manager.circuit_breakers.items()
485 },
486 }