Initial commit: Test GLM project
This commit is contained in:
@@ -0,0 +1,515 @@
|
||||
# Subtask: Dead Letter Queue and Recovery
|
||||
|
||||
**Parent Task**: Decomp/003
|
||||
**Subtask ID**: Decomp/003-08
|
||||
**Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-04 (Task Retry and Error Handling)
|
||||
|
||||
## Description
|
||||
|
||||
Implement comprehensive dead letter queue (DLQ) management for permanently failed tasks. Provide inspection, manual retry, archival, and alerting capabilities for failed tasks.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Store failed tasks with error details
|
||||
- Inspect DLQ contents with filtering
|
||||
- Manual retry for individual tasks
|
||||
- Bulk retry operations
|
||||
- DLQ archival to cold storage
|
||||
- Alerting on DLQ size thresholds
|
||||
- Automatic retry policies for specific errors
|
||||
- DLQ statistics and reporting
|
||||
|
||||
## Technical Specifications
|
||||
|
||||
**Dead letter queue manager**:
|
||||
```python
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import List, Dict, Optional
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class DLQAction(Enum):
|
||||
"""Actions that can be taken on DLQ tasks."""
|
||||
RETRY = "retry"
|
||||
DELETE = "delete"
|
||||
ARCHIVE = "archive"
|
||||
IGNORE = "ignore"
|
||||
|
||||
@dataclass
|
||||
class DLQTask:
|
||||
"""A task in the dead letter queue."""
|
||||
task_id: str
|
||||
task_name: str
|
||||
error: str
|
||||
traceback: Optional[str]
|
||||
failed_at: datetime
|
||||
retry_count: int
|
||||
args: List = field(default_factory=list)
|
||||
kwargs: Dict = field(default_factory=dict)
|
||||
metadata: Dict = field(default_factory=dict)
|
||||
|
||||
@dataclass
|
||||
class DLQStats:
|
||||
"""Statistics for the dead letter queue."""
|
||||
total_count: int
|
||||
failures_by_task: Dict[str, int]
|
||||
failures_by_error_type: Dict[str, int]
|
||||
oldest_failure: Optional[datetime]
|
||||
newest_failure: Optional[datetime]
|
||||
avg_retry_count: float
|
||||
|
||||
class DeadLetterQueueManager:
|
||||
"""Manager for dead letter queue operations."""
|
||||
|
||||
def __init__(self, db, broker, retry_handler):
|
||||
self.db = db
|
||||
self.broker = broker
|
||||
self.retry_handler = retry_handler
|
||||
|
||||
async def add_to_dlq(
|
||||
self,
|
||||
task_id: str,
|
||||
error: Exception,
|
||||
traceback: Optional[str] = None,
|
||||
metadata: dict = None
|
||||
):
|
||||
"""Add a failed task to the DLQ."""
|
||||
async with self.db.acquire() as conn:
|
||||
# Get task details
|
||||
task = await conn.fetchrow(
|
||||
"""SELECT id, task_name, args, kwargs, retry_count
|
||||
FROM tasks WHERE id = $1""",
|
||||
task_id
|
||||
)
|
||||
|
||||
if not task:
|
||||
logger.warning(f"Task {task_id} not found, cannot add to DLQ")
|
||||
return
|
||||
|
||||
# Add to DLQ
|
||||
await conn.execute(
|
||||
"""INSERT INTO dead_letter_queue (task_id, error, traceback, failed_at, metadata)
|
||||
VALUES ($1, $2, $3, NOW(), $4)
|
||||
ON CONFLICT (task_id) DO UPDATE
|
||||
SET error = EXCLUDED.error,
|
||||
traceback = EXCLUDED.traceback,
|
||||
failed_at = EXCLUDED.failed_at""",
|
||||
task_id,
|
||||
str(error),
|
||||
traceback,
|
||||
metadata or {}
|
||||
)
|
||||
|
||||
# Check if alert needed
|
||||
await self._check_dlq_alerts(conn)
|
||||
|
||||
logger.warning(f"Task {task_id} added to dead letter queue")
|
||||
|
||||
async def get_dlq_tasks(
|
||||
self,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
task_name: str = None,
|
||||
error_contains: str = None,
|
||||
since: datetime = None
|
||||
) -> List[DLQTask]:
|
||||
"""Get tasks from the DLQ with optional filtering."""
|
||||
async with self.db.acquire() as conn:
|
||||
query = """
|
||||
SELECT dlq.*, t.task_name, t.args, t.kwargs
|
||||
FROM dead_letter_queue dlq
|
||||
JOIN tasks t ON t.id = dlq.task_id
|
||||
WHERE 1=1
|
||||
"""
|
||||
params = []
|
||||
|
||||
if task_name:
|
||||
query += " AND t.task_name LIKE $1"
|
||||
params.append(f"%{task_name}%")
|
||||
|
||||
if error_contains:
|
||||
query += " AND dlq.error LIKE $2"
|
||||
params.append(f"%{error_contains}%")
|
||||
|
||||
if since:
|
||||
query += " AND dlq.failed_at >= $3"
|
||||
params.append(since)
|
||||
|
||||
query += " ORDER BY dlq.failed_at DESC"
|
||||
query += f" LIMIT ${len(params) + 1} OFFSET ${len(params) + 2}"
|
||||
params.extend([limit, offset])
|
||||
|
||||
rows = await conn.fetch(query, *params)
|
||||
|
||||
return [
|
||||
DLQTask(
|
||||
task_id=row["task_id"],
|
||||
task_name=row["task_name"],
|
||||
error=row["error"],
|
||||
traceback=row["traceback"],
|
||||
failed_at=row["failed_at"],
|
||||
retry_count=row.get("retry_count", 0),
|
||||
args=row.get("args", []),
|
||||
kwargs=row.get("kwargs", {}),
|
||||
metadata=row.get("metadata", {})
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
async def get_dlq_stats(self) -> DLQStats:
|
||||
"""Get statistics about the DLQ."""
|
||||
async with self.db.acquire() as conn:
|
||||
# Total count
|
||||
total_count = await conn.fetchval("SELECT COUNT(*) FROM dead_letter_queue")
|
||||
|
||||
# Failures by task name
|
||||
failures_by_task = await conn.fetch(
|
||||
"""SELECT t.task_name, COUNT(*) as count
|
||||
FROM dead_letter_queue dlq
|
||||
JOIN tasks t ON t.id = dlq.task_id
|
||||
GROUP BY t.task_name
|
||||
ORDER BY count DESC
|
||||
LIMIT 20"""
|
||||
)
|
||||
|
||||
# Failures by error (group by first line of error)
|
||||
failures_by_error = await conn.fetch(
|
||||
"""SELECT SPLIT_PART(error, E'\n', 1) as error_type, COUNT(*) as count
|
||||
FROM dead_letter_queue
|
||||
GROUP BY error_type
|
||||
ORDER BY count DESC
|
||||
LIMIT 20"""
|
||||
)
|
||||
|
||||
# Oldest and newest
|
||||
oldest = await conn.fetchval(
|
||||
"SELECT MIN(failed_at) FROM dead_letter_queue"
|
||||
)
|
||||
newest = await conn.fetchval(
|
||||
"SELECT MAX(failed_at) FROM dead_letter_queue"
|
||||
)
|
||||
|
||||
# Average retry count
|
||||
avg_retry = await conn.fetchval(
|
||||
"""SELECT COALESCE(AVG(t.retry_count), 0)
|
||||
FROM dead_letter_queue dlq
|
||||
JOIN tasks t ON t.id = dlq.task_id"""
|
||||
)
|
||||
|
||||
return DLQStats(
|
||||
total_count=total_count,
|
||||
failures_by_task={r["task_name"]: r["count"] for r in failures_by_task},
|
||||
failures_by_error_type={r["error_type"]: r["count"] for r in failures_by_error},
|
||||
oldest_failure=oldest,
|
||||
newest_failure=newest,
|
||||
avg_retry_count=float(avg_retry) if avg_retry else 0.0
|
||||
)
|
||||
|
||||
async def retry_task(self, task_id: str) -> bool:
|
||||
"""Retry a single task from the DLQ."""
|
||||
return await self.retry_handler.manual_retry(task_id)
|
||||
|
||||
async def retry_multiple(
|
||||
self,
|
||||
task_ids: List[str],
|
||||
delay_seconds: float = 0
|
||||
) -> Dict[str, bool]:
|
||||
"""Retry multiple tasks."""
|
||||
import asyncio
|
||||
|
||||
results = {}
|
||||
|
||||
for task_id in task_ids:
|
||||
try:
|
||||
await self.retry_task(task_id)
|
||||
results[task_id] = True
|
||||
if delay_seconds > 0:
|
||||
await asyncio.sleep(delay_seconds)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to retry task {task_id}: {e}")
|
||||
results[task_id] = False
|
||||
|
||||
return results
|
||||
|
||||
async def retry_all(
|
||||
self,
|
||||
task_name_filter: str = None,
|
||||
error_filter: str = None,
|
||||
limit: int = 100
|
||||
) -> int:
|
||||
"""Retry tasks matching filters."""
|
||||
tasks = await self.get_dlq_tasks(
|
||||
limit=limit,
|
||||
task_name=task_name_filter,
|
||||
error_contains=error_filter
|
||||
)
|
||||
|
||||
retried = 0
|
||||
for task in tasks:
|
||||
if await self.retry_task(task.task_id):
|
||||
retried += 1
|
||||
|
||||
return retried
|
||||
|
||||
async def delete_task(self, task_id: str) -> bool:
|
||||
"""Remove a task from the DLQ (and mark task as permanently failed)."""
|
||||
async with self.db.acquire() as conn:
|
||||
result = await conn.execute(
|
||||
"DELETE FROM dead_letter_queue WHERE task_id = $1",
|
||||
task_id
|
||||
)
|
||||
return result != "DELETE 0"
|
||||
|
||||
async def delete_multiple(self, task_ids: List[str]) -> int:
|
||||
"""Delete multiple tasks from DLQ."""
|
||||
if not task_ids:
|
||||
return 0
|
||||
|
||||
async with self.db.acquire() as conn:
|
||||
result = await conn.execute(
|
||||
f"DELETE FROM dead_letter_queue WHERE task_id = ANY($1)",
|
||||
task_ids
|
||||
)
|
||||
return int(result.split()[-1]) if result else 0
|
||||
|
||||
async def archive_old(
|
||||
self,
|
||||
older_than: timedelta = timedelta(days=30),
|
||||
archive_table: str = "dead_letter_queue_archive"
|
||||
) -> int:
|
||||
"""Archive old DLQ entries to a separate table."""
|
||||
cutoff = datetime.now(timezone.utc) - older_than
|
||||
|
||||
async with self.db.acquire() as conn:
|
||||
# Create archive table if not exists
|
||||
await conn.execute(
|
||||
f"""CREATE TABLE IF NOT EXISTS {archive_table} (
|
||||
LIKE dead_letter_queue INCLUDING ALL
|
||||
)"""
|
||||
)
|
||||
|
||||
# Move old entries
|
||||
result = await conn.execute(
|
||||
f"""WITH moved AS (
|
||||
DELETE FROM dead_letter_queue
|
||||
WHERE failed_at < $1
|
||||
RETURNING *
|
||||
)
|
||||
INSERT INTO {archive_table}
|
||||
SELECT * FROM moved""",
|
||||
cutoff
|
||||
)
|
||||
|
||||
return int(result.split()[-1]) if result else 0
|
||||
|
||||
async def get_archived(
|
||||
self,
|
||||
limit: int = 100,
|
||||
archive_table: str = "dead_letter_queue_archive"
|
||||
) -> List[dict]:
|
||||
"""Get archived DLQ entries."""
|
||||
async with self.db.acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
f"""SELECT * FROM {archive_table}
|
||||
ORDER BY failed_at DESC
|
||||
LIMIT $1""",
|
||||
limit
|
||||
)
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
async def _check_dlq_alerts(self, conn):
|
||||
"""Check if DLQ size thresholds are exceeded."""
|
||||
count = await conn.fetchval("SELECT COUNT(*) FROM dead_letter_queue")
|
||||
|
||||
# Get alert thresholds from config
|
||||
thresholds = {
|
||||
"warning": 50,
|
||||
"critical": 100
|
||||
}
|
||||
|
||||
if count >= thresholds["critical"]:
|
||||
await self._send_alert("critical", count)
|
||||
elif count >= thresholds["warning"]:
|
||||
await self._send_alert("warning", count)
|
||||
|
||||
async def _send_alert(self, level: str, count: int):
|
||||
"""Send an alert about DLQ size."""
|
||||
logger.warning(f"DLQ alert: {level} - {count} tasks in dead letter queue")
|
||||
|
||||
# Here you could integrate with external alerting systems
|
||||
# e.g., PagerDuty, Slack, email, etc.
|
||||
|
||||
async def create_auto_retry_rule(
|
||||
self,
|
||||
error_pattern: str,
|
||||
max_retries: int = 5,
|
||||
backoff_seconds: int = 300
|
||||
):
|
||||
"""Create a rule for auto-retrying specific errors."""
|
||||
async with self.db.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""INSERT INTO dlq_auto_retry_rules (error_pattern, max_retries, backoff_seconds)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (error_pattern) DO UPDATE
|
||||
SET max_retries = EXCLUDED.max_retries,
|
||||
backoff_seconds = EXCLUDED.backoff_seconds""",
|
||||
error_pattern,
|
||||
max_retries,
|
||||
backoff_seconds
|
||||
)
|
||||
|
||||
async def process_auto_retry_rules(self) -> int:
|
||||
"""Process auto-retry rules against DLQ entries."""
|
||||
async with self.db.acquire() as conn:
|
||||
# Get all rules
|
||||
rules = await conn.fetch("SELECT * FROM dlq_auto_retry_rules WHERE is_active = TRUE")
|
||||
|
||||
retried = 0
|
||||
|
||||
for rule in rules:
|
||||
# Find matching DLQ entries
|
||||
pattern = rule["error_pattern"]
|
||||
max_retries = rule["max_retries"]
|
||||
|
||||
rows = await conn.fetch(
|
||||
"""SELECT dlq.task_id, t.retry_count
|
||||
FROM dead_letter_queue dlq
|
||||
JOIN tasks t ON t.id = dlq.task_id
|
||||
WHERE dlq.error LIKE $1
|
||||
AND t.retry_count < $2""",
|
||||
f"%{pattern}%",
|
||||
max_retries
|
||||
)
|
||||
|
||||
for row in rows:
|
||||
try:
|
||||
await self.retry_task(row["task_id"])
|
||||
retried += 1
|
||||
except Exception as e:
|
||||
logger.error(f"Auto-retry failed for task {row['task_id']}: {e}")
|
||||
|
||||
return retried
|
||||
```
|
||||
|
||||
**Database schema extensions**:
|
||||
```sql
|
||||
-- Auto-retry rules table
|
||||
CREATE TABLE dlq_auto_retry_rules (
|
||||
id SERIAL PRIMARY KEY,
|
||||
error_pattern VARCHAR(500) NOT NULL UNIQUE,
|
||||
max_retries INTEGER DEFAULT 5,
|
||||
backoff_seconds INTEGER DEFAULT 300,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
created_by VARCHAR(200)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_dlq_rules_active ON dlq_auto_retry_rules(is_active);
|
||||
```
|
||||
|
||||
**DLQ CLI commands**:
|
||||
```python
|
||||
import click
|
||||
import json
|
||||
|
||||
@click.group()
|
||||
def dlq():
|
||||
"""Dead letter queue management commands."""
|
||||
pass
|
||||
|
||||
@dlq.command()
|
||||
@click.option('--limit', '-l', default=50, type=int)
|
||||
@click.option('--task-name', '-t', default=None)
|
||||
@click.option('--error', '-e', default=None)
|
||||
@click.option('--format', '-f', type=click.Choice(['table', 'json']), default='table')
|
||||
def list(limit, task_name, error, format):
|
||||
"""List tasks in the dead letter queue."""
|
||||
manager = get_dlq_manager()
|
||||
tasks = asyncio.run(manager.get_dlq_tasks(
|
||||
limit=limit,
|
||||
task_name=task_name,
|
||||
error_contains=error
|
||||
))
|
||||
|
||||
if format == 'json':
|
||||
click.echo(json.dumps([asdict(t) for t in tasks], default=str))
|
||||
else:
|
||||
# Table format
|
||||
click.echo(f"Found {len(tasks)} tasks in DLQ")
|
||||
for t in tasks[:20]:
|
||||
click.echo(f" {t.task_id[:8]}... | {t.task_name} | {t.error[:50]}...")
|
||||
|
||||
@dlq.command()
|
||||
@click.argument('task_id')
|
||||
def retry(task_id):
|
||||
"""Retry a task from the DLQ."""
|
||||
manager = get_dlq_manager()
|
||||
success = asyncio.run(manager.retry_task(task_id))
|
||||
if success:
|
||||
click.echo(f"Task {task_id} queued for retry")
|
||||
else:
|
||||
click.echo(f"Failed to retry task {task_id}", err=True)
|
||||
|
||||
@dlq.command()
|
||||
@click.option('--task-name', '-t', default=None)
|
||||
@click.option('--error', '-e', default=None)
|
||||
@click.option('--limit', '-l', default=100)
|
||||
def retry_all(task_name, error, limit):
|
||||
"""Retry multiple tasks from the DLQ."""
|
||||
manager = get_dlq_manager()
|
||||
count = asyncio.run(manager.retry_all(
|
||||
task_name_filter=task_name,
|
||||
error_filter=error,
|
||||
limit=limit
|
||||
))
|
||||
click.echo(f"Queued {count} tasks for retry")
|
||||
|
||||
@dlq.command()
|
||||
@click.option('--days', '-d', default=30, type=int)
|
||||
def archive(days):
|
||||
"""Archive old DLQ entries."""
|
||||
manager = get_dlq_manager()
|
||||
count = asyncio.run(manager.archive_old(
|
||||
older_than=timedelta(days=days)
|
||||
))
|
||||
click.echo(f"Archived {count} tasks")
|
||||
|
||||
@dlq.command()
|
||||
def stats():
|
||||
"""Show DLQ statistics."""
|
||||
manager = get_dlq_manager()
|
||||
stats = asyncio.run(manager.get_dlq_stats())
|
||||
|
||||
click.echo(f"Total tasks in DLQ: {stats.total_count}")
|
||||
click.echo(f"Average retry count: {stats.avg_retry_count:.1f}")
|
||||
click.echo("\nTop failures by task:")
|
||||
for task, count in list(stats.failures_by_task.items())[:10]:
|
||||
click.echo(f" {task}: {count}")
|
||||
```
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] Failed tasks are stored in DLQ
|
||||
- [ ] DLQ can be listed and filtered
|
||||
- [ ] Individual tasks can be retried
|
||||
- [ ] Bulk retry operations work
|
||||
- [ ] Old tasks can be archived
|
||||
- [ ] DLQ statistics are accurate
|
||||
- [ ] Auto-retry rules function correctly
|
||||
|
||||
## Notes
|
||||
|
||||
**Trade-offs**:
|
||||
- Archive vs delete: Archive preserves audit trail
|
||||
- Auto-retry complexity: Manual retry gives more control
|
||||
|
||||
**Performance**:
|
||||
- Archive in batches to avoid long transactions
|
||||
- Index DLQ by failed_at for efficient queries
|
||||
|
||||
**Alternatives considered**:
|
||||
- External DLQ (S3, SQS): Database simpler for this use case
|
||||
- Immediate alert on each failure: Batch alerts reduce noise
|
||||
Reference in New Issue
Block a user