| {-| | |
| Module : KAR.ErrorRecovery | |
| Description : استراتيجية الاسترداد من الأخطاء | Error Recovery Strategy | |
| Copyright : (c) Ahmad Ali Parr, 2026 | |
| License : Proprietary | |
| Maintainer : ahmedparr93@gmail.com | |
| Autonomous error recovery strategies. When intent execution fails, | |
| determines recovery action (retry, fallback, or graceful failure). | |
| استراتيجيات الاسترداد الذاتي من الأخطاء | |
| -} | |
| module KAR.ErrorRecovery | |
| ( selectRecoveryStrategy | |
| , ErrorContext(..) | |
| , canRetry | |
| , shouldFallback | |
| ) where | |
| import KAR.Types.Intent | |
| import KAR.Types.Decision (RecoveryStrategy(..)) | |
| import Data.Word (Word32) | |
| -- | Error context (why execution failed) | |
| data ErrorContext | |
| = ResourceExhausted -- ^ Ran out of resources (retry later) | |
| | TimeoutExpired -- ^ Execution timeout (retry or fail) | |
| | AgentCrashed Word32 -- ^ Agent crashed (fallback to another) | |
| | InvalidPayload -- ^ Malformed payload (fail immediately) | |
| | TrustViolation -- ^ Trust check failed (fail immediately) | |
| | UnknownError -- ^ Unknown error (retry once) | |
| deriving (Eq, Show) | |
| -- | Select recovery strategy based on error context and intent | |
| -- اختيار استراتيجية الاسترداد | |
| selectRecoveryStrategy | |
| :: ErrorContext | |
| -> Intent | |
| -> Int -- ^ Retry count so far | |
| -> RecoveryStrategy | |
| selectRecoveryStrategy errCtx intent retryCount = | |
| case errCtx of | |
| ResourceExhausted -> | |
| if retryCount < 3 | |
| then RetryWithBackoff (exponentialBackoff retryCount) | |
| else GracefulFail | |
| TimeoutExpired -> | |
| case intentPriority intent of | |
| Critical -> RetryImmediate -- Critical always retries | |
| High -> if retryCount < 2 | |
| then RetryWithBackoff 1000 | |
| else GracefulFail | |
| _ -> GracefulFail | |
| AgentCrashed agentId -> | |
| -- Try fallback to different agent | |
| FallbackAgent ((agentId + 1) `mod` 6) | |
| InvalidPayload -> | |
| -- No recovery possible for malformed input | |
| GracefulFail | |
| TrustViolation -> | |
| -- Security violation, no retry | |
| GracefulFail | |
| UnknownError -> | |
| if retryCount == 0 | |
| then RetryImmediate | |
| else GracefulFail | |
| -- | Check if intent can be retried | |
| -- التحقق من إمكانية إعادة المحاولة | |
| canRetry :: ErrorContext -> Bool | |
| canRetry ResourceExhausted = True | |
| canRetry TimeoutExpired = True | |
| canRetry UnknownError = True | |
| canRetry _ = False | |
| -- | Check if should attempt fallback agent | |
| -- التحقق من الحاجة للعامل الاحتياطي | |
| shouldFallback :: ErrorContext -> Bool | |
| shouldFallback (AgentCrashed _) = True | |
| shouldFallback _ = False | |
| -- | Exponential backoff calculation | |
| -- حساب التأخير الأسي | |
| exponentialBackoff :: Int -> Word32 | |
| exponentialBackoff n = | |
| let base = 500 -- 500ms base | |
| multiplier = 2 ^ min n 5 -- Cap at 2^5 = 32x | |
| in base * fromIntegral multiplier | |