Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(sdk): type SIE Relay refusals and attach request metadata to TypeScript errors (#689)

Krisztian Gajdarc571e0a75d80
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index 17f2a124d..aacbf2f1a 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -323,9 +323,13 @@ use local/PVC, S3, GCS, or Azure storage for that store.
Server-reported errors are raised as typed exceptions from
`sie_sdk.client.errors`; all inherit from `SIEError`, and errors that
-carry a server response expose `.code` and `.status_code`. Invalid
-client-side arguments (for example, a bad `base_url_headers` value)
-raise ordinary Python exceptions such as `ValueError`.
+carry a server response expose `.code` and `.status_code`. `RequestError`
+and `ServerError` also expose `.request`, the request metadata of the
+error response when it carried any: for example `served_by`,
+`fallback_reason` and `fallback_error` on a local refusal that answers a
+failed remote attempt. Invalid client-side arguments (for example, a bad
+`base_url_headers` value) raise ordinary Python exceptions such as
+`ValueError`.
Several `503` codes are transient and retried automatically (see the
next section for the `RESOURCE_EXHAUSTED` budget):
@@ -354,6 +358,18 @@ a `503 QUEUE_UNAVAILABLE` that carries `Retry-After`. A
lists how each response is classified; the Python and TypeScript SDKs
both test against it.
+SIE Cloud answers `403` when it will not serve a request through SIE
+Relay, its partner capacity. The SDK raises `RelayUnavailableError`, a
+`RequestError` subclass that carries the server's message, and never
+retries it. Branch on `.code`:
+
+- `THIRD_PARTY_SERVING_DISABLED` — serving through SIE Relay is disabled.
+- `THIRD_PARTY_RUNTIME_UNLISTED` — the SIE Relay runtime that would serve
+ the model is not listed.
+- `THIRD_PARTY_REGION_UNAVAILABLE` — SIE Relay cannot serve the model in
+ the API key's region. `.key_region` and `.deployment_region` name the
+ regions when the response includes them.
+
### Timeouts
Each attempt has a connect timeout (`connect_timeout_s`, default 10 s)
diff --git a/packages/sie_sdk/src/sie_sdk/__init__.py b/packages/sie_sdk/src/sie_sdk/__init__.py
index a79da5101..f9cea0770 100644
--- a/packages/sie_sdk/src/sie_sdk/__init__.py
+++ b/packages/sie_sdk/src/sie_sdk/__init__.py
@@ -25,6 +25,7 @@ from sie_sdk.client import (
PoolError,
ProvisioningError,
RateLimitError,
+ RelayUnavailableError,
RequestError,
ResourceExhaustedError,
ServerError,
@@ -161,6 +162,7 @@ __all__ = [
"ProvisioningError",
"RateIdentity",
"RateLimitError",
+ "RelayUnavailableError",
"RequestError",
"ResourceExhaustedError",
"SIEAsyncClient",
diff --git a/packages/sie_sdk/src/sie_sdk/client/__init__.py b/packages/sie_sdk/src/sie_sdk/client/__init__.py
index 9e12cd1e7..ab1c1aa22 100644
--- a/packages/sie_sdk/src/sie_sdk/client/__init__.py
+++ b/packages/sie_sdk/src/sie_sdk/client/__init__.py
@@ -18,6 +18,7 @@ from sie_sdk.client.errors import (
PoolError,
ProvisioningError,
RateLimitError,
+ RelayUnavailableError,
RequestError,
ResourceExhaustedError,
ServerError,
@@ -41,6 +42,7 @@ __all__ = [
"PoolError",
"ProvisioningError",
"RateLimitError",
+ "RelayUnavailableError",
"RequestError",
"ResourceExhaustedError",
"SIEAsyncClient",
diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.py
index bb6f4d20a..10ad74a67 100644
--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py
+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py
@@ -302,6 +302,7 @@ from .errors import (
ModelLoadingError,
ProvisioningError,
RateLimitError,
+ RelayUnavailableError,
RequestError,
ResourceExhaustedError,
ServerError,
@@ -575,6 +576,18 @@ KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE = "KEY_SPEND_LIMIT_EXCEEDED"
ACCOUNT_SUSPENDED_ERROR_CODE = "ACCOUNT_SUSPENDED"
ACCOUNT_PENDING_REVIEW_ERROR_CODE = "ACCOUNT_PENDING_REVIEW"
ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE = "ACCOUNT_STATE_UNAVAILABLE"
+# SIE Cloud refuses a request it would serve through SIE Relay, its partner
+# capacity, with one of these 403 codes. Terminal like the account errors above.
+THIRD_PARTY_SERVING_DISABLED_ERROR_CODE = "THIRD_PARTY_SERVING_DISABLED"
+THIRD_PARTY_RUNTIME_UNLISTED_ERROR_CODE = "THIRD_PARTY_RUNTIME_UNLISTED"
+THIRD_PARTY_REGION_UNAVAILABLE_ERROR_CODE = "THIRD_PARTY_REGION_UNAVAILABLE"
+RELAY_UNAVAILABLE_ERROR_CODES = frozenset(
+ {
+ THIRD_PARTY_SERVING_DISABLED_ERROR_CODE,
+ THIRD_PARTY_RUNTIME_UNLISTED_ERROR_CODE,
+ THIRD_PARTY_REGION_UNAVAILABLE_ERROR_CODE,
+ }
+)
# Retry jitter. Fixed / pure-exponential backoff makes every client that
# lost a worker at the same instant (cluster cold start, rolling restart)
@@ -1351,6 +1364,8 @@ def handle_error(response: _HttpResponse) -> NoReturn:
failures (terminal — never retried).
AccountInactiveError: For 403 account suspended / pending review
(terminal — never retried).
+ RelayUnavailableError: For 403 SIE Relay refusals (terminal — never
+ retried).
AccountStateUnavailableError: For 503 ACCOUNT_STATE_UNAVAILABLE.
RequestError: For other 4xx responses.
ServerError: For other 5xx responses.
@@ -1358,6 +1373,7 @@ def handle_error(response: _HttpResponse) -> NoReturn:
code = None
param = None
message = f"HTTP {response.status_code}"
+ fields: dict[str, Any] = {}
try:
# Try msgpack first
@@ -1369,6 +1385,7 @@ def handle_error(response: _HttpResponse) -> NoReturn:
if "error" in data:
error = data["error"]
if isinstance(error, dict):
+ fields = error
code = error.get("code")
message = error.get("message", message)
error_param = error.get("param")
@@ -1379,6 +1396,7 @@ def handle_error(response: _HttpResponse) -> NoReturn:
elif "detail" in data:
detail = data["detail"]
if isinstance(detail, dict):
+ fields = detail
code = detail.get("code")
message = detail.get("message", str(detail))
detail_param = detail.get("param")
@@ -1422,6 +1440,17 @@ def handle_error(response: _HttpResponse) -> NoReturn:
ACCOUNT_PENDING_REVIEW_ERROR_CODE,
):
raise AccountInactiveError(message, code=code, param=param, request=request)
+ if response.status_code == HTTP_FORBIDDEN and code in RELAY_UNAVAILABLE_ERROR_CODES:
+ key_region = fields.get("key_region")
+ deployment_region = fields.get("deployment_region")
+ raise RelayUnavailableError(
+ message,
+ code=code,
+ key_region=key_region if isinstance(key_region, str) else None,
+ deployment_region=deployment_region if isinstance(deployment_region, str) else None,
+ param=param,
+ request=request,
+ )
if response.status_code == HTTP_SERVICE_UNAVAILABLE and code == ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE:
raise AccountStateUnavailableError(message, retry_after=get_retry_after(response), param=param, request=request)
if response.status_code >= HTTP_SERVER_ERROR:
diff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.py
index 5262acbf1..c78e9e2a1 100644
--- a/packages/sie_sdk/src/sie_sdk/client/errors.py
+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py
@@ -389,6 +389,44 @@ class AccountInactiveError(RequestError):
super().__init__(message, code=code, status_code=403, param=param, request=request)
+class RelayUnavailableError(RequestError):
+ """Error when SIE Cloud will not serve the request through SIE Relay.
+
+ Raised when SIE Cloud returns HTTP ``403 FORBIDDEN`` with code
+ ``THIRD_PARTY_SERVING_DISABLED``, ``THIRD_PARTY_RUNTIME_UNLISTED`` or
+ ``THIRD_PARTY_REGION_UNAVAILABLE``. These codes concern serving through
+ SIE Relay, the service's partner capacity. This is a TERMINAL failure —
+ the SDK never retries it, because retrying the same request gets the
+ same answer.
+
+ Subclass of :class:`RequestError` so existing 4xx handlers keep working;
+ new code can catch :class:`RelayUnavailableError` and branch on
+ :attr:`code`. The message is the server's.
+
+ Attributes:
+ key_region: The API key's region, which a
+ ``THIRD_PARTY_REGION_UNAVAILABLE`` refusal names when the key has
+ one. ``None`` otherwise.
+ deployment_region: The deployment's region, which a
+ ``THIRD_PARTY_REGION_UNAVAILABLE`` refusal names. ``None`` when
+ the response does not name it.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ code: str | None = None,
+ key_region: str | None = None,
+ deployment_region: str | None = None,
+ param: str | None = None,
+ request: RequestMetadata | None = None,
+ ) -> None:
+ super().__init__(message, code=code, status_code=403, param=param, request=request)
+ self.key_region = key_region
+ self.deployment_region = deployment_region
+
+
class AccountStateUnavailableError(ServerError):
"""Error when the gateway cannot resolve the account's admission state.
diff --git a/packages/sie_sdk/tests/client/test_relay_unavailable.py b/packages/sie_sdk/tests/client/test_relay_unavailable.py
new file mode 100644
index 000000000..b4b68a6e2
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_relay_unavailable.py
@@ -0,0 +1,167 @@
+"""SIE Cloud refusals to serve through SIE Relay surface as ``RelayUnavailableError``.
+
+SIE Cloud answers ``403`` with ``THIRD_PARTY_SERVING_DISABLED``,
+``THIRD_PARTY_RUNTIME_UNLISTED`` or ``THIRD_PARTY_REGION_UNAVAILABLE`` when it
+will not serve a request through SIE Relay, its partner capacity. The region
+refusal also names ``key_region`` and ``deployment_region``. The refusal is
+terminal: the SDK raises it on the first response.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import msgpack
+import numpy as np
+import pytest
+from sie_sdk import AccountInactiveError, RelayUnavailableError, RequestError, SIEAsyncClient, SIEClient
+from sie_sdk.client._shared import handle_error
+from sie_sdk.client.async_ import _AioResponse
+
+RELAY_CODES = (
+ "THIRD_PARTY_SERVING_DISABLED",
+ "THIRD_PARTY_RUNTIME_UNLISTED",
+ "THIRD_PARTY_REGION_UNAVAILABLE",
+)
+
+
+def _refusal(code: str, **fields: Any) -> dict[str, Any]:
+ return {"detail": {"code": code, "message": f"refused: {code}", **fields}}
+
+
+def _response(status: int, body: dict[str, Any], headers: dict[str, str] | None = None) -> MagicMock:
+ resp = MagicMock()
+ resp.status_code = status
+ resp.headers = {"content-type": "application/json", **(headers or {})}
+ resp.json.return_value = body
+ resp.text = json.dumps(body)
+ return resp
+
+
+def _encode_success() -> MagicMock:
+ resp = MagicMock()
+ resp.status_code = 200
+ resp.headers = {"content-type": "application/msgpack"}
+ resp.content = msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True)
+ return resp
+
+
[email protected]("code", RELAY_CODES)
+def test_each_relay_code_is_a_typed_request_error(code: str) -> None:
+ with pytest.raises(RelayUnavailableError) as raised:
+ handle_error(_response(403, _refusal(code)))
+
+ error = raised.value
+ assert isinstance(error, RequestError)
+ assert error.code == code
+ assert error.status_code == 403
+ assert str(error) == f"refused: {code}"
+ assert error.key_region is None
+ assert error.deployment_region is None
+
+
+def test_the_region_refusal_carries_both_regions() -> None:
+ body = _refusal("THIRD_PARTY_REGION_UNAVAILABLE", key_region="eu", deployment_region="us")
+
+ with pytest.raises(RelayUnavailableError) as raised:
+ handle_error(_response(403, body))
+
+ assert raised.value.key_region == "eu"
+ assert raised.value.deployment_region == "us"
+
+
+def test_a_key_without_a_region_reads_as_none() -> None:
+ body = _refusal("THIRD_PARTY_REGION_UNAVAILABLE", key_region=None, deployment_region="us")
+
+ with pytest.raises(RelayUnavailableError) as raised:
+ handle_error(_response(403, body))
+
+ assert raised.value.key_region is None
+ assert raised.value.deployment_region == "us"
+
+
+def test_regions_that_are_not_strings_are_dropped() -> None:
+ body = _refusal("THIRD_PARTY_REGION_UNAVAILABLE", key_region=7, deployment_region=["us"])
+
+ with pytest.raises(RelayUnavailableError) as raised:
+ handle_error(_response(403, body))
+
+ assert raised.value.key_region is None
+ assert raised.value.deployment_region is None
+
+
+def test_the_error_code_header_identifies_a_relay_refusal_in_the_openai_envelope() -> None:
+ body = {"error": {"message": "refused", "type": "invalid_request_error", "code": "permission_denied"}}
+ headers = {"X-SIE-Error-Code": "THIRD_PARTY_SERVING_DISABLED", "X-SIE-Request-ID": "req-relay-1"}
+
+ with pytest.raises(RelayUnavailableError) as raised:
+ handle_error(_response(403, body, headers))
+
+ assert raised.value.code == "THIRD_PARTY_SERVING_DISABLED"
+ assert str(raised.value) == "refused"
+ assert raised.value.request == {"id": "req-relay-1"}
+
+
+ ("status", "code"),
+ [(403, "INVALID_KEY"), (403, "ACCOUNT_SUSPENDED"), (400, "THIRD_PARTY_SERVING_DISABLED")],
+)
+def test_other_refusals_are_not_relay_refusals(status: int, code: str) -> None:
+ with pytest.raises(RequestError) as raised:
+ handle_error(_response(status, _refusal(code)))
+
+ assert not isinstance(raised.value, RelayUnavailableError)
+ assert isinstance(raised.value, AccountInactiveError) == (code == "ACCOUNT_SUSPENDED")
+
+
[email protected]("code", RELAY_CODES)
+def test_the_sync_client_raises_it_on_the_first_response(code: str) -> None:
+ with (
+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,
+ patch("sie_sdk.client.sync.time.sleep") as mock_sleep,
+ ):
+ mock_client.return_value.post = MagicMock(
+ side_effect=[_response(403, _refusal(code, deployment_region="us")), _encode_success()]
+ )
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(RelayUnavailableError) as raised:
+ client.encode("bge-m3", {"text": "hi"})
+
+ assert raised.value.code == code
+ assert raised.value.deployment_region == "us"
+ assert mock_client.return_value.post.call_count == 1
+ assert mock_sleep.call_count == 0
+ client.close()
+
+
[email protected]("code", RELAY_CODES)
+async def test_the_async_client_raises_it_on_the_first_response(code: str) -> None:
+ body = _refusal(code, key_region="eu", deployment_region="us")
+ with (
+ patch("sie_sdk.client.async_.aiohttp.ClientSession"),
+ patch("sie_sdk.client.async_.asyncio.sleep") as mock_sleep,
+ ):
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(
+ side_effect=[
+ _AioResponse(403, json.dumps(body).encode(), {"content-type": "application/json"}),
+ _AioResponse(
+ 200,
+ msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True),
+ {"content-type": "application/msgpack"},
+ ),
+ ]
+ )
+
+ with pytest.raises(RelayUnavailableError) as raised:
+ await client.encode("bge-m3", {"text": "hi"})
+
+ assert raised.value.code == code
+ assert (raised.value.key_region, raised.value.deployment_region) == ("eu", "us")
+ assert client._post.await_count == 1
+ assert mock_sleep.call_count == 0
+ await client.close()
diff --git a/packages/sie_sdk/tests/test_error_exports.py b/packages/sie_sdk/tests/test_error_exports.py
index c761b80a6..40f56c72a 100644
--- a/packages/sie_sdk/tests/test_error_exports.py
+++ b/packages/sie_sdk/tests/test_error_exports.py
@@ -80,6 +80,7 @@ _NON_CLIENT_ERRORS = frozenset({"GatedModelError", "MalformedChunkError"})
"PoolError",
"ProvisioningError",
"RateLimitError",
+ "RelayUnavailableError",
"RequestError",
"ResourceExhaustedError",
"SIEConnectionError",
diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.md
index b1497d90f..34b814778 100644
--- a/packages/sie_ts_sdk/README.md
+++ b/packages/sie_ts_sdk/README.md
@@ -118,7 +118,11 @@ for await (const chunk of client.streamGenerate(
All errors extend `SIEError` and are exported from the package root.
Server-reported errors carry `.code` and `.statusCode`, plus
`.requestId` (the gateway `x-sie-request-id`) when the gateway included
-one in the response — check it before using it.
+one in the response — check it before using it. `RequestError` and
+`ServerError` also carry `.request`, the request metadata of the error
+response when it carried any: for example `servedBy`, `fallbackReason`
+and `fallbackError` on a local refusal that answers a failed remote
+attempt.
```typescript
import {
@@ -164,6 +168,18 @@ gateway's queue backpressure, a `503 QUEUE_UNAVAILABLE` that carries
lists how each response is classified; the TypeScript and Python SDKs
both test against it.
+SIE Cloud answers `403` when it will not serve a request through SIE
+Relay, its partner capacity. The SDK throws `RelayUnavailableError`, a
+`RequestError` subclass that carries the server's message, and never
+retries it. Branch on `.code`:
+
+- `THIRD_PARTY_SERVING_DISABLED` — serving through SIE Relay is disabled.
+- `THIRD_PARTY_RUNTIME_UNLISTED` — the SIE Relay runtime that would serve
+ the model is not listed.
+- `THIRD_PARTY_REGION_UNAVAILABLE` — SIE Relay cannot serve the model in
+ the API key's region. `.keyRegion` and `.deploymentRegion` name the
+ regions when the response includes them.
+
Each attempt waits up to `timeoutMs` (default 150000 ms, longer than the
gateway's default 120 s request deadline) for a response. A timed-out
request is never retried, because the server may still be processing it.
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index 0b2f8a396..06ea082e8 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -79,9 +79,9 @@ import {
parseEncodeResults,
parseExtractResults,
parseGenerateResult,
+ parseRequestMetadata,
parseScoreResult,
readRequestId,
- settledChargeFields,
throwIfEstimateUnroutable,
throwIfInputTooLong,
throwIfModelLoadFailed,
@@ -150,14 +150,6 @@ import type {
StreamGenerateOptions,
WireModelInfo,
} from "./types.js";
-import {
- FALLBACK_ERROR_PATTERN,
- FALLBACK_REASONS,
- type FallbackReason,
- SERVED_BY_VALUES,
- type ServedBy,
- UPSTREAM_NAME_PATTERN,
-} from "./types.js";
import { SDK_VERSION } from "./version.js";
const JOB_RESULT_NOT_FOUND_ERROR_CODE = "RESULT_NOT_FOUND";
@@ -414,11 +406,15 @@ async function parseTerminalJsonObject(
owner: string,
): Promise<Record<string, unknown>> {
const body = new Uint8Array(await response.arrayBuffer());
+ const request = parseRequestMetadata(response.headers);
if (!response.ok) {
throw new RequestError(
`Unexpected ${owner} HTTP response (${terminalResponseDiagnostic(response, body.byteLength)})`,
undefined,
response.status,
+ undefined,
+ undefined,
+ request,
);
}
let data: unknown;
@@ -429,6 +425,9 @@ async function parseTerminalJsonObject(
`Malformed ${owner} JSON response (${terminalResponseDiagnostic(response, body.byteLength)})`,
undefined,
response.status,
+ undefined,
+ undefined,
+ request,
);
}
if (data === null || typeof data !== "object" || Array.isArray(data)) {
@@ -436,121 +435,16 @@ async function parseTerminalJsonObject(
`Unexpected ${owner} response shape (${terminalResponseDiagnostic(response, body.byteLength)})`,
undefined,
response.status,
+ undefined,
+ undefined,
+ request,
);
}
return data as Record<string, unknown>;
}
-function parseNonnegativeMeterHeader(headers: Headers, name: string): number | undefined {
- const raw = headers.get(name);
- if (raw === null || !/^(0|[1-9]\d*)$/.test(raw)) return undefined;
- const parsed = Number(raw);
- return Number.isSafeInteger(parsed) ? parsed : undefined;
-}
-
const REMOTE_HEADER = "X-SIE-Remote";
-/**
- * Parse optional request-scoped metadata from one successful terminal response.
- *
- * `body` is the decoded response envelope, when the caller has one. The settled
- * charge is read from its `usage` block FIRST and falls back to the
- * `x-sie-credits-debited` header, which is the only source on a gateway that
- * predates in-body surfacing (#2434). The two always agree when both are
- * present; the body additionally names the rate book, which no header does.
- */
-function parseRequestMetadata(headers: Headers, body?: unknown): RequestMetadata | undefined {
- const metadata: RequestMetadata = {};
- const requestId = headers.get("x-sie-request-id");
- if (
- requestId !== null &&
- requestId.length > 0 &&
- requestId.length <= 256 &&
- requestId === requestId.trim() &&
- /^[\x20-\x7e]+$/.test(requestId)
- ) {
- metadata.id = requestId;
- }
- const executionIdentitySha256 = headers.get("x-sie-execution-identity-sha256");
- if (executionIdentitySha256 !== null && /^[0-9a-f]{64}$/.test(executionIdentitySha256)) {
- metadata.executionIdentitySha256 = executionIdentitySha256;
- }
- const executionBindingSha256 = headers.get("x-sie-execution-binding-sha256");
- if (executionBindingSha256 !== null && /^[0-9a-f]{64}$/.test(executionBindingSha256)) {
- metadata.executionBindingSha256 = executionBindingSha256;
- }
- const servedBy = headers.get("x-sie-served-by");
- const runtimeInstance = headers.get("x-sie-runtime-instance");
- if (runtimeInstance !== null && /^[0-9a-f]{64}$/.test(runtimeInstance)) {
- metadata.runtimeInstanceId = runtimeInstance;
- }
- if (servedBy !== null && (SERVED_BY_VALUES as readonly string[]).includes(servedBy)) {
- metadata.servedBy = servedBy as ServedBy;
- }
- const upstream = headers.get("x-sie-upstream");
- if (upstream !== null && UPSTREAM_NAME_PATTERN.test(upstream)) {
- metadata.upstream = upstream;
- }
- const fallbackReason = headers.get("x-sie-fallback-reason");
- if (fallbackReason !== null && (FALLBACK_REASONS as readonly string[]).includes(fallbackReason)) {
- metadata.fallbackReason = fallbackReason as FallbackReason;
- }
- const fallbackError = headers.get("x-sie-fallback-error");
- if (fallbackError !== null && FALLBACK_ERROR_PATTERN.test(fallbackError)) {
- metadata.fallbackError = fallbackError;
- }
-
- const usageHeaders = {
- inputTokens: "x-sie-units-input-tokens",
- pairs: "x-sie-units-pairs",
- contentInputTokens: "x-sie-units-content-input-tokens",
- images: "x-sie-units-images",
- pages: "x-sie-units-pages",
- outputTokens: "x-sie-units-output-tokens",
- audioMs: "x-sie-units-audio-ms",
- } as const;
- const usage: NonNullable<RequestMetadata["usage"]> = {};
- for (const [field, header] of Object.entries(usageHeaders) as [
- keyof typeof usageHeaders,
- string,
- ][]) {
- const value = parseNonnegativeMeterHeader(headers, header);
- if (value !== undefined) usage[field] = value;
- }
-
- const settled = settledChargeFromBody(body);
- if (settled !== undefined) {
- usage.creditsCharged = settled.creditsCharged;
- usage.rateBookVersion = settled.rateBookVersion;
- metadata.creditsDebited = settled.creditsCharged;
- metadata.rateBookVersion = settled.rateBookVersion;
- } else {
- const creditsDebited = parseNonnegativeMeterHeader(headers, "x-sie-credits-debited");
- if (creditsDebited !== undefined) metadata.creditsDebited = creditsDebited;
- }
- if (Object.keys(usage).length > 0) metadata.usage = usage;
- return Object.keys(metadata).length > 0 ? metadata : undefined;
-}
-
-/**
- * The settled charge from a response envelope's `usage` block (#2434).
- *
- * Shares `settledChargeFields`' validation so the metadata path and the result
- * parsers can never disagree about what counts as a publishable charge.
- * Anything malformed is treated as absent, so the header fallback still
- * applies.
- */
-function settledChargeFromBody(
- body: unknown,
-): { creditsCharged: number; rateBookVersion: string } | undefined {
- if (typeof body !== "object" || body === null || Array.isArray(body)) return undefined;
- const { creditsCharged, rateBookVersion } = settledChargeFields(
- (body as Record<string, unknown>).usage,
- );
- if (creditsCharged === undefined || rateBookVersion === undefined) return undefined;
- return { creditsCharged, rateBookVersion };
-}
-
function attachRequestMetadata<T extends { request?: RequestMetadata }>(
results: T[],
headers: Headers,
@@ -1977,6 +1871,7 @@ export class SIEClient {
model,
retries: oomRetries,
param: await getErrorParam(attemptResponse.clone()),
+ request: parseRequestMetadata(attemptResponse.headers),
},
);
}
@@ -1988,6 +1883,7 @@ export class SIEClient {
provisionTimeoutMs: this.provisionTimeout,
model,
param: await getErrorParam(attemptResponse.clone()),
+ request: parseRequestMetadata(attemptResponse.headers),
});
oomRetries += 1;
if (await abortableSleep(delay, controller.signal)) {
@@ -2020,6 +1916,7 @@ export class SIEClient {
HTTP_GATEWAY_TIMEOUT,
readRequestId(attemptResponse),
await getErrorParam(attemptResponse.clone()),
+ parseRequestMetadata(attemptResponse.headers),
);
}
diff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.ts
index d3c888734..46b5e2961 100644
--- a/packages/sie_ts_sdk/src/errors.ts
+++ b/packages/sie_ts_sdk/src/errors.ts
@@ -19,7 +19,7 @@
* }
*/
-import type { EncodeResult, ExtractResult } from "./types.js";
+import type { EncodeResult, ExtractResult, RequestMetadata } from "./types.js";
/**
* Base error for all SIE SDK errors.
@@ -85,6 +85,13 @@ export class RequestError extends SIEError {
readonly requestId: string | undefined;
/** Offending request field from the server error envelope, when known. */
readonly param: string | null | undefined;
+ /**
+ * Request metadata parsed from the error response's headers, when it
+ * carried any: for example `servedBy`, `fallbackReason` and `fallbackError`
+ * on a local refusal that answers a failed remote attempt. Mirrors the
+ * Python SDK's `RequestError.request`.
+ */
+ readonly request: RequestMetadata | undefined;
constructor(
message: string,
@@ -92,13 +99,15 @@ export class RequestError extends SIEError {
statusCode?: number,
requestId?: string,
param?: string | null,
+ request?: RequestMetadata,
) {
super(message);
this.name = "RequestError";
this.code = code;
this.statusCode = statusCode;
- this.requestId = requestId;
+ this.requestId = requestId ?? request?.id;
this.param = param;
+ this.request = request;
}
}
@@ -124,6 +133,13 @@ export class ServerError extends SIEError {
readonly requestId: string | undefined;
/** Offending request field from the server error envelope, when known. */
readonly param: string | null | undefined;
+ /**
+ * Request metadata parsed from the error response's headers, when it
+ * carried any: for example `servedBy`, `fallbackReason` and `fallbackError`
+ * on a local refusal that answers a failed remote attempt. Mirrors the
+ * Python SDK's `ServerError.request`.
+ */
+ readonly request: RequestMetadata | undefined;
constructor(
message: string,
@@ -131,13 +147,15 @@ export class ServerError extends SIEError {
statusCode?: number,
requestId?: string,
param?: string | null,
+ request?: RequestMetadata,
) {
super(message);
this.name = "ServerError";
this.code = code;
this.statusCode = statusCode;
- this.requestId = requestId;
+ this.requestId = requestId ?? request?.id;
this.param = param;
+ this.request = request;
}
}
@@ -264,9 +282,14 @@ export class ResourceExhaustedError extends ServerError {
constructor(
message: string,
- options?: { model?: string; retries?: number; param?: string | null },
+ options?: {
+ model?: string;
+ retries?: number;
+ param?: string | null;
+ request?: RequestMetadata;
+ },
) {
- super(message, "RESOURCE_EXHAUSTED", 503, undefined, options?.param);
+ super(message, "RESOURCE_EXHAUSTED", 503, undefined, options?.param, options?.request);
this.name = "ResourceExhaustedError";
this.model = options?.model;
this.retries = options?.retries ?? 0;
@@ -360,9 +383,10 @@ export class ModelLoadFailedError extends ServerError {
permanent?: boolean;
attempts?: number;
param?: string | null;
+ request?: RequestMetadata;
},
) {
- super(message, "MODEL_LOAD_FAILED", 502, undefined, options?.param);
+ super(message, "MODEL_LOAD_FAILED", 502, undefined, options?.param, options?.request);
this.name = "ModelLoadFailedError";
this.model = options?.model;
this.errorClass = options?.errorClass;
@@ -388,8 +412,11 @@ export class InputTooLongError extends RequestError {
/** The model that was requested */
readonly model: string | undefined;
- constructor(message: string, options?: { model?: string; param?: string | null }) {
- super(message, "INPUT_TOO_LONG", 400, undefined, options?.param);
+ constructor(
+ message: string,
+ options?: { model?: string; param?: string | null; request?: RequestMetadata },
+ ) {
+ super(message, "INPUT_TOO_LONG", 400, undefined, options?.param, options?.request);
this.name = "InputTooLongError";
this.model = options?.model;
}
@@ -454,10 +481,11 @@ export class IncompleteBatchError extends ServerError {
missingIds?: string[];
requestId?: string;
param?: string | null;
+ request?: RequestMetadata;
results?: readonly (EncodeResult | ExtractResult)[];
},
) {
- super(message, options.code, 200, options.requestId, options.param);
+ super(message, options.code, 200, options.requestId, options.param, options.request);
this.name = "IncompleteBatchError";
this.expected = options.expected;
this.received = options.received;
@@ -548,8 +576,8 @@ export class MalformedChunkError extends SIEError {
* Subclass of {@link ServerError} so existing 5xx handlers keep working.
*/
export class EstimateUnroutableError extends ServerError {
- constructor(message: string, code?: string, param?: string | null) {
- super(message, code, 503, undefined, param);
+ constructor(message: string, code?: string, param?: string | null, request?: RequestMetadata) {
+ super(message, code, 503, undefined, param, request);
this.name = "EstimateUnroutableError";
}
}
@@ -574,9 +602,22 @@ export class RateLimitError extends RequestError {
constructor(
message: string,
- options?: { retryAfter?: number; code?: string; requestId?: string; param?: string | null },
+ options?: {
+ retryAfter?: number;
+ code?: string;
+ requestId?: string;
+ param?: string | null;
+ request?: RequestMetadata;
+ },
) {
- super(message, options?.code ?? "RATE_LIMIT", 429, options?.requestId, options?.param);
+ super(
+ message,
+ options?.code ?? "RATE_LIMIT",
+ 429,
+ options?.requestId,
+ options?.param,
+ options?.request,
+ );
this.name = "RateLimitError";
this.retryAfter = options?.retryAfter;
}
@@ -593,8 +634,18 @@ export class RateLimitError extends RequestError {
* Mirrors the Python SDK's `InsufficientCreditsError`.
*/
export class InsufficientCreditsError extends RequestError {
- constructor(message: string, options?: { requestId?: string; param?: string | null }) {
- super(message, "INSUFFICIENT_CREDITS", 402, options?.requestId, options?.param);
+ constructor(
+ message: string,
+ options?: { requestId?: string; param?: string | null; request?: RequestMetadata },
+ ) {
+ super(
+ message,
+ "INSUFFICIENT_CREDITS",
+ 402,
+ options?.requestId,
+ options?.param,
+ options?.request,
+ );
this.name = "InsufficientCreditsError";
}
}
@@ -611,8 +662,18 @@ export class InsufficientCreditsError extends RequestError {
* Mirrors the Python SDK's `SpendLimitError`.
*/
export class SpendLimitError extends RequestError {
- constructor(message: string, options?: { requestId?: string; param?: string | null }) {
- super(message, "KEY_SPEND_LIMIT_EXCEEDED", 402, options?.requestId, options?.param);
+ constructor(
+ message: string,
+ options?: { requestId?: string; param?: string | null; request?: RequestMetadata },
+ ) {
+ super(
+ message,
+ "KEY_SPEND_LIMIT_EXCEEDED",
+ 402,
+ options?.requestId,
+ options?.param,
+ options?.request,
+ );
this.name = "SpendLimitError";
}
}
@@ -630,12 +691,61 @@ export class SpendLimitError extends RequestError {
* Mirrors the Python SDK's `AccountInactiveError`.
*/
export class AccountInactiveError extends RequestError {
- constructor(message: string, code?: string, requestId?: string, param?: string | null) {
- super(message, code, 403, requestId, param);
+ constructor(
+ message: string,
+ code?: string,
+ requestId?: string,
+ param?: string | null,
+ request?: RequestMetadata,
+ ) {
+ super(message, code, 403, requestId, param, request);
this.name = "AccountInactiveError";
}
}
+/**
+ * Error when SIE Cloud will not serve the request through SIE Relay.
+ *
+ * Thrown when SIE Cloud returns HTTP `403 FORBIDDEN` with code
+ * `THIRD_PARTY_SERVING_DISABLED`, `THIRD_PARTY_RUNTIME_UNLISTED` or
+ * `THIRD_PARTY_REGION_UNAVAILABLE`. These codes concern serving through SIE
+ * Relay, the service's partner capacity. This is a TERMINAL failure — the SDK
+ * never retries it, because retrying the same request gets the same answer.
+ * Branch on `code`; the message is the server's.
+ *
+ * Subclass of {@link RequestError} so existing 4xx handlers keep working.
+ * Mirrors the Python SDK's `RelayUnavailableError`.
+ */
+export class RelayUnavailableError extends RequestError {
+ /**
+ * The API key's region, which a `THIRD_PARTY_REGION_UNAVAILABLE` refusal
+ * names when the key has one.
+ */
+ readonly keyRegion: string | undefined;
+ /**
+ * The deployment's region, which a `THIRD_PARTY_REGION_UNAVAILABLE` refusal
+ * names.
+ */
+ readonly deploymentRegion: string | undefined;
+
+ constructor(
+ message: string,
+ options?: {
+ code?: string;
+ keyRegion?: string;
+ deploymentRegion?: string;
+ requestId?: string;
+ param?: string | null;
+ request?: RequestMetadata;
+ },
+ ) {
+ super(message, options?.code, 403, options?.requestId, options?.param, options?.request);
+ this.name = "RelayUnavailableError";
+ this.keyRegion = options?.keyRegion;
+ this.deploymentRegion = options?.deploymentRegion;
+ }
+}
+
/**
* Error when the gateway cannot resolve the account's admission state.
*
@@ -650,8 +760,13 @@ export class AccountInactiveError extends RequestError {
* Mirrors the Python SDK's `AccountStateUnavailableError`.
*/
export class AccountStateUnavailableError extends ServerError {
- constructor(message: string, requestId?: string, param?: string | null) {
- super(message, "ACCOUNT_STATE_UNAVAILABLE", 503, requestId, param);
+ constructor(
+ message: string,
+ requestId?: string,
+ param?: string | null,
+ request?: RequestMetadata,
+ ) {
+ super(message, "ACCOUNT_STATE_UNAVAILABLE", 503, requestId, param, request);
this.name = "AccountStateUnavailableError";
}
}
diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.ts
index 45cbf73f4..0ad21de17 100644
--- a/packages/sie_ts_sdk/src/index.ts
+++ b/packages/sie_ts_sdk/src/index.ts
@@ -203,6 +203,7 @@ export {
InsufficientCreditsError,
SpendLimitError,
AccountInactiveError,
+ RelayUnavailableError,
AccountStateUnavailableError,
} from "./errors.js";
diff --git a/packages/sie_ts_sdk/src/internal/constants.ts b/packages/sie_ts_sdk/src/internal/constants.ts
index 03bcce109..ed0e3ea39 100644
--- a/packages/sie_ts_sdk/src/internal/constants.ts
+++ b/packages/sie_ts_sdk/src/internal/constants.ts
@@ -91,6 +91,16 @@ export const KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE = "KEY_SPEND_LIMIT_EXCEEDED";
export const ACCOUNT_SUSPENDED_ERROR_CODE = "ACCOUNT_SUSPENDED";
export const ACCOUNT_PENDING_REVIEW_ERROR_CODE = "ACCOUNT_PENDING_REVIEW";
export const ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE = "ACCOUNT_STATE_UNAVAILABLE";
+// SIE Cloud refuses a request it would serve through SIE Relay, its partner
+// capacity, with one of these 403 codes. Terminal like the account errors above.
+export const THIRD_PARTY_SERVING_DISABLED_ERROR_CODE = "THIRD_PARTY_SERVING_DISABLED";
+export const THIRD_PARTY_RUNTIME_UNLISTED_ERROR_CODE = "THIRD_PARTY_RUNTIME_UNLISTED";
+export const THIRD_PARTY_REGION_UNAVAILABLE_ERROR_CODE = "THIRD_PARTY_REGION_UNAVAILABLE";
+export const RELAY_UNAVAILABLE_ERROR_CODES: ReadonlySet<string> = new Set([
+ THIRD_PARTY_SERVING_DISABLED_ERROR_CODE,
+ THIRD_PARTY_RUNTIME_UNLISTED_ERROR_CODE,
+ THIRD_PARTY_REGION_UNAVAILABLE_ERROR_CODE,
+]);
// Version negotiation headers
export const SDK_VERSION_HEADER = "X-SIE-SDK-Version";
diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.ts
index e81e3460d..7849c5c8b 100644
--- a/packages/sie_ts_sdk/src/internal/parsing.ts
+++ b/packages/sie_ts_sdk/src/internal/parsing.ts
@@ -12,25 +12,33 @@ import {
ModelLoadFailedError,
ProvisioningError,
RateLimitError,
+ RelayUnavailableError,
RequestError,
ServerError,
SpendLimitError,
} from "../errors.js";
import { unpackMessage } from "../msgpack.js";
-import type {
- CapacityInfo,
- Classification,
- DetectedObject,
- EncodeResult,
- Entity,
- ExtractItemError,
- ExtractResult,
- FinishReason,
- GenerateResult,
- Relation,
- ScoreEntry,
- ScoreResult,
- WorkerInfo,
+import {
+ type CapacityInfo,
+ type Classification,
+ type DetectedObject,
+ type EncodeResult,
+ type Entity,
+ type ExtractItemError,
+ type ExtractResult,
+ FALLBACK_ERROR_PATTERN,
+ FALLBACK_REASONS,
+ type FallbackReason,
+ type FinishReason,
+ type GenerateResult,
+ type Relation,
+ type RequestMetadata,
+ SERVED_BY_VALUES,
+ type ScoreEntry,
+ type ScoreResult,
+ type ServedBy,
+ UPSTREAM_NAME_PATTERN,
+ type WorkerInfo,
} from "../types.js";
import {
ACCOUNT_PENDING_REVIEW_ERROR_CODE,
@@ -47,6 +55,7 @@ import {
KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE,
MSGPACK_CONTENT_TYPE,
PROVISIONING_ERROR_CODE,
+ RELAY_UNAVAILABLE_ERROR_CODES,
} from "./constants.js";
import { getRetryAfter as getRetryAfterFromHeader } from "./retry.js";
@@ -89,6 +98,118 @@ export function validateRequestId(value: unknown): string | undefined {
return undefined;
}
+function parseNonnegativeMeterHeader(headers: Headers, name: string): number | undefined {
+ const raw = headers.get(name);
+ if (raw === null || !/^(0|[1-9]\d*)$/.test(raw)) return undefined;
+ const parsed = Number(raw);
+ return Number.isSafeInteger(parsed) ? parsed : undefined;
+}
+
+/**
+ * Parse optional request-scoped metadata from one terminal response, successful
+ * or not: an error response's metadata rides on the thrown error's `request`.
+ *
+ * `body` is the decoded response envelope, when the caller has one. The settled
+ * charge is read from its `usage` block FIRST and falls back to the
+ * `x-sie-credits-debited` header, which is the only source on a gateway that
+ * predates in-body surfacing (#2434). The two always agree when both are
+ * present; the body additionally names the rate book, which no header does.
+ */
+export function parseRequestMetadata(
+ headers: Headers,
+ body?: unknown,
+): RequestMetadata | undefined {
+ const metadata: RequestMetadata = {};
+ const requestId = headers.get("x-sie-request-id");
+ if (
+ requestId !== null &&
+ requestId.length > 0 &&
+ requestId.length <= 256 &&
+ requestId === requestId.trim() &&
+ /^[\x20-\x7e]+$/.test(requestId)
+ ) {
+ metadata.id = requestId;
+ }
+ const executionIdentitySha256 = headers.get("x-sie-execution-identity-sha256");
+ if (executionIdentitySha256 !== null && /^[0-9a-f]{64}$/.test(executionIdentitySha256)) {
+ metadata.executionIdentitySha256 = executionIdentitySha256;
+ }
+ const executionBindingSha256 = headers.get("x-sie-execution-binding-sha256");
+ if (executionBindingSha256 !== null && /^[0-9a-f]{64}$/.test(executionBindingSha256)) {
+ metadata.executionBindingSha256 = executionBindingSha256;
+ }
+ const servedBy = headers.get("x-sie-served-by");
+ const runtimeInstance = headers.get("x-sie-runtime-instance");
+ if (runtimeInstance !== null && /^[0-9a-f]{64}$/.test(runtimeInstance)) {
+ metadata.runtimeInstanceId = runtimeInstance;
+ }
+ if (servedBy !== null && (SERVED_BY_VALUES as readonly string[]).includes(servedBy)) {
+ metadata.servedBy = servedBy as ServedBy;
+ }
+ const upstream = headers.get("x-sie-upstream");
+ if (upstream !== null && UPSTREAM_NAME_PATTERN.test(upstream)) {
+ metadata.upstream = upstream;
+ }
+ const fallbackReason = headers.get("x-sie-fallback-reason");
+ if (fallbackReason !== null && (FALLBACK_REASONS as readonly string[]).includes(fallbackReason)) {
+ metadata.fallbackReason = fallbackReason as FallbackReason;
+ }
+ const fallbackError = headers.get("x-sie-fallback-error");
+ if (fallbackError !== null && FALLBACK_ERROR_PATTERN.test(fallbackError)) {
+ metadata.fallbackError = fallbackError;
+ }
+
+ const usageHeaders = {
+ inputTokens: "x-sie-units-input-tokens",
+ pairs: "x-sie-units-pairs",
+ contentInputTokens: "x-sie-units-content-input-tokens",
+ images: "x-sie-units-images",
+ pages: "x-sie-units-pages",
+ outputTokens: "x-sie-units-output-tokens",
+ audioMs: "x-sie-units-audio-ms",
+ } as const;
+ const usage: NonNullable<RequestMetadata["usage"]> = {};
+ for (const [field, header] of Object.entries(usageHeaders) as [
+ keyof typeof usageHeaders,
+ string,
+ ][]) {
+ const value = parseNonnegativeMeterHeader(headers, header);
+ if (value !== undefined) usage[field] = value;
+ }
+
+ const settled = settledChargeFromBody(body);
+ if (settled !== undefined) {
+ usage.creditsCharged = settled.creditsCharged;
+ usage.rateBookVersion = settled.rateBookVersion;
+ metadata.creditsDebited = settled.creditsCharged;
+ metadata.rateBookVersion = settled.rateBookVersion;
+ } else {
+ const creditsDebited = parseNonnegativeMeterHeader(headers, "x-sie-credits-debited");
+ if (creditsDebited !== undefined) metadata.creditsDebited = creditsDebited;
+ }
+ if (Object.keys(usage).length > 0) metadata.usage = usage;
+ return Object.keys(metadata).length > 0 ? metadata : undefined;
+}
+
+/**
+ * The settled charge from a response envelope's `usage` block (#2434).
+ *
+ * Shares `settledChargeFields`' validation so the metadata path and the result
+ * parsers can never disagree about what counts as a publishable charge.
+ * Anything malformed is treated as absent, so the header fallback still
+ * applies.
+ */
+function settledChargeFromBody(
+ body: unknown,
+): { creditsCharged: number; rateBookVersion: string } | undefined {
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return undefined;
+ const { creditsCharged, rateBookVersion } = settledChargeFields(
+ (body as Record<string, unknown>).usage,
+ );
+ if (creditsCharged === undefined || rateBookVersion === undefined) return undefined;
+ return { creditsCharged, rateBookVersion };
+}
+
/**
* Parse GPU parameter from "pool/gpu" format
*/
@@ -210,6 +331,7 @@ export async function throwIfModelLoadFailed(response: Response, model?: string)
permanent,
attempts,
param: errorParamFromDetail(detail),
+ request: parseRequestMetadata(response.headers),
});
}
@@ -233,7 +355,11 @@ export async function throwIfInputTooLong(response: Response, model?: string): P
typeof detail.message === "string"
? detail.message
: "Input exceeds the model's maximum token capacity";
- throw new InputTooLongError(message, { model, param: errorParamFromDetail(detail) });
+ throw new InputTooLongError(message, {
+ model,
+ param: errorParamFromDetail(detail),
+ request: parseRequestMetadata(response.headers),
+ });
}
/** The one exact path of the cost-estimate dry run (#2435). */
@@ -310,7 +436,12 @@ export async function throwIfEstimateUnroutable(response: Response): Promise<voi
detail && typeof detail.message === "string"
? detail.message
: "the active rate book cannot price this request";
- throw new EstimateUnroutableError(message, code, errorParamFromDetail(detail));
+ throw new EstimateUnroutableError(
+ message,
+ code,
+ errorParamFromDetail(detail),
+ parseRequestMetadata(response.headers),
+ );
}
/**
@@ -356,6 +487,7 @@ export async function handleError(response: Response, gpu?: string): Promise<nev
}
code = response.headers.get(SIE_ERROR_CODE_HEADER) ?? normalizeErrorCode(code);
const requestId = readRequestId(response);
+ const request = parseRequestMetadata(response.headers);
if (status === 503 && code === PROVISIONING_ERROR_CODE) {
const retryAfter = getRetryAfter(response);
@@ -372,6 +504,7 @@ export async function handleError(response: Response, gpu?: string): Promise<nev
code,
requestId,
param,
+ request,
});
}
@@ -380,34 +513,45 @@ export async function handleError(response: Response, gpu?: string): Promise<nev
// first response. Unrecognised 402/403 codes stay generic RequestError.
if (status === HTTP_PAYMENT_REQUIRED) {
if (code === INSUFFICIENT_CREDITS_ERROR_CODE)
- throw new InsufficientCreditsError(message, { requestId, param });
+ throw new InsufficientCreditsError(message, { requestId, param, request });
if (code === KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE)
- throw new SpendLimitError(message, { requestId, param });
+ throw new SpendLimitError(message, { requestId, param, request });
}
if (
status === HTTP_FORBIDDEN &&
(code === ACCOUNT_SUSPENDED_ERROR_CODE || code === ACCOUNT_PENDING_REVIEW_ERROR_CODE)
) {
- throw new AccountInactiveError(message, code, requestId, param);
+ throw new AccountInactiveError(message, code, requestId, param, request);
+ }
+ if (status === HTTP_FORBIDDEN && code !== undefined && RELAY_UNAVAILABLE_ERROR_CODES.has(code)) {
+ throw new RelayUnavailableError(message, {
+ code,
+ keyRegion: typeof detail?.key_region === "string" ? detail.key_region : undefined,
+ deploymentRegion:
+ typeof detail?.deployment_region === "string" ? detail.deployment_region : undefined,
+ requestId,
+ param,
+ request,
+ });
}
if (status === 503 && code === ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE) {
- throw new AccountStateUnavailableError(message, requestId, param);
+ throw new AccountStateUnavailableError(message, requestId, param, request);
}
if (status >= HTTP_CLIENT_ERROR_MIN && status <= HTTP_CLIENT_ERROR_MAX) {
if (status === 400 && code === "INPUT_TOO_LONG") {
// Fallback dispatch — ``model`` is only attached by the helper-style
// short-circuit (``throwIfInputTooLong``) on the extract path.
- throw new InputTooLongError(message, { param });
+ throw new InputTooLongError(message, { param, request });
}
- throw new RequestError(message, code, status, requestId, param);
+ throw new RequestError(message, code, status, requestId, param, request);
}
if (status >= HTTP_SERVER_ERROR_MIN && status <= HTTP_SERVER_ERROR_MAX) {
- throw new ServerError(message, code, status, requestId, param);
+ throw new ServerError(message, code, status, requestId, param, request);
}
- throw new ServerError(message, code, status, requestId, param);
+ throw new ServerError(message, code, status, requestId, param, request);
}
// Wire format types (what server sends)
diff --git a/packages/sie_ts_sdk/src/internal/provisioning.ts b/packages/sie_ts_sdk/src/internal/provisioning.ts
index 5cc4f52e8..4c49231f1 100644
--- a/packages/sie_ts_sdk/src/internal/provisioning.ts
+++ b/packages/sie_ts_sdk/src/internal/provisioning.ts
@@ -32,6 +32,7 @@ import {
ResourceExhaustedError,
ServerError,
} from "../errors.js";
+import type { RequestMetadata } from "../types.js";
import {
BACKPRESSURE_503_DEFAULT_DELAY,
BACKPRESSURE_503_ERROR_CODES,
@@ -51,6 +52,7 @@ import {
getErrorParam,
getRetryAfter,
handleError,
+ parseRequestMetadata,
readRequestId,
throwIfModelLoadFailed,
} from "./parsing.js";
@@ -119,16 +121,25 @@ export function nextOomRetryDelay(opts: {
provisionTimeoutMs: number;
model: string;
param?: string | null;
+ request?: RequestMetadata;
}): number {
- const { retryAfter, oomRetries, maxOomRetries, elapsedMs, provisionTimeoutMs, model, param } =
- opts;
+ const {
+ retryAfter,
+ oomRetries,
+ maxOomRetries,
+ elapsedMs,
+ provisionTimeoutMs,
+ model,
+ param,
+ request,
+ } = opts;
const message = `Server resource exhausted after ${oomRetries} retry attempt(s) for model '${model}'`;
if (oomRetries >= maxOomRetries || elapsedMs >= provisionTimeoutMs) {
- throw new ResourceExhaustedError(message, { model, retries: oomRetries, param });
+ throw new ResourceExhaustedError(message, { model, retries: oomRetries, param, request });
}
const delay = computeOomBackoff(retryAfter, oomRetries);
if (delay >= provisionTimeoutMs - elapsedMs) {
- throw new ResourceExhaustedError(message, { model, retries: oomRetries, param });
+ throw new ResourceExhaustedError(message, { model, retries: oomRetries, param, request });
}
return delay;
}
@@ -194,6 +205,7 @@ export async function admissionRetryDelay(
retryAfter,
requestId: readRequestId(response),
param: await getErrorParam(response.clone()),
+ request: parseRequestMetadata(response.headers),
},
);
}
@@ -310,6 +322,7 @@ export async function withProvisioningRetry(
provisionTimeoutMs: opts.provisionTimeoutMs,
model: opts.model,
param: await getErrorParam(response.clone()),
+ request: parseRequestMetadata(response.headers),
});
oomRetries += 1;
await sleep(delay);
@@ -348,6 +361,7 @@ export async function withProvisioningRetry(
HTTP_GATEWAY_TIMEOUT,
readRequestId(response),
await getErrorParam(response.clone()),
+ parseRequestMetadata(response.headers),
);
}
diff --git a/packages/sie_ts_sdk/tests/relayUnavailable.test.ts b/packages/sie_ts_sdk/tests/relayUnavailable.test.ts
new file mode 100644
index 000000000..2df36dda7
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/relayUnavailable.test.ts
@@ -0,0 +1,178 @@
+/**
+ * SIE Cloud refusals to serve through SIE Relay surface as `RelayUnavailableError`.
+ *
+ * SIE Cloud answers `403` with `THIRD_PARTY_SERVING_DISABLED`,
+ * `THIRD_PARTY_RUNTIME_UNLISTED` or `THIRD_PARTY_REGION_UNAVAILABLE` when it
+ * will not serve a request through SIE Relay, its partner capacity. The region
+ * refusal also names `key_region` and `deployment_region`. The refusal is
+ * terminal: the SDK throws it on the first response. Mirrors the Python SDK's
+ * `test_relay_unavailable.py`.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+import {
+ AccountInactiveError,
+ RelayUnavailableError,
+ RequestError,
+ SIEError,
+} from "../src/errors.js";
+import { handleError } from "../src/internal/parsing.js";
+import { packMessage } from "../src/msgpack.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+const RELAY_CODES = [
+ "THIRD_PARTY_SERVING_DISABLED",
+ "THIRD_PARTY_RUNTIME_UNLISTED",
+ "THIRD_PARTY_REGION_UNAVAILABLE",
+] as const;
+
+function refusal(
+ code: string,
+ fields: Record<string, unknown> = {},
+ status = 403,
+ headers: Record<string, string> = {},
+): Response {
+ return new Response(
+ JSON.stringify({ detail: { code, message: `refused: ${code}`, ...fields } }),
+ {
+ status,
+ headers: { "Content-Type": "application/json", ...headers },
+ },
+ );
+}
+
+function encodeSuccess(): Response {
+ return new Response(packMessage({ items: [{ dense: { values: new Float32Array([0.1]) } }] }), {
+ status: 200,
+ headers: { "Content-Type": "application/msgpack" },
+ });
+}
+
+async function thrown(promise: Promise<unknown>): Promise<unknown> {
+ return promise.then(
+ () => {
+ throw new Error("expected a rejection");
+ },
+ (error: unknown) => error,
+ );
+}
+
+describe("handleError maps SIE Relay refusals", () => {
+ it.each(RELAY_CODES)("maps 403 %s to a typed RequestError", async (code) => {
+ const error = await thrown(handleError(refusal(code)));
+
+ expect(error).toBeInstanceOf(RelayUnavailableError);
+ expect(error).toBeInstanceOf(RequestError);
+ expect(error).toBeInstanceOf(SIEError);
+ expect(error).toMatchObject({
+ name: "RelayUnavailableError",
+ code,
+ statusCode: 403,
+ message: `refused: ${code}`,
+ keyRegion: undefined,
+ deploymentRegion: undefined,
+ });
+ });
+
+ it("carries both regions of a region refusal", async () => {
+ const error = await thrown(
+ handleError(
+ refusal("THIRD_PARTY_REGION_UNAVAILABLE", { key_region: "eu", deployment_region: "us" }),
+ ),
+ );
+
+ expect(error).toMatchObject({ keyRegion: "eu", deploymentRegion: "us" });
+ });
+
+ it("reads a key without a region as undefined", async () => {
+ const error = await thrown(
+ handleError(
+ refusal("THIRD_PARTY_REGION_UNAVAILABLE", { key_region: null, deployment_region: "us" }),
+ ),
+ );
+
+ expect(error).toMatchObject({ keyRegion: undefined, deploymentRegion: "us" });
+ });
+
+ it("drops regions that are not strings", async () => {
+ const error = await thrown(
+ handleError(
+ refusal("THIRD_PARTY_REGION_UNAVAILABLE", { key_region: 7, deployment_region: ["us"] }),
+ ),
+ );
+
+ expect(error).toMatchObject({ keyRegion: undefined, deploymentRegion: undefined });
+ });
+
+ it("identifies a relay refusal in the OpenAI envelope by X-SIE-Error-Code", async () => {
+ const response = new Response(
+ JSON.stringify({
+ error: { message: "refused", type: "invalid_request_error", code: "permission_denied" },
+ }),
+ {
+ status: 403,
+ headers: {
+ "Content-Type": "application/json",
+ "X-SIE-Error-Code": "THIRD_PARTY_SERVING_DISABLED",
+ "X-SIE-Request-ID": "req-relay-1",
+ },
+ },
+ );
+
+ const error = await thrown(handleError(response));
+
+ expect(error).toBeInstanceOf(RelayUnavailableError);
+ expect(error).toMatchObject({
+ code: "THIRD_PARTY_SERVING_DISABLED",
+ message: "refused",
+ requestId: "req-relay-1",
+ request: { id: "req-relay-1" },
+ });
+ });
+
+ it.each([
+ [403, "INVALID_KEY"],
+ [403, "ACCOUNT_SUSPENDED"],
+ [400, "THIRD_PARTY_SERVING_DISABLED"],
+ ] as const)("leaves %s %s alone", async (status, code) => {
+ const error = await thrown(handleError(refusal(code, {}, status)));
+
+ expect(error).toBeInstanceOf(RequestError);
+ expect(error).not.toBeInstanceOf(RelayUnavailableError);
+ expect(error instanceof AccountInactiveError).toBe(code === "ACCOUNT_SUSPENDED");
+ });
+});
+
+describe("the client throws a relay refusal on the first response", () => {
+ beforeEach(() => mockFetch.mockReset());
+ afterEach(() => vi.clearAllMocks());
+
+ it.each(RELAY_CODES)("encode: %s", async (code) => {
+ const client = new SIEClient("http://localhost:8080");
+ mockFetch
+ .mockResolvedValueOnce(refusal(code, { deployment_region: "us" }))
+ .mockResolvedValueOnce(encodeSuccess());
+
+ const error = await thrown(client.encode("bge-m3", { text: "hi" }));
+
+ expect(error).toBeInstanceOf(RelayUnavailableError);
+ expect(error).toMatchObject({ code, deploymentRegion: "us" });
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ await client.close();
+ });
+
+ it.each(RELAY_CODES)("generate: %s", async (code) => {
+ const client = new SIEClient("http://localhost:8080");
+ mockFetch.mockResolvedValue(refusal(code, { key_region: "eu", deployment_region: "us" }));
+
+ const error = await thrown(client.generate("m", "hi", { maxNewTokens: 4 }));
+
+ expect(error).toBeInstanceOf(RelayUnavailableError);
+ expect(error).toMatchObject({ code, keyRegion: "eu", deploymentRegion: "us" });
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ await client.close();
+ });
+});
diff --git a/packages/sie_ts_sdk/tests/remoteServing.test.ts b/packages/sie_ts_sdk/tests/remoteServing.test.ts
index f1c98f724..98d513f8b 100644
--- a/packages/sie_ts_sdk/tests/remoteServing.test.ts
+++ b/packages/sie_ts_sdk/tests/remoteServing.test.ts
@@ -10,6 +10,8 @@ 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 { ModelLoadFailedError, RequestError, ServerError } from "../src/errors.js";
+import { handleError } from "../src/internal/parsing.js";
import { packMessage } from "../src/msgpack.js";
import {
FALLBACK_ERROR_PATTERN,
@@ -77,6 +79,15 @@ async function call(client: SIEClient, operation: Operation): Promise<RequestMet
.request;
}
+async function rejection(promise: Promise<unknown>): Promise<unknown> {
+ return promise.then(
+ () => {
+ throw new Error("expected a rejection");
+ },
+ (error: unknown) => error,
+ );
+}
+
function sentHeaders(): Record<string, string> {
return mockFetch.mock.calls[0]?.[1]?.headers as Record<string, string>;
}
@@ -144,6 +155,101 @@ describe("remote serving", () => {
expect(() => new SIEClient("http://localhost:8080", options)).toThrow(TypeError);
});
+ it("a local refusal after a failed remote attempt carries both outcomes on the error", async () => {
+ const response = new Response(
+ JSON.stringify({
+ detail: { code: "MODEL_LOADING", message: "Model 'm' is loading, please retry" },
+ }),
+ {
+ status: 503,
+ headers: {
+ "Content-Type": "application/json",
+ "Retry-After": "5",
+ [header.fallback_reason.name]: "model_loading",
+ [header.fallback_error.name]: "INFERENCE_ERROR",
+ },
+ },
+ );
+
+ const error = await rejection(handleError(response));
+
+ expect(error).toBeInstanceOf(ServerError);
+ expect((error as ServerError).request).toEqual({
+ fallbackReason: "model_loading",
+ fallbackError: "INFERENCE_ERROR",
+ });
+ });
+
+ it.each(OPERATIONS)(
+ "a restored refusal to %s exposes which side answered on the thrown error",
+ async (operation) => {
+ mockFetch.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ detail: { code: "MODEL_LOAD_FAILED", message: "load failed", permanent: true },
+ }),
+ {
+ status: 502,
+ headers: {
+ "Content-Type": "application/json",
+ "X-SIE-Request-ID": "req-restored",
+ [header.served_by.name]: "local",
+ [header.fallback_reason.name]: "unhealthy",
+ [header.fallback_error.name]: "INFERENCE_ERROR",
+ },
+ },
+ ),
+ );
+ const client = new SIEClient("http://localhost:8080");
+
+ const error = await rejection(call(client, operation));
+
+ expect(error).toBeInstanceOf(ModelLoadFailedError);
+ expect((error as ModelLoadFailedError).requestId).toBe("req-restored");
+ expect((error as ModelLoadFailedError).request).toEqual({
+ id: "req-restored",
+ servedBy: "local",
+ fallbackReason: "unhealthy",
+ fallbackError: "INFERENCE_ERROR",
+ });
+ },
+ );
+
+ it("a terminal streaming answer exposes which side answered on the thrown error", async () => {
+ mockFetch.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({ error: { code: "GATEWAY_TIMEOUT", message: "result deadline" } }),
+ {
+ status: 504,
+ headers: {
+ "Content-Type": "application/json",
+ [header.served_by.name]: "remote",
+ [header.upstream.name]: "team-sie",
+ },
+ },
+ ),
+ );
+ const client = new SIEClient("http://localhost:8080");
+
+ const error = await rejection(client.streamGenerate("m", "hi", { maxNewTokens: 4 }).next());
+
+ expect(error).toBeInstanceOf(ServerError);
+ expect((error as ServerError).request).toEqual({ servedBy: "remote", upstream: "team-sie" });
+ });
+
+ it("an error without disclosure headers carries no request metadata", async () => {
+ const response = new Response(
+ JSON.stringify({ detail: { code: "INVALID_INPUT", message: "bad" } }),
+ { status: 400, headers: { "Content-Type": "application/json" } },
+ );
+
+ const error = await rejection(handleError(response));
+
+ expect(error).toBeInstanceOf(RequestError);
+ expect((error as RequestError).request).toBeUndefined();
+ expect((error as RequestError).requestId).toBeUndefined();
+ });
+
it.each([
[header.served_by.name, "elsewhere"],
[header.served_by.name, "Remote"],