Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): retry transient model-load failures and reload exited engines (#394)
Krisztian Gajdar8767c819e41c
diff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.pyindex b4c046376..b55664924 100644--- a/packages/sie_sdk/src/sie_sdk/client/errors.py+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py@@ -178,11 +178,14 @@ class ModelLoadFailedError(ServerError):HTTP ``502 MODEL_LOAD_FAILED``. The server uses this code for both:- **Permanent-class failures** (``GATED``, ``NOT_FOUND``,- ``DEPENDENCY``, ``UNKNOWN``) where retrying would waste time and+ ``DEPENDENCY``, ``CONFIG``) where retrying would waste time andoperator intervention is required (e.g. set ``HF_TOKEN``, accept- the model license, upgrade ``transformers``). These carry+ the model license, upgrade ``transformers``, fix the model+ config). A transient failure that keeps recurring past the+ server's attempt budget also becomes permanent. These carry``permanent=True``.- - **Transient classes in active cooldown** (``OOM``, ``NETWORK``)+ - **Transient classes in active cooldown** (``OOM``, ``NETWORK``,+ ``STORAGE``, ``ENGINE``, ``TIMEOUT``, ``PLACEMENT``, ``UNKNOWN``)where the registry is suppressing retries for a finite window sothe load loop does not hot-spin. These carry ``permanent=False``;the failure auto-expires and a subsequent request will trigger a@@ -198,7 +201,9 @@ class ModelLoadFailedError(ServerError):Attributes:model: The model that was requested.error_class: Server-side classification (``GATED``, ``OOM``,- ``DEPENDENCY``, ``NOT_FOUND``, ``NETWORK``, ``UNKNOWN``).+ ``DEPENDENCY``, ``NOT_FOUND``, ``CONFIG``, ``NETWORK``,+ ``STORAGE``, ``ENGINE``, ``TIMEOUT``, ``PLACEMENT``,+ ``UNKNOWN``).Use this to route to remediation paths (surface an"HF_TOKEN" hint for ``GATED``, retry later for ``OOM``).permanent: Whether the failure is non-retryable per serverdiff --git a/packages/sie_server/src/sie_server/adapters/base.py b/packages/sie_server/src/sie_server/adapters/base.pyindex 57b358861..7d2d02024 100644--- a/packages/sie_server/src/sie_server/adapters/base.py+++ b/packages/sie_server/src/sie_server/adapters/base.py@@ -229,6 +229,16 @@ class ModelAdapter(ABC):_ = (device_type, device_total_bytes)return None+ def engine_exit_code(self) -> int | None:+ """Return the exit code of this adapter's engine process once it has exited.++ An adapter that serves through a child engine process reports the+ child's exit code after the child dies, so the registry can unload the+ model and load it again. ``None`` means the engine is running, is not+ started, or the adapter has no separate engine process.+ """+ return None+def encode(self,items: list[Item],diff --git a/packages/sie_server/src/sie_server/adapters/mlx/_server.py b/packages/sie_server/src/sie_server/adapters/mlx/_server.pyindex 24b355eb8..408859f09 100644--- a/packages/sie_server/src/sie_server/adapters/mlx/_server.py+++ b/packages/sie_server/src/sie_server/adapters/mlx/_server.py@@ -35,6 +35,8 @@ from pathlib import Pathimport requests+from sie_server.core.load_errors import EngineStartupError+logger = logging.getLogger(__name__)# In-process record of ports already handed out by ``find_free_port`` but not@@ -122,7 +124,7 @@ def find_free_port(start_port: int = BASE_PORT) -> int:_RESERVED_PORTS.add(port)return portmsg = f"Could not find free port in range {start_port}-{start_port + span - 1}"- raise RuntimeError(msg)+ raise EngineStartupError(msg)def release_port(port: int | None) -> None:diff --git a/packages/sie_server/src/sie_server/adapters/mlx/generation.py b/packages/sie_server/src/sie_server/adapters/mlx/generation.pyindex 2b0279678..71ebe355f 100644--- a/packages/sie_server/src/sie_server/adapters/mlx/generation.py+++ b/packages/sie_server/src/sie_server/adapters/mlx/generation.py@@ -49,6 +49,7 @@ from sie_server.adapters._generation_base import (from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADEDfrom sie_server.adapters.mlx import _server+from sie_server.core.load_errors import EngineStartupError, ModelConfigurationErrorfrom sie_server.types.inputs import ImageInput, VideoInputlogger = logging.getLogger(__name__)@@ -196,7 +197,7 @@ class MLXGenerationAdapter(GenerationAdapter):# module but lack adapter_options.loadtime.mlx_repo — without this, mlx_lm would# download the full-precision HF weights (e.g. a 27B model) and OOM on Metal.if not self._mlx_repo:- raise RuntimeError(+ raise ModelConfigurationError(f"Generation model '{self._model_name_or_path}' has no mlx_repo set; the Mac MLX ""backend requires an MLX-quantized repo. Add adapter_options.loadtime.mlx_repo ""to the model YAML (e.g. 'mlx-community/<model>-4bit'), or serve a curated Mac model "@@ -258,7 +259,7 @@ class MLXGenerationAdapter(GenerationAdapter):# never stamps a crash's elapsed time as the configured budget.crash_exit_code = self._process.poll()if crash_exit_code is not None:- raise RuntimeError(f"{_server.ERR_SERVER_CRASH} (exit code {crash_exit_code})")+ raise EngineStartupError(f"{_server.ERR_SERVER_CRASH} (exit code {crash_exit_code})")raise RuntimeError(_server.ERR_SERVER_STARTUP)# mlx_lm.server answers /health as soon as httpd is up, possibly before the modeldiff --git a/packages/sie_server/src/sie_server/adapters/sglang/_server.py b/packages/sie_server/src/sie_server/adapters/sglang/_server.pyindex 96f16cf2c..6c98bfa58 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/_server.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/_server.py@@ -38,6 +38,7 @@ from sie_server.config.device_groups import (resolve_device_group,validate_tensor_parallel_size,)+from sie_server.core.load_errors import EngineExitedError, EngineStartupErrorfrom sie_server.core.oom import is_oom_error__all__ = [@@ -297,7 +298,7 @@ def find_free_port(start_port: int = BASE_PORT) -> int:_RESERVED_PORTS.add(port)return portmsg = f"Could not find free port in range {start_port}-{start_port + span - 1}"- raise RuntimeError(msg)+ raise EngineStartupError(msg)def reserve_port(port: int) -> None:@@ -306,19 +307,19 @@ def reserve_port(port: int) -> None:For a port a profile declares. Release it with :func:`release_port`.Raises:- RuntimeError: If another model in this process has it reserved, or- something already has it bound.+ EngineStartupError: If another model in this process has it reserved,+ or something already has it bound."""with _RESERVED_PORTS_LOCK:if port in _RESERVED_PORTS:msg = f"port {port} is already reserved by another model in this process"- raise RuntimeError(msg)+ raise EngineStartupError(msg)with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:try:s.bind(("localhost", port))except OSError as error:msg = f"port {port} is already in use: {error}"- raise RuntimeError(msg) from error+ raise EngineStartupError(msg) from error_RESERVED_PORTS.add(port)@@ -595,6 +596,28 @@ def read_subprocess_output_tail(output_file: tempfile._TemporaryFileWrapper | Noreturn f"<failed to read SGLang log: {exc}>"+def engine_exit_code(process: subprocess.Popen[bytes] | None) -> int | None:+ """Return the exit code of an engine child process that has exited, else ``None``."""+ return None if process is None else process.poll()+++def raise_if_engine_exited(process: subprocess.Popen[bytes] | None, served_name: str) -> None:+ """Fail a request whose engine child process has already exited.++ Raises:+ EngineExitedError: Naming the exit code, so a crash is distinguishable+ from an orderly unload in a log.+ """+ exit_code = engine_exit_code(process)+ if exit_code is None:+ return+ msg = (+ f"SGLang engine for {served_name!r} is not running "+ f"(process exited with code {exit_code}). The model must be reloaded."+ )+ raise EngineExitedError(msg)++def startup_failure_error(output_file: tempfile._TemporaryFileWrapper | None,crash_exit_code: int | None = None,@@ -608,11 +631,14 @@ def startup_failure_error(from a fictional number. Callers pass the pre-terminate ``poll()`` resultas ``crash_exit_code``; None means the health poll genuinely timed out."""- prefix = f"{ERR_SERVER_CRASH} (exit code {crash_exit_code})" if crash_exit_code is not None else ERR_SERVER_STARTUP+ if crash_exit_code is None:+ error_type, prefix = RuntimeError, ERR_SERVER_STARTUP+ else:+ error_type, prefix = EngineStartupError, f"{ERR_SERVER_CRASH} (exit code {crash_exit_code})"output = read_subprocess_output_tail(output_file).strip()if output and is_oom_error(RuntimeError(output)):- return RuntimeError(f"{prefix}: out of memory detected in startup log")- return RuntimeError(prefix)+ return error_type(f"{prefix}: out of memory detected in startup log")+ return error_type(prefix)def estimate_load_required_memory_bytes(diff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.pyindex 0b0120dc6..61cbc5da1 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py@@ -117,21 +117,13 @@ class SGLangEmbeddingAdapter(BaseAdapter):def _check_loaded(self) -> None:if self._server_url is None:raise RuntimeError(ERR_NOT_LOADED)- process = self._process- if process is None:- return- exit_code = process.poll()- if exit_code is None:- return# Without this the adapter never notices its engine exiting, and every# later request opens a connection to a port nobody is listening on,- # waits out the connect timeout and returns a transport error, with no- # reload and no readiness change.- msg = (- f"SGLang engine for {self._model_name_or_path!r} is not running "- f"(process exited with code {exit_code}). The model must be reloaded."- )- raise RuntimeError(msg)+ # waits out the connect timeout and returns a transport error.+ _server.raise_if_engine_exited(self._process, str(self._model_name_or_path))++ def engine_exit_code(self) -> int | None:+ return _server.engine_exit_code(self._process)def __init__(self,diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 83ff3da07..93495f414 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -1275,20 +1275,13 @@ class SGLangGenerationAdapter(GenerationAdapter):request.Raises:- RuntimeError: Naming the exit code, so a crash is distinguishable- from an orderly unload in a log.+ EngineExitedError: Naming the exit code, so a crash is+ distinguishable from an orderly unload in a log."""- process = self._process- if process is None:- return- exit_code = process.poll()- if exit_code is None:- return- msg = (- f"SGLang engine for {self._served_model_name!r} is not running "- f"(process exited with code {exit_code}). The model must be reloaded."- )- raise RuntimeError(msg)+ _server.raise_if_engine_exited(self._process, self._served_model_name)++ def engine_exit_code(self) -> int | None:+ return _server.engine_exit_code(self._process)async def _get_or_create_http_client(self) -> httpx.AsyncClient:"""Return the shared client, opening it if this is the first call.diff --git a/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_server.py b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_server.pyindex d8078c7ec..230c935b5 100644--- a/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_server.py+++ b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_server.py@@ -18,6 +18,8 @@ from typing import Anyimport requests+from sie_server.core.load_errors import EngineStartupError+logger = logging.getLogger(__name__)DEFAULT_STARTUP_TIMEOUT_S = 900.0@@ -117,7 +119,7 @@ def wait_until_ready(health_url = f"{server_url}/health"while time.monotonic() < deadline:if process.poll() is not None:- raise RuntimeError(f"trtllm-serve exited during startup: {log_tail(output_file)}")+ raise EngineStartupError(f"trtllm-serve exited during startup: {log_tail(output_file)}")try:response = requests.get(health_url, timeout=5)if response.status_code == 200:diff --git a/packages/sie_server/src/sie_server/core/load_errors.py b/packages/sie_server/src/sie_server/core/load_errors.pyindex 089985b9b..1eb376412 100644--- a/packages/sie_server/src/sie_server/core/load_errors.py+++ b/packages/sie_server/src/sie_server/core/load_errors.py@@ -1,8 +1,24 @@from __future__ import annotations+import errno+import socket+from collections.abc import Iteratorfrom dataclasses import dataclassfrom enum import StrEnum+import botocore.exceptions+import httpx+import requests.exceptions+from huggingface_hub.errors import (+ DisabledRepoError,+ EntryNotFoundError,+ GatedRepoError,+ HfHubHTTPError,+ LocalEntryNotFoundError,+ OfflineModeIsEnabled,+ RepositoryNotFoundError,+ RevisionNotFoundError,+)from sie_sdk.exceptions import GatedModelErrorfrom sie_server.core.oom import is_oom_error@@ -11,16 +27,16 @@ from sie_server.core.oom import is_oom_errorclass LoadErrorClass(StrEnum):"""Classification of model-load failures.- Drives the registry's terminal-failed state machine and the API's+ Drives the registry's failed state machine and the API'sretry-vs-no-retry decision in ``ensure_loaded``.- Permanent classes (``GATED``, ``NOT_FOUND``, ``DEPENDENCY``) should not- be retried automatically because re-attempting them produces the same- error every time and burns request budget. ``OOM``, ``NETWORK`` and- ``PLACEMENT`` are transient — the registry holds a cooldown to avoid hot- retry loops but eventually allows another attempt. ``UNKNOWN`` is treated as- permanent for safety; operators should inspect the underlying error- and either fix it or restart the server to clear the failure.+ Permanent classes (``GATED``, ``NOT_FOUND``, ``DEPENDENCY``, ``CONFIG``)+ are not retried automatically because re-attempting them produces the+ same error every time; a config change or a restart clears them. Every+ other class is transient: the registry holds a cooldown that doubles with+ each failed attempt, and a failure that is still recurring after+ :data:`MAX_TRANSIENT_ATTEMPTS` attempts becomes permanent. ``UNKNOWN``+ is transient with a long base cooldown."""GATED = "GATED"@@ -30,25 +46,84 @@ class LoadErrorClass(StrEnum):DEPENDENCY = "DEPENDENCY"TIMEOUT = "TIMEOUT"PLACEMENT = "PLACEMENT"+ CONFIG = "CONFIG"+ STORAGE = "STORAGE"+ ENGINE = "ENGINE"UNKNOWN = "UNKNOWN"-# Cooldown windows (seconds) per error class. ``None`` means permanent —-# the failure stays sticky until ``clear_failure`` is invoked (e.g. by a-# config hot-reload, an explicit admin call, or a server restart).-_PERMANENT: float | None = None+_PERMANENT_CLASSES: frozenset[LoadErrorClass] = frozenset(+ {+ LoadErrorClass.GATED,+ LoadErrorClass.NOT_FOUND,+ LoadErrorClass.DEPENDENCY,+ LoadErrorClass.CONFIG,+ }+)-_COOLDOWN_BY_CLASS: dict[LoadErrorClass, float | None] = {- LoadErrorClass.GATED: _PERMANENT,- LoadErrorClass.NOT_FOUND: _PERMANENT,- LoadErrorClass.DEPENDENCY: _PERMANENT,- LoadErrorClass.UNKNOWN: _PERMANENT,+_BASE_COOLDOWN_S: dict[LoadErrorClass, float] = {LoadErrorClass.OOM: 60.0,LoadErrorClass.NETWORK: 30.0,LoadErrorClass.TIMEOUT: 30.0,LoadErrorClass.PLACEMENT: 30.0,+ LoadErrorClass.STORAGE: 60.0,+ LoadErrorClass.ENGINE: 30.0,+ LoadErrorClass.UNKNOWN: 600.0,}+MAX_COOLDOWN_S = 1800.0+MAX_TRANSIENT_ATTEMPTS = 8++_TRANSIENT_HTTP_STATUSES = frozenset({408, 429})++# Throttling and transient error codes that botocore's standard retry mode+# retries; S3 returns several of them with a 4xx status.+_TRANSIENT_AWS_ERROR_CODES = frozenset(+ {+ "BandwidthLimitExceeded",+ "EC2ThrottledException",+ "LimitExceededException",+ "PriorRequestNotComplete",+ "ProvisionedThroughputExceededException",+ "RequestLimitExceeded",+ "RequestThrottled",+ "RequestThrottledException",+ "RequestTimeout",+ "RequestTimeoutException",+ "SlowDown",+ "Throttling",+ "ThrottlingException",+ "ThrottledException",+ "TooManyRequestsException",+ "TransactionInProgressException",+ }+)++_NETWORK_EXCEPTIONS: tuple[type[BaseException], ...] = (+ ConnectionError,+ TimeoutError,+ socket.gaierror,+ httpx.TransportError,+ requests.exceptions.ConnectionError,+ requests.exceptions.Timeout,+ requests.exceptions.ChunkedEncodingError,+ botocore.exceptions.ConnectionError,+ botocore.exceptions.HTTPClientError,+ botocore.exceptions.IncompleteReadError,+)++_NOT_FOUND_EXCEPTIONS: tuple[type[BaseException], ...] = (+ RepositoryNotFoundError,+ RevisionNotFoundError,+ EntryNotFoundError,+ DisabledRepoError,+)++_STORAGE_ERRNOS = frozenset({errno.ENOSPC, errno.EDQUOT})+_STORAGE_MESSAGES = ("no space left on device", "disk quota exceeded")++_MAX_CHAIN_DEPTH = 32+class DevicePlacementError(RuntimeError):"""No device, or no block of devices, can take this load right now.@@ -59,6 +134,22 @@ class DevicePlacementError(RuntimeError):"""+class ModelConfigurationError(RuntimeError):+ """The model's configuration can never load on this worker as written.++ Classified as the permanent ``CONFIG`` class: only a config change or a+ restart can clear it.+ """+++class EngineStartupError(RuntimeError):+ """An engine child process could not start: it crashed during startup or its port was taken."""+++class EngineExitedError(RuntimeError):+ """The engine child process serving a loaded model has exited."""++class ModelLoadTimeoutError(TimeoutError):"""Raised when a post-download load stage exceeds ``SIE_MODEL_LOAD_TIMEOUT_S``.@@ -92,134 +183,145 @@ class LoadFailureClassification:return self.cooldown_s is None-def classify_load_error(exc: BaseException) -> LoadFailureClassification:- """Classify a model-load exception into a ``LoadErrorClass``.+def cooldown_for(error_class: LoadErrorClass, attempts: int) -> float | None:+ """Return the retry cooldown after the ``attempts``-th consecutive failure.- Detection order matters: ``GatedModelError`` is caught before generic- ``OSError``/``ConnectionError`` because the SDK's gated wrapper subclasses- ``Exception`` directly, but huggingface's underlying ``GatedRepoError``- inherits from ``HfHubHTTPError`` which is also an ``OSError``. Likewise- OOM is detected before generic ``RuntimeError`` because torch raises- ``RuntimeError("CUDA out of memory")`` and we want it bucketed as- ``OOM`` not ``UNKNOWN``.+ Permanent classes return ``None``. Transient classes double their base+ cooldown with each attempt, capped at :data:`MAX_COOLDOWN_S`, and return+ ``None`` once ``attempts`` exceeds :data:`MAX_TRANSIENT_ATTEMPTS`.+ """+ base = _BASE_COOLDOWN_S.get(error_class)+ if base is None or error_class in _PERMANENT_CLASSES or attempts > MAX_TRANSIENT_ATTEMPTS:+ return None+ return min(base * 2 ** (max(attempts, 1) - 1), MAX_COOLDOWN_S)+++def classify_load_error(exc: BaseException, *, attempts: int = 1) -> LoadFailureClassification:+ """Classify a model-load exception by its cause.++ Walks the exception chain (``__cause__``, ``__context__`` and the+ ``last_exception`` that boto3 and s3transfer retry wrappers carry) from+ the outermost exception inwards. The first link that matches a specific+ rule decides the class, so a typed wrapper such as ``GatedModelError``+ or ``ModelLoadTimeoutError`` wins over what it wraps, while an untyped+ wrapper such as huggingface_hub's ``LocalEntryNotFoundError`` is+ classified by the error it wraps. When no link matches, an outermost+ ``ValueError`` is a permanent ``CONFIG`` error and anything else is+ ``UNKNOWN``; a ``ValueError`` nested under another error does not make+ the failure permanent.Args:exc: The exception captured by ``_load_model_background``.+ attempts: Consecutive failed attempts including this one.Returns:Classification with the canonical class and cooldown."""- # Our own post-download load timeout — must come BEFORE the generic- # ``TimeoutError`` → NETWORK branch below, since this subclasses- # ``TimeoutError``. Bucketed separately so the metric and the- # operator-facing message identify "stuck local load" distinct from- # "stuck network".- if isinstance(exc, ModelLoadTimeoutError):- return LoadFailureClassification(- error_class=LoadErrorClass.TIMEOUT,- cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.TIMEOUT],- )-- # Checked before OOM because both are RuntimeErrors.- if isinstance(exc, DevicePlacementError):- return LoadFailureClassification(- error_class=LoadErrorClass.PLACEMENT,- cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.PLACEMENT],- )-- # Gated repo (HF auth) — permanent until operator fixes HF_TOKEN.- if isinstance(exc, GatedModelError):- return LoadFailureClassification(- error_class=LoadErrorClass.GATED,- cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.GATED],- )-- # Repo missing on the Hub — permanent.- not_found_cls: type[BaseException] | None+ error_class = next((c for c in map(_classify_link, _exception_chain(exc)) if c is not None), None)+ if error_class is None:+ error_class = LoadErrorClass.CONFIG if isinstance(exc, ValueError) else LoadErrorClass.UNKNOWN+ return LoadFailureClassification(error_class=error_class, cooldown_s=cooldown_for(error_class, attempts))+++def _exception_chain(exc: BaseException) -> Iterator[BaseException]:+ seen: set[int] = set()+ pending: list[BaseException] = [exc]+ while pending and len(seen) < _MAX_CHAIN_DEPTH:+ current = pending.pop(0)+ if id(current) in seen:+ continue+ seen.add(id(current))+ yield current+ last_exception = getattr(current, "last_exception", None)+ if isinstance(last_exception, BaseException):+ pending.append(last_exception)+ if current.__cause__ is not None:+ pending.append(current.__cause__)+ elif current.__context__ is not None and not current.__suppress_context__:+ pending.append(current.__context__)+++def _classify_link(exc: BaseException) -> LoadErrorClass | None:try:- from huggingface_hub.utils import RepositoryNotFoundError as _RepositoryNotFoundError-- not_found_cls = _RepositoryNotFoundError- except ImportError: # pragma: no cover- not_found_cls = None+ return _classify_single(exc)+ except Exception: # noqa: BLE001 - a third-party attribute accessor must not break classification+ return None- if not_found_cls is not None and isinstance(exc, not_found_cls):- return LoadFailureClassification(- error_class=LoadErrorClass.NOT_FOUND,- cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.NOT_FOUND],- )- # OOM (torch / driver) — transient with cooldown so the LRU evictor or- # operator can free memory before we try again.+def _classify_single(exc: BaseException) -> LoadErrorClass | None:+ if isinstance(exc, ModelLoadTimeoutError):+ return LoadErrorClass.TIMEOUT+ if isinstance(exc, DevicePlacementError):+ return LoadErrorClass.PLACEMENT+ if isinstance(exc, GatedModelError | GatedRepoError):+ return LoadErrorClass.GATED+ if isinstance(exc, ModelConfigurationError | OfflineModeIsEnabled):+ return LoadErrorClass.CONFIG+ if isinstance(exc, _NOT_FOUND_EXCEPTIONS) and not isinstance(exc, LocalEntryNotFoundError):+ return LoadErrorClass.NOT_FOUNDif isinstance(exc, RuntimeError) and is_oom_error(exc):- return LoadFailureClassification(- error_class=LoadErrorClass.OOM,- cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.OOM],- )-- # Missing transformer architecture or python dep — permanent until the- # environment is upgraded. Embeddinggemma in particular needs- # transformers >= 4.56 for ``Gemma3TextModel``.- if isinstance(exc, ImportError | ModuleNotFoundError):- return LoadFailureClassification(- error_class=LoadErrorClass.DEPENDENCY,- cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.DEPENDENCY],- )-- # Network / IO — transient, short cooldown.- # Includes built-in ConnectionError/TimeoutError plus library-specific- # network exceptions from httpx and requests, which do NOT inherit from- # the built-ins. Without these, transient download failures would fall- # through to UNKNOWN (permanent) and require server restart to recover.- network_excs: list[type[BaseException]] = [ConnectionError, TimeoutError]- try:- import httpx as _httpx-- network_excs.extend(- [- _httpx.TransportError, # base for ConnectError, ReadTimeout, etc.- _httpx.HTTPError, # base for protocol-level errors- ]- )- except ImportError: # pragma: no cover- pass- try:- import requests.exceptions as _req_exc-- network_excs.extend(- [- _req_exc.ConnectionError,- _req_exc.Timeout,- _req_exc.ChunkedEncodingError,- ]- )- except ImportError: # pragma: no cover- pass-- if isinstance(exc, tuple(network_excs)):- return LoadFailureClassification(- error_class=LoadErrorClass.NETWORK,- cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.NETWORK],- )-- return LoadFailureClassification(- error_class=LoadErrorClass.UNKNOWN,- cooldown_s=_COOLDOWN_BY_CLASS[LoadErrorClass.UNKNOWN],- )+ return LoadErrorClass.OOM+ if isinstance(exc, ImportError):+ return LoadErrorClass.DEPENDENCY+ if _is_storage_exhausted(exc):+ return LoadErrorClass.STORAGE+ if isinstance(exc, EngineStartupError | EngineExitedError) or (+ isinstance(exc, OSError) and exc.errno == errno.EADDRINUSE+ ):+ return LoadErrorClass.ENGINE+ status = _http_status(exc)+ if status is not None:+ if status in _TRANSIENT_HTTP_STATUSES or 500 <= status <= 599:+ return LoadErrorClass.NETWORK+ if status in (401, 403) and isinstance(exc, HfHubHTTPError):+ return LoadErrorClass.GATED+ if _aws_error_code(exc) in _TRANSIENT_AWS_ERROR_CODES:+ return LoadErrorClass.NETWORK+ if isinstance(exc, _NETWORK_EXCEPTIONS):+ return LoadErrorClass.NETWORK+ return None+++def _is_storage_exhausted(exc: BaseException) -> bool:+ if isinstance(exc, OSError) and exc.errno in _STORAGE_ERRNOS:+ return True+ message = str(exc).lower()+ return any(indicator in message for indicator in _STORAGE_MESSAGES)+++def _http_status(exc: BaseException) -> int | None:+ response = getattr(exc, "response", None)+ if isinstance(response, dict):+ metadata = response.get("ResponseMetadata")+ candidates = [metadata.get("HTTPStatusCode") if isinstance(metadata, dict) else None]+ else:+ candidates = [getattr(exc, "status_code", None), getattr(response, "status_code", None)]+ for candidate in candidates:+ if isinstance(candidate, int) and not isinstance(candidate, bool) and 100 <= candidate <= 599:+ return candidate+ return None+++def _aws_error_code(exc: BaseException) -> str | None:+ response = getattr(exc, "response", None)+ if not isinstance(response, dict):+ return None+ error = response.get("Error")+ code = error.get("Code") if isinstance(error, dict) else None+ return code if isinstance(code, str) else None@dataclass(frozen=True)class LoadFailure:"""Recorded load failure for a model.- Stored in ``ModelRegistry._failed`` to drive the terminal-failed- branch of the state machine and the ``MODEL_LOAD_FAILED`` API- response.+ Stored in ``ModelRegistry._failed`` to drive the failed branch of the+ state machine and the ``MODEL_LOAD_FAILED`` API response.Attributes:error_class: The classified error category.message: Human-readable summary suitable for API responses.- attempts: How many load attempts have been recorded so far.+ attempts: How many consecutive load attempts have failed so far.last_attempt_ts: ``time.monotonic()`` value at last attempt.cooldown_s: Seconds to suppress further retries; ``None`` meansthe failure is permanent until explicitly cleared.diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.pyindex 253250973..7423d7b06 100644--- a/packages/sie_server/src/sie_server/core/model_loader.py+++ b/packages/sie_server/src/sie_server/core/model_loader.py@@ -589,7 +589,7 @@ class ModelLoader::class:`ModelLoadTimeoutError` so theregistry's failure classifier buckets them as``LoadErrorClass.TIMEOUT`` (30 s cooldown) rather than- ``UNKNOWN`` (permanent) — consistent with the executor path.+ ``UNKNOWN`` (600 s cooldown) — consistent with the executor path.Args:name: Model name.@@ -907,8 +907,9 @@ def _raise_if_adapter_startup_timeout(name: str, started: float, exc: RuntimeErrtheir own startup timeouts should follow the same convention.A child process that CRASHED during startup deliberately does not match:- the adapters raise the distinct "... process exited during startup" message- for that case, which stays a plain load failure. On the genuine-timeout+ the adapters raise ``EngineStartupError`` with the distinct "... process+ exited during startup" message for that case, which is classified+ ``ENGINE`` rather than ``TIMEOUT``. On the genuine-timeoutpath ``timeout_s=elapsed`` below is an approximation that only holdsbecause the health poll ran the budget out (run 32945082497 showed theold crash-as-timeout labeling reporting a 16.5s crash as configured=16s).diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex c11914950..e644463f4 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -34,8 +34,10 @@ from sie_server.core.disk_cache import DiskCacheConfig, ModelDiskCacheManagerfrom sie_server.core.hot_reload import HotReloaderfrom sie_server.core.load_errors import (DevicePlacementError,+ EngineExitedError,LoadErrorClass,LoadFailure,+ ModelConfigurationError,ModelLoadTimeoutError,classify_load_error,)@@ -61,6 +63,8 @@ _ERR_MODEL_NOT_FOUND = "Model '{name}' not found in registry"_ERR_MODEL_NOT_LOADED = "Model '{name}' is not loaded"_ERR_MODEL_ALREADY_LOADED = "Model '{name}' is already loaded"+_ENGINE_STABLE_UPTIME_S = 600.0+class _ConfigChangedDuringLoadError(RuntimeError):"""The downloaded config is no longer current; a later request may retry."""@@ -123,6 +127,18 @@ def _is_python_runtime_adapter(adapter_path: str) -> bool:return not adapter_path.startswith("sie_server_rust.")+def _engine_exit_code(adapter: ModelAdapter) -> int | None:+ """Return the adapter's engine exit code, treating a failing probe as a running engine."""+ try:+ exit_code = adapter.engine_exit_code()+ except Exception:+ logger.exception("adapter.engine_exit_code() raised; treating the engine as running")+ return None+ if isinstance(exit_code, bool) or not isinstance(exit_code, int):+ return None+ return exit_code++def _adapter_load_required_bytes(adapter: ModelAdapter, memory_manager: MemoryManager) -> int | None:"""Return an adapter-provided load-headroom estimate, if any."""stats = memory_manager.get_stats()@@ -313,12 +329,17 @@ class ModelRegistry:self._sync_lifecycle_depth = 0self._loading: set[str] = set() # Models currently being loadedself._unloading: set[str] = set() # Models currently being unloaded- # Terminal-failed state. Populated by ``_load_model_background`` when a- # load raises; surfaces non-retryable ``MODEL_LOAD_FAILED`` errors via- # the API and short-circuits hot retry loops (see ``start_load_async``).- # Cleared on successful load, explicit ``clear_failure``, or hot-reload- # of the model config.+ # Failed state. Populated by ``_load_model_background`` when a load+ # raises and by the engine-exit check when a loaded model's engine+ # dies; surfaces ``MODEL_LOAD_FAILED`` errors via the API and+ # short-circuits hot retry loops (see ``start_load_async``). Cleared+ # through ``clear_failure`` on a successful load or a config change.self._failed: dict[str, LoadFailure] = {}+ # Consecutive engine exits per model. Survives the reload that clears+ # ``_failed``, so an engine that dies after every load still backs off+ # and eventually fails permanently; reset by a config change or by an+ # engine that stayed up for ``_ENGINE_STABLE_UPTIME_S``.+ self._engine_exits: dict[str, int] = {}# Background memory monitorself._monitor_task: asyncio.Task[None] | None = None@@ -1000,7 +1021,8 @@ class ModelRegistry:cannot exist.Raises:- RuntimeError: Naming the declared width and the visible devices.+ ModelConfigurationError: Naming the declared width and the visible+ devices."""if width <= len(self._devices):return@@ -1009,7 +1031,7 @@ class ModelRegistry:f"{len(self._devices)} device(s) ({self._devices}). The declared width and the ""visible devices must agree.")- raise RuntimeError(msg)+ raise ModelConfigurationError(msg)def _claimed_members(self, name: str) -> list[str]:"""Devices this model holds exclusively, anchor first, or empty."""@@ -1079,9 +1101,9 @@ class ModelRegistry:the next request can trigger a fresh attempt.Permanent failure classes (``GATED``, ``NOT_FOUND``,- ``DEPENDENCY``, ``UNKNOWN``) have ``cooldown_s=None`` and stay- sticky until :meth:`clear_failure` is invoked (e.g. by hot- reload).+ ``DEPENDENCY``, ``CONFIG``), and transient failures that exhausted+ their attempt budget, have ``cooldown_s=None`` and stay sticky until+ :meth:`clear_failure` is invoked (e.g. by a config change)."""failure = self._failed.get(name)if failure is None:@@ -1100,12 +1122,19 @@ class ModelRegistry:def clear_failure(self, name: str) -> bool:"""Drop any recorded failure for ``name``.- Returns True if a record existed and was removed. Used by hot- reload (a config change is operator intent that may have fixed- the underlying issue) and by successful loads.+ Returns True if a record existed and was removed. Called on every+ successful load and on every config change for the model (a config+ change is operator intent that may have fixed the underlying issue).+ An expired cooldown keeps the record, because its attempt count+ drives the next cooldown."""return self._failed.pop(name, None) is not None+ def _clear_config_failures(self, name: str) -> None:+ """Forget every failure recorded against ``name``'s previous config."""+ self._engine_exits.pop(name, None)+ self.clear_failure(name)+def _bind_lifecycle_loop(self) -> asyncio.AbstractEventLoop:"""Bind every asynchronous registry lifecycle operation to one loop."""loop = asyncio.get_running_loop()@@ -1405,8 +1434,7 @@ class ModelRegistry:self._loaded[name] = loadedself._register_across_group(name, loaded)- # Clear any stale failure record from a prior attempt.- self._failed.pop(name, None)+ self.clear_failure(name)load_outcome = "success"return loaded.adapterexcept ModelLoadTimeoutError as exc:@@ -1631,6 +1659,8 @@ class ModelRegistry:# would strand every card it reserved.if load_outcome != "success":self._release_device_claims(name)+ else:+ self.clear_failure(name)worker_telemetry().model_load_completed(model=name,duration_s=time.monotonic() - load_start,@@ -1703,8 +1733,8 @@ class ModelRegistry:On success any previously-recorded :class:`LoadFailure` for ``name``is cleared. On failure the exception is classified via:func:`classify_load_error` and recorded into ``self._failed`` so- the API surface can return a non-retryable- ``MODEL_LOAD_FAILED`` and the SDK stops hammering the loader.+ the API surface can return ``MODEL_LOAD_FAILED`` and the SDK stops+ hammering the loader.Args:name: Model name.@@ -1713,9 +1743,7 @@ class ModelRegistry:try:await self.load_async(name, device)logger.info("Background model load completed: %s", name)- # Successful load clears any prior failure record (e.g. a- # transient OOM that has since been resolved by eviction).- self._failed.pop(name, None)+ self.clear_failure(name)except (KeyboardInterrupt, SystemExit, asyncio.CancelledError):# Operator-initiated shutdown / task cancellation must NOT# be recorded as a load failure — that would leave the@@ -1736,17 +1764,19 @@ class ModelRegistry:# For normal loads, load_async already discarded, so this is a no-op.self._loading.discard(name)- def _record_load_failure(self, name: str, exc: BaseException) -> None:+ def _record_load_failure(self, name: str, exc: BaseException, *, attempts: int | None = None) -> None:"""Classify ``exc`` and record a :class:`LoadFailure` for ``name``.- Increments ``attempts`` if a failure is already on file. Emits a- WARNING-level log with structured fields so operators see the- actionable hint immediately rather than waiting for the SDK's- retry budget to elapse.+ Increments ``attempts`` if a failure is already on file, unless the+ caller supplies the count, which doubles a transient class's cooldown+ and, past the attempt budget, makes the failure permanent. Emits a+ log with structured fields so operators see the actionable hint+ immediately rather than waiting for the SDK's retry budget to elapse."""- classification = classify_load_error(exc)- previous = self._failed.get(name)- attempts = (previous.attempts + 1) if previous is not None else 1+ if attempts is None:+ previous = self._failed.get(name)+ attempts = (previous.attempts + 1) if previous is not None else 1+ classification = classify_load_error(exc, attempts=attempts)message = f"{type(exc).__name__}: {exc}"failure = LoadFailure(error_class=classification.error_class,@@ -1771,12 +1801,13 @@ class ModelRegistry:extra={"gated_model": True, "model": name},)else:- logger.exception(- "Background model load failed: %s (class=%s, attempts=%d, cooldown=%s)",+ logger.error(+ "Model load failure recorded: %s (class=%s, attempts=%d, cooldown=%s)",name,classification.error_class.value,attempts,"permanent" if classification.cooldown_s is None else f"{classification.cooldown_s:.0f}s",+ exc_info=exc,)def unload(self, name: str, *, reason: str = "manual") -> None:@@ -1848,9 +1879,9 @@ class ModelRegistry:``OOM`` is no longer relevant) and after device-level recoveryevents. Returns the number of records cleared.- Permanent classes (``GATED``, ``DEPENDENCY``, ``NOT_FOUND``,- ``UNKNOWN``) are never cleared by this helper — those require- operator intent (config update or explicit ``clear_failure``).+ Other classes are never cleared by this helper: transient ones wait+ out their cooldown, and permanent ones require operator intent (a+ config update, which calls ``clear_failure``)."""cleared = 0for name, failure in list(self._failed.items()):@@ -2310,7 +2341,7 @@ class ModelRegistry:if self._model_filter is not None:self._model_filter.discard(model_id)self._model_dirs.pop(model_id, None)- self._failed.pop(model_id, None)+ self._clear_config_failures(model_id)self._config_version += 1def _add_config_entry(self, config: ModelConfig, model_dir: Path | None = None) -> None:@@ -2367,7 +2398,7 @@ class ModelRegistry:# broken adapter option). Clear any sticky failure so the next# request retries with the new config.for name in expanded_configs:- self._failed.pop(name, None)+ self._clear_config_failures(name)self._config_version += 1# The config for an already-pinned model may have just arrived at runtime# (default Helm workers receive configs via the sidecar after a pin was@@ -2438,7 +2469,7 @@ class ModelRegistry:for name in new_configs:self._model_dirs[name] = model_dirfor name in invalidated:- self._failed.pop(name, None)+ self._clear_config_failures(name)self._config_version += 1self._refresh_worker_metric_catalog()@@ -2856,11 +2887,46 @@ class ModelRegistry:await self._hot_reloader.stop()self._hot_reloader = None+ async def _reap_exited_engines(self) -> None:+ """Unload every loaded model whose engine process has exited.++ The exit is recorded as a transient ``ENGINE`` failure, so the model+ reports ``failed`` with the exit code while the cooldown runs and the+ first request after it loads the model again. The attempt count is+ the number of consecutive exits, so an engine that dies after every+ load backs off and eventually fails permanently. Each model is+ claimed in the same step as its probe and unloaded through the+ ordinary drain-then-teardown path, one at a time, without holding+ ``_load_lock``.+ """+ for name in list(self._loaded):+ loaded = self._loaded.get(name)+ if loaded is None or name in self._unloading:+ continue+ exit_code = _engine_exit_code(loaded.adapter)+ if exit_code is None:+ continue+ info = self._memory_manager_for_model(name).get_model_info(name)+ stayed_up = info is not None and time.monotonic() - info.loaded_at >= _ENGINE_STABLE_UPTIME_S+ claimed = self._begin_unload(name)+ if claimed is None:+ continue+ exits = 1 if stayed_up else self._engine_exits.get(name, 0) + 1+ self._engine_exits[name] = exits+ error = EngineExitedError(f"Model '{name}' engine process exited with code {exit_code} after load")+ logger.error("%s; unloading it so the next request after the cooldown reloads it", error)+ self._record_load_failure(name, error, attempts=exits)+ try:+ await self._finish_unload(name, claimed, reason="other")+ except Exception:+ logger.exception("Unloading model '%s' after its engine exited failed", name)+async def _memory_monitor_loop(self) -> None:- """Background task that monitors memory pressure and evicts LRU models."""+ """Background task that reaps exited engines and evicts LRU models under memory pressure."""while self._monitor_running:try:await asyncio.sleep(self._memory_config.memory_check_interval_s)+ await self._reap_exited_engines()# Quick check without lockpressured_managers = [manager for manager in self._memory_managers.values() if manager.check_pressure()]diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 5b6a96f98..1ebc61dac 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -4,6 +4,7 @@ import asyncioimport loggingimport osimport tempfile+import timefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Final@@ -661,7 +662,8 @@ class QueueExecutor:- ``ready``: continue processing- ``loading_started``: progress-ACK and recheck (this call triggered a new load)- ``loading_in_progress``: progress-ACK and recheck with a longer delay- - ``retry_later``: NAK with base delay (unknown error path)+ - ``retry_later``: NAK with base delay (unknown model, or a transient+ load failure whose cooldown is still running)- ``failed``: TERMINAL — dead-letter as ``MODEL_LOAD_FAILED`` (do NOTrecheck). Emitted when the registry holds a PERMANENT``LoadFailure`` (``cooldown=permanent``).@@ -676,9 +678,10 @@ class QueueExecutor:*permanent* classes only, using the SAME ``get_failure().is_permanent``classification as the direct-HTTP ``check_not_failed`` gate and theModal lane's ``worker_runtime._terminal_load_failure``. Transient- in-cooldown classes (OOM / NETWORK / TIMEOUT) are intentionally NOT- terminal — they stay ``loading_in_progress`` so the caller retries- after the short cooldown.+ failures are not terminal: while their cooldown runs they report+ ``retry_later``, so the sidecar NAKs the item with a delay and it is+ redelivered, possibly to a worker that has the model loaded, instead+ of being held on this worker for the whole cooldown."""if not self._registry.has_model(model_id):return "retry_later"@@ -693,6 +696,9 @@ class QueueExecutor:if self._registry.is_loading(model_id):return "loading_in_progress"+ if failure is not None and failure.in_cooldown(time.monotonic()):+ return "retry_later"+try:started = await self._registry.start_load_async(model_id, self._registry.device)except KeyError:@@ -713,6 +719,8 @@ class QueueExecutor:failure = self._registry.get_failure(model_id)if failure is not None and failure.is_permanent:return "failed"+ if failure is not None and failure.in_cooldown(time.monotonic()):+ return "retry_later"return "loading_in_progress"# -- Handshake-driven model descriptor --------------------------------diff --git a/packages/sie_server/tests/core/test_load_error_classification.py b/packages/sie_server/tests/core/test_load_error_classification.pynew file mode 100644index 000000000..f0608bc6c--- /dev/null+++ b/packages/sie_server/tests/core/test_load_error_classification.py@@ -0,0 +1,365 @@+"""Load failures are classified by cause, with real exception types from the locked libraries."""++from __future__ import annotations++import errno+import socket+from pathlib import Path+from unittest.mock import patch++import boto3.exceptions+import botocore.exceptions+import httpx+import pytest+import requests+import s3transfer.exceptions+from huggingface_hub import HfApi+from huggingface_hub.errors import (+ DisabledRepoError,+ EntryNotFoundError,+ GatedRepoError,+ HfHubHTTPError,+ LocalEntryNotFoundError,+ OfflineModeIsEnabled,+ RepositoryNotFoundError,+ RevisionNotFoundError,+)+from sie_sdk.cache import CacheConfig, _download_from_huggingface+from sie_sdk.exceptions import GatedModelError+from sie_server.adapters.sglang import _server as sglang_server+from sie_server.core.load_errors import (+ MAX_COOLDOWN_S,+ MAX_TRANSIENT_ATTEMPTS,+ DevicePlacementError,+ EngineExitedError,+ EngineStartupError,+ LoadErrorClass,+ ModelConfigurationError,+ ModelLoadTimeoutError,+ classify_load_error,+ cooldown_for,+)+from sie_server.core.loader import reject_unknown_loadtime_options+++def _response(status: int) -> requests.Response:+ response = requests.Response()+ response.status_code = status+ response.url = "https://huggingface.co/api/models/org/model"+ return response+++def _hub_error(status: int) -> HfHubHTTPError:+ return HfHubHTTPError(f"{status} error", response=_response(status))+++def _aws_error(code: str, status: int) -> botocore.exceptions.ClientError:+ return botocore.exceptions.ClientError(+ {"Error": {"Code": code, "Message": code}, "ResponseMetadata": {"HTTPStatusCode": status}},+ "GetObject",+ )+++def _httpx_status_error(status: int) -> httpx.HTTPStatusError:+ request = httpx.Request("GET", "https://example.com/weights")+ return httpx.HTTPStatusError(f"{status} error", request=request, response=httpx.Response(status, request=request))+++def _caused_by(outer: BaseException, cause: BaseException) -> BaseException:+ outer.__cause__ = cause+ return outer+++def _raised_while_handling(outer: BaseException, context: BaseException) -> BaseException:+ try:+ try:+ raise context+ except type(context):+ raise outer # noqa: B904+ except type(outer) as raised:+ return raised+++TRANSIENT_CASES: list[tuple[str, BaseException, LoadErrorClass]] = [+ ("hub 408", _hub_error(408), LoadErrorClass.NETWORK),+ ("hub 429", _hub_error(429), LoadErrorClass.NETWORK),+ ("hub 500", _hub_error(500), LoadErrorClass.NETWORK),+ ("hub 502", _hub_error(502), LoadErrorClass.NETWORK),+ ("hub 503", _hub_error(503), LoadErrorClass.NETWORK),+ ("hub 504", _hub_error(504), LoadErrorClass.NETWORK),+ ("s3 slowdown", _aws_error("SlowDown", 503), LoadErrorClass.NETWORK),+ ("aws throttling on 400", _aws_error("Throttling", 400), LoadErrorClass.NETWORK),+ ("aws request timeout on 400", _aws_error("RequestTimeout", 400), LoadErrorClass.NETWORK),+ ("s3 internal error", _aws_error("InternalError", 500), LoadErrorClass.NETWORK),+ (+ "botocore endpoint connection",+ botocore.exceptions.EndpointConnectionError(endpoint_url="https://s3.amazonaws.com"),+ LoadErrorClass.NETWORK,+ ),+ (+ "botocore connect timeout",+ botocore.exceptions.ConnectTimeoutError(endpoint_url="https://s3.amazonaws.com"),+ LoadErrorClass.NETWORK,+ ),+ (+ "botocore read timeout",+ botocore.exceptions.ReadTimeoutError(endpoint_url="https://s3.amazonaws.com"),+ LoadErrorClass.NETWORK,+ ),+ (+ "botocore connection closed",+ botocore.exceptions.ConnectionClosedError(endpoint_url="https://s3.amazonaws.com"),+ LoadErrorClass.NETWORK,+ ),+ (+ "boto3 retries exceeded",+ boto3.exceptions.RetriesExceededError(+ botocore.exceptions.EndpointConnectionError(endpoint_url="https://s3.amazonaws.com")+ ),+ LoadErrorClass.NETWORK,+ ),+ (+ "s3transfer retries exceeded",+ s3transfer.exceptions.RetriesExceededError(_aws_error("SlowDown", 503)),+ LoadErrorClass.NETWORK,+ ),+ ("requests connection", requests.exceptions.ConnectionError("connection refused"), LoadErrorClass.NETWORK),+ ("requests read timeout", requests.exceptions.ReadTimeout("read timed out"), LoadErrorClass.NETWORK),+ ("requests chunked", requests.exceptions.ChunkedEncodingError("connection broken"), LoadErrorClass.NETWORK),+ ("httpx connect", httpx.ConnectError("connection refused"), LoadErrorClass.NETWORK),+ ("httpx read timeout", httpx.ReadTimeout("read timed out"), LoadErrorClass.NETWORK),+ ("httpx 503", _httpx_status_error(503), LoadErrorClass.NETWORK),+ ("builtin connection", ConnectionResetError("reset by peer"), LoadErrorClass.NETWORK),+ ("builtin timeout", TimeoutError("socket read timeout"), LoadErrorClass.NETWORK),+ ("dns", socket.gaierror(socket.EAI_NONAME, "Name or service not known"), LoadErrorClass.NETWORK),+ ("enospc", OSError(errno.ENOSPC, "No space left on device"), LoadErrorClass.STORAGE),+ ("edquot", OSError(errno.EDQUOT, "Disk quota exceeded"), LoadErrorClass.STORAGE),+ (+ "native io error text",+ RuntimeError("Data processing error: No space left on device (os error 28)"),+ LoadErrorClass.STORAGE,+ ),+ ("engine crash", sglang_server.startup_failure_error(None, crash_exit_code=1), LoadErrorClass.ENGINE),+ ("engine exit", EngineExitedError("process exited with code -9"), LoadErrorClass.ENGINE),+ ("port in use", OSError(errno.EADDRINUSE, "Address already in use"), LoadErrorClass.ENGINE),+ ("placement", DevicePlacementError("no free block"), LoadErrorClass.PLACEMENT),+ (+ "load timeout",+ ModelLoadTimeoutError(model="m", stage="load", elapsed_s=10.0, timeout_s=5.0),+ LoadErrorClass.TIMEOUT,+ ),+ ("cuda oom", RuntimeError("CUDA out of memory. Tried to allocate 2 GiB"), LoadErrorClass.OOM),+ ("unrecognised", RuntimeError("some unrelated failure"), LoadErrorClass.UNKNOWN),+ ("hub 400", _hub_error(400), LoadErrorClass.UNKNOWN),+ ("httpx 404", _httpx_status_error(404), LoadErrorClass.UNKNOWN),+ ("s3 access denied", _aws_error("AccessDenied", 403), LoadErrorClass.UNKNOWN),+]++PERMANENT_CASES: list[tuple[str, BaseException, LoadErrorClass]] = [+ ("sdk gated", GatedModelError("org/private", RuntimeError("401 unauthorized")), LoadErrorClass.GATED),+ ("hub gated", GatedRepoError("gated", response=_response(403)), LoadErrorClass.GATED),+ ("hub 401", _hub_error(401), LoadErrorClass.GATED),+ ("hub repo missing", RepositoryNotFoundError("missing", response=_response(404)), LoadErrorClass.NOT_FOUND),+ ("hub revision missing", RevisionNotFoundError("missing", response=_response(404)), LoadErrorClass.NOT_FOUND),+ ("hub file missing", EntryNotFoundError("missing", response=_response(404)), LoadErrorClass.NOT_FOUND),+ ("hub repo disabled", DisabledRepoError("disabled", response=_response(403)), LoadErrorClass.NOT_FOUND),+ ("import", ImportError("Gemma3TextModel not found in transformers"), LoadErrorClass.DEPENDENCY),+ ("module", ModuleNotFoundError("no module named transformers"), LoadErrorClass.DEPENDENCY),+ ("configuration", ModelConfigurationError("has no mlx_repo set"), LoadErrorClass.CONFIG),+ ("validation", ValueError("pooling_method is not a load-time option"), LoadErrorClass.CONFIG),+ ("hub offline", OfflineModeIsEnabled("offline mode is enabled"), LoadErrorClass.CONFIG),+ (+ "offline and not cached",+ LocalEntryNotFoundError("Cannot find an appropriate cached snapshot folder"),+ LoadErrorClass.CONFIG,+ ),+]++CHAINED_CASES: list[tuple[str, BaseException, LoadErrorClass]] = [+ (+ "hub download without a cached snapshot",+ _caused_by(+ LocalEntryNotFoundError("cannot find the requested files on the Hub or in the local cache"),+ requests.exceptions.ConnectionError("connection refused"),+ ),+ LoadErrorClass.NETWORK,+ ),+ (+ "hub outage without a cached snapshot",+ _caused_by(LocalEntryNotFoundError("cannot find the requested files"), _hub_error(503)),+ LoadErrorClass.NETWORK,+ ),+ (+ "sdk not-found wrapper",+ _caused_by(+ RuntimeError("Model 'org/model' not found."), RepositoryNotFoundError("missing", response=_response(404))+ ),+ LoadErrorClass.NOT_FOUND,+ ),+ (+ "port reservation",+ _caused_by(EngineStartupError("port 30000 is already in use"), OSError(errno.EADDRINUSE, "in use")),+ LoadErrorClass.ENGINE,+ ),+ (+ "typed wrapper wins over its cause",+ _caused_by(ModelLoadTimeoutError(model="m", stage="load", elapsed_s=1.0, timeout_s=1.0), ConnectionError("x")),+ LoadErrorClass.TIMEOUT,+ ),+ (+ "sdk gated wrapper wins over its 503 cause",+ _caused_by(GatedModelError("org/private", RuntimeError("503")), _hub_error(503)),+ LoadErrorClass.GATED,+ ),+ (+ "transient cause beats an untyped validation wrapper",+ _caused_by(ValueError("could not read config.json"), ConnectionError("connection reset")),+ LoadErrorClass.NETWORK,+ ),+ (+ "a nested validation error does not make an unrecognised failure permanent",+ _caused_by(RuntimeError("weights could not be read"), ValueError("invalid literal")),+ LoadErrorClass.UNKNOWN,+ ),+ (+ "implicit context",+ _raised_while_handling(RuntimeError("download failed"), OSError(errno.ENOSPC, "No space left on device")),+ LoadErrorClass.STORAGE,+ ),+]+++def _ids(cases: list[tuple[str, BaseException, LoadErrorClass]]) -> list[str]:+ return [case[0] for case in cases]+++class TestClassifyByCause:+ @pytest.mark.parametrize(("name", "exc", "expected"), TRANSIENT_CASES, ids=_ids(TRANSIENT_CASES))+ def test_transient_causes_retry_after_a_cooldown(+ self, name: str, exc: BaseException, expected: LoadErrorClass+ ) -> None:+ result = classify_load_error(exc)++ assert result.error_class is expected+ assert not result.is_permanent+ assert result.cooldown_s == cooldown_for(expected, 1)++ @pytest.mark.parametrize(("name", "exc", "expected"), PERMANENT_CASES, ids=_ids(PERMANENT_CASES))+ def test_configuration_and_identity_errors_stay_permanent(+ self, name: str, exc: BaseException, expected: LoadErrorClass+ ) -> None:+ result = classify_load_error(exc)++ assert result.error_class is expected+ assert result.is_permanent++ @pytest.mark.parametrize(("name", "exc", "expected"), CHAINED_CASES, ids=_ids(CHAINED_CASES))+ def test_wrapped_errors_are_classified_by_what_they_wrap(+ self, name: str, exc: BaseException, expected: LoadErrorClass+ ) -> None:+ assert classify_load_error(exc).error_class is expected++ def test_unknown_errors_get_a_long_but_bounded_cooldown(self) -> None:+ result = classify_load_error(RuntimeError("some unrelated failure"))++ assert result.error_class is LoadErrorClass.UNKNOWN+ assert result.cooldown_s == 600.0++ def test_a_self_referencing_chain_terminates(self) -> None:+ exc = RuntimeError("outer")+ inner = RuntimeError("inner")+ exc.__cause__ = inner+ inner.__cause__ = exc++ assert classify_load_error(exc).error_class is LoadErrorClass.UNKNOWN++ def test_an_unknown_load_time_option_stays_permanent(self) -> None:+ from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter++ with pytest.raises(ValueError, match="pooling_method") as caught:+ reject_unknown_loadtime_options(SGLangEmbeddingAdapter, {"pooling_method": "cls"}, model_name="org/embed")++ result = classify_load_error(caught.value)+ assert result.error_class is LoadErrorClass.CONFIG+ assert result.is_permanent++ def test_a_missing_mlx_repo_stays_permanent(self) -> None:+ from sie_server.adapters.mlx.generation import MLXGenerationAdapter++ with pytest.raises(RuntimeError, match="mlx_repo") as caught:+ MLXGenerationAdapter(model_name_or_path="Qwen/Qwen3.6-27B").load("mps")++ result = classify_load_error(caught.value)+ assert result.error_class is LoadErrorClass.CONFIG+ assert result.is_permanent++ def test_a_port_held_by_another_process_is_an_engine_startup_error(self) -> None:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as holder:+ holder.bind(("localhost", 0))+ port = holder.getsockname()[1]+ with pytest.raises(EngineStartupError, match="already in use") as caught:+ sglang_server.reserve_port(port)++ result = classify_load_error(caught.value)+ assert result.error_class is LoadErrorClass.ENGINE+ assert not result.is_permanent+++class TestHubDownloadFailures:+ """``snapshot_download`` rewrites fetch failures before the SDK cache wrapper sees them."""++ @pytest.mark.parametrize(+ ("api_error", "raised", "expected"),+ [+ (+ requests.exceptions.ConnectionError("connection refused"),+ LocalEntryNotFoundError,+ LoadErrorClass.NETWORK,+ ),+ (requests.exceptions.ReadTimeout("read timed out"), LocalEntryNotFoundError, LoadErrorClass.NETWORK),+ (_hub_error(429), LocalEntryNotFoundError, LoadErrorClass.NETWORK),+ (_hub_error(503), LocalEntryNotFoundError, LoadErrorClass.NETWORK),+ (OfflineModeIsEnabled("offline mode is enabled"), LocalEntryNotFoundError, LoadErrorClass.CONFIG),+ (_hub_error(401), GatedModelError, LoadErrorClass.GATED),+ (RepositoryNotFoundError("missing", response=_response(404)), RuntimeError, LoadErrorClass.NOT_FOUND),+ ],+ ids=["connection", "timeout", "429", "503", "offline", "401", "not-found"],+ )+ def test_the_class_follows_the_hub_error(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ api_error: BaseException,+ raised: type[BaseException],+ expected: LoadErrorClass,+ ) -> None:+ monkeypatch.delenv("HF_TOKEN", raising=False)+ config = CacheConfig(local_cache=tmp_path, cluster_cache=None, hf_fallback=True)++ with (+ patch("sie_sdk.cache._get_hf_ignore_patterns", return_value=[]),+ patch.object(HfApi, "repo_info", side_effect=api_error),+ pytest.raises(raised) as caught,+ ):+ _download_from_huggingface("org/model", config)++ assert classify_load_error(caught.value).error_class is expected+++class TestBackoff:+ def test_transient_cooldowns_double_up_to_the_cap(self) -> None:+ cooldowns = [cooldown_for(LoadErrorClass.NETWORK, attempts) for attempts in range(1, 8)]++ assert cooldowns == [30.0, 60.0, 120.0, 240.0, 480.0, 960.0, MAX_COOLDOWN_S]++ def test_a_transient_failure_becomes_permanent_after_the_attempt_budget(self) -> None:+ assert cooldown_for(LoadErrorClass.NETWORK, MAX_TRANSIENT_ATTEMPTS) == MAX_COOLDOWN_S+ assert cooldown_for(LoadErrorClass.NETWORK, MAX_TRANSIENT_ATTEMPTS + 1) is None+ assert classify_load_error(_hub_error(503), attempts=MAX_TRANSIENT_ATTEMPTS + 1).is_permanent++ @pytest.mark.parametrize(+ "error_class",+ [LoadErrorClass.GATED, LoadErrorClass.NOT_FOUND, LoadErrorClass.DEPENDENCY, LoadErrorClass.CONFIG],+ )+ def test_permanent_classes_have_no_cooldown(self, error_class: LoadErrorClass) -> None:+ assert cooldown_for(error_class, 1) is Nonediff --git a/packages/sie_server/tests/core/test_registry_engine_exit.py b/packages/sie_server/tests/core/test_registry_engine_exit.pynew file mode 100644index 000000000..1cdee194d--- /dev/null+++ b/packages/sie_server/tests/core/test_registry_engine_exit.py@@ -0,0 +1,326 @@+"""A loaded model whose engine process dies is unloaded, marked failed, and reloaded after the cooldown."""++from __future__ import annotations++import asyncio+import subprocess+import sys+import time+from collections.abc import Callable, Iterator+from contextlib import ExitStack+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+from sie_server.adapters.sglang import _server as sglang_server+from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.load_errors import (+ MAX_TRANSIENT_ATTEMPTS,+ EngineExitedError,+ LoadErrorClass,+ LoadFailure,+ cooldown_for,+)+from sie_server.core.memory import MemoryConfig+from sie_server.core.registry import _ENGINE_STABLE_UPTIME_S, ModelRegistry++MODEL = "test-model"+++def _make_config() -> ModelConfig:+ return ModelConfig(+ sie_id=MODEL,+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),+ profiles={+ "default": ProfileConfig(+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",+ max_batch_tokens=8192,+ )+ },+ )++[email protected](autouse=True)+def patch_ensure_model_cached() -> Iterator[MagicMock]:+ with patch("sie_sdk.cache.ensure_model_cached") as mock:+ mock.return_value = Path("/fake/cache/models--org--test")+ yield mock+++class FakeEngine:+ """A real child process standing in for an engine server."""++ def __init__(self) -> None:+ self.process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])++ def exit_code(self) -> int | None:+ return self.process.poll()++ def die(self) -> int:+ self.process.kill()+ return self.process.wait(timeout=10)++ def stop(self) -> None:+ if self.process.poll() is None:+ self.die()+++def engines() -> Iterator[list[FakeEngine]]:+ started: list[FakeEngine] = []+ yield started+ for engine in started:+ engine.stop()+++def _engine_adapter(engines: list[FakeEngine]) -> Callable[..., MagicMock]:+ def build(*_: object, **__: object) -> MagicMock:+ engine = FakeEngine()+ engines.append(engine)+ adapter = MagicMock()+ adapter.aclose_client = None+ adapter.memory_footprint.return_value = 1000+ adapter.requires_main_thread = False+ adapter.engine_exit_code.side_effect = engine.exit_code+ return adapter++ return build+++class _HeldWorker:+ """A running worker whose drain blocks until the test releases it."""++ def __init__(self) -> None:+ self.is_running = True+ self.stopping = asyncio.Event()+ self.release = asyncio.Event()++ async def stop(self) -> None:+ self.stopping.set()+ await self.release.wait()+ self.is_running = False+++def _registry(check_interval_s: float = 1.0) -> ModelRegistry:+ registry = ModelRegistry(memory_config=MemoryConfig(memory_check_interval_s=check_interval_s))+ registry.add_config(_make_config())+ return registry+++def _expire_cooldown(registry: ModelRegistry) -> None:+ failure = registry.get_failure(MODEL)+ assert failure is not None+ registry._failed[MODEL] = LoadFailure(+ error_class=failure.error_class,+ message=failure.message,+ attempts=failure.attempts,+ last_attempt_ts=time.monotonic() - 10_000,+ cooldown_s=failure.cooldown_s,+ )+++async def _wait_for(predicate: Callable[[], bool], timeout_s: float = 10.0) -> None:+ deadline = time.monotonic() + timeout_s+ while not predicate():+ if time.monotonic() > deadline:+ pytest.fail("condition not reached before the deadline")+ await asyncio.sleep(0.01)+++class TestEngineExitAfterLoad:+ async def test_a_live_engine_is_left_alone(self, engines: list[FakeEngine]) -> None:+ registry = _registry()+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_engine_adapter(engines)):+ await registry._load_model_background(MODEL, "cpu")++ await registry._reap_exited_engines()++ assert registry.is_loaded(MODEL)+ assert registry.get_failure(MODEL) is None++ async def test_a_dead_engine_is_unloaded_marked_failed_and_reloaded_after_the_cooldown(+ self, engines: list[FakeEngine]+ ) -> None:+ registry = _registry()+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_engine_adapter(engines)):+ await registry._load_model_background(MODEL, "cpu")+ first_adapter = registry.get(MODEL)+ exit_code = engines[0].die()++ await registry._reap_exited_engines()++ assert not registry.is_loaded(MODEL)+ first_adapter.unload.assert_called_once()+ failure = registry.get_failure(MODEL)+ assert failure is not None+ assert failure.error_class is LoadErrorClass.ENGINE+ assert not failure.is_permanent+ assert f"exited with code {exit_code}" in failure.message+ assert registry.is_failed(MODEL)+ assert await registry.start_load_async(MODEL, "cpu") is False++ _expire_cooldown(registry)+ assert await registry.start_load_async(MODEL, "cpu") is True+ await _wait_for(lambda: registry.is_loaded(MODEL))++ assert registry.get(MODEL) is not first_adapter+ assert registry.get_failure(MODEL) is None+ assert len(engines) == 2+ assert engines[1].exit_code() is None++ async def test_the_drain_of_a_dead_engine_runs_without_the_registry_lock(self, engines: list[FakeEngine]) -> None:+ registry = _registry()+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_engine_adapter(engines)):+ await registry._load_model_background(MODEL, "cpu")+ worker = _HeldWorker()+ registry._loaded[MODEL].worker = worker # type: ignore[assignment]+ engines[0].die()++ reaper = asyncio.create_task(registry._reap_exited_engines())+ try:+ await asyncio.wait_for(worker.stopping.wait(), timeout=10)++ assert registry.is_unloading(MODEL)+ async with asyncio.timeout(1):+ async with registry._get_load_lock():+ pass+ finally:+ worker.release.set()+ await asyncio.wait_for(reaper, timeout=10)+ assert not registry.is_loaded(MODEL)+ assert not registry.is_unloading(MODEL)+ failure = registry.get_failure(MODEL)+ assert failure is not None+ assert failure.error_class is LoadErrorClass.ENGINE++ async def test_the_memory_monitor_reaps_a_dead_engine(self, engines: list[FakeEngine]) -> None:+ registry = _registry(check_interval_s=0.01)+ with ExitStack() as stack:+ stack.enter_context(+ patch("sie_server.core.model_loader.load_adapter", side_effect=_engine_adapter(engines))+ )+ for manager in registry.memory_managers.values():+ stack.enter_context(patch.object(manager, "check_pressure", return_value=False))+ await registry._load_model_background(MODEL, "cpu")+ await registry.start_memory_monitor()+ try:+ engines[0].die()+ await _wait_for(lambda: not registry.is_loaded(MODEL))+ finally:+ await registry.stop_memory_monitor()++ failure = registry.get_failure(MODEL)+ assert failure is not None+ assert failure.error_class is LoadErrorClass.ENGINE++ async def test_a_failing_exit_probe_is_treated_as_a_running_engine(self, engines: list[FakeEngine]) -> None:+ registry = _registry()+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_engine_adapter(engines)):+ await registry._load_model_background(MODEL, "cpu")+ registry.get(MODEL).engine_exit_code.side_effect = OSError("probe failed")++ await registry._reap_exited_engines()++ assert registry.is_loaded(MODEL)+++class TestRepeatedEngineExits:+ """An engine that dies after every load backs off instead of reloading forever."""++ @staticmethod+ async def _load_and_crash(registry: ModelRegistry, engines: list[FakeEngine]) -> LoadFailure:+ if registry.get_failure(MODEL) is not None:+ _expire_cooldown(registry)+ assert await registry.start_load_async(MODEL, "cpu") is True+ await _wait_for(lambda: registry.is_loaded(MODEL))+ assert registry.get_failure(MODEL) is None+ engines[-1].die()+ await registry._reap_exited_engines()+ failure = registry.get_failure(MODEL)+ assert failure is not None+ return failure++ async def test_consecutive_exits_back_off_and_become_permanent(self, engines: list[FakeEngine]) -> None:+ registry = _registry()+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_engine_adapter(engines)):+ for exits in range(1, MAX_TRANSIENT_ATTEMPTS + 1):+ failure = await self._load_and_crash(registry, engines)+ assert failure.error_class is LoadErrorClass.ENGINE+ assert failure.attempts == exits+ assert failure.cooldown_s == cooldown_for(LoadErrorClass.ENGINE, exits)++ failure = await self._load_and_crash(registry, engines)++ assert failure.attempts == MAX_TRANSIENT_ATTEMPTS + 1+ assert failure.is_permanent+ _expire_cooldown(registry)+ assert await registry.start_load_async(MODEL, "cpu") is False++ async def test_an_engine_that_stayed_up_starts_counting_again(self, engines: list[FakeEngine]) -> None:+ registry = _registry()+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_engine_adapter(engines)):+ await self._load_and_crash(registry, engines)+ assert (await self._load_and_crash(registry, engines)).attempts == 2++ _expire_cooldown(registry)+ assert await registry.start_load_async(MODEL, "cpu") is True+ await _wait_for(lambda: registry.is_loaded(MODEL))+ info = registry._memory_manager_for_model(MODEL).get_model_info(MODEL)+ assert info is not None+ info.loaded_at -= _ENGINE_STABLE_UPTIME_S+ engines[-1].die()+ await registry._reap_exited_engines()++ failure = registry.get_failure(MODEL)+ assert failure is not None+ assert failure.attempts == 1++ async def test_a_config_change_resets_the_count(self, engines: list[FakeEngine]) -> None:+ registry = _registry()+ with patch("sie_server.core.model_loader.load_adapter", side_effect=_engine_adapter(engines)):+ await self._load_and_crash(registry, engines)+ await self._load_and_crash(registry, engines)++ registry.add_config(_make_config())+ assert registry.get_failure(MODEL) is None++ assert (await self._load_and_crash(registry, engines)).attempts == 1+++class TestSGLangEngineExitProbe:+ """The SGLang adapters report their engine's exit through the typed error and the probe."""++ @staticmethod+ def _exited_process() -> subprocess.Popen[bytes]:+ process = subprocess.Popen([sys.executable, "-c", "raise SystemExit(3)"])+ process.wait(timeout=10)+ return process++ def test_the_embedding_adapter_reports_the_exit(self) -> None:+ from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter++ adapter = SGLangEmbeddingAdapter(model_name_or_path="org/embed", dense_dim=768)+ adapter._server_url = "http://localhost:30005"+ adapter._process = self._exited_process()++ assert adapter.engine_exit_code() == 3+ with pytest.raises(EngineExitedError, match="exited with code 3"):+ adapter._check_loaded()++ def test_the_generation_adapter_reports_the_exit(self) -> None:+ from sie_server.adapters.sglang.generation import SGLangGenerationAdapter++ adapter = SGLangGenerationAdapter(+ model_name_or_path="Qwen/Qwen3-4B-Instruct",+ max_seq_length=32768,+ served_model_name="Qwen/Qwen3-4B-Instruct",+ )+ adapter._process = self._exited_process()++ assert adapter.engine_exit_code() == 3+ with pytest.raises(EngineExitedError, match="exited with code 3"):+ adapter._check_engine_alive()++ def test_an_unloaded_adapter_reports_no_exit(self) -> None:+ assert sglang_server.engine_exit_code(None) is Nonediff --git a/packages/sie_server/tests/core/test_registry_failed_state.py b/packages/sie_server/tests/core/test_registry_failed_state.pyindex 5e43a58b4..804871540 100644--- a/packages/sie_server/tests/core/test_registry_failed_state.py+++ b/packages/sie_server/tests/core/test_registry_failed_state.py@@ -20,8 +20,10 @@ from sie_sdk.exceptions import GatedModelErrorfrom sie_server.adapters.sglang import _server as sglang_serverfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasksfrom sie_server.core.load_errors import (+ MAX_TRANSIENT_ATTEMPTS,LoadErrorClass,classify_load_error,+ cooldown_for,)from sie_server.core.registry import ModelRegistry@@ -102,10 +104,11 @@ class TestClassifyLoadError:assert result.error_class is LoadErrorClass.NETWORKassert result.cooldown_s is not None- def test_unknown_runtime_error_is_unknown_permanent(self) -> None:+ def test_unknown_runtime_error_is_unknown_with_a_bounded_cooldown(self) -> None:result = classify_load_error(RuntimeError("some unrelated failure"))assert result.error_class is LoadErrorClass.UNKNOWN- assert result.is_permanent+ assert not result.is_permanent+ assert result.cooldown_s is not None# ---------------------------------------------------------------------------@@ -229,3 +232,26 @@ class TestRegistryFailedState:# Re-add a (possibly fixed) config.registry_with_model.add_config(_make_config(name="test-model"))assert not registry_with_model.is_failed("test-model")++ async def test_repeated_transient_failures_back_off_then_become_permanent(+ self, registry_with_model: ModelRegistry+ ) -> None:+ cooldowns = []+ for _ in range(MAX_TRANSIENT_ATTEMPTS):+ registry_with_model._record_load_failure("test-model", ConnectionError("dns failure"))+ failure = registry_with_model.get_failure("test-model")+ assert failure is not None+ cooldowns.append(failure.cooldown_s)++ assert cooldowns == [cooldown_for(LoadErrorClass.NETWORK, n) for n in range(1, MAX_TRANSIENT_ATTEMPTS + 1)]+ assert cooldowns[0] < cooldowns[1] < cooldowns[2]+ assert not registry_with_model.get_failure("test-model").is_permanent++ registry_with_model._record_load_failure("test-model", ConnectionError("dns failure"))++ failure = registry_with_model.get_failure("test-model")+ assert failure is not None+ assert failure.error_class is LoadErrorClass.NETWORK+ assert failure.attempts == MAX_TRANSIENT_ATTEMPTS + 1+ assert failure.is_permanent+ assert await registry_with_model.start_load_async("test-model", "cpu") is Falsediff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.pyindex c43785956..009d83ad5 100644--- a/packages/sie_server/tests/test_queue_executor.py+++ b/packages/sie_server/tests/test_queue_executor.py@@ -338,9 +338,10 @@ class TestEnsureModelReady:reg.start_load_async.assert_not_called()@pytest.mark.asyncio- async def test_transient_failure_is_not_terminal(self) -> None:- """A TRANSIENT in-cooldown failure (OOM/NETWORK/TIMEOUT) stays- retryable — it must not be reported as terminal ``failed``.+ async def test_transient_failure_in_cooldown_is_retried_later(self) -> None:+ """A TRANSIENT in-cooldown failure is not terminal: the sidecar NAKs+ the item with a delay so it is redelivered, possibly to another+ worker, instead of dead-lettering it or holding it here."""from sie_server.core.load_errors import LoadErrorClass, LoadFailure@@ -354,7 +355,44 @@ class TestEnsureModelReady:)reg.start_load_async = AsyncMock(return_value=False)ex = QueueExecutor(reg)- assert await ex.ensure_model_ready("test/model") == "loading_in_progress"+ assert await ex.ensure_model_ready("test/model") == "retry_later"+ reg.start_load_async.assert_not_called()++ @pytest.mark.asyncio+ async def test_transient_failure_past_its_cooldown_starts_a_new_load(self) -> None:+ from sie_server.core.load_errors import LoadErrorClass, LoadFailure++ reg = _make_registry(loaded=False, loading=False)+ reg.get_failure.return_value = LoadFailure(+ error_class=LoadErrorClass.NETWORK,+ message="HfHubHTTPError: 503",+ attempts=2,+ last_attempt_ts=time.monotonic() - 1000.0,+ cooldown_s=60.0,+ )+ reg.start_load_async = AsyncMock(return_value=True)+ ex = QueueExecutor(reg)+ assert await ex.ensure_model_ready("test/model") == "loading_started"+ reg.start_load_async.assert_awaited_once_with("test/model", "cpu")++ @pytest.mark.asyncio+ async def test_transient_failure_recorded_mid_start_is_retried_later(self) -> None:+ from sie_server.core.load_errors import LoadErrorClass, LoadFailure++ reg = _make_registry(loaded=False, loading=False)+ reg.get_failure.side_effect = [+ None,+ LoadFailure(+ error_class=LoadErrorClass.NETWORK,+ message="ConnectionError: reset",+ attempts=1,+ last_attempt_ts=time.monotonic(),+ cooldown_s=30.0,+ ),+ ]+ reg.start_load_async = AsyncMock(return_value=False)+ ex = QueueExecutor(reg)+ assert await ex.ensure_model_ready("test/model") == "retry_later"@pytest.mark.asyncioasync def test_permanent_failure_recorded_mid_start_returns_failed(self) -> None:diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex 6982098ee..27ff86f63 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -204,8 +204,10 @@ pub enum ReadinessState {/// Terminal, non-retryable load failure. The Python executor/// reports this when the registry holds a PERMANENT `LoadFailure`/// (`cooldown=permanent`: `GATED` / `NOT_FOUND` / `DEPENDENCY` /- /// `UNKNOWN`) — the same classification used by the gateway- /// readiness gate. It exists+ /// `CONFIG`, or a transient failure that exhausted its attempt budget)+ /// — the same classification used by the gateway readiness gate. A+ /// transient failure still in its cooldown is reported as `RetryLater`+ /// instead. It exists/// so the sidecar can DISTINGUISH "still loading" (retry) from/// "dead on arrival" (dead-letter): on `Failed` the dispatcher stops/// re-driving `EnsureModelReady` and publishes a typeddiff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.tsindex de379e9d7..d3c888734 100644--- a/packages/sie_ts_sdk/src/errors.ts+++ b/packages/sie_ts_sdk/src/errors.ts@@ -342,7 +342,8 @@ export class ModelLoadFailedError extends ServerError {readonly model: string | undefined;/*** Server-side classification: one of `GATED`, `OOM`, `DEPENDENCY`,- * `NOT_FOUND`, `NETWORK`, `UNKNOWN`. Use this to route to specific+ * `NOT_FOUND`, `CONFIG`, `NETWORK`, `STORAGE`, `ENGINE`, `TIMEOUT`,+ * `PLACEMENT`, `UNKNOWN`. Use this to route to specific* remediation paths (e.g. surface a "set HF_TOKEN" hint for `GATED`).*/readonly errorClass: string | undefined;