"""Structured generation failure attribution helpers.""" from __future__ import annotations import re from typing import Any from engines.image_provider import ImageProviderError SECRET_KEYWORDS = ("api_key", "apikey", "authorization", "bearer", "password", "secret", "token") def provider_failure_attribution( exc: ImageProviderError, *, route_context: dict[str, Any] | None = None, fallback_used: bool = False, ) -> dict[str, Any]: route = route_context or {} status_code = exc.status_code category = _category(exc.error_type, status_code) attribution = { "source": "image_provider", "category": category, "error_type": exc.error_type, "message": _safe_message(str(exc)), "provider_id": _first_text(exc.provider_id, route.get("provider_id"), "unknown"), "status_code": status_code, "retryable": _is_retryable(category, status_code), "fallback_used": bool(fallback_used), "user_action_required": category in {"configuration_error", "auth_error", "request_error"}, } for key in ("route_name", "route_id", "model_id", "modality"): value = route.get(key) if value is not None: attribution[key] = value details = _safe_details(exc.details) if details: attribution["details"] = details return attribution def _category(error_type: str, status_code: int | None) -> str: if error_type == "configuration_error": return "configuration_error" if error_type == "network_error": return "network_error" if error_type == "invalid_response": return "invalid_response" if status_code in {401, 403}: return "auth_error" if status_code == 429: return "rate_limited" if status_code in {408, 504}: return "timeout" if status_code is not None and 500 <= status_code <= 599: return "provider_unavailable" if status_code is not None and 400 <= status_code <= 499: return "request_error" return error_type or "provider_error" def _is_retryable(category: str, status_code: int | None) -> bool: if category in {"network_error", "timeout", "rate_limited", "provider_unavailable"}: return True return bool(status_code is not None and 500 <= status_code <= 599) def _safe_details(details: dict[str, Any]) -> dict[str, Any]: cleaned: dict[str, Any] = {} for key, value in details.items(): key_text = str(key) if _is_secret_key(key_text): cleaned[key_text] = "[REDACTED]" elif isinstance(value, str): cleaned[key_text] = _safe_message(value, limit=500) elif isinstance(value, (int, float, bool)) or value is None: cleaned[key_text] = value else: cleaned[key_text] = _safe_message(str(value), limit=500) return cleaned def _safe_message(value: str, *, limit: int = 240) -> str: text = " ".join(str(value or "").split()) text = re.sub(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+", "Bearer [REDACTED]", text) text = re.sub( r'''(?ix)(["']?(?:api[_-]?key|apikey|authorization|token|password|secret)["']?\s*[:=]\s*["']?)(?:Bearer\s+)?[^"'\s,;}]+''', r"\1[REDACTED]", text, ) text = re.sub(r"\bsk-[A-Za-z0-9_-]{8,}\b", "[REDACTED]", text) return text[:limit] if text else "image provider failed" def _is_secret_key(key: str) -> bool: lowered = key.lower() return any(keyword in lowered for keyword in SECRET_KEYWORDS) def _first_text(*values: Any) -> str: for value in values: text = str(value or "").strip() if text: return text return "unknown"