Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(sdk): retry 503 KEY_STATE_UNAVAILABLE that carries Retry-After (#965)
Krisztian Gajdar3f84db7cfd15
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.mdindex 9294d9320..636460085 100644--- a/packages/sie_sdk/README.md+++ b/packages/sie_sdk/README.md@@ -429,13 +429,16 @@ Admission rejections happen before any work is dispatched, so everyinference call retries them within `provision_timeout_s`, honouring`Retry-After` (`estimate()` raises them without retrying):`429 RATE_LIMIT`, `503 QUEUE_FULL`, `503 BILLING_CAPACITY_UNAVAILABLE`,-and the gateway's queue backpressure, a `503 QUEUE_UNAVAILABLE` that-carries `Retry-After`. A `QUEUE_UNAVAILABLE` without `Retry-After` is-terminal. On SIE Cloud, `429 RATE_LIMIT` means the API key or its account-has reached its limit on requests in flight or per second, and+the gateway's queue backpressure, a `503 QUEUE_UNAVAILABLE` that+carries `Retry-After`, and a `503 KEY_STATE_UNAVAILABLE` that carries+`Retry-After`. Either code without `Retry-After` is terminal. On SIE+Cloud, `429 RATE_LIMIT` means the API key or its account has reached its+limit on requests in flight or per second,`503 BILLING_CAPACITY_UNAVAILABLE` means the gateway could not reserve-billing capacity for the request in time. Neither means the credit-balance ran out, and neither is billed.+billing capacity for the request in time, and+`503 KEY_STATE_UNAVAILABLE` means the gateway has not yet decided whether+the API key is valid, as on the first request with a key created moments+ago. None of them means the credit balance ran out, and none is billed.[`packages/wire-fixtures/retry_classification.json`](../wire-fixtures/retry_classification.json)lists how each response is classified; the Python and TypeScript SDKsboth test against it.diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex b72908ec5..17409871b 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -613,7 +613,13 @@ BACKPRESSURE_503_DEFAULT_DELAY_S = 1.0 # Fallback when the server omits Retry-A# retryable.QUEUE_UNAVAILABLE_ERROR_CODE = "QUEUE_UNAVAILABLE"OPENAI_TRANSPORT_FAILURE_ERROR_CODE = "transport_failure"-RETRY_AFTER_GATED_503_ERROR_CODES = frozenset({QUEUE_UNAVAILABLE_ERROR_CODE, OPENAI_TRANSPORT_FAILURE_ERROR_CODE})+# SIE Cloud answers 503 KEY_STATE_UNAVAILABLE plus Retry-After when it has not+# yet decided whether the API key is valid, for example on the first request+# with a key created moments ago. That decision precedes admission.+KEY_STATE_UNAVAILABLE_ERROR_CODE = "KEY_STATE_UNAVAILABLE"+RETRY_AFTER_GATED_503_ERROR_CODES = frozenset(+ {QUEUE_UNAVAILABLE_ERROR_CODE, OPENAI_TRANSPORT_FAILURE_ERROR_CODE, KEY_STATE_UNAVAILABLE_ERROR_CODE}+)# ── Terminal credit / account errors (pass-2 audit B3) — NEVER retried ──# 402/403 credit/account failures are mapped to typed exceptions in@@ -1643,6 +1649,10 @@ def admission_retry_delay(``Retry-After``: the gateway rejected the publish under queuebackpressure. Without the hint these codes stay terminal. The give-upmatches the previous arm.+ * ``503 KEY_STATE_UNAVAILABLE`` carrying a usable ``Retry-After``: SIE+ Cloud has not yet decided whether the API key is valid, for example on+ the first request with a key created moments ago. Without the hint it+ stays terminal. The give-up matches the previous arm.``packages/wire-fixtures/retry_classification.json`` pins thesedecisions for both SDKs.diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex d6f45606b..6f94197d4 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -1306,9 +1306,10 @@ class SIEClient:``ResourceExhaustedError`` below; the ``RESOURCE_EXHAUSTED``branch can be disabled by passing ``max_oom_retries=0``.The pre-dispatch admission signals ``429 RATE_LIMIT``,- ``503 BILLING_CAPACITY_UNAVAILABLE``, ``503 QUEUE_FULL`` and- ``503 QUEUE_UNAVAILABLE`` with ``Retry-After`` (queue- backpressure) are likewise retried regardless of this flag —+ ``503 BILLING_CAPACITY_UNAVAILABLE``, ``503 QUEUE_FULL``, and+ ``503 QUEUE_UNAVAILABLE`` (queue backpressure) or+ ``503 KEY_STATE_UNAVAILABLE`` (API key not yet decided) with+ ``Retry-After`` are likewise retried regardless of this flag —no work has been published yet — honouring ``Retry-After`` andcapped by ``provision_timeout_s``. On give-up they raise``RateLimitError`` (429) or the server's terminal 503.@@ -2305,8 +2306,9 @@ class SIEClient:``RESOURCE_EXHAUSTED`` branch can be disabled by passing``max_oom_retries=0``. The pre-dispatch admission signals``429 RATE_LIMIT``, ``503 BILLING_CAPACITY_UNAVAILABLE``,- ``503 QUEUE_FULL`` and ``503 QUEUE_UNAVAILABLE`` with- ``Retry-After`` (queue backpressure) are likewise retried+ ``503 QUEUE_FULL``, and ``503 QUEUE_UNAVAILABLE`` (queue+ backpressure) or ``503 KEY_STATE_UNAVAILABLE`` (API key not+ yet decided) with ``Retry-After`` are likewise retriedregardless of this flag — no work has been published yet — honouring``Retry-After`` and capped by ``provision_timeout_s``. Ongive-up they raise ``RateLimitError`` (429) or the server's@@ -2648,13 +2650,14 @@ class SIEClient:(matching encode/score/extract): the worker has alreadyaccepted the request and is loading the target model. Thepre-dispatch admission signals ``429 RATE_LIMIT``,- ``503 BILLING_CAPACITY_UNAVAILABLE``, ``503 QUEUE_FULL`` and- ``503 QUEUE_UNAVAILABLE`` with ``Retry-After`` are also- retried regardless of this flag — they reject the request- before any generation is published, so retrying cannot- double-bill — honouring ``Retry-After`` and capped by- ``provision_timeout_s``; on give-up they raise- ``RateLimitError`` (429) or the server's terminal 503.+ ``503 BILLING_CAPACITY_UNAVAILABLE``, ``503 QUEUE_FULL``, and+ ``503 QUEUE_UNAVAILABLE`` or ``503 KEY_STATE_UNAVAILABLE``+ with ``Retry-After`` are also retried regardless of this+ flag — they reject the request before any generation is+ published, so retrying cannot double-bill — honouring+ ``Retry-After`` and capped by ``provision_timeout_s``; on+ give-up they raise ``RateLimitError`` (429) or the server's+ terminal 503.provision_timeout_s: Maximum time to wait for capacity.max_oom_retries: Maximum number of worker-side``503 RESOURCE_EXHAUSTED`` retries.@@ -3591,8 +3594,9 @@ class SIEClient:``RESOURCE_EXHAUSTED`` branch can be disabled by passing``max_oom_retries=0``. The pre-dispatch admission signals``429 RATE_LIMIT``, ``503 BILLING_CAPACITY_UNAVAILABLE``,- ``503 QUEUE_FULL`` and ``503 QUEUE_UNAVAILABLE`` with- ``Retry-After`` (queue backpressure) are likewise retried+ ``503 QUEUE_FULL``, and ``503 QUEUE_UNAVAILABLE`` (queue+ backpressure) or ``503 KEY_STATE_UNAVAILABLE`` (API key not+ yet decided) with ``Retry-After`` are likewise retriedregardless of this flag — no work has been published yet — honouring``Retry-After`` and capped by ``provision_timeout_s``. Ongive-up they raise ``RateLimitError`` (429) or the server'sdiff --git a/packages/sie_sdk/tests/client/test_retry_classification.py b/packages/sie_sdk/tests/client/test_retry_classification.pyindex f94ecce08..18a1a2f0b 100644--- a/packages/sie_sdk/tests/client/test_retry_classification.py+++ b/packages/sie_sdk/tests/client/test_retry_classification.py@@ -28,6 +28,7 @@ from sie_sdk import (IncompleteBatchError,ModelLoadingError,ProvisioningError,+ ServerError,SIEAsyncClient,SIEClient,SIEConnectionError,@@ -63,11 +64,12 @@ class _Reply:class _StubServer:- """Threaded HTTP server that replays scripted replies and records request paths."""+ """Threaded HTTP server that replays scripted replies and records request paths and credentials."""def __init__(self) -> None:self.replies: list[_Reply] = []self.paths: list[str] = []+ self.authorizations: list[str | None] = []self._lock = threading.Lock()self._release = threading.Event()stub = self@@ -77,7 +79,7 @@ class _StubServer:def do_POST(self) -> None:self.rfile.read(int(self.headers.get("Content-Length") or 0))- reply = stub._next(self.path)+ reply = stub._next(self.path, self.headers.get("Authorization"))if reply.delay_s:stub._release.wait(reply.delay_s)try:@@ -103,9 +105,10 @@ class _StubServer:host, port = self._server.server_address[:2]return f"http://{host!s}:{port}"- def _next(self, path: str) -> _Reply:+ def _next(self, path: str, authorization: str | None) -> _Reply:with self._lock:self.paths.append(path)+ self.authorizations.append(authorization)if len(self.replies) > 1:return self.replies.pop(0)return self.replies[0]@@ -590,3 +593,67 @@ async def test_async_refusal_of_the_final_attempt_is_raised_with_its_metadata(_assert_final_refusal(excinfo.value, code)assert len(stub.paths) == 2assert budget_clock.now == DEFAULT_PROVISION_TIMEOUT_S+++_FRESH_KEY = "sk-sie-just-created"+_KEY_STATE_UNAVAILABLE = next(case for case in _RESPONSE_CASES if case["name"] == "key_state_unavailable")+_KEY_STATE_RETRY_AFTER_S = float(_KEY_STATE_UNAVAILABLE["headers"]["Retry-After"])+_INFERENCE_OPERATIONS = ("encode", "score", "extract", "generate", "chat_completions", "responses", "stream_generate")++[email protected]("operation", _INFERENCE_OPERATIONS)+def test_sync_fresh_key_first_request_waits_out_key_state_unavailable(+ stub: _StubServer, budget_clock: _BudgetClock, operation: str+) -> None:+ stub.replies = [_fixture_reply(_KEY_STATE_UNAVAILABLE), _success(operation)]+ client = SIEClient(stub.url, api_key=_FRESH_KEY)+ try:+ _call_sync(client, operation, provision_timeout_s=30.0)+ assert client.last_retry_count == 1+ finally:+ client.close()+ assert stub.authorizations == [f"Bearer {_FRESH_KEY}"] * 2+ assert budget_clock.now == _KEY_STATE_RETRY_AFTER_S++[email protected]("operation", _INFERENCE_OPERATIONS)+async def test_async_fresh_key_first_request_waits_out_key_state_unavailable(+ stub: _StubServer, budget_clock: _BudgetClock, operation: str+) -> None:+ stub.replies = [_fixture_reply(_KEY_STATE_UNAVAILABLE), _success(operation)]+ async with SIEAsyncClient(stub.url, api_key=_FRESH_KEY) as client:+ await _call_async(client, operation, provision_timeout_s=30.0)+ assert client.last_retry_count == 1+ assert stub.authorizations == [f"Bearer {_FRESH_KEY}"] * 2+ assert budget_clock.now == _KEY_STATE_RETRY_AFTER_S++[email protected]("operation", _INFERENCE_OPERATIONS)+def test_sync_key_state_unavailable_is_raised_when_its_wait_would_end_the_budget(+ stub: _StubServer, budget_clock: _BudgetClock, operation: str+) -> None:+ stub.replies = [_fixture_reply(_KEY_STATE_UNAVAILABLE), _success(operation)]+ client = SIEClient(stub.url, api_key=_FRESH_KEY)+ try:+ with pytest.raises(ServerError) as excinfo:+ _call_sync(client, operation, provision_timeout_s=_KEY_STATE_RETRY_AFTER_S)+ finally:+ client.close()+ assert excinfo.value.status_code == 503+ assert excinfo.value.code == "KEY_STATE_UNAVAILABLE"+ assert len(stub.paths) == 1+ assert budget_clock.now == 0.0++[email protected]("operation", _INFERENCE_OPERATIONS)+async def test_async_key_state_unavailable_is_raised_when_its_wait_would_end_the_budget(+ stub: _StubServer, budget_clock: _BudgetClock, operation: str+) -> None:+ stub.replies = [_fixture_reply(_KEY_STATE_UNAVAILABLE), _success(operation)]+ async with SIEAsyncClient(stub.url, api_key=_FRESH_KEY) as client:+ with pytest.raises(ServerError) as excinfo:+ await _call_async(client, operation, provision_timeout_s=_KEY_STATE_RETRY_AFTER_S)+ assert excinfo.value.status_code == 503+ assert excinfo.value.code == "KEY_STATE_UNAVAILABLE"+ assert len(stub.paths) == 1+ assert budget_clock.now == 0.0diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.mdindex 0adc7d295..ceaf2928e 100644--- a/packages/sie_ts_sdk/README.md+++ b/packages/sie_ts_sdk/README.md@@ -239,13 +239,16 @@ Admission rejections happen before any work is dispatched, so everyinference call retries them within `provisionTimeout`, honouring`Retry-After` (delay seconds or an HTTP date; `estimate()` throws themwithout retrying): `429 RATE_LIMIT`, `503 QUEUE_FULL`,-`503 BILLING_CAPACITY_UNAVAILABLE`, and the gateway's queue backpressure, a-`503 QUEUE_UNAVAILABLE` that carries `Retry-After`. A `QUEUE_UNAVAILABLE`-without `Retry-After` is terminal. On SIE Cloud, `429 RATE_LIMIT` means the-API key or its account has reached its limit on requests in flight or per-second, and `503 BILLING_CAPACITY_UNAVAILABLE` means the gateway could not-reserve billing capacity for the request in time. Neither means the credit-balance ran out, and neither is billed.+`503 BILLING_CAPACITY_UNAVAILABLE`, the gateway's queue backpressure, a+`503 QUEUE_UNAVAILABLE` that carries `Retry-After`, and a+`503 KEY_STATE_UNAVAILABLE` that carries `Retry-After`. Either code without+`Retry-After` is terminal. On SIE Cloud, `429 RATE_LIMIT` means the API key+or its account has reached its limit on requests in flight or per second,+`503 BILLING_CAPACITY_UNAVAILABLE` means the gateway could not reserve+billing capacity for the request in time, and `503 KEY_STATE_UNAVAILABLE`+means the gateway has not yet decided whether the API key is valid, as on+the first request with a key created moments ago. None of them means the+credit balance ran out, and none is billed.[`packages/wire-fixtures/retry_classification.json`](../wire-fixtures/retry_classification.json)lists how each response is classified; the TypeScript and Python SDKsboth test against it.diff --git a/packages/sie_ts_sdk/src/internal/constants.ts b/packages/sie_ts_sdk/src/internal/constants.tsindex ed0e3ea39..d903a4ee8 100644--- a/packages/sie_ts_sdk/src/internal/constants.ts+++ b/packages/sie_ts_sdk/src/internal/constants.ts@@ -76,9 +76,14 @@ export const BACKPRESSURE_503_DEFAULT_DELAY = 1_000; // Fallback (ms) when the s// retryable.export const QUEUE_UNAVAILABLE_ERROR_CODE = "QUEUE_UNAVAILABLE";export const OPENAI_TRANSPORT_FAILURE_ERROR_CODE = "transport_failure";+// SIE Cloud answers 503 KEY_STATE_UNAVAILABLE plus Retry-After when it has not+// yet decided whether the API key is valid, for example on the first request+// with a key created moments ago. That decision precedes admission.+export const KEY_STATE_UNAVAILABLE_ERROR_CODE = "KEY_STATE_UNAVAILABLE";export const RETRY_AFTER_GATED_503_ERROR_CODES: ReadonlySet<string> = new Set([QUEUE_UNAVAILABLE_ERROR_CODE,OPENAI_TRANSPORT_FAILURE_ERROR_CODE,+ KEY_STATE_UNAVAILABLE_ERROR_CODE,]);// Terminal credit / account errors (pass-2 audit B3) — NEVER retried. 402/403diff --git a/packages/sie_ts_sdk/src/internal/provisioning.ts b/packages/sie_ts_sdk/src/internal/provisioning.tsindex cf459eb9a..de5459eb3 100644--- a/packages/sie_ts_sdk/src/internal/provisioning.ts+++ b/packages/sie_ts_sdk/src/internal/provisioning.ts@@ -165,6 +165,10 @@ export function nextOomRetryDelay(opts: {* `Retry-After`: the gateway rejected the publish under queue backpressure.* Without the hint these codes stay terminal. The give-up matches the* previous arm.+ * - `503 KEY_STATE_UNAVAILABLE` carrying a usable `Retry-After`: SIE Cloud has+ * not yet decided whether the API key is valid, for example on the first+ * request with a key created moments ago. Without the hint it stays+ * terminal. The give-up matches the previous arm.** `packages/wire-fixtures/retry_classification.json` pins these decisions for* both SDKs.diff --git a/packages/sie_ts_sdk/tests/retryClassification.test.ts b/packages/sie_ts_sdk/tests/retryClassification.test.tsindex a36093088..0acd85b70 100644--- a/packages/sie_ts_sdk/tests/retryClassification.test.ts+++ b/packages/sie_ts_sdk/tests/retryClassification.test.ts@@ -11,7 +11,7 @@ import { readFileSync } from "node:fs";import { fileURLToPath } from "node:url";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { SIEClient } from "../src/client.js";-import { IncompleteBatchError, SIEConnectionError, SIEError } from "../src/errors.js";+import { IncompleteBatchError, SIEConnectionError, SIEError, ServerError } from "../src/errors.js";import { getRetryAfter } from "../src/internal/retry.js";import { packMessage } from "../src/msgpack.js";@@ -174,6 +174,84 @@ describe("shared retry classification table", () => {});});+describe("a just-created API key", () => {+ const apiKey = "sk-sie-just-created";+ const keyState = fixture.responses.find((testCase) => testCase.name === "key_state_unavailable");+ if (!keyState) throw new Error("fixture case missing");+ const retryAfterMs = Number(keyState.headers["Retry-After"]) * 1000;+ const operations = [...OPERATIONS, "streamGenerate"] as const;++ function successOf(operation: (typeof operations)[number]): Response {+ if (operation !== "streamGenerate") return successFor(operation);+ return new Response('data: {"request_id":"r","seq":0,"text_delta":"ok","done":true}\n\n', {+ status: 200,+ headers: { "Content-Type": "text/event-stream" },+ });+ }++ async function run(client: SIEClient, operation: (typeof operations)[number]): Promise<unknown> {+ if (operation !== "streamGenerate") return call(client, operation);+ const chunks: unknown[] = [];+ for await (const chunk of client.streamGenerate("m", "hi", { maxNewTokens: 4 })) {+ chunks.push(chunk);+ }+ return chunks;+ }++ beforeEach(() => {+ mockFetch.mockReset();+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ for (const operation of operations) {+ it(`${operation}: the first request waits out KEY_STATE_UNAVAILABLE and is retried`, async () => {+ mockFetch+ .mockResolvedValueOnce(fixtureResponse(keyState))+ .mockResolvedValueOnce(successOf(operation));+ const client = new SIEClient("http://localhost:8080", { apiKey, provisionTimeout: 30_000 });++ const outcome = run(client, operation).then(+ () => ({ ok: true as const }),+ (error: unknown) => ({ ok: false as const, error }),+ );+ await vi.advanceTimersByTimeAsync(retryAfterMs - 1);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1);++ expect(await outcome).toEqual({ ok: true });+ expect(mockFetch).toHaveBeenCalledTimes(2);+ for (const [, init] of mockFetch.mock.calls) {+ expect(new Headers((init as RequestInit).headers).get("Authorization")).toBe(+ `Bearer ${apiKey}`,+ );+ }+ });++ it(`${operation}: KEY_STATE_UNAVAILABLE is thrown when its wait would end the budget`, async () => {+ mockFetch+ .mockResolvedValueOnce(fixtureResponse(keyState))+ .mockResolvedValueOnce(successOf(operation));+ const client = new SIEClient("http://localhost:8080", {+ apiKey,+ provisionTimeout: retryAfterMs,+ });++ const outcome = await settle(run(client, operation), 0);++ expect(outcome.ok).toBe(false);+ const error = outcome.ok ? undefined : outcome.error;+ expect(error).toBeInstanceOf(ServerError);+ expect((error as ServerError).code).toBe("KEY_STATE_UNAVAILABLE");+ expect((error as ServerError).statusCode).toBe(503);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });+ }+});+describe("fetch failure classification", () => {beforeEach(() => {mockFetch.mockReset();diff --git a/packages/wire-fixtures/retry_classification.json b/packages/wire-fixtures/retry_classification.jsonindex 80a3a48ff..794735990 100644--- a/packages/wire-fixtures/retry_classification.json+++ b/packages/wire-fixtures/retry_classification.json@@ -105,6 +105,22 @@"idempotent": "terminal","generation": "terminal"},+ {+ "name": "key_state_unavailable",+ "status": 503,+ "headers": {"Retry-After": "5"},+ "body": {"detail": {"code": "KEY_STATE_UNAVAILABLE", "message": "API key authorization state is temporarily unavailable"}},+ "idempotent": "retry",+ "generation": "retry"+ },+ {+ "name": "key_state_unavailable_without_retry_after",+ "status": 503,+ "headers": {},+ "body": {"detail": {"code": "KEY_STATE_UNAVAILABLE", "message": "API key authorization state is temporarily unavailable"}},+ "idempotent": "terminal",+ "generation": "terminal"+ },{"name": "account_state_unavailable","status": 503,