Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(sdk): retry once more at the provisioning budget end and attach refusal metadata to capacity errors (#699)

Krisztian Gajdara796d332c947
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index 0898dc068..cdee60058 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -337,11 +337,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`. `RequestError`
-and `ServerError` also expose `.request`, the request metadata of the
+carry a server response expose `.code` and `.status_code`. `RequestError`,
+`ServerError`, `ProvisioningError`, `ModelLoadingError` and
+`LoraLoadingError` 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
+failed remote attempt. When a retry budget runs out, it describes the
+last refusal. Invalid client-side arguments (for example, a bad
`base_url_headers` value) raise ordinary Python exceptions such as
`ValueError`.
diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.py
index 4e599623e..2439bc9ce 100644
--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py
+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py
@@ -434,6 +434,16 @@ def resolve_timeouts(
return connect, read
+def attempt_timeout_cap(remaining: float) -> float:
+ """Seconds that cap the timeouts of one attempt.
+
+ Attempts are capped by the remaining provisioning budget. The final
+ attempt, made after a capacity wait that used up the budget, is not capped
+ and runs with the client's own timeouts.
+ """
+ return remaining if remaining > 0 else math.inf
+
+
# Pool settings
DEFAULT_LEASE_RENEWAL_INTERVAL_S = 60.0 # Renew lease every 60s (lease is 1200s)
@@ -443,7 +453,7 @@ LORA_LOADING_DEFAULT_DELAY_S = 1.0 # Default retry delay if no Retry-After head
LORA_LOADING_ERROR_CODE = "LORA_LOADING" # Error code from server
# Model loading retry settings
-MODEL_LOADING_MAX_RETRIES = 60 # Max retries (60 * 5s = 5 min, matches provision timeout)
+MODEL_LOADING_MAX_RETRIES = 60 # Max retries (60 * 5s = 5 min)
MODEL_LOADING_DEFAULT_DELAY_S = 5.0 # Default retry delay (model loads take longer than LoRA)
MODEL_LOADING_ERROR_CODE = "MODEL_LOADING" # Error code from server
PROVISIONING_ERROR_CODE = "PROVISIONING" # Gateway scale-from-zero / worker provisioning
@@ -1289,7 +1299,7 @@ def raise_if_model_load_failed(response: _HttpResponse, model: str | None = None
Used by the SDK retry loops to short-circuit *before* checking the
``MODEL_LOADING`` retry budget. The server returns this on the very
first request when it has a recorded terminal failure for the
- model, so the caller should fail fast instead of retrying for 5
+ model, so the caller should fail fast instead of retrying for 15
minutes.
Args:
@@ -1435,7 +1445,7 @@ def handle_error(response: _HttpResponse) -> NoReturn:
# Fallback dispatch — ``model`` is only attached by the helper-style
# short-circuit (``raise_if_input_too_long``) on the extract path.
if response.status_code == HTTP_SERVICE_UNAVAILABLE and code == PROVISIONING_ERROR_CODE:
- raise ProvisioningError(message, retry_after=get_retry_after(response), param=param)
+ raise ProvisioningError(message, retry_after=get_retry_after(response), param=param, request=request)
if response.status_code == HTTP_CLIENT_ERROR and code == INPUT_TOO_LONG_ERROR_CODE:
raise InputTooLongError(message, param=param, request=request)
# Rate limit (pass-2 audit B1). Retried on the admission ladder in the
@@ -1495,11 +1505,15 @@ def provisioning_retry_delay(
param = get_error_param(response)
if not wait_for_capacity:
msg = f"No capacity available for GPU '{gpu}'. Server is provisioning."
- raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after, param=param)
+ raise ProvisioningError(
+ msg, gpu=gpu, retry_after=retry_after, param=param, request=parse_request_metadata(response.headers)
+ )
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{gpu}'"
- raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after, param=param)
+ raise ProvisioningError(
+ msg, gpu=gpu, retry_after=retry_after, param=param, request=parse_request_metadata(response.headers)
+ )
remaining = timeout - elapsed
if retry_after is not None:
return min(retry_after, remaining)
@@ -1640,7 +1654,7 @@ def next_stream_retry_delay(
if code == MODEL_LOADING_ERROR_CODE:
if elapsed >= timeout:
msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
retry_after = get_retry_after(response)
delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)
return min(delay, timeout - elapsed), oom_retries
diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.py
index 8ae83ed15..9030f1ad9 100644
--- a/packages/sie_sdk/src/sie_sdk/client/async_.py
+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py
@@ -124,6 +124,7 @@ from ._shared import (
_coerce_token_count,
admission_retry_delay,
attach_request_metadata,
+ attempt_timeout_cap,
base_url_accepts_origin_credentials,
build_chat_body,
build_estimate_envelope,
@@ -625,13 +626,15 @@ class SIEAsyncClient:
def _attempt_timeout(self, remaining: float, read_timeout_s: float | None = None) -> aiohttp.ClientTimeout:
"""Timeouts for one attempt, capped by the remaining provision budget.
- An explicit per-call ``read_timeout_s`` is honoured as given.
+ An explicit per-call ``read_timeout_s`` is honoured as given. See
+ :func:`attempt_timeout_cap` for the final attempt.
"""
- read = read_timeout_s if read_timeout_s is not None else min(self._timeout, remaining)
+ cap = attempt_timeout_cap(remaining)
+ read = read_timeout_s if read_timeout_s is not None else min(self._timeout, cap)
return aiohttp.ClientTimeout(
total=max(remaining, read),
connect=read,
- sock_connect=min(self._connect_timeout, remaining),
+ sock_connect=min(self._connect_timeout, cap),
sock_read=read,
)
@@ -1417,6 +1420,7 @@ class SIEAsyncClient:
# Retry counter for server-side OOM (RESOURCE_EXHAUSTED).
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
# Retry loop for retryable provisioning/capacity responses.
while True:
@@ -1424,9 +1428,10 @@ class SIEAsyncClient:
# This ensures a single hanging request can't exceed the overall timeout
elapsed = time.monotonic() - start_time
remaining = timeout - elapsed
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
request_timeout = self._attempt_timeout(remaining)
try:
@@ -1504,6 +1509,7 @@ class SIEAsyncClient:
)
self._record_retry()
await asyncio.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == LORA_LOADING_ERROR_CODE:
@@ -1513,7 +1519,12 @@ class SIEAsyncClient:
# Extract lora from options for error message
lora_name = resolved_options.get("lora") if resolved_options else None
msg = f"LoRA loading timeout after {lora_retries} retries"
- raise LoraLoadingError(msg, lora=str(lora_name) if lora_name else None, model=model)
+ raise LoraLoadingError(
+ msg,
+ lora=str(lora_name) if lora_name else None,
+ model=model,
+ request=parse_request_metadata(response.headers),
+ )
# Wait and retry
retry_after = get_retry_after(response)
@@ -1533,7 +1544,7 @@ class SIEAsyncClient:
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
# Wait and retry, respecting remaining time
retry_after = get_retry_after(response)
@@ -1548,6 +1559,7 @@ class SIEAsyncClient:
)
self._record_retry()
await asyncio.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == RESOURCE_EXHAUSTED_ERROR_CODE:
@@ -1993,6 +2005,7 @@ class SIEAsyncClient:
# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
# Retry loop for retryable provisioning/capacity responses.
while True:
@@ -2000,9 +2013,10 @@ class SIEAsyncClient:
# This ensures a single hanging request can't exceed the overall timeout
elapsed = time.monotonic() - start_time
remaining = timeout - elapsed
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
request_timeout = self._attempt_timeout(remaining)
try:
@@ -2080,13 +2094,14 @@ class SIEAsyncClient:
)
self._record_retry()
await asyncio.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == MODEL_LOADING_ERROR_CODE:
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
retry_after = get_retry_after(response)
delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)
@@ -2100,6 +2115,7 @@ class SIEAsyncClient:
)
self._record_retry()
await asyncio.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == RESOURCE_EXHAUSTED_ERROR_CODE:
@@ -2239,13 +2255,15 @@ class SIEAsyncClient:
start_time = time.monotonic()
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
while True:
elapsed = time.monotonic() - start_time
remaining = timeout - elapsed
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
request_timeout = self._attempt_timeout(remaining, read_timeout_s)
try:
@@ -2304,6 +2322,7 @@ class SIEAsyncClient:
)
self._record_retry()
await asyncio.sleep(delay)
+ after_capacity_wait = True
continue
if error_code == MODEL_LOADING_ERROR_CODE:
@@ -2314,7 +2333,7 @@ class SIEAsyncClient:
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
retry_after = get_retry_after(response)
delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)
remaining = timeout - elapsed
@@ -2326,7 +2345,7 @@ class SIEAsyncClient:
f"Model loading retry delay ({delay:.1f}s) would exceed the "
f"provision timeout ({timeout:.1f}s, {elapsed:.1f}s elapsed) for '{model}'"
)
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
self._record_retry()
await asyncio.sleep(delay)
continue
@@ -2445,11 +2464,13 @@ class SIEAsyncClient:
start_time = time.monotonic()
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
while True:
remaining = timeout - (time.monotonic() - start_time)
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
try:
async with (
self._throttle(),
@@ -2499,6 +2520,7 @@ class SIEAsyncClient:
)
self._record_retry()
await asyncio.sleep(delay)
+ after_capacity_wait = True
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="Responses")
@@ -2595,11 +2617,13 @@ class SIEAsyncClient:
start_time = time.monotonic()
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
while True:
remaining = timeout - (time.monotonic() - start_time)
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
try:
async with (
self._throttle(),
@@ -2651,6 +2675,7 @@ class SIEAsyncClient:
)
self._record_retry()
await asyncio.sleep(delay)
+ after_capacity_wait = True
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="chat completion")
@@ -2853,11 +2878,13 @@ class SIEAsyncClient:
start_time = time.monotonic()
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
while True:
remaining = timeout - (time.monotonic() - start_time)
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
retry_delay: float | None = None
try:
async with (
@@ -2879,8 +2906,8 @@ class SIEAsyncClient:
# (per socket read), not total.
timeout=aiohttp.ClientTimeout(
total=None,
- connect=min(self._timeout, remaining),
- sock_connect=min(self._connect_timeout, remaining),
+ connect=min(self._timeout, attempt_timeout_cap(remaining)),
+ sock_connect=min(self._connect_timeout, attempt_timeout_cap(remaining)),
sock_read=self._timeout,
),
allow_redirects=False,
@@ -2987,6 +3014,7 @@ class SIEAsyncClient:
if retry_delay is not None:
self._record_retry()
await asyncio.sleep(retry_delay)
+ after_capacity_wait = True
# Use overload for proper type hints when single item vs list
@overload
@@ -3091,6 +3119,7 @@ class SIEAsyncClient:
# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
# Retry loop for retryable provisioning/capacity responses.
while True:
@@ -3098,9 +3127,10 @@ class SIEAsyncClient:
# This ensures a single hanging request can't exceed the overall timeout
elapsed = time.monotonic() - start_time
remaining = timeout - elapsed
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
request_timeout = self._attempt_timeout(remaining)
try:
@@ -3181,13 +3211,14 @@ class SIEAsyncClient:
)
self._record_retry()
await asyncio.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == MODEL_LOADING_ERROR_CODE:
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
retry_after = get_retry_after(response)
delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)
@@ -3201,6 +3232,7 @@ class SIEAsyncClient:
)
self._record_retry()
await asyncio.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == RESOURCE_EXHAUSTED_ERROR_CODE:
diff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.py
index c78e9e2a1..f5f2b2906 100644
--- a/packages/sie_sdk/src/sie_sdk/client/errors.py
+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py
@@ -83,6 +83,10 @@ class ProvisioningError(SIEError):
Attributes:
gpu: The GPU type that was requested.
retry_after: Suggested retry delay from server (if provided).
+ request: Request metadata of the refusal, when it carried any: for
+ example ``served_by``, ``fallback_reason`` and ``fallback_error``
+ on a local refusal that answers a failed remote attempt. When the
+ provisioning budget runs out, the metadata of the last refusal.
"""
def __init__(
@@ -92,11 +96,13 @@ class ProvisioningError(SIEError):
gpu: str | None = None,
retry_after: float | None = None,
param: str | None = None,
+ request: RequestMetadata | None = None,
) -> None:
super().__init__(message)
self.gpu = gpu
self.retry_after = retry_after
self.param = param
+ self.request = request
class PoolError(SIEError):
@@ -135,6 +141,8 @@ class LoraLoadingError(SIEError):
Attributes:
lora: The LoRA adapter that was requested.
model: The model the LoRA was requested for.
+ request: Request metadata of the last refusal, when it carried any
+ (see :class:`ProvisioningError`).
"""
def __init__(
@@ -143,10 +151,12 @@ class LoraLoadingError(SIEError):
*,
lora: str | None = None,
model: str | None = None,
+ request: RequestMetadata | None = None,
) -> None:
super().__init__(message)
self.lora = lora
self.model = model
+ self.request = request
class ModelLoadingError(SIEError):
@@ -158,6 +168,8 @@ class ModelLoadingError(SIEError):
Attributes:
model: The model that was requested.
+ request: Request metadata of the last refusal, when it carried any
+ (see :class:`ProvisioningError`).
"""
def __init__(
@@ -165,9 +177,11 @@ class ModelLoadingError(SIEError):
message: str,
*,
model: str | None = None,
+ request: RequestMetadata | None = None,
) -> None:
super().__init__(message)
self.model = model
+ self.request = request
class ModelLoadFailedError(ServerError):
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.py
index 4d4c8c4eb..1aac52475 100644
--- a/packages/sie_sdk/src/sie_sdk/client/sync.py
+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py
@@ -133,6 +133,7 @@ from ._shared import (
_coerce_token_count,
admission_retry_delay,
attach_request_metadata,
+ attempt_timeout_cap,
base_url_accepts_origin_credentials,
build_chat_body,
build_estimate_envelope,
@@ -636,10 +637,12 @@ class SIEClient:
def _attempt_timeout(self, remaining: float, read_timeout_s: float | None = None) -> httpx.Timeout:
"""Timeouts for one attempt, capped by the remaining provision budget.
- An explicit per-call ``read_timeout_s`` is honoured as given.
+ An explicit per-call ``read_timeout_s`` is honoured as given. See
+ :func:`attempt_timeout_cap` for the final attempt.
"""
- read = read_timeout_s if read_timeout_s is not None else min(self._timeout, remaining)
- return httpx.Timeout(read, connect=min(self._connect_timeout, remaining))
+ cap = attempt_timeout_cap(remaining)
+ read = read_timeout_s if read_timeout_s is not None else min(self._timeout, cap)
+ return httpx.Timeout(read, connect=min(self._connect_timeout, cap))
def _check_server_version(self, response: httpx.Response) -> None:
revision = response.headers.get(MODEL_REVISION_HEADER)
@@ -1415,6 +1418,7 @@ class SIEClient:
# backoff via ``compute_oom_backoff``.
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
# Retry loop for retryable provisioning/capacity responses.
while True:
@@ -1422,9 +1426,10 @@ class SIEClient:
# This ensures a single hanging request can't exceed the overall timeout
elapsed = time.monotonic() - start_time
remaining = timeout - elapsed
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
request_timeout = self._attempt_timeout(remaining)
try:
@@ -1481,7 +1486,7 @@ class SIEClient:
# Short-circuit terminal load failures BEFORE engaging the
# MODEL_LOADING retry budget. The server emits 502
# MODEL_LOAD_FAILED for permanent classes (gated repos,
- # missing deps) — retrying would waste 5 minutes on a
+ # missing deps) — retrying would waste 15 minutes on a
# known-bad configuration.
raise_if_model_load_failed(response, model=model)
@@ -1503,6 +1508,7 @@ class SIEClient:
)
self._record_retry()
time.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == LORA_LOADING_ERROR_CODE:
@@ -1512,7 +1518,12 @@ class SIEClient:
# Extract lora from options for error message
lora_name = resolved_options.get("lora") if resolved_options else None
msg = f"LoRA loading timeout after {lora_retries} retries"
- raise LoraLoadingError(msg, lora=str(lora_name) if lora_name else None, model=model)
+ raise LoraLoadingError(
+ msg,
+ lora=str(lora_name) if lora_name else None,
+ model=model,
+ request=parse_request_metadata(response.headers),
+ )
# Wait and retry
retry_after = get_retry_after(response)
@@ -1532,7 +1543,7 @@ class SIEClient:
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
# Wait and retry, respecting remaining time
retry_after = get_retry_after(response)
@@ -1547,6 +1558,7 @@ class SIEClient:
)
self._record_retry()
time.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == RESOURCE_EXHAUSTED_ERROR_CODE:
@@ -2088,7 +2100,7 @@ class SIEClient:
gpu: GPU type to wait for (e.g., "l4", "a100-80gb").
model: Optional model to use for warmup request. If provided, sends
a warmup encode request which may trigger model loading.
- timeout_s: Maximum time to wait for capacity. Default: 300s (5 min).
+ timeout_s: Maximum time to wait for capacity. Default: 900s (15 min).
poll_interval_s: How often to check capacity. Default: 5s.
Returns:
@@ -2272,6 +2284,7 @@ class SIEClient:
# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
# Retry loop for retryable provisioning/capacity responses.
while True:
@@ -2279,9 +2292,10 @@ class SIEClient:
# This ensures a single hanging request can't exceed the overall timeout
elapsed = time.monotonic() - start_time
remaining = timeout - elapsed
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
request_timeout = self._attempt_timeout(remaining)
try:
@@ -2356,6 +2370,7 @@ class SIEClient:
)
self._record_retry()
time.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == MODEL_LOADING_ERROR_CODE:
@@ -2363,7 +2378,7 @@ class SIEClient:
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
# Wait and retry, respecting remaining time
retry_after = get_retry_after(response)
@@ -2378,6 +2393,7 @@ class SIEClient:
)
self._record_retry()
time.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == RESOURCE_EXHAUSTED_ERROR_CODE:
@@ -2599,13 +2615,15 @@ class SIEClient:
start_time = time.monotonic()
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
while True:
elapsed = time.monotonic() - start_time
remaining = timeout - elapsed
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
request_timeout = self._attempt_timeout(remaining, read_timeout_s)
try:
@@ -2666,6 +2684,7 @@ class SIEClient:
)
self._record_retry()
time.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == MODEL_LOADING_ERROR_CODE:
@@ -2676,7 +2695,7 @@ class SIEClient:
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
retry_after = get_retry_after(response)
delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)
remaining = timeout - elapsed
@@ -2688,7 +2707,7 @@ class SIEClient:
f"Model loading retry delay ({delay:.1f}s) would exceed the "
f"provision timeout ({timeout:.1f}s, {elapsed:.1f}s elapsed) for '{model}'"
)
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
self._record_retry()
time.sleep(delay)
continue
@@ -2844,11 +2863,13 @@ class SIEClient:
start_time = time.monotonic()
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
while True:
remaining = timeout - (time.monotonic() - start_time)
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
try:
response = self._client.post(
"/v1/responses",
@@ -2892,6 +2913,7 @@ class SIEClient:
)
self._record_retry()
time.sleep(delay)
+ after_capacity_wait = True
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="Responses")
@@ -2989,11 +3011,13 @@ class SIEClient:
start_time = time.monotonic()
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
while True:
remaining = timeout - (time.monotonic() - start_time)
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
try:
response = self._client.post(
"/v1/chat/completions",
@@ -3039,6 +3063,7 @@ class SIEClient:
)
self._record_retry()
time.sleep(delay)
+ after_capacity_wait = True
self._check_server_version(response)
data = parse_terminal_json_object(response, owner="chat completion")
@@ -3253,11 +3278,13 @@ class SIEClient:
start_time = time.monotonic()
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
while True:
remaining = timeout - (time.monotonic() - start_time)
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
retry_delay: float | None = None
try:
with self._client.stream(
@@ -3364,6 +3391,7 @@ class SIEClient:
# Reached only on the non-200 pre-stream retry path.
if retry_delay is not None:
time.sleep(retry_delay)
+ after_capacity_wait = True
# Use overload for proper type hints when single item vs list
@overload
@@ -3558,6 +3586,7 @@ class SIEClient:
# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.
oom_retries = 0
connect_retries = 0
+ after_capacity_wait = False
# Retry loop for retryable provisioning/capacity responses.
while True:
@@ -3565,9 +3594,10 @@ class SIEClient:
# This ensures a single hanging request can't exceed the overall timeout
elapsed = time.monotonic() - start_time
remaining = timeout - elapsed
- if remaining <= 0:
+ if remaining <= 0 and not after_capacity_wait:
msg = f"Provision timeout ({timeout:.1f}s) exceeded before request could be sent"
raise ProvisioningError(msg, gpu=resolved_gpu)
+ after_capacity_wait = False
request_timeout = self._attempt_timeout(remaining)
try:
@@ -3645,6 +3675,7 @@ class SIEClient:
)
self._record_retry()
time.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == MODEL_LOADING_ERROR_CODE:
@@ -3652,7 +3683,7 @@ class SIEClient:
elapsed = time.monotonic() - start_time
if elapsed >= timeout:
msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"
- raise ModelLoadingError(msg, model=model)
+ raise ModelLoadingError(msg, model=model, request=parse_request_metadata(response.headers))
# Wait and retry, respecting remaining time
retry_after = get_retry_after(response)
@@ -3667,6 +3698,7 @@ class SIEClient:
)
self._record_retry()
time.sleep(actual_delay)
+ after_capacity_wait = True
continue
if error_code == RESOURCE_EXHAUSTED_ERROR_CODE:
diff --git a/packages/sie_sdk/tests/client/test_error_request_metadata.py b/packages/sie_sdk/tests/client/test_error_request_metadata.py
index 16104716f..16c0b6518 100644
--- a/packages/sie_sdk/tests/client/test_error_request_metadata.py
+++ b/packages/sie_sdk/tests/client/test_error_request_metadata.py
@@ -7,7 +7,14 @@ from unittest.mock import MagicMock
import httpx
import pytest
from sie_sdk.client._shared import get_retry_after, handle_error
-from sie_sdk.client.errors import AccountStateUnavailableError, RequestError, ServerError
+from sie_sdk.client.errors import (
+ AccountStateUnavailableError,
+ LoraLoadingError,
+ ModelLoadingError,
+ ProvisioningError,
+ RequestError,
+ ServerError,
+)
def _error_response(status_code: int, headers: dict[str, str]) -> MagicMock:
@@ -73,6 +80,50 @@ def test_error_constructor_positional_compatibility_and_missing_metadata() -> No
assert (server_error.code, server_error.status_code, server_error.request) == ("legacy_code", 500, None)
+def test_capacity_error_constructors_keep_their_arguments_and_default_to_no_metadata() -> None:
+ provisioning = ProvisioningError("no capacity", gpu="l4", retry_after=30.0, param="model")
+ model_loading = ModelLoadingError("loading", model="m")
+ lora_loading = LoraLoadingError("lora loading", lora="adapter", model="m")
+
+ assert (str(provisioning), provisioning.gpu, provisioning.retry_after, provisioning.param) == (
+ "no capacity",
+ "l4",
+ 30.0,
+ "model",
+ )
+ assert (str(model_loading), model_loading.model) == ("loading", "m")
+ assert (str(lora_loading), lora_loading.lora, lora_loading.model) == ("lora loading", "adapter", "m")
+ assert provisioning.request is None
+ assert model_loading.request is None
+ assert lora_loading.request is None
+
+
+def test_provisioning_refusal_retains_request_metadata() -> None:
+ response = httpx.Response(
+ 503,
+ headers={
+ "Retry-After": "60",
+ "X-SIE-Request-ID": "req-provisioning",
+ "X-SIE-Served-By": "local",
+ "X-SIE-Fallback-Reason": "provisioning",
+ "X-SIE-Fallback-Error": "QUEUE_FULL",
+ },
+ json={"error": {"code": "PROVISIONING", "message": "Capacity for model 'm' is starting."}},
+ )
+
+ with pytest.raises(ProvisioningError) as excinfo:
+ handle_error(response)
+
+ assert str(excinfo.value) == "Capacity for model 'm' is starting."
+ assert excinfo.value.retry_after == 60.0
+ assert excinfo.value.request == {
+ "id": "req-provisioning",
+ "served_by": "local",
+ "fallback_reason": "provisioning",
+ "fallback_error": "QUEUE_FULL",
+ }
+
+
@pytest.mark.parametrize("status_code", [500, 503, 504])
@pytest.mark.parametrize(
("hint", "expected"),
diff --git a/packages/sie_sdk/tests/client/test_provisioning.py b/packages/sie_sdk/tests/client/test_provisioning.py
index b06d675a2..f26c47366 100644
--- a/packages/sie_sdk/tests/client/test_provisioning.py
+++ b/packages/sie_sdk/tests/client/test_provisioning.py
@@ -1,10 +1,111 @@
+import asyncio
import json
+from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
+import aiohttp
+import httpx
import msgpack
import numpy as np
import pytest
-from sie_sdk import ServerError, SIEAsyncClient, SIEClient
+from sie_sdk import LoraLoadingError, ModelLoadingError, ProvisioningError, ServerError, SIEAsyncClient, SIEClient
+from sie_sdk.client._shared import (
+ DEFAULT_CONNECT_TIMEOUT_S,
+ DEFAULT_PROVISION_TIMEOUT_S,
+ DEFAULT_READ_TIMEOUT_S,
+ LORA_LOADING_MAX_RETRIES,
+)
+from sie_sdk.client.async_ import _AioResponse
+
+_REFUSAL_HEADERS = {
+ "X-SIE-Request-ID": "req-refused",
+ "X-SIE-Served-By": "local",
+ "X-SIE-Fallback-Reason": "provisioning",
+ "X-SIE-Fallback-Error": "QUEUE_FULL",
+}
+_REFUSAL_METADATA = {
+ "id": "req-refused",
+ "served_by": "local",
+ "fallback_reason": "provisioning",
+ "fallback_error": "QUEUE_FULL",
+}
+_CAPACITY_READY_AT_S = 700.0
+
+
+class _Clock:
+ """Monotonic clock that advances only when the client sleeps."""
+
+ def __init__(self) -> None:
+ self.now = 0.0
+ self.sleeps: list[float] = []
+
+ def monotonic(self) -> float:
+ return self.now
+
+ def sleep(self, seconds: float) -> None:
+ self.sleeps.append(seconds)
+ self.now += seconds
+
+
+class _ClockAsyncio:
+ """The ``asyncio`` module as the async client sees it, sleeping on the fake clock."""
+
+ def __init__(self, clock: _Clock) -> None:
+ self._clock = clock
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(asyncio, name)
+
+ async def sleep(self, seconds: float, result: Any = None) -> Any:
+ self._clock.sleep(seconds)
+ return result
+
+
+def clock(monkeypatch: pytest.MonkeyPatch) -> _Clock:
+ fake = _Clock()
+ monkeypatch.setattr("sie_sdk.client.sync.time", fake)
+ monkeypatch.setattr("sie_sdk.client.async_.time", fake)
+ monkeypatch.setattr("sie_sdk.client._shared.time", fake)
+ monkeypatch.setattr("sie_sdk.client.async_.asyncio", _ClockAsyncio(fake))
+ return fake
+
+
+def _refusal_body(code: str) -> dict[str, Any]:
+ return {"error": {"code": code, "message": "Capacity for model 'bge-m3' is starting."}}
+
+
+def _sync_refusal(code: str, retry_after: str = "900") -> MagicMock:
+ response = MagicMock()
+ response.status_code = 503
+ response.headers = {"content-type": "application/json", "Retry-After": retry_after, **_REFUSAL_HEADERS}
+ response.json.return_value = _refusal_body(code)
+ response.content = json.dumps(_refusal_body(code)).encode()
+ return response
+
+
+def _sync_encoded() -> MagicMock:
+ response = MagicMock()
+ response.status_code = 200
+ response.headers = {"content-type": "application/msgpack"}
+ response.content = msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True)
+ return response
+
+
+def _async_refusal(code: str, retry_after: str = "900") -> _AioResponse:
+ return _AioResponse(
+ 503,
+ json.dumps(_refusal_body(code)).encode(),
+ {"content-type": "application/json", "Retry-After": retry_after, **_REFUSAL_HEADERS},
+ )
+
+
+def _async_encoded() -> _AioResponse:
+ return _AioResponse(
+ 200,
+ msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True),
+ {"content-type": "application/msgpack"},
+ )
class TestProvisioningRetry:
@@ -367,3 +468,160 @@ class TestAsyncModelLoadingRetry:
assert "timeout" in str(exc_info.value).lower()
await client.close()
+
+
+class TestFinalAttemptAtBudgetEnd:
+ """A capacity wait that reaches the end of the budget is followed by one final attempt."""
+
+ @pytest.mark.parametrize("code", ["PROVISIONING", "MODEL_LOADING"])
+ def test_sync_capacity_ready_during_the_last_wait_is_used(self, clock: _Clock, code: str) -> None:
+ def post(*_args: object, **_kwargs: object) -> MagicMock:
+ return _sync_encoded() if clock.now >= _CAPACITY_READY_AT_S else _sync_refusal(code)
+
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(side_effect=post)
+ client = SIEClient("http://localhost:8080")
+
+ result = client.encode("bge-m3", {"text": "hello"})
+
+ assert "dense" in result
+ assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
+ assert mock_client.return_value.post.call_count == 2
+ assert client.last_retry_count == 1
+ final_attempt = mock_client.return_value.post.call_args
+ assert final_attempt.kwargs["timeout"] == httpx.Timeout(
+ DEFAULT_READ_TIMEOUT_S, connect=DEFAULT_CONNECT_TIMEOUT_S
+ )
+ client.close()
+
+ @pytest.mark.parametrize("code", ["PROVISIONING", "MODEL_LOADING"])
+ async def test_async_capacity_ready_during_the_last_wait_is_used(self, clock: _Clock, code: str) -> None:
+ async def post(*_args: object, **_kwargs: object) -> _AioResponse:
+ return _async_encoded() if clock.now >= _CAPACITY_READY_AT_S else _async_refusal(code)
+
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(side_effect=post) # type: ignore[method-assign]
+
+ result = await client.encode("bge-m3", {"text": "hello"})
+
+ assert "dense" in result
+ assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
+ assert client._post.call_count == 2
+ assert client.last_retry_count == 1
+ assert client._post.call_args.kwargs["client_timeout"] == aiohttp.ClientTimeout(
+ total=DEFAULT_READ_TIMEOUT_S,
+ connect=DEFAULT_READ_TIMEOUT_S,
+ sock_connect=DEFAULT_CONNECT_TIMEOUT_S,
+ sock_read=DEFAULT_READ_TIMEOUT_S,
+ )
+ await client.close()
+
+ def test_sync_final_attempt_still_provisioning_raises_provisioning_error(self, clock: _Clock) -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(side_effect=lambda *_a, **_k: _sync_refusal("PROVISIONING"))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(ProvisioningError) as excinfo:
+ client.encode("bge-m3", {"text": "hello"}, gpu="l4")
+
+ assert mock_client.return_value.post.call_count == 2
+ client.close()
+
+ assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
+ error = excinfo.value
+ assert str(error) == "Provisioning timeout after 900.0s waiting for GPU 'l4'"
+ assert (error.gpu, error.retry_after, error.request) == ("l4", 900.0, _REFUSAL_METADATA)
+
+ async def test_async_final_attempt_still_provisioning_raises_provisioning_error(self, clock: _Clock) -> None:
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(side_effect=lambda *_a, **_k: _async_refusal("PROVISIONING")) # type: ignore[method-assign]
+
+ with pytest.raises(ProvisioningError) as excinfo:
+ await client.encode("bge-m3", {"text": "hello"}, gpu="l4")
+
+ assert client._post.call_count == 2
+ assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
+ error = excinfo.value
+ assert str(error) == "Provisioning timeout after 900.0s waiting for GPU 'l4'"
+ assert (error.gpu, error.retry_after, error.request) == ("l4", 900.0, _REFUSAL_METADATA)
+ await client.close()
+
+ def test_sync_final_attempt_still_loading_raises_model_loading_error(self, clock: _Clock) -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(side_effect=lambda *_a, **_k: _sync_refusal("MODEL_LOADING"))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(ModelLoadingError) as excinfo:
+ client.encode("bge-m3", {"text": "hello"})
+
+ assert mock_client.return_value.post.call_count == 2
+ client.close()
+
+ assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
+ assert (excinfo.value.model, excinfo.value.request) == ("bge-m3", _REFUSAL_METADATA)
+
+ async def test_async_final_attempt_still_loading_raises_model_loading_error(self, clock: _Clock) -> None:
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(side_effect=lambda *_a, **_k: _async_refusal("MODEL_LOADING")) # type: ignore[method-assign]
+
+ with pytest.raises(ModelLoadingError) as excinfo:
+ await client.encode("bge-m3", {"text": "hello"})
+
+ assert client._post.call_count == 2
+ assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
+ assert (excinfo.value.model, excinfo.value.request) == ("bge-m3", _REFUSAL_METADATA)
+ await client.close()
+
+
+class TestRefusalRequestMetadata:
+ """Provisioning, model-loading and LoRA-loading errors carry the refusal's request metadata."""
+
+ def test_sync_provisioning_without_waiting(self) -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_sync_refusal("PROVISIONING", retry_after="30"))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(ProvisioningError) as excinfo:
+ client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=False)
+
+ assert mock_client.return_value.post.call_count == 1
+ client.close()
+
+ assert (excinfo.value.retry_after, excinfo.value.request) == (30.0, _REFUSAL_METADATA)
+
+ async def test_async_provisioning_without_waiting(self) -> None:
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(return_value=_async_refusal("PROVISIONING", retry_after="30")) # type: ignore[method-assign]
+
+ with pytest.raises(ProvisioningError) as excinfo:
+ await client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=False)
+
+ assert client._post.call_count == 1
+ assert (excinfo.value.retry_after, excinfo.value.request) == (30.0, _REFUSAL_METADATA)
+ await client.close()
+
+ def test_sync_lora_loading_retries_exhausted(self, clock: _Clock) -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(side_effect=lambda *_a, **_k: _sync_refusal("LORA_LOADING", "1"))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(LoraLoadingError) as excinfo:
+ client.encode("bge-m3", {"text": "hello"}, options={"lora": "adapter-a"})
+
+ assert mock_client.return_value.post.call_count == LORA_LOADING_MAX_RETRIES + 1
+ client.close()
+
+ error = excinfo.value
+ assert (error.lora, error.model, error.request) == ("adapter-a", "bge-m3", _REFUSAL_METADATA)
+
+ async def test_async_lora_loading_retries_exhausted(self, clock: _Clock) -> None:
+ client = SIEAsyncClient("http://localhost:8080")
+ client._post = AsyncMock(side_effect=lambda *_a, **_k: _async_refusal("LORA_LOADING", "1")) # type: ignore[method-assign]
+
+ with pytest.raises(LoraLoadingError) as excinfo:
+ await client.encode("bge-m3", {"text": "hello"}, options={"lora": "adapter-a"})
+
+ assert client._post.call_count == LORA_LOADING_MAX_RETRIES + 1
+ error = excinfo.value
+ assert (error.lora, error.model, error.request) == ("adapter-a", "bge-m3", _REFUSAL_METADATA)
+ await client.close()
diff --git a/packages/sie_sdk/tests/client/test_retry_classification.py b/packages/sie_sdk/tests/client/test_retry_classification.py
index f63a5e89f..f94ecce08 100644
--- a/packages/sie_sdk/tests/client/test_retry_classification.py
+++ b/packages/sie_sdk/tests/client/test_retry_classification.py
@@ -24,11 +24,21 @@ import httpx
import msgpack
import numpy as np
import pytest
-from sie_sdk import IncompleteBatchError, SIEAsyncClient, SIEClient, SIEConnectionError, SIEError
+from sie_sdk import (
+ IncompleteBatchError,
+ ModelLoadingError,
+ ProvisioningError,
+ SIEAsyncClient,
+ SIEClient,
+ SIEConnectionError,
+ SIEError,
+)
+from sie_sdk.client import _shared as shared_module
from sie_sdk.client import async_ as async_module
from sie_sdk.client import sync as sync_module
from sie_sdk.client._shared import (
DEFAULT_CONNECT_TIMEOUT_S,
+ DEFAULT_PROVISION_TIMEOUT_S,
DEFAULT_READ_TIMEOUT_S,
get_retry_after,
resolve_timeouts,
@@ -154,7 +164,17 @@ def _json_ok(operation: str) -> _Reply:
def _success(operation: str) -> _Reply:
- return _encode_ok() if operation == "encode" else _json_ok(operation)
+ if operation == "encode":
+ return _encode_ok()
+ if operation == "score":
+ scores = {"model": "m", "scores": [{"item_id": "a", "score": 0.5, "rank": 0}]}
+ return _Reply(200, msgpack.packb(scores, use_bin_type=True), dict(_MSGPACK_HEADERS))
+ if operation == "extract":
+ extracted = {"model": "m", "items": [{"id": "a", "entities": []}]}
+ return _Reply(200, msgpack.packb(extracted, use_bin_type=True), dict(_MSGPACK_HEADERS))
+ if operation == "stream_generate":
+ return _sse_reply()
+ return _json_ok(operation)
def _fixture_reply(case: dict[str, Any]) -> _Reply:
@@ -168,20 +188,32 @@ def _operation_class(operation: str) -> str:
def _call_sync(client: SIEClient, operation: str, **kwargs: Any) -> Any:
if operation == "encode":
return client.encode("m", {"id": "a", "text": "hi"}, **kwargs)
+ if operation == "score":
+ return client.score("m", {"text": "q"}, [{"id": "a", "text": "hi"}], **kwargs)
+ if operation == "extract":
+ return client.extract("m", {"id": "a", "text": "hi"}, labels=["person"], **kwargs)
if operation == "generate":
return client.generate("m", "hi", max_new_tokens=4, **kwargs)
if operation == "responses":
return client.responses("m", "hi", **kwargs)
+ if operation == "stream_generate":
+ return list(client.stream_generate("m", "hi", max_new_tokens=4, **kwargs))
return client.chat_completions("m", [{"role": "user", "content": "hi"}], **kwargs)
async def _call_async(client: SIEAsyncClient, operation: str, **kwargs: Any) -> Any:
if operation == "encode":
return await client.encode("m", {"id": "a", "text": "hi"}, **kwargs)
+ if operation == "score":
+ return await client.score("m", {"text": "q"}, [{"id": "a", "text": "hi"}], **kwargs)
+ if operation == "extract":
+ return await client.extract("m", {"id": "a", "text": "hi"}, labels=["person"], **kwargs)
if operation == "generate":
return await client.generate("m", "hi", max_new_tokens=4, **kwargs)
if operation == "responses":
return await client.responses("m", "hi", **kwargs)
+ if operation == "stream_generate":
+ return [chunk async for chunk in client.stream_generate("m", "hi", max_new_tokens=4, **kwargs)]
return await client.chat_completions("m", [{"role": "user", "content": "hi"}], **kwargs)
@@ -435,3 +467,126 @@ async def test_async_stream_retries_queue_backpressure_before_opening(stub: _Stu
assert client.last_retry_count == 1
assert [chunk["text_delta"] for chunk in chunks] == ["ok"]
assert len(stub.paths) == 2
+
+
+class _BudgetClock:
+ """Monotonic clock that advances only when a client sleeps."""
+
+ def __init__(self) -> None:
+ self.now = 0.0
+
+ def monotonic(self) -> float:
+ return self.now
+
+ def sleep(self, seconds: float) -> None:
+ self.now += seconds
+
+
+class _BudgetClockAsyncio:
+ def __init__(self, clock: _BudgetClock) -> None:
+ self._clock = clock
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(asyncio, name)
+
+ async def sleep(self, seconds: float, result: Any = None) -> Any:
+ self._clock.sleep(seconds)
+ return result
+
+
+def budget_clock(monkeypatch: pytest.MonkeyPatch) -> _BudgetClock:
+ clock = _BudgetClock()
+ monkeypatch.setattr(sync_module, "time", clock)
+ monkeypatch.setattr(async_module, "time", clock)
+ monkeypatch.setattr(shared_module, "time", clock)
+ monkeypatch.setattr(async_module, "asyncio", _BudgetClockAsyncio(clock))
+ return clock
+
+
+_REFUSAL_HEADERS = {
+ "Retry-After": "900",
+ "X-SIE-Request-ID": "req-final",
+ "X-SIE-Served-By": "local",
+ "X-SIE-Fallback-Reason": "provisioning",
+ "X-SIE-Fallback-Error": "QUEUE_FULL",
+}
+_REFUSAL_METADATA = {
+ "id": "req-final",
+ "served_by": "local",
+ "fallback_reason": "provisioning",
+ "fallback_error": "QUEUE_FULL",
+}
+_CAPACITY_WAIT_CASES = [
+ (operation, code)
+ for operation in ("encode", "score", "extract", "generate", "chat_completions", "responses", "stream_generate")
+ for code in ("PROVISIONING", "MODEL_LOADING")
+ # generate() raises ModelLoadingError instead of waiting when Retry-After reaches the budget end.
+ if (operation, code) != ("generate", "MODEL_LOADING")
+]
+
+
+def _capacity_refusal(code: str) -> _Reply:
+ body = {"detail": {"code": code, "message": "Capacity for model 'm' is starting."}}
+ return _Reply(503, json.dumps(body).encode(), {**_JSON_HEADERS, **_REFUSAL_HEADERS})
+
+
+def _assert_final_refusal(error: SIEError, code: str) -> None:
+ assert isinstance(error, ProvisioningError if code == "PROVISIONING" else ModelLoadingError)
+ assert error.request == _REFUSAL_METADATA
+
+
[email protected](("operation", "code"), _CAPACITY_WAIT_CASES)
+def test_sync_final_attempt_follows_the_wait_that_ends_the_budget(
+ stub: _StubServer, budget_clock: _BudgetClock, operation: str, code: str
+) -> None:
+ stub.replies = [_capacity_refusal(code), _success(operation)]
+ client = SIEClient(stub.url)
+ try:
+ _call_sync(client, operation)
+ assert client.last_retry_count == 1
+ finally:
+ client.close()
+ assert len(stub.paths) == 2
+ assert budget_clock.now == DEFAULT_PROVISION_TIMEOUT_S
+
+
[email protected](("operation", "code"), _CAPACITY_WAIT_CASES)
+async def test_async_final_attempt_follows_the_wait_that_ends_the_budget(
+ stub: _StubServer, budget_clock: _BudgetClock, operation: str, code: str
+) -> None:
+ stub.replies = [_capacity_refusal(code), _success(operation)]
+ async with SIEAsyncClient(stub.url) as client:
+ await _call_async(client, operation)
+ assert client.last_retry_count == 1
+ assert len(stub.paths) == 2
+ assert budget_clock.now == DEFAULT_PROVISION_TIMEOUT_S
+
+
[email protected](("operation", "code"), _CAPACITY_WAIT_CASES)
+def test_sync_refusal_of_the_final_attempt_is_raised_with_its_metadata(
+ stub: _StubServer, budget_clock: _BudgetClock, operation: str, code: str
+) -> None:
+ stub.replies = [_capacity_refusal(code)]
+ client = SIEClient(stub.url)
+ try:
+ with pytest.raises(SIEError) as excinfo:
+ _call_sync(client, operation)
+ finally:
+ client.close()
+ _assert_final_refusal(excinfo.value, code)
+ assert len(stub.paths) == 2
+ assert budget_clock.now == DEFAULT_PROVISION_TIMEOUT_S
+
+
[email protected](("operation", "code"), _CAPACITY_WAIT_CASES)
+async def test_async_refusal_of_the_final_attempt_is_raised_with_its_metadata(
+ stub: _StubServer, budget_clock: _BudgetClock, operation: str, code: str
+) -> None:
+ stub.replies = [_capacity_refusal(code)]
+ async with SIEAsyncClient(stub.url) as client:
+ with pytest.raises(SIEError) as excinfo:
+ await _call_async(client, operation)
+ _assert_final_refusal(excinfo.value, code)
+ assert len(stub.paths) == 2
+ assert budget_clock.now == DEFAULT_PROVISION_TIMEOUT_S
diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.md
index 2a40abfea..84875bc93 100644
--- a/packages/sie_ts_sdk/README.md
+++ b/packages/sie_ts_sdk/README.md
@@ -131,11 +131,13 @@ 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. `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.
+one in the response — check it before using it. `RequestError`,
+`ServerError`, `ProvisioningError`, `ModelLoadingError` and
+`LoraLoadingError` 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. When a retry budget runs out, it describes the
+last refusal.
```typescript
import {
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index e0934d645..aa3db0c86 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -1131,7 +1131,7 @@ export class SIEClient {
itemsArray,
model,
"encode",
- response.headers.get("x-sie-request-id") ?? undefined,
+ parseRequestMetadata(response.headers),
);
if (isSingleItem) {
@@ -1844,6 +1844,7 @@ export class SIEClient {
gpu,
getRetryAfter(attemptResponse),
await getErrorParam(attemptResponse.clone()),
+ parseRequestMetadata(attemptResponse.headers),
);
}
const elapsed = Date.now() - startTime;
@@ -1853,6 +1854,7 @@ export class SIEClient {
gpu,
getRetryAfter(attemptResponse),
await getErrorParam(attemptResponse.clone()),
+ parseRequestMetadata(attemptResponse.headers),
);
}
const retryAfter = getRetryAfter(attemptResponse);
@@ -1877,6 +1879,7 @@ export class SIEClient {
`Model loading timeout for '${model}'`,
model,
await getErrorParam(attemptResponse.clone()),
+ parseRequestMetadata(attemptResponse.headers),
);
}
const delay = getRetryAfter(attemptResponse) ?? MODEL_LOADING_DEFAULT_DELAY;
@@ -2138,7 +2141,7 @@ export class SIEClient {
itemsArray,
model,
"extract",
- response.headers.get("x-sie-request-id") ?? undefined,
+ parseRequestMetadata(response.headers),
);
if (isSingleItem) {
@@ -2710,6 +2713,7 @@ export class SIEClient {
gpu,
retryAfter,
await getErrorParam(response.clone()),
+ parseRequestMetadata(response.headers),
);
}
@@ -2720,6 +2724,7 @@ export class SIEClient {
gpu,
retryAfter,
await getErrorParam(response.clone()),
+ parseRequestMetadata(response.headers),
);
}
@@ -2739,6 +2744,7 @@ export class SIEClient {
undefined, // We don't have lora name at this level
model,
await getErrorParam(response.clone()),
+ parseRequestMetadata(response.headers),
);
}
@@ -2757,6 +2763,7 @@ export class SIEClient {
`Model loading timeout after ${(elapsed / 1000).toFixed(1)}s for '${model}'`,
model,
await getErrorParam(response.clone()),
+ parseRequestMetadata(response.headers),
);
}
@@ -2782,6 +2789,7 @@ export class SIEClient {
provisionTimeoutMs: this.provisionTimeout,
model,
param: await getErrorParam(response.clone()),
+ request: parseRequestMetadata(response.headers),
});
oomRetries += 1;
await sleep(delay);
diff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.ts
index 46b5e2961..2729227e9 100644
--- a/packages/sie_ts_sdk/src/errors.ts
+++ b/packages/sie_ts_sdk/src/errors.ts
@@ -176,13 +176,28 @@ export class ProvisioningError extends SIEError {
readonly retryAfter: number | undefined;
/** Offending request field from the server error envelope, when known. */
readonly param: string | null | undefined;
+ /**
+ * Request metadata of the refusal, when it carried any: for example
+ * `servedBy`, `fallbackReason` and `fallbackError` on a local refusal that
+ * answers a failed remote attempt. When the provisioning budget runs out,
+ * the metadata of the last refusal. Mirrors the Python SDK's
+ * `ProvisioningError.request`.
+ */
+ readonly request: RequestMetadata | undefined;
- constructor(message: string, gpu?: string, retryAfter?: number, param?: string | null) {
+ constructor(
+ message: string,
+ gpu?: string,
+ retryAfter?: number,
+ param?: string | null,
+ request?: RequestMetadata,
+ ) {
super(message);
this.name = "ProvisioningError";
this.gpu = gpu;
this.retryAfter = retryAfter;
this.param = param;
+ this.request = request;
}
}
@@ -226,13 +241,22 @@ export class LoraLoadingError extends SIEError {
readonly model: string | undefined;
/** Offending request field from the server error envelope, when known. */
readonly param: string | null | undefined;
+ /** Request metadata of the last refusal, when it carried any (see {@link ProvisioningError}). */
+ readonly request: RequestMetadata | undefined;
- constructor(message: string, lora?: string, model?: string, param?: string | null) {
+ constructor(
+ message: string,
+ lora?: string,
+ model?: string,
+ param?: string | null,
+ request?: RequestMetadata,
+ ) {
super(message);
this.name = "LoraLoadingError";
this.lora = lora;
this.model = model;
this.param = param;
+ this.request = request;
}
}
@@ -251,12 +275,15 @@ export class ModelLoadingError extends SIEError {
readonly model: string | undefined;
/** Offending request field from the server error envelope, when known. */
readonly param: string | null | undefined;
+ /** Request metadata of the last refusal, when it carried any (see {@link ProvisioningError}). */
+ readonly request: RequestMetadata | undefined;
- constructor(message: string, model?: string, param?: string | null) {
+ constructor(message: string, model?: string, param?: string | null, request?: RequestMetadata) {
super(message);
this.name = "ModelLoadingError";
this.model = model;
this.param = param;
+ this.request = request;
}
}
diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.ts
index 7849c5c8b..65d920137 100644
--- a/packages/sie_ts_sdk/src/internal/parsing.ts
+++ b/packages/sie_ts_sdk/src/internal/parsing.ts
@@ -112,7 +112,7 @@ function parseNonnegativeMeterHeader(headers: Headers, name: string): number | u
* `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
+ * predates in-body surfacing. The two always agree when both are
* present; the body additionally names the rate book, which no header does.
*/
export function parseRequestMetadata(
@@ -192,7 +192,7 @@ export function parseRequestMetadata(
}
/**
- * The settled charge from a response envelope's `usage` block (#2434).
+ * The settled charge from a response envelope's `usage` block.
*
* Shares `settledChargeFields`' validation so the metadata path and the result
* parsers can never disagree about what counts as a publishable charge.
@@ -491,7 +491,7 @@ export async function handleError(response: Response, gpu?: string): Promise<nev
if (status === 503 && code === PROVISIONING_ERROR_CODE) {
const retryAfter = getRetryAfter(response);
- throw new ProvisioningError(message, gpu, retryAfter, param);
+ throw new ProvisioningError(message, gpu, retryAfter, param, request);
}
// Rate limit (pass-2 audit B1). Retried on the admission ladder in the
@@ -754,7 +754,7 @@ export function validateBatchResultCount(
submitted: readonly unknown[],
model: string,
operation: "encode" | "extract",
- requestId?: string,
+ request?: RequestMetadata,
): void {
if (results.length === submitted.length) {
return;
@@ -774,7 +774,7 @@ export function validateBatchResultCount(
code,
model,
missingIds,
- requestId,
+ request,
results,
});
}
diff --git a/packages/sie_ts_sdk/src/internal/provisioning.ts b/packages/sie_ts_sdk/src/internal/provisioning.ts
index 4c49231f1..cf459eb9a 100644
--- a/packages/sie_ts_sdk/src/internal/provisioning.ts
+++ b/packages/sie_ts_sdk/src/internal/provisioning.ts
@@ -282,6 +282,7 @@ export async function withProvisioningRetry(
opts.gpu,
getRetryAfter(response),
await getErrorParam(response.clone()),
+ parseRequestMetadata(response.headers),
);
}
const elapsed = Date.now() - startTime;
@@ -291,6 +292,7 @@ export async function withProvisioningRetry(
opts.gpu,
getRetryAfter(response),
await getErrorParam(response.clone()),
+ parseRequestMetadata(response.headers),
);
}
const retryAfter = getRetryAfter(response);
@@ -305,6 +307,7 @@ export async function withProvisioningRetry(
`Model loading timeout for '${opts.model}'`,
opts.model,
await getErrorParam(response.clone()),
+ parseRequestMetadata(response.headers),
);
}
const delay = getRetryAfter(response) ?? MODEL_LOADING_DEFAULT_DELAY;
diff --git a/packages/sie_ts_sdk/tests/capacityRefusals.test.ts b/packages/sie_ts_sdk/tests/capacityRefusals.test.ts
new file mode 100644
index 000000000..cfe446aef
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/capacityRefusals.test.ts
@@ -0,0 +1,235 @@
+/**
+ * Capacity refusals: the final attempt at the end of the provisioning budget,
+ * and the request metadata a refusal leaves on the thrown error.
+ *
+ * A `503` capacity refusal can be the local refusal that answers a failed
+ * remote attempt, and its `X-SIE-*` headers then say which side answered. The
+ * thrown error carries them as `request`; when the budget runs out, those of
+ * the last refusal. Mirrors the Python SDK's `test_provisioning.py`.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+import {
+ LoraLoadingError,
+ ModelLoadingError,
+ ProvisioningError,
+ ResourceExhaustedError,
+} from "../src/errors.js";
+import {
+ DEFAULT_PROVISION_TIMEOUT,
+ LORA_LOADING_MAX_RETRIES,
+ RESOURCE_EXHAUSTED_MAX_RETRIES,
+} from "../src/internal/constants.js";
+import { handleError } from "../src/internal/parsing.js";
+import { packMessage } from "../src/msgpack.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+const REFUSAL_HEADERS = {
+ "X-SIE-Request-ID": "req-refused",
+ "X-SIE-Served-By": "local",
+ "X-SIE-Fallback-Reason": "provisioning",
+ "X-SIE-Fallback-Error": "QUEUE_FULL",
+};
+const REFUSAL_METADATA = {
+ id: "req-refused",
+ servedBy: "local",
+ fallbackReason: "provisioning",
+ fallbackError: "QUEUE_FULL",
+};
+const CAPACITY_READY_AT_MS = 700_000;
+
+type Operation = "encode" | "generate" | "streamGenerate";
+const OPERATIONS: Operation[] = ["encode", "generate", "streamGenerate"];
+
+function refusal(code: string, retryAfter = "900"): Response {
+ return new Response(
+ JSON.stringify({ error: { code, message: "Capacity for model 'm' is starting." } }),
+ {
+ status: 503,
+ headers: {
+ "Content-Type": "application/json",
+ "Retry-After": retryAfter,
+ ...REFUSAL_HEADERS,
+ },
+ },
+ );
+}
+
+function success(operation: Operation): Response {
+ if (operation === "encode") {
+ return new Response(packMessage({ items: [{ dense: { values: new Float32Array([0.1]) } }] }), {
+ status: 200,
+ headers: { "Content-Type": "application/msgpack" },
+ });
+ }
+ if (operation === "generate") {
+ return new Response(JSON.stringify({ model: "m", text: "ok", finish_reason: "stop" }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+ const chunk = { request_id: "r", seq: 0, text_delta: "ok", done: true };
+ return new Response(`data: ${JSON.stringify(chunk)}\n\ndata: [DONE]\n\n`, {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ });
+}
+
+async function call(
+ client: SIEClient,
+ operation: Operation,
+ waitForCapacity?: boolean,
+): Promise<unknown> {
+ if (operation === "encode") return client.encode("m", { text: "hi" }, { waitForCapacity });
+ if (operation === "generate") {
+ return client.generate("m", "hi", { maxNewTokens: 4, waitForCapacity });
+ }
+ const chunks: unknown[] = [];
+ for await (const chunk of client.streamGenerate("m", "hi", {
+ maxNewTokens: 4,
+ waitForCapacity,
+ })) {
+ chunks.push(chunk);
+ }
+ return chunks;
+}
+
+function settle(promise: Promise<unknown>): Promise<{ error?: unknown }> {
+ return promise.then(
+ () => ({}),
+ (error: unknown) => ({ error }),
+ );
+}
+
+describe("the final attempt at the end of the provisioning budget", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it.each(OPERATIONS)(
+ "%s uses capacity that became ready during the last wait",
+ async (operation) => {
+ const start = Date.now();
+ mockFetch.mockImplementation(async () =>
+ Date.now() - start >= CAPACITY_READY_AT_MS ? success(operation) : refusal("PROVISIONING"),
+ );
+ const client = new SIEClient("http://localhost:8080");
+
+ const settled = settle(call(client, operation));
+ await vi.advanceTimersByTimeAsync(DEFAULT_PROVISION_TIMEOUT);
+
+ expect(await settled).toEqual({});
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ expect(Date.now() - start).toBe(DEFAULT_PROVISION_TIMEOUT);
+ },
+ );
+
+ it.each(
+ OPERATIONS.flatMap((operation) => [
+ { operation, code: "PROVISIONING", type: ProvisioningError },
+ { operation, code: "MODEL_LOADING", type: ModelLoadingError },
+ ]),
+ )(
+ "$operation throws the $code refusal of the final attempt with its metadata",
+ async ({ operation, code, type }) => {
+ mockFetch.mockImplementation(async () => refusal(code));
+ const client = new SIEClient("http://localhost:8080");
+
+ const settled = settle(call(client, operation));
+ await vi.advanceTimersByTimeAsync(DEFAULT_PROVISION_TIMEOUT);
+ const { error } = await settled;
+
+ expect(error).toBeInstanceOf(type);
+ expect((error as ProvisioningError | ModelLoadingError).request).toEqual(REFUSAL_METADATA);
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ },
+ );
+});
+
+describe("request metadata on capacity refusals", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it.each(OPERATIONS)("%s without waiting throws ProvisioningError with it", async (operation) => {
+ mockFetch.mockImplementation(async () => refusal("PROVISIONING", "30"));
+ const client = new SIEClient("http://localhost:8080");
+
+ const { error } = await settle(call(client, operation, false));
+
+ expect(error).toBeInstanceOf(ProvisioningError);
+ expect(error).toMatchObject({ retryAfter: 30_000, request: REFUSAL_METADATA });
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("handleError keeps it on a ProvisioningError", async () => {
+ const { error } = await settle(handleError(refusal("PROVISIONING", "60")));
+
+ expect(error).toBeInstanceOf(ProvisioningError);
+ expect(error).toMatchObject({ retryAfter: 60_000, request: REFUSAL_METADATA });
+ });
+
+ it("encode throws LoraLoadingError with the last refusal's", async () => {
+ mockFetch.mockImplementation(async () => refusal("LORA_LOADING", "1"));
+ const client = new SIEClient("http://localhost:8080");
+
+ const settled = settle(client.encode("m", { text: "hi" }));
+ await vi.advanceTimersByTimeAsync(LORA_LOADING_MAX_RETRIES * 1_000);
+ const { error } = await settled;
+
+ expect(error).toBeInstanceOf(LoraLoadingError);
+ expect((error as LoraLoadingError).request).toEqual(REFUSAL_METADATA);
+ expect(mockFetch).toHaveBeenCalledTimes(LORA_LOADING_MAX_RETRIES + 1);
+ });
+
+ it("encode throws ResourceExhaustedError with the last refusal's", async () => {
+ mockFetch.mockImplementation(async () => refusal("RESOURCE_EXHAUSTED", "1"));
+ const client = new SIEClient("http://localhost:8080");
+
+ const settled = settle(client.encode("m", { text: "hi" }));
+ await vi.advanceTimersByTimeAsync(60_000);
+ const { error } = await settled;
+
+ expect(error).toBeInstanceOf(ResourceExhaustedError);
+ expect((error as ResourceExhaustedError).request).toEqual(REFUSAL_METADATA);
+ expect(mockFetch).toHaveBeenCalledTimes(RESOURCE_EXHAUSTED_MAX_RETRIES + 1);
+ });
+});
+
+describe("capacity error constructors", () => {
+ it("keep their positional arguments and default to no request metadata", () => {
+ expect(new ProvisioningError("no capacity", "l4", 30_000, "model")).toMatchObject({
+ message: "no capacity",
+ gpu: "l4",
+ retryAfter: 30_000,
+ param: "model",
+ request: undefined,
+ });
+ expect(new ModelLoadingError("loading", "m", "model")).toMatchObject({
+ message: "loading",
+ model: "m",
+ param: "model",
+ request: undefined,
+ });
+ expect(new LoraLoadingError("lora loading", "adapter", "m", "model")).toMatchObject({
+ message: "lora loading",
+ lora: "adapter",
+ model: "m",
+ param: "model",
+ request: undefined,
+ });
+ });
+});
diff --git a/packages/sie_ts_sdk/tests/incompleteBatch.test.ts b/packages/sie_ts_sdk/tests/incompleteBatch.test.ts
index 698ebf41b..b750ff75a 100644
--- a/packages/sie_ts_sdk/tests/incompleteBatch.test.ts
+++ b/packages/sie_ts_sdk/tests/incompleteBatch.test.ts
@@ -95,6 +95,33 @@ describe("encode batch guard", () => {
}
});
+ it("carries the response's request metadata", async () => {
+ mockFetch.mockResolvedValueOnce(
+ msgpackResponse(
+ { items: [dense(0.1)] },
+ {
+ "x-sie-request-id": "req-drop",
+ "x-sie-served-by": "remote",
+ "x-sie-upstream": "team-sie",
+ "x-sie-fallback-reason": "saturated",
+ },
+ ),
+ );
+
+ const error = await client
+ .encode("bge-m3", [{ text: "ok" }, { text: "over-length" }])
+ .catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(IncompleteBatchError);
+ expect((error as IncompleteBatchError).request).toEqual({
+ id: "req-drop",
+ servedBy: "remote",
+ upstream: "team-sie",
+ fallbackReason: "saturated",
+ });
+ expect((error as IncompleteBatchError).requestId).toBe("req-drop");
+ });
+
it("names the dropped ids when every item carries one", async () => {
mockFetch.mockResolvedValueOnce(
msgpackResponse({
@@ -169,6 +196,26 @@ describe("extract batch guard", () => {
}
});
+ it("carries the response's request metadata", async () => {
+ mockFetch.mockResolvedValueOnce(
+ msgpackResponse(
+ { items: [{ entities: [] }] },
+ { "x-sie-request-id": "req-extract", "x-sie-served-by": "local" },
+ ),
+ );
+
+ const error = await client
+ .extract("gliner", [{ text: "Apple info" }, { text: "Tesla info" }], { labels: ["org"] })
+ .catch((caught: unknown) => caught);
+
+ expect(error).toBeInstanceOf(IncompleteBatchError);
+ expect((error as IncompleteBatchError).request).toEqual({
+ id: "req-extract",
+ servedBy: "local",
+ });
+ expect((error as IncompleteBatchError).requestId).toBe("req-extract");
+ });
+
it("passes through when the counts match", async () => {
mockFetch.mockResolvedValueOnce(
msgpackResponse({