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(server): answer an upstream that cannot serve yet with a retryable 503 (#494)

Krisztian Gajdarab0217b4dbf2
diff --git a/packages/sie_server/src/sie_server/adapters/errors.py b/packages/sie_server/src/sie_server/adapters/errors.py
index 145dc1e00..9015bbda5 100644
--- a/packages/sie_server/src/sie_server/adapters/errors.py
+++ b/packages/sie_server/src/sie_server/adapters/errors.py
@@ -1,2 +1,29 @@
+from typing import Literal
+
+UpstreamFailureKind = Literal["not_ready", "busy", "unavailable"]
+
+_KIND_TEXT: dict[UpstreamFailureKind, str] = {
+ "not_ready": "is not ready",
+ "busy": "is busy",
+ "unavailable": "is unavailable",
+}
+
+
class InputTooLongError(ValueError):
pass
+
+
+class UpstreamUnavailableError(RuntimeError):
+ """An upstream did not serve the request, and the same request may succeed later.
+
+ ``kind`` says why: the model is ``not_ready`` on the upstream, the upstream
+ is ``busy``, or it is ``unavailable``. ``retry_after_s`` is the wait to
+ suggest to the caller. The message is fixed text and never carries anything
+ the upstream sent.
+ """
+
+ def __init__(self, upstream: str, kind: UpstreamFailureKind, *, retry_after_s: int, reason: str) -> None:
+ super().__init__(f"upstream {upstream!r} {_KIND_TEXT[kind]}: {reason}")
+ self.upstream = upstream
+ self.kind: UpstreamFailureKind = kind
+ self.retry_after_s = retry_after_s
diff --git a/packages/sie_server/src/sie_server/adapters/remote/_http.py b/packages/sie_server/src/sie_server/adapters/remote/_http.py
new file mode 100644
index 000000000..f0baf4bc7
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/remote/_http.py
@@ -0,0 +1,242 @@
+"""HTTP rules shared by the remote adapters.
+
+The upstream is outside this deployment, so its answer is untrusted. A body is
+read uncompressed under a size cap and a deadline. A failed call becomes fixed
+text: the status, a known error code and ``Retry-After`` are read only to
+decide whether the same request may succeed later, and nothing else the
+upstream sent is kept.
+
+A failure the same request may survive raises :class:`UpstreamUnavailableError`:
+the model is not ready upstream (``MODEL_LOADING``, ``PROVISIONING``,
+``LORA_LOADING``), the upstream is busy (429, ``QUEUE_FULL``,
+``RESOURCE_EXHAUSTED``, ``BILLING_CAPACITY_UNAVAILABLE``, or
+``QUEUE_UNAVAILABLE`` with a ``Retry-After``), or it is unavailable (no
+connection, a timeout, a dropped response, another 5xx). A 501, a 505 and the
+codes ``MODEL_LOAD_FAILED``, ``ACCOUNT_STATE_UNAVAILABLE`` and
+``COLD_START_RATE_LIMITED`` are final. A refused input raises
+:class:`InputTooLongError` or :class:`InvalidInputError`. Everything else is a
+:class:`RemoteUpstreamError`.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import time
+from datetime import UTC, datetime
+from email.utils import parsedate_to_datetime
+
+import httpx
+from sie_sdk._msgpack import unpackb
+
+from sie_server.adapters.errors import InputTooLongError, UpstreamUnavailableError
+from sie_server.config.upstreams import UpstreamCredentialError
+from sie_server.core.upstream_client import UpstreamRedirectRefusedError
+from sie_server.types.inputs import InvalidInputError
+
+RETRY_AFTER_MIN_S = 1
+RETRY_AFTER_MAX_S = 60
+DEFAULT_RETRY_AFTER_S = 5
+_ERROR_BODY_MAX_BYTES = 64 << 10
+
+_NOT_READY_CODES = frozenset({"MODEL_LOADING", "PROVISIONING", "LORA_LOADING"})
+_BUSY_CODES = frozenset({"QUEUE_FULL", "RESOURCE_EXHAUSTED", "BILLING_CAPACITY_UNAVAILABLE"})
+_BUSY_WITH_RETRY_AFTER_CODES = frozenset({"QUEUE_UNAVAILABLE", "transport_failure"})
+_TERMINAL_CODES = frozenset({"MODEL_LOAD_FAILED", "ACCOUNT_STATE_UNAVAILABLE", "COLD_START_RATE_LIMITED"})
+_TERMINAL_SERVER_STATUSES = frozenset({501, 505})
+_KNOWN_ERROR_CODES = (
+ _NOT_READY_CODES
+ | _BUSY_CODES
+ | _BUSY_WITH_RETRY_AFTER_CODES
+ | _TERMINAL_CODES
+ | frozenset(
+ {
+ "ACCOUNT_PENDING_REVIEW",
+ "ACCOUNT_SUSPENDED",
+ "GATEWAY_TIMEOUT",
+ "INFERENCE_ERROR",
+ "INPUT_TOO_LONG",
+ "INSUFFICIENT_CREDITS",
+ "INTERNAL_ERROR",
+ "INVALID_INPUT",
+ "KEY_SPEND_LIMIT_EXCEEDED",
+ "MODEL_NOT_FOUND",
+ "MODEL_NOT_LOADED",
+ "RATE_LIMIT",
+ }
+ )
+)
+
+
+class RemoteUpstreamError(RuntimeError):
+ """The upstream call failed in a way a retry would not fix, or its answer broke the profile's contract."""
+
+
+def send_bounded(
+ client: httpx.Client,
+ request: httpx.Request,
+ *,
+ upstream: str,
+ max_bytes: int,
+ deadline_s: float,
+) -> bytes:
+ """Send ``request`` to ``upstream`` and return the body of a successful answer.
+
+ Raises :class:`UpstreamUnavailableError` when the same request may succeed
+ later, :class:`InputTooLongError` or :class:`InvalidInputError` when the
+ upstream refused the input, and :class:`RemoteUpstreamError` otherwise.
+ """
+ deadline = time.monotonic() + deadline_s
+ try:
+ response = client.send(request, stream=True)
+ except UpstreamCredentialError:
+ raise RemoteUpstreamError("the upstream credential is unavailable") from None
+ except httpx.HTTPError as exc:
+ raise failure_for_transport_error(exc, upstream=upstream) from None
+ try:
+ if response.status_code >= 400:
+ raise failure_for_status(
+ response.status_code,
+ upstream_error_code(response.headers, _read_error_body(response, deadline)),
+ parse_retry_after(response.headers.get("retry-after")),
+ upstream=upstream,
+ )
+ if _is_compressed(response):
+ raise RemoteUpstreamError("upstream sent a compressed body, which is refused")
+ return _read_body(response, upstream=upstream, max_bytes=max_bytes, deadline=deadline)
+ except httpx.HTTPError as exc:
+ raise failure_for_transport_error(exc, upstream=upstream) from None
+ finally:
+ response.close()
+
+
+def failure_for_status(status: int, code: str | None, retry_after_s: int | None, *, upstream: str) -> Exception:
+ """The failure an upstream error status amounts to, given its known error code and wait."""
+ answered = f"answered {status} {code}" if code else f"answered {status}"
+ wait = retry_after_s if retry_after_s is not None else DEFAULT_RETRY_AFTER_S
+ if code in _TERMINAL_CODES or status in _TERMINAL_SERVER_STATUSES:
+ return RemoteUpstreamError(f"upstream {answered}")
+ if status == 429:
+ return UpstreamUnavailableError(upstream, "busy", retry_after_s=wait, reason=answered)
+ if status >= 500:
+ if code in _NOT_READY_CODES:
+ return UpstreamUnavailableError(upstream, "not_ready", retry_after_s=wait, reason=answered)
+ if code in _BUSY_CODES or (code in _BUSY_WITH_RETRY_AFTER_CODES and retry_after_s is not None):
+ return UpstreamUnavailableError(upstream, "busy", retry_after_s=wait, reason=answered)
+ return UpstreamUnavailableError(upstream, "unavailable", retry_after_s=wait, reason=answered)
+ if code == "INPUT_TOO_LONG":
+ return InputTooLongError(f"the upstream refused the input as too long ({status} INPUT_TOO_LONG)")
+ if code == "INVALID_INPUT" and status in {400, 422}:
+ return InvalidInputError(f"the upstream refused the input ({status} INVALID_INPUT)")
+ return RemoteUpstreamError(f"upstream {answered}")
+
+
+def failure_for_transport_error(exc: httpx.HTTPError, *, upstream: str) -> Exception:
+ """The failure a client-side error amounts to: retryable unless the request itself was at fault."""
+ if isinstance(exc, UpstreamRedirectRefusedError):
+ return RemoteUpstreamError("upstream answered with a redirect, which is refused")
+ failed = f"request failed ({type(exc).__name__})"
+ if isinstance(exc, httpx.TransportError) and not isinstance(
+ exc, httpx.UnsupportedProtocol | httpx.LocalProtocolError
+ ):
+ return UpstreamUnavailableError(upstream, "unavailable", retry_after_s=DEFAULT_RETRY_AFTER_S, reason=failed)
+ return RemoteUpstreamError(f"upstream {failed}")
+
+
+def upstream_error_code(headers: httpx.Headers, body: bytes) -> str | None:
+ """The upstream's error code when it is one this server knows, else ``None``.
+
+ Read from ``X-SIE-Error-Code`` first, then from the ``error`` or ``detail``
+ object of a JSON or msgpack body, as the SDKs read it.
+ """
+ from_header = _known_code(headers.get("x-sie-error-code"))
+ if from_header is not None:
+ return from_header
+ if not body:
+ return None
+ try:
+ if "msgpack" in headers.get("content-type", "").lower():
+ decoded = unpackb(body, numeric_arrays=False)
+ else:
+ decoded = json.loads(body)
+ except Exception: # noqa: BLE001 - untrusted bytes; an unreadable body carries no code
+ return None
+ if not isinstance(decoded, dict):
+ return None
+ for key in ("error", "detail"):
+ envelope = decoded.get(key)
+ if isinstance(envelope, dict):
+ return _known_code(envelope.get("code"))
+ return None
+
+
+def parse_retry_after(value: str | None) -> int | None:
+ """Whole seconds to wait from a ``Retry-After`` value, clamped to the bounded range.
+
+ Accepts delay seconds or an HTTP date; a date in the past means the
+ shortest wait. ``None`` when the value is absent or unusable.
+ """
+ text = (value or "").strip()
+ if not text:
+ return None
+ try:
+ seconds: float | None = float(text)
+ except ValueError:
+ seconds = _seconds_until(text)
+ if seconds is None or not math.isfinite(seconds) or seconds < 0:
+ return None
+ return min(RETRY_AFTER_MAX_S, max(RETRY_AFTER_MIN_S, math.ceil(seconds)))
+
+
+def _seconds_until(http_date: str) -> float | None:
+ try:
+ when = parsedate_to_datetime(http_date)
+ except (TypeError, ValueError):
+ return None
+ if when.tzinfo is None:
+ when = when.replace(tzinfo=UTC)
+ return max(0.0, (when - datetime.now(UTC)).total_seconds())
+
+
+def _known_code(value: object) -> str | None:
+ if value == "provisioning":
+ return "PROVISIONING"
+ return value if isinstance(value, str) and value in _KNOWN_ERROR_CODES else None
+
+
+def _is_compressed(response: httpx.Response) -> bool:
+ return response.headers.get("content-encoding", "identity").strip().lower() not in {"", "identity"}
+
+
+def _read_body(response: httpx.Response, *, upstream: str, max_bytes: int, deadline: float) -> bytes:
+ chunks: list[bytes] = []
+ size = 0
+ for chunk in response.iter_raw():
+ size += len(chunk)
+ if size > max_bytes:
+ raise RemoteUpstreamError("upstream response exceeds the size limit")
+ if time.monotonic() > deadline:
+ raise UpstreamUnavailableError(
+ upstream,
+ "unavailable",
+ retry_after_s=DEFAULT_RETRY_AFTER_S,
+ reason="the response exceeded the deadline",
+ )
+ chunks.append(chunk)
+ return b"".join(chunks)
+
+
+def _read_error_body(response: httpx.Response, deadline: float) -> bytes:
+ if _is_compressed(response):
+ return b""
+ chunks: list[bytes] = []
+ size = 0
+ try:
+ for chunk in response.iter_raw():
+ size += len(chunk)
+ if size > _ERROR_BODY_MAX_BYTES or time.monotonic() > deadline:
+ return b""
+ chunks.append(chunk)
+ except httpx.HTTPError:
+ return b""
+ return b"".join(chunks)
diff --git a/packages/sie_server/src/sie_server/adapters/remote/sie.py b/packages/sie_server/src/sie_server/adapters/remote/sie.py
index e6f599c64..4bd8a524f 100644
--- a/packages/sie_server/src/sie_server/adapters/remote/sie.py
+++ b/packages/sie_server/src/sie_server/adapters/remote/sie.py
@@ -5,17 +5,18 @@ model id the upstream serves. ``encode`` forwards text items to the upstream's
``/v1/encode`` in the SDK's msgpack wire format and returns its dense vectors.
Loading makes no outbound call, holds no weights and uses no accelerator.
-The upstream is outside this deployment, so its answer is treated as untrusted:
-the body is read uncompressed under a size cap and a deadline, and a failure
-reaches the caller as fixed text, never as anything the upstream sent. No read
-waits longer than ``READ_TIMEOUT_S``, so a call takes at most the connect
-timeout plus ``REQUEST_DEADLINE_S`` plus one read timeout.
+The upstream is outside this deployment, so its answer is treated as untrusted
+by the rules in :mod:`sie_server.adapters.remote._http`: the body is read
+uncompressed under a size cap and a deadline, and a failure reaches the caller
+as fixed text, never as anything the upstream sent. A failure the same request
+may survive later, such as an upstream that is still loading the model, raises
+:class:`~sie_server.adapters.errors.UpstreamUnavailableError`. No read waits
+longer than ``READ_TIMEOUT_S``, so a call takes at most the connect timeout
+plus ``REQUEST_DEADLINE_S`` plus one read timeout.
"""
from __future__ import annotations
-import re
-import time
from typing import TYPE_CHECKING, Any, ClassVar
from urllib.parse import quote
@@ -27,7 +28,8 @@ from sie_sdk.client._shared import parse_encode_results
from sie_server.adapters._base_adapter import BaseAdapter
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED
-from sie_server.config.upstreams import UpstreamConfigError, UpstreamCredentialError, UpstreamKind, upstream_for_serving
+from sie_server.adapters.remote._http import RemoteUpstreamError, send_bounded
+from sie_server.config.upstreams import UpstreamConfigError, UpstreamKind, upstream_for_serving
from sie_server.core.inference_output import EncodeOutput
from sie_server.core.upstream_client import upstream_sync_client
@@ -41,11 +43,6 @@ _CONNECT_TIMEOUT_S = 5.0
_RESPONSE_OVERHEAD_BYTES = 1 << 20
_BYTES_PER_VALUE = 16
_UNKNOWN_DIM_RESPONSE_BYTES = 64 << 20
-_ERROR_CODE = re.compile(r"^[A-Z][A-Z0-9_]{0,63}$")
-
-
-class RemoteUpstreamError(RuntimeError):
- """The upstream call failed or did not return the vectors this profile promises."""
class SieUpstreamAdapter(BaseAdapter):
@@ -116,7 +113,13 @@ class SieUpstreamAdapter(BaseAdapter):
encode_prefix = self._client.base_url.raw_path.rstrip(b"/") + b"/v1/encode/"
if not request.url.raw_path.startswith(encode_prefix):
raise RemoteUpstreamError("the upstream model id does not form an encode path")
- body = self._send(self._client, request, max_bytes=self._max_response_bytes(len(items)))
+ body = send_bounded(
+ self._client,
+ request,
+ upstream=self._upstream_name,
+ max_bytes=self._max_response_bytes(len(items)),
+ deadline_s=REQUEST_DEADLINE_S,
+ )
try:
decoded = unpackb(body, numeric_arrays=True)
wire_items = decoded.get("items") if isinstance(decoded, dict) else None
@@ -145,34 +148,3 @@ class SieUpstreamAdapter(BaseAdapter):
if self._dense_dim is None:
return _UNKNOWN_DIM_RESPONSE_BYTES
return _RESPONSE_OVERHEAD_BYTES + item_count * self._dense_dim * _BYTES_PER_VALUE
-
- @staticmethod
- def _send(client: httpx.Client, request: httpx.Request, *, max_bytes: int) -> bytes:
- deadline = time.monotonic() + REQUEST_DEADLINE_S
- try:
- response = client.send(request, stream=True)
- except UpstreamCredentialError:
- raise RemoteUpstreamError("the upstream credential is unavailable") from None
- except httpx.HTTPError as exc:
- raise RemoteUpstreamError(f"upstream request failed ({type(exc).__name__})") from None
- try:
- if response.status_code >= 400:
- code = response.headers.get("x-sie-error-code", "")
- suffix = f" {code}" if _ERROR_CODE.fullmatch(code) else ""
- raise RemoteUpstreamError(f"upstream answered {response.status_code}{suffix}")
- if response.headers.get("content-encoding", "identity").strip().lower() not in {"", "identity"}:
- raise RemoteUpstreamError("upstream sent a compressed body, which is refused")
- chunks: list[bytes] = []
- size = 0
- for chunk in response.iter_raw():
- size += len(chunk)
- if size > max_bytes:
- raise RemoteUpstreamError("upstream response exceeds the size limit")
- if time.monotonic() > deadline:
- raise RemoteUpstreamError("upstream response exceeded the deadline")
- chunks.append(chunk)
- return b"".join(chunks)
- except httpx.HTTPError as exc:
- raise RemoteUpstreamError(f"upstream request failed ({type(exc).__name__})") from None
- finally:
- response.close()
diff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.py
index fdd0a3084..49c23f0a3 100644
--- a/packages/sie_server/src/sie_server/api/helpers.py
+++ b/packages/sie_server/src/sie_server/api/helpers.py
@@ -10,7 +10,7 @@ import msgspec
from fastapi import HTTPException, Request, status
from fastapi.responses import JSONResponse
-from sie_server.adapters.errors import InputTooLongError
+from sie_server.adapters.errors import InputTooLongError, UpstreamUnavailableError
from sie_server.api.serialization import MsgPackResponse, _convert_for_json
from sie_server.config.model import is_remote_adapter_path
from sie_server.core.model_suggestions import suggestion_suffix
@@ -123,6 +123,30 @@ def serving_disclosure_headers(registry: "ModelRegistry", model: str) -> dict[st
return {SERVED_BY_HEADER: "local"}
+def upstream_unavailable_exception(error: UpstreamUnavailableError, model: str) -> HTTPException:
+ """503 for a request its upstream did not serve, with the upstream's clamped ``Retry-After``.
+
+ A model that is not ready upstream answers ``MODEL_LOADING``; a busy or
+ unreachable upstream answers ``QUEUE_FULL``. The SDKs retry both. The
+ message is fixed text: nothing the upstream sent reaches the caller.
+ """
+ if error.kind == "not_ready":
+ code = ErrorCode.MODEL_LOADING
+ message = f"Model '{model}' is loading on its upstream, please retry"
+ else:
+ code = ErrorCode.QUEUE_FULL
+ message = f"The upstream serving model '{model}' is {error.kind}, please retry"
+ return HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail={"code": code.value, "message": message},
+ headers={
+ "Retry-After": str(error.retry_after_s),
+ SERVED_BY_HEADER: "remote",
+ UPSTREAM_HEADER: error.upstream,
+ },
+ )
+
+
def _get_server_version() -> str:
try:
return pkg_version("sie-server")
@@ -659,8 +683,10 @@ class InferenceErrorHandler:
OOM errors are mapped to 503 ``RESOURCE_EXHAUSTED`` with a
``Retry-After`` header so the SDK can auto-retry. A request the
worker drained on eviction never ran at all, so it maps to the
- existing retryable 503 ``MODEL_LOADING`` shape. Everything else
- keeps the legacy 500 ``INFERENCE_ERROR`` mapping.
+ existing retryable 503 ``MODEL_LOADING`` shape. A request a remote
+ profile's upstream did not serve maps to a retryable 503 through
+ :func:`upstream_unavailable_exception`. Everything else keeps the
+ legacy 500 ``INFERENCE_ERROR`` mapping.
Args:
error: Exception from inference.
@@ -691,6 +717,12 @@ class InferenceErrorHandler:
headers={"Retry-After": str(WORKER_DRAINED_RETRY_AFTER_S)},
)
+ if isinstance(error, UpstreamUnavailableError):
+ logger.warning("%s for model %s was not served by its upstream: %s", operation, self.model, error)
+ self.span.set_attribute("error", f"upstream_{error.kind}")
+ self._record_completion("retry")
+ return upstream_unavailable_exception(error, self.model)
+
# Recognise both the worker's ``ResourceExhaustedError`` (recovery
# exhausted) and any OOM that escaped without recovery (recovery
# disabled or a code path the executor doesn't wrap). Both deserve
diff --git a/packages/sie_server/src/sie_server/api/openai_compat.py b/packages/sie_server/src/sie_server/api/openai_compat.py
index 7ca3eca35..b794912ab 100644
--- a/packages/sie_server/src/sie_server/api/openai_compat.py
+++ b/packages/sie_server/src/sie_server/api/openai_compat.py
@@ -28,6 +28,7 @@ from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from pydantic.json_schema import SkipJsonSchema
+from sie_server.adapters.errors import InputTooLongError, UpstreamUnavailableError
from sie_server.api.helpers import (
WORKER_DRAINED_RETRY_AFTER_S,
ModelStateChecker,
@@ -35,6 +36,7 @@ from sie_server.api.helpers import (
oom_retry_after_from_registry,
openai_error_response,
serving_disclosure_headers,
+ upstream_unavailable_exception,
)
from sie_server.api.options import resolve_runtime_options_with_profile
from sie_server.api.validation import validate_machine_profile_header
@@ -45,7 +47,7 @@ from sie_server.core.worker import QueueFullError
from sie_server.core.worker.types import WorkerDrainedError
from sie_server.observability.tracing import tracer
from sie_server.observability.worker_telemetry import worker_telemetry, worker_telemetry_enabled
-from sie_server.types.inputs import Item, item_size_error
+from sie_server.types.inputs import InvalidInputError, Item, item_size_error
from sie_server.types.openapi import (
OpenAIEmbeddingsErrorResponse,
OpenAIEmbeddingsModelLoadFailedErrorResponse,
@@ -565,6 +567,42 @@ async def _create_embeddings(
},
headers={"Retry-After": str(WORKER_DRAINED_RETRY_AFTER_S)},
) from e
+ except UpstreamUnavailableError as e:
+ logger.warning("Embeddings for model %s were not served by its upstream: %s", model, e)
+ span.set_attribute("error", f"upstream_{e.kind}")
+ if inference_started is not None:
+ worker_telemetry().item_completed(
+ operation="embeddings",
+ outcome="retry",
+ model=model,
+ profile="default",
+ duration_s=time.perf_counter() - inference_started,
+ item_count=len(items),
+ )
+ raise _openai_state_error(upstream_unavailable_exception(e, model)) from e
+ except (InputTooLongError, InvalidInputError) as e:
+ too_long = isinstance(e, InputTooLongError)
+ span.set_attribute("error", "input_too_long" if too_long else "invalid_input")
+ if inference_started is not None:
+ worker_telemetry().item_completed(
+ operation="embeddings",
+ outcome="error",
+ model=model,
+ profile="default",
+ duration_s=time.perf_counter() - inference_started,
+ item_count=len(items),
+ )
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={
+ "error": {
+ "code": ErrorCode.INPUT_TOO_LONG.value if too_long else "invalid_request",
+ "message": str(e),
+ "type": "invalid_request_error",
+ "param": "input",
+ }
+ },
+ ) from e
except Exception as e:
if is_oom_error(e):
# Transient memory pressure (worker ResourceExhaustedError after
diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.py
index 13cadf7f1..9207b086e 100644
--- a/packages/sie_server/src/sie_server/queue_executor.py
+++ b/packages/sie_server/src/sie_server/queue_executor.py
@@ -13,7 +13,7 @@ import msgspec
import yaml
from sie_sdk._msgpack import packb as pack_msgpack
-from sie_server.adapters.errors import InputTooLongError
+from sie_server.adapters.errors import InputTooLongError, UpstreamUnavailableError
from sie_server.api.ws import (
BundleConfigView,
BundleMetadataUnavailableError,
@@ -103,6 +103,7 @@ _INFERENCE_ERROR_CODE: Final[str] = "inference_error"
# which under a systemic failure is also the correct answer, because every one
# of them was going to fail anyway.
_MAX_ENCODE_ISOLATION_PASSES: Final[int] = 24
+_UPSTREAM_NAK_MAX_DELAY_S: Final[float] = 60.0
_CANONICAL_AUDIO_SAMPLE_RATE: Final[int] = 16_000
_MAX_AUDIO_CHANNELS: Final[int] = 2
_MIN_AUDIO_SAMPLE_RATE: Final[int] = 8_000
@@ -2215,6 +2216,20 @@ def _oom_nak_outcome(bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem) ->
)
+def _upstream_nak_outcome(bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem, retry_after_s: int) -> ItemOutcome:
+ # Never shorter than the base delay: a work item has a fixed number of
+ # deliveries, and a one-second hint would spend them long before the
+ # gateway stops waiting for the result.
+ delay_s = min(_UPSTREAM_NAK_MAX_DELAY_S, max(_default_nak_delay_s(), float(retry_after_s)))
+ return ItemOutcome(
+ work_item_id=bi.work_item_id,
+ request_id=bi.request_id,
+ item_index=bi.item_index,
+ disposition="nak_retry",
+ nak_delay_ms=int(delay_s * 1000),
+ )
+
+
def _inference_exception_outcome(
bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem,
exc: BaseException,
@@ -2229,6 +2244,10 @@ def _inference_exception_outcome(
# park items in a batcher today, so this arm is a contract guard
# against a future caller that submits through the queueing path.
return _nak_outcome(bi)
+ if isinstance(exc, UpstreamUnavailableError):
+ # A remote profile's upstream did not serve the item, and asking again
+ # later may succeed: redeliver instead of publishing a terminal error.
+ return _upstream_nak_outcome(bi, exc.retry_after_s)
if isinstance(exc, InputTooLongError):
# The input exceeds the model's window: INPUT_TOO_LONG (HTTP 400), as
# the HTTP path reports it, not a server-side inference failure.
diff --git a/packages/sie_server/tests/adapters/conftest.py b/packages/sie_server/tests/adapters/conftest.py
new file mode 100644
index 000000000..c815f959b
--- /dev/null
+++ b/packages/sie_server/tests/adapters/conftest.py
@@ -0,0 +1,189 @@
+"""Real SIE apps on loopback for the remote adapter tests.
+
+An upstream is a real SIE app serving the built-in fake models, so a request
+and its answer cross the actual wire format in both directions. A local app
+serves the remote-backed model ``acme/remote-fake`` through it.
+"""
+
+from __future__ import annotations
+
+import socket
+import threading
+import time
+from collections.abc import Callable, Iterator
+from contextlib import AbstractContextManager, contextmanager
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+import uvicorn
+from fastapi import FastAPI, Request
+from fastapi.testclient import TestClient
+from sie_server.app.app_factory import AppFactory
+from sie_server.app.app_state_config import AppStateConfig
+from sie_server.config.upstreams import install_upstreams
+
+MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
+_CREDENTIAL = "sk-canary-3d9f1a7b52c6e804"
+_CREDENTIAL_ENV = "REMOTE_SIE_TEST_KEY"
+_REMOTE_MODEL = """\
+sie_id: acme/remote-fake
+remote_backed: true
+inputs:
+ text: true
+tasks:
+ encode:
+ dense:
+ dim: 384
+profiles:
+ default:
+ adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter
+ max_batch_tokens: 8192
+ adapter_options:
+ loadtime:
+ upstream: {upstream}
+ upstream_model: {upstream_model}
+"""
+
+
+@dataclass
+class LoopbackUpstream:
+ """A running upstream SIE app and the ``Authorization`` header of each encode it received."""
+
+ url: str
+ seen_authorization: list[str | None] = field(default_factory=list)
+
+
+@contextmanager
+def _serve(app: FastAPI) -> Iterator[str]:
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ port = sock.getsockname()[1]
+ server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning"))
+ thread = threading.Thread(target=server.run, daemon=True)
+ thread.start()
+ deadline = time.monotonic() + 30
+ while not server.started:
+ assert time.monotonic() < deadline, "the app on loopback did not start"
+ time.sleep(0.05)
+ try:
+ yield f"http://127.0.0.1:{port}"
+ finally:
+ server.should_exit = True
+ thread.join(timeout=10)
+
+
+def _offline_apps(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Apps built by these fixtures send no usage telemetry off the machine."""
+ monkeypatch.setenv("SIE_TELEMETRY_DISABLED", "1")
+
+
+def upstream_credential_env() -> str:
+ """The environment variable that holds the credential of the local app's upstream."""
+ return _CREDENTIAL_ENV
+
+
+def upstream_credential(monkeypatch: pytest.MonkeyPatch, upstream_credential_env: str) -> Iterator[str]:
+ """The credential a local app sends its upstream. It must never reach a response or a log."""
+ monkeypatch.setenv(upstream_credential_env, _CREDENTIAL)
+ yield _CREDENTIAL
+ install_upstreams({})
+
+
+def serve_on_loopback() -> Callable[[FastAPI], AbstractContextManager[str]]:
+ """Run an app on 127.0.0.1 for the length of a ``with`` block, which receives its base URL."""
+ return _serve
+
+
+def sie_upstream(_offline_apps: None) -> Callable[..., AbstractContextManager[LoopbackUpstream]]:
+ """Start a real SIE app serving the fake models named, ``sie-fake`` when none is named."""
+
+ @contextmanager
+ def start(*models: str) -> Iterator[LoopbackUpstream]:
+ app = AppFactory.create_app(
+ AppStateConfig(models_dir=str(MODELS_DIR), model_filter=list(models or ("sie-fake",)), device="cpu")
+ )
+ upstream = LoopbackUpstream(url="")
+
+ @app.middleware("http")
+ async def record_authorization(request: Request, call_next: Any) -> Any:
+ if request.url.path.startswith("/v1/encode/"):
+ upstream.seen_authorization.append(request.headers.get("authorization"))
+ return await call_next(request)
+
+ with _serve(app) as url:
+ upstream.url = url
+ yield upstream
+
+ return start
+
+
+def remote_app(
+ tmp_path: Path, upstream_credential: str, upstream_credential_env: str, _offline_apps: None
+) -> Callable[..., FastAPI]:
+ """Build a local app that serves ``acme/remote-fake`` through the upstream at a URL."""
+ _ = upstream_credential
+
+ def build(
+ upstream_url: str,
+ *,
+ remote_serving: bool = True,
+ upstream: str = "fake-sie",
+ upstream_model: str = "sie-fake",
+ extra_models: dict[str, str] | None = None,
+ preload: bool = False,
+ ) -> FastAPI:
+ models = tmp_path / "models"
+ models.mkdir(exist_ok=True)
+ (models / "remote-fake.yaml").write_text(
+ _REMOTE_MODEL.format(upstream=upstream, upstream_model=upstream_model), encoding="utf-8"
+ )
+ for file_name, text in (extra_models or {}).items():
+ (models / file_name).write_text(text, encoding="utf-8")
+ upstreams = tmp_path / "upstreams.yaml"
+ upstreams.write_text(
+ "upstreams:\n"
+ " fake-sie:\n"
+ " kind: sie\n"
+ f" base_url: {upstream_url}\n"
+ f" api_key_secret: {upstream_credential_env}\n"
+ " rate_cap: {requests_per_minute: 600, max_concurrency: 8}\n",
+ encoding="utf-8",
+ )
+ return AppFactory.create_app(
+ AppStateConfig(
+ models_dir=str(models),
+ device="cpu",
+ upstreams_file=str(upstreams),
+ remote_serving=remote_serving,
+ preload_models=["acme/remote-fake"] if preload else None,
+ )
+ )
+
+ return build
+
+
+def encode_when_loaded() -> Callable[..., httpx.Response]:
+ """POST one text item to ``/v1/encode`` until the answer is not a 503, for at most 30 s."""
+
+ def post(client: TestClient, model: str, text: str, *, params: dict[str, Any] | None = None) -> httpx.Response:
+ body: dict[str, Any] = {"items": [{"text": text}]}
+ if params is not None:
+ body["params"] = params
+ deadline = time.monotonic() + 30
+ while True:
+ response = client.post(f"/v1/encode/{model}", json=body, headers={"Accept": "application/json"})
+ if response.status_code != 503 or time.monotonic() > deadline:
+ return response
+ time.sleep(0.1)
+
+ return post
diff --git a/packages/sie_server/tests/adapters/test_remote_sie_adapter.py b/packages/sie_server/tests/adapters/test_remote_sie_adapter.py
index db0fb020e..6fb1bf7bb 100644
--- a/packages/sie_server/tests/adapters/test_remote_sie_adapter.py
+++ b/packages/sie_server/tests/adapters/test_remote_sie_adapter.py
@@ -6,50 +6,33 @@ the request and the vectors cross the actual wire format in both directions.
from __future__ import annotations
+import json
import logging
-import socket
-import threading
import time
-from collections.abc import Iterator
-from contextlib import contextmanager
+from collections.abc import Callable, Iterator
+from datetime import UTC, datetime, timedelta
+from email.utils import format_datetime
from pathlib import Path
from typing import Any
import httpx
import numpy as np
import pytest
-import uvicorn
-from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from sie_sdk import SIEClient
+from sie_sdk._msgpack import packb
+from sie_server.adapters.errors import InputTooLongError, UpstreamUnavailableError
+from sie_server.adapters.remote import _http as remote_http
from sie_server.adapters.remote import sie as remote_sie
from sie_server.app.app_factory import AppFactory
from sie_server.app.app_state_config import AppStateConfig
from sie_server.config.upstreams import Upstream, install_upstreams
+from sie_server.core.oom import is_oom_error
from sie_server.core.upstream_client import upstream_sync_client
-from sie_server.types.inputs import Item
+from sie_server.types.inputs import InvalidInputError, Item
MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
-CANARY = "sk-canary-3d9f1a7b52c6e804"
-KEY_ENV = "REMOTE_SIE_TEST_KEY"
-REMOTE_MODEL = """\
-sie_id: acme/remote-fake
-remote_backed: true
-inputs:
- text: true
-tasks:
- encode:
- dense:
- dim: 384
-profiles:
- default:
- adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter
- max_batch_tokens: 8192
- adapter_options:
- loadtime:
- upstream: {upstream}
- upstream_model: sie-fake
-"""
+CANARY = "sk-canary-77c2e41b09d8f356"
MIXED_MODEL = """\
@@ -80,95 +63,24 @@ profiles:
@pytest.fixture(autouse=True)
-def _reset_upstreams(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
- monkeypatch.setenv(KEY_ENV, CANARY)
- yield
- install_upstreams({})
+def _credential(upstream_credential: str) -> str:
+ return upstream_credential
-@contextmanager
-def fake_sie_upstream() -> Iterator[tuple[str, list[str | None]]]:
- app = AppFactory.create_app(AppStateConfig(models_dir=str(MODELS_DIR), model_filter=["sie-fake"], device="cpu"))
- seen_authorization: list[str | None] = []
-
- @app.middleware("http")
- async def record_authorization(request: Request, call_next: Any) -> Any:
- if request.url.path.startswith("/v1/encode/"):
- seen_authorization.append(request.headers.get("authorization"))
- return await call_next(request)
-
- with socket.socket() as sock:
- sock.bind(("127.0.0.1", 0))
- port = sock.getsockname()[1]
- server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning"))
- thread = threading.Thread(target=server.run, daemon=True)
- thread.start()
- deadline = time.monotonic() + 30
- while not server.started:
- assert time.monotonic() < deadline, "the upstream SIE app did not start"
- time.sleep(0.05)
- try:
- yield f"http://127.0.0.1:{port}", seen_authorization
- finally:
- server.should_exit = True
- thread.join(timeout=10)
-
-
-def local_app(
- tmp_path: Path,
- upstream_url: str,
- *,
- remote_serving: bool = True,
- upstream: str = "fake-sie",
- extra_models: dict[str, str] | None = None,
-) -> FastAPI:
- models = tmp_path / "models"
- models.mkdir()
- (models / "remote-fake.yaml").write_text(REMOTE_MODEL.format(upstream=upstream), encoding="utf-8")
- for file_name, text in (extra_models or {}).items():
- (models / file_name).write_text(text, encoding="utf-8")
- upstreams = tmp_path / "upstreams.yaml"
- upstreams.write_text(
- "upstreams:\n"
- " fake-sie:\n"
- " kind: sie\n"
- f" base_url: {upstream_url}\n"
- f" api_key_secret: {KEY_ENV}\n"
- " rate_cap: {requests_per_minute: 600, max_concurrency: 8}\n",
- encoding="utf-8",
- )
- return AppFactory.create_app(
- AppStateConfig(
- models_dir=str(models),
- device="cpu",
- upstreams_file=str(upstreams),
- remote_serving=remote_serving,
- )
- )
-
-
-def encode_when_loaded(
- client: TestClient, model: str, text: str, *, params: dict[str, Any] | None = None
-) -> httpx.Response:
- body: dict[str, Any] = {"items": [{"text": text}]}
- if params is not None:
- body["params"] = params
- deadline = time.monotonic() + 30
- while True:
- response = client.post(f"/v1/encode/{model}", json=body, headers={"Accept": "application/json"})
- if response.status_code != 503 or time.monotonic() > deadline:
- return response
- time.sleep(0.1)
-
-
-def test_a_remote_backed_model_returns_the_upstreams_vectors(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
+def test_a_remote_backed_model_returns_the_upstreams_vectors(
+ sie_upstream: Callable[..., Any],
+ remote_app: Callable[..., Any],
+ encode_when_loaded: Callable[..., httpx.Response],
+ upstream_credential: str,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
caplog.set_level(logging.DEBUG)
- with fake_sie_upstream() as (upstream_url, seen_authorization):
- with SIEClient(upstream_url) as upstream:
- expected = upstream.encode("sie-fake", {"text": "remote backends"})["dense"]
- seen_authorization.clear()
+ with sie_upstream() as upstream:
+ with SIEClient(upstream.url) as direct:
+ expected = direct.encode("sie-fake", {"text": "remote backends"})["dense"]
+ upstream.seen_authorization.clear()
- with TestClient(local_app(tmp_path, upstream_url)) as client:
+ with TestClient(remote_app(upstream.url)) as client:
response = encode_when_loaded(client, "acme/remote-fake", "remote backends")
embeddings = client.post("/v1/embeddings", json={"model": "acme/remote-fake", "input": "remote backends"})
listed = client.get("/v1/models/acme/remote-fake")
@@ -182,13 +94,13 @@ def test_a_remote_backed_model_returns_the_upstreams_vectors(tmp_path: Path, cap
assert embeddings.headers["x-sie-served-by"] == "remote"
assert embeddings.headers["x-sie-upstream"] == "fake-sie"
assert listed.json()["routing"] == {"policy": "remote_only", "upstream_kind": "sie"}
- assert seen_authorization == [f"Bearer {CANARY}", f"Bearer {CANARY}"]
- assert CANARY not in response.text
- assert CANARY not in str(response.headers)
- assert CANARY not in caplog.text
+ assert upstream.seen_authorization == [f"Bearer {upstream_credential}", f"Bearer {upstream_credential}"]
+ assert upstream_credential not in response.text
+ assert upstream_credential not in str(response.headers)
+ assert upstream_credential not in caplog.text
-def test_a_local_model_discloses_local_serving() -> None:
+def test_a_local_model_discloses_local_serving(encode_when_loaded: Callable[..., httpx.Response]) -> None:
app = AppFactory.create_app(AppStateConfig(models_dir=str(MODELS_DIR), model_filter=["sie-fake"], device="cpu"))
with TestClient(app) as client:
@@ -201,11 +113,15 @@ def test_a_local_model_discloses_local_serving() -> None:
assert listed.json()["routing"] == {"policy": None, "upstream_kind": None}
-def test_the_served_side_follows_the_model_id_not_a_request_option(tmp_path: Path) -> None:
- with fake_sie_upstream() as (upstream_url, _):
- with SIEClient(upstream_url) as upstream:
- upstream.encode("sie-fake", {"text": "warm"})
- app = local_app(tmp_path, upstream_url, extra_models={"mixed.yaml": MIXED_MODEL})
+def test_the_served_side_follows_the_model_id_not_a_request_option(
+ sie_upstream: Callable[..., Any],
+ remote_app: Callable[..., Any],
+ encode_when_loaded: Callable[..., httpx.Response],
+) -> None:
+ with sie_upstream() as upstream:
+ with SIEClient(upstream.url) as direct:
+ direct.encode("sie-fake", {"text": "warm"})
+ app = remote_app(upstream.url, extra_models={"mixed.yaml": MIXED_MODEL})
with TestClient(app) as client:
selected = encode_when_loaded(client, "acme/mixed", "mixed", params={"options": {"profile": "remote"}})
variant = encode_when_loaded(client, "acme/mixed:remote", "mixed")
@@ -218,40 +134,52 @@ def test_the_served_side_follows_the_model_id_not_a_request_option(tmp_path: Pat
assert variant.headers["x-sie-upstream"] == "fake-sie"
-def test_the_global_switch_refuses_remote_profiles_and_sends_nothing(tmp_path: Path) -> None:
- with fake_sie_upstream() as (upstream_url, seen_authorization):
- with TestClient(local_app(tmp_path, upstream_url, remote_serving=False)) as client:
+def test_the_global_switch_refuses_remote_profiles_and_sends_nothing(
+ sie_upstream: Callable[..., Any],
+ remote_app: Callable[..., Any],
+ encode_when_loaded: Callable[..., httpx.Response],
+) -> None:
+ with sie_upstream() as upstream:
+ with TestClient(remote_app(upstream.url, remote_serving=False)) as client:
response = encode_when_loaded(client, "acme/remote-fake", "remote backends")
assert response.status_code == 502, response.text
assert "remote serving is switched off" in response.text
- assert seen_authorization == []
+ assert upstream.seen_authorization == []
-def test_a_model_naming_an_undefined_upstream_stops_startup(tmp_path: Path) -> None:
- app = local_app(tmp_path, "http://127.0.0.1:9", upstream="nobody")
+def test_a_model_naming_an_undefined_upstream_stops_startup(remote_app: Callable[..., Any]) -> None:
+ app = remote_app("http://127.0.0.1:9", upstream="nobody")
with pytest.raises(ValueError, match="names an undefined upstream 'nobody'"), TestClient(app):
pass
def test_a_malformed_credential_never_reaches_the_caller_or_the_upstream(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+ sie_upstream: Callable[..., Any],
+ remote_app: Callable[..., Any],
+ encode_when_loaded: Callable[..., httpx.Response],
+ upstream_credential: str,
+ upstream_credential_env: str,
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
) -> None:
- monkeypatch.setenv(KEY_ENV, f"{CANARY} trailing-garbage")
+ monkeypatch.setenv(upstream_credential_env, f"{upstream_credential} trailing-garbage")
caplog.set_level(logging.DEBUG)
- with fake_sie_upstream() as (upstream_url, seen_authorization):
- with TestClient(local_app(tmp_path, upstream_url)) as client:
+ with sie_upstream() as upstream:
+ with TestClient(remote_app(upstream.url)) as client:
response = encode_when_loaded(client, "acme/remote-fake", "remote backends")
- assert response.status_code != 200
- assert seen_authorization == []
- assert CANARY not in response.text
- assert CANARY not in caplog.text
+ assert response.status_code == 500, response.text
+ assert upstream.seen_authorization == []
+ assert upstream_credential not in response.text
+ assert upstream_credential not in caplog.text
-def test_with_the_switch_off_a_stale_upstream_name_does_not_stop_startup(tmp_path: Path) -> None:
- app = local_app(tmp_path, "http://127.0.0.1:9", upstream="nobody", remote_serving=False)
+def test_with_the_switch_off_a_stale_upstream_name_does_not_stop_startup(
+ remote_app: Callable[..., Any], encode_when_loaded: Callable[..., httpx.Response]
+) -> None:
+ app = remote_app("http://127.0.0.1:9", upstream="nobody", remote_serving=False)
with TestClient(app) as client:
response = encode_when_loaded(client, "acme/remote-fake", "remote backends")
@@ -271,7 +199,10 @@ class Recorder:
def adapter_over(
- monkeypatch: pytest.MonkeyPatch, recorder: Recorder, *, upstream_model: str = "sie-fake"
+ monkeypatch: pytest.MonkeyPatch,
+ recorder: Callable[[httpx.Request], httpx.Response],
+ *,
+ upstream_model: str = "sie-fake",
) -> remote_sie.SieUpstreamAdapter:
upstream = Upstream.model_validate(
{
@@ -292,8 +223,6 @@ def adapter_over(
def encode_payload(items: list[dict[str, Any]]) -> bytes:
- from sie_sdk._msgpack import packb
-
return packb({"items": items})
@@ -359,13 +288,13 @@ def test_upstream_error_text_is_never_relayed(monkeypatch: pytest.MonkeyPatch) -
def test_an_unexpected_error_code_is_dropped(monkeypatch: pytest.MonkeyPatch) -> None:
- recorder = Recorder(streamed(500, b"x", **{"X-SIE-Error-Code": f"leak {CANARY}"}))
+ recorder = Recorder(streamed(404, b"x", **{"X-SIE-Error-Code": f"leak {CANARY}"}))
adapter = adapter_over(monkeypatch, recorder)
with pytest.raises(remote_sie.RemoteUpstreamError) as raised:
adapter.encode([Item(text="a")], ["dense"])
- assert str(raised.value) == "upstream answered 500"
+ assert str(raised.value) == "upstream answered 404"
def test_a_compressed_body_is_refused(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -396,9 +325,12 @@ def test_a_slow_body_is_cut_at_the_deadline(monkeypatch: pytest.MonkeyPatch) ->
recorder = Recorder(httpx.Response(200, stream=_SlowBody()))
adapter = adapter_over(monkeypatch, recorder)
- with pytest.raises(remote_sie.RemoteUpstreamError, match="exceeded the deadline"):
+ with pytest.raises(UpstreamUnavailableError, match="exceeded the deadline") as raised:
adapter.encode([Item(text="a")], ["dense"])
+ assert raised.value.kind == "unavailable"
+ assert raised.value.retry_after_s == remote_http.DEFAULT_RETRY_AFTER_S
+
@pytest.mark.parametrize(
("content", "reason"),
@@ -434,3 +366,411 @@ def test_a_short_answer_is_an_error(monkeypatch: pytest.MonkeyPatch) -> None:
with pytest.raises(remote_sie.RemoteUpstreamError, match="different number of results"):
adapter.encode([Item(text="a"), Item(text="b")], ["dense"])
+
+
+def error_answer(
+ status: int,
+ code: str | None = None,
+ *,
+ envelope: str = "detail",
+ retry_after: str | None = None,
+ header_code: bool = False,
+ msgpack: bool = False,
+ padding: int = 0,
+) -> httpx.Response:
+ """An upstream error answer. Its message carries the canary, which must never be relayed."""
+ headers = {"Content-Type": "application/msgpack" if msgpack else "application/json"}
+ if retry_after is not None:
+ headers["Retry-After"] = retry_after
+ detail: dict[str, Any] = {"message": f"upstream says {CANARY}" + " " * padding}
+ if code is not None:
+ if header_code:
+ headers["X-SIE-Error-Code"] = code
+ else:
+ detail["code"] = code
+ content = packb({envelope: detail}) if msgpack else json.dumps({envelope: detail}).encode()
+ return streamed(status, content, **headers)
+
+
+RETRYABLE_ANSWERS = [
+ pytest.param(lambda: error_answer(503, "MODEL_LOADING", retry_after="5"), "not_ready", 5, id="503-model-loading"),
+ pytest.param(
+ lambda: error_answer(503, "PROVISIONING", header_code=True, retry_after="60"),
+ "not_ready",
+ 60,
+ id="503-provisioning-in-header",
+ ),
+ pytest.param(
+ lambda: error_answer(503, "provisioning", envelope="error"),
+ "not_ready",
+ 5,
+ id="503-provisioning-openai-envelope",
+ ),
+ pytest.param(lambda: error_answer(503, "LORA_LOADING", retry_after="1"), "not_ready", 1, id="503-lora-loading"),
+ pytest.param(
+ lambda: error_answer(429, "RATE_LIMIT", envelope="error", retry_after="2"), "busy", 2, id="429-rate-limit"
+ ),
+ pytest.param(lambda: error_answer(429), "busy", 5, id="429-without-code-or-wait"),
+ pytest.param(lambda: error_answer(503, "QUEUE_FULL", retry_after="1"), "busy", 1, id="503-queue-full"),
+ pytest.param(
+ lambda: error_answer(503, "RESOURCE_EXHAUSTED", msgpack=True, retry_after="7"),
+ "busy",
+ 7,
+ id="503-resource-exhausted-msgpack",
+ ),
+ pytest.param(
+ lambda: error_answer(503, "BILLING_CAPACITY_UNAVAILABLE", envelope="error", retry_after="1"),
+ "busy",
+ 1,
+ id="503-billing-capacity-unavailable",
+ ),
+ pytest.param(
+ lambda: error_answer(503, "QUEUE_UNAVAILABLE", retry_after="5"), "busy", 5, id="503-queue-unavailable-with-wait"
+ ),
+ pytest.param(
+ lambda: error_answer(503, "transport_failure", envelope="error", retry_after="3"),
+ "busy",
+ 3,
+ id="503-transport-failure-with-wait",
+ ),
+ pytest.param(
+ lambda: error_answer(503, "QUEUE_UNAVAILABLE"), "unavailable", 5, id="503-queue-unavailable-without-wait"
+ ),
+ pytest.param(lambda: error_answer(503), "unavailable", 5, id="503-without-code"),
+ pytest.param(
+ lambda: error_answer(503, "SOMETHING_NEW", retry_after="9"), "unavailable", 9, id="503-with-unknown-code"
+ ),
+ pytest.param(lambda: error_answer(500, "INFERENCE_ERROR"), "unavailable", 5, id="500"),
+ pytest.param(lambda: error_answer(502), "unavailable", 5, id="502"),
+ pytest.param(
+ lambda: error_answer(504, "GATEWAY_TIMEOUT", header_code=True, retry_after="5"), "unavailable", 5, id="504"
+ ),
+ pytest.param(
+ lambda: error_answer(503, "MODEL_LOADING", padding=128 << 10), "unavailable", 5, id="oversized-error-body"
+ ),
+ pytest.param(lambda: error_answer(503, "MODEL_LOADING", retry_after="0"), "not_ready", 1, id="wait-raised-to-1-s"),
+ pytest.param(lambda: error_answer(503, "QUEUE_FULL", retry_after="86400"), "busy", 60, id="wait-capped-at-60-s"),
+ pytest.param(lambda: error_answer(503, "QUEUE_FULL", retry_after="soon"), "busy", 5, id="unusable-wait"),
+]
+
+
[email protected](("answer", "kind", "retry_after_s"), RETRYABLE_ANSWERS)
+def test_an_answer_the_same_request_may_survive_is_retryable(
+ monkeypatch: pytest.MonkeyPatch, answer: Callable[[], httpx.Response], kind: str, retry_after_s: int
+) -> None:
+ adapter = adapter_over(monkeypatch, Recorder(answer()))
+
+ with pytest.raises(UpstreamUnavailableError) as raised:
+ adapter.encode([Item(text="a")], ["dense"])
+
+ assert (raised.value.upstream, raised.value.kind, raised.value.retry_after_s) == ("team-sie", kind, retry_after_s)
+ assert CANARY not in str(raised.value)
+ assert "SOMETHING_NEW" not in str(raised.value)
+ assert raised.value.__cause__ is None
+ assert raised.value.__context__ is None
+ assert not is_oom_error(raised.value)
+
+
+FINAL_ANSWERS = [
+ pytest.param(
+ lambda: error_answer(429, "COLD_START_RATE_LIMITED", envelope="error"),
+ remote_http.RemoteUpstreamError,
+ "upstream answered 429 COLD_START_RATE_LIMITED",
+ id="429-cold-start-rate-limited",
+ ),
+ pytest.param(
+ lambda: error_answer(503, "ACCOUNT_STATE_UNAVAILABLE", envelope="error", retry_after="1"),
+ remote_http.RemoteUpstreamError,
+ "upstream answered 503 ACCOUNT_STATE_UNAVAILABLE",
+ id="503-account-state-unavailable",
+ ),
+ pytest.param(
+ lambda: error_answer(502, "MODEL_LOAD_FAILED"),
+ remote_http.RemoteUpstreamError,
+ "upstream answered 502 MODEL_LOAD_FAILED",
+ id="502-model-load-failed",
+ ),
+ pytest.param(lambda: error_answer(501), remote_http.RemoteUpstreamError, "upstream answered 501", id="501"),
+ pytest.param(lambda: error_answer(505), remote_http.RemoteUpstreamError, "upstream answered 505", id="505"),
+ pytest.param(lambda: error_answer(401), remote_http.RemoteUpstreamError, "upstream answered 401", id="401"),
+ pytest.param(
+ lambda: error_answer(402, "INSUFFICIENT_CREDITS", envelope="error"),
+ remote_http.RemoteUpstreamError,
+ "upstream answered 402 INSUFFICIENT_CREDITS",
+ id="402",
+ ),
+ pytest.param(
+ lambda: error_answer(403, "ACCOUNT_SUSPENDED", envelope="error"),
+ remote_http.RemoteUpstreamError,
+ "upstream answered 403 ACCOUNT_SUSPENDED",
+ id="403",
+ ),
+ pytest.param(
+ lambda: error_answer(404, "MODEL_NOT_FOUND"),
+ remote_http.RemoteUpstreamError,
+ "upstream answered 404 MODEL_NOT_FOUND",
+ id="404",
+ ),
+ pytest.param(lambda: error_answer(400), remote_http.RemoteUpstreamError, "upstream answered 400", id="400"),
+ pytest.param(lambda: error_answer(413), remote_http.RemoteUpstreamError, "upstream answered 413", id="413"),
+ pytest.param(
+ lambda: error_answer(400, "INVALID_INPUT"),
+ InvalidInputError,
+ "the upstream refused the input (400 INVALID_INPUT)",
+ id="400-invalid-input",
+ ),
+ pytest.param(
+ lambda: error_answer(422, "INVALID_INPUT"),
+ InvalidInputError,
+ "the upstream refused the input (422 INVALID_INPUT)",
+ id="422-invalid-input",
+ ),
+ pytest.param(
+ lambda: error_answer(400, "INPUT_TOO_LONG"),
+ InputTooLongError,
+ "the upstream refused the input as too long (400 INPUT_TOO_LONG)",
+ id="400-input-too-long",
+ ),
+ pytest.param(
+ lambda: error_answer(413, "INPUT_TOO_LONG", header_code=True),
+ InputTooLongError,
+ "the upstream refused the input as too long (413 INPUT_TOO_LONG)",
+ id="413-input-too-long",
+ ),
+]
+
+
[email protected](("answer", "error_type", "message"), FINAL_ANSWERS)
+def test_an_answer_no_retry_would_fix_is_final(
+ monkeypatch: pytest.MonkeyPatch, answer: Callable[[], httpx.Response], error_type: type[Exception], message: str
+) -> None:
+ adapter = adapter_over(monkeypatch, Recorder(answer()))
+
+ with pytest.raises(error_type) as raised:
+ adapter.encode([Item(text="a")], ["dense"])
+
+ assert type(raised.value) is error_type
+ assert str(raised.value) == message
+
+
+class Raiser:
+ def __init__(self, error: Exception) -> None:
+ self.requests: list[httpx.Request] = []
+ self._error = error
+
+ def __call__(self, request: httpx.Request) -> httpx.Response:
+ self.requests.append(request)
+ raise self._error
+
+
+ "error",
+ [
+ httpx.ConnectError("refused"),
+ httpx.ConnectTimeout("connect"),
+ httpx.PoolTimeout("pool"),
+ httpx.ProxyError("proxy"),
+ httpx.WriteError("write"),
+ httpx.WriteTimeout("write"),
+ httpx.ReadError("read"),
+ httpx.ReadTimeout("read"),
+ httpx.RemoteProtocolError("dropped"),
+ ],
+ ids=lambda error: type(error).__name__,
+)
+def test_a_failed_connection_is_retryable(monkeypatch: pytest.MonkeyPatch, error: httpx.TransportError) -> None:
+ adapter = adapter_over(monkeypatch, Raiser(error))
+
+ with pytest.raises(UpstreamUnavailableError) as raised:
+ adapter.encode([Item(text="a")], ["dense"])
+
+ assert str(raised.value) == f"upstream 'team-sie' is unavailable: request failed ({type(error).__name__})"
+ assert raised.value.retry_after_s == remote_http.DEFAULT_RETRY_AFTER_S
+ assert raised.value.__cause__ is None
+ assert raised.value.__suppress_context__
+
+
+ "error", [httpx.UnsupportedProtocol("scheme"), httpx.LocalProtocolError("header")], ids=lambda e: type(e).__name__
+)
+def test_a_request_the_client_cannot_send_is_final(monkeypatch: pytest.MonkeyPatch, error: httpx.HTTPError) -> None:
+ adapter = adapter_over(monkeypatch, Raiser(error))
+
+ with pytest.raises(remote_sie.RemoteUpstreamError) as raised:
+ adapter.encode([Item(text="a")], ["dense"])
+
+ assert str(raised.value) == f"upstream request failed ({type(error).__name__})"
+
+
+def test_a_redirect_is_final_and_never_followed(monkeypatch: pytest.MonkeyPatch) -> None:
+ recorder = Recorder(httpx.Response(307, headers={"Location": "https://collector.example/steal"}))
+ adapter = adapter_over(monkeypatch, recorder)
+
+ with pytest.raises(remote_sie.RemoteUpstreamError, match="redirect, which is refused"):
+ adapter.encode([Item(text="a")], ["dense"])
+
+ assert len(recorder.requests) == 1
+
+
+ ("value", "seconds"),
+ [
+ (None, None),
+ ("", None),
+ (" ", None),
+ ("5", 5),
+ (" 12 ", 12),
+ ("0", 1),
+ ("1.5", 2),
+ ("86400", 60),
+ ("1e400", None),
+ ("-1", None),
+ ("nan", None),
+ ("soon", None),
+ ("Wed, 21 Oct 2015 07:28:00 GMT", 1),
+ ],
+)
+def test_retry_after_is_whole_seconds_within_the_bounded_range(value: str | None, seconds: int | None) -> None:
+ assert remote_http.parse_retry_after(value) == seconds
+
+
+def test_a_retry_after_date_is_the_wait_until_that_date() -> None:
+ when = format_datetime(datetime.now(UTC) + timedelta(seconds=30), usegmt=True)
+
+ seconds = remote_http.parse_retry_after(when)
+
+ assert seconds is not None
+ assert 29 <= seconds <= 30
+
+
+ ("headers", "body", "code"),
+ [
+ ({"X-SIE-Error-Code": "QUEUE_FULL"}, b"", "QUEUE_FULL"),
+ ({"X-SIE-Error-Code": f"leak {CANARY}"}, b'{"detail": {"code": "MODEL_LOADING"}}', "MODEL_LOADING"),
+ ({}, b'{"error": {"code": "provisioning"}}', "PROVISIONING"),
+ (
+ {"Content-Type": "application/msgpack"},
+ packb({"detail": {"code": "RESOURCE_EXHAUSTED"}}),
+ "RESOURCE_EXHAUSTED",
+ ),
+ ({}, b'{"detail": {"code": "NOT_A_CODE_THIS_SERVER_KNOWS"}}', None),
+ ({}, b'{"detail": "Service unavailable"}', None),
+ ({}, b'{"detail": {"code": ["MODEL_LOADING"]}}', None),
+ ({}, b"[1, 2]", None),
+ ({}, b"\xff not json", None),
+ ],
+ ids=[
+ "header",
+ "unknown-header-then-body",
+ "openai-envelope",
+ "msgpack",
+ "unknown-code",
+ "detail-without-object",
+ "code-not-a-string",
+ "not-an-object",
+ "undecodable",
+ ],
+)
+def test_only_an_error_code_this_server_knows_is_read(headers: dict[str, str], body: bytes, code: str | None) -> None:
+ assert remote_http.upstream_error_code(httpx.Headers(headers), body) == code
+
+
+def mock_upstream_app(
+ monkeypatch: pytest.MonkeyPatch, remote_app: Callable[..., Any], answer: Callable[[], httpx.Response]
+) -> Any:
+ monkeypatch.setattr(
+ remote_sie,
+ "upstream_sync_client",
+ lambda upstream: upstream_sync_client(upstream, transport=httpx.MockTransport(lambda _request: answer())),
+ )
+ return remote_app("https://sie.example.internal", preload=True)
+
+
+def test_a_busy_upstream_is_a_retryable_queue_full_on_both_routes(
+ monkeypatch: pytest.MonkeyPatch, remote_app: Callable[..., Any]
+) -> None:
+ app = mock_upstream_app(monkeypatch, remote_app, lambda: error_answer(429, "RATE_LIMIT", retry_after="7"))
+
+ with TestClient(app) as client:
+ native = client.post(
+ "/v1/encode/acme/remote-fake", json={"items": [{"text": "a"}]}, headers={"Accept": "application/json"}
+ )
+ openai = client.post("/v1/embeddings", json={"model": "acme/remote-fake", "input": "a"})
+
+ assert native.status_code == 503, native.text
+ assert native.json() == {
+ "detail": {
+ "code": "QUEUE_FULL",
+ "message": "The upstream serving model 'acme/remote-fake' is busy, please retry",
+ }
+ }
+ assert openai.status_code == 503, openai.text
+ assert openai.json()["error"]["code"] == "QUEUE_FULL"
+ assert openai.json()["error"]["type"] == "server_error"
+ for response in (native, openai):
+ assert response.headers["retry-after"] == "7"
+ assert response.headers["x-sie-served-by"] == "remote"
+ assert response.headers["x-sie-upstream"] == "fake-sie"
+ assert CANARY not in response.text
+
+
+ ("answer", "native_code", "openai_code", "message"),
+ [
+ pytest.param(
+ lambda: error_answer(400, "INPUT_TOO_LONG"),
+ "INPUT_TOO_LONG",
+ "INPUT_TOO_LONG",
+ "the upstream refused the input as too long (400 INPUT_TOO_LONG)",
+ id="too-long",
+ ),
+ pytest.param(
+ lambda: error_answer(422, "INVALID_INPUT"),
+ "INVALID_INPUT",
+ "invalid_request",
+ "the upstream refused the input (422 INVALID_INPUT)",
+ id="invalid",
+ ),
+ ],
+)
+def test_an_input_the_upstream_refuses_is_the_callers_error_on_both_routes(
+ monkeypatch: pytest.MonkeyPatch,
+ remote_app: Callable[..., Any],
+ answer: Callable[[], httpx.Response],
+ native_code: str,
+ openai_code: str,
+ message: str,
+) -> None:
+ app = mock_upstream_app(monkeypatch, remote_app, answer)
+
+ with TestClient(app) as client:
+ native = client.post(
+ "/v1/encode/acme/remote-fake", json={"items": [{"text": "a"}]}, headers={"Accept": "application/json"}
+ )
+ openai = client.post("/v1/embeddings", json={"model": "acme/remote-fake", "input": "a"})
+
+ assert native.status_code == 400, native.text
+ assert native.json()["detail"] == {"code": native_code, "message": message}
+ assert openai.status_code == 400, openai.text
+ assert openai.json()["error"] == {
+ "code": openai_code,
+ "message": message,
+ "type": "invalid_request_error",
+ "param": "input",
+ }
+
+
+def test_an_upstream_that_refuses_the_credential_is_a_server_error(
+ monkeypatch: pytest.MonkeyPatch, remote_app: Callable[..., Any]
+) -> None:
+ app = mock_upstream_app(monkeypatch, remote_app, lambda: error_answer(401))
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/encode/acme/remote-fake", json={"items": [{"text": "a"}]}, headers={"Accept": "application/json"}
+ )
+
+ assert response.status_code == 500, response.text
+ assert response.json()["detail"] == {"code": "INFERENCE_ERROR", "message": "internal error during encoding"}
+ assert "retry-after" not in response.headers
diff --git a/packages/sie_server/tests/adapters/test_remote_upstream_failures.py b/packages/sie_server/tests/adapters/test_remote_upstream_failures.py
new file mode 100644
index 000000000..f86d40c4f
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_remote_upstream_failures.py
@@ -0,0 +1,288 @@
+"""What the caller sees when an SIE upstream cannot serve a request yet.
+
+Every upstream here is a real SIE app on loopback. Its fake model is held in its
+load, fails to load, or is never reached, so the local server answers through
+the real error path on both ingress paths: single-node HTTP and the queue worker.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import socket
+import threading
+import time
+from collections.abc import Callable, Iterator
+from pathlib import Path
+from typing import Any
+
+import httpx
+import numpy as np
+import pytest
+from fastapi.testclient import TestClient
+from sie_sdk import SIEClient
+from sie_server.adapters.errors import UpstreamUnavailableError
+from sie_server.config.upstreams import Upstream, install_upstreams
+from sie_server.core.registry import ModelRegistry
+from sie_server.ipc_types import EncodeBatchItem, ItemOutcome, ProcessEncodeBatchRequest
+from sie_server.queue_executor import QueueExecutor, _inference_exception_outcome
+
+REMOTE_MODEL = "acme/remote-fake"
+NOT_READY_MESSAGE = "Model 'acme/remote-fake' is loading on its upstream, please retry"
+
+
[email protected](autouse=True)
+def _credential(upstream_credential: str) -> str:
+ return upstream_credential
+
+
+def held_upstream_load(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
+ """Hold the upstream's fake model in its load until the returned file exists."""
+ release = tmp_path / "release-upstream-load"
+ monkeypatch.setenv(
+ "SIE_FAKE_FAULTS", json.dumps({"sie-fake": {"load_latch_file": str(release), "latch_timeout_s": 60}})
+ )
+ yield release
+ release.touch()
+
+
+def closed_port() -> int:
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
+def encode(client: TestClient, text: str = "cold") -> httpx.Response:
+ return client.post(
+ f"/v1/encode/{REMOTE_MODEL}", json={"items": [{"text": text}]}, headers={"Accept": "application/json"}
+ )
+
+
+def embeddings(client: TestClient, text: str = "cold") -> httpx.Response:
+ return client.post("/v1/embeddings", json={"model": REMOTE_MODEL, "input": text})
+
+
+def test_a_cold_upstream_is_a_retryable_model_loading_with_its_wait(
+ sie_upstream: Callable[..., Any],
+ remote_app: Callable[..., Any],
+ encode_when_loaded: Callable[..., httpx.Response],
+ held_upstream_load: Path,
+ upstream_credential: str,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ caplog.set_level(logging.DEBUG)
+ with sie_upstream() as upstream, TestClient(remote_app(upstream.url, preload=True)) as client:
+ native = encode(client)
+ openai = embeddings(client)
+ held_upstream_load.touch()
+ served = encode_when_loaded(client, REMOTE_MODEL, "cold")
+
+ assert native.status_code == 503, native.text
+ assert native.json() == {"detail": {"code": "MODEL_LOADING", "message": NOT_READY_MESSAGE}}
+ assert openai.status_code == 503, openai.text
+ assert openai.json()["error"] == {
+ "code": "MODEL_LOADING",
+ "message": NOT_READY_MESSAGE,
+ "type": "server_error",
+ "param": None,
+ }
+ for response in (native, openai):
+ assert response.headers["retry-after"] == "5"
+ assert response.headers["x-sie-served-by"] == "remote"
+ assert response.headers["x-sie-upstream"] == "fake-sie"
+ assert upstream_credential not in response.text
+ assert served.status_code == 200, served.text
+ assert upstream_credential not in caplog.text
+
+
+def test_the_sdk_retries_a_cold_upstream_and_returns_its_vectors(
+ sie_upstream: Callable[..., Any],
+ remote_app: Callable[..., Any],
+ serve_on_loopback: Callable[..., Any],
+ held_upstream_load: Path,
+) -> None:
+ with sie_upstream() as upstream:
+
+ def release_after_the_first_refusal() -> None:
+ deadline = time.monotonic() + 30
+ while not upstream.seen_authorization and time.monotonic() < deadline:
+ time.sleep(0.05)
+ held_upstream_load.touch()
+
+ with serve_on_loopback(remote_app(upstream.url, preload=True)) as local_url:
+ releaser = threading.Thread(target=release_after_the_first_refusal, daemon=True)
+ releaser.start()
+ with SIEClient(local_url) as client:
+ served = client.encode(REMOTE_MODEL, {"text": "cold"})["dense"]
+ releaser.join(timeout=30)
+ with SIEClient(upstream.url) as direct:
+ expected = direct.encode("sie-fake", {"text": "cold"})["dense"]
+
+ np.testing.assert_allclose(served, expected, rtol=1e-6)
+ assert len(upstream.seen_authorization) >= 3, "the refused request, the retried one, and the direct one"
+
+
+def test_an_unreachable_upstream_is_a_retryable_queue_full(remote_app: Callable[..., Any]) -> None:
+ with TestClient(remote_app(f"http://127.0.0.1:{closed_port()}", preload=True)) as client:
+ native = encode(client)
+ openai = embeddings(client)
+
+ message = "The upstream serving model 'acme/remote-fake' is unavailable, please retry"
+ assert native.status_code == 503, native.text
+ assert native.json() == {"detail": {"code": "QUEUE_FULL", "message": message}}
+ assert openai.status_code == 503, openai.text
+ assert openai.json()["error"] == {"code": "QUEUE_FULL", "message": message, "type": "server_error", "param": None}
+ for response in (native, openai):
+ assert response.headers["retry-after"] == "5"
+ assert response.headers["x-sie-served-by"] == "remote"
+ assert response.headers["x-sie-upstream"] == "fake-sie"
+
+
+def test_an_upstream_that_cannot_load_the_model_is_a_final_error(
+ sie_upstream: Callable[..., Any],
+ remote_app: Callable[..., Any],
+ encode_when_loaded: Callable[..., httpx.Response],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("SIE_FAKE_FAULTS", json.dumps({"sie-fake": {"fail_load": True}}))
+ with sie_upstream() as upstream, TestClient(remote_app(upstream.url, preload=True)) as client:
+ response = encode_when_loaded(client, REMOTE_MODEL, "never")
+
+ assert response.status_code == 500, response.text
+ assert response.json() == {"detail": {"code": "INFERENCE_ERROR", "message": "internal error during encoding"}}
+ assert "retry-after" not in response.headers
+
+
+async def queue_outcome(
+ registry: ModelRegistry, text: str = "cold", *, attempts: int = 1, interval_s: float = 0.0
+) -> ItemOutcome:
+ """Process one encode work item, again while it is NAKed, up to ``attempts`` times."""
+ executor = QueueExecutor(registry)
+ for attempt in range(attempts):
+ batch = await executor.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id=REMOTE_MODEL,
+ items=[
+ EncodeBatchItem(
+ work_item_id=f"req-{attempt}.0",
+ request_id=f"req-{attempt}",
+ item_index=0,
+ total_items=1,
+ timestamp=time.time(),
+ item={"text": text},
+ )
+ ],
+ )
+ )
+ outcome = batch.outcomes[0]
+ if outcome.disposition != "nak_retry":
+ return outcome
+ await asyncio.sleep(interval_s)
+ return outcome
+
+
+async def queue_worker(tmp_path: Path, upstream_url: str, credential_env: str) -> ModelRegistry:
+ models = tmp_path / "queue-models"
+ models.mkdir()
+ (models / "remote-fake.yaml").write_text(
+ "sie_id: acme/remote-fake\n"
+ "remote_backed: true\n"
+ "inputs: {text: true}\n"
+ "tasks: {encode: {dense: {dim: 384}}}\n"
+ "profiles:\n"
+ " default:\n"
+ " adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter\n"
+ " max_batch_tokens: 8192\n"
+ " adapter_options: {loadtime: {upstream: fake-sie, upstream_model: sie-fake}}\n",
+ encoding="utf-8",
+ )
+ install_upstreams(
+ {
+ "fake-sie": Upstream.model_validate(
+ {
+ "kind": "sie",
+ "base_url": upstream_url,
+ "api_key_secret": credential_env,
+ "rate_cap": {"requests_per_minute": 600, "max_concurrency": 8},
+ }
+ )
+ }
+ )
+ registry = ModelRegistry(models_dir=str(models), device="cpu", enable_hot_reload=False)
+ await registry.load_async(REMOTE_MODEL, "cpu")
+ return registry
+
+
+async def test_the_queue_worker_redelivers_an_item_its_cold_upstream_refused(
+ sie_upstream: Callable[..., Any], held_upstream_load: Path, tmp_path: Path, upstream_credential_env: str
+) -> None:
+ with sie_upstream() as upstream:
+ registry = await queue_worker(tmp_path, upstream.url, upstream_credential_env)
+ try:
+ refused = await queue_outcome(registry)
+ await asyncio.to_thread(held_upstream_load.touch)
+ served = await queue_outcome(registry, attempts=100, interval_s=0.1)
+ finally:
+ await registry.unload_all_async()
+
+ assert refused.disposition == "nak_retry"
+ assert refused.nak_delay_ms == 5_000
+ assert refused.error is None
+ assert refused.error_code is None
+ assert served.disposition == "publish_and_ack", served.error
+
+
+async def test_the_queue_worker_redelivers_an_item_its_unreachable_upstream_never_saw(
+ tmp_path: Path, upstream_credential_env: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("SIE_NAK_DELAY_S", "2.0")
+ registry = await queue_worker(tmp_path, f"http://127.0.0.1:{closed_port()}", upstream_credential_env)
+ try:
+ outcome = await queue_outcome(registry)
+ finally:
+ await registry.unload_all_async()
+
+ assert outcome.disposition == "nak_retry"
+ assert outcome.nak_delay_ms == 5_000, "the upstream's wait, which is longer than the base delay"
+ assert outcome.error_code is None
+
+
+async def test_the_queue_worker_publishes_a_final_upstream_error(
+ sie_upstream: Callable[..., Any], tmp_path: Path, upstream_credential_env: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("SIE_FAKE_FAULTS", json.dumps({"sie-fake": {"fail_load": True}}))
+ with sie_upstream() as upstream:
+ registry = await queue_worker(tmp_path, upstream.url, upstream_credential_env)
+ try:
+ outcome = await queue_outcome(registry, attempts=100, interval_s=0.1)
+ finally:
+ await registry.unload_all_async()
+
+ assert outcome.disposition == "publish_error_and_ack"
+ assert outcome.error_code == "inference_error"
+ assert outcome.error == "upstream answered 502 MODEL_LOAD_FAILED"
+
+
+def work_item() -> EncodeBatchItem:
+ return EncodeBatchItem(
+ work_item_id="req-1.0", request_id="req-1", item_index=0, total_items=1, timestamp=0.0, item={"text": "a"}
+ )
+
+
+ ("base_delay", "retry_after_s", "delay_ms"),
+ [("5.0", 1, 5_000), ("5.0", 30, 30_000), ("2.0", 60, 60_000), ("120.0", 5, 60_000)],
+ ids=["base-delay-is-the-floor", "upstream-wait-above-the-floor", "upstream-wait-at-the-cap", "capped-at-60-s"],
+)
+def test_the_redelivery_delay_is_the_upstream_wait_between_the_base_delay_and_a_minute(
+ monkeypatch: pytest.MonkeyPatch, base_delay: str, retry_after_s: int, delay_ms: int
+) -> None:
+ monkeypatch.setenv("SIE_NAK_DELAY_S", base_delay)
+ error = UpstreamUnavailableError("fake-sie", "busy", retry_after_s=retry_after_s, reason="answered 429")
+
+ outcome = _inference_exception_outcome(work_item(), error)
+
+ assert outcome.disposition == "nak_retry"
+ assert outcome.nak_delay_ms == delay_ms