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
release: v0.3.1
github-actions[bot]8634c1b7bf80
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b4f80d3e4..baaffa1cb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,18 @@# Changelog+## v0.3.1++- chore(main): release 0.3.1+- fix(bge-m3): tighten score_mode validation, drop module docstring+- docs(sdk,server): clarify MODEL_LOAD_FAILED covers transient cooldowns+- fix(bge-m3): extend score support to bge_m3 and bge_m3_flag adapters+- fix(sdk,server): address CodeRabbit review on terminal load failures+- fix(siglip): cast pixel_values to model dtype on open_clip path+- chore(server): regenerate openapi.json with state and last_error fields+- feat(siglip): add Marqo/marqo-ecommerce-embeddings-B via open_clip backend+- fix(server): add terminal failed state to model registry (sie-test#85)+- feat(bge-m3): support /v1/score with dense/sparse/colbert/hybrid modes+## v0.3.0- chore(main): release 0.3.0diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex d603d131f..f22b1852c 100644--- a/deploy/helm/sie-cluster/Chart.yaml+++ b/deploy/helm/sie-cluster/Chart.yaml@@ -4,8 +4,8 @@ description: >-SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,and observabilitytype: application-version: 0.3.0 # x-release-please-version-appVersion: v0.3.0 # x-release-please-version+version: 0.3.1 # x-release-please-version+appVersion: v0.3.1 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex cfc6d4edd..9a24291f6 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.3.0"+version = "0.3.1"description = "SIE integration for ChromaDB"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.tomlindex 378ebb28f..505c444f7 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.3.0"+version = "0.3.1"description = "SIE integration for CrewAI"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.tomlindex 129e929e0..468945d7c 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.3.0"+version = "0.3.1"description = "SIE integration for DSPy"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.tomlindex d4c4187e2..5adab0d9f 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.3.0"+version = "0.3.1"description = "SIE integration for Haystack"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.tomlindex 81ad94877..0792f2383 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.3.0"+version = "0.3.1"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex a38ee3004..6cea93269 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.3.0"+version = "0.3.1"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex 47e5d29fd..ea8fcc4c5 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.3.0"+version = "0.3.1"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 3efa398b6..789064ddf 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.3.0"+version = "0.3.1"description = "SIE integration for Qdrant"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.jsonindex 53e802a6a..be97d8394 100644--- a/integrations/sie_ts_chroma/package.json+++ b/integrations/sie_ts_chroma/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-chroma",- "version": "0.3.0",+ "version": "0.3.1","description": "SIE embedding function for ChromaDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.jsonindex ae0bd6ecb..74ec47172 100644--- a/integrations/sie_ts_lancedb/package.json+++ b/integrations/sie_ts_lancedb/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-lancedb",- "version": "0.3.0",+ "version": "0.3.1","description": "SIE embedding function and reranker for LanceDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.jsonindex 094cab12c..f6a0266f1 100644--- a/integrations/sie_ts_langchain/package.json+++ b/integrations/sie_ts_langchain/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-langchain",- "version": "0.3.0",+ "version": "0.3.1","description": "SIE embeddings integration for LangChain.js","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.jsonindex cb2e37dea..a1cf3999a 100644--- a/integrations/sie_ts_llamaindex/package.json+++ b/integrations/sie_ts_llamaindex/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-llamaindex",- "version": "0.3.0",+ "version": "0.3.1","description": "SIE embeddings integration for LlamaIndex.TS","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.tomlindex 9c46bda12..60ec3d4f1 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.3.0"+version = "0.3.1"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lockindex 572612f4d..d84a525bd 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -2774,7 +2774,7 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"[[package]]name = "sie-gateway"-version = "0.3.0"+version = "0.3.1"dependencies = ["arc-swap","async-nats",diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex b981fa8d2..b14c342fa 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.3.0"+version = "0.3.1"edition = "2021"publish = falsediff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex 45abbd96f..1fb04e126 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.3.0"+version = "0.3.1"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_sdk/src/sie_sdk/__init__.py b/packages/sie_sdk/src/sie_sdk/__init__.pyindex 84b5ce229..726dce0fd 100644--- a/packages/sie_sdk/src/sie_sdk/__init__.py+++ b/packages/sie_sdk/src/sie_sdk/__init__.py@@ -13,6 +13,7 @@ For ColBERT/late interaction models, use the scoring module:from sie_sdk.client import (LoraLoadingError,+ ModelLoadFailedError,ModelLoadingError,PoolError,ProvisioningError,@@ -72,6 +73,7 @@ __all__ = ["Item","LoraLoadingError","ModelInfo",+ "ModelLoadFailedError","ModelLoadingError","ModelSummary","PoolError",diff --git a/packages/sie_sdk/src/sie_sdk/client/__init__.py b/packages/sie_sdk/src/sie_sdk/client/__init__.pyindex 9f7477a28..54df17cce 100644--- a/packages/sie_sdk/src/sie_sdk/client/__init__.py+++ b/packages/sie_sdk/src/sie_sdk/client/__init__.py@@ -6,6 +6,7 @@ Re-exports all client classes and errors for backwards compatibility.from sie_sdk.client.async_ import SIEAsyncClientfrom sie_sdk.client.errors import (LoraLoadingError,+ ModelLoadFailedError,ModelLoadingError,PoolError,ProvisioningError,@@ -18,6 +19,7 @@ from sie_sdk.client.sync import SIEClient__all__ = ["LoraLoadingError",+ "ModelLoadFailedError","ModelLoadingError","PoolError","ProvisioningError",diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex 4c5fbbd59..902d7cf2c 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -39,7 +39,7 @@ from sie_sdk.types import (SparseResult,)-from .errors import RequestError, ServerError+from .errors import ModelLoadFailedError, RequestError, ServerError# Content typesMSGPACK_CONTENT_TYPE = "application/msgpack"@@ -68,6 +68,11 @@ MODEL_LOADING_MAX_RETRIES = 60 # Max retries (60 * 5s = 5 min, matches provisioMODEL_LOADING_DEFAULT_DELAY_S = 5.0 # Default retry delay (model loads take longer than LoRA)MODEL_LOADING_ERROR_CODE = "MODEL_LOADING" # Error code from server+# Terminal load failure (non-retryable). Server returns this with HTTP 502+# and *no* Retry-After header so the SDK can short-circuit immediately+# instead of burning the MODEL_LOADING retry budget.+MODEL_LOAD_FAILED_ERROR_CODE = "MODEL_LOAD_FAILED"+# Resource-exhausted retry settings (server-side OOM recovery exhausted).# Default backoff sequence: 5 -> 10 -> 20 s (capped at 30s). Three attempts# is enough to cover the typical eviction + retry window without making@@ -281,6 +286,23 @@ def get_error_code(response: _HttpResponse) -> str | None:Returns:Error code string, or None if not found."""+ detail = get_error_detail(response)+ if detail is None:+ return None+ code = detail.get("code")+ return code if isinstance(code, str) else None+++def get_error_detail(response: _HttpResponse) -> dict[str, Any] | None:+ """Extract the full error-detail dict from a response body.++ Returns the nested ``error``/``detail`` object so callers can read+ auxiliary fields like ``error_class``, ``permanent``, ``attempts``+ (carried by ``MODEL_LOAD_FAILED`` responses) without re-parsing.++ Returns ``None`` if the body has no recognised error detail or it is+ not a dict.+ """try:if MSGPACK_CONTENT_TYPE in response.headers.get("content-type", ""):data = msgpack.unpackb(response.content, raw=False)@@ -290,17 +312,67 @@ def get_error_code(response: _HttpResponse) -> str | None:if "error" in data:error = data["error"]if isinstance(error, dict):- return error.get("code")- return None # error is a string, no code+ return error+ return Noneif "detail" in data:detail = data["detail"]if isinstance(detail, dict):- return detail.get("code")+ return detailexcept (ValueError, KeyError, TypeError):passreturn None+def raise_if_model_load_failed(response: _HttpResponse, model: str | None = None) -> None:+ """Raise :class:`ModelLoadFailedError` if the response is 502 ``MODEL_LOAD_FAILED``.++ Used by the SDK retry loops to short-circuit *before* checking the+ ``MODEL_LOADING`` retry budget. The server returns this on the very+ first request when it has a recorded terminal failure for the+ model, so the caller should fail fast instead of retrying for 5+ minutes.++ Args:+ response: HTTP response to inspect.+ model: Model name for inclusion in the raised error.++ Raises:+ ModelLoadFailedError: If the response is a 502 carrying the+ ``MODEL_LOAD_FAILED`` error code.+ """+ if response.status_code != 502:+ return+ detail = get_error_detail(response)+ if detail is None:+ return+ if detail.get("code") != MODEL_LOAD_FAILED_ERROR_CODE:+ return+ error_class = detail.get("error_class")+ permanent = bool(detail.get("permanent", True))+ attempts_raw = detail.get("attempts", 1)+ # Defensive: a malformed/buggy server payload (e.g. ``"attempts": "n/a"``,+ # ``"inf"``, ``-5``) must not crash the retry loop or expose nonsense+ # values upstream. Coerce best-effort, then clamp to a sane minimum of 1.+ # OverflowError (from float('inf')) and any other exception fall back+ # to 1 so malformed payloads always degrade safely.+ try:+ if isinstance(attempts_raw, int | float | str):+ attempts = int(attempts_raw)+ else:+ attempts = 1+ except (TypeError, ValueError, OverflowError):+ attempts = 1+ attempts = max(attempts, 1)+ message = str(detail.get("message") or f"Model '{model}' failed to load")+ raise ModelLoadFailedError(+ message,+ model=model,+ error_class=str(error_class) if error_class is not None else None,+ permanent=permanent,+ attempts=attempts,+ )++def handle_error(response: _HttpResponse) -> None:"""Handle error response from server.diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex 240fc7415..14c9440ca 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -86,6 +86,7 @@ from ._shared import (parse_extract_results,parse_gpu_param,parse_score_result,+ raise_if_model_load_failed,)from .errors import (LoraLoadingError,@@ -1049,6 +1050,9 @@ class SIEAsyncClient:await asyncio.sleep(actual_delay)continue+ # Short-circuit terminal load failures (sie-test#85).+ raise_if_model_load_failed(response, model=model)+# Handle 503 with LORA_LOADING or MODEL_LOADING - auto-retryif response.status_code == 503:from ._shared import get_error_code@@ -1516,6 +1520,9 @@ class SIEAsyncClient:await asyncio.sleep(actual_delay)continue+ # Short-circuit terminal load failures (sie-test#85).+ raise_if_model_load_failed(response, model=model)+# Handle 503 with MODEL_LOADING - auto-retryif response.status_code == 503:from ._shared import get_error_code@@ -1778,6 +1785,9 @@ class SIEAsyncClient:await asyncio.sleep(actual_delay)continue+ # Short-circuit terminal load failures (sie-test#85).+ raise_if_model_load_failed(response, model=model)+# Handle 503 with MODEL_LOADING - auto-retryif response.status_code == 503:from ._shared import get_error_codediff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.pyindex 934ab01d9..b60a99355 100644--- a/packages/sie_sdk/src/sie_sdk/client/errors.py+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py@@ -125,6 +125,62 @@ class ModelLoadingError(SIEError):self.model = model+class ModelLoadFailedError(ServerError):+ """Error when the server reports a recorded model-load failure.++ Distinct from :class:`ModelLoadingError` — this is raised on the+ first response (no retry budget consumed) when the server returns+ 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+ operator intervention is required (e.g. set ``HF_TOKEN``, accept+ the model license, upgrade ``transformers``). These carry+ ``permanent=True``.+ - **Transient classes in active cooldown** (``OOM``, ``NETWORK``)+ where the registry is suppressing retries for a finite window so+ the load loop does not hot-spin. These carry ``permanent=False``;+ the failure auto-expires and a subsequent request will trigger a+ fresh load attempt.++ Either way the server omits the ``Retry-After`` header so the SDK+ short-circuits its ``MODEL_LOADING`` retry budget and surfaces the+ error immediately. Callers can either catch :class:`ServerError`+ generally (preserves legacy 5xx handling) or catch+ :class:`ModelLoadFailedError` specifically and branch on+ :attr:`permanent` / :attr:`error_class` for tailored remediation.++ Attributes:+ model: The model that was requested.+ error_class: Server-side classification (``GATED``, ``OOM``,+ ``DEPENDENCY``, ``NOT_FOUND``, ``NETWORK``, ``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 server+ policy. ``True`` indicates a terminal failure that will not+ auto-clear — an operator must fix the underlying cause.+ ``False`` indicates a server-side cooldown over a transient+ condition; retrying after the cooldown window will succeed+ once the underlying issue resolves.+ attempts: How many load attempts the server has logged.+ """++ def __init__(+ self,+ message: str,+ *,+ model: str | None = None,+ error_class: str | None = None,+ permanent: bool = True,+ attempts: int = 1,+ ) -> None:+ super().__init__(message, code="MODEL_LOAD_FAILED", status_code=502)+ self.model = model+ self.error_class = error_class+ self.permanent = permanent+ self.attempts = attempts++class ResourceExhaustedError(ServerError):"""Error when the server has exhausted its OOM-recovery strategies.diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 81443de53..0773817d8 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -94,6 +94,7 @@ from ._shared import (parse_extract_results,parse_gpu_param,parse_score_result,+ raise_if_model_load_failed,)from .errors import (LoraLoadingError,@@ -1094,6 +1095,13 @@ class SIEClient:time.sleep(actual_delay)continue+ # Short-circuit terminal load failures BEFORE engaging the+ # MODEL_LOADING retry budget. The server emits 502+ # MODEL_LOAD_FAILED for permanent classes (gated repos,+ # missing deps) — retrying would waste 5 minutes on a+ # known-bad config (sie-test#85).+ raise_if_model_load_failed(response, model=model)+# Handle 503 with LORA_LOADING or MODEL_LOADING - auto-retryif response.status_code == 503:from ._shared import get_error_code@@ -1738,6 +1746,9 @@ class SIEClient:time.sleep(actual_delay)continue+ # Short-circuit terminal load failures (sie-test#85).+ raise_if_model_load_failed(response, model=model)+# Handle 503 with MODEL_LOADING - auto-retryif response.status_code == 503:from ._shared import get_error_code@@ -2092,6 +2103,9 @@ class SIEClient:time.sleep(actual_delay)continue+ # Short-circuit terminal load failures (sie-test#85).+ raise_if_model_load_failed(response, model=model)+# Handle 503 with MODEL_LOADING - auto-retryif response.status_code == 503:from ._shared import get_error_codediff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex 3c41db9e0..de700761a 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -33,8 +33,10 @@ DEFAULT_OUTPUT_DTYPE: OutputDType = "float32"# Output type optionsOutputType = Literal["dense", "sparse", "multivector"]-# Model state (for status messages)-ModelState = Literal["available", "loading", "loaded", "unloading"]+# Model state (for status messages).+# ``failed`` is the terminal branch added for non-retryable load failures+# (gated repos, missing dependencies, etc.). See sie-test#85 for context.+ModelState = Literal["available", "loading", "loaded", "unloading", "failed"]def np_to_dtype(arr: np.ndarray) -> DType:diff --git a/packages/sie_sdk/tests/client/test_model_load_failed.py b/packages/sie_sdk/tests/client/test_model_load_failed.pynew file mode 100644index 000000000..ca8d02549--- /dev/null+++ b/packages/sie_sdk/tests/client/test_model_load_failed.py@@ -0,0 +1,235 @@+"""Tests for the ``ModelLoadFailedError`` short-circuit (sie-test#85).++A 502 ``MODEL_LOAD_FAILED`` response must:+- raise :class:`ModelLoadFailedError` immediately on the first response+- never engage the ``MODEL_LOADING`` retry budget (no sleep, no retry)+- expose the structured ``error_class`` / ``permanent`` / ``attempts``+ fields from the server payload++The 503 ``MODEL_LOADING`` retry behavior must be unchanged.+"""++from __future__ import annotations++import json+from unittest.mock import AsyncMock, MagicMock, patch++import msgpack+import numpy as np+import pytest+from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk.client.async_ import _AioResponse+from sie_sdk.client.errors import ModelLoadFailedError, ModelLoadingError+++def _resp_load_failed(+ *,+ error_class: str = "GATED",+ permanent: bool = True,+ attempts: int = 1,+ message: str = "Model 'org/test' failed to load (GATED): missing HF_TOKEN",+) -> MagicMock:+ """Build a 502 MODEL_LOAD_FAILED response with no Retry-After."""+ resp = MagicMock()+ resp.status_code = 502+ resp.headers = {"content-type": "application/json"}+ resp.json.return_value = {+ "detail": {+ "code": "MODEL_LOAD_FAILED",+ "message": message,+ "error_class": error_class,+ "permanent": permanent,+ "attempts": attempts,+ }+ }+ return resp+++def _resp_model_loading() -> MagicMock:+ """503 MODEL_LOADING with a tiny Retry-After (sanity contrast)."""+ resp = MagicMock()+ resp.status_code = 503+ resp.headers = {"Retry-After": "0.01", "content-type": "application/json"}+ resp.json.return_value = {"detail": {"code": "MODEL_LOADING", "message": "loading"}}+ return resp+++def _resp_200_encode() -> MagicMock:+ resp = MagicMock()+ resp.status_code = 200+ resp.headers = {"content-type": "application/msgpack"}+ resp.content = msgpack.packb(+ {"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]},+ use_bin_type=True,+ )+ return resp+++# ---------------------------------------------------------------------------+# Sync client+# ---------------------------------------------------------------------------+++class TestSyncModelLoadFailed:+ def test_raises_immediately_on_first_response(self) -> None:+ """No retries are attempted; the error surfaces on the first call."""+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep") as mock_sleep,+ ):+ mock_client.return_value.post = MagicMock(side_effect=[_resp_load_failed()])+ client = SIEClient("http://localhost:8080")++ with pytest.raises(ModelLoadFailedError) as excinfo:+ client.encode("org/test", {"text": "hi"})++ assert excinfo.value.model == "org/test"+ assert excinfo.value.error_class == "GATED"+ assert excinfo.value.permanent is True+ assert excinfo.value.attempts == 1+ # Critical: no retry happened.+ assert mock_client.return_value.post.call_count == 1+ mock_sleep.assert_not_called()+ client.close()++ def test_does_not_consume_model_loading_budget(self) -> None:+ """A 502 must never be retried as if it were a 503 MODEL_LOADING."""+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep"),+ ):+ mock_client.return_value.post = MagicMock(+ side_effect=[_resp_load_failed(error_class="DEPENDENCY", permanent=True)]+ )+ client = SIEClient("http://localhost:8080")++ with pytest.raises(ModelLoadFailedError) as excinfo:+ client.encode("org/test", {"text": "hi"}, provision_timeout_s=300.0)++ assert excinfo.value.error_class == "DEPENDENCY"+ assert mock_client.return_value.post.call_count == 1+ client.close()++ def test_503_model_loading_still_retries(self) -> None:+ """Regression guard: the 502 short-circuit must not break 503 retries."""+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep"),+ ):+ mock_client.return_value.post = MagicMock(+ side_effect=[_resp_model_loading(), _resp_model_loading(), _resp_200_encode()]+ )+ client = SIEClient("http://localhost:8080")++ result = client.encode("bge-m3", {"text": "hi"})++ assert result["dense"].shape == (4,)+ assert mock_client.return_value.post.call_count == 3+ client.close()++ def test_modelloadfailed_distinct_from_modelloading(self) -> None:+ """The two error classes must not be confused in catch sites."""+ assert not issubclass(ModelLoadFailedError, ModelLoadingError)+ assert not issubclass(ModelLoadingError, ModelLoadFailedError)++ def test_score_endpoint_short_circuits(self) -> None:+ """The 502 short-circuit applies to /score too, not just /encode."""+ score_200 = MagicMock()+ score_200.status_code = 200+ score_200.headers = {"content-type": "application/msgpack"}+ score_200.content = msgpack.packb(+ {"model": "m", "scores": [{"item_id": "a", "score": 0.5, "rank": 0}]},+ use_bin_type=True,+ )++ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep") as mock_sleep,+ ):+ mock_client.return_value.post = MagicMock(side_effect=[_resp_load_failed()])+ client = SIEClient("http://localhost:8080")++ with pytest.raises(ModelLoadFailedError):+ client.score("org/test", query={"text": "q"}, items=[{"text": "d"}])++ assert mock_client.return_value.post.call_count == 1+ mock_sleep.assert_not_called()+ client.close()+++# ---------------------------------------------------------------------------+# Async client+# ---------------------------------------------------------------------------+++def _aio_load_failed(+ *,+ error_class: str = "GATED",+ permanent: bool = True,+ attempts: int = 1,+) -> object:+ return _AioResponse(+ 502,+ json.dumps(+ {+ "detail": {+ "code": "MODEL_LOAD_FAILED",+ "message": "Model 'org/test' failed to load",+ "error_class": error_class,+ "permanent": permanent,+ "attempts": attempts,+ }+ }+ ).encode(),+ {"content-type": "application/json"},+ )+++def _aio_model_loading() -> object:+ return _AioResponse(+ 503,+ json.dumps({"detail": {"code": "MODEL_LOADING", "message": "loading"}}).encode(),+ {"Retry-After": "0.01", "content-type": "application/json"},+ )+++def _aio_200_encode() -> object:+ return _AioResponse(+ 200,+ msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True),+ {"content-type": "application/msgpack"},+ )+++class TestAsyncModelLoadFailed:+ @pytest.mark.asyncio+ async def test_raises_immediately(self) -> None:+ with (+ patch("sie_sdk.client.async_.aiohttp.ClientSession"),+ patch("sie_sdk.client.async_.asyncio.sleep") as mock_sleep,+ ):+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(side_effect=[_aio_load_failed()])++ with pytest.raises(ModelLoadFailedError) as excinfo:+ await client.encode("org/test", {"text": "hi"})++ assert excinfo.value.error_class == "GATED"+ assert excinfo.value.permanent is True+ assert client._post.await_count == 1+ mock_sleep.assert_not_called()+ await client.close()++ @pytest.mark.asyncio+ async def test_503_model_loading_still_retries(self) -> None:+ with (+ patch("sie_sdk.client.async_.aiohttp.ClientSession"),+ patch("sie_sdk.client.async_.asyncio.sleep"),+ ):+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(side_effect=[_aio_model_loading(), _aio_model_loading(), _aio_200_encode()])++ result = await client.encode("bge-m3", {"text": "hi"})+ assert result["dense"].shape == (4,)+ assert client._post.await_count == 3+ await client.close()diff --git a/packages/sie_server/bundles/default.yaml b/packages/sie_server/bundles/default.yamlindex d839a6ddf..ff8914973 100644--- a/packages/sie_server/bundles/default.yaml+++ b/packages/sie_server/bundles/default.yaml@@ -71,6 +71,8 @@ deps:loguru: '>=0.7,<1'# donut, florence2timm: '>=0.9.0,<1.0'+ # siglip (Marqo/marqo-ecommerce-embeddings-B uses open_clip native loader)+ open-clip-torch: '>=2.24'# docling — composite-document parser (PDF/DOCX/HTML)docling: '>=2,<3'# Flash Attention 2 — CUDA only, prebuilt wheeldiff --git a/packages/sie_server/models/BAAI__bge-m3.yaml b/packages/sie_server/models/BAAI__bge-m3.yamlindex cdb4e49b7..8b33028ce 100644--- a/packages/sie_server/models/BAAI__bge-m3.yaml+++ b/packages/sie_server/models/BAAI__bge-m3.yaml@@ -13,7 +13,7 @@ tasks:dim: 250002multivector:dim: 1024- score: null+ score: {}extract: nullmax_sequence_length: 8192profiles:diff --git a/packages/sie_server/models/Marqo__marqo-ecommerce-embeddings-B.yaml b/packages/sie_server/models/Marqo__marqo-ecommerce-embeddings-B.yamlnew file mode 100644index 000000000..1d405caed--- /dev/null+++ b/packages/sie_server/models/Marqo__marqo-ecommerce-embeddings-B.yaml@@ -0,0 +1,28 @@+sie_id: Marqo/marqo-ecommerce-embeddings-B+hf_id: Marqo/marqo-ecommerce-embeddings-B+inputs:+ text: true+ image: true+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 64+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: float16+ adapter_path: sie_server.adapters.siglip:SiglipAdapter+ adapter_options:+ loadtime:+ backend: open_clip+ open_clip_model_id: hf-hub:Marqo/marqo-ecommerce-embeddings-B+ dense_dim: 768+ runtime:+ normalize: truediff --git a/packages/sie_server/models/google__embeddinggemma-300m.yaml b/packages/sie_server/models/google__embeddinggemma-300m.yamlindex dc40308ab..89e26f638 100644--- a/packages/sie_server/models/google__embeddinggemma-300m.yaml+++ b/packages/sie_server/models/google__embeddinggemma-300m.yaml@@ -1,5 +1,20 @@+# NOTE: ``google/embeddinggemma-300m`` is a *gated* HuggingFace repo. The+# server requires ``HF_TOKEN`` (with the model license accepted on the+# HF account) to load this model. Without it, the registry records a+# terminal ``GATED`` failure and the API returns ``MODEL_LOAD_FAILED``+# (502, no Retry-After) so the SDK does not loop.+#+# Architecture support: needs ``transformers>=4.56`` for+# ``Gemma3TextModel``. Older versions raise an unsupported-model error+# which the registry classifies as ``DEPENDENCY``.sie_id: google/embeddinggemma-300mhf_id: google/embeddinggemma-300m+# Track the default branch. Note: ``main`` is mutable on the Hub, so+# this does NOT guarantee bit-for-bit reproducibility — it merely names+# the branch we expect HuggingFace to resolve. For a true pin, replace+# this with an immutable commit SHA after verifying the new revision+# against ``test_google_embeddinggemma_300m_dense``.+hf_revision: maininputs:text: trueimage: false@@ -17,6 +32,11 @@ max_sequence_length: 2048profiles:default:max_batch_tokens: 16384+ # bfloat16 on CUDA matches the captured reference embedding in+ # ``test_all_models.py``. On CPU the adapter falls back to fp32+ # automatically (see pytorch_embedding adapter); the loaded model+ # still works, but numerical-equivalence tests should be gated on+ # CUDA availability if drift becomes an issue.compute_precision: bfloat16adapter_path: sie_server.adapters.pytorch_embedding:PyTorchEmbeddingAdapteradapter_options:diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 0f5ed96b8..8e5a78131 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -3,7 +3,7 @@"info": {"title": "SIE Server","description": "Search Inference Engine - GPU inference server for search workloads",- "version": "0.3.0"+ "version": "0.3.1"},"paths": {"/": {@@ -134,6 +134,9 @@"404": {"description": "Model not found"},+ "502": {+ "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry. See sie-test#85."+ },"503": {"description": "Model not loaded or service unavailable"},@@ -234,6 +237,9 @@"404": {"description": "Model not found"},+ "502": {+ "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry. See sie-test#85."+ },"503": {"description": "Model not loaded or service unavailable"},@@ -334,6 +340,9 @@"404": {"description": "Model not found"},+ "502": {+ "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry. See sie-test#85."+ },"503": {"description": "Model not loaded or service unavailable"},@@ -504,6 +513,9 @@"404": {"description": "Model not found"},+ "502": {+ "description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry. See sie-test#85."+ },"503": {"description": "Service unavailable"},@@ -847,6 +859,28 @@"type": "boolean","title": "Loaded"},+ "state": {+ "type": "string",+ "enum": [+ "available",+ "loading",+ "loaded",+ "unloading",+ "failed"+ ],+ "title": "State",+ "default": "available"+ },+ "last_error": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelLoadError"+ },+ {+ "type": "null"+ }+ ]+ },"max_sequence_length": {"anyOf": [{@@ -878,6 +912,35 @@"title": "ModelInfo","description": "Information about a model."},+ "ModelLoadError": {+ "properties": {+ "code": {+ "type": "string",+ "title": "Code"+ },+ "message": {+ "type": "string",+ "title": "Message"+ },+ "attempts": {+ "type": "integer",+ "title": "Attempts"+ },+ "permanent": {+ "type": "boolean",+ "title": "Permanent"+ }+ },+ "type": "object",+ "required": [+ "code",+ "message",+ "attempts",+ "permanent"+ ],+ "title": "ModelLoadError",+ "description": "Diagnostic detail for a recorded load failure.\n\nSurfaced in :class:`ModelInfo` when the registry has a sticky\nfailure for the model. Attributes mirror the server-side\n:class:`sie_server.core.load_errors.LoadFailure`."+ },"ModelsListResponse": {"properties": {"models": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex 6a576eb74..21a6f11f8 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.3.0"+version = "0.3.1"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }@@ -29,6 +29,8 @@ dependencies = [# Docling — composite-document parser (PDF/DOCX/HTML) for extract()"docling>=2,<3","loguru>=0.7,<1",+ # SigLIP (Marqo/marqo-ecommerce-embeddings-B native open_clip loader)+ "open-clip-torch>=2.24",# Image processing"pillow>=11,<12","numpy>=2,<3",diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py b/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.pyindex 425962225..b1d1285f5 100644--- a/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py@@ -26,6 +26,7 @@ from torch.nn import functionalfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecision+from sie_server.adapters.bge_m3_score_mixin import BGEM3ScoreMixinfrom sie_server.core.inference_output import EncodeOutput, SparseVectorfrom sie_server.types.inputs import Item@@ -35,16 +36,19 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-class BGEM3Adapter(BaseAdapter):+class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):"""Adapter for BAAI/bge-m3 model.This adapter uses direct PyTorch inference with Flash Attention 2for optimal performance (dense, sparse, and multi-vector outputs).++ Scoring (`/v1/score`) is supported via :class:`BGEM3ScoreMixin`, which+ composes scores from the encoder outputs (dense / sparse / multivector)."""spec = AdapterSpec(inputs=("text",),- outputs=("dense", "sparse", "multivector"),+ outputs=("dense", "sparse", "multivector", "score"),dense_dim=1024,sparse_dim=250002,multivector_dim=1024,diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3_flag/__init__.py b/packages/sie_server/src/sie_server/adapters/bge_m3_flag/__init__.pyindex eb688b6c1..2ba33c9d0 100644--- a/packages/sie_server/src/sie_server/adapters/bge_m3_flag/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/bge_m3_flag/__init__.py@@ -23,6 +23,7 @@ import torchfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecision+from sie_server.adapters.bge_m3_score_mixin import BGEM3ScoreMixinfrom sie_server.core.inference_output import EncodeOutput, SparseVectorif TYPE_CHECKING:@@ -35,16 +36,19 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-class BGEM3FlagAdapter(BaseAdapter):+class BGEM3FlagAdapter(BGEM3ScoreMixin, BaseAdapter):"""Adapter for BAAI/bge-m3 using FlagEmbedding library.This adapter uses the FlagEmbedding library's BGEM3FlagModel.For better performance, use BGEM3Adapter which uses Flash Attention 2.++ Scoring (`/v1/score`) is supported via :class:`BGEM3ScoreMixin`, which+ composes scores from the encoder outputs (dense / sparse / multivector)."""spec = AdapterSpec(inputs=("text",),- outputs=("dense", "sparse", "multivector"),+ outputs=("dense", "sparse", "multivector", "score"),dense_dim=1024,sparse_dim=250002,multivector_dim=1024,diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.pyindex e047a2ba6..0b72ab8d1 100644--- a/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py@@ -14,6 +14,7 @@ from sie_server.adapters._flash_base import FlashBaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.adapters._utils import validate_output_types+from sie_server.adapters.bge_m3_score_mixin import BGEM3ScoreMixinfrom sie_server.adapters.peft_lora_mixin import PEFTLoRAMixinfrom sie_server.core.inference_output import EncodeOutput, SparseVectorfrom sie_server.types.inputs import Item@@ -26,7 +27,7 @@ logger = logging.getLogger(__name__)_ERR_CPU_NOT_SUPPORTED = "BGEM3FlashAdapter requires CUDA. Use bge_m3 adapter for CPU."-class BGEM3FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):+class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):"""BGE-M3 adapter using Flash Attention 2 with variable-length sequences.This adapter eliminates padding waste by packing sequences and using@@ -41,7 +42,7 @@ class BGEM3FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):spec = AdapterSpec(inputs=("text",),- outputs=("dense", "sparse", "multivector"),+ outputs=("dense", "sparse", "multivector", "score"),dense_dim=1024,sparse_dim=250002,multivector_dim=1024,@@ -232,6 +233,8 @@ class BGEM3FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):return self._to_inference_output(results, output_types, len(items), is_query)+ # score() and score_pairs() are provided by BGEM3ScoreMixin.+def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:"""Build XLMRoberta-style position IDs for packed sequences.diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3_score_mixin.py b/packages/sie_server/src/sie_server/adapters/bge_m3_score_mixin.pynew file mode 100644index 000000000..5b286179a--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/bge_m3_score_mixin.py@@ -0,0 +1,283 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Any, ClassVar++import numpy as np++from sie_server.core.inference_output import ScoreOutput++if TYPE_CHECKING:+ from sie_server.core.inference_output import EncodeOutput+ from sie_server.types.inputs import Item+++class BGEM3ScoreMixin:+ """Adds BGE-M3 score()/score_pairs() to any adapter implementing encode().++ BGE-M3 supports four scoring modes composable from any of its encode+ outputs (dense / sparse / multivector). This mixin implements the modes+ once and is consumed by every BGE-M3 adapter (``bge_m3_flash``,+ ``bge_m3``, ``bge_m3_flag``) so they all expose the same ``/v1/score``+ semantics.++ Modes:+ - ``dense`` : cosine similarity between CLS-pooled, L2-normalized vectors.+ - ``sparse`` : ``Σ q_w * d_w`` over shared token ids (BGE-M3 paper /+ FlagEmbedding's ``compute_lexical_matching_score``).+ - ``colbert``: ColBERT-style MaxSim over the multi-vector projection,+ normalized by query length (matches FlagEmbedding's ``colbert_score``).+ - ``hybrid`` : weighted sum (default ``{dense: 0.4, sparse: 0.2, colbert: 0.4}``,+ override via ``options["score_weights"]``).++ Runtime-side companion to ``"score"`` being declared in+ :class:`AdapterSpec.outputs`; the class-level validator at+ :mod:`sie_server.adapters._base_adapter` only checks that ``score`` /+ ``score_pairs`` are overridden on the class — both come from this mixin.++ Subclasses must provide ``encode()`` and ``_check_loaded()`` (the latter+ is supplied by the standard adapter base classes). The TYPE_CHECKING+ stubs below let the type checker resolve ``self.encode`` / ``self._check_loaded``+ inside this module without affecting Python's runtime MRO — they only+ exist for the type checker, never as live attributes.+ """++ if TYPE_CHECKING:++ def encode(+ self,+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = ...,+ is_query: bool = ...,+ prepared_items: Any = ...,+ options: dict[str, Any] | None = ...,+ ) -> EncodeOutput: ...++ def _check_loaded(self) -> None: ...++ # Default hybrid weights from the BGE-M3 paper (Chen et al., 2024).+ _DEFAULT_HYBRID_WEIGHTS: ClassVar[dict[str, float]] = {"dense": 0.4, "sparse": 0.2, "colbert": 0.4}+ _VALID_SCORE_MODES: ClassVar[frozenset[str]] = frozenset({"dense", "sparse", "colbert", "hybrid"})+ _MODE_TO_OUTPUT: ClassVar[dict[str, str]] = {+ "dense": "dense",+ "sparse": "sparse",+ "colbert": "multivector",+ }++ # ------------------------------------------------------------------ public++ def score(+ self,+ query: Item,+ items: list[Item],+ *,+ instruction: str | None = None,+ options: dict[str, Any] | None = None,+ ) -> list[float]:+ """Score items against a query using bi-encoder similarity.++ Args:+ query: Query item.+ items: Document items to score.+ instruction: Optional instruction prepended to query and items.+ options: Runtime options. Recognized keys:+ ``score_mode``: one of+ ``"dense" | "sparse" | "colbert" | "hybrid"`` (default ``"dense"``).+ ``score_weights``: mapping+ ``{dense, sparse, colbert} -> float`` for hybrid mode.++ Returns:+ List of scores parallel to ``items``.+ """+ self._check_loaded()+ if not items:+ return []++ score_mode, weights = self._resolve_score_mode(options)+ output_types = self._output_types_for_mode(score_mode, weights)++ query_out = self.encode(+ [query],+ output_types=output_types,+ instruction=instruction,+ is_query=True,+ options=options,+ )+ items_out = self.encode(+ items,+ output_types=output_types,+ instruction=instruction,+ is_query=False,+ options=options,+ )++ return [self._compute_pair_score(query_out, 0, items_out, i, score_mode, weights) for i in range(len(items))]++ def score_pairs(+ self,+ queries: list[Item],+ docs: list[Item],+ *,+ instruction: str | None = None,+ options: dict[str, Any] | None = None,+ ) -> ScoreOutput:+ """Score parallel (query, doc) pairs in a single batched encode."""+ self._check_loaded()+ if len(queries) != len(docs):+ msg = f"score_pairs requires equal-length queries and docs, got {len(queries)} queries and {len(docs)} docs"+ raise ValueError(msg)+ if not queries:+ return ScoreOutput(scores=np.empty(0, dtype=np.float32))++ score_mode, weights = self._resolve_score_mode(options)+ output_types = self._output_types_for_mode(score_mode, weights)++ queries_out = self.encode(+ queries,+ output_types=output_types,+ instruction=instruction,+ is_query=True,+ options=options,+ )+ docs_out = self.encode(+ docs,+ output_types=output_types,+ instruction=instruction,+ is_query=False,+ options=options,+ )++ scores = np.asarray(+ [self._compute_pair_score(queries_out, i, docs_out, i, score_mode, weights) for i in range(len(queries))],+ dtype=np.float32,+ )+ return ScoreOutput(scores=scores)++ # ------------------------------------------------------------ option resolve++ def _resolve_score_mode(self, options: dict[str, Any] | None) -> tuple[str, dict[str, float]]:+ """Validate and resolve ``score_mode`` and ``score_weights`` from options."""+ opts = options or {}+ score_mode = opts.get("score_mode", "dense")+ # Validate type before membership (frozenset.__contains__ would raise+ # TypeError on unhashable inputs like list/dict, leaking a 500).+ if not isinstance(score_mode, str) or score_mode not in self._VALID_SCORE_MODES:+ msg = f"Invalid score_mode '{score_mode}'. Expected one of {sorted(self._VALID_SCORE_MODES)}."+ raise ValueError(msg)++ weights = dict(self._DEFAULT_HYBRID_WEIGHTS)+ override = opts.get("score_weights")+ if override is not None:+ if not isinstance(override, dict):+ msg = "score_weights must be a mapping of {dense, sparse, colbert} -> float"+ raise ValueError(msg)+ unknown = set(override) - set(self._DEFAULT_HYBRID_WEIGHTS)+ if unknown:+ msg = f"Unknown score_weights keys: {sorted(unknown)}. Allowed: dense, sparse, colbert"+ raise ValueError(msg)+ for key, value in override.items():+ # bool is a subclass of int — reject it explicitly to avoid silently+ # treating True/False as 1.0/0.0 weights.+ if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:+ msg = f"score_weights['{key}'] must be a non-negative number, got {value!r}"+ raise ValueError(msg)+ weights[key] = float(value)++ if score_mode == "hybrid":+ total = sum(weights.values())+ if total <= 0:+ msg = "score_weights for hybrid mode must contain at least one positive weight"+ raise ValueError(msg)++ return score_mode, weights++ def _output_types_for_mode(self, score_mode: str, weights: dict[str, float]) -> list[str]:+ """Resolve which encode outputs are needed for the requested score mode."""+ if score_mode == "hybrid":+ # Skip outputs whose weight is zero to save compute.+ return [self._MODE_TO_OUTPUT[mode] for mode in ("dense", "sparse", "colbert") if weights.get(mode, 0.0) > 0]+ return [self._MODE_TO_OUTPUT[score_mode]]++ # ------------------------------------------------------------------ similarity++ def _compute_pair_score(+ self,+ q_out: EncodeOutput,+ q_idx: int,+ d_out: EncodeOutput,+ d_idx: int,+ score_mode: str,+ weights: dict[str, float],+ ) -> float:+ """Compute a single (query, doc) score under the resolved mode."""+ if score_mode == "dense":+ return self._dense_sim(q_out, q_idx, d_out, d_idx)+ if score_mode == "sparse":+ return self._sparse_sim(q_out, q_idx, d_out, d_idx)+ if score_mode == "colbert":+ return self._colbert_sim(q_out, q_idx, d_out, d_idx)+ # hybrid+ score = 0.0+ if weights.get("dense", 0.0) > 0:+ score += weights["dense"] * self._dense_sim(q_out, q_idx, d_out, d_idx)+ if weights.get("sparse", 0.0) > 0:+ score += weights["sparse"] * self._sparse_sim(q_out, q_idx, d_out, d_idx)+ if weights.get("colbert", 0.0) > 0:+ score += weights["colbert"] * self._colbert_sim(q_out, q_idx, d_out, d_idx)+ return float(score)++ @staticmethod+ def _dense_sim(q_out: EncodeOutput, q_idx: int, d_out: EncodeOutput, d_idx: int) -> float:+ """Cosine similarity between dense vectors (normalized inside encode)."""+ if q_out.dense is None or d_out.dense is None:+ msg = "Dense vectors required for dense scoring but missing from encode output"+ raise RuntimeError(msg)+ q = q_out.dense[q_idx]+ d = d_out.dense[d_idx]+ # Defensive normalization in case caller disabled normalize at runtime.+ q_norm = float(np.linalg.norm(q))+ d_norm = float(np.linalg.norm(d))+ if q_norm == 0.0 or d_norm == 0.0:+ return 0.0+ return float(np.dot(q, d) / (q_norm * d_norm))++ @staticmethod+ def _sparse_sim(q_out: EncodeOutput, q_idx: int, d_out: EncodeOutput, d_idx: int) -> float:+ """BGE-M3 lexical-match score: sum of q_w * d_w over shared token ids."""+ if q_out.sparse is None or d_out.sparse is None:+ msg = "Sparse vectors required for sparse scoring but missing from encode output"+ raise RuntimeError(msg)+ q_vec = q_out.sparse[q_idx]+ d_vec = d_out.sparse[d_idx]+ if len(q_vec.indices) == 0 or len(d_vec.indices) == 0:+ return 0.0+ d_lookup = dict(zip(d_vec.indices.tolist(), d_vec.values.tolist(), strict=True))+ total = 0.0+ for tid, q_w in zip(q_vec.indices.tolist(), q_vec.values.tolist(), strict=True):+ d_w = d_lookup.get(tid)+ if d_w is not None:+ total += float(q_w) * float(d_w)+ return float(total)++ @staticmethod+ def _colbert_sim(q_out: EncodeOutput, q_idx: int, d_out: EncodeOutput, d_idx: int) -> float:+ """ColBERT MaxSim: sum over query tokens of max-dot against doc tokens, normalized by query length.++ Matches FlagEmbedding's ``BGEM3FlagModel.colbert_score`` exactly.+ """+ if q_out.multivector is None or d_out.multivector is None:+ msg = "Multivector outputs required for colbert scoring but missing from encode output"+ raise RuntimeError(msg)+ q_mv = q_out.multivector[q_idx]+ d_mv = d_out.multivector[d_idx]+ if q_mv.size == 0 or d_mv.size == 0:+ return 0.0+ # Defensive normalization (multivector is normalized inside encode by default).+ q_norms = np.linalg.norm(q_mv, axis=-1, keepdims=True)+ d_norms = np.linalg.norm(d_mv, axis=-1, keepdims=True)+ q_normed = np.divide(q_mv, q_norms, out=np.zeros_like(q_mv), where=q_norms > 0)+ d_normed = np.divide(d_mv, d_norms, out=np.zeros_like(d_mv), where=d_norms > 0)+ sim = q_normed @ d_normed.T # [q_len, d_len]+ max_per_query_token = sim.max(axis=-1)+ return float(max_per_query_token.sum() / q_mv.shape[0])diff --git a/packages/sie_server/src/sie_server/adapters/siglip/__init__.py b/packages/sie_server/src/sie_server/adapters/siglip/__init__.pyindex bbcb688d1..e9daac773 100644--- a/packages/sie_server/src/sie_server/adapters/siglip/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/siglip/__init__.py@@ -7,15 +7,34 @@ Per roadmap Project 10.4, uses transformers SiglipModel with SiglipProcessorfor Phase 1. SigLIP differs from CLIP in using sigmoid loss instead of softmaxand not having a separate projection_dim - it uses hidden_size directly.+Supports two backends:++- ``transformers`` (default): standard ``SiglipModel`` + ``SiglipProcessor``+ for stock checkpoints such as ``google/siglip-*``.+- ``open_clip``: native ``open_clip`` loading for SigLIP-architecture+ checkpoints distributed as open_clip weights, e.g.+ ``Marqo/marqo-ecommerce-embeddings-B``. This bypasses the model's HF+ custom-code wrapper, which fails to load under newer transformers because+ the wrapper instantiates real-weight submodules inside ``__init__`` while+ ``from_pretrained`` is using a meta-tensor init context.+Supports:- Text-only encoding → dense embeddings- Image-only encoding → dense embeddings- Image+text encoding → image embeddings (for retrieval)-Example configuration:+Example configuration (transformers backend):SiglipAdapter(model_name_or_path="google/siglip-so400m-patch14-384",)++Example configuration (open_clip backend):+ SiglipAdapter(+ model_name_or_path="Marqo/marqo-ecommerce-embeddings-B",+ backend="open_clip",+ open_clip_model_id="hf-hub:Marqo/marqo-ecommerce-embeddings-B",+ dense_dim=768,+ )"""from __future__ import annotations@@ -23,18 +42,17 @@ from __future__ import annotationsimport ioimport loggingfrom pathlib import Path-from typing import TYPE_CHECKING, Any, ClassVar+from typing import TYPE_CHECKING, Any, ClassVar, Literalimport torchfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpec-from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision+from sie_server.adapters._types import ComputePrecisionfrom sie_server.core.inference_output import EncodeOutputif TYPE_CHECKING:from PIL import Image- from transformers import SiglipModel, SiglipProcessorfrom sie_server.types.inputs import Item@@ -42,13 +60,25 @@ logger = logging.getLogger(__name__)# Error messages_ERR_NO_INPUT = "SiglipAdapter requires either text or images input"+_ERR_OPEN_CLIP_ID = (+ "SiglipAdapter(backend='open_clip') requires open_clip_model_id (e.g. 'hf-hub:Marqo/marqo-ecommerce-embeddings-B')"+)+_ERR_OPEN_CLIP_DIM = (+ "SiglipAdapter(backend='open_clip') requires an explicit dense_dim "+ "(open_clip does not surface embedding dim through a single config attribute)"+)+++SiglipBackend = Literal["transformers", "open_clip"]class SiglipAdapter(BaseAdapter):"""Adapter for SigLIP image-text embedding models.Supports encoding text, images, or both into dense embeddings in a shared- vector space. Uses HuggingFace transformers SiglipModel and SiglipProcessor.+ vector space. Uses HuggingFace transformers SiglipModel and SiglipProcessor+ by default; can be switched to the ``open_clip`` library for checkpoints+ distributed in that format.Key difference from CLIP: SigLIP uses hidden_size directly instead ofprojection_dim for the embedding dimension.@@ -57,7 +87,13 @@ class SiglipAdapter(BaseAdapter):spec: ClassVar[AdapterSpec] = AdapterSpec(inputs=("text", "image"),outputs=("dense",),- unload_fields=("_model", "_processor", "_dense_dim"),+ unload_fields=(+ "_model",+ "_processor",+ "_dense_dim",+ "_open_clip_preprocess",+ "_open_clip_tokenizer",+ ),default_preprocessor="image",)@@ -69,23 +105,55 @@ class SiglipAdapter(BaseAdapter):compute_precision: ComputePrecision = "float16",trust_remote_code: bool = False,max_seq_length: int | None = None,+ backend: SiglipBackend = "transformers",+ open_clip_model_id: str | None = None,+ dense_dim: int | None = None,) -> None:"""Initialize the adapter.Args:- model_name_or_path: HuggingFace model ID or local path.+ model_name_or_path: HuggingFace model ID or local path. Used by+ the ``transformers`` backend; informational only for the+ ``open_clip`` backend (used in logs and as the+ ``ImagePreprocessor`` model name).normalize: Whether to L2-normalize embeddings.compute_precision: Compute precision for inference.- trust_remote_code: Whether to trust remote code.+ trust_remote_code: Forwarded to ``SiglipModel.from_pretrained`` /+ ``SiglipProcessor.from_pretrained`` in the transformers+ backend. Ignored by the ``open_clip`` backend.max_seq_length: Ignored - SigLIP uses fixed token length from model config.+ backend: Which loader to use. ``transformers`` (default) for stock+ SigLIP checkpoints; ``open_clip`` for open_clip-distributed+ SigLIP checkpoints (e.g. Marqo).+ open_clip_model_id: open_clip model identifier (e.g.+ ``"hf-hub:Marqo/marqo-ecommerce-embeddings-B"``). Required+ when ``backend="open_clip"``.+ dense_dim: Optional explicit embedding dimension. Required for+ the ``open_clip`` backend (open_clip does not surface dim via+ a single config attribute). When omitted with the+ ``transformers`` backend, the adapter reads+ ``vision_config.hidden_size`` from the loaded model config."""self._model_name_or_path = str(model_name_or_path)self._normalize = normalizeself._compute_precision = compute_precisionself._trust_remote_code = trust_remote_code-- self._model: SiglipModel | None = None- self._processor: SiglipProcessor | None = None+ self._backend: SiglipBackend = backend+ self._open_clip_model_id = open_clip_model_id+ self._dense_dim_override = dense_dim++ # Validate the open_clip backend's required options up-front so the+ # error surfaces at adapter construction rather than at load time.+ if self._backend == "open_clip":+ if not self._open_clip_model_id:+ raise ValueError(_ERR_OPEN_CLIP_ID)+ if self._dense_dim_override is None:+ raise ValueError(_ERR_OPEN_CLIP_DIM)++ self._model: Any | None = None+ self._processor: Any | None = None+ self._open_clip_preprocess: Any | None = None+ self._open_clip_tokenizer: Any | None = Noneself._device: str | None = Noneself._dense_dim: int | None = None@@ -95,27 +163,47 @@ class SiglipAdapter(BaseAdapter):Args:device: Device string (e.g., "cuda:0", "cpu")."""- from transformers import SiglipModel, SiglipProcessor-self._device = device# Determine dtypedtype = self._resolve_dtype()logger.info(- "Loading SigLIP model %s on device=%s with dtype=%s",+ "Loading SigLIP model %s on device=%s with dtype=%s backend=%s",self._model_name_or_path,device,dtype,+ self._backend,)- # Load processor (handles both text tokenization and image preprocessing)+ if self._backend == "open_clip":+ self._load_open_clip(device, dtype)+ else:+ self._load_transformers(device, dtype)++ # Resolve embedding dimension. The ``open_clip`` backend always+ # supplies an explicit override (validated in ``__init__``); the+ # ``transformers`` backend can fall back to ``vision_config``.+ if self._dense_dim_override is not None:+ self._dense_dim = self._dense_dim_override+ else:+ assert self._backend == "transformers"+ assert self._model is not None # guarded by _load_transformers+ vision_config = getattr(self._model.config, "vision_config", None)+ if vision_config is None or not hasattr(vision_config, "hidden_size"):+ msg = "Cannot infer dense_dim from model config; pass adapter_options.loadtime.dense_dim explicitly."+ raise RuntimeError(msg)+ self._dense_dim = vision_config.hidden_size++ def _load_transformers(self, device: str, dtype: torch.dtype) -> None:+ """Load via transformers SiglipModel/SiglipProcessor."""+ from transformers import SiglipModel, SiglipProcessor+self._processor = SiglipProcessor.from_pretrained(self._model_name_or_path,trust_remote_code=self._trust_remote_code,)- # Load modelself._model = SiglipModel.from_pretrained(self._model_name_or_path,torch_dtype=dtype,@@ -124,10 +212,30 @@ class SiglipAdapter(BaseAdapter):self._model.to(device)self._model.eval()- # Get embedding dimension from model config- # SigLIP uses hidden_size directly (not projection_dim like CLIP)- # The vision and text encoders should have the same hidden_size- self._dense_dim = self._model.config.vision_config.hidden_size+ def _load_open_clip(self, device: str, dtype: torch.dtype) -> None:+ """Load via open_clip native loader.++ The model is moved to ``device`` and cast to ``dtype`` after+ construction; this matches the transformers path's behavior and avoids+ the meta-tensor incompatibility that bites HF custom-code wrappers+ which call ``self.model.to(...)`` from inside ``__init__``.+ """+ import open_clip++ assert self._open_clip_model_id is not None # guarded in __init__++ model, _train_preproc, val_preproc = open_clip.create_model_and_transforms(self._open_clip_model_id)+ tokenizer = open_clip.get_tokenizer(self._open_clip_model_id)++ model.to(device=device, dtype=dtype)+ model.eval()++ self._model = model+ self._open_clip_preprocess = val_preproc+ self._open_clip_tokenizer = tokenizer+ # ``_processor`` stays ``None`` on this backend; ``_check_loaded()``+ # only consults ``_model`` and the encode paths branch on+ # ``self._backend`` to pick the right tokenizer/preprocess callable.def _resolve_dtype(self) -> torch.dtype:"""Resolve dtype based on device and config."""@@ -163,23 +271,47 @@ class SiglipAdapter(BaseAdapter):output_types: Which outputs to return (only "dense" supported).instruction: Optional instruction (not used by SigLIP).is_query: Whether items are queries.- prepared_items: Not used by this adapter.+ prepared_items: Optional list of ``PreparedItem[ImagePayload]``+ from the framework's image preprocessor. When supplied, the+ ``open_clip`` backend reuses the preprocessed pixel tensors+ (which were computed in parallel on a CPU executor thread)+ instead of re-running ``val_preproc`` here. The transformers+ backend currently ignores this hint.Returns:EncodeOutput with dense embeddings."""+ # ``_check_loaded`` guards on ``_model``; backend-specific helpers+ # (``_open_clip_tokenizer`` / ``_open_clip_preprocess`` for open_clip,+ # ``_processor`` for transformers) are validated inside the encode+ # branches via local ``assert``s.self._check_loaded()- if self._processor is None:- raise RuntimeError(ERR_NOT_LOADED)self._validate_output_types(output_types)+ # Index prepared image tensors by the original item index so the+ # per-item loop can reuse them. Only the open_clip backend currently+ # consumes these; the transformers ImagePreprocessor produces tensors+ # in a layout matching SiglipProcessor, but the existing transformers+ # code path re-runs the processor inline — left untouched here to+ # avoid behavioral drift on the google/siglip* regression tests.+ prepared_by_index: dict[int, Any] = {}+ if self._backend == "open_clip" and prepared_items:+ for prepared in prepared_items:+ payload = getattr(prepared, "payload", None)+ if payload is None:+ continue+ pixel_values = getattr(payload, "pixel_values", None)+ if pixel_values is None:+ continue+ prepared_by_index[prepared.original_index] = pixel_values+# Encode each item individually and stack into batchimport numpy as npembeddings_list = []- for item in items:- embedding = self._encode_single_item(item)+ for i, item in enumerate(items):+ embedding = self._encode_single_item(item, prepared_pixel_values=prepared_by_index.get(i))embeddings_list.append(embedding)# Stack into batched array [batch, dim]@@ -192,9 +324,17 @@ class SiglipAdapter(BaseAdapter):dense_dim=self._dense_dim,)- def _encode_single_item(self, item: Item) -> Any:+ def _encode_single_item(self, item: Item, prepared_pixel_values: Any = None) -> Any:"""Encode a single item (text, image, or both).+ Args:+ item: Input item.+ prepared_pixel_values: Optional pre-processed ``[C, H, W]`` tensor+ from the framework's image preprocessor. Only honored on the+ ``open_clip`` backend and only when the item has exactly one+ image (matching what the preprocessor consumed). Falls back+ to inline preprocessing otherwise.+Returns:Numpy array of shape [dense_dim]."""@@ -207,7 +347,16 @@ class SiglipAdapter(BaseAdapter):# Determine what to encodeif has_images:- # Image encoding (or image+text where image takes precedence)+ # Image encoding (or image+text where image takes precedence).+ # The framework's preprocessor only handles the first image per+ # item, so we can only reuse it when the item has exactly one.+ if (+ self._backend == "open_clip"+ and prepared_pixel_values is not None+ and images is not None+ and len(images) == 1+ ):+ return self._encode_images([], prepared_pixel_values=prepared_pixel_values)pil_images = self._load_images(item)return self._encode_images(pil_images)# Text-only encoding (text is guaranteed non-None if no images)@@ -236,33 +385,62 @@ class SiglipAdapter(BaseAdapter):return pil_images- def _encode_images(self, images: list[Image.Image]) -> Any:+ def _encode_images(+ self,+ images: list[Image.Image],+ prepared_pixel_values: Any = None,+ ) -> Any:"""Encode images into embeddings.Args:- images: List of PIL Images.+ images: List of PIL Images. Ignored on the ``open_clip`` backend+ when ``prepared_pixel_values`` is supplied.+ prepared_pixel_values: Optional pre-processed ``[C, H, W]`` tensor+ from the framework's preprocessor. Only the ``open_clip``+ backend uses this fast path; when supplied, ``val_preproc``+ is skipped and the tensor is moved to device and batched+ directly.Returns:Numpy array of shape [dense_dim] (averaged if multiple images)."""assert self._model is not None- assert self._processor is not Nonefrom torch.nn import functional- # Process images- inputs = self._processor(images=images, return_tensors="pt")- inputs = {k: v.to(self._device) for k, v in inputs.items()}-- with torch.inference_mode():- image_features = self._model.get_image_features(**inputs)-- # L2 normalize if configured- if self._normalize:- image_features = functional.normalize(image_features, p=2, dim=-1)+ if self._backend == "open_clip":+ # ``val_preproc`` and the framework preprocessor both return+ # float32 tensors. The open_clip model was cast to ``dtype`` at+ # load time (e.g. fp16 on CUDA), so we must match here — unlike+ # ``transformers.SiglipModel``, ``open_clip``'s ``encode_image``+ # does not auto-cast inputs.+ model_dtype = next(self._model.parameters()).dtype+ if prepared_pixel_values is not None:+ # Fast path: framework preprocessor already produced a+ # [C, H, W] tensor in the val_preproc layout. Add the batch+ # dim, move to device, and cast to the model's dtype.+ pixel_values = prepared_pixel_values.unsqueeze(0).to(device=self._device, dtype=model_dtype)+ effective_count = 1+ else:+ assert self._open_clip_preprocess is not None+ pixel_values = torch.stack([self._open_clip_preprocess(img) for img in images]).to(+ device=self._device, dtype=model_dtype+ )+ effective_count = len(images)+ with torch.inference_mode():+ image_features = self._model.encode_image(pixel_values, normalize=self._normalize)+ else:+ assert self._processor is not None+ inputs = self._processor(images=images, return_tensors="pt")+ inputs = {k: v.to(self._device) for k, v in inputs.items()}+ with torch.inference_mode():+ image_features = self._model.get_image_features(**inputs)+ if self._normalize:+ image_features = functional.normalize(image_features, p=2, dim=-1)+ effective_count = len(images)# If multiple images, average the embeddings- if len(images) > 1:+ if effective_count > 1:image_features = image_features.mean(dim=0, keepdim=True)return image_features[0].float().cpu().numpy()@@ -277,21 +455,24 @@ class SiglipAdapter(BaseAdapter):Numpy array of shape [dense_dim]."""assert self._model is not None- assert self._processor is not Nonefrom torch.nn import functional- # Process text - use max_length padding to match MTEB behavior- # SigLIP text embeddings depend on sequence length, so consistent padding is required- inputs = self._processor(text=[text], return_tensors="pt", padding="max_length", truncation=True)- inputs = {k: v.to(self._device) for k, v in inputs.items()}-- with torch.inference_mode():- text_features = self._model.get_text_features(**inputs)-- # L2 normalize if configured- if self._normalize:- text_features = functional.normalize(text_features, p=2, dim=-1)+ if self._backend == "open_clip":+ assert self._open_clip_tokenizer is not None+ input_ids = self._open_clip_tokenizer([text]).to(self._device)+ with torch.inference_mode():+ text_features = self._model.encode_text(input_ids, normalize=self._normalize)+ else:+ assert self._processor is not None+ # Process text - use max_length padding to match MTEB behavior+ # SigLIP text embeddings depend on sequence length, so consistent padding is required+ inputs = self._processor(text=[text], return_tensors="pt", padding="max_length", truncation=True)+ inputs = {k: v.to(self._device) for k, v in inputs.items()}+ with torch.inference_mode():+ text_features = self._model.get_text_features(**inputs)+ if self._normalize:+ text_features = functional.normalize(text_features, p=2, dim=-1)return text_features[0].float().cpu().numpy()@@ -306,8 +487,18 @@ class SiglipAdapter(BaseAdapter):"""Return an ImagePreprocessor for CPU/GPU overlap.Returns:- ImagePreprocessor wrapping the SiglipProcessor, or None if not loaded.+ ``ImagePreprocessor`` wrapping the SiglipProcessor on the+ transformers backend, ``OpenCLIPImagePreprocessor`` wrapping the+ open_clip ``val_preproc`` callable on the open_clip backend, or+ ``None`` if not loaded."""+ if self._backend == "open_clip":+ if self._open_clip_preprocess is None:+ return None+ from sie_server.core.preprocessor.image import OpenCLIPImagePreprocessor++ return OpenCLIPImagePreprocessor(self._open_clip_preprocess, self._model_name_or_path)+if self._processor is None:return Nonediff --git a/packages/sie_server/src/sie_server/api/encode.py b/packages/sie_server/src/sie_server/api/encode.pyindex 4a8252b0d..20381ac72 100644--- a/packages/sie_server/src/sie_server/api/encode.py+++ b/packages/sie_server/src/sie_server/api/encode.py@@ -172,6 +172,14 @@ def _build_response_items(},400: {"description": "Invalid request"},404: {"description": "Model not found"},+ 502: {+ "description": (+ "Terminal model-load failure (MODEL_LOAD_FAILED). "+ "Carried in the ``detail`` envelope: ``{code, message, "+ "error_class, permanent, attempts}``. No ``Retry-After`` "+ "header — clients MUST NOT auto-retry. See sie-test#85."+ ),+ },503: {"description": "Model not loaded or service unavailable"},},openapi_extra={diff --git a/packages/sie_server/src/sie_server/api/extract.py b/packages/sie_server/src/sie_server/api/extract.pyindex 036db9111..0a06cfc16 100644--- a/packages/sie_server/src/sie_server/api/extract.py+++ b/packages/sie_server/src/sie_server/api/extract.py@@ -239,6 +239,14 @@ def _build_response(},400: {"description": "Invalid request"},404: {"description": "Model not found"},+ 502: {+ "description": (+ "Terminal model-load failure (MODEL_LOAD_FAILED). "+ "Carried in the ``detail`` envelope: ``{code, message, "+ "error_class, permanent, attempts}``. No ``Retry-After`` "+ "header — clients MUST NOT auto-retry. See sie-test#85."+ ),+ },503: {"description": "Model not loaded or service unavailable"},},openapi_extra={diff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.pyindex ae122768f..9ed3513d2 100644--- a/packages/sie_server/src/sie_server/api/helpers.py+++ b/packages/sie_server/src/sie_server/api/helpers.py@@ -300,6 +300,49 @@ class ModelStateChecker:headers={"Retry-After": "5"},)+ def check_not_failed(self) -> None:+ """Check whether the model has a recorded terminal load failure.++ When the registry has a sticky :class:`LoadFailure` still in+ cooldown, return ``502 MODEL_LOAD_FAILED`` with **no**+ ``Retry-After`` header. The SDK uses the absence of+ ``Retry-After`` (combined with the dedicated error code) to+ bypass its 5-minute ``MODEL_LOADING`` retry budget and surface+ a :class:`ModelLoadFailedError` to the caller immediately.++ This is the symptom-side fix for sie-test#85: previously a+ gated/dep-missing model would loop the SDK for 5 minutes; now+ the server tells the SDK "don't bother" the first time it asks.++ Raises:+ HTTPException: 502 ``MODEL_LOAD_FAILED`` if registry holds a+ non-expired failure record.+ """+ if not self.registry.is_failed(self.model):+ return+ failure = self.registry.get_failure(self.model)+ # Defensive: ``is_failed`` is True implies a record exists, but a+ # concurrent ``clear_failure`` could have raced us to the dict.+ if failure is None: # pragma: no cover — narrow race window+ return+ self.span.set_attribute("error", "model_load_failed")+ self.span.set_attribute("model_load_error_class", failure.error_class.value)+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail={+ "code": ErrorCode.MODEL_LOAD_FAILED.value,+ "message": (+ f"Model '{self.model}' failed to load "+ f"({failure.error_class.value}, attempts={failure.attempts}): {failure.message}"+ ),+ "error_class": failure.error_class.value,+ "attempts": failure.attempts,+ "permanent": failure.is_permanent,+ },+ # Intentionally no Retry-After header — the SDK uses its+ # absence to short-circuit the MODEL_LOADING retry budget.+ )+async def ensure_loaded(self, device: str) -> None:"""Start loading model if not loaded, raise 503 to retry.@@ -307,25 +350,54 @@ class ModelStateChecker:device: Device to load model on (cpu, cuda, mps).Raises:- HTTPException: 503 with Retry-After if model needs loading.+ HTTPException: 502 ``MODEL_LOAD_FAILED`` (non-retryable) if a+ terminal failure is already recorded; otherwise 503+ ``MODEL_LOADING`` with ``Retry-After`` so the SDK retries."""- if not self.registry.is_loaded(self.model):- logger.info("Starting background load for model %s on device %s", self.model, device)- await self.registry.start_load_async(self.model, device=device)- self.span.set_attribute("error", "model_loading")- raise HTTPException(- status_code=status.HTTP_503_SERVICE_UNAVAILABLE,- detail={- "code": ErrorCode.MODEL_LOADING.value,- "message": f"Model '{self.model}' is loading, please retry",- },- headers={"Retry-After": "5"},- )+ if self.registry.is_loaded(self.model):+ return++ # Short-circuit recorded terminal failures BEFORE kicking off+ # another doomed background load. Without this guard, every+ # request would retrigger ``start_load_async`` and the SDK+ # would burn its 5-minute MODEL_LOADING budget on a known-bad+ # configuration (sie-test#85).+ self.check_not_failed()++ logger.info("Starting background load for model %s on device %s", self.model, device)+ await self.registry.start_load_async(self.model, device=device)++ # ``start_load_async`` is a no-op when a failure was recorded+ # mid-flight (race between ``check_not_failed`` and this call).+ # Re-check and surface the terminal error rather than telling+ # the SDK to retry.+ self.check_not_failed()++ # Race window: a *concurrent* request could have driven the load+ # to completion between the initial ``is_loaded`` check above+ # and this point. In that case we should return success to the+ # caller (no need to make them retry on a 503) — the model is+ # already serving.+ if self.registry.is_loaded(self.model):+ return++ self.span.set_attribute("error", "model_loading")+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail={+ "code": ErrorCode.MODEL_LOADING.value,+ "message": f"Model '{self.model}' is loading, please retry",+ },+ headers={"Retry-After": "5"},+ )async def validate_ready(self, device: str) -> None:"""Run all state checks to ensure model is ready for inference.- Checks in order: exists, not unloading, not loading, ensure loaded.+ Checks in order: exists, not unloading, not failed, not loading,+ ensure loaded. ``check_not_failed`` runs before ``check_not_loading``+ so a recorded terminal failure short-circuits the SDK's retry+ loop even if a stale ``_loading`` flag races with it.Args:device: Device to load model on if needed.@@ -335,6 +407,7 @@ class ModelStateChecker:"""self.check_exists()self.check_not_unloading()+ self.check_not_failed()self.check_not_loading()await self.ensure_loaded(device)diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.pyindex af2dc19cf..55f02fd69 100644--- a/packages/sie_server/src/sie_server/api/models.py+++ b/packages/sie_server/src/sie_server/api/models.py@@ -1,10 +1,20 @@+from typing import TYPE_CHECKING, Any, Literal+from fastapi import APIRouter, HTTPException, Request, statusfrom pydantic import BaseModelfrom sie_server.types.responses import ErrorCode+if TYPE_CHECKING:+ from sie_server.core.registry import ModelRegistry+router = APIRouter(prefix="/v1", tags=["models"])+# Wire-level state strings exposed in ``ModelInfo.state``. Mirrors the+# server-side ``ModelRegistry`` state machine plus the terminal ``failed``+# branch added for non-retryable load failures.+ModelStateStr = Literal["available", "loading", "loaded", "unloading", "failed"]+class ProfileInfo(BaseModel):"""Information about a profile."""@@ -12,6 +22,27 @@ class ProfileInfo(BaseModel):is_default: bool = False+class ModelLoadError(BaseModel):+ """Diagnostic detail for a recorded load failure.++ Surfaced in :class:`ModelInfo` when the registry has a sticky+ failure for the model. Attributes mirror the server-side+ :class:`sie_server.core.load_errors.LoadFailure`.+ """++ code: str+ """Stable enum value (``GATED``, ``OOM``, ...) for client routing."""++ message: str+ """Human-readable error summary, including the underlying exception."""++ attempts: int+ """How many load attempts have failed so far."""++ permanent: bool+ """True when the failure will not auto-retry; operator must intervene."""++class ModelInfo(BaseModel):"""Information about a model."""@@ -20,10 +51,59 @@ class ModelInfo(BaseModel):outputs: list[str]dims: dict[str, int]loaded: bool+ """Backwards-compatible boolean. Prefer ``state`` for full lifecycle."""++ state: ModelStateStr = "available"+ """Lifecycle state including the terminal ``failed`` branch."""++ last_error: ModelLoadError | None = None+ """Recorded load failure (when ``state == 'failed'``), else ``None``."""+max_sequence_length: int | None = Noneprofiles: dict[str, ProfileInfo] = {}+def _resolve_state_and_error(+ registry: "ModelRegistry | Any",+ name: str,+) -> tuple[ModelStateStr, ModelLoadError | None]:+ """Compute ``(state, last_error)`` for a model from the registry.++ Mirrors the ws.py state precedence (loading > unloading > loaded >+ failed > available) and produces the diagnostic payload for+ ``last_error`` when a sticky failure exists. The ``Any`` union in+ the signature accommodates the ``MagicMock(spec=ModelRegistry)``+ fixtures used in API tests.+ """+ is_loading = registry.is_loading(name)+ is_unloading = registry.is_unloading(name)+ is_loaded = registry.is_loaded(name)+ is_failed = registry.is_failed(name)+ failure = registry.get_failure(name)++ state: ModelStateStr+ if is_loading:+ state = "loading"+ elif is_unloading:+ state = "unloading"+ elif is_loaded:+ state = "loaded"+ elif is_failed:+ state = "failed"+ else:+ state = "available"++ last_error: ModelLoadError | None = None+ if failure is not None:+ last_error = ModelLoadError(+ code=failure.error_class.value,+ message=failure.message,+ attempts=failure.attempts,+ permanent=failure.is_permanent,+ )+ return state, last_error++class ModelsListResponse(BaseModel):"""Response for listing models."""@@ -51,6 +131,7 @@ async def list_models(http_request: Request) -> ModelsListResponse:)for pname in config.profiles}+ state, last_error = _resolve_state_and_error(registry, name)models.append(ModelInfo(name=config.sie_id,@@ -58,6 +139,8 @@ async def list_models(http_request: Request) -> ModelsListResponse:outputs=config.outputs,dims=config.dims,loaded=registry.is_loaded(name),+ state=state,+ last_error=last_error,max_sequence_length=config.max_sequence_length,profiles=profiles,)@@ -101,12 +184,15 @@ async def get_model(model: str, http_request: Request) -> ModelInfo:)for pname in config.profiles}+ state, last_error = _resolve_state_and_error(registry, model)return ModelInfo(name=config.sie_id,inputs=config.inputs.to_list(),outputs=config.outputs,dims=config.dims,loaded=registry.is_loaded(model),+ state=state,+ last_error=last_error,max_sequence_length=config.max_sequence_length,profiles=profiles,)diff --git a/packages/sie_server/src/sie_server/api/openai_compat.py b/packages/sie_server/src/sie_server/api/openai_compat.pyindex c5e18d212..ec44e505d 100644--- a/packages/sie_server/src/sie_server/api/openai_compat.py+++ b/packages/sie_server/src/sie_server/api/openai_compat.py@@ -294,6 +294,14 @@ def _build_embeddings_response(200: {"description": "Embeddings generated successfully"},400: {"description": "Invalid request"},404: {"description": "Model not found"},+ 502: {+ "description": (+ "Terminal model-load failure (MODEL_LOAD_FAILED). "+ "Carried in the ``detail`` envelope: ``{code, message, "+ "error_class, permanent, attempts}``. No ``Retry-After`` "+ "header — clients MUST NOT auto-retry. See sie-test#85."+ ),+ },503: {"description": "Service unavailable"},},)diff --git a/packages/sie_server/src/sie_server/api/score.py b/packages/sie_server/src/sie_server/api/score.pyindex 871f9a588..e4517fa4e 100644--- a/packages/sie_server/src/sie_server/api/score.py+++ b/packages/sie_server/src/sie_server/api/score.py@@ -145,6 +145,14 @@ async def _score_via_worker(},400: {"description": "Invalid request"},404: {"description": "Model not found"},+ 502: {+ "description": (+ "Terminal model-load failure (MODEL_LOAD_FAILED). "+ "Carried in the ``detail`` envelope: ``{code, message, "+ "error_class, permanent, attempts}``. No ``Retry-After`` "+ "header — clients MUST NOT auto-retry. See sie-test#85."+ ),+ },503: {"description": "Model not loaded or service unavailable"},},openapi_extra={diff --git a/packages/sie_server/src/sie_server/api/ws.py b/packages/sie_server/src/sie_server/api/ws.pyindex c39827cc7..d298afe70 100644--- a/packages/sie_server/src/sie_server/api/ws.py+++ b/packages/sie_server/src/sie_server/api/ws.py@@ -77,8 +77,12 @@ def get_model_status(registry: ModelRegistry) -> list[ModelStatus]:loaded = registry.is_loaded(name)loading = registry.is_loading(name)unloading = registry.is_unloading(name)+ failed = registry.is_failed(name)- # Determine state: loading/unloading take precedence+ # Determine state: loading/unloading take precedence over loaded.+ # ``failed`` ranks below ``loaded`` (a recovered failure that has+ # since loaded successfully should report ``loaded``) but above+ # ``available`` so the diagnostic surface is preserved.state: ModelStateif loading:state = "loading"@@ -86,6 +90,8 @@ def get_model_status(registry: ModelRegistry) -> list[ModelStatus]:state = "unloading"elif loaded:state = "loaded"+ elif failed:+ state = "failed"else:state = "available"diff --git a/packages/sie_server/src/sie_server/core/load_errors.py b/packages/sie_server/src/sie_server/core/load_errors.pynew file mode 100644index 000000000..c54a56d70--- /dev/null+++ b/packages/sie_server/src/sie_server/core/load_errors.py@@ -0,0 +1,196 @@+from __future__ import annotations++from dataclasses import dataclass+from enum import StrEnum++from sie_sdk.exceptions import GatedModelError++from sie_server.core.oom import is_oom_error+++class LoadErrorClass(StrEnum):+ """Classification of model-load failures.++ Drives the registry's terminal-failed state machine and the API's+ retry-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`` and ``NETWORK`` 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.+ """++ GATED = "GATED"+ NOT_FOUND = "NOT_FOUND"+ OOM = "OOM"+ NETWORK = "NETWORK"+ DEPENDENCY = "DEPENDENCY"+ 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++_COOLDOWN_BY_CLASS: dict[LoadErrorClass, float | None] = {+ LoadErrorClass.GATED: _PERMANENT,+ LoadErrorClass.NOT_FOUND: _PERMANENT,+ LoadErrorClass.DEPENDENCY: _PERMANENT,+ LoadErrorClass.UNKNOWN: _PERMANENT,+ LoadErrorClass.OOM: 60.0,+ LoadErrorClass.NETWORK: 30.0,+}+++@dataclass(frozen=True)+class LoadFailureClassification:+ """Result of classifying a load-time exception."""++ error_class: LoadErrorClass+ cooldown_s: float | None+ """Seconds to suppress retries; ``None`` for permanent failures."""++ @property+ def is_permanent(self) -> bool:+ """True if this failure should never auto-retry."""+ return self.cooldown_s is None+++def classify_load_error(exc: BaseException) -> LoadFailureClassification:+ """Classify a model-load exception into a ``LoadErrorClass``.++ 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``.++ Args:+ exc: The exception captured by ``_load_model_background``.++ Returns:+ Classification with the canonical class and cooldown.+ """+ # 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+ try:+ from huggingface_hub.utils import RepositoryNotFoundError as _RepositoryNotFoundError++ not_found_cls = _RepositoryNotFoundError+ except ImportError: # pragma: no cover+ not_found_cls = 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.+ if 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],+ )+++@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.++ 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.+ last_attempt_ts: ``time.monotonic()`` value at last attempt.+ cooldown_s: Seconds to suppress further retries; ``None`` means+ the failure is permanent until explicitly cleared.+ """++ error_class: LoadErrorClass+ message: str+ attempts: int+ last_attempt_ts: float+ cooldown_s: float | None++ @property+ def is_permanent(self) -> bool:+ """True when retries are not auto-scheduled."""+ return self.cooldown_s is None++ def in_cooldown(self, now: float) -> bool:+ """Whether the failure is still within its cooldown window.++ Permanent failures are always in cooldown.+ """+ if self.cooldown_s is None:+ return True+ return (now - self.last_attempt_ts) < self.cooldown_sdiff --git a/packages/sie_server/src/sie_server/core/preprocessor/image.py b/packages/sie_server/src/sie_server/core/preprocessor/image.pyindex 319484711..2299760b9 100644--- a/packages/sie_server/src/sie_server/core/preprocessor/image.py+++ b/packages/sie_server/src/sie_server/core/preprocessor/image.py@@ -7,11 +7,15 @@ image-text models like CLIP and SigLIP that take single images.from __future__ import annotationsimport io+from collections.abc import Callablefrom typing import TYPE_CHECKING, Anyfrom sie_server.core.prepared import ImagePayload, PreparedBatch, PreparedItemif TYPE_CHECKING:+ import torch+ from PIL import Image as PILImageType+from sie_server.config.model import ModelConfigfrom sie_server.types.inputs import Item@@ -127,3 +131,130 @@ class ImagePreprocessor:pixel_values = torch.stack([p.payload.pixel_values for p in prepared])return {"pixel_values": pixel_values.to(device)}+++class OpenCLIPImagePreprocessor:+ """Preprocessor for ``open_clip``-native models.++ Adapts the ``val_preproc`` callable returned by+ ``open_clip.create_model_and_transforms`` (a ``torchvision.transforms``+ pipeline mapping ``PIL.Image -> Tensor[C, H, W]``) to the+ ``Preprocessor`` protocol shared by adapters in this codebase. This lets+ the framework run PIL decoding + resize on a CPU executor thread in+ parallel with the previous batch's GPU forward pass, matching the+ CPU/GPU-overlap optimization that ``ImagePreprocessor`` provides for+ HuggingFace processors.++ Thread-safety: assumes ``val_preproc`` is stateless and reentrant. The+ pipeline returned by ``open_clip.create_model_and_transforms`` (resize ++ center crop + ``ToTensor`` + ``Normalize``) satisfies this. Custom+ callables that share mutable state (e.g. transforms with non-thread-local+ RNG) are the caller's responsibility.+ """++ def __init__(+ self,+ val_preproc: Callable[[PILImageType.Image], torch.Tensor],+ model_name: str,+ ) -> None:+ """Initialize with an open_clip val_preproc callable.++ Args:+ val_preproc: The ``val_preproc`` callable returned by+ ``open_clip.create_model_and_transforms`` (a torchvision+ Compose). Maps ``PIL.Image -> Tensor[C, H, W]`` already+ normalized for the model.+ model_name: Model name for logging.+ """+ self._val_preproc = val_preproc+ self._model_name = model_name++ @property+ def modality(self) -> str:+ """Return 'image'."""+ return "image"++ def prepare(+ self,+ items: list[Item],+ *,+ config: ModelConfig,+ is_query: bool = False,+ instruction: str | None = None,+ task: str | None = None,+ ) -> PreparedBatch[ImagePayload]:+ """Process images from items via open_clip's val_preproc.++ Each item may have multiple images. As with ``ImagePreprocessor``, we+ take the first image per item to match the encode-side behavior.++ Args:+ items: Items with images field.+ config: Model config (unused for images currently).+ is_query: Whether items are queries (unused for standard images).+ instruction: Optional instruction (unused for standard image preprocessing).+ task: Optional task token (unused for standard image preprocessing).++ Returns:+ PreparedBatch with ImagePayload items.+ """+ from PIL import Image as PILImage++ prepared_items: list[PreparedItem[ImagePayload]] = []+ total_cost = 0++ for i, item in enumerate(items):+ if not item.images:+ # Skip items without images (they may be text-only)+ continue++ # Load first image from bytes+ img_input = item.images[0]+ pil_img = PILImage.open(io.BytesIO(img_input["data"]))+ original_size = pil_img.size++ # Convert to RGB if needed+ if pil_img.mode != "RGB":+ pil_img = pil_img.convert("RGB")++ # open_clip val_preproc returns a [C, H, W] tensor (no batch dim)+ pixel_values = self._val_preproc(pil_img)++ payload = ImagePayload(+ pixel_values=pixel_values,+ original_size=original_size,+ )+ # Cost = 1 per image (fixed dimensions after resize)+ prepared_items.append(PreparedItem(payload=payload, cost=1, original_index=i))+ total_cost += 1++ return PreparedBatch(+ items=prepared_items,+ total_cost=total_cost,+ modality="image",+ )++ def collate(+ self,+ prepared: list[PreparedItem[ImagePayload]],+ *,+ device: str,+ ) -> dict[str, Any]:+ """Collate image items into batched tensor.++ Args:+ prepared: List of prepared image items.+ device: Target device.++ Returns:+ Dict with 'pixel_values' tensor of shape [B, C, H, W].+ """+ import torch++ if not prepared:+ return {"pixel_values": torch.tensor([])}++ # Stack pixel values into batch+ pixel_values = torch.stack([p.payload.pixel_values for p in prepared])++ return {"pixel_values": pixel_values.to(device)}diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex 2288967b8..f0c0c53d9 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -25,6 +25,11 @@ from sie_server.config.engine import EngineConfigfrom sie_server.config.model import ModelConfigfrom sie_server.core.disk_cache import DiskCacheConfig, ModelDiskCacheManagerfrom sie_server.core.hot_reload import HotReloader+from sie_server.core.load_errors import (+ LoadErrorClass,+ LoadFailure,+ classify_load_error,+)from sie_server.core.loader import load_model_configsfrom sie_server.core.memory import MemoryConfig, MemoryManagerfrom sie_server.core.model_loader import DEFAULT_MAX_LORAS, LoadedModel, ModelLoader@@ -119,6 +124,12 @@ class ModelRegistry:self._load_lock: asyncio.Lock | None = None # Created lazily on first useself._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.+ self._failed: dict[str, LoadFailure] = {}# Background memory monitorself._monitor_task: asyncio.Task[None] | None = None@@ -316,6 +327,43 @@ class ModelRegistry:"""Check if a model is currently being unloaded."""return name in self._unloading+ def is_failed(self, name: str) -> bool:+ """Check whether a model has a recorded load failure still in cooldown.++ A model is considered "failed" only while its recorded+ :class:`LoadFailure` is within the cooldown window for its error+ class. Once the cooldown elapses (transient classes only) the+ failure is treated as expired and ``is_failed`` returns False so+ 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).+ """+ failure = self._failed.get(name)+ if failure is None:+ return False+ return failure.in_cooldown(time.monotonic())++ def get_failure(self, name: str) -> LoadFailure | None:+ """Return the recorded :class:`LoadFailure` for ``name`` if any.++ Returns ``None`` when no failure has been recorded; the failure+ record is returned regardless of cooldown so that ``GET /v1/models``+ can include diagnostic detail even after the cooldown has elapsed.+ """+ return self._failed.get(name)++ 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.+ """+ return self._failed.pop(name, None) is not None+def _get_load_lock(self) -> asyncio.Lock:"""Get or create the load lock (must be called from async context)."""if self._load_lock is None:@@ -451,6 +499,9 @@ class ModelRegistry:# Register with memory manager for LRU trackingself._memory_manager.register_model(name, estimated_bytes=loaded.memory_bytes)+ # Clear any stale failure record from a prior attempt.+ self._failed.pop(name, None)+return loaded.adapterasync def load_async(self, name: str, device: str) -> ModelAdapter:@@ -590,6 +641,13 @@ class ModelRegistry:if name in self._loading:return False+ # Recorded failure still in cooldown — don't start another doomed+ # background load. The API surface (``ensure_loaded``) checks+ # ``is_failed`` and returns ``MODEL_LOAD_FAILED`` instead of+ # ``MODEL_LOADING``, so the SDK won't keep retrying.+ if self.is_failed(name):+ return False+# Check model exists and dependencies are compatible BEFORE starting background task.# This surfaces errors synchronously so the API can return 404/409 immediately.self._check_model_loadable(name)@@ -613,6 +671,12 @@ class ModelRegistry:is managed here with a finally block to ensure cleanup even if load_asyncreturns early (e.g., model already loaded by another task).+ 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.+Args:name: Model name.device: Device string (e.g., "cuda:0", "cpu").@@ -620,8 +684,18 @@ class ModelRegistry:try:await self.load_async(name, device)logger.info("Background model load completed: %s", name)- except Exception:- logger.exception("Background model load failed: %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)+ except (KeyboardInterrupt, SystemExit, asyncio.CancelledError):+ # Operator-initiated shutdown / task cancellation must NOT+ # be recorded as a load failure — that would leave the+ # model permanently in ``failed`` state across server+ # restarts. Let these propagate so asyncio's task lifecycle+ # handles them normally.+ raise+ except Exception as exc: # noqa: BLE001 — classify_load_error buckets every exception type+ self._record_load_failure(name, exc)finally:# Always remove from _loading when background task completes.# This handles the case where load_async returned early (model already@@ -629,6 +703,49 @@ 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:+ """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.+ """+ classification = classify_load_error(exc)+ previous = self._failed.get(name)+ attempts = (previous.attempts + 1) if previous is not None else 1+ message = f"{type(exc).__name__}: {exc}"+ failure = LoadFailure(+ error_class=classification.error_class,+ message=message,+ attempts=attempts,+ last_attempt_ts=time.monotonic(),+ cooldown_s=classification.cooldown_s,+ )+ self._failed[name] = failure++ if classification.error_class is LoadErrorClass.GATED:+ # Gated models almost always indicate a missing/invalid HF_TOKEN.+ # Emit the actionable hint up-front instead of relying on the+ # 300s soft-warning that only fires on slow loads.+ logger.warning(+ "Model '%s' load failed: gated repository (attempts=%d). "+ "Ensure HF_TOKEN is set and the account has accepted the model "+ "license on HuggingFace. Underlying error: %s",+ name,+ attempts,+ message,+ extra={"gated_model": True, "model": name},+ )+ else:+ logger.exception(+ "Background model load failed: %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",+ )+def unload(self, name: str) -> None:"""Unload a model and free resources.@@ -662,6 +779,24 @@ class ModelRegistry:logger.info("Model '%s' unloaded", name)+ def _clear_transient_failures(self, classes: tuple[LoadErrorClass, ...] = (LoadErrorClass.OOM,)) -> int:+ """Drop transient-class failure records for all models.++ Used after a successful unload (memory has been freed, so a prior+ ``OOM`` is no longer relevant) and after device-level recovery+ events. 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``).+ """+ cleared = 0+ for name, failure in list(self._failed.items()):+ if failure.error_class in classes:+ self._failed.pop(name, None)+ cleared += 1+ return cleared+async def _do_unload(self, name: str) -> None:"""Unload a model safely (drains worker first).@@ -709,6 +844,17 @@ class ModelRegistry:# Unregister from memory managerself._memory_manager.unregister_model(name)+ # Freeing memory makes any prior OOM-class load failure on a+ # *sibling* model retryable; clear those records so the next+ # request can re-attempt without waiting out the cooldown.+ cleared = self._clear_transient_failures()+ if cleared:+ logger.debug(+ "Cleared %d transient failure record(s) after unloading '%s'",+ cleared,+ name,+ )+logger.info("Model '%s' unloaded", name)finally:self._unloading.discard(name)@@ -781,6 +927,11 @@ class ModelRegistry:self._model_filter.add(config.sie_id)if model_dir is not None:self._model_dirs[config.sie_id] = model_dir+ # A config update is operator intent that may have fixed the+ # underlying issue (e.g. pinned a working revision, dropped a+ # broken adapter option). Clear any sticky failure so the next+ # request retries with the new config.+ self._failed.pop(config.sie_id, None)self._config_version += 1def get_model_info(self, name: str) -> dict[str, Any]:diff --git a/packages/sie_server/src/sie_server/types/responses.py b/packages/sie_server/src/sie_server/types/responses.pyindex ee4a1f127..b7356385d 100644--- a/packages/sie_server/src/sie_server/types/responses.py+++ b/packages/sie_server/src/sie_server/types/responses.py@@ -176,6 +176,7 @@ class ErrorCode(StrEnum):MODEL_NOT_LOADED = "MODEL_NOT_LOADED"LORA_LOADING = "LORA_LOADING" # LoRA adapter loading in progress - SDK should retryMODEL_LOADING = "MODEL_LOADING" # Model loading in progress - SDK should retry+ MODEL_LOAD_FAILED = "MODEL_LOAD_FAILED" # Terminal load failure (gated, missing dep, etc) - SDK MUST NOT retryINFERENCE_ERROR = "INFERENCE_ERROR"QUEUE_FULL = "QUEUE_FULL"INTERNAL_ERROR = "INTERNAL_ERROR"diff --git a/packages/sie_server/tests/adapters/test_bge_m3.py b/packages/sie_server/tests/adapters/test_bge_m3.pyindex b28ba43c5..471fdd309 100644--- a/packages/sie_server/tests/adapters/test_bge_m3.py+++ b/packages/sie_server/tests/adapters/test_bge_m3.py@@ -45,7 +45,7 @@ class TestBGEM3FlagAdapter:"""Adapter reports correct capabilities."""caps = adapter.capabilitiesassert caps.inputs == ["text"]- assert caps.outputs == ["dense", "sparse", "multivector"]+ assert caps.outputs == ["dense", "sparse", "multivector", "score"]def test_dims(self, adapter: BGEM3FlagAdapter) -> None:"""Adapter reports correct dimensions."""@@ -206,7 +206,7 @@ class TestBGEM3Adapter:"""Adapter reports correct capabilities."""caps = adapter.capabilitiesassert caps.inputs == ["text"]- assert caps.outputs == ["dense", "sparse", "multivector"]+ assert caps.outputs == ["dense", "sparse", "multivector", "score"]def test_dims(self, adapter: BGEM3Adapter) -> None:"""Adapter reports correct dimensions."""diff --git a/packages/sie_server/tests/adapters/test_bge_m3_flash.py b/packages/sie_server/tests/adapters/test_bge_m3_flash.pynew file mode 100644index 000000000..132840144--- /dev/null+++ b/packages/sie_server/tests/adapters/test_bge_m3_flash.py@@ -0,0 +1,507 @@+from __future__ import annotations++from pathlib import Path+from typing import Any+from unittest.mock import MagicMock++import numpy as np+import pytest+import yaml+from sie_server.adapters.bge_m3_flash import BGEM3FlashAdapter+from sie_server.config.model import ModelConfig+from sie_server.core.inference_output import EncodeOutput, SparseVector+from sie_server.types.inputs import Item++# bge_m3_flash requires CUDA at load() time. The score() / score_pairs() unit+# tests in this module bypass load() by:+# * setting ``adapter._model = MagicMock()`` so ``_check_loaded()`` passes,+# * monkey-patching ``adapter.encode`` to return synthetic ``EncodeOutput``+# fixtures that exercise the dense / sparse / multivector code paths.+# This keeps the tests CPU-only and focused on the scoring math.++_RNG = np.random.default_rng(0)+++def _normalize(vec: np.ndarray) -> np.ndarray:+ norm = np.linalg.norm(vec, axis=-1, keepdims=True)+ norm = np.where(norm == 0, 1.0, norm)+ return vec / norm+++def _make_dense_output(vectors: np.ndarray) -> EncodeOutput:+ return EncodeOutput(+ dense=vectors.astype(np.float32),+ batch_size=vectors.shape[0],+ dense_dim=vectors.shape[1],+ )+++def _make_sparse_output(weights: list[dict[int, float]]) -> EncodeOutput:+ sparse = []+ for w in weights:+ if w:+ indices = np.array(sorted(w.keys()), dtype=np.int32)+ values = np.array([w[k] for k in indices], dtype=np.float32)+ else:+ indices = np.array([], dtype=np.int32)+ values = np.array([], dtype=np.float32)+ sparse.append(SparseVector(indices=indices, values=values))+ return EncodeOutput(sparse=sparse, batch_size=len(weights))+++def _make_multivector_output(mvs: list[np.ndarray]) -> EncodeOutput:+ return EncodeOutput(+ multivector=[m.astype(np.float32) for m in mvs],+ batch_size=len(mvs),+ multivector_token_dim=mvs[0].shape[-1] if mvs else None,+ )+++class TestBGEM3FlashAdapterSpec:+ """Static spec / capability assertions (no load required)."""++ def test_spec_advertises_score(self) -> None:+ spec = BGEM3FlashAdapter.spec+ assert "score" in spec.outputs+ assert {"dense", "sparse", "multivector"}.issubset(set(spec.outputs))++ def test_capabilities_include_score(self) -> None:+ adapter = BGEM3FlashAdapter()+ caps = adapter.capabilities+ assert "score" in caps.outputs+++class TestBGEM3YamlConfig:+ """Validate the shipped BAAI__bge-m3.yaml advertises scoring."""++ @pytest.fixture+ def config(self) -> ModelConfig:+ models_dir = Path(__file__).resolve().parents[2] / "models"+ path = models_dir / "BAAI__bge-m3.yaml"+ raw = yaml.safe_load(path.read_text())+ return ModelConfig(**raw)++ def test_score_task_enabled(self, config: ModelConfig) -> None:+ # Regression guard for sie-internal#728: bge-m3 was advertised as a+ # scoring model but the YAML had `score: null`, causing /v1/score+ # requests to be rejected before reaching the adapter.+ assert config.tasks.score is not None++ def test_score_in_outputs(self, config: ModelConfig) -> None:+ assert "score" in config.outputs+++class TestResolveScoreMode:+ """Validation of options['score_mode'] / options['score_weights']."""++ @pytest.fixture+ def adapter(self) -> BGEM3FlashAdapter:+ return BGEM3FlashAdapter()++ def test_default_is_dense(self, adapter: BGEM3FlashAdapter) -> None:+ mode, weights = adapter._resolve_score_mode(None)+ assert mode == "dense"+ # Weights default to paper values regardless of mode (only used in hybrid)+ assert weights == {"dense": 0.4, "sparse": 0.2, "colbert": 0.4}++ @pytest.mark.parametrize("mode", ["dense", "sparse", "colbert", "hybrid"])+ def test_valid_modes(self, adapter: BGEM3FlashAdapter, mode: str) -> None:+ resolved, _ = adapter._resolve_score_mode({"score_mode": mode})+ assert resolved == mode++ def test_invalid_mode_raises(self, adapter: BGEM3FlashAdapter) -> None:+ with pytest.raises(ValueError, match="Invalid score_mode"):+ adapter._resolve_score_mode({"score_mode": "wat"})++ @pytest.mark.parametrize("bad", [[], {}, ["dense"], None.__class__, 5])+ def test_invalid_mode_type_raises_value_error(self, adapter: BGEM3FlashAdapter, bad: object) -> None:+ # Unhashable inputs (list/dict) would raise TypeError from+ # frozenset.__contains__ before our validation; ensure we catch the+ # type up-front and surface a uniform ValueError (→ 400, not 500).+ with pytest.raises(ValueError, match="Invalid score_mode"):+ adapter._resolve_score_mode({"score_mode": bad})++ def test_score_weights_override(self, adapter: BGEM3FlashAdapter) -> None:+ _, weights = adapter._resolve_score_mode(+ {"score_mode": "hybrid", "score_weights": {"dense": 1.0, "sparse": 0.0}}+ )+ assert weights["dense"] == 1.0+ assert weights["sparse"] == 0.0+ # colbert preserves default+ assert weights["colbert"] == 0.4++ def test_score_weights_must_be_mapping(self, adapter: BGEM3FlashAdapter) -> None:+ with pytest.raises(ValueError, match="score_weights must be a mapping"):+ adapter._resolve_score_mode({"score_weights": [1.0, 0.0, 0.0]})++ def test_score_weights_unknown_key(self, adapter: BGEM3FlashAdapter) -> None:+ with pytest.raises(ValueError, match="Unknown score_weights keys"):+ adapter._resolve_score_mode({"score_weights": {"foo": 1.0}})++ def test_score_weights_negative(self, adapter: BGEM3FlashAdapter) -> None:+ with pytest.raises(ValueError, match="must be a non-negative"):+ adapter._resolve_score_mode({"score_weights": {"dense": -1.0}})++ def test_score_weights_bool_rejected(self, adapter: BGEM3FlashAdapter) -> None:+ # bool is a subclass of int; we reject it to avoid silent True/False -> 1/0.+ with pytest.raises(ValueError, match="must be a non-negative"):+ adapter._resolve_score_mode({"score_weights": {"dense": True}})++ def test_score_weights_string_rejected(self, adapter: BGEM3FlashAdapter) -> None:+ with pytest.raises(ValueError, match="must be a non-negative"):+ adapter._resolve_score_mode({"score_weights": {"dense": "0.5"}})++ def test_hybrid_zero_weights_rejected(self, adapter: BGEM3FlashAdapter) -> None:+ with pytest.raises(ValueError, match="at least one positive weight"):+ adapter._resolve_score_mode(+ {+ "score_mode": "hybrid",+ "score_weights": {"dense": 0.0, "sparse": 0.0, "colbert": 0.0},+ }+ )+++class TestOutputTypesForMode:+ @pytest.fixture+ def adapter(self) -> BGEM3FlashAdapter:+ return BGEM3FlashAdapter()++ def test_dense_only_for_dense_mode(self, adapter: BGEM3FlashAdapter) -> None:+ assert adapter._output_types_for_mode("dense", {}) == ["dense"]++ def test_sparse_only_for_sparse_mode(self, adapter: BGEM3FlashAdapter) -> None:+ assert adapter._output_types_for_mode("sparse", {}) == ["sparse"]++ def test_multivector_for_colbert_mode(self, adapter: BGEM3FlashAdapter) -> None:+ assert adapter._output_types_for_mode("colbert", {}) == ["multivector"]++ def test_hybrid_uses_all_with_positive_weights(self, adapter: BGEM3FlashAdapter) -> None:+ out = adapter._output_types_for_mode("hybrid", {"dense": 0.4, "sparse": 0.2, "colbert": 0.4})+ assert set(out) == {"dense", "sparse", "multivector"}++ def test_hybrid_skips_zero_weight_outputs(self, adapter: BGEM3FlashAdapter) -> None:+ out = adapter._output_types_for_mode("hybrid", {"dense": 1.0, "sparse": 0.0, "colbert": 0.0})+ assert out == ["dense"]+++class TestSimilarityHelpers:+ """Direct tests for the four similarity primitives."""++ def test_dense_sim_identical_vectors_is_one(self) -> None:+ vec = _RNG.standard_normal((1, 8)).astype(np.float32)+ vec = _normalize(vec)+ out = _make_dense_output(vec)+ sim = BGEM3FlashAdapter._dense_sim(out, 0, out, 0)+ assert sim == pytest.approx(1.0, abs=1e-5)++ def test_dense_sim_orthogonal_vectors_is_zero(self) -> None:+ q = np.array([[1.0, 0.0, 0.0]], dtype=np.float32)+ d = np.array([[0.0, 1.0, 0.0]], dtype=np.float32)+ sim = BGEM3FlashAdapter._dense_sim(_make_dense_output(q), 0, _make_dense_output(d), 0)+ assert sim == pytest.approx(0.0, abs=1e-6)++ def test_dense_sim_handles_unnormalized_input(self) -> None:+ # Cosine still yields 1.0 for parallel vectors of different magnitudes.+ q = np.array([[2.0, 0.0]], dtype=np.float32)+ d = np.array([[5.0, 0.0]], dtype=np.float32)+ sim = BGEM3FlashAdapter._dense_sim(_make_dense_output(q), 0, _make_dense_output(d), 0)+ assert sim == pytest.approx(1.0, abs=1e-6)++ def test_sparse_sim_overlapping_tokens(self) -> None:+ q_out = _make_sparse_output([{1: 0.5, 2: 0.3}])+ d_out = _make_sparse_output([{1: 0.4, 3: 0.9}])+ sim = BGEM3FlashAdapter._sparse_sim(q_out, 0, d_out, 0)+ # Only token id 1 overlaps: 0.5 * 0.4 = 0.2+ assert sim == pytest.approx(0.2, abs=1e-6)++ def test_sparse_sim_disjoint_tokens_is_zero(self) -> None:+ q_out = _make_sparse_output([{1: 0.5}])+ d_out = _make_sparse_output([{2: 0.9}])+ assert BGEM3FlashAdapter._sparse_sim(q_out, 0, d_out, 0) == 0.0++ def test_sparse_sim_empty_vector_is_zero(self) -> None:+ q_out = _make_sparse_output([{}])+ d_out = _make_sparse_output([{1: 0.5}])+ assert BGEM3FlashAdapter._sparse_sim(q_out, 0, d_out, 0) == 0.0++ def test_colbert_sim_identical_sequences_is_one(self) -> None:+ vecs = _normalize(_RNG.standard_normal((4, 8)).astype(np.float32))+ out = _make_multivector_output([vecs])+ sim = BGEM3FlashAdapter._colbert_sim(out, 0, out, 0)+ assert sim == pytest.approx(1.0, abs=1e-5)++ def test_colbert_sim_disjoint_directions_is_low(self) -> None:+ q = np.array([[1.0, 0.0]], dtype=np.float32)+ d = np.array([[0.0, 1.0]], dtype=np.float32)+ sim = BGEM3FlashAdapter._colbert_sim(_make_multivector_output([q]), 0, _make_multivector_output([d]), 0)+ assert sim == pytest.approx(0.0, abs=1e-6)+++class TestScoreEndToEnd:+ """Test the public score() / score_pairs() entry points with mocked encode()."""++ @pytest.fixture+ def adapter(self) -> BGEM3FlashAdapter:+ ad = BGEM3FlashAdapter()+ # Bypass _check_loaded()+ ad._model = MagicMock()+ return ad++ @staticmethod+ def _patch_encode_dense(+ adapter: BGEM3FlashAdapter,+ *,+ query_vec: np.ndarray,+ doc_vecs: np.ndarray,+ ) -> list[dict[str, Any]]:+ """Patch ``encode`` with role-aware fixture and capture the calls."""+ calls: list[dict[str, Any]] = []++ def fake_encode(+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = None,+ is_query: bool = False,+ options: dict[str, Any] | None = None,+ **_: Any,+ ) -> EncodeOutput:+ calls.append(+ {+ "n": len(items),+ "is_query": is_query,+ "output_types": list(output_types),+ "instruction": instruction,+ }+ )+ if is_query:+ return _make_dense_output(np.tile(query_vec, (len(items), 1)))+ return _make_dense_output(doc_vecs[: len(items)])++ adapter.encode = fake_encode # type: ignore[method-assign]+ return calls++ def test_score_returns_list_of_floats(self, adapter: BGEM3FlashAdapter) -> None:+ q = _normalize(np.array([[1.0, 0.0, 0.0]], dtype=np.float32))+ # Doc 0 == query (sim 1.0); doc 1 orthogonal (sim 0.0); doc 2 anti-aligned (sim -1.0)+ docs = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]], dtype=np.float32)+ self._patch_encode_dense(adapter, query_vec=q[0], doc_vecs=docs)++ scores = adapter.score(Item(text="q"), [Item(text="a"), Item(text="b"), Item(text="c")])++ assert isinstance(scores, list)+ assert len(scores) == 3+ assert all(isinstance(s, float) for s in scores)+ assert scores[0] == pytest.approx(1.0, abs=1e-5)+ assert scores[1] == pytest.approx(0.0, abs=1e-6)+ assert scores[2] == pytest.approx(-1.0, abs=1e-5)++ def test_score_pairs_returns_score_output(self, adapter: BGEM3FlashAdapter) -> None:+ q = _normalize(np.array([[1.0, 0.0]], dtype=np.float32))+ docs = np.array([[1.0, 0.0], [0.0, 1.0]], dtype=np.float32)+ self._patch_encode_dense(adapter, query_vec=q[0], doc_vecs=docs)++ out = adapter.score_pairs(+ [Item(text="q1"), Item(text="q2")],+ [Item(text="d1"), Item(text="d2")],+ )++ assert out.scores.dtype == np.float32+ assert out.scores.shape == (2,)+ assert out.scores[0] == pytest.approx(1.0, abs=1e-5)+ assert out.scores[1] == pytest.approx(0.0, abs=1e-6)++ def test_score_pairs_empty_inputs(self, adapter: BGEM3FlashAdapter) -> None:+ out = adapter.score_pairs([], [])+ assert out.scores.shape == (0,)+ assert out.scores.dtype == np.float32++ def test_score_pairs_length_mismatch_raises(self, adapter: BGEM3FlashAdapter) -> None:+ with pytest.raises(ValueError, match="equal-length"):+ adapter.score_pairs([Item(text="q")], [Item(text="d1"), Item(text="d2")])++ def test_score_empty_items(self, adapter: BGEM3FlashAdapter) -> None:+ # encode() should never be called when items is empty+ adapter.encode = MagicMock(side_effect=AssertionError("encode should not be called")) # type: ignore[method-assign]+ assert adapter.score(Item(text="q"), []) == []++ def test_score_uses_is_query_flag(self, adapter: BGEM3FlashAdapter) -> None:+ q = _normalize(np.array([[1.0, 0.0]], dtype=np.float32))+ docs = np.array([[1.0, 0.0]], dtype=np.float32)+ calls = self._patch_encode_dense(adapter, query_vec=q[0], doc_vecs=docs)++ adapter.score(Item(text="q"), [Item(text="d")])++ # First call encodes the query, second the docs+ assert len(calls) == 2+ assert calls[0]["is_query"] is True+ assert calls[0]["n"] == 1+ assert calls[1]["is_query"] is False+ assert calls[1]["n"] == 1++ def test_invalid_score_mode_raises(self, adapter: BGEM3FlashAdapter) -> None:+ with pytest.raises(ValueError, match="Invalid score_mode"):+ adapter.score(Item(text="q"), [Item(text="d")], options={"score_mode": "bogus"})++ def test_score_sparse_mode(self, adapter: BGEM3FlashAdapter) -> None:+ def fake_encode(+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = None,+ is_query: bool = False,+ options: dict[str, Any] | None = None,+ **_: Any,+ ) -> EncodeOutput:+ assert output_types == ["sparse"]+ if is_query:+ return _make_sparse_output([{10: 0.5, 20: 0.3}])+ # Two docs: first overlaps tokens 10 & 20, second only token 999+ return _make_sparse_output(+ [+ {10: 0.4, 20: 0.6, 30: 0.1}, # 0.5*0.4 + 0.3*0.6 = 0.38+ {999: 0.9}, # disjoint => 0+ ]+ )++ adapter.encode = fake_encode # type: ignore[method-assign]++ scores = adapter.score(+ Item(text="q"),+ [Item(text="d1"), Item(text="d2")],+ options={"score_mode": "sparse"},+ )+ assert scores[0] == pytest.approx(0.38, abs=1e-5)+ assert scores[1] == pytest.approx(0.0, abs=1e-6)++ def test_score_colbert_mode(self, adapter: BGEM3FlashAdapter) -> None:+ q_mv = np.array([[1.0, 0.0], [0.0, 1.0]], dtype=np.float32)+ # Doc identical to query (perfect MaxSim)+ d_mv = np.array([[1.0, 0.0], [0.0, 1.0]], dtype=np.float32)++ def fake_encode(+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = None,+ is_query: bool = False,+ options: dict[str, Any] | None = None,+ **_: Any,+ ) -> EncodeOutput:+ assert output_types == ["multivector"]+ return _make_multivector_output([q_mv if is_query else d_mv])++ adapter.encode = fake_encode # type: ignore[method-assign]++ scores = adapter.score(Item(text="q"), [Item(text="d")], options={"score_mode": "colbert"})+ assert scores == [pytest.approx(1.0, abs=1e-5)]++ def test_hybrid_dense_only_weight_equals_dense_mode(self, adapter: BGEM3FlashAdapter) -> None:+ """Hybrid with weights {dense: 1.0, others: 0.0} matches pure dense path."""+ q = _normalize(np.array([[1.0, 0.0, 0.0]], dtype=np.float32))+ docs = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=np.float32)++ def fake_encode(+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = None,+ is_query: bool = False,+ options: dict[str, Any] | None = None,+ **_: Any,+ ) -> EncodeOutput:+ # Weight-pruning should request only "dense"+ assert output_types == ["dense"]+ if is_query:+ return _make_dense_output(np.tile(q[0], (len(items), 1)))+ return _make_dense_output(docs[: len(items)])++ adapter.encode = fake_encode # type: ignore[method-assign]++ scores = adapter.score(+ Item(text="q"),+ [Item(text="d1"), Item(text="d2")],+ options={+ "score_mode": "hybrid",+ "score_weights": {"dense": 1.0, "sparse": 0.0, "colbert": 0.0},+ },+ )+ assert scores[0] == pytest.approx(1.0, abs=1e-5)+ assert scores[1] == pytest.approx(0.0, abs=1e-6)++ def test_hybrid_combines_modes(self, adapter: BGEM3FlashAdapter) -> None:+ """Hybrid score is a linear combination of the per-mode scores."""+ q_dense = _normalize(np.array([[1.0, 0.0]], dtype=np.float32))+ d_dense = _normalize(np.array([[1.0, 0.0]], dtype=np.float32)) # sim 1.0+ # Sparse: only token 5 overlaps with weights 0.5 & 0.4 -> sim 0.2++ def fake_encode(+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = None,+ is_query: bool = False,+ options: dict[str, Any] | None = None,+ **_: Any,+ ) -> EncodeOutput:+ # colbert weight is 0 -> multivector is pruned out.+ assert set(output_types) == {"dense", "sparse"}+ dense = q_dense if is_query else d_dense+ sparse = _make_sparse_output([{5: 0.5}]).sparse if is_query else _make_sparse_output([{5: 0.4}]).sparse+ return EncodeOutput(+ dense=dense,+ sparse=sparse,+ batch_size=1,+ )++ adapter.encode = fake_encode # type: ignore[method-assign]++ scores = adapter.score(+ Item(text="q"),+ [Item(text="d")],+ options={+ "score_mode": "hybrid",+ # Use convenient weights that make arithmetic obvious.+ "score_weights": {"dense": 0.5, "sparse": 0.5, "colbert": 0.0},+ },+ )+ # 0.5 * 1.0 (dense) + 0.5 * 0.2 (sparse) + 0 = 0.6+ assert scores == [pytest.approx(0.6, abs=1e-5)]++ def test_hybrid_combines_all_three_modes(self, adapter: BGEM3FlashAdapter) -> None:+ """Hybrid with all three weights > 0 fans encode out to all output types."""+ q_dense = _normalize(np.array([[1.0, 0.0]], dtype=np.float32))+ d_dense = _normalize(np.array([[1.0, 0.0]], dtype=np.float32))+ mv = np.array([[1.0, 0.0]], dtype=np.float32)++ def fake_encode(+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = None,+ is_query: bool = False,+ options: dict[str, Any] | None = None,+ **_: Any,+ ) -> EncodeOutput:+ assert set(output_types) == {"dense", "sparse", "multivector"}+ dense = q_dense if is_query else d_dense+ sparse = _make_sparse_output([{5: 0.5}]).sparse if is_query else _make_sparse_output([{5: 0.4}]).sparse+ return EncodeOutput(+ dense=dense,+ sparse=sparse,+ multivector=[mv],+ batch_size=1,+ )++ adapter.encode = fake_encode # type: ignore[method-assign]++ scores = adapter.score(+ Item(text="q"),+ [Item(text="d")],+ options={+ "score_mode": "hybrid",+ "score_weights": {"dense": 0.4, "sparse": 0.2, "colbert": 0.4},+ },+ )+ # 0.4*1.0 + 0.2*0.2 + 0.4*1.0 = 0.84+ assert scores == [pytest.approx(0.84, abs=1e-5)]diff --git a/packages/sie_server/tests/api/test_encode_dtype.py b/packages/sie_server/tests/api/test_encode_dtype.pyindex 045996a79..c6abcfec0 100644--- a/packages/sie_server/tests/api/test_encode_dtype.py+++ b/packages/sie_server/tests/api/test_encode_dtype.py@@ -80,6 +80,8 @@ def mock_registry(mock_adapter: MagicMock) -> MagicMock:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="test-model",@@ -361,6 +363,8 @@ class TestProfileOutputDtype:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="test-model",diff --git a/packages/sie_server/tests/api/test_encode_endpoint.py b/packages/sie_server/tests/api/test_encode_endpoint.pyindex 9a29fd422..12012aa18 100644--- a/packages/sie_server/tests/api/test_encode_endpoint.py+++ b/packages/sie_server/tests/api/test_encode_endpoint.py@@ -1,3 +1,4 @@+import timefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock@@ -16,6 +17,7 @@ from sie_server.config.model import (ProfileConfig,Tasks,)+from sie_server.core.load_errors import LoadErrorClass, LoadFailurefrom sie_server.core.registry import ModelRegistry# Patch msgpack for numpy support@@ -83,6 +85,8 @@ def mock_registry(mock_adapter: MagicMock) -> MagicMock:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="test-model",@@ -242,6 +246,44 @@ class TestEncodeEndpoint:assert "loading" in data["detail"]["message"].lower()mock_registry.start_load_async.assert_called_once()+ def test_encode_returns_model_load_failed_when_terminal(self, client: TestClient, mock_registry: MagicMock) -> None:+ """A registry-recorded terminal failure returns 502 MODEL_LOAD_FAILED.++ Regression for sie-test#85: previously the API returned 503+ MODEL_LOADING for any not-loaded model, which the SDK retried for+ 5 minutes even on permanent gated/dependency failures. The new+ contract returns 502 MODEL_LOAD_FAILED with no Retry-After header+ so the SDK can short-circuit immediately.+ """+ failure = LoadFailure(+ error_class=LoadErrorClass.GATED,+ message="GatedModelError: HF_TOKEN missing or invalid for org/test",+ attempts=1,+ last_attempt_ts=time.monotonic(),+ cooldown_s=None,+ )+ mock_registry.is_loaded.return_value = False+ mock_registry.is_failed.return_value = True+ mock_registry.get_failure.return_value = failure++ # Should NOT trigger another background load.+ mock_registry.start_load_async = MagicMock()++ response = client.post(+ "/v1/encode/test-model",+ json={"items": [{"text": "Hello"}]},+ )+ assert response.status_code == 502+ data = response.json()+ assert data["detail"]["code"] == "MODEL_LOAD_FAILED"+ assert data["detail"]["error_class"] == "GATED"+ assert data["detail"]["permanent"] is True+ assert data["detail"]["attempts"] == 1+ # Critical: no Retry-After header so the SDK does not loop.+ assert "retry-after" not in {k.lower() for k in response.headers}+ # And no background load was kicked off.+ mock_registry.start_load_async.assert_not_called()+def test_encode_lazy_loads_model(self, client: TestClient, mock_registry: MagicMock, mock_adapter: MagicMock) -> None:@@ -580,6 +622,8 @@ class TestEncodeLoraRouting:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="test-model",diff --git a/packages/sie_server/tests/api/test_encode_json_schema.py b/packages/sie_server/tests/api/test_encode_json_schema.pyindex a5c7ba1a0..acd4fdb17 100644--- a/packages/sie_server/tests/api/test_encode_json_schema.py+++ b/packages/sie_server/tests/api/test_encode_json_schema.py@@ -80,6 +80,8 @@ def mock_registry(mock_adapter: MagicMock) -> MagicMock:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="test-model",diff --git a/packages/sie_server/tests/api/test_encode_timing.py b/packages/sie_server/tests/api/test_encode_timing.pyindex a396866a3..d377124ca 100644--- a/packages/sie_server/tests/api/test_encode_timing.py+++ b/packages/sie_server/tests/api/test_encode_timing.py@@ -78,6 +78,8 @@ def mock_registry(mock_adapter: MagicMock) -> MagicMock:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="test-model",@@ -132,6 +134,8 @@ class TestTimingHeaders:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapter_with_timingregistry.get_config.return_value = ModelConfig(sie_id="test-model",diff --git a/packages/sie_server/tests/api/test_encode_validation.py b/packages/sie_server/tests/api/test_encode_validation.pyindex 9c90d40c6..9aa023bed 100644--- a/packages/sie_server/tests/api/test_encode_validation.py+++ b/packages/sie_server/tests/api/test_encode_validation.py@@ -78,6 +78,8 @@ def mock_registry(mock_adapter: MagicMock) -> MagicMock:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="test-model",diff --git a/packages/sie_server/tests/api/test_extract.py b/packages/sie_server/tests/api/test_extract.pyindex 6f71f6961..ca16d7df0 100644--- a/packages/sie_server/tests/api/test_extract.py+++ b/packages/sie_server/tests/api/test_extract.py@@ -135,6 +135,8 @@ def mock_registry(mock_adapter: MagicMock) -> MagicMock:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="test-extractor",diff --git a/packages/sie_server/tests/api/test_extract_oom.py b/packages/sie_server/tests/api/test_extract_oom.pyindex 3e69bfcf3..9540fbdd3 100644--- a/packages/sie_server/tests/api/test_extract_oom.py+++ b/packages/sie_server/tests/api/test_extract_oom.py@@ -59,6 +59,8 @@ def _build_client(failure: BaseException) -> TestClient:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = adapterregistry.get_config.return_value = ModelConfig(sie_id="test-extractor",diff --git a/packages/sie_server/tests/api/test_models.py b/packages/sie_server/tests/api/test_models.pyindex 4d060ca01..4a750266d 100644--- a/packages/sie_server/tests/api/test_models.py+++ b/packages/sie_server/tests/api/test_models.py@@ -1,3 +1,4 @@+import timefrom unittest.mock import MagicMockimport pytest@@ -11,6 +12,7 @@ from sie_server.config.model import (ProfileConfig,Tasks,)+from sie_server.core.load_errors import LoadErrorClass, LoadFailurefrom sie_server.core.registry import ModelRegistry@@ -76,6 +78,10 @@ def mock_registry() -> MagicMock:registry.get_config = get_configregistry.has_model = has_modelregistry.is_loaded = is_loaded+ registry.is_loading = lambda _name: False+ registry.is_unloading = lambda _name: False+ registry.is_failed = lambda _name: False+ registry.get_failure = lambda _name: Nonereturn registry@@ -153,3 +159,84 @@ class TestGetModel:assert response.status_code == 404data = response.json()assert data["detail"]["code"] == "MODEL_NOT_FOUND"+++class TestModelStateField:+ """Coverage for the ``state`` and ``last_error`` fields on ``ModelInfo``."""++ def test_loaded_model_reports_loaded_state(self, client: TestClient) -> None:+ response = client.get("/v1/models/model-a")+ assert response.status_code == 200+ data = response.json()+ assert data["state"] == "loaded"+ assert data["last_error"] is None++ def test_available_model_reports_available_state(self, client: TestClient) -> None:+ response = client.get("/v1/models/model-b")+ assert response.status_code == 200+ data = response.json()+ assert data["state"] == "available"+ assert data["last_error"] is None++ def test_failed_model_reports_failed_state_with_error(self, mock_registry: MagicMock) -> None:+ """A registry-recorded failure surfaces via ``state`` + ``last_error``."""+ failure = LoadFailure(+ error_class=LoadErrorClass.GATED,+ message="GatedModelError: model is gated, set HF_TOKEN",+ attempts=2,+ last_attempt_ts=time.monotonic(),+ cooldown_s=None,+ )++ mock_registry.is_loaded = lambda name: False+ mock_registry.is_failed = lambda name: name == "model-b"+ mock_registry.get_failure = lambda name: failure if name == "model-b" else None++ app = FastAPI()+ app.include_router(models_router)+ app.state.registry = mock_registry+ client = TestClient(app)++ response = client.get("/v1/models/model-b")+ assert response.status_code == 200+ data = response.json()+ assert data["state"] == "failed"+ assert data["loaded"] is False+ assert data["last_error"] is not None+ assert data["last_error"]["code"] == "GATED"+ assert data["last_error"]["attempts"] == 2+ assert data["last_error"]["permanent"] is True+ assert "HF_TOKEN" in data["last_error"]["message"]++ def test_list_models_includes_failed_entries(self, mock_registry: MagicMock) -> None:+ """``GET /v1/models`` carries the per-model state for clients."""+ failure = LoadFailure(+ error_class=LoadErrorClass.OOM,+ message="RuntimeError: CUDA out of memory",+ attempts=1,+ last_attempt_ts=time.monotonic(),+ cooldown_s=60.0,+ )++ mock_registry.is_loaded = lambda name: False+ mock_registry.is_failed = lambda name: name == "model-a"+ mock_registry.get_failure = lambda name: failure if name == "model-a" else None++ app = FastAPI()+ app.include_router(models_router)+ app.state.registry = mock_registry+ client = TestClient(app)++ response = client.get("/v1/models")+ assert response.status_code == 200+ data = response.json()++ by_name = {m["name"]: m for m in data["models"]}+ assert by_name["model-a"]["state"] == "failed"+ assert by_name["model-a"]["last_error"]["code"] == "OOM"+ assert by_name["model-a"]["last_error"]["permanent"] is False+ assert by_name["model-b"]["state"] == "available"+ # Healthy models must not leak a stale error payload alongside+ # a failed sibling — guard against accidental cross-talk in the+ # list serializer.+ assert by_name["model-b"].get("last_error") is Nonediff --git a/packages/sie_server/tests/api/test_openai_compat.py b/packages/sie_server/tests/api/test_openai_compat.pyindex 0c43e3cc5..922e4bb16 100644--- a/packages/sie_server/tests/api/test_openai_compat.py+++ b/packages/sie_server/tests/api/test_openai_compat.py@@ -47,6 +47,8 @@ def mock_registry(mock_adapter: MagicMock) -> MagicMock:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="text-embedding-3-small",diff --git a/packages/sie_server/tests/api/test_score.py b/packages/sie_server/tests/api/test_score.pyindex 62b9ff71c..70011cc02 100644--- a/packages/sie_server/tests/api/test_score.py+++ b/packages/sie_server/tests/api/test_score.py@@ -115,6 +115,8 @@ def mock_registry(mock_adapter: MagicMock) -> MagicMock:registry.is_loaded.return_value = Trueregistry.is_loading.return_value = Falseregistry.is_unloading.return_value = False+ registry.is_failed.return_value = False+ registry.get_failure.return_value = Noneregistry.get.return_value = mock_adapterregistry.get_config.return_value = ModelConfig(sie_id="test-reranker",diff --git a/packages/sie_server/tests/core/test_preprocessor.py b/packages/sie_server/tests/core/test_preprocessor.pyindex 7cc4421dc..6b5f69c19 100644--- a/packages/sie_server/tests/core/test_preprocessor.py+++ b/packages/sie_server/tests/core/test_preprocessor.py@@ -8,6 +8,7 @@ import torchfrom PIL import Imagefrom sie_server.core.prepared import ImagePayload, PreparedItem, TextPayloadfrom sie_server.core.preprocessor import ImagePreprocessor, Preprocessor, TextPreprocessor+from sie_server.core.preprocessor.image import OpenCLIPImagePreprocessorfrom sie_server.types.inputs import ImageInput, Item@@ -349,6 +350,131 @@ class TestImagePreprocessor:assert result["pixel_values"].numel() == 0+class TestOpenCLIPImagePreprocessor:+ """Tests for OpenCLIPImagePreprocessor.++ Uses a lambda ``val_preproc`` so the tests are pure unit tests with no+ model download.+ """++ @pytest.fixture+ def fake_val_preproc(self):+ """A torchvision-compose-shaped callable: PIL.Image -> Tensor[3, 224, 224]."""++ def _fn(img: Image.Image) -> torch.Tensor:+ # Deterministic encoding of (width, height) into the first two+ # channels of the corner pixel so tests can verify which image+ # produced the tensor.+ tensor = torch.zeros(3, 224, 224)+ tensor[0, 0, 0] = float(img.width)+ tensor[1, 0, 0] = float(img.height)+ return tensor++ return _fn++ @pytest.fixture+ def mock_config(self):+ """Create mock model config."""+ return MagicMock()++ @pytest.fixture+ def sample_image_bytes(self):+ """Create a 640x480 JPEG."""+ img = Image.new("RGB", (640, 480), color="red")+ buffer = io.BytesIO()+ img.save(buffer, format="JPEG")+ return buffer.getvalue()++ def test_is_preprocessor(self, fake_val_preproc):+ """OpenCLIPImagePreprocessor satisfies the Preprocessor protocol."""+ preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")+ assert isinstance(preprocessor, Preprocessor)++ def test_modality(self, fake_val_preproc):+ """Modality is 'image'."""+ preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")+ assert preprocessor.modality == "image"++ def test_prepare_runs_val_preproc_and_records_payload(self, fake_val_preproc, mock_config, sample_image_bytes):+ """prepare() invokes val_preproc and stores the resulting tensor on the payload."""+ preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")+ items = [Item(images=[ImageInput(data=sample_image_bytes, format="jpeg")])]++ batch = preprocessor.prepare(items, config=mock_config)++ assert batch.size == 1+ assert batch.modality == "image"+ assert batch.total_cost == 1++ item = batch.items[0]+ assert item.cost == 1+ assert item.original_index == 0+ assert isinstance(item.payload, ImagePayload)+ assert item.payload.original_size == (640, 480)+ # Tensor shape is [C, H, W] (no batch dim) — same contract as ImagePreprocessor+ assert item.payload.pixel_values.shape == (3, 224, 224)+ # Verify our fake val_preproc actually ran (encoded width/height)+ assert item.payload.pixel_values[0, 0, 0].item() == 640.0+ assert item.payload.pixel_values[1, 0, 0].item() == 480.0++ def test_prepare_skips_text_only_items(self, fake_val_preproc, mock_config, sample_image_bytes):+ """Items without images are skipped; original_index of image items is preserved."""+ preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")+ items: list[Item] = [+ Item(text="text only"),+ Item(images=[ImageInput(data=sample_image_bytes, format="jpeg")]),+ Item(text="also text only"),+ ]++ batch = preprocessor.prepare(items, config=mock_config)++ assert batch.size == 1+ assert batch.total_cost == 1+ assert batch.items[0].original_index == 1++ def test_prepare_rgba_conversion(self, fake_val_preproc, mock_config):+ """RGBA images are converted to RGB before val_preproc."""+ img = Image.new("RGBA", (100, 100), color=(255, 0, 0, 128))+ buffer = io.BytesIO()+ img.save(buffer, format="PNG")+ rgba_bytes = buffer.getvalue()++ preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")+ items = [Item(images=[ImageInput(data=rgba_bytes, format="png")])]++ # Should not raise — RGBA → RGB happens before the lambda is invoked.+ batch = preprocessor.prepare(items, config=mock_config)+ assert batch.size == 1+ assert batch.items[0].payload.pixel_values.shape == (3, 224, 224)++ def test_collate_stacks_into_batch(self, fake_val_preproc):+ """collate() stacks [C, H, W] payloads into [B, C, H, W] on the requested device."""+ preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")+ prepared = [+ PreparedItem(+ payload=ImagePayload(+ pixel_values=torch.randn(3, 224, 224),+ original_size=(640, 480),+ ),+ cost=1,+ original_index=i,+ )+ for i in range(4)+ ]++ result = preprocessor.collate(prepared, device="cpu")++ assert "pixel_values" in result+ assert result["pixel_values"].shape == (4, 3, 224, 224)++ def test_collate_empty_returns_empty_tensor(self, fake_val_preproc):+ """collate() on an empty list returns a 0-element tensor (matches ImagePreprocessor)."""+ preprocessor = OpenCLIPImagePreprocessor(fake_val_preproc, "test-model")+ result = preprocessor.collate([], device="cpu")++ assert result["pixel_values"].numel() == 0++class TestNemoColEmbedPreprocessor:"""Tests for NemoColEmbedPreprocessor."""diff --git a/packages/sie_server/tests/core/test_registry_failed_state.py b/packages/sie_server/tests/core/test_registry_failed_state.pynew file mode 100644index 000000000..bec6458c4--- /dev/null+++ b/packages/sie_server/tests/core/test_registry_failed_state.py@@ -0,0 +1,217 @@+"""Tests for the terminal ``failed`` state machine in ModelRegistry.++Covers the regression tracked in sie-test#85: a load failure (gated repo,+missing dependency, etc.) used to silently return the model to+``available``, producing an infinite retry loop. The registry now records+a :class:`LoadFailure` and short-circuits ``start_load_async`` while the+failure is in cooldown, and the API surfaces ``MODEL_LOAD_FAILED`` rather+than a retryable ``MODEL_LOADING``.+"""++from __future__ import annotations++import time+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+from sie_sdk.exceptions import GatedModelError+from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.load_errors import (+ LoadErrorClass,+ classify_load_error,+)+from sie_server.core.registry import ModelRegistry+++def _make_config(name: str = "test-model", hf_id: str = "org/test") -> ModelConfig:+ return ModelConfig(+ sie_id=name,+ hf_id=hf_id,+ 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():+ """Avoid real HF downloads in unit tests."""+ with patch("sie_sdk.cache.ensure_model_cached") as mock:+ mock.return_value = Path("/fake/cache/models--org--test")+ yield mock+++def registry_with_model() -> ModelRegistry:+ registry = ModelRegistry()+ registry.add_config(_make_config())+ return registry+++# ---------------------------------------------------------------------------+# classify_load_error+# ---------------------------------------------------------------------------+++class TestClassifyLoadError:+ """Pure unit tests for the classifier."""++ def test_gated_model_error_is_permanent(self) -> None:+ exc = GatedModelError("org/private", RuntimeError("401 unauthorized"))+ result = classify_load_error(exc)+ assert result.error_class is LoadErrorClass.GATED+ assert result.is_permanent+ assert result.cooldown_s is None++ def test_import_error_is_dependency_permanent(self) -> None:+ result = classify_load_error(ImportError("Gemma3TextModel not found in transformers"))+ assert result.error_class is LoadErrorClass.DEPENDENCY+ assert result.is_permanent++ def test_module_not_found_is_dependency(self) -> None:+ result = classify_load_error(ModuleNotFoundError("no module named transformers"))+ assert result.error_class is LoadErrorClass.DEPENDENCY++ def test_oom_runtime_error_is_oom_with_cooldown(self) -> None:+ result = classify_load_error(RuntimeError("CUDA out of memory. Tried to allocate 2 GiB"))+ assert result.error_class is LoadErrorClass.OOM+ assert result.cooldown_s is not None+ assert not result.is_permanent++ def test_connection_error_is_network_with_cooldown(self) -> None:+ result = classify_load_error(ConnectionError("dns failure"))+ assert result.error_class is LoadErrorClass.NETWORK+ assert result.cooldown_s is not None++ def test_unknown_runtime_error_is_unknown_permanent(self) -> None:+ result = classify_load_error(RuntimeError("some unrelated failure"))+ assert result.error_class is LoadErrorClass.UNKNOWN+ assert result.is_permanent+++# ---------------------------------------------------------------------------+# Registry: failed state recording+# ---------------------------------------------------------------------------+++class TestRegistryFailedState:+ async def test_load_failure_is_recorded_as_terminal(self, registry_with_model: ModelRegistry) -> None:+ """A gated-model failure ends in ``_failed`` not ``_loading``/``_loaded``."""+ with patch("sie_server.core.model_loader.load_adapter") as mock_load:+ mock_load.side_effect = GatedModelError("org/test", RuntimeError("401 unauthorized"))++ await registry_with_model._load_model_background("test-model", "cpu")++ assert not registry_with_model.is_loaded("test-model")+ assert not registry_with_model.is_loading("test-model")+ assert registry_with_model.is_failed("test-model")++ failure = registry_with_model.get_failure("test-model")+ assert failure is not None+ assert failure.error_class is LoadErrorClass.GATED+ assert failure.attempts == 1+ assert failure.is_permanent++ async def test_repeated_failures_increment_attempts(self, registry_with_model: ModelRegistry) -> None:+ """Each ``_record_load_failure`` bumps the attempt counter."""+ for _ in range(3):+ registry_with_model._record_load_failure("test-model", RuntimeError("CUDA out of memory"))++ failure = registry_with_model.get_failure("test-model")+ assert failure is not None+ assert failure.attempts == 3+ assert failure.error_class is LoadErrorClass.OOM++ async def test_start_load_async_short_circuits_when_failed(self, registry_with_model: ModelRegistry) -> None:+ """A recorded permanent failure makes ``start_load_async`` a no-op."""+ registry_with_model._record_load_failure("test-model", GatedModelError("org/test", RuntimeError("401")))++ started = await registry_with_model.start_load_async("test-model", "cpu")+ assert started is False+ # No background task was created either+ assert not registry_with_model.is_loading("test-model")++ async def test_oom_cooldown_blocks_then_releases(self, registry_with_model: ModelRegistry) -> None:+ """OOM failures are transient: blocked during cooldown, retryable after."""+ import asyncio++ from sie_server.core.load_errors import LoadFailure++ # Simulate an OOM record with a short cooldown by writing it in+ # with a back-dated timestamp so the cooldown window has already+ # elapsed without an actual sleep — keeps the test deterministic+ # and avoids ``ASYNC251`` violations from ``time.sleep`` in async.+ now = time.monotonic()+ registry_with_model._failed["test-model"] = LoadFailure(+ error_class=LoadErrorClass.OOM,+ message="RuntimeError: CUDA out of memory",+ attempts=1,+ last_attempt_ts=now,+ cooldown_s=10.0, # long cooldown+ )++ # Inside cooldown — start_load_async no-ops.+ assert await registry_with_model.start_load_async("test-model", "cpu") is False++ # Rewrite the record with the timestamp far in the past so the+ # cooldown is considered expired without sleeping.+ registry_with_model._failed["test-model"] = LoadFailure(+ error_class=LoadErrorClass.OOM,+ message="RuntimeError: CUDA out of memory",+ attempts=1,+ last_attempt_ts=now - 1000.0,+ cooldown_s=10.0,+ )+ # Yield so the event loop is consistent with surrounding async test.+ await asyncio.sleep(0)+ assert not registry_with_model.is_failed("test-model")++ async def test_clear_failure_re_arms(self, registry_with_model: ModelRegistry) -> None:+ registry_with_model._record_load_failure("test-model", GatedModelError("org/test", RuntimeError("401")))+ assert registry_with_model.is_failed("test-model")+ cleared = registry_with_model.clear_failure("test-model")+ assert cleared is True+ assert not registry_with_model.is_failed("test-model")+ # Subsequent clear is a no-op and returns False.+ assert registry_with_model.clear_failure("test-model") is False++ async def test_successful_load_clears_prior_failure(self, registry_with_model: ModelRegistry) -> None:+ """A subsequent successful load wipes the failure record."""+ # Stamp a transient failure first.+ registry_with_model._record_load_failure("test-model", ConnectionError("dns failure"))+ assert registry_with_model.is_failed("test-model")++ with patch("sie_server.core.model_loader.load_adapter") as mock_load:+ mock_adapter = MagicMock()+ mock_adapter.memory_footprint.return_value = 1000+ mock_load.return_value = mock_adapter++ # Force-clear cooldown so load_async runs (would otherwise be+ # blocked in real flow; here we exercise the success-path+ # cleanup directly).+ registry_with_model._failed["test-model"] = registry_with_model._failed["test-model"].__class__(+ error_class=LoadErrorClass.NETWORK,+ message="ConnectionError",+ attempts=1,+ last_attempt_ts=time.monotonic() - 1000,+ cooldown_s=0.0001,+ )++ await registry_with_model._load_model_background("test-model", "cpu")++ assert registry_with_model.is_loaded("test-model")+ assert registry_with_model.get_failure("test-model") is None++ async def test_add_config_clears_failure(self, registry_with_model: ModelRegistry) -> None:+ """A config update is operator intent and clears sticky failures."""+ registry_with_model._record_load_failure("test-model", GatedModelError("org/test", RuntimeError("401")))+ assert registry_with_model.is_failed("test-model")++ # 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")diff --git a/packages/sie_server/tests/test_all_models.py b/packages/sie_server/tests/test_all_models.pyindex f8807ffb0..0320ff50d 100644--- a/packages/sie_server/tests/test_all_models.py+++ b/packages/sie_server/tests/test_all_models.py@@ -1,6 +1,7 @@from __future__ import annotationsimport io+import osfrom pathlib import Pathfrom typing import Any@@ -214,7 +215,16 @@ def test_alibaba_nlp_gte_qwen2_7b_instruct_dense() -> None:_assert_dense("Alibaba-NLP/gte-Qwen2-7B-instruct", 3584, None)+ not os.environ.get("HF_TOKEN"),+ reason="google/embeddinggemma-300m is gated; HF_TOKEN required to download weights",+)def test_google_embeddinggemma_300m_dense() -> None:+ # Architecture support: ``Gemma3TextModel`` requires transformers>=4.56.+ # Older versions raise ImportError/ValueError during ``AutoModel.from_pretrained``;+ # gate the test rather than letting numerical-equivalence drift mask the+ # underlying problem (sie-test#85).+ pytest.importorskip("transformers", minversion="4.56.0")_assert_dense("google/embeddinggemma-300m", 768, [0.01641845703125, 0.052001953125, -0.0009312629699707031])@@ -385,6 +395,22 @@ def test_laion_clip_vit_h_14_laion2b_image_dense() -> None:_assert_dense_image("laion/CLIP-ViT-H-14-laion2B-s32B-b79K", 1024, None)+def test_marqo_ecommerce_embeddings_b_dense() -> None:+ _assert_dense(+ "Marqo/marqo-ecommerce-embeddings-B",+ 768,+ [-0.03741455078125, 0.002193450927734375, -0.00609588623046875],+ )+++def test_marqo_ecommerce_embeddings_b_image_dense() -> None:+ _assert_dense_image(+ "Marqo/marqo-ecommerce-embeddings-B",+ 768,+ [0.00914764404296875, -0.021392822265625, 0.00676727294921875],+ )++def test_openai_clip_vit_base_patch32_dense() -> None:_assert_dense("openai/clip-vit-base-patch32", 512, [-0.003787994384765625, 0.00225830078125, -0.007648468017578125])diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex 3348063c6..679f8fb99 100644--- a/packages/sie_ts_sdk/package.json+++ b/packages/sie_ts_sdk/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-sdk",- "version": "0.3.0",+ "version": "0.3.1","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.tsindex 369fa4d94..c65419e6a 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -61,6 +61,7 @@ import {parseEncodeResults,parseExtractResults,parseScoreResult,+ throwIfModelLoadFailed,} from "./internal/parsing.js";import { packMessage, unpackMessage } from "./msgpack.js";import type {@@ -1055,6 +1056,13 @@ export class SIEClient {continue;}+ // Short-circuit terminal load failures (sie-test#85). The server+ // emits 502 MODEL_LOAD_FAILED for permanent classes (gated repos,+ // missing dependencies, unrecognised architectures); we must+ // surface the error immediately rather than burn the+ // MODEL_LOADING retry budget on a known-bad config.+ await throwIfModelLoadFailed(response, model);+// Handle 503 with LORA_LOADING or MODEL_LOADING - auto-retryif (response.status === 503) {const clonedResponse = response.clone();diff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.tsindex 630a16f4b..f88a5d5e7 100644--- a/packages/sie_ts_sdk/src/errors.ts+++ b/packages/sie_ts_sdk/src/errors.ts@@ -197,3 +197,48 @@ export class ModelLoadingError extends SIEError {this.model = model;}}++/**+ * Error when the server reports a *terminal* model-load failure.+ *+ * Distinct from {@link ModelLoadingError} — this is thrown on the first+ * response (no retry budget consumed) when the server returns HTTP+ * `502 MODEL_LOAD_FAILED`. The server uses this code for permanent-class+ * failures (gated repos, missing dependencies, unrecognised model+ * architectures) where retrying would waste time. See sie-test#85.+ *+ * Permanent failures will not auto-clear; an operator must fix the+ * underlying cause (e.g. set `HF_TOKEN`, accept the model license on+ * HuggingFace, upgrade `transformers`).+ */+export class ModelLoadFailedError extends ServerError {+ /** The model that was requested */+ readonly model: string | undefined;+ /**+ * Server-side classification: one of `GATED`, `OOM`, `DEPENDENCY`,+ * `NOT_FOUND`, `NETWORK`, `UNKNOWN`. Use this to route to specific+ * remediation paths (e.g. surface a "set HF_TOKEN" hint for `GATED`).+ */+ readonly errorClass: string | undefined;+ /** Whether the failure is non-retryable per server policy. */+ readonly permanent: boolean;+ /** How many load attempts the server has logged. */+ readonly attempts: number;++ constructor(+ message: string,+ options?: {+ model?: string;+ errorClass?: string;+ permanent?: boolean;+ attempts?: number;+ },+ ) {+ super(message, "MODEL_LOAD_FAILED", 502);+ this.name = "ModelLoadFailedError";+ this.model = options?.model;+ this.errorClass = options?.errorClass;+ this.permanent = options?.permanent ?? true;+ this.attempts = options?.attempts ?? 1;+ }+}diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.tsindex 3a4bb8b32..4af68583d 100644--- a/packages/sie_ts_sdk/src/index.ts+++ b/packages/sie_ts_sdk/src/index.ts@@ -91,6 +91,7 @@ export {PoolError,LoraLoadingError,ModelLoadingError,+ ModelLoadFailedError,} from "./errors.js";// Client-side scoring (MaxSim for ColBERT-style models)diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.tsindex e36742f43..79ddb092a 100644--- a/packages/sie_ts_sdk/src/internal/parsing.ts+++ b/packages/sie_ts_sdk/src/internal/parsing.ts@@ -2,7 +2,7 @@* Parsing utilities for SIE responses*/-import { ProvisioningError, RequestError, ServerError } from "../errors.js";+import { ModelLoadFailedError, ProvisioningError, RequestError, ServerError } from "../errors.js";import { unpackMessage } from "../msgpack.js";import type {CapacityInfo,@@ -47,9 +47,15 @@ export function getRetryAfter(response: Response): number | undefined {}/**- * Extract error code from response body (handles both JSON and msgpack)+ * Extract the error-detail object from a response body (JSON or msgpack).+ *+ * Returns the nested `error` / `detail` object so callers can read+ * auxiliary fields like `error_class`, `permanent`, `attempts` without+ * re-parsing. Used by the {@link throwIfModelLoadFailed} short-circuit.*/-export async function getErrorCode(response: Response): Promise<string | undefined> {+export async function getErrorDetail(+ response: Response,+): Promise<Record<string, unknown> | undefined> {try {const contentType = response.headers.get("content-type") ?? "";let data: Record<string, unknown>;@@ -61,25 +67,14 @@ export async function getErrorCode(response: Response): Promise<string | undefindata = (await response.json()) as Record<string, unknown>;}- // Check error.code patternif (data.error && typeof data.error === "object") {- const error = data.error as Record<string, unknown>;- if (typeof error.code === "string") {- return error.code;- }+ return data.error as Record<string, unknown>;}-- // Check detail.code patternif (data.detail && typeof data.detail === "object") {- const detail = data.detail as Record<string, unknown>;- if (typeof detail.code === "string") {- return detail.code;- }+ return data.detail as Record<string, unknown>;}-- // Check top-level codeif (typeof data.code === "string") {- return data.code;+ return data;}} catch {// Ignore parsing errors@@ -87,6 +82,58 @@ export async function getErrorCode(response: Response): Promise<string | undefinreturn undefined;}+/**+ * Extract error code from response body (handles both JSON and msgpack)+ */+export async function getErrorCode(response: Response): Promise<string | undefined> {+ const detail = await getErrorDetail(response);+ if (!detail) return undefined;+ const code = detail.code;+ return typeof code === "string" ? code : undefined;+}++/**+ * Throw {@link ModelLoadFailedError} if the response is a 502 carrying+ * the `MODEL_LOAD_FAILED` error code.+ *+ * Used by the retry loop to short-circuit *before* engaging the+ * `MODEL_LOADING` budget. The server emits 502 + this code for+ * permanent-class failures (gated repos, missing dependencies); the SDK+ * must surface the error immediately rather than retrying for the full+ * provision timeout.+ *+ * No-op for any other status / error code.+ */+export async function throwIfModelLoadFailed(response: Response, model?: string): Promise<void> {+ if (response.status !== 502) return;+ const detail = await getErrorDetail(response.clone());+ if (!detail) return;+ if (detail.code !== "MODEL_LOAD_FAILED") return;+ const errorClass = typeof detail.error_class === "string" ? detail.error_class : undefined;+ const permanent = typeof detail.permanent === "boolean" ? detail.permanent : true;+ // Defensive: server should always send an int >= 1, but a malformed+ // payload must not crash the retry loop. Use ``Number.isFinite`` so+ // ``NaN`` (from a non-numeric string) and infinities both fall back+ // to 1, and a legitimate 0 (if the server semantics ever change) is+ // preserved instead of being clobbered by ``|| 1``.+ const attemptsRaw = detail.attempts;+ const parsedAttempts =+ typeof attemptsRaw === "number"+ ? attemptsRaw+ : typeof attemptsRaw === "string"+ ? Number.parseInt(attemptsRaw, 10)+ : Number.NaN;+ const attempts = Number.isFinite(parsedAttempts) ? parsedAttempts : 1;+ const message =+ typeof detail.message === "string" ? detail.message : `Model '${model ?? "?"}' failed to load`;+ throw new ModelLoadFailedError(message, {+ model,+ errorClass,+ permanent,+ attempts,+ });+}+/*** Handle HTTP error response and throw appropriate error*/diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 892aa3ec9..403c3f419 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.3.0"; // x-release-please-version+export const SDK_VERSION = "0.3.1"; // x-release-please-versiondiff --git a/packages/sie_ts_sdk/tests/modelLoadFailed.test.ts b/packages/sie_ts_sdk/tests/modelLoadFailed.test.tsnew file mode 100644index 000000000..61bfed0d0--- /dev/null+++ b/packages/sie_ts_sdk/tests/modelLoadFailed.test.ts@@ -0,0 +1,175 @@+/**+ * Tests for the ``ModelLoadFailedError`` short-circuit (sie-test#85).+ *+ * A 502 ``MODEL_LOAD_FAILED`` response must:+ * - throw {@link ModelLoadFailedError} immediately on the first response+ * - never engage the ``MODEL_LOADING`` retry budget (no sleep, no retry)+ * - expose the structured ``errorClass`` / ``permanent`` / ``attempts``+ * fields from the server payload+ *+ * The 503 ``MODEL_LOADING`` retry behavior must be unchanged.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SIEClient } from "../src/client.js";+import { ModelLoadFailedError, ModelLoadingError, SIEError } from "../src/errors.js";+import { packMessage } from "../src/msgpack.js";++const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);++function loadFailedResponse(+ options: {+ errorClass?: string;+ permanent?: boolean;+ attempts?: number;+ message?: string;+ } = {},+): Response {+ const body = JSON.stringify({+ detail: {+ code: "MODEL_LOAD_FAILED",+ message: options.message ?? "Model 'org/test' failed to load",+ error_class: options.errorClass ?? "GATED",+ permanent: options.permanent ?? true,+ attempts: options.attempts ?? 1,+ },+ });+ return new Response(body, {+ status: 502,+ headers: { "Content-Type": "application/json" },+ });+}++function modelLoadingResponse(): Response {+ // ``Retry-After: 1`` is the smallest positive integer the parser accepts;+ // values <=0 fall through to ``MODEL_LOADING_DEFAULT_DELAY`` (5s) which+ // would blow past the test timeout.+ return new Response(JSON.stringify({ detail: { code: "MODEL_LOADING", message: "loading" } }), {+ status: 503,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": "1",+ },+ });+}++function encodeSuccessResponse(): Response {+ return new Response(+ packMessage({ items: [{ dense: { values: new Float32Array([0.1, 0.2]) } }] }),+ {+ status: 200,+ headers: { "Content-Type": "application/msgpack" },+ },+ );+}++describe("ModelLoadFailedError class", () => {+ it("is a SIEError but not a ModelLoadingError", () => {+ const err = new ModelLoadFailedError("test", { model: "x" });+ expect(err).toBeInstanceOf(SIEError);+ expect(err).toBeInstanceOf(Error);+ expect(err).not.toBeInstanceOf(ModelLoadingError);+ expect(err.name).toBe("ModelLoadFailedError");+ });++ it("defaults permanent=true and attempts=1", () => {+ const err = new ModelLoadFailedError("test");+ expect(err.permanent).toBe(true);+ expect(err.attempts).toBe(1);+ });++ it("preserves all structured fields", () => {+ const err = new ModelLoadFailedError("gated", {+ model: "org/m",+ errorClass: "GATED",+ permanent: true,+ attempts: 3,+ });+ expect(err.model).toBe("org/m");+ expect(err.errorClass).toBe("GATED");+ expect(err.permanent).toBe(true);+ expect(err.attempts).toBe(3);+ });+});++describe("502 MODEL_LOAD_FAILED short-circuit", () => {+ beforeEach(() => {+ mockFetch.mockClear();+ });++ afterEach(() => {+ mockFetch.mockClear();+ });++ it("throws ModelLoadFailedError on the first response", async () => {+ mockFetch.mockResolvedValueOnce(loadFailedResponse());+ const client = new SIEClient("http://localhost:8080");++ await expect(client.encode("org/test", { text: "hi" })).rejects.toThrow(ModelLoadFailedError);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it("populates errorClass / permanent / attempts from payload", async () => {+ mockFetch.mockResolvedValueOnce(+ loadFailedResponse({+ errorClass: "DEPENDENCY",+ permanent: true,+ attempts: 4,+ }),+ );+ const client = new SIEClient("http://localhost:8080");++ try {+ await client.encode("org/test", { text: "hi" });+ throw new Error("should have thrown");+ } catch (err) {+ expect(err).toBeInstanceOf(ModelLoadFailedError);+ const e = err as ModelLoadFailedError;+ expect(e.errorClass).toBe("DEPENDENCY");+ expect(e.permanent).toBe(true);+ expect(e.attempts).toBe(4);+ expect(e.model).toBe("org/test");+ }+ });++ it("does not consume the MODEL_LOADING retry budget", async () => {+ // Even with a long provision timeout, a 502 must surface immediately.+ mockFetch.mockResolvedValueOnce(loadFailedResponse());+ const client = new SIEClient("http://localhost:8080", {+ provisionTimeout: 600_000, // 10 min — would burn 5 min on 503 loop+ });++ const startTime = Date.now();+ await expect(client.encode("org/test", { text: "hi" })).rejects.toThrow(ModelLoadFailedError);+ const elapsed = Date.now() - startTime;++ // Must complete in well under a second; no retry sleeps consumed.+ expect(elapsed).toBeLessThan(1000);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it("does not affect 503 MODEL_LOADING retry behavior", async () => {+ // Fake timers so the 1s Retry-After sleep doesn't blow the test+ // budget. Vitest's ``vi.useFakeTimers`` advances ``setTimeout``+ // synchronously when paired with ``vi.runAllTimersAsync`` below.+ vi.useFakeTimers();+ try {+ mockFetch+ .mockResolvedValueOnce(modelLoadingResponse())+ .mockResolvedValueOnce(modelLoadingResponse())+ .mockResolvedValueOnce(encodeSuccessResponse());++ const client = new SIEClient("http://localhost:8080");+ const promise = client.encode("bge-m3", { text: "hi" });+ // Drain pending timers (the sleep() between retries) without+ // wall-clock waits.+ await vi.runAllTimersAsync();+ const result = await promise;+ expect(result.dense).toBeDefined();+ expect(mockFetch).toHaveBeenCalledTimes(3);+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/uv.lock b/uv.lockindex bb745ce91..2dccf57ee 100644--- a/uv.lock+++ b/uv.lock@@ -1327,6 +1327,18 @@ http = [{ name = "aiohttp" },]+[[package]]+name = "ftfy"+version = "6.3.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "wcwidth" },+]+sdist = { url = "https://files.pythonhosted.org/packages/a5/d3/8650919bc3c7c6e90ee3fa7fd618bf373cbbe55dff043bd67353dbb20cd8/ftfy-6.3.1.tar.gz", hash = "sha256:9b3c3d90f84fb267fe64d375a07b7f8912d817cf86009ae134aa03e1819506ec", size = 308927 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/ab/6e/81d47999aebc1b155f81eca4477a616a70f238a2549848c38983f3c22a82/ftfy-6.3.1-py3-none-any.whl", hash = "sha256:7c70eb532015cd2f9adb53f101fb6c7945988d023a085d127d1573dc49dd0083", size = 44821 },+]+[[package]]name = "gitdb"version = "4.0.12"@@ -3372,6 +3384,28 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f7/86/9a1ac7c8a8eba7967935d4c109fc956d8f9ba61cba61d9368315bb27d0bc/onnxruntime-1.25.0-cp312-cp312-win_arm64.whl", hash = "sha256:463aed7f5e4a3ca5a476db7e9bba9164fa26921ef34c37e59b28c4c61e55f266", size = 12600072 },]+[[package]]+name = "open-clip-torch"+version = "2.32.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "ftfy" },+ { name = "huggingface-hub" },+ { name = "regex" },+ { name = "safetensors" },+ { name = "timm" },+ { name = "torch", version = "2.9.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },+ { name = "torch", version = "2.9.1+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux'" },+ { name = "torchvision", version = "0.24.1", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "platform_machine == 'aarch64' and sys_platform == 'linux'" },+ { name = "torchvision", version = "0.24.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },+ { name = "torchvision", version = "0.24.1+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "platform_machine != 'aarch64' and sys_platform == 'linux'" },+ { name = "tqdm" },+]+sdist = { url = "https://files.pythonhosted.org/packages/6d/7b/fd38dfd522968135dce71d0b543c2ae776f9c8e27df6ad46b63bab09eef7/open_clip_torch-2.32.0.tar.gz", hash = "sha256:0220bc111162527eb738c1fe20dbfd6ea45dfe44726b54a4de18d3945d8f2f00", size = 1491248 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/32/f9/0458745c1d299411161ee3b6c32228a3de0be1d8497d779fd7f17a8e96aa/open_clip_torch-2.32.0-py3-none-any.whl", hash = "sha256:80b35b43e37afc2b6173aa5ab0ad68744ab3a3211e624f72dfe743a162707637", size = 1528783 },+]+[[package]]name = "openai"version = "2.30.0"@@ -5145,7 +5179,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.3.0"+version = "0.3.1"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5178,7 +5212,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.3.0"+version = "0.3.1"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5255,7 +5289,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.3.0"+version = "0.3.1"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5327,7 +5361,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.3.0"+version = "0.3.1"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5352,7 +5386,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.3.0"+version = "0.3.1"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5377,7 +5411,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.3.0"+version = "0.3.1"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5404,7 +5438,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.3.0"+version = "0.3.1"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -5431,7 +5465,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.3.0"+version = "0.3.1"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -5458,7 +5492,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.3.0"+version = "0.3.1"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -5485,7 +5519,7 @@ requires-dist = [[[package]]name = "sie-qdrant"-version = "0.3.0"+version = "0.3.1"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -5508,7 +5542,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.3.0"+version = "0.3.1"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -5557,7 +5591,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.3.0"+version = "0.3.1"source = { editable = "packages/sie_server" }dependencies = [{ name = "docling" },@@ -5574,6 +5608,7 @@ dependencies = [{ name = "msgspec" },{ name = "nats-py" },{ name = "numpy" },+ { name = "open-clip-torch" },{ name = "opentelemetry-api" },{ name = "opentelemetry-exporter-otlp" },{ name = "opentelemetry-instrumentation-fastapi" },@@ -5634,6 +5669,7 @@ requires-dist = [{ name = "nats-py", specifier = ">=2.9,<3" },{ name = "numpy", specifier = ">=2,<3" },{ name = "nvidia-ml-py", marker = "extra == 'gpu-metrics'", specifier = ">=13.5,<14" },+ { name = "open-clip-torch", specifier = ">=2.24" },{ name = "opentelemetry-api", specifier = ">=1.28,<2" },{ name = "opentelemetry-exporter-otlp", specifier = ">=1.28,<2" },{ name = "opentelemetry-instrumentation-fastapi", specifier = ">=0.49b0,<1" },@@ -5668,7 +5704,7 @@ dev = [][[package]]name = "sie-weaviate"-version = "0.3.0"+version = "0.3.1"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },