"""Case-local recovery policy cells for the API reliability successor.""" from __future__ import annotations from typing import Any FAILURE_SIGNALS = ( "queued_replay", "provider_5xx", "timeout", "rate_limit", ) OPERATION_CLASSES = ( "observation", "decision", "mutation", "pricing", ) # Opaque identifiers prevent the label itself from revealing the correct action. RECOVERY_PROFILES = ( "recovery-profile-k7", "recovery-profile-m4", "recovery-profile-q9", "recovery-profile-v2", ) def _rule_cells() -> list[dict[str, str]]: cells: list[dict[str, str]] = [] for row, failure_signal in enumerate(FAILURE_SIGNALS): for column, operation_class in enumerate(OPERATION_CLASSES): cells.append( { "rule_atom": f"R{len(cells) + 1:02d}", "failure_signal": failure_signal, "operation_class": operation_class, "recovery_profile_id": RECOVERY_PROFILES[(row + column) % len(RECOVERY_PROFILES)], "evidence": "verified archived recovery outcome", } ) return cells RECOVERY_RULE_CELLS = _rule_cells() RULE_LOOKUP = { (cell["failure_signal"], cell["operation_class"]): cell["recovery_profile_id"] for cell in RECOVERY_RULE_CELLS } RULE_ATOM_LOOKUP = { (cell["failure_signal"], cell["operation_class"]): cell["rule_atom"] for cell in RECOVERY_RULE_CELLS } def failure_signal_for(source: dict[str, Any]) -> str: status = str(source.get("status") or "").lower() error_code = str(source.get("error_code") or "").upper() if status == "queued" or error_code == "REPLAY_QUEUED": return "queued_replay" if status == "rate_limited" or error_code in {"HTTP_429", "RATE_LIMIT_REMAINING_ZERO"}: return "rate_limit" if status == "timeout" or error_code == "TIMEOUT" or error_code == "HTTP_504": return "timeout" if status == "transient_error" or error_code.startswith("HTTP_5"): return "provider_5xx" return "provider_5xx" def operation_class_for(operation: str) -> str: operation = str(operation or "").lower() if operation in {"track_parcel", "list_watch_hits", "sync_availability", "validate_address"}: return "observation" if operation in {"review_case", "score_transaction", "release_hold"}: return "decision" if operation in {"quote_shipment"}: return "pricing" return "mutation" def required_recovery_profile(source: dict[str, Any]) -> str: return RULE_LOOKUP[(failure_signal_for(source), operation_class_for(source.get("operation", "")))]