Repository navigation
feat(transport): add opt-in bounded upstream retry advice #27
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
Merged
Changes from all commits
Commits
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| # Bounded upstream Retry-After advice | ||
|
|
||
| `UPSTREAM_RETRY_AFTER_ADVICE_ENABLED` defaults to false. Unset or empty settings | ||
| use their defaults. Disabled traffic keeps its existing retries, waits, headers, | ||
| response bodies and free-pool cooldown timing. Native Worker and raw Flask paths | ||
| continue to forward upstream bytes without parsing or scheduling retries. | ||
|
|
||
| Enable local advice with: | ||
|
|
||
| ```text | ||
| UPSTREAM_RETRY_AFTER_ADVICE_ENABLED=true | ||
| UPSTREAM_RETRY_AFTER_MAX_SECONDS=3600 | ||
| ``` | ||
|
|
||
| The maximum defaults to 3600 seconds and accepts whole seconds from 1 to 604800, | ||
| matching the existing free-pool cooldown ceiling. An invalid flag or enabled | ||
| maximum disables advice and logs the setting name once per process, without its | ||
| value. The maximum is ignored while advice is disabled. | ||
|
|
||
| `services.retry_advice.parse_retry_advice` returns immutable local advice with | ||
| `source`, `observed_at`, `retry_at`, `delay_seconds` and `scope`. Times are Unix | ||
| seconds. It recognizes these formats, using case-insensitive header names: | ||
|
|
||
| - `Retry-After`: nonnegative decimal seconds or an HTTP-date with a timezone. | ||
| - `X-RateLimit-Reset`: an absolute Unix timestamp in seconds. | ||
| - `X-RateLimit-Reset-Requests` and `X-RateLimit-Reset-Tokens`: duration strings, | ||
| such as `1h2m3.4s`, when the matching remaining counter is finite and exhausted. | ||
| - `Anthropic-RateLimit-Requests-Reset` and `Anthropic-RateLimit-Tokens-Reset`: | ||
| ISO timestamps with a timezone, when the matching remaining counter is exhausted. | ||
|
|
||
| Malformed, nonfinite, zero-delay and stale hints are ignored. Individual values | ||
| are limited to 512 characters. When several active hints are valid, the latest | ||
| reset wins so an exhausted dimension is not bypassed. Only local advice is | ||
| clamped; the upstream header is never replaced. With observation time 100, | ||
| `Retry-After: 20` yields retry time 120. With maximum 5 it yields local retry time | ||
| 105, while the header remains `20`. | ||
|
|
||
| The [upstream outcome](upstream-outcomes.md) classifier keeps 429 throttling neutral for provider health. | ||
| Exhausted remaining counters label advice `quota_exhausted`; other 429 advice | ||
| uses `rate_limit`; provider failures use `provider`. Authentication and caller | ||
| errors do not supply retry advice. Successful exhausted responses can supply | ||
| cooldown advice without changing their health classification. | ||
|
|
||
| Managed retries still require the existing method/idempotency/transport policy | ||
| and attempt limit. Parsing never grants replay permission. An ambiguous POST or | ||
| stream does not gain a retry from headers. While enabled, legacy timeout-body | ||
| retries additionally require a safe method or an idempotency key. Connect-timeout | ||
| retries remain allowed by the existing policy because nothing reached upstream. | ||
| Existing managed response normalization remains in the proxy service. | ||
|
|
||
| For an allowed retry, the scheduler waits for the greater of existing backoff | ||
| and bounded advice. Invalid or absent advice uses existing backoff. An optional | ||
| monotonic `deadline` on `_make_base_request`, or the existing Flask | ||
| `g.cascade_deadline`, must cover the entire wait. A refused wait returns the | ||
| original upstream result. The scheduler rechecks the deadline after sleeping and | ||
| does not dispatch a late retry. Without a shared deadline, existing per-attempt | ||
| timeouts remain unchanged; the feature does not create a request-wide deadline | ||
| or reserve time for another attempt. Free-pool `retry_seconds` uses the same | ||
| bounded parser while enabled, including a bounded fallback cooldown. | ||
|
|
||
| There are no new routes, response headers, storage tables or dependencies. Advice | ||
| reads headers only and retains no credentials, prompts or response content. | ||
| Existing cooldown storage and its monotonic extension rules remain in use; | ||
| enabling a lower maximum does not shorten a previously stored cooldown. Advice | ||
| is neither proof of provider capacity nor authorization for additional cost. | ||
| Retries can consume additional quota only when already authorized by transport | ||
| policy. The Worker forwards both settings to the Container. |
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 |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| """Managed attempt scheduling, separate from raw dispatch and normalization.""" | ||
|
|
||
| import math | ||
| import time | ||
| from typing import Callable | ||
|
|
||
| import requests | ||
| from flask import g, has_request_context | ||
|
|
||
| from services.retry_advice import parse_retry_advice, retry_advice_settings | ||
| from services.upstream_outcome import UpstreamOutcome | ||
| from services.upstream_transport import close_retry_response | ||
|
|
||
| Attempt = Callable[[int], requests.Response] | ||
| Outcome = Callable[[], UpstreamOutcome] | ||
|
|
||
|
|
||
| def retry_managed_attempt( | ||
| attempt: Attempt, | ||
| outcome: Outcome, | ||
| *, | ||
| retry_count: int, | ||
| max_retries: int, | ||
| retry_delay: float, | ||
| response: requests.Response | None = None, | ||
| deadline: float | None = None, | ||
| sleep: Callable[[float], None] = time.sleep, | ||
| ) -> requests.Response | None: | ||
| """Dispatch again only under the existing transport's replay permission. | ||
|
|
||
| A supplied deadline is monotonic. The existing cascade deadline is used when | ||
| available; absent one, per-attempt timeouts remain the transport's policy. | ||
| None means that the original response/error must finish normally. | ||
| """ | ||
| classified = outcome() | ||
| if not classified.replay_permission or retry_count >= max_retries: | ||
| return None | ||
| settings = retry_advice_settings() | ||
| delay = retry_delay * (retry_count + 1) | ||
| if settings.enabled: | ||
| if response is not None: | ||
| advice = parse_retry_advice( | ||
| response.headers, | ||
| now=time.time(), | ||
| status_code=response.status_code, | ||
| max_seconds=settings.max_seconds, | ||
| ) | ||
| if advice is not None: | ||
| delay = max(delay, advice.delay_seconds) | ||
| if deadline is None and has_request_context(): | ||
| deadline = getattr(g, "cascade_deadline", None) | ||
| if deadline is not None: | ||
| if not math.isfinite(deadline) or delay >= deadline - time.monotonic(): | ||
| return None | ||
| # Keep the original response usable if scheduling consumes the budget. | ||
| sleep(delay) | ||
| if time.monotonic() >= deadline: | ||
| return None | ||
| if response is not None: | ||
| close_retry_response(response) | ||
| return attempt(retry_count + 1) | ||
| if response is not None: | ||
| close_retry_response(response) | ||
| sleep(delay) | ||
| return attempt(retry_count + 1) |
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When advice is enabled, this call omits
status_code, soparse_retry_adviceclassifies every free-route outcome as its default 429. The callers inroutes/free_routes.pyalso useretry_secondsfor 401/403/404 and other failures; consequently, aRetry-Afteron an authentication or caller error is accepted and can block a provider or model for up to the configured maximum, even though the parser explicitly rejects advice for those statuses. Add a status parameter and pass the available upstream status so these responses use the fallback cooldown instead.Useful? React with 👍 / 👎.