Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: keep Deep Research alive when the provider asks it to slow down (#9720)

Nilaya2eb5341a400
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 7f421f16a0a..fb7beb01d40 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -1241,7 +1241,12 @@ class ExternalProviderClient:
response.status_code,
error_text[:500],
)
- yield _error_sse_line(response.status_code, error_text, self.provider_type)
+ yield _error_sse_line(
+ response.status_code,
+ error_text,
+ self.provider_type,
+ response.headers.get("Retry-After"),
+ )
return
# Manual __anext__ (not `async for`) so we can close the
@@ -1541,7 +1546,12 @@ class ExternalProviderClient:
response.status_code,
error_text[:500],
)
- yield _error_sse_line(response.status_code, error_text, self.provider_type)
+ yield _error_sse_line(
+ response.status_code,
+ error_text,
+ self.provider_type,
+ response.headers.get("Retry-After"),
+ )
return
lines_gen = response.aiter_lines().__aiter__()
@@ -1632,7 +1642,12 @@ class ExternalProviderClient:
response.status_code,
error_text[:500],
)
- yield _error_sse_line(response.status_code, error_text, self.provider_type)
+ yield _error_sse_line(
+ response.status_code,
+ error_text,
+ self.provider_type,
+ response.headers.get("Retry-After"),
+ )
return
# Manual __anext__ loop instead of `async for` — see the
# stream_chat_completion comment for the Python 3.13 +
@@ -1737,7 +1752,12 @@ class ExternalProviderClient:
response.status_code,
error_text[:500],
)
- yield _error_sse_line(response.status_code, error_text, self.provider_type)
+ yield _error_sse_line(
+ response.status_code,
+ error_text,
+ self.provider_type,
+ response.headers.get("Retry-After"),
+ )
return
lines_gen = response.aiter_lines().__aiter__()
@@ -2382,7 +2402,12 @@ class ExternalProviderClient:
f"data: "
f"{_json.dumps({'id': completion_id, 'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': {}, 'finish_reason': None}], '_toolEvent': {'type': 'container_invalidated'}})}"
)
- yield _error_sse_line(response.status_code, error_text, self.provider_type)
+ yield _error_sse_line(
+ response.status_code,
+ error_text,
+ self.provider_type,
+ response.headers.get("Retry-After"),
+ )
return
# NOTE: same manual __anext__ loop as stream_chat_completion — see comment there.
@@ -4159,7 +4184,12 @@ class ExternalProviderClient:
response.status_code,
error_text[:500],
)
- yield _error_sse_line(response.status_code, error_text, self.provider_type)
+ yield _error_sse_line(
+ response.status_code,
+ error_text,
+ self.provider_type,
+ response.headers.get("Retry-After"),
+ )
return
if web_search_active:
@@ -5281,7 +5311,12 @@ class ExternalProviderClient:
retried = True
attempt_container_id = None
continue
- yield _error_sse_line(response.status_code, error_text, self.provider_type)
+ yield _error_sse_line(
+ response.status_code,
+ error_text,
+ self.provider_type,
+ response.headers.get("Retry-After"),
+ )
return
# NOTE: same manual __anext__ loop as stream_chat_completion --
@@ -6649,19 +6684,27 @@ def _readable_provider_error(status_code: int, message: str, provider_type: str)
return f"{text} ({code})" if code and code not in text else text
-def _error_sse_line(status_code: int, message: str, provider_type: str) -> str:
- """Format an error as an SSE data line in OpenAI error format."""
+def _error_sse_line(
+ status_code: int,
+ message: str,
+ provider_type: str,
+ retry_after: str | None = None,
+) -> str:
+ """Format an error as an SSE data line in OpenAI error format.
+
+ ``retry_after`` carries the upstream Retry-After through: this stream is delivered under a
+ 200, so a client that backs off has nowhere else to read the delay from."""
import json
- error_obj = {
- "error": {
- "message": _readable_provider_error(status_code, message, provider_type),
- "type": "provider_error",
- "code": str(status_code),
- "provider": provider_type,
- }
+ error: dict[str, str] = {
+ "message": _readable_provider_error(status_code, message, provider_type),
+ "type": "provider_error",
+ "code": str(status_code),
+ "provider": provider_type,
}
- return f"data: {json.dumps(error_obj)}"
+ if retry_after:
+ error["retry_after"] = retry_after
+ return f"data: {json.dumps({'error': error})}"
def _build_usage_chunk(
diff --git a/studio/backend/core/inference/openai_codex_client.py b/studio/backend/core/inference/openai_codex_client.py
index b67cd623d2e..a6a9e1b715d 100644
--- a/studio/backend/core/inference/openai_codex_client.py
+++ b/studio/backend/core/inference/openai_codex_client.py
@@ -554,13 +554,30 @@ async def ensure_subscription_models(provider_id: str) -> set[str]:
return set()
-def _quota_metadata(response: httpx.Response) -> dict[str, Any]:
+def _retry_after_ms_seconds(response: httpx.Response) -> str | None:
+ """``retry-after-ms`` as whole seconds. The client's own backoff already reads this header,
+ so dropping it here left only it honoured and the caller's retry guessing."""
+ raw = response.headers.get("retry-after-ms")
+ if not raw:
+ return None
+ try:
+ return str(max(0.0, float(raw) / 1000.0))
+ except ValueError:
+ return None
+
+
+def _quota_metadata(response: httpx.Response, *, terminal: bool = False) -> dict[str, Any]:
values = {
- "retry_after": response.headers.get("retry-after"),
+ "retry_after": response.headers.get("retry-after") or _retry_after_ms_seconds(response),
"requests_reset": response.headers.get("x-ratelimit-reset-requests"),
"tokens_reset": response.headers.get("x-ratelimit-reset-tokens"),
}
- return {key: value for key, value in values.items() if value}
+ metadata = {key: value for key, value in values.items() if value}
+ if terminal:
+ # Exhausted, not throttled. Both leave as a 429, so without this a client waits out
+ # a delay that no wait can clear.
+ metadata["terminal"] = True
+ return metadata
async def _upstream_error_detail(response: httpx.Response) -> str | None:
@@ -585,6 +602,23 @@ async def _upstream_error_detail(response: httpx.Response) -> str | None:
return " ".join(detail.split())[:500] or None
+async def _upstream_error_code(response: httpx.Response) -> str | None:
+ """The structured error's code or type. _upstream_error_detail prefers the display message
+ and drops these, which hides a terminal code behind a generic "slow down" sentence."""
+ try:
+ # Same read-then-parse as the sibling above, so this does not depend on being called
+ # after it. A body whose read already failed raises StreamError, not HTTPError.
+ await response.aread()
+ payload = response.json()
+ except (ValueError, json.JSONDecodeError, httpx.HTTPError, httpx.StreamError, AttributeError):
+ return None
+ error = payload.get("error") if isinstance(payload, dict) else None
+ if not isinstance(error, dict):
+ return None
+ code = error.get("code") or error.get("type")
+ return code if isinstance(code, str) and code.strip() else None
+
+
async def _wait_for_cancel(cancel_event: threading.Event) -> None:
while not cancel_event.is_set():
await asyncio.sleep(0.05)
@@ -736,9 +770,10 @@ async def _validated_stream_response(
status = 401,
metadata = {"access_token": token},
)
- retryable = response.status_code in _RETRYABLE_STATUSES and not _is_terminal_quota(
- detail
+ terminal_quota = _is_terminal_quota(detail) or _is_terminal_quota(
+ await _upstream_error_code(response)
)
+ retryable = response.status_code in _RETRYABLE_STATUSES and not terminal_quota
if retryable and attempt < _MAX_TRANSIENT_RETRIES:
await _retry_pause(_retry_delay_seconds(response, attempt), cancel_event)
if cancel_event is not None and cancel_event.is_set():
@@ -749,7 +784,7 @@ async def _validated_stream_response(
raise CodexQuotaError(
"ChatGPT subscription quota is temporarily unavailable.",
status = 429,
- metadata = _quota_metadata(response),
+ metadata = _quota_metadata(response, terminal = terminal_quota),
)
suffix = f" {detail}" if detail else ""
raise CodexTransportError(
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.py
index 8242cd8976b..c1946913b7b 100644
--- a/studio/backend/core/research_runs.py
+++ b/studio/backend/core/research_runs.py
@@ -14,6 +14,7 @@ import threading
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
+from email.utils import parsedate_to_datetime
from typing import Any, AsyncIterator, Callable
import httpx
@@ -122,6 +123,12 @@ _ADMISSION_HEARTBEAT_MISSES = 3
# the poll loop stays bounded however long generation itself may run.
_DEFAULT_MODEL_TIMEOUT_SECONDS = 900.0
_MAX_MODEL_WAIT_BUDGET_SECONDS = 3600.0
+# Bounds a provider's Retry-After when the run has no wall clock of its own: past the hourly
+# windows providers reset on, short of parking a run and its lease on one mistaken header.
+_MAX_RATE_LIMIT_WAIT_SECONDS = 3600.0
+# Lifetime of the internal key one model call authenticates with. Retry waits are bounded by
+# what is left of it: a key that expires mid-backoff fails auth without reaching the provider.
+_MODEL_CALL_KEY_LIFETIME_SECONDS = 2 * 60 * 60
# Headroom so the named stall guards expire before HTTPX's own read timeout does.
_STREAM_READ_TIMEOUT_MARGIN_SECONDS = 30.0
@@ -454,18 +461,97 @@ async def _model_unloaded(response: httpx.Response) -> str | None:
return "named" if _MODEL_NOT_FOUND_CODE in text else None
-def _retry_after_seconds(response: httpx.Response) -> float | None:
- """The response's Retry-After delay in seconds, or None when it is absent or a HTTP date."""
- header = response.headers.get("Retry-After")
- if not header:
+def _retry_after_delay(raw: object) -> float | None:
+ """A Retry-After value as a delay in seconds, or None when it names none or has passed.
+
+ RFC 9110 defines the field as ``HTTP-date / delay-seconds``, and providers behind a CDN do
+ send dates. Reading only the number backs off a second inside a cooldown with minutes left."""
+ if raw is None:
+ return None
+ text = str(raw).strip()
+ if not text:
return None
try:
- delay = float(header.strip())
+ delay = float(text)
except ValueError:
- return None
+ try:
+ at = parsedate_to_datetime(text)
+ except (IndexError, TypeError, ValueError):
+ return None
+ if at is None:
+ return None
+ if at.tzinfo is None:
+ # RFC 9110 dates are GMT; a form that omits the zone is not a local time.
+ at = at.replace(tzinfo = timezone.utc)
+ delay = (at - datetime.now(timezone.utc)).total_seconds()
return delay if delay > 0 else None
+def _retry_after_seconds(response: httpx.Response) -> float | None:
+ """The response's Retry-After delay in seconds, or None when it is absent or already past."""
+ return _retry_after_delay(response.headers.get("Retry-After"))
+
+
+async def _peek_stream_head(lines: AsyncIterator[str]) -> str | None:
+ """The stream's first line, or None when it ends without one.
+
+ One line only: a queue notice belongs to the loop that refreshes the admission bound, and the
+ refusal below is always a stream's first line."""
+ async for line in lines:
+ return line
+ return None
+
+
+def _stream_rate_limit_delay(head: str | None) -> float | None:
+ """The delay a proxied provider rate-limit refusal asks for: None when the stream does not
+ open with one, 0.0 when it names no delay.
+
+ core.inference.external_provider turns an upstream non-200 into a 200 stream carrying one
+ OpenAI-shaped error line, so a 429 survives only there: as ``code`` (``type`` for the ChatGPT
+ connection) plus the forwarded Retry-After."""
+ if head is None or not head.startswith("data:"):
+ return None
+ try:
+ chunk = json.loads(head[5:].strip())
+ except (TypeError, ValueError):
+ return None
+ error = chunk.get("error") if isinstance(chunk, dict) else None
+ if not isinstance(error, dict):
+ return None
+ if str(error.get("code")) != "429" and error.get("type") != "rate_limit_error":
+ return None
+ metadata = error.get("metadata")
+ if isinstance(metadata, dict) and metadata.get("terminal"):
+ # Quota exhausted rather than throttled: no wait clears it, so surface it now.
+ return None
+ requested = error.get("retry_after")
+ if requested is None and isinstance(metadata, dict):
+ requested = metadata.get("retry_after")
+ return _retry_after_delay(requested) or 0.0
+
+
+async def _with_head(head: str | None, rest: AsyncIterator[str]) -> AsyncIterator[str]:
+ """``rest`` with the line already read off it put back in front.
+
+ Explicitly against None, not truthiness: a blank SSE separator line is a line."""
+ if head is not None:
+ yield head
+ async for line in rest:
+ yield line
+
+
+def _rate_limit_wait(requested: float, remaining: float, headroom: float) -> float:
+ """How much of a provider's requested retry delay this call can afford.
+
+ The delay is the provider's, not a share of the model-load budget, so it is bounded by what is
+ left of the call minus the room the re-send needs; coming back early only spends an attempt on
+ the same refusal. The standing ceiling covers a run with no wall clock at all."""
+ # Never reserve all of what is left: a call whose wall clock is no larger than its
+ # first-output budget reserves the whole of it, and every wait collapses to zero.
+ headroom = min(headroom, remaining / 2)
+ return max(0.0, min(requested, _MAX_RATE_LIMIT_WAIT_SECONDS, remaining - headroom))
+
+
def _local_model_ready() -> bool:
"""Whether the local chat-completions path has a model to serve, using the same two checks
routes.inference.openai_chat_completions makes before it 400s. Fails open when neither
@@ -1066,6 +1152,24 @@ class ResearchSupervisor:
remaining -= _MODEL_WAIT_POLL_SECONDS
await self._check_active(run_id)
+ async def _wait_out_rate_limit(
+ self, run: dict, requested: float, deadline: float, headroom: float
+ ) -> None:
+ """Wait out a provider's retry delay, whatever carried it, against the same budget."""
+ remaining = deadline - asyncio.get_running_loop().time()
+ await self._wait_out_retry_after(
+ run["id"], _rate_limit_wait(requested, remaining, headroom)
+ )
+
+ async def _wait_out_retry_after(self, run_id: str, delay: float) -> None:
+ """Wait out a provider-set retry delay in the same poll-sized slices as the model waits
+ above, so a cancel or a lost lease ends the run during the wait rather than after it."""
+ remaining = delay
+ while remaining > 0:
+ await self._check_active(run_id)
+ await asyncio.sleep(min(_MODEL_WAIT_POLL_SECONDS, remaining))
+ remaining -= _MODEL_WAIT_POLL_SECONDS
+
@staticmethod
def _absorb_late_task(run_id: str, what: str, task: asyncio.Task) -> None:
"""Retrieve the outcome of a task that outlived the cleanup bound."""
@@ -1173,7 +1277,10 @@ class ResearchSupervisor:
preview_labels: bool = False,
) -> tuple[str, str, str | None, dict[str, int] | None]:
call_id = uuid.uuid4().hex
- expires = (datetime.now(timezone.utc) + timedelta(hours = 2)).isoformat()
+ expires = (
+ datetime.now(timezone.utc) + timedelta(seconds = _MODEL_CALL_KEY_LIFETIME_SECONDS)
+ ).isoformat()
+ key_minted = asyncio.get_running_loop().time()
token, key = await asyncio.to_thread(
auth_storage.create_api_key,
username = run["ownerSubject"],
@@ -1337,6 +1444,12 @@ class ResearchSupervisor:
ModelOutputIdleTimeout,
)
+ call_started = loop.time()
+ # No backoff below may outlast this call's wall clock or the key the re-send
+ # authenticates with, so all of them measure against whichever ends first.
+ retry_deadline = key_minted + _MODEL_CALL_KEY_LIFETIME_SECONDS
+ if model_timeout:
+ retry_deadline = min(retry_deadline, call_started + model_timeout)
async with (
_wall_clock_timeout(model_timeout or None),
httpx.AsyncClient(timeout = timeout, trust_env = False) as client,
@@ -1373,7 +1486,6 @@ class ResearchSupervisor:
response = await send_task
response.raise_for_status()
first_output_deadline = loop.time() + first_output_budget
- break
except (httpx.TransportError, httpx.HTTPStatusError) as exc:
# Only reachable before a body byte is touched (the stream is consumed
# after this loop), so a re-send cannot duplicate report text.
@@ -1382,9 +1494,14 @@ class ResearchSupervisor:
if isinstance(exc, httpx.HTTPStatusError)
else None
)
+ rate_limited = (
+ isinstance(exc, httpx.HTTPStatusError)
+ and exc.response.status_code == 429
+ )
retryable = (
not isinstance(exc, httpx.HTTPStatusError)
or exc.response.status_code >= 500
+ or rate_limited
)
if unloaded:
model_waits += 1
@@ -1407,13 +1524,40 @@ class ResearchSupervisor:
):
raise
else:
- # re-check the lease and cancellation before re-sending.
- await asyncio.sleep(2**attempt)
+ delay = 2**attempt
+ if rate_limited:
+ # This runs to minutes, so re-read the run while it
+ # waits; the backoff below never outlasts one poll.
+ await self._wait_out_rate_limit(
+ run,
+ _retry_after_seconds(exc.response) or delay,
+ retry_deadline,
+ first_output_budget,
+ )
+ else:
+ await asyncio.sleep(delay)
attempt += 1
+ # re-check the lease and cancellation before re-sending.
await self._check_active(run["id"])
- async for line in self._iter_stream_lines(
- run["id"], response, semantic_deadline
- ):
+ continue
+ # A proxied provider 429 arrives as a 200 whose first line is the
+ # refusal, so the status cannot see it. No body byte is used yet, so a
+ # re-send cannot duplicate report text.
+ stream = self._iter_stream_lines(run["id"], response, semantic_deadline)
+ head = await _peek_stream_head(stream)
+ throttled = _stream_rate_limit_delay(head)
+ if throttled is None or attempt == 2:
+ # Out of attempts: let the stream raise the provider's own error.
+ break
+ await stream.aclose()
+ await response.aclose()
+ response = None
+ await self._wait_out_rate_limit(
+ run, throttled or 2**attempt, retry_deadline, first_output_budget
+ )
+ attempt += 1
+ await self._check_active(run["id"])
+ async for line in _with_head(head, stream):
if self._cancel_event(run["id"]).is_set():
await self._check_active(run["id"])
if not line.startswith("data:"):
diff --git a/studio/backend/tests/test_openai_codex_subscription.py b/studio/backend/tests/test_openai_codex_subscription.py
index 14740cdad4e..fdba51e6996 100644
--- a/studio/backend/tests/test_openai_codex_subscription.py
+++ b/studio/backend/tests/test_openai_codex_subscription.py
@@ -18,6 +18,7 @@ import hashlib
import json
import time
+import httpx
import pytest
from core.inference import openai_codex_auth as codex_auth
@@ -2848,3 +2849,141 @@ def test_a_read_started_after_a_release_cannot_be_matched_by_the_older_one(monke
assert offered_subscription_model_ids("provider-release-race") == {"new-slug"}
finally:
forget_subscription_models("provider-release-race")
+
+
+def test_quota_metadata_marks_a_terminal_refusal():
+ """A 429 is both "wait a moment" and "your plan is spent"; only the flag tells them apart."""
+ from core.inference import openai_codex_client as codex_client
+
+ response = httpx.Response(
+ 429,
+ headers = {"retry-after": "30"},
+ request = httpx.Request("POST", "https://chatgpt.com/backend-api/codex/responses"),
+ )
+ throttled = codex_client._quota_metadata(response)
+ assert throttled == {"retry_after": "30"}
+ assert codex_client._quota_metadata(response, terminal = True) == {
+ "retry_after": "30",
+ "terminal": True,
+ }
+
+
+def test_quota_metadata_falls_back_to_retry_after_ms():
+ """The client's own backoff already reads retry-after-ms; dropping it here left the delay
+ honoured on this side of the proxy and guessed at on the other."""
+ from core.inference import openai_codex_client as codex_client
+
+ request = httpx.Request("POST", "https://chatgpt.com/backend-api/codex/responses")
+ ms_only = httpx.Response(429, headers = {"retry-after-ms": "30000"}, request = request)
+ assert codex_client._quota_metadata(ms_only) == {"retry_after": "30.0"}
+ # Seconds win when both are present, and neither means no invented delay.
+ both = httpx.Response(
+ 429,
+ headers = {"retry-after": "45", "retry-after-ms": "30000"},
+ request = request,
+ )
+ assert codex_client._quota_metadata(both) == {"retry_after": "45"}
+ assert codex_client._quota_metadata(httpx.Response(429, request = request)) == {}
+
+
+def _quota_error_for(monkeypatch, body):
+ """Drive the real send/classify loop against one 429 and return the CodexQuotaError."""
+ from core.inference import openai_codex_client as codex_client
+
+ request = httpx.Request("POST", "https://chatgpt.com/backend-api/codex/responses")
+
+ async def _no_pause(delay, cancel_event):
+ return None
+
+ monkeypatch.setattr(codex_client, "_retry_pause", _no_pause)
+
+ class _Ctx:
+ async def __aenter__(self):
+ return httpx.Response(429, json = body, request = request)
+
+ async def __aexit__(self, *exc):
+ return False
+
+ monkeypatch.setattr(codex_client, "_stream_response", lambda *a, **k: _Ctx())
+
+ async def _run():
+ async with codex_client._validated_stream_response(
+ None,
+ url = "https://chatgpt.com/backend-api/codex/responses",
+ headers = {"Authorization": "Bearer t"},
+ body = {},
+ cancel_event = None,
+ refresh_access = None,
+ ):
+ pass
+
+ with pytest.raises(codex_client.CodexQuotaError) as raised:
+ asyncio.run(_run())
+ return raised.value
+
+
+def test_a_terminal_code_is_recognised_behind_a_generic_message(monkeypatch):
+ """_upstream_error_detail prefers the display message, so a terminal code arrived hidden
+ behind a "slow down" sentence and the refusal was retried as if waiting could clear it."""
+ hidden = _quota_error_for(
+ monkeypatch,
+ {"error": {"message": "Too many requests.", "code": "insufficient_quota"}},
+ )
+ assert hidden.metadata.get("terminal") is True
+
+
+def test_a_transient_code_behind_a_generic_message_stays_retryable(monkeypatch):
+ """The tightened classification must not start refusing throttles that a wait does clear."""
+ throttled = _quota_error_for(
+ monkeypatch,
+ {"error": {"message": "Too many requests.", "code": "rate_limit_exceeded"}},
+ )
+ assert "terminal" not in throttled.metadata
+
+
+def test_upstream_error_code_survives_a_body_that_cannot_be_read():
+ """Parsing a body whose read failed raises StreamError, which is not an HTTPError. The
+ classification runs after a failed read, so an uncaught one would replace the quota error
+ the caller is supposed to see."""
+ from core.inference import openai_codex_client as codex_client
+
+ class _FailingStream(httpx.AsyncByteStream):
+ async def __aiter__(self):
+ raise httpx.ReadTimeout("body read died mid-flight")
+ yield b""
+
+ request = httpx.Request("POST", "https://chatgpt.com/backend-api/codex/responses")
+
+ async def _both():
+ response = httpx.Response(429, stream = _FailingStream(), request = request)
+ # The order the send loop uses: the message first, then the code off the same response.
+ return (
+ await codex_client._upstream_error_detail(response),
+ await codex_client._upstream_error_code(response),
+ )
+
+ assert asyncio.run(_both()) == (None, None)
+
+
+def test_upstream_error_code_reads_code_then_type():
+ from core.inference import openai_codex_client as codex_client
+
+ request = httpx.Request("POST", "https://chatgpt.com/backend-api/codex/responses")
+
+ def _code_of(body):
+ return asyncio.run(
+ codex_client._upstream_error_code(httpx.Response(429, json = body, request = request))
+ )
+
+ assert _code_of({"error": {"message": "m", "code": "insufficient_quota"}}) == (
+ "insufficient_quota"
+ )
+ assert _code_of({"error": {"message": "m", "type": "rate_limit_error"}}) == "rate_limit_error"
+ assert _code_of({"detail": "nope"}) is None
+ assert _code_of({"error": "flat string"}) is None
+
+
+def test_terminal_quota_detail_is_recognised():
+ from core.inference import openai_codex_client as codex_client
+ assert codex_client._is_terminal_quota("You exceeded your current quota (insufficient_quota)")
+ assert not codex_client._is_terminal_quota("Rate limit reached, try again in 30s")
diff --git a/studio/backend/tests/test_openai_responses_translation.py b/studio/backend/tests/test_openai_responses_translation.py
index 59ae4ec9ed8..dc45e0c0deb 100644
--- a/studio/backend/tests/test_openai_responses_translation.py
+++ b/studio/backend/tests/test_openai_responses_translation.py
@@ -840,3 +840,13 @@ def test_error_sse_line_carries_no_json_blob(monkeypatch):
assert error["message"] == "Rate limit reached. (rate_limit_exceeded)"
assert "{" not in error["message"]
assert error["code"] == "429"
+
+
+def test_error_sse_line_forwards_retry_after():
+ """The 200 this rides on has no status line left, so the delay has to travel in the body."""
+ body = '{"error": {"message": "Rate limit reached."}}'
+ error = json.loads(ep_mod._error_sse_line(429, body, "openai", "30")[len("data:") :])["error"]
+ assert error["retry_after"] == "30"
+ # Absent upstream, absent here: never invent a delay the provider did not ask for.
+ plain = json.loads(ep_mod._error_sse_line(429, body, "openai")[len("data:") :])["error"]
+ assert "retry_after" not in plain
diff --git a/studio/backend/tests/test_research_runs_hardening.py b/studio/backend/tests/test_research_runs_hardening.py
index 3b65893f3ad..aad7d1e170b 100644
--- a/studio/backend/tests/test_research_runs_hardening.py
+++ b/studio/backend/tests/test_research_runs_hardening.py
@@ -6,6 +6,7 @@
from __future__ import annotations
import asyncio
+import datetime
import json
import sys
import time
@@ -2204,14 +2205,21 @@ def test_model_unloaded_matches_the_model_switch_refusal():
assert asyncio.run(research_runs._model_unloaded(_response(503, body = "overloaded"))) is None
-def test_retry_after_seconds_reads_only_a_delay():
+def _http_date_in(seconds):
+ at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds = seconds)
+ return at.strftime("%a, %d %b %Y %H:%M:%S GMT")
+
+
+def test_retry_after_seconds_reads_both_rfc_9110_forms():
assert research_runs._retry_after_seconds(_switch_failed()) == 5.0
assert research_runs._retry_after_seconds(_switch_failed(None)) is None
- # HTTP-date form and non-positive delays carry no usable delay, so the default applies.
- assert (
- research_runs._retry_after_seconds(_switch_failed("Wed, 21 Oct 2026 07:28:00 GMT")) is None
- )
+ # RFC 9110 allows "Retry-After: <HTTP-date>", which is the delay from now until then.
+ soon = research_runs._retry_after_seconds(_switch_failed(_http_date_in(30)))
+ assert soon is not None and 27.0 < soon <= 30.0
+ # A date already past, a non-positive delay, and an unparsable one all carry none.
+ assert research_runs._retry_after_seconds(_switch_failed(_http_date_in(-60))) is None
assert research_runs._retry_after_seconds(_switch_failed("0")) is None
+ assert research_runs._retry_after_seconds(_switch_failed("shortly")) is None
def test_stream_completion_waits_out_an_in_flight_model_switch(monkeypatch):
@@ -2286,3 +2294,272 @@ def test_an_unlimited_run_survives_a_gap_past_the_default_queue_bound(monkeypatc
supervisor = _make_supervisor(_noop_check_active)
assert _run_stream(supervisor, timeout_seconds = 0) == ("report", "", "stop", None)
+
+
+def _send_attempts(
+ monkeypatch,
+ status,
+ headers = None,
+ model_timeout = 900.0,
+ first_output = 5.0,
+ on_wait = None,
+ on_check = None,
+ body = b"{}",
+ errors = None,
+):
+ """Drive the real send/retry loop against a canned response; return (attempts, waits).
+
+ ``waits`` totals the wait before each re-send, so it does not depend on how many slices
+ the wait is split into. The hooks see the virtual clock at each slice."""
+ run = {
+ "id": "run-1",
+ "ownerSubject": "owner",
+ "threadId": "thread-1",
+ "config": {
+ "model": "m",
+ "inferenceRequest": {"model": "m"},
+ "budgets": {
+ "modelTimeoutSeconds": model_timeout,
+ "firstOutputTimeoutSeconds": first_output,
+ },
+ },
+ }
+ supervisor = research_runs.ResearchSupervisor.__new__(research_runs.ResearchSupervisor)
+ attempts, waits = [], []
+ clock, waited = {"t": 0.0}, {"t": 0.0}
+ real_sleep = asyncio.sleep
+
+ async def _sleep(delay, *args, **kwargs):
+ if delay and delay > 0.25:
+ if on_wait is not None:
+ on_wait(clock["t"])
+ clock["t"] += delay
+ waited["t"] += delay
+ return await real_sleep(0)
+
+ async def _send(
+ self,
+ request,
+ stream = False,
+ ):
+ if waited["t"]:
+ waits.append(round(waited["t"], 2))
+ waited["t"] = 0.0
+ attempts.append(request.url)
+ return httpx.Response(status, headers = headers or {}, content = body, request = request)
+
+ async def _check_active(run_id):
+ if on_check is not None:
+ on_check(clock["t"])
+ return await real_sleep(0)
+
+ monkeypatch.setattr(asyncio, "sleep", _sleep)
+ monkeypatch.setattr(httpx.AsyncClient, "send", _send)
+ monkeypatch.setattr(
+ research_runs.auth_storage, "create_api_key", lambda **k: ("token", {"id": 1})
+ )
+ monkeypatch.setattr(research_runs.auth_storage, "revoke_internal_api_key", lambda key_id: None)
+ supervisor._note_phase = lambda *a, **k: real_sleep(0)
+ supervisor._check_active = _check_active
+ supervisor._cancel_event = lambda run_id: SimpleNamespace(is_set = lambda: False)
+ supervisor._endpoint = lambda: "http://127.0.0.1:9/v1/chat/completions"
+ supervisor._discard_task = lambda *a, **k: real_sleep(0)
+
+ with pytest.raises(Exception) as raised:
+ asyncio.run(supervisor._stream_completion(run, [{"role": "user", "content": "x"}]))
+ if errors is not None:
+ errors.append(raised.value)
+ return len(attempts), waits
+
+
+def test_provider_rate_limit_is_retried_not_fatal(monkeypatch):
+ # A 429 used to end the run on the first send, discarding every gathered source.
+ assert _send_attempts(monkeypatch, 429)[0] == 3
+
+
+def test_rate_limit_honours_retry_after(monkeypatch):
+ assert _send_attempts(monkeypatch, 429, {"Retry-After": "30"})[1] == [30.0, 30.0]
+
+
+def test_rate_limit_wait_is_capped_by_what_is_left_of_the_call(monkeypatch):
+ # The cap is the call's own wall clock less the room the re-send needs (20 - 5, shrinking
+ # as the call runs), not the model-load share a 20s budget would allow (5).
+ _, waits = _send_attempts(monkeypatch, 429, {"Retry-After": "300"}, model_timeout = 20.0)
+ assert len(waits) == 2
+ assert all(13.0 < wait <= 15.0 for wait in waits), waits
+
+
+def test_a_wall_clock_no_larger_than_the_first_output_budget_still_waits(monkeypatch):
+ # firstOutputTimeoutSeconds defaults to 120 and modelTimeoutSeconds may be set as low as
+ # 10, so any run configured at or under its own first-output budget reserved the whole
+ # of it as headroom. Every wait collapsed to zero and the three sends went out
+ # back-to-back, which is the failure this retry path exists to prevent.
+ _, waits = _send_attempts(
+ monkeypatch,
+ 429,
+ {"Retry-After": "30"},
+ model_timeout = 120.0,
+ first_output = 120.0,
+ )
+ assert waits == [30.0, 30.0]
+
+
+def test_reserving_headroom_never_consumes_the_whole_remaining_budget():
+ # Half of what is left, at most: the reserve scales with the budget instead of being an
+ # absolute that can equal it. A budget with room to spare is unaffected.
+ assert research_runs._rate_limit_wait(30.0, 120.0, 120.0) == 30.0
+ assert research_runs._rate_limit_wait(30.0, 900.0, 120.0) == 30.0
+ # Still bounded by what is left: half of a 40s remainder cannot fund a 300s delay.
+ assert research_runs._rate_limit_wait(300.0, 40.0, 120.0) == 20.0
+
+
+def test_server_error_backoff_is_unchanged(monkeypatch):
+ assert _send_attempts(monkeypatch, 500) == (3, [1, 2])
+
+
+def _provider_error_sse(error):
+ return f"data: {json.dumps({'error': error})}\n\n".encode()
+
+
+_PROVIDER_429 = {
+ "message": "Rate limit reached for gpt-4o",
+ "type": "provider_error",
+ "code": "429",
+ "provider": "openai",
+}
+
+
+def test_a_retry_after_http_date_is_read_as_a_delay(monkeypatch):
+ # RFC 9110 allows "Retry-After: <HTTP-date>", and providers behind a CDN send it. Reading
+ # only the numeric form backed off for a second inside a 30s cooldown.
+ _, waits = _send_attempts(monkeypatch, 429, {"Retry-After": _http_date_in(30)})
+ assert len(waits) == 2
+ assert all(27.0 < wait <= 30.0 for wait in waits), waits
+
+
+def test_a_retry_after_date_already_past_falls_back_to_the_backoff(monkeypatch):
+ assert _send_attempts(monkeypatch, 429, {"Retry-After": _http_date_in(-60)}) == (3, [1, 2])
+
+
+def test_an_unlimited_run_honours_the_whole_retry_after(monkeypatch):
+ # No wall clock to divide, so nothing may trim the provider's delay to a model-load share.
+ unlimited = _send_attempts(monkeypatch, 429, {"Retry-After": "300"}, model_timeout = 0.0)
+ assert unlimited == (3, [300.0, 300.0])
+
+
+def test_an_unlimited_rate_limit_wait_still_has_a_ceiling(monkeypatch):
+ # Unlimited is not "park this run for a day on one header".
+ _, waits = _send_attempts(monkeypatch, 429, {"Retry-After": "86400"}, model_timeout = 0.0)
+ assert waits == [research_runs._MAX_RATE_LIMIT_WAIT_SECONDS] * 2
+
+
+def test_a_rate_limit_delivered_inside_the_stream_is_retried(monkeypatch):
+ # An external provider's 429 is proxied as a 200 whose first line carries the refusal, so
+ # the status line never shows it and the run used to end on the first send.
+ errors = []
+ body = _provider_error_sse(_PROVIDER_429)
+ assert _send_attempts(monkeypatch, 200, body = body, errors = errors) == (3, [1, 2])
+ assert "Rate limit reached for gpt-4o" in str(errors[0])
+
+
+def test_an_in_band_rate_limit_honours_the_forwarded_retry_after(monkeypatch):
+ # The proxy carries the provider's Retry-After in the error line, since the 200 the stream
+ # rides on has no status line left to put it on.
+ body = _provider_error_sse(dict(_PROVIDER_429, retry_after = "30"))
+ assert _send_attempts(monkeypatch, 200, body = body) == (3, [30.0, 30.0])
+
+
+def test_a_chatgpt_quota_refusal_in_the_stream_is_retried(monkeypatch):
+ # The ChatGPT connection reports its 429 by type with the delay in metadata, not by code.
+ body = _provider_error_sse(
+ {
+ "message": "ChatGPT subscription quota is temporarily unavailable.",
+ "type": "rate_limit_error",
+ "metadata": {"retry_after": "30"},
+ }
+ )
+ assert _send_attempts(monkeypatch, 200, body = body) == (3, [30.0, 30.0])
+
+
+def test_an_in_band_retry_after_http_date_is_read_as_a_delay(monkeypatch):
+ body = _provider_error_sse(dict(_PROVIDER_429, retry_after = _http_date_in(30)))
+ _, waits = _send_attempts(monkeypatch, 200, body = body)
+ assert len(waits) == 2
+ assert all(27.0 < wait <= 30.0 for wait in waits), waits
+
+
+def test_a_terminal_quota_refusal_is_not_retried(monkeypatch):
+ # ChatGPT reports an exhausted subscription with the same 429 shape as a throttle. Waiting
+ # out its Retry-After cannot clear it, so it must surface on the first send.
+ body = _provider_error_sse(
+ {
+ "message": "ChatGPT subscription quota is temporarily unavailable.",
+ "type": "rate_limit_error",
+ "metadata": {"retry_after": "30", "terminal": True},
+ }
+ )
+ assert _send_attempts(monkeypatch, 200, body = body) == (1, [])
+
+
+def test_a_rate_limit_wait_cannot_outlive_the_internal_key(monkeypatch):
+ # A wait past the call key's expiry would fail auth without reaching the provider, and an
+ # unlimited run has no wall clock, which leaves the key as the only thing bounding it.
+ monkeypatch.setattr(research_runs, "_MODEL_CALL_KEY_LIFETIME_SECONDS", 100)
+ _, waits = _send_attempts(monkeypatch, 429, {"Retry-After": "3000"}, model_timeout = 0.0)
+ # 100 less the 5s reserve: not the 3000s asked for, and not the standing ceiling.
+ assert len(waits) == 2
+ assert all(93.0 < wait <= 95.0 for wait in waits), waits
+
+
+def test_a_blank_first_line_survives_the_peek_and_replay():
+ """A blank SSE separator is a line. Peeled off to be inspected and put back, it has to
+ round-trip verbatim through the whole path, or every line after it shifts up one."""
+
+ async def _stream():
+ for line in ("", "data: one", "data: [DONE]"):
+ yield line
+
+ async def _peek_then_replay():
+ lines = _stream()
+ head = await research_runs._peek_stream_head(lines)
+ assert research_runs._stream_rate_limit_delay(head) is None
+ return head, [line async for line in research_runs._with_head(head, lines)]
+
+ head, replayed = asyncio.run(_peek_then_replay())
+ assert head == ""
+ assert replayed == ["", "data: one", "data: [DONE]"]
+
+
+def test_another_in_band_provider_error_is_not_retried(monkeypatch):
+ # Only a rate limit is transient; anything else must surface on the first send.
+ errors = []
+ other = dict(_PROVIDER_429, code = "400", message = "Unsupported parameter")
+ body = _provider_error_sse(other)
+ assert _send_attempts(monkeypatch, 200, body = body, errors = errors) == (1, [])
+ assert "Unsupported parameter" in str(errors[0])
+
+
+def test_a_cancel_during_the_rate_limit_wait_is_not_held_for_the_retry_after(monkeypatch):
+ # One uninterrupted sleep held a cancelled run open for the whole Retry-After, then
+ # re-sent without re-reading the lease.
+ started, ended = [], []
+
+ def _cancel_once_the_wait_starts(now):
+ if not started:
+ started.append(now)
+
+ def _end_when_cancelled(now):
+ if started and not ended:
+ ended.append(now)
+ raise RunCancelled()
+
+ _send_attempts(
+ monkeypatch,
+ 429,
+ {"Retry-After": "30"},
+ on_wait = _cancel_once_the_wait_starts,
+ on_check = _end_when_cancelled,
+ )
+
+ assert ended, "the wait never re-checked the run"
+ assert ended[0] - started[0] <= research_runs._MODEL_WAIT_POLL_SECONDS