-
Notifications
You must be signed in to change notification settings - Fork 1
UN-2793 [FEAT] Added exponential backoff retry mechanism for platform service connections #199
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
chandrasekharan-zipstack
merged 17 commits into
main
from
feat/added-retries-for-platform-service-calls
Oct 7, 2025
Merged
Changes from 6 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
ba4ecf4
feat/added-retries-for-platform-service-calls [FEAT] Added exponentia…
chandrasekharan-zipstack 403492c
Delete mypy-errors.txt
chandrasekharan-zipstack 8e305d7
Apply suggestions from code review
chandrasekharan-zipstack 565078a
UN-2793 Moved ConnectionError handling to allow the retry decorator a…
chandrasekharan-zipstack ae9de7a
Merge branch 'main' into feat/added-retries-for-platform-service-calls
chandrasekharan-zipstack fd4240f
UN-2793 [FEAT] Refactor retry mechanism to use backoff library with c…
chandrasekharan-zipstack 8d50eca
Apply suggestion from @coderabbitai[bot]
chandrasekharan-zipstack 2c50779
Apply suggestion from @chandrasekharan-zipstack
chandrasekharan-zipstack 4452b09
Apply suggestion from @chandrasekharan-zipstack
chandrasekharan-zipstack 3649d4a
UN-2793 [FEAT] Added retry decorator for prompt service calls
chandrasekharan-zipstack 5fbc56b
UN-2793 Removed use of backoff lib and added own decorator for retries
chandrasekharan-zipstack 31f7497
minor: Removed a default argument to make calls to decorator explicit
chandrasekharan-zipstack 2039147
misc: Raised err to validate envs for retry
chandrasekharan-zipstack 089cac3
Update src/unstract/sdk/utils/retry_utils.py
chandrasekharan-zipstack bab02a3
Apply suggestion from @coderabbitai[bot]
chandrasekharan-zipstack c86fa90
Apply suggestion from @coderabbitai[bot]
chandrasekharan-zipstack 987f11f
Apply suggestion from @coderabbitai[bot]
chandrasekharan-zipstack File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| __version__ = "v0.77.3" | ||
| __version__ = "v0.78.0" | ||
|
|
||
|
|
||
| def get_sdk_version() -> str: | ||
| """Returns the SDK version.""" | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
chandrasekharan-zipstack marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| """Generic retry utilities using backoff library with configurable prefixes.""" | ||
|
|
||
| import errno | ||
| import logging | ||
| import os | ||
| from collections.abc import Callable | ||
| from typing import Any | ||
|
|
||
| import backoff | ||
| from requests.exceptions import ConnectionError, HTTPError, Timeout | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def is_retryable_error(error: Exception) -> bool: | ||
ritwik-g marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """Check if an error is retryable (preserving existing logic). | ||
|
|
||
| Handles: | ||
| - ConnectionError and Timeout from requests | ||
| - HTTPError with status codes 502, 503, 504 | ||
| - OSError with specific errno codes (ECONNREFUSED, ECONNRESET, etc.) | ||
|
|
||
| Args: | ||
| error: The exception to check | ||
|
|
||
| Returns: | ||
| True if the error should trigger a retry | ||
| """ | ||
| # Requests connection and timeout errors | ||
| if isinstance(error, (ConnectionError | Timeout)): | ||
| return True | ||
chandrasekharan-zipstack marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # HTTP errors with specific status codes | ||
| if isinstance(error, HTTPError): | ||
| if hasattr(error, "response") and error.response is not None: | ||
| status_code = error.response.status_code | ||
| # Retry on server errors and bad gateway | ||
| if status_code in [502, 503, 504]: | ||
| return True | ||
|
|
||
| # OS-level connection failures (preserving existing errno checks) | ||
| if isinstance(error, OSError) and error.errno in { | ||
| errno.ECONNREFUSED, # Connection refused | ||
| getattr(errno, "ECONNRESET", 104), # Connection reset by peer | ||
| getattr(errno, "ETIMEDOUT", 110), # Connection timed out | ||
| getattr(errno, "EHOSTUNREACH", 113), # No route to host | ||
| getattr(errno, "ENETUNREACH", 101), # Network is unreachable | ||
| }: | ||
| return True | ||
|
|
||
| return False | ||
|
|
||
chandrasekharan-zipstack marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| def create_retry_decorator( | ||
| prefix: str = "PLATFORM_SERVICE", | ||
chandrasekharan-zipstack marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| exceptions: tuple[type[Exception], ...] | None = None, | ||
| logger_instance: logging.Logger | None = None, | ||
| ) -> Callable: | ||
| """Create a configured backoff decorator for a specific service. | ||
|
|
||
| Args: | ||
| prefix: Environment variable prefix for configuration | ||
| logger_instance: Optional logger for retry events | ||
| exceptions: Tuple of exception types to retry on. | ||
| Defaults to (ConnectionError, HTTPError, Timeout, OSError) | ||
|
|
||
| Environment variables (using prefix): | ||
| {prefix}_MAX_RETRIES: Maximum retry attempts (default: 3) | ||
| {prefix}_MAX_TIME: Maximum total time in seconds (default: 60) | ||
| {prefix}_BASE_DELAY: Initial delay in seconds (default: 1.0) | ||
| {prefix}_MULTIPLIER: Backoff multiplier (default: 2.0) | ||
| {prefix}_JITTER: Enable jitter true/false (default: true) | ||
|
|
||
| Returns: | ||
| Configured backoff decorator | ||
| """ | ||
| # Set default exceptions if not provided | ||
| if exceptions is None: | ||
| exceptions = (ConnectionError, HTTPError, Timeout, OSError) | ||
|
|
||
chandrasekharan-zipstack marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # Load configuration from environment | ||
| max_tries = int(os.getenv(f"{prefix}_MAX_RETRIES", "3")) + 1 # +1 for initial attempt | ||
| max_time = float(os.getenv(f"{prefix}_MAX_TIME", "60")) | ||
| base = float(os.getenv(f"{prefix}_BASE_DELAY", "1.0")) | ||
| factor = float(os.getenv(f"{prefix}_MULTIPLIER", "2.0")) | ||
| use_jitter = os.getenv(f"{prefix}_JITTER", "true").strip().lower() in { | ||
| "true", | ||
| "1", | ||
| "yes", | ||
| "on", | ||
| } | ||
|
|
||
chandrasekharan-zipstack marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if logger_instance is None: | ||
| logger_instance = logger | ||
|
|
||
| def on_backoff_handler(details: dict[str, Any]) -> None: | ||
| """Log retry attempts with useful context.""" | ||
| exception = details["exception"] | ||
| tries = details["tries"] | ||
| wait = details.get("wait", 0) | ||
|
|
||
| logger_instance.warning( | ||
| "Retry %d/%d for %s: %s (waiting %.1fs)", | ||
| tries, | ||
| max_tries - 1, | ||
| prefix, | ||
| exception, | ||
| wait, | ||
| ) | ||
|
|
||
| def on_giveup_handler(details: dict[str, Any]) -> None: | ||
| """Log when giving up after all retries.""" | ||
| exception = details["exception"] | ||
| tries = details["tries"] | ||
|
|
||
| logger_instance.exception( | ||
| "Giving up after %d retries for %s: %s", tries, prefix, exception | ||
| ) | ||
|
|
||
| # Create the decorator with backoff | ||
| return backoff.on_exception( | ||
| backoff.expo, | ||
| exceptions, # Use the configurable exceptions | ||
| max_tries=max_tries, | ||
| max_time=max_time, | ||
| base=base, | ||
| factor=factor, | ||
| jitter=backoff.full_jitter if use_jitter else None, | ||
| giveup=lambda e: not ( | ||
| is_retryable_error(e) | ||
| or (isinstance(exceptions, tuple) and isinstance(e, exceptions)) | ||
| ), | ||
chandrasekharan-zipstack marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| on_backoff=on_backoff_handler, | ||
| on_giveup=on_giveup_handler, | ||
| ) | ||
|
|
||
|
|
||
| # Retry configured through below envs. | ||
| # - PLATFORM_SERVICE_MAX_RETRIES (default: 3) | ||
| # - PLATFORM_SERVICE_MAX_TIME (default: 60s) | ||
| # - PLATFORM_SERVICE_BASE_DELAY (default: 1.0s) | ||
| # - PLATFORM_SERVICE_MULTIPLIER (default: 2.0) | ||
| # - PLATFORM_SERVICE_JITTER (default: true) | ||
| retry_platform_service_call = create_retry_decorator("PLATFORM_SERVICE") | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.