Wait out LLM outages with backoff (L5) #116
No files matched your search
@@ -39,6 +39,13 @@ class LLMError(RuntimeError):
|
|||||||
RATE_LIMIT_STATUS = 429
|
RATE_LIMIT_STATUS = 429
|
||||||
RATE_LIMIT_RETRY_S = 20.0
|
RATE_LIMIT_RETRY_S = 20.0
|
||||||
|
|
||||||
|
# The proxy, or what's behind it, briefly gone: a 502/503/504 or a dropped
|
||||||
|
# connection. Outages delay, never fail (L5): waited out with backoff before
|
||||||
|
# the work is stopped. Not a 500 (it may be the request) and not a timeout
|
||||||
|
# (a hung model has had its request_timeout_s already).
|
||||||
|
OUTAGE_STATUSES = frozenset({502, 503, 504})
|
||||||
|
OUTAGE_BACKOFF_S = (5.0, 15.0, 45.0)
|
||||||
|
|
||||||
# Generous by default. Output is billed by what is produced, not by the
|
# Generous by default. Output is billed by what is produced, not by the
|
||||||
# ceiling, and a ceiling too low does not fail loudly — it truncates a tool
|
# ceiling, and a ceiling too low does not fail loudly — it truncates a tool
|
||||||
# call mid-argument and hands back something that parses. Measured: Opus
|
# call mid-argument and hands back something that parses. Measured: Opus
|
||||||
@@ -381,20 +388,39 @@ class AnthropicPassthroughClient:
|
|||||||
def _post_with_rate_limit_retry(
|
def _post_with_rate_limit_retry(
|
||||||
http: httpx.Client, path: str, body: dict[str, Any], sleep: Any
|
http: httpx.Client, path: str, body: dict[str, Any], sleep: Any
|
||||||
) -> tuple[httpx.Response, float]:
|
) -> tuple[httpx.Response, float]:
|
||||||
"""The response, and how long was spent waiting out a rate limit."""
|
"""The response, and how long was spent waiting: out a rate limit (once)
|
||||||
|
or an outage (with backoff), not on the model."""
|
||||||
waited = 0.0
|
waited = 0.0
|
||||||
for attempt in (1, 2):
|
rate_limited = False
|
||||||
|
outages = iter(OUTAGE_BACKOFF_S)
|
||||||
|
while True:
|
||||||
try:
|
try:
|
||||||
response = http.post(path, json=body)
|
response = http.post(path, json=body)
|
||||||
|
except httpx.TimeoutException as exc:
|
||||||
|
raise UpstreamUnavailable(f"LLM request failed: {exc}") from exc
|
||||||
except httpx.HTTPError as exc:
|
except httpx.HTTPError as exc:
|
||||||
# Could not reach the proxy at all: nothing about the request was
|
# Could not reach the proxy at all: nothing about the request was
|
||||||
# wrong, so callers holding work in progress should keep it.
|
# wrong, so callers holding work in progress should keep it.
|
||||||
raise UpstreamUnavailable(f"LLM request failed: {exc}") from exc
|
pause = next(outages, None)
|
||||||
if response.status_code != RATE_LIMIT_STATUS or attempt == 2:
|
if pause is None:
|
||||||
return response, waited
|
raise UpstreamUnavailable(f"LLM request failed: {exc}") from exc
|
||||||
sleep(RATE_LIMIT_RETRY_S)
|
sleep(pause)
|
||||||
waited += RATE_LIMIT_RETRY_S
|
waited += pause
|
||||||
raise AssertionError("unreachable")
|
continue
|
||||||
|
if response.status_code == RATE_LIMIT_STATUS and not rate_limited:
|
||||||
|
rate_limited = True
|
||||||
|
sleep(RATE_LIMIT_RETRY_S)
|
||||||
|
waited += RATE_LIMIT_RETRY_S
|
||||||
|
continue
|
||||||
|
if response.status_code in OUTAGE_STATUSES and not _looks_like_budget_refusal(
|
||||||
|
response.text
|
||||||
|
):
|
||||||
|
pause = next(outages, None)
|
||||||
|
if pause is not None:
|
||||||
|
sleep(pause)
|
||||||
|
waited += pause
|
||||||
|
continue
|
||||||
|
return response, waited
|
||||||
|
|
||||||
|
|
||||||
# Model families we have a native renderer adapter for. L9: delegations take
|
# Model families we have a native renderer adapter for. L9: delegations take
|
||||||
|
|||||||
@@ -143,6 +143,9 @@ class FakeTransport:
|
|||||||
def build_offline(tmp_path: Path, origin: Path, monkeypatch: Any) -> Any:
|
def build_offline(tmp_path: Path, origin: Path, monkeypatch: Any) -> Any:
|
||||||
"""Assemble the real graph with only the network boundaries faked."""
|
"""Assemble the real graph with only the network boundaries faked."""
|
||||||
config = config_for(tmp_path)
|
config = config_for(tmp_path)
|
||||||
|
# The proxy here doesn't exist: a call to it fails at once rather than
|
||||||
|
# waiting out an outage's backoff (L5).
|
||||||
|
monkeypatch.setattr("nisse_dev.llm.OUTAGE_BACKOFF_S", ())
|
||||||
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"nisse_dev.agent.GiteaClient.whoami", lambda self: "nisse-dev-testing"
|
"nisse_dev.agent.GiteaClient.whoami", lambda self: "nisse-dev-testing"
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from nisse_dev.canonical import (
|
|||||||
from nisse_dev.envfile import load_env_file
|
from nisse_dev.envfile import load_env_file
|
||||||
from nisse_dev.llm import (
|
from nisse_dev.llm import (
|
||||||
DEFAULT_MAX_OUTPUT_TOKENS,
|
DEFAULT_MAX_OUTPUT_TOKENS,
|
||||||
|
OUTAGE_BACKOFF_S,
|
||||||
RATE_LIMIT_RETRY_S,
|
RATE_LIMIT_RETRY_S,
|
||||||
AnthropicPassthroughClient,
|
AnthropicPassthroughClient,
|
||||||
BudgetExhausted,
|
BudgetExhausted,
|
||||||
@@ -432,3 +433,81 @@ def test_the_answering_model_is_recorded() -> None:
|
|||||||
)
|
)
|
||||||
client.complete(EVENTS, tools=None, model="local-fast")
|
client.complete(EVENTS, tools=None, model="local-fast")
|
||||||
assert client.last_model == "gpt-test-1"
|
assert client.last_model == "gpt-test-1"
|
||||||
|
|
||||||
|
|
||||||
|
# --- outages delay, never fail (L5) --------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_gateway_error_is_waited_out_with_backoff() -> None:
|
||||||
|
responses = [
|
||||||
|
httpx.Response(502, text="bad gateway"),
|
||||||
|
httpx.Response(503, text="unavailable"),
|
||||||
|
completion({"content": "back"}),
|
||||||
|
]
|
||||||
|
waited: list[float] = []
|
||||||
|
client = make_client(lambda request: responses.pop(0), sleep=waited.append)
|
||||||
|
[event] = client.complete(EVENTS, tools=None, model="local/qwen")
|
||||||
|
assert isinstance(event, AssistantText) and event.text == "back"
|
||||||
|
assert waited == list(OUTAGE_BACKOFF_S[:2])
|
||||||
|
# Waiting isn't the model's time.
|
||||||
|
assert client.last_rate_limit_wait_s == sum(OUTAGE_BACKOFF_S[:2])
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_outage_that_outlasts_the_backoff_is_surfaced() -> None:
|
||||||
|
attempts: list[int] = []
|
||||||
|
waited: list[float] = []
|
||||||
|
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
attempts.append(1)
|
||||||
|
return httpx.Response(502, text="bad gateway")
|
||||||
|
|
||||||
|
client = make_client(handler, sleep=waited.append)
|
||||||
|
with pytest.raises(UpstreamUnavailable, match="502"):
|
||||||
|
client.complete(EVENTS, tools=None, model="local/qwen")
|
||||||
|
assert len(attempts) == len(OUTAGE_BACKOFF_S) + 1
|
||||||
|
assert waited == list(OUTAGE_BACKOFF_S)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_dropped_connection_is_retried() -> None:
|
||||||
|
calls: list[int] = []
|
||||||
|
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
calls.append(1)
|
||||||
|
if len(calls) == 1:
|
||||||
|
raise httpx.ConnectError("refused")
|
||||||
|
return completion({"content": "ok"})
|
||||||
|
|
||||||
|
[event] = make_client(handler).complete(EVENTS, tools=None, model="local/qwen")
|
||||||
|
assert isinstance(event, AssistantText) and len(calls) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_500_or_a_timeout_is_not_retried() -> None:
|
||||||
|
# A 500 may be the request's fault; a timeout already had its full
|
||||||
|
# request_timeout_s.
|
||||||
|
for failure in (
|
||||||
|
lambda request: httpx.Response(500, text="boom"),
|
||||||
|
lambda request: (_ for _ in ()).throw(httpx.ReadTimeout("slow")),
|
||||||
|
):
|
||||||
|
calls: list[int] = []
|
||||||
|
|
||||||
|
def handler(
|
||||||
|
request: httpx.Request, failure=failure, calls=calls
|
||||||
|
) -> httpx.Response:
|
||||||
|
calls.append(1)
|
||||||
|
return failure(request)
|
||||||
|
|
||||||
|
with pytest.raises(LLMError):
|
||||||
|
make_client(handler).complete(EVENTS, tools=None, model="local/qwen")
|
||||||
|
assert len(calls) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_budget_refusal_is_not_waited_on() -> None:
|
||||||
|
calls: list[int] = []
|
||||||
|
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
calls.append(1)
|
||||||
|
return httpx.Response(503, text="Budget has been exceeded! Current cost: 5.1")
|
||||||
|
|
||||||
|
with pytest.raises(BudgetExhausted):
|
||||||
|
make_client(handler).complete(EVENTS, tools=None, model="local/qwen")
|
||||||
|
assert len(calls) == 1
|
||||||
Reference in new issue
Block a user