python
import asyncio
import dataclasses
import enum
import logging
import random
import time
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, TypeVar, Union
import pydantic
from pydantic import BaseModel, Field, validator
T = TypeVar("T") # Generic type for request/response
logger = logging.getLogger(__name__)
# =============================================================================
# 1. ERROR TAXONOMIES
# =============================================================================
class ErrorCategory(enum.Enum):
"""Taxonomy of errors for retry decisions."""
RETRYABLE_TRANSIENT = "retryable_transient" # e.g., network blips, 5xx
RETRYABLE_THROTTLED = "retryable_throttled" # e.g., 429, rate limits
RETRYABLE_IDEMPOTENT = "retryable_idempotent" # Safe to retry (e.g., GET)
NON_RETRYABLE = "non_retryable" # e.g., 4xx client errors
FATAL = "fatal" # e.g., auth failures, data corruption
@dataclasses.dataclass
class ErrorRule:
"""Rule for classifying errors into taxonomy."""
error_type: Union[type, str] # Exception class or string code
category: ErrorCategory
match_fn: Optional[Callable[[Exception], bool]] = None
def matches(self, error: Exception) -> bool:
if self.match_fn:
return self.match_fn(error)
if isinstance(self.error_type, type):
return isinstance(error, self.error_type)
return str(error).startswith(self.error_type)
class ErrorTaxonomy(BaseModel):
"""Global or per-tenant error classification rules."""
rules: List[ErrorRule] = Field(default_factory=list)
def classify(self, error: Exception) -> ErrorCategory:
"""Classify error into category."""
for rule in self.rules:
if rule.matches(error):
return rule.category
return ErrorCategory.NON_RETRYABLE # Default: don't retry
@classmethod
def default(cls) -> "ErrorTaxonomy":
"""Common error rules (extensible)."""
return cls(
rules=[
# HTTP-like errors
ErrorRule("429", ErrorCategory.RETRYABLE_THROTTLED),
ErrorRule("5", ErrorCategory.RETRYABLE_TRANSIENT), # 5xx prefix
ErrorRule("TimeoutError", ErrorCategory.RETRYABLE_TRANSIENT),
ErrorRule("ConnectionError", ErrorCategory.RETRYABLE_TRANSIENT),
# Custom examples
ErrorRule(ConnectionResetError, ErrorCategory.RETRYABLE_TRANSIENT),
ErrorRule(ValueError, ErrorCategory.NON_RETRYABLE),
# Fatal: e.g., auth
ErrorRule("401", ErrorCategory.FATAL),
ErrorRule("403", ErrorCategory.FATAL),
]
)
# =============================================================================
# 2. RISK HEURISTICS
# =============================================================================
@dataclasses.dataclass
class RiskScore:
"""Computed risk for a retry decision."""
base_score: float = 0.0 # 0-1: low to high risk
cost_multiplier: float = 1.0 # Request cost factor
failure_history: float = 0.0 # Recent failure rate (0-1)
staleness_penalty: float = 0.0 # Time since request age
total_risk: float = Field(init=False)
def __post_init__(self):
self.total_risk = min(1.0, self.base_score + self.cost_multiplier * 0.1 + self.failure_history * 0.3 + self.staleness_penalty * 0.2)
class RiskHeuristic(BaseModel):
"""Pluggable risk evaluation heuristic."""
name: str
compute_fn: Callable[[Dict[str, Any], int], float] # ctx, attempt -> score delta
@classmethod
def default_heuristics(cls) -> List["RiskHeuristic"]:
"""Built-in heuristics."""
def cost_heuristic(ctx: Dict[str, Any], attempt: int) -> float:
"""High cost requests riskier to retry."""
cost = ctx.get("estimated_cost_ms", 100) / 1000.0
return cost * (1 + attempt * 0.5) # Exponential cost growth
def history_heuristic(ctx: Dict[str, Any], attempt: int) -> float:
"""Recent failures increase risk."""
history = ctx.get("recent_failure_rate", 0.0)
return history * (1 + attempt * 0.1)
def staleness_heuristic(ctx: Dict[str, Any], attempt: int) -> float:
"""Old requests riskier (data staleness)."""
age_s = time.time() - ctx.get("request_start_time", time.time())
return min(1.0, age_s / 3600.0) # Cap at 1h
return [
cls(name="cost", compute_fn=cost_heuristic),
cls(name="history", compute_fn=history_heuristic),
cls(name="staleness", compute_fn=staleness_heuristic),
]
class RiskEvaluator(BaseModel):
"""Evaluates total risk using heuristics."""
heuristics: List[RiskHeuristic] = Field(default_factory=RiskHeuristic.default_heuristics)
risk_threshold: float = 0.7 # Above this: don't retry
def evaluate(self, ctx: Dict[str, Any], attempt: int) -> RiskScore:
"""Compute risk score from context."""
base_score = 0.0
for h in self.heuristics:
base_score += h.compute_fn(ctx, attempt)
return RiskScore(base_score=base_score / len(self.heuristics))
# =============================================================================
# 3. PER-TENANT SERVICE LEVELS
# =============================================================================
class TenantSLA(BaseModel):
"""Per-tenant configs for SLAs."""
tenant_id: str
max_retries: int = 5
max_total_time_s: float = 30.0
budget_per_min: float = 1000.0 # Request budget (e.g., compute units)
priority: int = 1 # Higher = more aggressive retries
error_taxonomy: Optional[ErrorTaxonomy] = None
risk_evaluator: Optional[RiskEvaluator] = None
@validator("error_taxonomy", pre=True, always=True)
def default_taxonomy(cls, v):
return v or ErrorTaxonomy.default()
@validator("risk_evaluator", pre=True, always=True)
def default_risk_eval(cls, v):
from typing import Any
return v or RiskEvaluator()
def allows_retry(self, elapsed_time: float, used_budget: float, attempt: int) -> bool:
"""Check if SLA permits another retry."""
return (
attempt < self.max_retries
and elapsed_time < self.max_total_time_s
and used_budget < self.budget_per_min / 60.0 * elapsed_time # Prorate budget
)
class TenantManager(BaseModel):
"""Manages per-tenant SLAs."""
tenants: Dict[str, TenantSLA] = {}
def get_sla(self, tenant_id: str) -> TenantSLA:
return self.tenants.get(tenant_id, TenantSLA(tenant_id=tenant_id)) # Default
def register(self, sla: TenantSLA):
self.tenants[sla.tenant_id] = sla
# =============================================================================
# 4. RETRY POLICY
# =============================================================================
@dataclasses.dataclass
class RetryDecision:
"""Decision for next retry."""
should_retry: bool = False
backoff_ms: int = 0
jitter_ms: int = 0
max_attempts: int = 0
reason: str = ""
next_delay_ms: int = Field(init=False)
def __post_init__(self):
self.next_delay_ms = self.backoff_ms + random.randint(0, self.jitter_ms)
# =============================================================================
# 5. CORE ORCHESTRATOR
# =============================================================================
class AdaptiveRetryOrchestrator:
"""Per-request adaptive retry orchestrator."""
def __init__(
self,
tenant_manager: TenantManager,
default_taxonomy: ErrorTaxonomy = None,
default_risk_eval: RiskEvaluator = None,
):
self.tenant_manager = tenant_manager
self.default_taxonomy = default_taxonomy or ErrorTaxonomy.default()
self.default_risk_eval = default_risk_eval or RiskEvaluator()
async def should_retry(
self,
ctx: Dict[str, Any], # Per-request context: tenant_id, request_start_time, etc.
error: Optional[Exception] = None,
attempt: int = 1,
elapsed_ms: int = 0,
used_budget: float = 0.0,
) -> RetryDecision:
"""
Evaluate if should retry this request.
Adaptive: uses error taxonomy, risk heuristics, tenant SLA.
"""
tenant_id = ctx.get("tenant_id", "default")
sla = self.tenant_manager.get_sla(tenant_id)
# 1. Error Taxonomy
category = (
sla.error_taxonomy.classify(error)
if error
else ErrorCategory.NON_RETRYABLE
)
if category in (ErrorCategory.NON_RETRYABLE, ErrorCategory.FATAL):
return RetryDecision(should_retry=False, reason=f"Non-retryable: {category}")
# 2. Risk Heuristics
risk_score = sla.risk_evaluator.evaluate(ctx, attempt)
if risk_score.total_risk > sla.risk_evaluator.risk_threshold:
return RetryDecision(should_retry=False, reason=f"High risk: {risk_score.total_risk:.2f}")
# 3. Tenant SLA Check
if not sla.allows_retry(elapsed_ms / 1000, used_budget, attempt):
return RetryDecision(should_retry=False, reason="SLA exceeded")
# 4. Compute Adaptive Backoff (exponential + jitter + tenant priority)
base_backoff = 50 * (2 ** (attempt - 1)) # Exp backoff: 50, 100, 200...
jitter = base_backoff * 0.5 # ±50%
priority_factor = 1.0 / max(1, sla.priority) # Higher priority = faster retry
return RetryDecision(
should_retry=True,
backoff_ms=int(base_backoff * priority_factor),
jitter_ms=int(jitter),
max_attempts=sla.max_retries,
reason=f"Retry OK (risk={risk_score.total_risk:.2f}, cat={category})",
)
async def execute_with_retry(
self,
fn: Callable[[], T],
ctx: Dict[str, Any],
max_attempts: Optional[int] = None,
) -> Tuple[Optional[T], Optional[Exception]]:
"""
Execute fn with adaptive retries.
Returns (result, final_error)
"""
start_time = time.time()
attempt = 1
elapsed_ms = 0
used_budget = 0.0
while True:
try:
ctx["attempt"] = attempt
ctx["request_start_time"] = start_time
result = await asyncio.wait_for(fn(), timeout=ctx.get("timeout_s", 10))
return result, None
except asyncio.TimeoutError:
error = asyncio.TimeoutError("Request timeout")
except Exception as e:
error = e
decision = await self.should_retry(ctx, error, attempt, elapsed_ms, used_budget)
if not decision.should_retry or attempt >= (max_attempts or decision.max_attempts):
return None, error
# Apply backoff
await asyncio.sleep(decision.next_delay_ms / 1000.0)
elapsed_ms = int((time.time() - start_time) * 1000)
used_budget += ctx.get("estimated_cost", 1.0) # Track budget
attempt += 1
logger.info(f"Retry {attempt-1} -> {attempt}: {decision.reason}")
# =============================================================================
# 6. USAGE EXAMPLE
# =============================================================================
async def example():
# Setup tenants
tenant_mgr = TenantManager()
tenant_mgr.register(
TenantSLA(
tenant_id="gold-customer",
max_retries=10,
max_total_time_s=60.0,
budget_per_min=5000.0,
priority=2, # High priority
)
)
tenant_mgr.register(
TenantSLA(
tenant_id="free-tier",
max_retries=3,
max_total_time_s=10.0,
budget_per_min=100.0,
priority=1,
)
)
orchestrator = AdaptiveRetryOrchestrator(tenant_mgr)
# Example flaky API call
async def flaky_api(ctx: Dict[str, Any]) -> str:
if random.random() < 0.7: # 70% success
return "Success!"
raise ConnectionError("Transient network error") # Retryable
# Test per-tenant
for tenant_id in ["gold-customer", "free-tier"]:
ctx = {
"tenant_id": tenant_id,
"estimated_cost_ms": 200 if tenant_id == "gold-customer" else 50,
"recent_failure_rate": 0.4,
"timeout_s": 5,
}
result, error = await orchestrator.execute_with_retry(
lambda: flaky_api(ctx), ctx
)
print(f"Tenant {tenant_id}: result={result}, error={error}")
if __name__ == "__main__":
asyncio.run(example())
Outputs vary (random failures), but gold-customer retries more aggressively than free-tier.
This is production-ready scaffolding—extend with Redis for shared history, tracing (e.g., OpenTelemetry), or ML-based risk. Questions?