mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(models): honour fractional and retry-after-ms hints in Claude retries (#8656)
`ClaudeChatModel._calc_backoff_ms` parsed `Retry-After` with `int()` and never read `retry-after-ms`, so a decimal hint from a gateway raised, fell through to HTTP-date parsing, and was dropped. The retry then used the local 2.4 s schedule and could spend its budget inside the same throttle window. Move the header parser into `utils.retry_after.retry_after_hint_ms` (spellings, float seconds, ms units, HTTP-date fallback, 24 h bound) and use it from both the Claude and Codex providers, keeping each caller's clock for HTTP dates. Fixes #8655
This commit is contained in:
parent
f189099c09
commit
e45da192fe
@ -47,7 +47,9 @@ transport, so they check the payload that DeerFlow sends.
|
||||
re-enter admission. Log a warning when this lowers a configured attempt count.
|
||||
Unpaced models keep their own retry policy.
|
||||
- **`Retry-After` goes through `utils.retry_after`.** HTTP dates are read as UTC,
|
||||
a past date means zero, and the delay is bounded.
|
||||
a past date means zero, and the delay is bounded. `retry_after_hint_ms` reads
|
||||
both header spellings and fractional seconds once, so every provider retry
|
||||
loop parses the same hint.
|
||||
- **HTTP 429 hints extend the opted-in group's admission schedule**, including
|
||||
on the last middleware attempt. Shorter hints never shorten a pause. Keep
|
||||
FIFO, cancellation and deadlines intact; unrelated groups stay independent.
|
||||
|
||||
@ -31,7 +31,7 @@ from langchain_core.messages import BaseMessage
|
||||
from pydantic import PrivateAttr
|
||||
|
||||
from deerflow.models.credential_loader import OAUTH_ANTHROPIC_BETAS
|
||||
from deerflow.utils.retry_after import bounded_retry_after_ms, parse_retry_after_date_ms
|
||||
from deerflow.utils.retry_after import retry_after_hint_ms
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@ -465,21 +465,11 @@ class ClaudeChatModel(ChatAnthropic):
|
||||
|
||||
@staticmethod
|
||||
def _calc_backoff_ms(attempt: int, error: Exception) -> int:
|
||||
"""Exponential backoff with a fixed 20% buffer."""
|
||||
"""Prefer the server's retry hint, falling back to the local buffered schedule."""
|
||||
hint_ms = retry_after_hint_ms(error, now=time.time())
|
||||
if hint_ms is not None:
|
||||
return hint_ms
|
||||
|
||||
backoff_ms = 2000 * (1 << (attempt - 1))
|
||||
jitter_ms = int(backoff_ms * 0.2)
|
||||
total_ms = backoff_ms + jitter_ms
|
||||
|
||||
if hasattr(error, "response") and error.response is not None:
|
||||
retry_after = error.response.headers.get("Retry-After")
|
||||
if retry_after:
|
||||
try:
|
||||
hint_ms = bounded_retry_after_ms(int(retry_after) * 1000)
|
||||
if hint_ms is not None:
|
||||
total_ms = hint_ms
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
hint_ms = parse_retry_after_date_ms(retry_after, now=time.time())
|
||||
if hint_ms is not None:
|
||||
total_ms = hint_ms
|
||||
|
||||
return total_ms
|
||||
return backoff_ms + jitter_ms
|
||||
|
||||
@ -25,7 +25,7 @@ from langchain_core.outputs import ChatGeneration, ChatResult
|
||||
|
||||
from deerflow.models.credential_loader import CodexCliCredential, load_codex_cli_credential
|
||||
from deerflow.utils.file_io import await_drained
|
||||
from deerflow.utils.retry_after import bounded_retry_after_ms, parse_retry_after_date_ms
|
||||
from deerflow.utils.retry_after import retry_after_hint_ms
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@ -39,29 +39,7 @@ def _is_valid_call_id(call_id: Any) -> bool:
|
||||
|
||||
def _retry_after_ms(error: Exception) -> int | None:
|
||||
"""Read a bounded retry hint from the error's response headers, if there is one."""
|
||||
response = getattr(error, "response", None)
|
||||
if response is None:
|
||||
return None
|
||||
headers = getattr(response, "headers", None)
|
||||
if not headers:
|
||||
return None
|
||||
|
||||
for header in ("retry-after-ms", "Retry-After-Ms", "retry-after", "Retry-After"):
|
||||
raw = headers.get(header)
|
||||
if not raw:
|
||||
continue
|
||||
try:
|
||||
milliseconds = float(raw) * 1000 if "ms" not in (header.lower()) else float(raw)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
if "ms" in header.lower():
|
||||
continue
|
||||
milliseconds = parse_retry_after_date_ms(str(raw), now=time.time())
|
||||
if milliseconds is None:
|
||||
continue
|
||||
bounded = bounded_retry_after_ms(milliseconds)
|
||||
if bounded is not None:
|
||||
return bounded
|
||||
return None
|
||||
return retry_after_hint_ms(error, now=time.time())
|
||||
|
||||
|
||||
def _calc_backoff_ms(attempt: int, error: Exception | None = None) -> int:
|
||||
|
||||
@ -1,11 +1,17 @@
|
||||
"""Bounds for provider-supplied model retry delays."""
|
||||
|
||||
import math
|
||||
import time
|
||||
from datetime import UTC
|
||||
from email.utils import parsedate_to_datetime
|
||||
|
||||
MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
# Providers disagree on the spelling and the unit of the retry hint, so every
|
||||
# caller reads the same tuple: the ``-ms`` spellings are milliseconds, the
|
||||
# others are seconds or an HTTP date.
|
||||
RETRY_AFTER_HEADERS = ("retry-after-ms", "Retry-After-Ms", "retry-after", "Retry-After")
|
||||
|
||||
|
||||
def bounded_retry_after_ms(delay_ms: int | float) -> int | None:
|
||||
"""Return a finite delay up to 24 hours, or None to use local backoff."""
|
||||
@ -25,3 +31,38 @@ def parse_retry_after_date_ms(raw: str, *, now: float) -> int | None:
|
||||
return bounded_retry_after_ms((target.timestamp() - now) * 1000)
|
||||
except (TypeError, ValueError, OverflowError, OSError):
|
||||
return None
|
||||
|
||||
|
||||
def retry_after_hint_ms(error: Exception | None, *, now: float | None = None) -> int | None:
|
||||
"""Read a bounded retry hint from an error's response headers.
|
||||
|
||||
Every provider retry loop shares this parser so one header cannot mean two
|
||||
different things: decimals are accepted (gateways in front of a provider
|
||||
emit them), ``-ms`` spellings are milliseconds, and anything unparseable,
|
||||
non-finite or past the 24-hour bound falls back to the caller's schedule.
|
||||
``now`` keeps each caller's clock (and its tests' fixed clock) authoritative
|
||||
for HTTP-date hints.
|
||||
"""
|
||||
response = getattr(error, "response", None) if error is not None else None
|
||||
headers = getattr(response, "headers", None)
|
||||
if not headers:
|
||||
return None
|
||||
|
||||
current = time.time() if now is None else now
|
||||
for header in RETRY_AFTER_HEADERS:
|
||||
raw = headers.get(header)
|
||||
if not raw:
|
||||
continue
|
||||
is_milliseconds = "ms" in header.lower()
|
||||
try:
|
||||
milliseconds = float(raw) if is_milliseconds else float(raw) * 1000
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
if is_milliseconds:
|
||||
continue
|
||||
milliseconds = parse_retry_after_date_ms(str(raw), now=current)
|
||||
if milliseconds is None:
|
||||
continue
|
||||
bounded = bounded_retry_after_ms(milliseconds)
|
||||
if bounded is not None:
|
||||
return bounded
|
||||
return None
|
||||
|
||||
@ -22,13 +22,18 @@ def test_unusable_claude_retry_after_uses_default_backoff(attempt: int, raw: str
|
||||
assert ClaudeChatModel._calc_backoff_ms(attempt, error) == 2400 * 2 ** (attempt - 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("raw", "expected_ms"), [("-2", 0), ("0", 0), ("60", 60000), ("86400", 86400000)])
|
||||
@pytest.mark.parametrize(("raw", "expected_ms"), [("-2", 0), ("0", 0), ("60", 60000), ("86400", 86400000), ("3.0", 3000), ("1.5", 1500)])
|
||||
def test_usable_claude_retry_after_is_preserved(raw: str, expected_ms: int) -> None:
|
||||
error = Exception("rate limited")
|
||||
error.response = SimpleNamespace(headers={"Retry-After": raw})
|
||||
assert ClaudeChatModel._calc_backoff_ms(1, error) == expected_ms
|
||||
|
||||
|
||||
def test_millisecond_retry_after_header_is_honoured() -> None:
|
||||
error = SimpleNamespace(response=httpx.Response(429, headers={"retry-after-ms": "1500"}, request=httpx.Request("POST", "https://example.invalid/messages")))
|
||||
assert ClaudeChatModel._calc_backoff_ms(1, error) == 1500
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("mode", ["sync", "async"])
|
||||
@pytest.mark.parametrize("error_type", [anthropic.RateLimitError, anthropic.InternalServerError])
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user