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.7.0
github-actions[bot]641331ae8bbb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 55c961f62..ba888f303 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,23 @@# Changelog+## v0.7.0++- chore(release): refresh locks and generated sources+- chore(main): release 0.7.0+- fix(release): unpin sidecar path dependency+- fix(sdk): refresh stale job result refs+- fix(cloud): align catalog canary model contracts+- fix(server): normalize Grounding DINO instructions+- test(server): isolate serve environment fixtures+- fix(server): validate pinned model selection+- fix(server): preserve pinned models in serve config+- fix(clients): address terminal response review+- fix(cloud): harden generation response handling+- feat(cloud): bill audio_ms at a 1,150 ms minimum duration+- fix(server): echo queued extract item ids+- fix(deps): declare requests and huggingface-hub in the serving distribution+- fix(deps): provide the dependencies the bundle and the eval already declare+## v0.6.30- chore(release): refresh locks and generated sourcesdiff --git a/Cargo.lock b/Cargo.lockindex e717571c3..0fc4e319f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3583,7 +3583,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-audio-prep"-version = "0.6.30"+version = "0.7.0"dependencies = ["audioadapter-buffers","opusic-sys",@@ -3597,7 +3597,7 @@ dependencies = [[[package]]name = "sie-gateway"-version = "0.6.30"+version = "0.7.0"dependencies = ["arc-swap","async-nats",@@ -3655,7 +3655,7 @@ dependencies = [[[package]]name = "sie-server-sidecar"-version = "0.6.30"+version = "0.7.0"dependencies = ["anyhow","async-nats",diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex 8345ed00c..39c084b28 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.6.30 # x-release-please-version-appVersion: v0.6.30 # x-release-please-version+version: 0.7.0 # x-release-please-version+appVersion: v0.7.0 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex e29232202..fdb1f9798 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.30"+version = "0.7.0"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 280685d36..979ed7758 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.30"+version = "0.7.0"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 02ec8cb51..b76cfd202 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.30"+version = "0.7.0"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 93c27677e..680e1032a 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.30"+version = "0.7.0"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 cd933b2c2..412b9d934 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.30"+version = "0.7.0"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex f84c437ff..1da786e4f 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.30"+version = "0.7.0"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex de0b37933..54955d21e 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.30"+version = "0.7.0"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 26538cf92..1f4723dc9 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.30"+version = "0.7.0"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 359fa46a7..37a1a671b 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.6.30",+ "version": "0.7.0","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 0c95159d1..4f712015c 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.6.30",+ "version": "0.7.0","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 e80072bd9..4dd2d09bb 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.6.30",+ "version": "0.7.0","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 0375c1c74..b01eb6c4c 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.6.30",+ "version": "0.7.0","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 2b8ccae62..e56c81903 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.30"+version = "0.7.0"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_audio_prep/Cargo.toml b/packages/sie_audio_prep/Cargo.tomlindex 644108385..b33609411 100644--- a/packages/sie_audio_prep/Cargo.toml+++ b/packages/sie_audio_prep/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-audio-prep"-version = "0.6.30"+version = "0.7.0"edition = "2021"license = "Apache-2.0"description = "Bounded, shared audio decoding and resampling for SIE workers."diff --git a/packages/sie_audio_prep/build_wheel.py b/packages/sie_audio_prep/build_wheel.pyindex 7db1a4d8b..45bec2959 100644--- a/packages/sie_audio_prep/build_wheel.py+++ b/packages/sie_audio_prep/build_wheel.py@@ -16,7 +16,7 @@ import zipfilefrom pathlib import PathMATURIN_VERSION = "1.13.3"-AUDIO_PREP_VERSION = "0.6.30" # x-release-please-version+AUDIO_PREP_VERSION = "0.7.0" # x-release-please-versionAUDIO_WHEEL_COMPATIBILITY = "manylinux_2_28"AUDIO_WHEEL_FILENAME = f"sie_audio_prep-{AUDIO_PREP_VERSION}-cp312-abi3-{AUDIO_WHEEL_COMPATIBILITY}_x86_64.whl"AUDIO_WHEEL_REMOTE = f"/opt/sie/wheels/{AUDIO_WHEEL_FILENAME}"diff --git a/packages/sie_audio_prep/pyproject.toml b/packages/sie_audio_prep/pyproject.tomlindex cc61c324b..ab9ef3dda 100644--- a/packages/sie_audio_prep/pyproject.toml+++ b/packages/sie_audio_prep/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "maturin"[project]name = "sie-audio-prep"-version = "0.6.30"+version = "0.7.0"description = "Bounded, shared audio decoding and resampling for SIE workers."requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex e2e255e5b..e5eabe526 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.30"+version = "0.7.0"edition = "2021"publish = falsediff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex dc32d6602..263d484a7 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -3745,7 +3745,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.30"+ "version": "0.7.0"},"openapi": "3.1.0","paths": {diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex baa66b80c..83995bdc4 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.30"+version = "0.7.0"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex 5339838cf..66adb6be6 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -25,6 +25,8 @@ _logger = logging.getLogger(__name__)_HTTP_HEADER_NAME = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")+_HTTP_MEDIA_TYPE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+/[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")+_CONTENT_SAFE_MEDIA_TYPES = frozenset({"application/json", "application/problem+json", "text/html"})_RESERVED_BASE_URL_HEADERS = frozenset({"accept",@@ -178,6 +180,13 @@ HTTP_SERVER_ERROR = 500HTTP_SERVICE_UNAVAILABLE = 503HTTP_GATEWAY_TIMEOUT = 504+# A result ref can land on a gateway replica whose payload-store view has not+# converged yet. The gateway uses this exact 404 code to tell the SDK to fetch+# a fresh job view before trying the refs again. Keep the refresh bounded: a+# storage outage is a distinct 503 and must never be hidden by this path.+JOB_RESULT_NOT_FOUND_ERROR_CODE = "RESULT_NOT_FOUND"+JOB_RESULT_REF_MAX_REFRESHES = 3+_GENERATE_GRAMMAR_VARIANTS = frozenset({"json_schema", "regex", "ebnf"})_GENERATE_GRAMMAR_FIELDS = _GENERATE_GRAMMAR_VARIANTS | {"label", "strict"}@@ -770,16 +779,43 @@ def parse_request_metadata(headers: Any, body: Any = None) -> RequestMetadata |return metadata or None+def _terminal_response_diagnostic(response: _HttpResponse) -> str:+ """Describe a terminal response without copying attacker-controlled values."""+ raw_content_type = _header_value(response.headers, "content-type")+ content_type = "unknown"+ if isinstance(raw_content_type, str):+ candidate = raw_content_type.partition(";")[0].strip().lower()+ if candidate in _CONTENT_SAFE_MEDIA_TYPES:+ content_type = candidate+ elif _HTTP_MEDIA_TYPE.fullmatch(candidate):+ content_type = "other"+ return f"status={response.status_code}, content_type={content_type}, body_bytes={len(response.content)}"++def parse_terminal_json_object(response: _HttpResponse, *, owner: str) -> dict[str, Any]:- """Parse one terminal JSON object while retaining response metering evidence."""+ """Parse one successful terminal JSON object with content-safe diagnostics."""request = parse_request_metadata(response.headers)+ diagnostic = _terminal_response_diagnostic(response)++ if not 200 <= response.status_code < 300:+ msg = f"Unexpected {owner} HTTP response ({diagnostic})"+ raise RequestError(msg, status_code=response.status_code, request=request)++ malformed = Falsetry:data = response.json()- except (TypeError, ValueError) as exc:- raise RequestError(f"Malformed {owner} JSON response", request=request) from exc+ except (TypeError, ValueError):+ # Raise only after the parser exception context has been cleared. JSON+ # decoder exceptions can retain the raw response body (for example in+ # JSONDecodeError.doc), which must never escape through chaining.+ malformed = True+ data = None+ if malformed:+ msg = f"Malformed {owner} JSON response ({diagnostic})"+ raise RequestError(msg, status_code=response.status_code, request=request)if not isinstance(data, dict):- msg = f"Unexpected {owner} response shape: {type(data).__name__}"- raise RequestError(msg, request=request)+ msg = f"Unexpected {owner} response shape: {type(data).__name__} ({diagnostic})"+ raise RequestError(msg, status_code=response.status_code, request=request)return data@@ -1090,6 +1126,14 @@ def next_stream_retry_delay(request=parse_request_metadata(response.headers),)+ if 300 <= status < HTTP_CLIENT_ERROR:+ msg = f"Unexpected HTTP redirect ({_terminal_response_diagnostic(response)})"+ raise RequestError(+ msg,+ status_code=status,+ request=parse_request_metadata(response.headers),+ )+if status >= HTTP_CLIENT_ERROR:handle_error(response) # always raisesdiff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex e219fa33c..9b2d26dd4 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -100,6 +100,8 @@ from ._shared import (HTTP_CLIENT_ERROR,HTTP_GATEWAY_TIMEOUT,HTTP_SERVICE_UNAVAILABLE,+ JOB_RESULT_NOT_FOUND_ERROR_CODE,+ JOB_RESULT_REF_MAX_REFRESHES,JSON_CONTENT_TYPE,LORA_LOADING_DEFAULT_DELAY_S,LORA_LOADING_ERROR_CODE,@@ -3018,25 +3020,34 @@ class _AsyncJobs(_AsyncNamespace):async def results(self, job_id: str) -> JobResults:"""Async ``jobs.results`` — read + decode the finished job's chunk refs."""- job = await self.get(job_id)- chunks = job_chunks(job)- items = []- for chunk in chunks:- ref = chunk.get("ref")- if chunk.get("state") != "succeeded" or not ref:- continue- items.extend(decode_chunk_bytes(await self._read_ref(ref)))- dims = next((it["dims"] for it in items if it.get("dims")), None)- return {- "job_id": job.get("id", job_id),- "state": job.get("state"),- "total_items": job.get("total_items"),- "settled_credits": job.get("settled_credits"),- "chunks": chunks,- "retrieved": len(items),- "dims": dims,- "items": items,- }+ refreshes = 0+ while True:+ job = await self.get(job_id)+ chunks = job_chunks(job)+ items = []+ try:+ for chunk in chunks:+ ref = chunk.get("ref")+ if chunk.get("state") != "succeeded" or not ref:+ continue+ items.extend(decode_chunk_bytes(await self._read_ref(ref)))+ except RequestError as exc:+ refreshable = exc.status_code == 404 and exc.code == JOB_RESULT_NOT_FOUND_ERROR_CODE+ if refreshable and refreshes < JOB_RESULT_REF_MAX_REFRESHES:+ refreshes += 1+ continue+ raise+ dims = next((it["dims"] for it in items if it.get("dims")), None)+ return {+ "job_id": job.get("id", job_id),+ "state": job.get("state"),+ "total_items": job.get("total_items"),+ "settled_credits": job.get("settled_credits"),+ "chunks": chunks,+ "retrieved": len(items),+ "dims": dims,+ "items": items,+ }async def wait(self, job_id: str, *, timeout_s: float = 600.0, poll_s: float = 2.0) -> JobStatus:"""Poll until terminal, or return a connector plan at its stable planned phase."""diff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.pyindex 0c7a078a8..3cc786fde 100644--- a/packages/sie_sdk/src/sie_sdk/client/errors.py+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py@@ -17,7 +17,10 @@ class SIEConnectionError(SIEError):class RequestError(SIEError):- """Error in the request (4xx responses).+ """Terminal request or response-contract error.++ This covers 4xx responses plus unexpected redirects, malformed successful+ response bodies, and other terminal response-shape violations.``request`` contains canonical request, usage, and debit metadata parsedfrom the terminal response headers when the server supplied any.diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 4570d43c4..73ae3ac1f 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -108,6 +108,8 @@ from ._shared import (HTTP_CLIENT_ERROR,HTTP_GATEWAY_TIMEOUT,HTTP_SERVICE_UNAVAILABLE,+ JOB_RESULT_NOT_FOUND_ERROR_CODE,+ JOB_RESULT_REF_MAX_REFRESHES,JSON_CONTENT_TYPE,LORA_LOADING_DEFAULT_DELAY_S,LORA_LOADING_ERROR_CODE,@@ -3444,25 +3446,34 @@ class _SyncJobs(_SyncNamespace):http(s) URL in the POC) and unpacks the msgpack ``WorkResult`` array;dense embeddings decode to numpy arrays (like :meth:`encode`)."""- job = self.get(job_id)- chunks = job_chunks(job)- items = []- for chunk in chunks:- ref = chunk.get("ref")- if chunk.get("state") != "succeeded" or not ref:- continue- items.extend(decode_chunk_bytes(self._read_ref(ref)))- dims = next((it["dims"] for it in items if it.get("dims")), None)- return {- "job_id": job.get("id", job_id),- "state": job.get("state"),- "total_items": job.get("total_items"),- "settled_credits": job.get("settled_credits"),- "chunks": chunks,- "retrieved": len(items),- "dims": dims,- "items": items,- }+ refreshes = 0+ while True:+ job = self.get(job_id)+ chunks = job_chunks(job)+ items = []+ try:+ for chunk in chunks:+ ref = chunk.get("ref")+ if chunk.get("state") != "succeeded" or not ref:+ continue+ items.extend(decode_chunk_bytes(self._read_ref(ref)))+ except RequestError as exc:+ refreshable = exc.status_code == 404 and exc.code == JOB_RESULT_NOT_FOUND_ERROR_CODE+ if refreshable and refreshes < JOB_RESULT_REF_MAX_REFRESHES:+ refreshes += 1+ continue+ raise+ dims = next((it["dims"] for it in items if it.get("dims")), None)+ return {+ "job_id": job.get("id", job_id),+ "state": job.get("state"),+ "total_items": job.get("total_items"),+ "settled_credits": job.get("settled_credits"),+ "chunks": chunks,+ "retrieved": len(items),+ "dims": dims,+ "items": items,+ }def wait(self, job_id: str, *, timeout_s: float = 600.0, poll_s: float = 2.0) -> JobStatus:"""Poll until terminal, or return a connector plan at its stable planned phase."""diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex 86c679474..c9b0c4b99 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -1220,11 +1220,15 @@ class CostEstimate(TypedDict):Settlement bills the worker-authoritative counts against that plan andreleases the remainder, so the real charge is at most this number.- ``minimum_billed_units`` is present only for duration-priced (sealed custom- lane, ``gpu_second``) identities, where a dry run cannot know the request's- duration: there the quote is a rate card — ``applied_rates`` plus this- per-request floor — and ``unit_ceilings`` is the whole-window hold, not a- prediction. ``estimate_basis`` says which of the two you are looking at.+ ``minimum_billed_units`` is present only for duration-priced identities.+ On a sealed custom lane (``gpu_second``) a dry run cannot know the+ request's duration: there the quote is a rate card — ``applied_rates``+ plus this per-request floor — and ``unit_ceilings`` is the whole-window+ hold, not a prediction. On a measured ``audio_ms`` identity it is the+ minimum billed audio duration: a request settles at least this many+ milliseconds of accepted audio, so below it the rate is a+ per-started-window price and above it a duration price.+ ``estimate_basis`` says which of these you are looking at.Every field except ``minimum_billed_units`` is always present: the gatewayserializes a whole ``ReservationPlan`` projection, so a partial quote is notdiff --git a/packages/sie_sdk/tests/client/test_generate.py b/packages/sie_sdk/tests/client/test_generate.pyindex 31811106b..ae8776344 100644--- a/packages/sie_sdk/tests/client/test_generate.py+++ b/packages/sie_sdk/tests/client/test_generate.py@@ -11,6 +11,7 @@ Mocks the HTTP layer; exercises:from __future__ import annotationsimport json+import tracebackfrom types import MappingProxyTypefrom unittest.mock import AsyncMock, MagicMock, patch@@ -18,6 +19,7 @@ import httpximport pytestfrom sie_sdk import SIEAsyncClient, SIEClient, SIEConnectionErrorfrom sie_sdk.client._shared import validate_generate_grammar+from sie_sdk.client.async_ import _AioResponsefrom sie_sdk.client.errors import ProvisioningError, RequestError, ServerError@@ -78,6 +80,19 @@ def _resp_503_openai_provisioning() -> MagicMock:return response+def _resp_303() -> MagicMock:+ response = MagicMock()+ response.status_code = 303+ response.headers = {+ "content-type": " Text/HTML ; charset=utf-8",+ "Location": "https://redirect.example/private-token",+ "X-SIE-Request-ID": "req-generate-redirect",+ }+ response.content = "private response π".encode()+ response.json.side_effect = AssertionError("redirect response must not be parsed")+ return response++def _ok_envelope() -> dict:return {"model": "m",@@ -89,11 +104,13 @@ def _ok_envelope() -> dict:def _aio_resp(status: int, body: object, headers: dict | None = None) -> object:- from sie_sdk.client.async_ import _AioResponse-return _AioResponse(status, json.dumps(body).encode("utf-8"), headers or {"content-type": "application/json"})+def _aio_raw_resp(status: int, body: bytes, headers: dict | None = None) -> object:+ return _AioResponse(status, body, headers or {"content-type": "application/json"})++def test_openai_provisioning_header_is_classified_as_provisioning() -> None:from sie_sdk.client._shared import get_error_code, handle_error@@ -410,6 +427,67 @@ class TestSyncGenerate:}client.close()+ def test_generate_rejects_redirect_without_following_or_retrying(self) -> None:+ redirect = _resp_303()+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.side_effect = [redirect, _ok_response(_ok_envelope())]+ client = SIEClient("http://localhost:8080")+ try:+ with pytest.raises(RequestError) as excinfo:+ client.generate("m", prompt="hi", max_new_tokens=4)+ finally:+ client.close()++ error = excinfo.value+ assert error.status_code == 303+ assert error.request == {"id": "req-generate-redirect"}+ assert str(error) == (+ "Unexpected generate HTTP response "+ f"(status=303, content_type=text/html, body_bytes={len(redirect.content)})"+ )+ assert "private-token" not in str(error)+ assert "private response" not in str(error)+ assert "Location" not in str(error)+ assert mock_client.return_value.post.call_count == 1+ assert client.last_retry_count == 0+ assert mock_client.call_args.kwargs["follow_redirects"] is False+ redirect.json.assert_not_called()++ def test_generate_malformed_json_has_content_safe_diagnostics(self) -> None:+ response = MagicMock()+ response.status_code = 200+ response.headers = {+ "content-type": " application/PRIVATE-TOKEN-ABC ; charset=UTF-8",+ "Location": "https://redirect.example/private-token",+ "X-SIE-Request-ID": "req-generate-invalid-json",+ }+ response.content = "private malformed π".encode()+ response.json.side_effect = lambda: json.loads(response.content)+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = response+ client = SIEClient("http://localhost:8080")+ try:+ with pytest.raises(RequestError) as excinfo:+ client.generate("m", prompt="hi", max_new_tokens=4)+ finally:+ client.close()++ error = excinfo.value+ assert error.status_code == 200+ assert error.request == {"id": "req-generate-invalid-json"}+ assert str(error) == (+ f"Malformed generate JSON response (status=200, content_type=other, body_bytes={len(response.content)})"+ )+ assert "PRIVATE-TOKEN-ABC" not in str(error)+ assert "private-token" not in str(error)+ assert "private malformed" not in str(error)+ assert "Location" not in str(error)+ assert error.__cause__ is None+ assert error.__context__ is None+ formatted = "".join(traceback.format_exception(error))+ assert "private-token" not in formatted+ assert "private malformed" not in formatted+@pytest.mark.parametrize("body", [{"text": "ok"}, {"model": "m"}])def test_generate_invalid_object_retains_request_metadata(self, body: dict) -> None:response = _ok_response(@@ -566,6 +644,45 @@ class TestAsyncGenerate:"credits_debited": 8,}+ @pytest.mark.asyncio+ async def test_generate_rejects_redirect_without_following_or_retrying(self) -> None:+ redirect_body = "private response π".encode()+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock( # type: ignore[method-assign]+ side_effect=[+ _aio_raw_resp(+ 303,+ redirect_body,+ {+ "content-type": " Text/HTML ; charset=utf-8",+ "Location": "https://redirect.example/private-token",+ "X-SIE-Request-ID": "req-async-generate-redirect",+ },+ ),+ _aio_resp(200, _ok_envelope()),+ ]+ )+ with patch.object(client, "_ensure_session") as ensure:+ ensure.return_value.post = _make_session_post(client._post)+ try:+ with pytest.raises(RequestError) as excinfo:+ await client.generate("m", prompt="hi", max_new_tokens=4)+ finally:+ await client.close()++ error = excinfo.value+ assert error.status_code == 303+ assert error.request == {"id": "req-async-generate-redirect"}+ assert str(error) == (+ f"Unexpected generate HTTP response (status=303, content_type=text/html, body_bytes={len(redirect_body)})"+ )+ assert "private-token" not in str(error)+ assert "private response" not in str(error)+ assert "Location" not in str(error)+ assert client._post.call_count == 1+ assert ensure.return_value.post.call_count == 1+ assert ensure.return_value.post.call_args.kwargs["allow_redirects"] is False+@pytest.mark.asyncio@pytest.mark.parametrize("body", [{"text": "ok"}, {"model": "m"}])async def test_generate_invalid_object_retains_request_metadata(self, body: dict) -> None:diff --git a/packages/sie_sdk/tests/client/test_jobs.py b/packages/sie_sdk/tests/client/test_jobs.pyindex 4ba441c0b..52f45ee30 100644--- a/packages/sie_sdk/tests/client/test_jobs.py+++ b/packages/sie_sdk/tests/client/test_jobs.py@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport msgpackimport pytest-from sie_sdk import SIEAsyncClient, SIEClient+from sie_sdk import RequestError, ServerError, SIEAsyncClient, SIEClientGW = "http://gw.test:8080"KEY = "sk-sie-testkey"@@ -25,6 +25,36 @@ _SUBMIT_RESP = {}+def _result_chunk(item_id: str) -> bytes:+ return msgpack.packb(+ [+ {+ "success": True,+ "id": item_id,+ "units": {"input_tokens": 5},+ "result_msgpack": msgpack.packb(+ {"dense": {"dims": 2, "values": [0.1, 0.2]}},+ use_bin_type=True,+ ),+ }+ ],+ use_bin_type=True,+ )+++def _result_job(*refs: str) -> dict[str, Any]:+ return {+ "id": "job-1",+ "state": "succeeded",+ "total_items": len(refs),+ "settled_credits": 5 * len(refs),+ "output": {+ "kind": "refs",+ "chunks": [{"seq": seq, "items": 1, "state": "succeeded", "ref": ref} for seq, ref in enumerate(refs)],+ },+ }++def _resp(status: int, body: Any) -> MagicMock:r = MagicMock()r.status_code = status@@ -278,6 +308,74 @@ def test_results_reads_local_refs_and_decodes(tmp_path: Any) -> None:client.close()+def test_results_refreshes_job_after_replica_miss_without_duplicating_partial_items() -> None:+ stale = _result_job("https://gw.test/stale-0", "https://gw.test/stale-1")+ fresh = _result_job("https://gw.test/fresh-0", "https://gw.test/fresh-1")+ replica_miss = RequestError("not on this replica", code="RESULT_NOT_FOUND", status_code=404)+ with patch("sie_sdk.client.sync.httpx.Client"):+ client = SIEClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", side_effect=[stale, fresh]) as get_job,+ patch.object(+ client.jobs,+ "_read_ref",+ side_effect=[_result_chunk("discarded"), replica_miss, _result_chunk("0"), _result_chunk("1")],+ ) as read_ref,+ ):+ results = client.jobs.results("job-1")++ assert get_job.call_count == 2+ assert read_ref.call_count == 4+ assert results["retrieved"] == 2+ assert [item["id"] for item in results["items"]] == ["0", "1"]+ assert [chunk["ref"] for chunk in results["chunks"]] == [+ "https://gw.test/fresh-0",+ "https://gw.test/fresh-1",+ ]+ client.close()+++def test_results_bounds_replica_miss_refreshes() -> None:+ replica_miss = RequestError("not on this replica", code="RESULT_NOT_FOUND", status_code=404)+ with patch("sie_sdk.client.sync.httpx.Client"):+ client = SIEClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", return_value=_result_job("https://gw.test/stale")) as get_job,+ patch.object(client.jobs, "_read_ref", side_effect=replica_miss) as read_ref,+ pytest.raises(RequestError, match="not on this replica") as excinfo,+ ):+ client.jobs.results("job-1")++ expected_attempts = 4+ assert get_job.call_count == expected_attempts+ assert read_ref.call_count == expected_attempts+ assert excinfo.value is replica_miss+ client.close()+++ "error",+ [+ RequestError("ordinary missing ref", code="NOT_FOUND", status_code=404),+ ServerError("payload store unavailable", code="STORAGE_UNAVAILABLE", status_code=503),+ ],+)+def test_results_does_not_refresh_unrelated_ref_failures(error: RequestError | ServerError) -> None:+ with patch("sie_sdk.client.sync.httpx.Client"):+ client = SIEClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", return_value=_result_job("https://gw.test/ref")) as get_job,+ patch.object(client.jobs, "_read_ref", side_effect=error) as read_ref,+ pytest.raises(type(error)) as excinfo,+ ):+ client.jobs.results("job-1")++ get_job.assert_called_once_with("job-1")+ read_ref.assert_called_once_with("https://gw.test/ref")+ assert excinfo.value is error+ client.close()++# ---------------------------------------------------------------------------# async# ---------------------------------------------------------------------------@@ -438,3 +536,73 @@ async def test_async_repair_posts_exact_revision_predecessor_and_one_idempotency]assert result["id"] == "job-9"await client.close()+++async def test_async_results_refreshes_job_after_replica_miss_without_duplicating_partial_items() -> None:+ stale = _result_job("https://gw.test/stale-0", "https://gw.test/stale-1")+ fresh = _result_job("https://gw.test/fresh-0", "https://gw.test/fresh-1")+ replica_miss = RequestError("not on this replica", code="RESULT_NOT_FOUND", status_code=404)+ client = SIEAsyncClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", new=AsyncMock(side_effect=[stale, fresh])) as get_job,+ patch.object(+ client.jobs,+ "_read_ref",+ new=AsyncMock(+ side_effect=[_result_chunk("discarded"), replica_miss, _result_chunk("0"), _result_chunk("1")]+ ),+ ) as read_ref,+ ):+ results = await client.jobs.results("job-1")++ assert get_job.await_count == 2+ assert read_ref.await_count == 4+ assert results["retrieved"] == 2+ assert [item["id"] for item in results["items"]] == ["0", "1"]+ assert [chunk["ref"] for chunk in results["chunks"]] == [+ "https://gw.test/fresh-0",+ "https://gw.test/fresh-1",+ ]+ await client.close()+++async def test_async_results_bounds_replica_miss_refreshes() -> None:+ replica_miss = RequestError("not on this replica", code="RESULT_NOT_FOUND", status_code=404)+ client = SIEAsyncClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", new=AsyncMock(return_value=_result_job("https://gw.test/stale"))) as get_job,+ patch.object(client.jobs, "_read_ref", new=AsyncMock(side_effect=replica_miss)) as read_ref,+ pytest.raises(RequestError, match="not on this replica") as excinfo,+ ):+ await client.jobs.results("job-1")++ expected_attempts = 4+ assert get_job.await_count == expected_attempts+ assert read_ref.await_count == expected_attempts+ assert excinfo.value is replica_miss+ await client.close()+++ "error",+ [+ RequestError("ordinary missing ref", code="NOT_FOUND", status_code=404),+ ServerError("payload store unavailable", code="STORAGE_UNAVAILABLE", status_code=503),+ ],+)+async def test_async_results_does_not_refresh_unrelated_ref_failures(error: RequestError | ServerError) -> None:+ client = SIEAsyncClient(GW, api_key=KEY)+ with (+ patch.object(client.jobs, "get", new=AsyncMock(return_value=_result_job("https://gw.test/ref"))) as get_job,+ patch.object(client.jobs, "_read_ref", new=AsyncMock(side_effect=error)) as read_ref,+ pytest.raises(type(error)) as excinfo,+ ):+ await client.jobs.results("job-1")++ get_job.assert_awaited_once_with("job-1")+ read_ref.assert_awaited_once_with("https://gw.test/ref")+ assert excinfo.value is error+ await client.close()diff --git a/packages/sie_sdk/tests/client/test_responses.py b/packages/sie_sdk/tests/client/test_responses.pyindex abc48ff79..cae2c64a4 100644--- a/packages/sie_sdk/tests/client/test_responses.py+++ b/packages/sie_sdk/tests/client/test_responses.py@@ -10,7 +10,7 @@ import aiohttpimport httpximport pytestfrom sie_sdk import SIEAsyncClient, SIEClient-from sie_sdk.client.errors import ProvisioningError, ServerError, SIEConnectionError+from sie_sdk.client.errors import ProvisioningError, RequestError, ServerError, SIEConnectionErrorfrom sie_sdk.types import ResponseInputContentPart, ResponseInputMessage@@ -178,6 +178,36 @@ def test_responses_does_not_retry_post_publish_timeout() -> None:client.close()+def test_responses_rejects_redirect_without_retrying() -> None:+ redirect = _sync_response(+ 303,+ {"private": "response-body"},+ headers={+ "content-type": "text/html",+ "location": "https://redirect.example/private-token",+ "x-sie-request-id": "req-responses-redirect",+ },+ )+ with (+ patch("sie_sdk.client.sync.httpx.Client") as client_cls,+ patch("sie_sdk.client.sync.time.sleep") as sleep,+ ):+ client_cls.return_value.post.return_value = redirect+ client = SIEClient("http://localhost:8080")++ with pytest.raises(RequestError) as exc_info:+ client.responses("m", "Hi")++ assert exc_info.value.status_code == 303+ assert exc_info.value.request == {"id": "req-responses-redirect"}+ assert "private-token" not in str(exc_info.value)+ assert "response-body" not in str(exc_info.value)+ assert client_cls.return_value.post.call_count == 1+ assert client.last_retry_count == 0+ sleep.assert_not_called()+ client.close()++def test_responses_does_not_retry_midflight_transport_failure() -> None:with patch("sie_sdk.client.sync.httpx.Client") as client_cls:client_cls.return_value.post.side_effect = httpx.ReadError("connection reset")diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex aad1ee049..208aec5ef 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.6.30"+ "version": "0.7.0"},"paths": {"/healthz": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex a4b6d900e..033b077bc 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.30"+version = "0.7.0"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }@@ -25,13 +25,27 @@ dependencies = ["tokenizers>=0.20,<1","sentence-transformers>=5.0,<6","safetensors>=0.4,<1",+ # Artifact resolution (snapshot_download / hf_hub_download / scan_cache_dir)+ # is imported directly by the adapters and the disk cache, and `requests` by+ # the sglang and mlx sidecar clients. Both are mirrored in+ # bundles/default.yaml `deps` and both previously reached the image only as+ # somebody else's transitive requirement, which a lock that resolves the+ # whole workspace cannot distinguish from a first-class one (#2873).+ "huggingface-hub>=0.26,<2",+ "requests>=2.32,<3","FlagEmbedding>=1.3,<2",# LoRA runtime (adapters/peft_lora_mixin: PeftModel wrap + hot-swap).# Load-bearing for BYO-LoRA; previously only a transitive pin."peft>=0.19,<1","einops>=0.8,<1", # Tensor ops (required by NV-Embed-v2 trust_remote_code)- # GLiNER / GLiREL / GLiClass extraction adapters+ # GLiNER / GLiNER2 / GLiREL / GLiClass extraction adapters.+ # Keep every range here in step with the matching key in+ # bundles/default.yaml `deps`. That mapping is a mirror, not an install+ # authority: only what this distribution declares reaches a resolved lock+ # and therefore a built image. gliner2 lived in the bundle alone and so+ # never shipped, killing three extract cells at model load (#2873)."gliner>=0.2,<1",+ "gliner2>=1.3.1,<2","glirel>=1.0,<2","gliclass>=0.1,<1",# Docling, composite-document parser (PDF/DOCX/HTML) for extract().diff --git a/packages/sie_server/src/sie_server/adapters/grounding_dino/adapter.py b/packages/sie_server/src/sie_server/adapters/grounding_dino/adapter.pyindex a23b41c9b..a2a11840c 100644--- a/packages/sie_server/src/sie_server/adapters/grounding_dino/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/grounding_dino/adapter.py@@ -199,7 +199,9 @@ class GroundingDINOAdapter(BaseAdapter):if labels:text_prompt = " ".join(f"{label.lower().strip()}." for label in labels)elif instruction and instruction.strip():- text_prompt = instruction.strip()+ text_prompt = instruction.strip().lower()+ if not text_prompt.endswith("."):+ text_prompt += "."else:raise ValueError(_ERR_NO_PROMPT)diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.pyindex f817ac3dc..9b4b65dab 100644--- a/packages/sie_server/src/sie_server/cli.py+++ b/packages/sie_server/src/sie_server/cli.py@@ -40,7 +40,13 @@ from sie_sdk.bundle_utils import (import sie_serverfrom sie_server.api.generate import router as generate_routerfrom sie_server.api.openai_audio import router as openai_audio_router-from sie_server.app.app_state_config import ENV_DEVICES, ENV_POOL, AppStateConfig+from sie_server.app.app_state_config import (+ ENV_DEVICES,+ ENV_PINNED_MODELS,+ ENV_POOL,+ ENV_PRELOAD_MODELS,+ AppStateConfig,+)from sie_server.config.model import ModelConfigfrom sie_server.core.deps import collect_bundle_depsfrom sie_server.core.loader import load_model_configs@@ -100,6 +106,16 @@ def parse_devices(value: str | None) -> list[str] | None:return devices or None+def _canonical_model_id(value: str) -> str:+ """Normalize model IDs consistently with registry pin matching."""+ base, separator, profile = value.strip().lower().partition(":")+ base = base.strip()+ profile = profile.strip()+ if not separator or not profile or profile == "default":+ return base+ return f"{base}:{profile}"++app = typer.Typer(name="sie-server",help="Search Inference Engine - GPU inference server for search workloads",@@ -546,7 +562,7 @@ def serve(raise typer.Exit(1)typer.echo(f"Preload: {len(preload_models)} models will be loaded at startup")else:- preload_env = os.environ.get("SIE_PRELOAD_MODELS")+ preload_env = os.environ.get(ENV_PRELOAD_MODELS)if preload_env:preload_models = [m.strip() for m in preload_env.split(",") if m.strip()]if preload_models:@@ -557,12 +573,26 @@ def serve(raise typer.Exit(1)typer.echo(f"Preload (from env): {len(preload_models)} models will be loaded at startup")+ pinned_env = os.environ.get(ENV_PINNED_MODELS)+ pinned_models = [m.strip() for m in pinned_env.split(",") if m.strip()] if pinned_env else None+ if pinned_models:+ if model_filter is not None:+ selected_model_ids = {_canonical_model_id(model_id) for model_id in model_filter}+ invalid = [+ model_id for model_id in pinned_models if _canonical_model_id(model_id) not in selected_model_ids+ ]+ if invalid:+ typer.echo(f"Error: Pinned model(s) not in model filter: {', '.join(invalid)}", err=True)+ raise typer.Exit(1)+ typer.echo(f"Pinned (from env): {len(pinned_models)} models will be kept resident")+config = AppStateConfig(models_dir=models_dir_resolved,device=resolved_device,devices=resolved_devices,model_filter=model_filter,preload_models=preload_models,+ pinned_models=pinned_models,pool_name=pool_name,)diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex e51c430be..c41fd9a86 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -1942,7 +1942,8 @@ def _extract_success_outcome(# Adapter returned no results for a single-item request — surface an# error instead of publishing an object the client reads as success.return _error_outcome(bi, _INFERENCE_ERROR_CODE, "adapter returned no extraction results")- result_msgpack = msgpack.packb(extraction_results[0], use_bin_type=True)+ item_id = server_item.id if server_item.id is not None else f"item-{bi.item_index}"+ result_msgpack = msgpack.packb({**extraction_results[0], "id": item_id}, use_bin_type=True)return ItemOutcome(work_item_id=bi.work_item_id,diff --git a/packages/sie_server/tests/adapters/test_grounding_dino.py b/packages/sie_server/tests/adapters/test_grounding_dino.pyindex 584ad45ec..378f47aba 100644--- a/packages/sie_server/tests/adapters/test_grounding_dino.py+++ b/packages/sie_server/tests/adapters/test_grounding_dino.py@@ -70,7 +70,11 @@ class TestGroundingDINOAdapter:("labels", "instruction", "expected_prompt"),[(["Person", " car "], "ignored instruction", "person. car."),- (None, "find the damaged screen", "find the damaged screen"),+ (None, " Find the Damaged Screen ", "find the damaged screen."),+ (None, "text", "text."),+ (None, "text.", "text."),+ (None, "Text?", "text?."),+ (None, "Text!", "text!."),],)def test_extract_uses_labels_or_instruction_prompt(diff --git a/packages/sie_server/tests/test_cli_devices.py b/packages/sie_server/tests/test_cli_devices.pyindex 39df779fe..4f03264dd 100644--- a/packages/sie_server/tests/test_cli_devices.py+++ b/packages/sie_server/tests/test_cli_devices.py@@ -9,6 +9,8 @@ from typer.testing import CliRunnerdef test_serve_threads_sie_devices_env_to_app_config(monkeypatch, tmp_path) -> None:"""Helm-rendered SIE_DEVICES reaches AppStateConfig through the CLI path."""+ monkeypatch.delenv("SIE_PRELOAD_MODELS", raising=False)+ monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)captured: dict[str, AppStateConfig] = {}def fake_run_server(**kwargs: Any) -> None:diff --git a/packages/sie_server/tests/test_cli_pool.py b/packages/sie_server/tests/test_cli_pool.pyindex 1aa5ed26f..ca4457b4c 100644--- a/packages/sie_server/tests/test_cli_pool.py+++ b/packages/sie_server/tests/test_cli_pool.py@@ -13,6 +13,7 @@ from typer.testing import CliRunnerdef test_serve_passes_sie_pool_to_app_config(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ _clear_unrelated_serve_env(monkeypatch)captured: dict[str, Any] = {}def fake_run_server(*, config: AppStateConfig, **kwargs: Any) -> None:@@ -93,9 +94,99 @@ def _write_model(def _clear_unrelated_serve_env(monkeypatch: pytest.MonkeyPatch) -> None:"""Keep CLI tests independent from suite-level env round-trip tests."""monkeypatch.delenv("SIE_BUNDLE", raising=False)+ monkeypatch.delenv("SIE_DEVICE", raising=False)monkeypatch.delenv("SIE_EXTRA_MODELS", raising=False)+ monkeypatch.delenv("SIE_DEVICES", raising=False)+ monkeypatch.delenv("SIE_MODELS_DIR", raising=False)+ monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)monkeypatch.delenv("SIE_POOL", raising=False)monkeypatch.delenv("SIE_PRELOAD_MODELS", raising=False)+ monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)+++def test_serve_preserves_env_backed_runtime_config_through_uvicorn_handoff(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+) -> None:+ """Environment-backed serve config survives run_server's env round trip."""+ _clear_unrelated_serve_env(monkeypatch)+ model_ids = ["org/preload-a", "org/preload-b", "org/pinned-a", "org/pinned-b"]+ for index, model_id in enumerate(model_ids):+ _write_model(tmp_path / f"model-{index}.yaml", sie_id=model_id)+ captured: dict[str, AppStateConfig] = {}++ def fake_run_server(*, config: AppStateConfig, **kwargs: Any) -> None:+ config.save_to_env_vars()+ captured["config"] = AppStateConfig.from_env_vars()++ monkeypatch.setenv("SIE_POOL", "customer-a")+ monkeypatch.setenv("SIE_DEVICES", "cpu")+ monkeypatch.setenv("SIE_PRELOAD_MODELS", "org/preload-a, org/preload-b")+ monkeypatch.setenv("SIE_PINNED_MODELS", "ORG/PINNED-A:default, org/pinned-b")+ monkeypatch.setattr(cli, "run_server", fake_run_server)++ try:+ cli.serve(+ port=8080,+ host="127.0.0.1",+ device="cpu",+ models_dir=str(tmp_path),+ bundle=None,+ models=",".join(model_ids),+ local_cache=None,+ cluster_cache=None,+ hf_fallback=True,+ reload=False,+ tracing=False,+ instrumentation=False,+ verbose=False,+ log_level="info",+ preload=None,+ json_logs=False,+ )+ finally:+ monkeypatch.delenv("SIE_BUNDLE", raising=False)+ monkeypatch.delenv("SIE_HF_FALLBACK", raising=False)+ monkeypatch.delenv("SIE_INSTRUMENTATION", raising=False)++ config = captured["config"]+ assert config.devices == ["cpu"]+ assert config.pool_name == "customer-a"+ assert config.preload_models == ["org/preload-a", "org/preload-b"]+ assert config.pinned_models == ["ORG/PINNED-A:default", "org/pinned-b"]+ assert "Pinned (from env): 2 models will be kept resident" in capsys.readouterr().out+++def test_serve_rejects_pinned_models_outside_model_filter(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ _clear_unrelated_serve_env(monkeypatch)+ bundles_dir = tmp_path / "bundles"+ models_dir = tmp_path / "models"+ bundles_dir.mkdir()+ models_dir.mkdir()+ _write_bundle(bundles_dir / "fake.yaml", name="fake")+ _write_model(models_dir / "selected.yaml", sie_id="org/selected")+ called = False++ def fake_run_server(*, config: AppStateConfig, **kwargs: Any) -> None:+ nonlocal called+ called = True++ monkeypatch.setenv("SIE_PINNED_MODELS", "org/not-selected")+ monkeypatch.setattr(cli, "_DEFAULT_BUNDLES_DIR", bundles_dir)+ monkeypatch.setattr(cli, "run_server", fake_run_server)++ result = CliRunner().invoke(+ cli.app,+ ["serve", "--device", "cpu", "--models-dir", str(models_dir), "--models", "org/selected"],+ )++ assert result.exit_code == 1+ assert "Pinned model(s) not in model filter: org/not-selected" in result.output+ assert not calleddef test_load_bundle_filters_models_by_sie_pool(tmp_path: Path) -> None:diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.pyindex 1354a92ab..f059b23fe 100644--- a/packages/sie_server/tests/test_queue_executor.py+++ b/packages/sie_server/tests/test_queue_executor.py@@ -1307,16 +1307,18 @@ class TestProcessExtractBatch:assert requests[0].prepared_items == [prepared_item]@pytest.mark.asyncio- async def test_single_item_publish_and_ack(self) -> None:+ async def test_extract_results_echo_or_generate_original_item_ids(self) -> None:reg = _make_registry()worker = AsyncMock()extract_output = ExtractOutput(entities=[[{"text": "Alice", "label": "person", "score": 0.99, "start": 0, "end": 5}]])- wr = WorkerResult(output=extract_output, timing=RequestTiming())- fut: asyncio.Future[WorkerResult] = asyncio.Future()- fut.set_result(wr)- worker.submit_extract_preformed_batch = AsyncMock(return_value=[fut])+ futures: list[asyncio.Future[WorkerResult]] = []+ for _ in range(2):+ fut: asyncio.Future[WorkerResult] = asyncio.Future()+ fut.set_result(WorkerResult(output=extract_output, timing=RequestTiming()))+ futures.append(fut)+ worker.submit_extract_preformed_batch = AsyncMock(return_value=futures)reg.start_worker = AsyncMock(return_value=worker)ex = QueueExecutor(reg)@@ -1328,18 +1330,28 @@ class TestProcessExtractBatch:work_item_id="req-1.0",request_id="req-1",item_index=0,- total_items=1,+ total_items=2,timestamp=time.time(),- item={"text": "Alice works at Acme."},+ item={"id": "caller-id", "text": "Alice works at Acme."},labels=["person"],- )+ ),+ ExtractBatchItem(+ work_item_id="req-1.1",+ request_id="req-1",+ item_index=1,+ total_items=2,+ timestamp=time.time(),+ item={"text": "Bob works at Example."},+ labels=["person"],+ ),],))- assert outcome.outcomes[0].disposition == "publish_and_ack"- inner = msgpack.unpackb(outcome.outcomes[0].result_msgpack, raw=False)- assert "entities" in inner+ assert [item.work_item_id for item in outcome.outcomes] == ["req-1.0", "req-1.1"]+ assert [item.disposition for item in outcome.outcomes] == ["publish_and_ack", "publish_and_ack"]+ result_ids = [msgpack.unpackb(item.result_msgpack, raw=False)["id"] for item in outcome.outcomes]+ assert result_ids == ["caller-id", "item-1"]@pytest.mark.asyncioasync def test_effective_profile_options_drive_lora_grouping_and_invalid_is_per_item(self) -> None:diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex 8e34a79fd..83d3e8a8e 100644--- a/packages/sie_server_sidecar/Cargo.toml+++ b/packages/sie_server_sidecar/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-server-sidecar"-version = "0.6.30"+version = "0.7.0"edition = "2021"publish = falsedescription = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."@@ -14,7 +14,7 @@ name = "sie-server-sidecar"path = "src/main.rs"[dependencies]-sie-audio-prep = { path = "../sie_audio_prep", version = "0.6.20", features = ["msgpack"] }+sie-audio-prep = { path = "../sie_audio_prep", features = ["msgpack"] }# Shared OTLP transport/proxy/resource/propagation plumbing (#2339).sie-telemetry = { path = "../sie_telemetry" }tokio = { version = "1", features = ["full"] }diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex dbdefa45b..ce5fb8b36 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.6.30",+ "version": "0.7.0","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 dddf786f7..c24c0c265 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -137,6 +137,9 @@ import type {} from "./types.js";import { SDK_VERSION } from "./version.js";+const JOB_RESULT_NOT_FOUND_ERROR_CODE = "RESULT_NOT_FOUND";+const JOB_RESULT_REF_MAX_REFRESHES = 3;+/** The `client.jobs` batch namespace. */export interface JobsNamespace {/** Submit a batch job; exact connector replays may return current status. */@@ -248,6 +251,54 @@ function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}+const CONTENT_SAFE_MEDIA_TYPES = new Set([+ "application/json",+ "application/problem+json",+ "text/html",+]);++function terminalResponseDiagnostic(response: Response, bodyBytes: number): string {+ const rawContentType = response.headers.get("content-type");+ let contentType = "unknown";+ if (rawContentType !== null) {+ const candidate = rawContentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";+ contentType = CONTENT_SAFE_MEDIA_TYPES.has(candidate) ? candidate : "other";+ }+ return `status=${response.status}, content_type=${contentType}, body_bytes=${bodyBytes}`;+}++async function parseTerminalJsonObject(+ response: Response,+ owner: string,+): Promise<Record<string, unknown>> {+ const body = new Uint8Array(await response.arrayBuffer());+ if (!response.ok) {+ throw new RequestError(+ `Unexpected ${owner} HTTP response (${terminalResponseDiagnostic(response, body.byteLength)})`,+ undefined,+ response.status,+ );+ }+ let data: unknown;+ try {+ data = JSON.parse(new TextDecoder().decode(body));+ } catch {+ throw new RequestError(+ `Malformed ${owner} JSON response (${terminalResponseDiagnostic(response, body.byteLength)})`,+ undefined,+ response.status,+ );+ }+ if (data === null || typeof data !== "object" || Array.isArray(data)) {+ throw new RequestError(+ `Unexpected ${owner} response shape (${terminalResponseDiagnostic(response, body.byteLength)})`,+ undefined,+ response.status,+ );+ }+ return data as Record<string, unknown>;+}+function parseNonnegativeMeterHeader(headers: Headers, name: string): number | undefined {const raw = headers.get(name);if (raw === null || !/^(0|[1-9]\d*)$/.test(raw)) return undefined;@@ -1051,10 +1102,7 @@ export class SIEClient {provisionTimeoutMs: this.provisionTimeout,});- const data = (await response.json()) as Record<string, unknown>;- if (data === null || typeof data !== "object") {- throw new RequestError("Unexpected generate response shape");- }+ const data = await parseTerminalJsonObject(response, "generate");const result = parseGenerateResult(data);attachRequestMetadata([result], response.headers, data);return result;@@ -1084,12 +1132,14 @@ export class SIEClient {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), this.timeout);try {- return await fetch(url, {+ const response = await fetch(url, {method: "POST",headers,body: JSON.stringify(body),signal: controller.signal,+ redirect: "error",});+ return response;} catch (err) {if (err instanceof Error && err.name === "AbortError") {throw new SIEConnectionError(`Request timeout after ${this.timeout}ms`, "timeout");@@ -1178,10 +1228,10 @@ export class SIEClient {this.checkServerVersion(response);- const data = (await response.json()) as ChatCompletion;- if (data === null || typeof data !== "object") {- throw new RequestError("Unexpected chat.completion response shape");- }+ const data = (await parseTerminalJsonObject(+ response,+ "chat.completion",+ )) as unknown as ChatCompletion;attachRequestMetadata([data], response.headers, data);return data;}@@ -1389,6 +1439,7 @@ export class SIEClient {headers,body: JSON.stringify(body),signal: controller.signal,+ redirect: "error",});} catch (error) {if (signal?.aborted) {@@ -1805,6 +1856,7 @@ export class SIEClient {headers,body: JSON.stringify(requestBody),signal: controller.signal,+ redirect: "error",});if (response.status >= HTTP_CLIENT_ERROR_MIN) {@@ -1862,6 +1914,7 @@ export class SIEClient {method: "POST",headers: renewHeaders,signal: perAttempt.signal,+ redirect: "error",});if (resp.ok) break;} catch {@@ -1996,6 +2049,7 @@ export class SIEClient {method: "DELETE",headers,signal: controller.signal,+ redirect: "error",});return response.ok || response.status === 404;@@ -2375,6 +2429,7 @@ export class SIEClient {headers,body: body !== undefined ? packMessage(body) : undefined,signal: controller.signal,+ redirect: "error",});return response;@@ -2415,6 +2470,7 @@ export class SIEClient {method,headers,signal: controller.signal,+ redirect: "error",});if (!response.ok) {@@ -2472,6 +2528,7 @@ export class SIEClient {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), timeoutMs);init.signal = controller.signal;+ init.redirect = "error";try {const response = await fetch(url, init);if (!response.ok) {@@ -2564,25 +2621,40 @@ export class SIEClient {}private async jobResults(jobId: string): Promise<JobResults> {- const job = await this.jobGet(jobId);- const chunks = jobChunks(job);- const items: JobResultItem[] = [];- for (const chunk of chunks) {- if (chunk.state !== "succeeded" || !chunk.ref) continue;- const raw = await this.readRef(chunk.ref);- items.push(...decodeChunkBytes(raw));- }- const withDims = items.find((it) => it.dims != null);- return {- job_id: job.id ?? jobId,- state: job.state,- total_items: job.total_items,- settled_credits: job.settled_credits,- chunks,- retrieved: items.length,- dims: withDims ? withDims.dims : null,- items,- };+ let refreshes = 0;+ for (;;) {+ const job = await this.jobGet(jobId);+ const chunks = jobChunks(job);+ const items: JobResultItem[] = [];+ try {+ for (const chunk of chunks) {+ if (chunk.state !== "succeeded" || !chunk.ref) continue;+ const raw = await this.readRef(chunk.ref);+ items.push(...decodeChunkBytes(raw));+ }+ } catch (error) {+ const refreshable =+ error instanceof RequestError &&+ error.statusCode === 404 &&+ error.code === JOB_RESULT_NOT_FOUND_ERROR_CODE;+ if (refreshable && refreshes < JOB_RESULT_REF_MAX_REFRESHES) {+ refreshes += 1;+ continue;+ }+ throw error;+ }+ const withDims = items.find((it) => it.dims != null);+ return {+ job_id: job.id ?? jobId,+ state: job.state,+ total_items: job.total_items,+ settled_credits: job.settled_credits,+ chunks,+ retrieved: items.length,+ dims: withDims ? withDims.dims : null,+ items,+ };+ }}private async jobWait(@@ -2623,6 +2695,7 @@ export class SIEClient {const response = await fetch(ref, {headers: { Accept: "application/octet-stream" },signal: controller.signal,+ redirect: "error",});if (!response.ok) {await handleError(response);@@ -2729,6 +2802,7 @@ export class SIEClient {headers,body,signal: controller.signal,+ redirect: "error",});if (!response.ok) {await handleError(response);@@ -2761,7 +2835,12 @@ export class SIEClient {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), this.timeout);try {- const response = await fetch(url, { method: "GET", headers, signal: controller.signal });+ const response = await fetch(url, {+ method: "GET",+ headers,+ signal: controller.signal,+ redirect: "error",+ });if (!response.ok) {await handleError(response);}@@ -2946,6 +3025,7 @@ export class SIEClient {method: "GET",headers,signal: controller.signal,+ redirect: "error",});if (!response.ok) {diff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.tsindex 2886ef636..6b518ca3f 100644--- a/packages/sie_ts_sdk/src/errors.ts+++ b/packages/sie_ts_sdk/src/errors.ts@@ -60,9 +60,10 @@ export class SIEConnectionError extends SIEError {}/**- * Error in the request (4xx responses).+ * Terminal request or response-contract error.*- * Raised when the client sends an invalid request:+ * Raised for 4xx responses, malformed successful response bodies, and other+ * terminal response-shape violations. Common 4xx cases include:* - 400: Bad request (invalid parameters, malformed body)* - 401: Unauthorized (missing or invalid API key)* - 403: Forbidden (insufficient permissions)@@ -72,7 +73,7 @@ export class SIEConnectionError extends SIEError {export class RequestError extends SIEError {/** Error code from the server (e.g., "INVALID_MODEL", "VALIDATION_ERROR") */readonly code: string | undefined;- /** HTTP status code (400-499) */+ /** HTTP status code, when the failure came from a terminal response. */readonly statusCode: number | undefined;constructor(message: string, code?: string, statusCode?: number) {diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex a6d1ff1d0..02094c1d6 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -1282,11 +1282,14 @@ export interface RateIdentity {* Settlement bills the worker-authoritative counts against that plan and* releases the remainder, so the real charge is at most this number.*- * `minimum_billed_units` is present only for duration-priced (sealed custom- * lane, `gpu_second`) identities, where a dry run cannot know the request's+ * `minimum_billed_units` is present only for duration-priced identities. On a+ * sealed custom lane (`gpu_second`) a dry run cannot know the request's* duration: there the quote is a rate card — `applied_rates` plus this* per-request floor — and `unit_ceilings` is the whole-window hold, not a- * prediction. `estimate_basis` says which of the two you are reading.+ * prediction. On a measured `audio_ms` identity it is the minimum billed audio+ * duration: a request settles at least this many milliseconds of accepted+ * audio, so below it the rate is a per-started-window price and above it a+ * duration price. `estimate_basis` says which of these you are reading.*/export interface CostEstimate {endpoint: string;diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex e174f04a5..73ffb60ca 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.6.30"; // x-release-please-version+export const SDK_VERSION = "0.7.0"; // x-release-please-versiondiff --git a/packages/sie_ts_sdk/tests/chat.test.ts b/packages/sie_ts_sdk/tests/chat.test.tsindex 8fd17c556..42896c04a 100644--- a/packages/sie_ts_sdk/tests/chat.test.ts+++ b/packages/sie_ts_sdk/tests/chat.test.ts@@ -85,6 +85,7 @@ describe("SIEClient.chatCompletions", () => {const [url, init] = mockFetch.mock.calls[0];expect(url).toBe("http://localhost:8080/v1/chat/completions");expect(init.method).toBe("POST");+ expect(init.redirect).toBe("error");expect(init.headers["Content-Type"]).toBe("application/json");expect(init.headers.Accept).toBe("application/json");const body = JSON.parse(init.body);diff --git a/packages/sie_ts_sdk/tests/client.test.ts b/packages/sie_ts_sdk/tests/client.test.tsindex cd9a1e0e2..f76248143 100644--- a/packages/sie_ts_sdk/tests/client.test.ts+++ b/packages/sie_ts_sdk/tests/client.test.ts@@ -1056,6 +1056,7 @@ describe("SIEClient.createPool() - bundle / warm-floor / pinned-model args", ()const [url, init] = mockFetch.mock.calls[0];expect(url).toBe("http://localhost:8080/v1/pools");+ expect(init.redirect).toBe("error");expect(JSON.parse(init.body)).toEqual({name: "eval",gpus: { l4: 2 },diff --git a/packages/sie_ts_sdk/tests/generate.test.ts b/packages/sie_ts_sdk/tests/generate.test.tsindex 4804fb38d..e2b3a5c94 100644--- a/packages/sie_ts_sdk/tests/generate.test.ts+++ b/packages/sie_ts_sdk/tests/generate.test.ts@@ -101,6 +101,7 @@ describe("SIEClient.generate", () => {const [url, init] = mockFetch.mock.calls[0];expect(url).toBe("http://localhost:8080/v1/generate/m");expect(init.method).toBe("POST");+ expect(init.redirect).toBe("error");expect(init.headers["Content-Type"]).toBe("application/json");expect(init.headers.Accept).toBe("application/json");const body = JSON.parse(init.body);@@ -223,6 +224,36 @@ describe("SIEClient.generate", () => {);});+ it("reports malformed JSON without exposing response headers or body", async () => {+ mockFetch.mockResolvedValueOnce(+ new Response("SECRET-RESPONSE-BODY", {+ status: 200,+ headers: {+ "Content-Type": "application/PRIVATE-TOKEN-ABC",+ Location: "https://redirect.example/private-token",+ },+ }),+ );++ const client = new SIEClient("http://localhost:8080");+ const error = await client+ .generate("m", "hi", { maxNewTokens: 4 })+ .catch((caught: unknown) => caught);++ expect(error).toBeInstanceOf(RequestError);+ const requestError = error as RequestError & { cause?: unknown; stack?: string };+ expect(requestError.statusCode).toBe(200);+ expect(requestError.message).toContain(+ "Malformed generate JSON response (status=200, content_type=other, body_bytes=20)",+ );+ expect(requestError.message).not.toContain("PRIVATE-TOKEN-ABC");+ expect(requestError.message).not.toContain("SECRET-RESPONSE-BODY");+ expect(requestError.message).not.toContain("private-token");+ expect(requestError.stack).not.toContain("SECRET-RESPONSE-BODY");+ expect(requestError.cause).toBeUndefined();+ expect(mockFetch).toHaveBeenCalledOnce();+ });+// H4 regression: a truncated / malformed envelope must NOT silently// produce an empty completion. Missing or non-string `model` / `text`// raises (matches the Python SDK contract).@@ -328,6 +359,21 @@ describe("SIEClient.generate retry semantics (B1c)", () => {expect(mockFetch).toHaveBeenCalledOnce();});+ it("refuses redirects as a terminal single-shot transport error", async () => {+ const client = new SIEClient("http://localhost:8080", {+ timeout: 30_000,+ provisionTimeout: 60_000,+ });+ mockFetch.mockRejectedValueOnce(new TypeError("fetch failed"));++ await expect(+ client.generate("m", "hi", { maxNewTokens: 8, waitForCapacity: true }),+ ).rejects.toBeInstanceOf(SIEConnectionError);++ expect(mockFetch).toHaveBeenCalledOnce();+ expect(mockFetch.mock.calls[0]?.[1].redirect).toBe("error");+ });+it("does NOT retry a mid-flight TypeError when waitForCapacity is false", async () => {const client = new SIEClient("http://localhost:8080", { timeout: 1000 });diff --git a/packages/sie_ts_sdk/tests/jobs.test.ts b/packages/sie_ts_sdk/tests/jobs.test.tsindex ba17f61da..e5e458403 100644--- a/packages/sie_ts_sdk/tests/jobs.test.ts+++ b/packages/sie_ts_sdk/tests/jobs.test.ts@@ -444,6 +444,102 @@ describe("client.jobs", () => {expect(Array.from(results.items[0].dense as number[])).toEqual([0.1, 0.2, 0.3, 0.4]);});+ it("results refreshes the job after a replica miss and discards partial items", async () => {+ const chunk = (id: string) =>+ packMessage([+ {+ success: true,+ id,+ units: { input_tokens: 5 },+ result_msgpack: packMessage({ dense: { dims: 2, values: [0.1, 0.2] } }),+ },+ ]);+ const job = (prefix: string) => ({+ id: "job-1",+ state: "succeeded",+ total_items: 2,+ output: {+ kind: "refs",+ chunks: [+ { seq: 0, items: 1, state: "succeeded", ref: `http://refs.local/${prefix}-0` },+ { seq: 1, items: 1, state: "succeeded", ref: `http://refs.local/${prefix}-1` },+ ],+ },+ });+ mockFetch+ .mockResolvedValueOnce(jsonResponse(job("stale")))+ .mockResolvedValueOnce(new Response(chunk("discarded"), { status: 200 }))+ .mockResolvedValueOnce(+ jsonResponse({ detail: { code: "RESULT_NOT_FOUND", message: "not on this replica" } }, 404),+ )+ .mockResolvedValueOnce(jsonResponse(job("fresh")))+ .mockResolvedValueOnce(new Response(chunk("0"), { status: 200 }))+ .mockResolvedValueOnce(new Response(chunk("1"), { status: 200 }));++ const client = new SIEClient("http://gw:8080");+ const results = await client.jobs.results("job-1");++ expect(mockFetch).toHaveBeenCalledTimes(6);+ expect(results.retrieved).toBe(2);+ expect(results.items.map((item) => item.id)).toEqual(["0", "1"]);+ expect(results.chunks.map((chunk) => chunk.ref)).toEqual([+ "http://refs.local/fresh-0",+ "http://refs.local/fresh-1",+ ]);+ });++ it("results bounds replica-miss refreshes", async () => {+ const job = {+ id: "job-1",+ state: "succeeded",+ output: {+ kind: "refs",+ chunks: [{ seq: 0, items: 1, state: "succeeded", ref: "http://refs.local/stale" }],+ },+ };+ const expectedAttempts = 4;+ for (let attempt = 0; attempt < expectedAttempts; attempt += 1) {+ mockFetch+ .mockResolvedValueOnce(jsonResponse(job))+ .mockResolvedValueOnce(+ jsonResponse(+ { detail: { code: "RESULT_NOT_FOUND", message: "not on this replica" } },+ 404,+ ),+ );+ }++ const client = new SIEClient("http://gw:8080");+ await expect(client.jobs.results("job-1")).rejects.toMatchObject({+ code: "RESULT_NOT_FOUND",+ statusCode: 404,+ });+ expect(mockFetch).toHaveBeenCalledTimes(expectedAttempts * 2);+ });++ it.each([+ [404, "NOT_FOUND"],+ [503, "STORAGE_UNAVAILABLE"],+ ])("results does not refresh unrelated ref failure %i %s", async (status, code) => {+ const job = {+ id: "job-1",+ state: "succeeded",+ output: {+ kind: "refs",+ chunks: [{ seq: 0, items: 1, state: "succeeded", ref: "http://refs.local/ref" }],+ },+ };+ mockFetch+ .mockResolvedValueOnce(jsonResponse(job))+ .mockResolvedValueOnce(+ jsonResponse({ detail: { code, message: "terminal ref failure" } }, status),+ );++ const client = new SIEClient("http://gw:8080");+ await expect(client.jobs.results("job-1")).rejects.toMatchObject({ code, statusCode: status });+ expect(mockFetch).toHaveBeenCalledTimes(2);+ });+it("wait polls until the job reaches a terminal state", async () => {mockFetch.mockResolvedValueOnce(jsonResponse({ id: "job-1", state: "running" }))diff --git a/packages/sie_ts_sdk/tests/streaming.test.ts b/packages/sie_ts_sdk/tests/streaming.test.tsindex 947ed1b20..a2dd571e7 100644--- a/packages/sie_ts_sdk/tests/streaming.test.ts+++ b/packages/sie_ts_sdk/tests/streaming.test.ts@@ -334,6 +334,7 @@ describe("SIEClient.streamChatCompletions", () => {const [url, init] = mockFetch.mock.calls[0];expect(url).toBe("http://localhost:8080/v1/chat/completions");+ expect(init.redirect).toBe("error");expect(init.headers.Accept).toBe("text/event-stream");const body = JSON.parse(init.body);expect(body.stream).toBe(true);@@ -518,6 +519,7 @@ describe("SIEClient.streamGenerate", () => {}const [url, init] = mockFetch.mock.calls[0];expect(url).toBe("http://localhost:8080/v1/generate/Qwen__Qwen3-4B-Instruct-2507");+ expect(init.redirect).toBe("error");expect(init.headers.Accept).toBe("text/event-stream");const body = JSON.parse(init.body);expect(body).toEqual({diff --git a/uv.lock b/uv.lockindex 1651b8859..3653ed688 100644--- a/uv.lock+++ b/uv.lock@@ -1290,6 +1290,21 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/7c/6e/d54d3d2867e29b68a22b144f570c8204209647fccc7879cec5218d6ed5fb/gliner-0.2.26-py3-none-any.whl", hash = "sha256:b9baa47641efb90b9d069add0528ed2464d137991ff097f42b0cab37a91ba991", size = 170429 },]+[[package]]+name = "gliner2"+version = "1.3.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "peft" },+ { name = "pydantic" },+ { name = "requests" },+ { name = "urllib3" },+]+sdist = { url = "https://files.pythonhosted.org/packages/06/ea/d6091c70ba05d5611e49520198f40c11e5df3b0f5cedc629e4ec01c496ea/gliner2-1.3.2.tar.gz", hash = "sha256:0c07befb66c031d288c7fe0398880885a6a4016f14ff3f6e17568439fe6019d8", size = 133808 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/5e/e5/ce58a45306747714072179d24f9a6c59d642a588cededf35132bdbfd74f8/gliner2-1.3.2-py3-none-any.whl", hash = "sha256:d4e5e2f76a2eec1da5e4d6c205b6fc99dfc6c3c82ff29ea07a27565040730802", size = 96814 },+]+[[package]]name = "glirel"version = "1.2.1"@@ -4373,12 +4388,12 @@ dev = [[[package]]name = "sie-audio-prep"-version = "0.6.30"+version = "0.7.0"source = { editable = "packages/sie_audio_prep" }[[package]]name = "sie-chroma"-version = "0.6.30"+version = "0.7.0"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -4458,7 +4473,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.30"+version = "0.7.0"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -4483,7 +4498,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.30"+version = "0.7.0"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -4508,7 +4523,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.30"+version = "0.7.0"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -4535,7 +4550,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.30"+version = "0.7.0"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -4562,7 +4577,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.30"+version = "0.7.0"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -4589,7 +4604,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.30"+version = "0.7.0"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -4655,7 +4670,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.6.30"+version = "0.7.0"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -4678,7 +4693,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.30"+version = "0.7.0"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -4731,7 +4746,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.30"+version = "0.7.0"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -4741,8 +4756,10 @@ dependencies = [{ name = "flagembedding" },{ name = "gliclass" },{ name = "gliner" },+ { name = "gliner2" },{ name = "glirel" },{ name = "httpx" },+ { name = "huggingface-hub" },{ name = "loguru" },{ name = "msgpack" },{ name = "msgpack-numpy" },@@ -4762,6 +4779,7 @@ dependencies = [{ name = "pydantic-settings" },{ name = "python-multipart" },{ name = "pyyaml" },+ { name = "requests" },{ name = "rich" },{ name = "safetensors" },{ name = "sentence-transformers" },@@ -4807,8 +4825,10 @@ requires-dist = [{ name = "flash-attn", marker = "sys_platform == 'linux' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.11/flash_attn-2.7.4+cu129torch2.9-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl" },{ name = "gliclass", specifier = ">=0.1,<1" },{ name = "gliner", specifier = ">=0.2,<1" },+ { name = "gliner2", specifier = ">=1.3.1,<2" },{ name = "glirel", specifier = ">=1.0,<2" },{ name = "httpx", specifier = ">=0.28.1" },+ { name = "huggingface-hub", specifier = ">=0.26,<2" },{ name = "loguru", specifier = ">=0.7,<1" },{ name = "msgpack", specifier = ">=1.2.1,<2" },{ name = "msgpack-numpy", specifier = ">=0.4,<1" },@@ -4829,6 +4849,7 @@ requires-dist = [{ name = "pydantic-settings", specifier = ">=2.6,<3" },{ name = "python-multipart", specifier = ">=0.0.20,<1" },{ name = "pyyaml", specifier = ">=6,<7" },+ { name = "requests", specifier = ">=2.32,<3" },{ name = "rich", specifier = ">=13,<14" },{ name = "safetensors", specifier = ">=0.4,<1" },{ name = "sentence-transformers", specifier = ">=5.0,<6" },@@ -4854,7 +4875,7 @@ dev = [][[package]]name = "sie-weaviate"-version = "0.6.30"+version = "0.7.0"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },