fix(models): share rate-limit cooldowns within quota groups (#8427)

* fix(models): share rate-limit cooldowns within quota groups

Signed-off-by: PeaceMaker-best <221849497+PeaceMaker-best@users.noreply.github.com>

* docs(models): clarify request admission polling

Signed-off-by: Willem Jiang <willem.jiang@gmail.com>

---------

Signed-off-by: PeaceMaker-best <221849497+PeaceMaker-best@users.noreply.github.com>
Signed-off-by: Willem Jiang <willem.jiang@gmail.com>
Co-authored-by: PeaceMaker-best <221849497+PeaceMaker-best@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
PeaceMaker-best 2026-11-21 11:40:44 +08:00 committed by GitHub
parent 9337f5b032
commit b41bd8b2ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 194 additions and 3 deletions

View File

@ -98,6 +98,15 @@ BaseChatModel invoke/stream hooks. Restart the Gateway after changing,
disabling or regrouping active policies; conflicting settings fail model disabling or regrouping active policies; conflicting settings fail model
construction instead of resetting a live budget. construction instead of resetting a live budget.
When Agent middleware receives HTTP 429 with a valid `Retry-After` (seconds or
HTTP date) or `retry-after-ms` of up to 24 hours, new requests in that admission
group also wait for the provider's cooldown, even if the failed call has no
retries left. A shorter subsequent hint cannot shorten the pause. Already
dispatched calls and independent groups are unaffected. Queue bounds, FIFO,
cancellation and `max_wait_seconds` still apply, so a waiting call can time out
before the cooldown ends. Missing or invalid hints and other statuses do not
pause peers. Calls outside Agent middleware do not publish cooldown feedback.
When enabled, exposed SDK `max_retries` settings are set to zero: SDK retries When enabled, exposed SDK `max_retries` settings are set to zero: SDK retries
would bypass the admission hook. Claude and Codex also set their provider-internal would bypass the admission hook. Claude and Codex also set their provider-internal
`retry_max_attempts` to one, regardless of config or caller overrides, and log a `retry_max_attempts` to one, regardless of config or caller overrides, and log a

View File

@ -26,7 +26,7 @@ from langgraph.errors import GraphBubbleUp
from deerflow.agents.middlewares.model_response import append_visible_text, is_empty_stop_response, last_ai_message from deerflow.agents.middlewares.model_response import append_visible_text, is_empty_stop_response, last_ai_message
from deerflow.config.app_config import AppConfig from deerflow.config.app_config import AppConfig
from deerflow.models.request_admission import AdmissionError from deerflow.models.request_admission import AdmissionError, RequestAdmission
from deerflow.models.response_errors import EmptyModelResponseError from deerflow.models.response_errors import EmptyModelResponseError
from deerflow.utils.custom_events import aemit_custom_event, emit_custom_event from deerflow.utils.custom_events import aemit_custom_event, emit_custom_event
from deerflow.utils.retry_after import bounded_retry_after_ms, parse_retry_after_date_ms from deerflow.utils.retry_after import bounded_retry_after_ms, parse_retry_after_date_ms
@ -826,6 +826,7 @@ class LLMErrorHandlingMiddleware(AgentMiddleware[AgentState]):
self._release_half_open_probe(admission=admission) self._release_half_open_probe(admission=admission)
raise raise
except Exception as exc: except Exception as exc:
_share_rate_limit_cooldown(request, exc)
retriable, reason = self._classify_error(exc) retriable, reason = self._classify_error(exc)
max_attempts = self._max_attempts_for(exc, reason) max_attempts = self._max_attempts_for(exc, reason)
should_retry = retriable and attempt < max_attempts should_retry = retriable and attempt < max_attempts
@ -891,6 +892,7 @@ class LLMErrorHandlingMiddleware(AgentMiddleware[AgentState]):
self._release_half_open_probe(admission=admission) self._release_half_open_probe(admission=admission)
raise raise
except Exception as exc: except Exception as exc:
_share_rate_limit_cooldown(request, exc)
retriable, reason = self._classify_error(exc) retriable, reason = self._classify_error(exc)
max_attempts = self._max_attempts_for(exc, reason) max_attempts = self._max_attempts_for(exc, reason)
should_retry = retriable and attempt < max_attempts should_retry = retriable and attempt < max_attempts
@ -1027,6 +1029,21 @@ def _as_http_status(value: Any) -> int | None:
return None return None
def _share_rate_limit_cooldown(request: ModelRequest, exc: BaseException) -> None:
"""Publish a 429 hint even when this call has exhausted its retry budget."""
if _extract_status_code(exc) != 429:
return
try:
limiter = getattr(request.model, "rate_limiter", None)
if isinstance(limiter, RequestAdmission):
wait_ms = _extract_retry_after_ms(exc)
if wait_ms is not None:
limiter.defer_for(wait_ms / 1000)
except Exception:
# Bookkeeping must not replace the provider's original error outcome.
logger.debug("Could not share provider cooldown with model admission")
def _extract_retry_after_ms(exc: BaseException) -> int | None: def _extract_retry_after_ms(exc: BaseException) -> int | None:
response = getattr(exc, "response", None) response = getattr(exc, "response", None)
headers = getattr(response, "headers", None) headers = getattr(response, "headers", None)

View File

@ -48,6 +48,10 @@ transport, so they check the payload that DeerFlow sends.
Unpaced models keep their own retry policy. Unpaced models keep their own retry policy.
- **`Retry-After` goes through `utils.retry_after`.** HTTP dates are read as UTC, - **`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.
- **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.
Cover provider feedback in `tests/test_model_request_admission.py`.
## Provider wire rules ## Provider wire rules

View File

@ -6,6 +6,7 @@ Requests are evenly spaced; idle time never accumulates a burst allowance.
""" """
import asyncio import asyncio
import math
import threading import threading
import time import time
from collections import deque from collections import deque
@ -53,6 +54,14 @@ class RequestAdmission(BaseRateLimiter):
self._waiters.append(ticket) self._waiters.append(ticket)
return False, ticket return False, ticket
def defer_for(self, seconds: float) -> None:
"""Extend the shared dispatch schedule without revoking in-flight work."""
if not math.isfinite(seconds) or seconds < 0:
raise ValueError("Admission cooldown must be finite and non-negative")
with self._lock:
# A later, shorter provider hint must not undo an existing pause.
self._next = max(self._next, monotonic() + seconds)
def _remove(self, ticket: object) -> None: def _remove(self, ticket: object) -> None:
with self._lock: with self._lock:
self._waiters.remove(ticket) self._waiters.remove(ticket)
@ -64,9 +73,9 @@ class RequestAdmission(BaseRateLimiter):
raise AdmissionError("LLM admission timed out before dispatch; increase max_wait_seconds or reduce workload.") raise AdmissionError("LLM admission timed out before dispatch; increase max_wait_seconds or reduce workload.")
with self._lock: with self._lock:
until_next = self._next - now until_next = self._next - now
# Track short admission intervals rather than imposing a 20/s ceiling. # Cap each sleep at 50 ms and shorten it for an approaching dispatch or deadline.
# Non-head waiters still yield when the schedule is already due. # Non-head waiters still yield when the schedule is already due.
return min(0.05, self._interval, until_next if until_next > 0 else self._interval, remaining) return min(0.05, until_next if until_next > 0 else self._interval, remaining)
def acquire(self, *, blocking: bool = True) -> bool: def acquire(self, *, blocking: bool = True) -> bool:
acquired, ticket = self._try_or_enqueue(blocking=blocking) acquired, ticket = self._try_or_enqueue(blocking=blocking)

View File

@ -3,10 +3,13 @@
import asyncio import asyncio
import json import json
import logging import logging
import math
import threading import threading
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
import httpx
import pytest import pytest
import pytest_asyncio
import yaml import yaml
from pydantic import ValidationError from pydantic import ValidationError
@ -219,6 +222,155 @@ def test_group_sharing_isolation_and_conflict(registry, clock):
admission.get_request_admission("a", config.model_copy(update={"requests_per_minute": 30})) admission.get_request_admission("a", config.model_copy(update={"requests_per_minute": 30}))
@pytest_asyncio.fixture
async def admission_graphs(monkeypatch, registry, clock):
"""Keep the graph, factory and OpenAI SDK real; replace only HTTP transport."""
from langchain.agents import create_agent
from deerflow.agents.middlewares import llm_error_handling_middleware as errors
from deerflow.config.app_config import AppConfig
from deerflow.models.factory import create_chat_model
monkeypatch.setattr(errors, "_PROCESS_LIMITER", None)
monkeypatch.setattr(errors, "_CAP_RESOLVED", False)
clients = []
async_clients = []
def build(name, *, group="shared", status=200, headers=None, max_wait_seconds=300):
requests = []
def respond(request):
requests.append((clock[0], json.loads(request.content)))
if status != 200:
return httpx.Response(status, headers=headers or {}, json={"error": {"message": "offline provider failure", "type": "rate_limit_error"}})
return httpx.Response(200, json={"id": "offline", "model": name, "choices": [{"index": 0, "message": {"role": "assistant", "content": "done"}, "finish_reason": "stop"}]})
client = httpx.Client(transport=httpx.MockTransport(respond))
async_client = httpx.AsyncClient(transport=httpx.MockTransport(respond))
clients.append(client)
async_clients.append(async_client)
config = AppConfig.model_validate(
{
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"llm_call": {"retry_max_attempts": 1},
"models": [{"name": name, "use": "langchain_openai:ChatOpenAI", "model": name, "api_key": "offline-test-key", "request_admission": {"requests_per_minute": 6000, "group": group, "max_wait_seconds": max_wait_seconds}}],
}
)
model = create_chat_model(name, app_config=config, attach_tracing=False, http_client=client, http_async_client=async_client, use_responses_api=False, disable_streaming=True)
graph = create_agent(model=model, middleware=[errors.LLMErrorHandlingMiddleware(app_config=config)])
return graph, model.rate_limiter, requests
try:
yield build
finally:
for client in clients:
client.close()
for client in async_clients:
await client.aclose()
@pytest.mark.asyncio
@pytest.mark.parametrize("mode", ["sync", "async"])
@pytest.mark.parametrize("status,headers,paused", [(429, {"retry-after": "10"}, True), (429, {"retry-after-ms": "10000"}, True), (429, {"retry-after": "invalid"}, False), (429, {}, False), (503, {"retry-after": "10"}, False)])
async def test_provider_cooldown_reaches_peers_even_on_final_attempt(admission_graphs, clock, mode, status, headers, paused):
graph, limiter, requests = admission_graphs("research", status=status, headers=headers)
_, peer, _ = admission_graphs("writer")
_, independent, _ = admission_graphs("other", group="other")
payload = {"messages": [("user", "Research this topic")]}
if mode == "sync":
graph.invoke(payload)
else:
await graph.ainvoke(payload)
assert len(requests) == 1 # The provider failure really fired; no SDK retry.
assert peer is limiter
clock[0] = 1 # Normal RPM spacing has elapsed, but the provider's hint has not.
assert peer.acquire(blocking=False) is not paused
assert independent.acquire(blocking=False)
@pytest.mark.asyncio
@pytest.mark.parametrize("cancel_first", [False, True], ids=["fifo", "cancelled-head"])
async def test_agent_graphs_resume_after_shared_cooldown(admission_graphs, monkeypatch, clock, cancel_first):
owner, limiter, failed_requests = admission_graphs("research", status=429, headers={"retry-after": "10"})
first, _, first_requests = admission_graphs("writer")
last, _, last_requests = admission_graphs("reviewer")
payload = {"messages": [("user", "Continue work")]}
await owner.ainvoke(payload)
assert len(failed_requests) == 1
clock[0] = 1
parked = asyncio.Event()
original_enqueue = limiter._try_or_enqueue
def observe_enqueue(*, blocking):
result = original_enqueue(blocking=blocking)
if result[1] is not None:
parked.set()
return result
monkeypatch.setattr(limiter, "_try_or_enqueue", observe_enqueue)
tasks = []
try:
tasks.append(asyncio.create_task(first.ainvoke(payload)))
await asyncio.wait_for(parked.wait(), 2)
parked.clear()
tasks.append(asyncio.create_task(last.ainvoke(payload)))
await asyncio.wait_for(parked.wait(), 2)
assert not first_requests and not last_requests
assert len(limiter._waiters) == 2
if cancel_first:
tasks[0].cancel()
with pytest.raises(asyncio.CancelledError):
await tasks[0]
assert len(limiter._waiters) == 1
clock[0] = 10
completed = tasks[1] if cancel_first else tasks[0]
assert (await asyncio.wait_for(completed, 2))["messages"][-1].content == "done"
if not cancel_first:
assert not last_requests
clock[0] = 11
await asyncio.wait_for(tasks[1], 2)
assert [at for at, _ in first_requests] == ([] if cancel_first else [10])
assert [at for at, _ in last_requests] == ([10] if cancel_first else [11])
assert not limiter._waiters
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
def test_cooldown_extends_schedule_without_spending_a_permit(clock):
limiter = admission.RequestAdmission(RequestAdmissionConfig(requests_per_minute=60))
limiter.defer_for(10)
clock[0] = 1
limiter.defer_for(2)
assert not limiter.acquire(blocking=False)
clock[0] = 10
assert limiter.acquire(blocking=False)
assert not limiter.acquire(blocking=False)
clock[0] = 11
assert limiter.acquire(blocking=False)
@pytest.mark.parametrize("delay", [math.inf, math.nan, -1])
def test_invalid_cooldown_preserves_admission(clock, delay):
limiter = admission.RequestAdmission(RequestAdmissionConfig(requests_per_minute=60))
with pytest.raises(ValueError, match="finite and non-negative"):
limiter.defer_for(delay)
assert limiter.acquire(blocking=False)
def test_cooldown_polling_is_bounded_and_deadline_still_applies(clock, monkeypatch):
limiter = admission.RequestAdmission(RequestAdmissionConfig(requests_per_minute=60000, max_wait_seconds=1))
limiter.defer_for(10)
assert limiter._delay(1) == pytest.approx(0.05)
monkeypatch.setattr(admission.time, "sleep", lambda _: clock.__setitem__(0, 2))
with pytest.raises(admission.AdmissionError, match="timed out"):
limiter.acquire()
assert not limiter._waiters
clock[0] = 10
assert limiter.acquire(blocking=False)
def make_model(monkeypatch, *, name="a", policy=None, provider=False): def make_model(monkeypatch, *, name="a", policy=None, provider=False):
from langchain_core.language_models.fake_chat_models import FakeListChatModel from langchain_core.language_models.fake_chat_models import FakeListChatModel