[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BWMMFMD716Z02TYPNZWRK9":3,"skill-same:01M7BWMMFMD716Z02TYPNZWRK9":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BWMMFMD716Z02TYPNZWRK9","python-resilience",null,"Python resilience patterns including automatic retries, exponential backoff, timeouts, and fault-tolerant decorators. Use when adding retry logic, implementing timeouts, building fault-tolerant services, or handling transient failures.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fpython-development\u002Fskills\u002Fpython-resilience\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: python-resilience\ndescription: Python resilience patterns including automatic retries, exponential backoff, timeouts, and fault-tolerant decorators. Use when adding retry logic, implementing timeouts, building fault-tolerant services, or handling transient failures.\n---\n\n# Python Resilience Patterns\n\nBuild fault-tolerant Python applications that gracefully handle transient failures, network issues, and service outages. Resilience patterns keep systems running when dependencies are unreliable.\n\n## When to Use This Skill\n\n- Adding retry logic to external service calls\n- Implementing timeouts for network operations\n- Building fault-tolerant microservices\n- Handling rate limiting and backpressure\n- Creating infrastructure decorators\n- Designing circuit breakers\n\n## Core Concepts\n\n### 1. Transient vs Permanent Failures\n\nRetry transient errors (network timeouts, temporary service issues). Don't retry permanent errors (invalid credentials, bad requests).\n\n### 2. Exponential Backoff\n\nIncrease wait time between retries to avoid overwhelming recovering services.\n\n### 3. Jitter\n\nAdd randomness to backoff to prevent thundering herd when many clients retry simultaneously.\n\n### 4. Bounded Retries\n\nCap both attempt count and total duration to prevent infinite retry loops.\n\n## Quick Start\n\n```python\nfrom tenacity import retry, stop_after_attempt, wait_exponential_jitter\n\n@retry(\n    stop=stop_after_attempt(3),\n    wait=wait_exponential_jitter(initial=1, max=10),\n)\ndef call_external_service(request: dict) -> dict:\n    return httpx.post(\"https:\u002F\u002Fapi.example.com\", json=request).json()\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Basic Retry with Tenacity\n\nUse the `tenacity` library for production-grade retry logic. For simpler cases, consider built-in retry functionality or a lightweight custom implementation.\n\n```python\nfrom tenacity import (\n    retry,\n    stop_after_attempt,\n    stop_after_delay,\n    wait_exponential_jitter,\n    retry_if_exception_type,\n)\n\nTRANSIENT_ERRORS = (ConnectionError, TimeoutError, OSError)\n\n@retry(\n    retry=retry_if_exception_type(TRANSIENT_ERRORS),\n    stop=stop_after_attempt(5) | stop_after_delay(60),\n    wait=wait_exponential_jitter(initial=1, max=30),\n)\ndef fetch_data(url: str) -> dict:\n    \"\"\"Fetch data with automatic retry on transient failures.\"\"\"\n    response = httpx.get(url, timeout=30)\n    response.raise_for_status()\n    return response.json()\n```\n\n### Pattern 2: Retry Only Appropriate Errors\n\nWhitelist specific transient exceptions. Never retry:\n\n- `ValueError`, `TypeError` - These are bugs, not transient issues\n- `AuthenticationError` - Invalid credentials won't become valid\n- HTTP 4xx errors (except 429) - Client errors are permanent\n\n```python\nfrom tenacity import retry, retry_if_exception_type\nimport httpx\n\n# Define what's retryable\nRETRYABLE_EXCEPTIONS = (\n    ConnectionError,\n    TimeoutError,\n    httpx.ConnectTimeout,\n    httpx.ReadTimeout,\n)\n\n@retry(\n    retry=retry_if_exception_type(RETRYABLE_EXCEPTIONS),\n    stop=stop_after_attempt(3),\n    wait=wait_exponential_jitter(initial=1, max=10),\n)\ndef resilient_api_call(endpoint: str) -> dict:\n    \"\"\"Make API call with retry on network issues.\"\"\"\n    return httpx.get(endpoint, timeout=10).json()\n```\n\n### Pattern 3: HTTP Status Code Retries\n\nRetry specific HTTP status codes that indicate transient issues.\n\n```python\nfrom tenacity import retry, retry_if_result, stop_after_attempt\nimport httpx\n\nRETRY_STATUS_CODES = {429, 502, 503, 504}\n\ndef should_retry_response(response: httpx.Response) -> bool:\n    \"\"\"Check if response indicates a retryable error.\"\"\"\n    return response.status_code in RETRY_STATUS_CODES\n\n@retry(\n    retry=retry_if_result(should_retry_response),\n    stop=stop_after_attempt(3),\n    wait=wait_exponential_jitter(initial=1, max=10),\n)\ndef http_request(method: str, url: str, **kwargs) -> httpx.Response:\n    \"\"\"Make HTTP request with retry on transient status codes.\"\"\"\n    return httpx.request(method, url, timeout=30, **kwargs)\n```\n\n### Pattern 4: Combined Exception and Status Retry\n\nHandle both network exceptions and HTTP status codes.\n\n```python\nfrom tenacity import (\n    retry,\n    retry_if_exception_type,\n    retry_if_result,\n    stop_after_attempt,\n    wait_exponential_jitter,\n    before_sleep_log,\n)\nimport logging\nimport httpx\n\nlogger = logging.getLogger(__name__)\n\nTRANSIENT_EXCEPTIONS = (\n    ConnectionError,\n    TimeoutError,\n    httpx.ConnectError,\n    httpx.ReadTimeout,\n)\nRETRY_STATUS_CODES = {429, 500, 502, 503, 504}\n\ndef is_retryable_response(response: httpx.Response) -> bool:\n    return response.status_code in RETRY_STATUS_CODES\n\n@retry(\n    retry=(\n        retry_if_exception_type(TRANSIENT_EXCEPTIONS) |\n        retry_if_result(is_retryable_response)\n    ),\n    stop=stop_after_attempt(5),\n    wait=wait_exponential_jitter(initial=1, max=30),\n    before_sleep=before_sleep_log(logger, logging.WARNING),\n)\ndef robust_http_call(\n    method: str,\n    url: str,\n    **kwargs,\n) -> httpx.Response:\n    \"\"\"HTTP call with comprehensive retry handling.\"\"\"\n    return httpx.request(method, url, timeout=30, **kwargs)\n```\n\n## Advanced Patterns\n\n### Pattern 5: Logging Retry Attempts\n\nTrack retry behavior for debugging and alerting.\n\n```python\nfrom tenacity import retry, stop_after_attempt, wait_exponential\nimport structlog\n\nlogger = structlog.get_logger()\n\ndef log_retry_attempt(retry_state):\n    \"\"\"Log detailed retry information.\"\"\"\n    exception = retry_state.outcome.exception()\n    logger.warning(\n        \"Retrying operation\",\n        attempt=retry_state.attempt_number,\n        exception_type=type(exception).__name__,\n        exception_message=str(exception),\n        next_wait_seconds=retry_state.next_action.sleep if retry_state.next_action else None,\n    )\n\n@retry(\n    stop=stop_after_attempt(3),\n    wait=wait_exponential(multiplier=1, max=10),\n    before_sleep=log_retry_attempt,\n)\ndef call_with_logging(request: dict) -> dict:\n    \"\"\"External call with retry logging.\"\"\"\n    ...\n```\n\n### Pattern 6: Timeout Decorator\n\nCreate reusable timeout decorators for consistent timeout handling.\n\n```python\nimport asyncio\nfrom functools import wraps\nfrom typing import TypeVar, Callable\n\nT = TypeVar(\"T\")\n\ndef with_timeout(seconds: float):\n    \"\"\"Decorator to add timeout to async functions.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        @wraps(func)\n        async def wrapper(*args, **kwargs) -> T:\n            return await asyncio.wait_for(\n                func(*args, **kwargs),\n                timeout=seconds,\n            )\n        return wrapper\n    return decorator\n\n@with_timeout(30)\nasync def fetch_with_timeout(url: str) -> dict:\n    \"\"\"Fetch URL with 30 second timeout.\"\"\"\n    async with httpx.AsyncClient() as client:\n        response = await client.get(url)\n        return response.json()\n```\n\n### Pattern 7: Cross-Cutting Concerns via Decorators\n\nStack decorators to separate infrastructure from business logic.\n\n```python\nfrom functools import wraps\nfrom typing import TypeVar, Callable\nimport structlog\n\nlogger = structlog.get_logger()\nT = TypeVar(\"T\")\n\ndef traced(name: str | None = None):\n    \"\"\"Add tracing to function calls.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        span_name = name or func.__name__\n\n        @wraps(func)\n        async def wrapper(*args, **kwargs) -> T:\n            logger.info(\"Operation started\", operation=span_name)\n            try:\n                result = await func(*args, **kwargs)\n                logger.info(\"Operation completed\", operation=span_name)\n                return result\n            except Exception as e:\n                logger.error(\"Operation failed\", operation=span_name, error=str(e))\n                raise\n        return wrapper\n    return decorator\n\n# Stack multiple concerns\n@traced(\"fetch_user_data\")\n@with_timeout(30)\n@retry(stop=stop_after_attempt(3), wait=wait_exponential_jitter())\nasync def fetch_user_data(user_id: str) -> dict:\n    \"\"\"Fetch user with tracing, timeout, and retry.\"\"\"\n    ...\n```\n\n### Pattern 8: Dependency Injection for Testability\n\nPass infrastructure components through constructors for easy testing.\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\nclass Logger(Protocol):\n    def info(self, msg: str, **kwargs) -> None: ...\n    def error(self, msg: str, **kwargs) -> None: ...\n\nclass MetricsClient(Protocol):\n    def increment(self, metric: str, tags: dict | None = None) -> None: ...\n    def timing(self, metric: str, value: float) -> None: ...\n\n@dataclass\nclass UserService:\n    \"\"\"Service with injected infrastructure.\"\"\"\n\n    repository: UserRepository\n    logger: Logger\n    metrics: MetricsClient\n\n    async def get_user(self, user_id: str) -> User:\n        self.logger.info(\"Fetching user\", user_id=user_id)\n        start = time.perf_counter()\n\n        try:\n            user = await self.repository.get(user_id)\n            self.metrics.increment(\"user.fetch.success\")\n            return user\n        except Exception as e:\n            self.metrics.increment(\"user.fetch.error\")\n            self.logger.error(\"Failed to fetch user\", user_id=user_id, error=str(e))\n            raise\n        finally:\n            elapsed = time.perf_counter() - start\n            self.metrics.timing(\"user.fetch.duration\", elapsed)\n\n# Easy to test with fakes\nservice = UserService(\n    repository=FakeRepository(),\n    logger=FakeLogger(),\n    metrics=FakeMetrics(),\n)\n```\n\n### Pattern 9: Fail-Safe Defaults\n\nDegrade gracefully when non-critical operations fail.\n\n```python\nfrom typing import TypeVar\nfrom collections.abc import Callable\n\nT = TypeVar(\"T\")\n\ndef fail_safe(default: T, log_failure: bool = True):\n    \"\"\"Return default value on failure instead of raising.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        @wraps(func)\n        async def wrapper(*args, **kwargs) -> T:\n            try:\n                return await func(*args, **kwargs)\n            except Exception as e:\n                if log_failure:\n                    logger.warning(\n                        \"Operation failed, using default\",\n                        function=func.__name__,\n                        error=str(e),\n                    )\n                return default\n        return wrapper\n    return decorator\n\n@fail_safe(default=[])\nasync def get_recommendations(user_id: str) -> list[str]:\n    \"\"\"Get recommendations, return empty list on failure.\"\"\"\n    ...\n```\n\n## Best Practices Summary\n\n1. **Retry only transient errors** - Don't retry bugs or authentication failures\n2. **Use exponential backoff** - Give services time to recover\n3. **Add jitter** - Prevent thundering herd from synchronized retries\n4. **Cap total duration** - `stop_after_attempt(5) | stop_after_delay(60)`\n5. **Log every retry** - Silent retries hide systemic problems\n6. **Use decorators** - Keep retry logic separate from business logic\n7. **Inject dependencies** - Make infrastructure testable\n8. **Set timeouts everywhere** - Every network call needs a timeout\n9. **Fail gracefully** - Return cached\u002Fdefault values for non-critical paths\n10. **Monitor retry rates** - High retry rates indicate underlying issues\n","# Python Resilience Patterns\n\nBuild fault-tolerant Python applications that gracefully handle transient failures, network issues, and service outages. Resilience patterns keep systems running when dependencies are unreliable.\n\n## When to Use This Skill\n\n- Adding retry logic to external service calls\n- Implementing timeouts for network operations\n- Building fault-tolerant microservices\n- Handling rate limiting and backpressure\n- Creating infrastructure decorators\n- Designing circuit breakers\n\n## Core Concepts\n\n### 1. Transient vs Permanent Failures\n\nRetry transient errors (network timeouts, temporary service issues). Don't retry permanent errors (invalid credentials, bad requests).\n\n### 2. Exponential Backoff\n\nIncrease wait time between retries to avoid overwhelming recovering services.\n\n### 3. Jitter\n\nAdd randomness to backoff to prevent thundering herd when many clients retry simultaneously.\n\n### 4. Bounded Retries\n\nCap both attempt count and total duration to prevent infinite retry loops.\n\n## Quick Start\n\n```python\nfrom tenacity import retry, stop_after_attempt, wait_exponential_jitter\n\n@retry(\n    stop=stop_after_attempt(3),\n    wait=wait_exponential_jitter(initial=1, max=10),\n)\ndef call_external_service(request: dict) -> dict:\n    return httpx.post(\"https:\u002F\u002Fapi.example.com\", json=request).json()\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Basic Retry with Tenacity\n\nUse the `tenacity` library for production-grade retry logic. For simpler cases, consider built-in retry functionality or a lightweight custom implementation.\n\n```python\nfrom tenacity import (\n    retry,\n    stop_after_attempt,\n    stop_after_delay,\n    wait_exponential_jitter,\n    retry_if_exception_type,\n)\n\nTRANSIENT_ERRORS = (ConnectionError, TimeoutError, OSError)\n\n@retry(\n    retry=retry_if_exception_type(TRANSIENT_ERRORS),\n    stop=stop_after_attempt(5) | stop_after_delay(60),\n    wait=wait_exponential_jitter(initial=1, max=30),\n)\ndef fetch_data(url: str) -> dict:\n    \"\"\"Fetch data with automatic retry on transient failures.\"\"\"\n    response = httpx.get(url, timeout=30)\n    response.raise_for_status()\n    return response.json()\n```\n\n### Pattern 2: Retry Only Appropriate Errors\n\nWhitelist specific transient exceptions. Never retry:\n\n- `ValueError`, `TypeError` - These are bugs, not transient issues\n- `AuthenticationError` - Invalid credentials won't become valid\n- HTTP 4xx errors (except 429) - Client errors are permanent\n\n```python\nfrom tenacity import retry, retry_if_exception_type\nimport httpx\n\n# Define what's retryable\nRETRYABLE_EXCEPTIONS = (\n    ConnectionError,\n    TimeoutError,\n    httpx.ConnectTimeout,\n    httpx.ReadTimeout,\n)\n\n@retry(\n    retry=retry_if_exception_type(RETRYABLE_EXCEPTIONS),\n    stop=stop_after_attempt(3),\n    wait=wait_exponential_jitter(initial=1, max=10),\n)\ndef resilient_api_call(endpoint: str) -> dict:\n    \"\"\"Make API call with retry on network issues.\"\"\"\n    return httpx.get(endpoint, timeout=10).json()\n```\n\n### Pattern 3: HTTP Status Code Retries\n\nRetry specific HTTP status codes that indicate transient issues.\n\n```python\nfrom tenacity import retry, retry_if_result, stop_after_attempt\nimport httpx\n\nRETRY_STATUS_CODES = {429, 502, 503, 504}\n\ndef should_retry_response(response: httpx.Response) -> bool:\n    \"\"\"Check if response indicates a retryable error.\"\"\"\n    return response.status_code in RETRY_STATUS_CODES\n\n@retry(\n    retry=retry_if_result(should_retry_response),\n    stop=stop_after_attempt(3),\n    wait=wait_exponential_jitter(initial=1, max=10),\n)\ndef http_request(method: str, url: str, **kwargs) -> httpx.Response:\n    \"\"\"Make HTTP request with retry on transient status codes.\"\"\"\n    return httpx.request(method, url, timeout=30, **kwargs)\n```\n\n### Pattern 4: Combined Exception and Status Retry\n\nHandle both network exceptions and HTTP status codes.\n\n```python\nfrom tenacity import (\n    retry,\n    retry_if_exception_type,\n    retry_if_result,\n    stop_after_attempt,\n    wait_exponential_jitter,\n    before_sleep_log,\n)\nimport logging\nimport httpx\n\nlogger = logging.getLogger(__name__)\n\nTRANSIENT_EXCEPTIONS = (\n    ConnectionError,\n    TimeoutError,\n    httpx.ConnectError,\n    httpx.ReadTimeout,\n)\nRETRY_STATUS_CODES = {429, 500, 502, 503, 504}\n\ndef is_retryable_response(response: httpx.Response) -> bool:\n    return response.status_code in RETRY_STATUS_CODES\n\n@retry(\n    retry=(\n        retry_if_exception_type(TRANSIENT_EXCEPTIONS) |\n        retry_if_result(is_retryable_response)\n    ),\n    stop=stop_after_attempt(5),\n    wait=wait_exponential_jitter(initial=1, max=30),\n    before_sleep=before_sleep_log(logger, logging.WARNING),\n)\ndef robust_http_call(\n    method: str,\n    url: str,\n    **kwargs,\n) -> httpx.Response:\n    \"\"\"HTTP call with comprehensive retry handling.\"\"\"\n    return httpx.request(method, url, timeout=30, **kwargs)\n```\n\n## Advanced Patterns\n\n### Pattern 5: Logging Retry Attempts\n\nTrack retry behavior for debugging and alerting.\n\n```python\nfrom tenacity import retry, stop_after_attempt, wait_exponential\nimport structlog\n\nlogger = structlog.get_logger()\n\ndef log_retry_attempt(retry_state):\n    \"\"\"Log detailed retry information.\"\"\"\n    exception = retry_state.outcome.exception()\n    logger.warning(\n        \"Retrying operation\",\n        attempt=retry_state.attempt_number,\n        exception_type=type(exception).__name__,\n        exception_message=str(exception),\n        next_wait_seconds=retry_state.next_action.sleep if retry_state.next_action else None,\n    )\n\n@retry(\n    stop=stop_after_attempt(3),\n    wait=wait_exponential(multiplier=1, max=10),\n    before_sleep=log_retry_attempt,\n)\ndef call_with_logging(request: dict) -> dict:\n    \"\"\"External call with retry logging.\"\"\"\n    ...\n```\n\n### Pattern 6: Timeout Decorator\n\nCreate reusable timeout decorators for consistent timeout handling.\n\n```python\nimport asyncio\nfrom functools import wraps\nfrom typing import TypeVar, Callable\n\nT = TypeVar(\"T\")\n\ndef with_timeout(seconds: float):\n    \"\"\"Decorator to add timeout to async functions.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        @wraps(func)\n        async def wrapper(*args, **kwargs) -> T:\n            return await asyncio.wait_for(\n                func(*args, **kwargs),\n                timeout=seconds,\n            )\n        return wrapper\n    return decorator\n\n@with_timeout(30)\nasync def fetch_with_timeout(url: str) -> dict:\n    \"\"\"Fetch URL with 30 second timeout.\"\"\"\n    async with httpx.AsyncClient() as client:\n        response = await client.get(url)\n        return response.json()\n```\n\n### Pattern 7: Cross-Cutting Concerns via Decorators\n\nStack decorators to separate infrastructure from business logic.\n\n```python\nfrom functools import wraps\nfrom typing import TypeVar, Callable\nimport structlog\n\nlogger = structlog.get_logger()\nT = TypeVar(\"T\")\n\ndef traced(name: str | None = None):\n    \"\"\"Add tracing to function calls.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        span_name = name or func.__name__\n\n        @wraps(func)\n        async def wrapper(*args, **kwargs) -> T:\n            logger.info(\"Operation started\", operation=span_name)\n            try:\n                result = await func(*args, **kwargs)\n                logger.info(\"Operation completed\", operation=span_name)\n                return result\n            except Exception as e:\n                logger.error(\"Operation failed\", operation=span_name, error=str(e))\n                raise\n        return wrapper\n    return decorator\n\n# Stack multiple concerns\n@traced(\"fetch_user_data\")\n@with_timeout(30)\n@retry(stop=stop_after_attempt(3), wait=wait_exponential_jitter())\nasync def fetch_user_data(user_id: str) -> dict:\n    \"\"\"Fetch user with tracing, timeout, and retry.\"\"\"\n    ...\n```\n\n### Pattern 8: Dependency Injection for Testability\n\nPass infrastructure components through constructors for easy testing.\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\nclass Logger(Protocol):\n    def info(self, msg: str, **kwargs) -> None: ...\n    def error(self, msg: str, **kwargs) -> None: ...\n\nclass MetricsClient(Protocol):\n    def increment(self, metric: str, tags: dict | None = None) -> None: ...\n    def timing(self, metric: str, value: float) -> None: ...\n\n@dataclass\nclass UserService:\n    \"\"\"Service with injected infrastructure.\"\"\"\n\n    repository: UserRepository\n    logger: Logger\n    metrics: MetricsClient\n\n    async def get_user(self, user_id: str) -> User:\n        self.logger.info(\"Fetching user\", user_id=user_id)\n        start = time.perf_counter()\n\n        try:\n            user = await self.repository.get(user_id)\n            self.metrics.increment(\"user.fetch.success\")\n            return user\n        except Exception as e:\n            self.metrics.increment(\"user.fetch.error\")\n            self.logger.error(\"Failed to fetch user\", user_id=user_id, error=str(e))\n            raise\n        finally:\n            elapsed = time.perf_counter() - start\n            self.metrics.timing(\"user.fetch.duration\", elapsed)\n\n# Easy to test with fakes\nservice = UserService(\n    repository=FakeRepository(),\n    logger=FakeLogger(),\n    metrics=FakeMetrics(),\n)\n```\n\n### Pattern 9: Fail-Safe Defaults\n\nDegrade gracefully when non-critical operations fail.\n\n```python\nfrom typing import TypeVar\nfrom collections.abc import Callable\n\nT = TypeVar(\"T\")\n\ndef fail_safe(default: T, log_failure: bool = True):\n    \"\"\"Return default value on failure instead of raising.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        @wraps(func)\n        async def wrapper(*args, **kwargs) -> T:\n            try:\n                return await func(*args, **kwargs)\n            except Exception as e:\n                if log_failure:\n                    logger.warning(\n                        \"Operation failed, using default\",\n                        function=func.__name__,\n                        error=str(e),\n                    )\n                return default\n        return wrapper\n    return decorator\n\n@fail_safe(default=[])\nasync def get_recommendations(user_id: str) -> list[str]:\n    \"\"\"Get recommendations, return empty list on failure.\"\"\"\n    ...\n```\n\n## Best Practices Summary\n\n1. **Retry only transient errors** - Don't retry bugs or authentication failures\n2. **Use exponential backoff** - Give services time to recover\n3. **Add jitter** - Prevent thundering herd from synchronized retries\n4. **Cap total duration** - `stop_after_attempt(5) | stop_after_delay(60)`\n5. **Log every retry** - Silent retries hide systemic problems\n6. **Use decorators** - Keep retry logic separate from business logic\n7. **Inject dependencies** - Make infrastructure testable\n8. **Set timeouts everywhere** - Every network call needs a timeout\n9. **Fail gracefully** - Return cached\u002Fdefault values for non-critical paths\n10. **Monitor retry rates** - High retry rates indicate underlying issues\n",{"name":5,"description":7},"main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fpython-development\u002Fskills\u002Fpython-resilience",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill python-resilience",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill python-resilience",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill python-resilience","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fpython-development\u002Fskills\u002Fpython-resilience\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]