# Subtask: Task Retry and Error Handling **Parent Task**: Decomp/003 **Subtask ID**: Decomp/003-04 **Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-03 (Task Worker Implementation) ## Description Implement automatic retry logic for failed tasks with exponential backoff. Support configurable retry policies per task type, exception-based retry conditions, and manual retry triggering. ## Requirements - Automatic retry on task failure - Exponential backoff with jitter - Configurable max retries per task - Exception-based retry conditions (retry on specific exceptions only) - Manual retry capability for failed tasks - Retry history tracking - Dead letter queue for permanently failed tasks - Retry backoff storage (scheduled retry time) ## Technical Specifications **Retry policy configuration**: ```python from dataclasses import dataclass from typing import Type, Tuple, Set, Optional, Callable from enum import Enum class BackoffStrategy(Enum): """Backoff strategies for retries.""" EXPONENTIAL = "exponential" # 2^retry_count * base LINEAR = "linear" # retry_count * base FIBONACCI = "fibonacci" # Fibonacci sequence FIXED = "fixed" # Always the same delay @dataclass class RetryPolicy: """Configuration for task retry behavior.""" max_retries: int = 3 backoff_base: int = 60 # Base delay in seconds backoff_max: int = 3600 # Maximum delay in seconds backoff_strategy: BackoffStrategy = BackoffStrategy.EXPONENTIAL jitter: bool = True # Add randomness to prevent thundering herd retry_on_exceptions: Optional[Tuple[Type[Exception], ...]] = None # None = retry on all retry_on_exception_callback: Optional[Callable[[Exception], bool]] = None def should_retry(self, exception: Exception, retry_count: int) -> bool: """Determine if task should be retried.""" if retry_count >= self.max_retries: return False if self.retry_on_exceptions is not None: return isinstance(exception, self.retry_on_exceptions) if self.retry_on_exception_callback is not None: return self.retry_on_exception_callback(exception) return True def get_backoff_delay(self, retry_count: int) -> int: """Calculate backoff delay for given retry count.""" if self.backoff_strategy == BackoffStrategy.EXPONENTIAL: delay = self.backoff_base * (2 ** retry_count) elif self.backoff_strategy == BackoffStrategy.LINEAR: delay = self.backoff_base * (retry_count + 1) elif self.backoff_strategy == BackoffStrategy.FIBONACCI: delay = self.backoff_base * self._fibonacci(retry_count + 1) else: # FIXED delay = self.backoff_base delay = min(delay, self.backoff_max) # Add jitter: ±25% random variation if self.jitter: import random delay = int(delay * (0.75 + random.random() * 0.5)) return delay @staticmethod def _fibonacci(n: int) -> int: """Calculate nth Fibonacci number.""" a, b = 0, 1 for _ in range(n): a, b = b, a + b return a # Default retry policies DEFAULT_RETRY_POLICY = RetryPolicy(max_retries=3) NO_RETRY_POLICY = RetryPolicy(max_retries=0) AGGRESSIVE_RETRY_POLICY = RetryPolicy( max_retries=10, backoff_base=30, backoff_max=1800 ) ``` **Retry handler implementation**: ```python import asyncio from datetime import datetime, timedelta, timezone from typing import Optional import logging logger = logging.getLogger(__name__) class RetryHandler: """Handles task retry logic.""" def __init__(self, db, broker): self.db = db self.broker = broker async def handle_task_failure( self, task_id: str, exception: Exception, retry_count: int, max_retries: int, traceback: Optional[str] = None ) -> bool: """ Handle a failed task and determine if it should be retried. Returns: True if task was scheduled for retry, False if sent to DLQ """ # Get retry policy for this task type from .producer import TASK_REGISTRY task_name = await self._get_task_name(task_id) task_info = TASK_REGISTRY.get(task_name, {}) retry_policy = task_info.get("retry_policy", DEFAULT_RETRY_POLICY) # Override max_retries from task if specified if max_retries != retry_policy.max_retries: retry_policy = RetryPolicy( max_retries=max_retries, backoff_base=retry_policy.backoff_base, backoff_max=retry_policy.backoff_max, backoff_strategy=retry_policy.backoff_strategy, jitter=retry_policy.jitter ) # Check if should retry if not retry_policy.should_retry(exception, retry_count): logger.info(f"Task {task_id} will not be retried (max retries or non-retryable exception)") await self._send_to_dlq(task_id, exception, traceback) return False # Calculate backoff delay delay = retry_policy.get_backoff_delay(retry_count) retry_at = datetime.now(timezone.utc) + timedelta(seconds=delay) # Schedule retry await self._schedule_retry(task_id, retry_count + 1, retry_at) logger.info( f"Task {task_id} scheduled for retry at {retry_at.isoformat()} " f"(attempt {retry_count + 1}/{max_retries}, delay: {delay}s)" ) return True async def _schedule_retry(self, task_id: str, retry_count: int, retry_at: datetime): """Schedule a task for retry.""" async with self.db.acquire() as conn: await conn.execute( """UPDATE tasks SET status = 'pending', retry_count = $1, scheduled_at = $2, error = NULL, traceback = NULL, worker_id = NULL, started_at = NULL WHERE id = $3""", retry_count, retry_at, task_id ) # Log retry in history await conn.execute( """INSERT INTO task_history (task_id, status, details) VALUES ($1, 'retry', $2)""", task_id, {"retry_count": retry_count, "scheduled_at": retry_at.isoformat()} ) async def _send_to_dlq(self, task_id: str, exception: Exception, traceback: Optional[str]): """Send failed task to dead letter queue.""" async with self.db.acquire() as conn: # Update task status await conn.execute( """UPDATE tasks SET status = 'failed', completed_at = NOW() WHERE id = $1""", task_id ) # Add to DLQ table await conn.execute( """INSERT INTO dead_letter_queue (task_id, error, traceback, failed_at) VALUES ($1, $2, $3, NOW()) ON CONFLICT (task_id) DO NOTHING""", task_id, str(exception), traceback ) # Log in history await conn.execute( """INSERT INTO task_history (task_id, status, details) VALUES ($1, 'dead_lettered', $2)""", task_id, {"error": str(exception)} ) logger.warning(f"Task {task_id} sent to dead letter queue") async def _get_task_name(self, task_id: str) -> str: """Get task name from database.""" async with self.db.acquire() as conn: return await conn.fetchval( "SELECT task_name FROM tasks WHERE id = $1", task_id ) async def manual_retry(self, task_id: str) -> bool: """ Manually retry a failed task. Returns: True if retry was scheduled """ async with self.db.acquire() as conn: # Check if task exists and is failed row = await conn.fetchrow( """SELECT id, status, retry_count, max_retries FROM tasks WHERE id = $1""", task_id ) if not row: raise ValueError(f"Task {task_id} not found") if row["status"] not in ("failed", "cancelled"): raise ValueError(f"Cannot retry task with status: {row['status']}") # Reset task for retry await conn.execute( """UPDATE tasks SET status = 'pending', retry_count = 0, scheduled_at = NOW(), error = NULL, traceback = NULL, worker_id = NULL, started_at = NULL, completed_at = NULL WHERE id = $1""", task_id ) # Remove from DLQ if present await conn.execute( "DELETE FROM dead_letter_queue WHERE task_id = $1", task_id ) # Get queue name and add to broker queue_name = await conn.fetchval( """SELECT tq.name FROM tasks t JOIN task_queues tq ON t.queue_id = tq.id WHERE t.id = $1""", task_id ) if queue_name: await self.broker.enqueue(queue_name, task_id) # Log manual retry await conn.execute( """INSERT INTO task_history (task_id, status, details) VALUES ($1, 'manual_retry', $2)""", task_id, {"timestamp": datetime.now(timezone.utc).isoformat()} ) logger.info(f"Task {task_id} manually queued for retry") return True async def retry_all_dlq(self, limit: int = 100) -> int: """ Retry all tasks in dead letter queue. Returns: Number of tasks scheduled for retry """ async with self.db.acquire() as conn: # Get tasks from DLQ rows = await conn.fetch( """SELECT task_id FROM dead_letter_queue ORDER BY failed_at LIMIT $1""", limit ) retried = 0 for row in rows: task_id = row["task_id"] try: await self.manual_retry(task_id) retried += 1 except Exception as e: logger.error(f"Failed to retry task {task_id}: {e}") return retried ``` **Integration with worker**: ```python # Modify TaskWorker._execute_task to use RetryHandler async def _execute_task(self, task: dict): """Execute a single task with retry handling.""" task_id = task["id"] task_name = task["task_name"] args = self._deserialize_args(task["args"]) kwargs = self._deserialize_args(task["kwargs"]) retry_count = task.get("retry_count", 0) max_retries = task.get("max_retries", 3) logger.info(f"Executing task {task_id}: {task_name} (attempt {retry_count + 1})") # Mark as running await self._mark_task_running(task_id) # Get task function from .producer import TASK_REGISTRY task_info = TASK_REGISTRY.get(task_name) if not task_info: error = ValueError(f"Task function not registered: {task_name}") await self.retry_handler.handle_task_failure( task_id, error, retry_count, max_retries ) return func = task_info["func"] # Execute with timeout timeout = self.config.task_timeout try: if asyncio.iscoroutinefunction(func): if timeout: result = await asyncio.wait_for( func(*args, **kwargs), timeout=timeout ) else: result = await func(*args, **kwargs) else: if timeout: result = await asyncio.wait_for( asyncio.to_thread(func, *args, **kwargs), timeout=timeout ) else: result = await asyncio.to_thread(func, *args, **kwargs) # Mark as completed await self._mark_task_completed(task_id, result) logger.info(f"Task {task_id} completed successfully") except Exception as e: tb = traceback.format_exc() logger.error(f"Task {task_id} failed: {e}") # Handle retry or send to DLQ await self.retry_handler.handle_task_failure( task_id, e, retry_count, max_retries, tb ) ``` **Database extension for DLQ**: ```sql -- Dead letter queue table CREATE TABLE dead_letter_queue ( id BIGSERIAL PRIMARY KEY, task_id BIGINT NOT NULL UNIQUE REFERENCES tasks(id) ON DELETE CASCADE, error TEXT NOT NULL, traceback TEXT, failed_at TIMESTAMP NOT NULL DEFAULT NOW(), retry_count INTEGER DEFAULT 0, last_retry_at TIMESTAMP, metadata JSONB DEFAULT '{}'::jsonb ); CREATE INDEX idx_dlq_failed_at ON dead_letter_queue(failed_at DESC); ``` ## Acceptance Criteria - [ ] Failed tasks are automatically retried up to max_retries - [ ] Exponential backoff delay is calculated correctly - [ ] Jitter is applied to prevent thundering herd - [ ] Tasks exceeding max retries go to DLQ - [ ] Manual retry can re-queue failed tasks - [ ] Retry history is tracked in task_history - [ ] Exception-based retry conditions work ## Notes **Trade-offs**: - Jitter vs deterministic scheduling: Jitter preferred for distributed systems - Immediate vs scheduled retry: Scheduled to avoid overwhelming workers **Performance**: - Batch DLQ retries to avoid spikes **Alternatives considered**: - Celery-style autoretry_for: Similar approach adopted - Immediate retry: Rejected, can cause cascading failures