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

1""" 

2Comprehensive timeout management system for async operations. 

3 

4This module provides timeout handling, circuit breaker patterns, and 

5graceful degradation for all async operations in crackerjack. 

6""" 

7 

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 

17 

18logger = logging.getLogger("crackerjack.timeout_manager") 

19 

20 

21class _DummyPerformanceMonitor: 

22 """Dummy performance monitor to avoid circular import issues.""" 

23 

24 def record_operation_start(self, operation: str) -> float: 

25 return time.time() 

26 

27 def record_operation_success(self, operation: str, start_time: float) -> None: 

28 pass 

29 

30 def record_operation_failure(self, operation: str, start_time: float) -> None: 

31 pass 

32 

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 

41 

42 def record_circuit_breaker_event(self, operation: str, opened: bool) -> None: 

43 pass 

44 

45 

46class TimeoutStrategy(Enum): 

47 """Timeout handling strategies.""" 

48 

49 FAIL_FAST = "fail_fast" 

50 RETRY_WITH_BACKOFF = "retry_with_backoff" 

51 CIRCUIT_BREAKER = "circuit_breaker" 

52 GRACEFUL_DEGRADATION = "graceful_degradation" 

53 

54 

55class CircuitBreakerState(Enum): 

56 """Circuit breaker states.""" 

57 

58 CLOSED = "closed" # Normal operation 

59 OPEN = "open" # Failing fast 

60 HALF_OPEN = "half_open" # Testing if service recovered 

61 

62 

63@dataclass 

64class TimeoutConfig: 

65 """Configuration for timeout handling.""" 

66 

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 ) 

82 

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 

88 

89 # Circuit breaker configuration 

90 failure_threshold: int = 5 

91 recovery_timeout: float = 60.0 

92 half_open_max_calls: int = 3 

93 

94 

95@dataclass 

96class CircuitBreakerState: 

97 """State of a circuit breaker.""" 

98 

99 state: CircuitBreakerState = CircuitBreakerState.CLOSED 

100 failure_count: int = 0 

101 last_failure_time: float = 0.0 

102 half_open_calls: int = 0 

103 

104 

105class TimeoutError(Exception): 

106 """Custom timeout error with context.""" 

107 

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 ) 

116 

117 

118class AsyncTimeoutManager: 

119 """Comprehensive async timeout and circuit breaker manager.""" 

120 

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]] = {} 

125 

126 # Initialize performance monitor lazily to avoid circular imports 

127 self._performance_monitor = None 

128 

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 ) 

134 

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 

141 

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 

147 

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) 

158 

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 

165 

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 

185 

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) 

190 

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) 

197 

198 if strategy == TimeoutStrategy.CIRCUIT_BREAKER: 

199 self._update_circuit_breaker(operation, False) 

200 

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 

207 

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) 

213 

214 if strategy == TimeoutStrategy.CIRCUIT_BREAKER: 

215 self._update_circuit_breaker(operation, False) 

216 

217 raise 

218 

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) 

230 

231 timeout_value = timeout or self.get_timeout(operation) 

232 start_time = self.performance_monitor.record_operation_start(operation) 

233 

234 try: 

235 # Wrap coroutine execution with timeout protection 

236 result = await asyncio.wait_for(coro, timeout=timeout_value) 

237 

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) 

242 

243 if strategy == TimeoutStrategy.CIRCUIT_BREAKER: 

244 self._update_circuit_breaker(operation, True) 

245 

246 return result 

247 

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) 

254 

255 if strategy == TimeoutStrategy.CIRCUIT_BREAKER: 

256 self._update_circuit_breaker(operation, False) 

257 

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 

264 

265 raise TimeoutError(operation, timeout_value, elapsed) from e 

266 

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) 

271 

272 if strategy == TimeoutStrategy.CIRCUIT_BREAKER: 

273 self._update_circuit_breaker(operation, False) 

274 

275 raise 

276 

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 

286 

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 

294 

295 if attempt == self.config.max_retries: 

296 break 

297 

298 logger.warning( 

299 f"Attempt {attempt + 1}/{self.config.max_retries + 1} " 

300 f"failed for {operation}: {e}, retrying in {delay}s" 

301 ) 

302 

303 await asyncio.sleep(delay) 

304 delay = min( 

305 delay * self.config.backoff_multiplier, self.config.max_retry_delay 

306 ) 

307 

308 raise last_exception 

309 

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 

315 

316 breaker = self.circuit_breakers[operation] 

317 current_time = time.time() 

318 

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 

332 

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

337 

338 breaker = self.circuit_breakers[operation] 

339 previous_state = breaker.state 

340 

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

350 

351 if breaker.failure_count >= self.config.failure_threshold: 

352 breaker.state = CircuitBreakerState.OPEN 

353 

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 ) 

359 

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] = [] 

364 

365 stats = self.operation_stats[operation] 

366 stats.append(elapsed) 

367 

368 # Keep only recent stats (last 100 operations) 

369 if len(stats) > 100: 

370 stats.pop(0) 

371 

372 if self.config.operation_timeouts.get(operation): 

373 self._update_circuit_breaker(operation, True) 

374 

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 ) 

381 

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 } 

393 

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 } 

407 

408 

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.""" 

417 

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 ) 

427 

428 return wrapper 

429 

430 return decorator 

431 

432 

433# Global timeout manager instance 

434_global_timeout_manager: AsyncTimeoutManager | None = None 

435 

436 

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 

443 

444 

445def configure_timeouts(config: TimeoutConfig) -> None: 

446 """Configure global timeout manager.""" 

447 global _global_timeout_manager 

448 _global_timeout_manager = AsyncTimeoutManager(config) 

449 

450 

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 

455 

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 }