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.6.5
github-actions[bot]cd03082baf23
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 469572361..0d0d86f36 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,33 @@# Changelog+## v0.6.5++- chore(main): release 0.6.5+- fix(gateway): preserve ref sibling schema semantics+- fix(gateway): dereference structured output schema refs+- refactor(sidecar): inline applied bundle hash+- fix(config): fingerprint model pool ownership+- chore(worker): address SGLang load review nits+- fix(gateway): align provisioning contract docs+- fix(gateway): address provisioning review feedback+- fix(server): guard readiness for removed configs+- test(server): fix ipc registry mock snapshot+- docs: clarify pool capacity semantics+- fix: align GPU memory pressure defaults+- fix(server): honor pool-aware model configs+- fix(gateway): make provisioning non-2xx universally+- fix(worker): keep SGLang loads off event loop+- fix(gateway): return retryable OpenAI provisioning errors+- test(server): cover qwen3 vl reranker document image ordering+- fix(sdk): normalize score images for wire transport+- fix(server): render qwen3 vl reranker document images in user prompt+- fix(gateway): decode native media JSON bytes+- fix(deps): bump sidecar prometheus for protobuf advisory+- fix(config): harden replace snapshot IPC+- fix(config): replace drifted export snapshots+- fix(config): detect bundle config hash drift+- fix(sie-cluster): add spot toleration to AKS worker pool+## v0.6.4- chore(main): release 0.6.4diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex b524b3a01..e41839a02 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.4 # x-release-please-version-appVersion: v0.6.4 # x-release-please-version+version: 0.6.5 # x-release-please-version+appVersion: v0.6.5 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex c0f2c403d..09c611d79 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -50,7 +50,8 @@ When scaling from zero, expect the following latencies:### Client HandlingWhen a pool is scaling from zero, the gateway returns:-- **202 Accepted** with `Retry-After: 120` header+- **503 Service Unavailable** with `X-SIE-Error-Code: PROVISIONING`+- **Retry-After: 60** header- Client should retry after the indicated delayThe SDK handles this automatically with configurable retries.@@ -194,19 +195,20 @@ Use one of these patterns deliberately:- **Static custom queue namespace**: set a worker group's `queuePool` to anamed value and declare the same name under`queueRouting.staticQueuePools`. These pool objects are synthesized by the- gateway at startup and do not expire. Example:+ gateway at startup and do not expire. Queue pool names are rendered and+ routed in lowercase. Example:```yamlqueueRouting:staticQueuePools:- companyA:+ company-a:gpus:l4: 0gpuCaps: {}workers:pools:l4:- queuePool: companyA+ queuePool: company-a````gpuCaps: {}` means uncapped admission for matching workers. Usediff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex 676846716..3655aff77 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -473,14 +473,14 @@ Returns a comma-joined, sorted list of distinct machine profiles.*/}}{{- define "sie-cluster.bundle.machineProfiles" -}}{{- $root := .root -}}-{{- $queuePool := .queuePool -}}+{{- $queuePool := .queuePool | lower -}}{{- $bundle := .bundle -}}-{{- $defaultQueuePool := default "default" $root.Values.workers.common.queuePool -}}+{{- $defaultQueuePool := default "default" $root.Values.workers.common.queuePool | lower -}}{{- $profiles := dict -}}{{- range $poolName, $pool := $root.Values.workers.pools -}}{{- if $pool.enabled -}}{{- $mp := default $poolName $pool.machineProfile -}}-{{- $qp := default $defaultQueuePool $pool.queuePool -}}+{{- $qp := default $defaultQueuePool $pool.queuePool | lower -}}{{- if eq $qp $queuePool -}}{{- range $bundleName, $bundleCfg := $pool.bundles -}}{{- if and (eq $bundleName $bundle) (dig "enabled" true $bundleCfg) -}}diff --git a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml b/deploy/helm/sie-cluster/templates/keda-scaledobject.yamlindex cefd64266..f4c8f2c9d 100644--- a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml+++ b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml@@ -80,7 +80,7 @@ data:{{- range $poolName, $pool := .Values.workers.pools }}{{- if $pool.enabled }}{{- $machineProfile := default $poolName $pool.machineProfile }}-{{- $queuePool := default (default "default" $root.Values.workers.common.queuePool) $pool.queuePool }}+{{- $queuePool := default (default "default" $root.Values.workers.common.queuePool) $pool.queuePool | lower }}{{- range $bundleName, $bundleCfg := $pool.bundles }}{{- if dig "enabled" true $bundleCfg }}{{- $bundle := $bundleName }}diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex 92d97a477..af00f973a 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -23,7 +23,7 @@ fast at render time.{{- end }}{{- $platform := default $root.Values.workers.common.platform $pool.platform }}{{- $machineProfile := default $poolName $pool.machineProfile }}-{{- $queuePool := default (default "default" $root.Values.workers.common.queuePool) $pool.queuePool }}+{{- $queuePool := default (default "default" $root.Values.workers.common.queuePool) $pool.queuePool | lower }}{{- range $bundleName, $bundleCfg := $pool.bundles }}{{- if dig "enabled" true $bundleCfg }}{{- if not (hasKey $bundleCfg "minReplicas") }}diff --git a/deploy/helm/sie-cluster/values-aks.yaml b/deploy/helm/sie-cluster/values-aks.yamlindex 7ae5b277d..d6c317aac 100644--- a/deploy/helm/sie-cluster/values-aks.yaml+++ b/deploy/helm/sie-cluster/values-aks.yaml@@ -137,10 +137,19 @@ workers:limits:cpu: "4"memory: "16Gi"+ # AKS GPU pool taint (set on every GPU node). Required regardless of spot.+ # AKS spot pool taint (set only when machineProfiles.<name>.spot=true);+ # without this, the worker pod stays Pending on spot nodes even after+ # cluster-autoscaler scales the pool up, because every kubelet on a spot+ # VMSS adds `kubernetes.azure.com/scalesetpriority=spot:NoSchedule`.tolerations:- key: nvidia.com/gpuoperator: Existseffect: NoSchedule+ - key: kubernetes.azure.com/scalesetpriority+ operator: Equal+ value: spot+ effect: NoSchedulebundles:default:minReplicas: 0diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex c0f4108e9..c89e359dd 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -361,6 +361,8 @@ workers:# should consume from a dedicated logical queue namespace / tenant pool# such as `customer-acme`, in which case callers must send that pool# explicitly (SDK `gpu="customer-acme/l4"`).+ # Queue pool values are rendered and routed in lowercase so NATS/KEDA+ # labels stay canonical even if an override uses mixed case.queuePool: default# -- Runtime class for workers (e.g., "nvidia" to enable GPU runtime)@@ -405,7 +407,7 @@ workers:## # Proactive idle-eviction TTL (seconds, default disabled).# # Unloads models that have been idle longer than this threshold.- # # Additive to the 85% pressure monitor; helps free cold weights+ # # Additive to the pressure monitor; helps free cold weights# # before pressure builds up under load.# - name: SIE_IDLE_EVICT_S# value: "300"@@ -421,9 +423,12 @@ workers:# path/port are contracts owned by the template: startup→/healthz (cheap,# process-alive), liveness→/livez (GPU-aware; restarts a wedged CUDA context,# issue #1025), readiness→/readyz (ready flag + GPU). Only the timing fields- # below are overridable. The liveness threshold is deliberately generous- # (30s × 3 = 90s, 10s timeout) so a momentarily busy GPU is not mistaken for- # a wedge.+ # below are overridable. The liveness threshold must tolerate long GPU model+ # startup as well as brief contention: /livez runs a CUDA probe, so it can+ # block while an engine-backed adapter such as SGLang is loading. Keep this+ # above SGLang's default 900s startup timeout (30s x 36 = 1080s) so the+ # adapter reaches its cleanup-safe timeout instead of kubelet killing the pod+ # mid-load.## Defaults are tightened to reduce kubelet probe-poll latency on the# cold-start path (issue #814):@@ -440,7 +445,7 @@ workers:initialDelaySeconds: 10periodSeconds: 30timeoutSeconds: 10- failureThreshold: 3+ failureThreshold: 36readiness:periodSeconds: 2timeoutSeconds: 10@@ -1081,14 +1086,15 @@ queueRouting:# Messages older than this are discarded. Set higher for slow model loads.streamMaxAgeSec: 120# -- Non-expiring pool objects synthesized by the gateway for Helm-declared- # queue namespaces. Keys are queue pool names. Use this when+ # queue namespaces. Keys are queue pool names; names are normalized to+ # lowercase before gateway storage/routing. Use this when# poolAdmission.enabled=true and a worker group sets a named non-default# workers.pools.<name>.queuePool but the pool is static/deploy-owned rather# than created through the expiring /v1/pools API.## Example:# staticQueuePools:- # companyA:+ # company-a:# gpus:# l4: 0# gpuCaps: {}diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex a565e6d0b..24ac59986 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.4"+version = "0.6.5"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 b61918701..3f845440e 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.4"+version = "0.6.5"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 8c3a919e6..d40071151 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.4"+version = "0.6.5"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 d91447343..a04f8aa21 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.4"+version = "0.6.5"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 e15dd838e..a9dbbb46f 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.4"+version = "0.6.5"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 9fa30c951..cd9fb0b94 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.4"+version = "0.6.5"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex dd1aa3d79..0308e6a29 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.4"+version = "0.6.5"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 0c09d1963..ca7180410 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.4"+version = "0.6.5"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 1ceb14645..01c38e907 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.4",+ "version": "0.6.5","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 4941fa246..c54e37eac 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.4",+ "version": "0.6.5","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 3b58e4953..241ed5d51 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.4",+ "version": "0.6.5","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 18b5b4903..b2c2c9b4b 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.4",+ "version": "0.6.5","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 e19411131..50577bf23 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.4"+version = "0.6.5"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_config/src/sie_config/config_api.py b/packages/sie_config/src/sie_config/config_api.pyindex 2ac2d4ab4..e73609545 100644--- a/packages/sie_config/src/sie_config/config_api.py+++ b/packages/sie_config/src/sie_config/config_api.py@@ -909,10 +909,10 @@ async def get_bundle(request: Request, bundle_id: str) -> Response:@router.get("/epoch")async def latest_epoch(request: Request) -> dict[str, int | str]:- """Return the current config epoch counter and bundle-set fingerprint.+ """Return the current config epoch counter and control-plane fingerprints.Lightweight complement to `GET /v1/configs/export`. Called periodically- by the Rust gateway's `state::config_poller` to detect drift on TWO+ by the Rust gateway's `state::config_poller` to detect drift on threeindependent axes:- ``epoch`` (int, monotonic): bumped on every model-config write. If the@@ -928,6 +928,12 @@ async def latest_epoch(request: Request) -> dict[str, int | str]:hash changes, independent of the model epoch — without it, a sie-configredeploy that adds a bundle would not propagate to the gateway until acoincidental model write or a manual gateway restart.+ - ``bundle_config_hashes_hash`` (hex sha256, may be empty): fingerprint+ over the per-bundle config hashes exported by ``/v1/configs/export``+ plus model-level pool ownership. This catches filesystem-baseline or+ no-store config drift where the epoch remains unchanged but workers and+ sie-config agree on a new ``bundle_config_hash`` or model pool+ assignment that stale gateways have not installed yet.Intentionally uses read auth rather than admin auth — the epoch is amonotonic integer counter and the hash is a one-way digest; neither@@ -941,11 +947,16 @@ async def latest_epoch(request: Request) -> dict[str, int | str]:# Stay tolerant of a missing registry — `/epoch` is the gateway's# liveness signal for sie-config and must keep answering even during a# registry init failure (see test_epoch_works_without_registry). Empty- # `bundles_hash` is the documented "nothing to sync" sentinel; the- # gateway will not trigger a bundle re-fetch in that state.+ # hashes are documented "nothing to sync" sentinels; the gateway+ # will not trigger a re-fetch in that state.model_registry: ModelRegistry | None = getattr(request.app.state, "model_registry", None)bundles_hash = model_registry.compute_bundles_hash() if model_registry is not None else ""- return {"epoch": epoch, "bundles_hash": bundles_hash}+ bundle_config_hashes_hash = model_registry.compute_bundle_config_hashes_hash() if model_registry is not None else ""+ return {+ "epoch": epoch,+ "bundles_hash": bundles_hash,+ "bundle_config_hashes_hash": bundle_config_hashes_hash,+ }@router.get("/export")diff --git a/packages/sie_config/src/sie_config/model_registry.py b/packages/sie_config/src/sie_config/model_registry.pyindex 7b418bf69..d0abc538e 100644--- a/packages/sie_config/src/sie_config/model_registry.py+++ b/packages/sie_config/src/sie_config/model_registry.py@@ -67,6 +67,7 @@ class ProfileConflictError(ValueError):# load error rather than tolerating them.KNOWN_ENGINES: frozenset[str] = frozenset({"pytorch"})DEFAULT_ENGINE: str = "pytorch"+_MAX_POOL_NAME_LEN = 128# Adapter-module prefix expected for each engine. The gateway's matcher# is engine-agnostic (it intersects ``bundle.adapters`` with the model's@@ -80,6 +81,35 @@ _ENGINE_ADAPTER_PREFIXES: dict[str, tuple[str, ...]] = {}+def _normalize_pool_name(config: dict) -> None:+ """Validate and canonicalize an optional model-level pool name."""+ if "pool" not in config:+ return++ raw_pool = config.get("pool")+ if raw_pool is None:+ config.pop("pool", None)+ return+ if not isinstance(raw_pool, str):+ msg = "Field 'pool' must be a string"+ raise ValueError(msg)++ pool = raw_pool.strip().lower()+ if not pool:+ config.pop("pool", None)+ return++ if (+ len(pool) > _MAX_POOL_NAME_LEN+ or pool == "_default"+ or not all(c.isascii() and (c.isalnum() or c in "_-") for c in pool)+ ):+ msg = "Field 'pool' must match [A-Za-z0-9_-]{1,128} and must not be _default"+ raise ValueError(msg)++ config["pool"] = pool++@dataclassclass BundleInfo:"""Information about a bundle.@@ -505,6 +535,37 @@ class ModelRegistry:payload = json.dumps(canonical, sort_keys=True, separators=(",", ":"))return hashlib.sha256(payload.encode("utf-8")).hexdigest()+ def compute_bundle_config_hashes_hash(self) -> str:+ """Stable SHA-256 over per-bundle config hashes and pool ownership.++ The gateway polls this via ``GET /v1/configs/epoch`` to detect+ control-plane config drift even when the model epoch is unchanged (for+ example, no-store deployments where a sie-config image redeploy+ rebuilds the filesystem baseline at epoch 0). ``bundle_config_hash``+ intentionally stays worker-parity scoped to runtime profile fields, so+ this compact fingerprint also includes model-level pool ownership: a+ pure top-level ``pool:`` move changes routing/readiness even when the+ worker-applied config hash for each bundle is otherwise unchanged.+ """+ by_bundle = {}+ with self._lock:+ bundle_ids = sorted(self._bundles)+ if not bundle_ids:+ return ""+ for bundle_id in bundle_ids:+ model_pools = {}+ for model_name, model_info in sorted(self._models.items()):+ if bundle_id not in model_info.bundles:+ continue+ pool = self._model_full_configs.get(model_name, {}).get("pool") or "default"+ model_pools[model_name] = str(pool).strip().lower() or "default"+ by_bundle[bundle_id] = {+ "bundle_config_hash": self.compute_bundle_config_hash(bundle_id),+ "model_pools": model_pools,+ }+ payload = json.dumps(by_bundle, sort_keys=True, separators=(",", ":"))+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()+def get_bundle_info(self, bundle: str) -> BundleInfo | None:"""Get bundle info.@@ -577,6 +638,10 @@ class ModelRegistry:msg = "Missing required field: sie_id"raise ValueError(msg)+ _normalize_pool_name(config)+ incoming_has_pool = "pool" in config+ incoming_pool = config.get("pool") or "default"+profiles = config.get("profiles", {})if not profiles:msg = "Missing required field: profiles"@@ -613,6 +678,10 @@ class ModelRegistry:skipped_profiles: list[str] = []if existing:+ existing_pool = self._model_full_configs.get(sie_id, {}).get("pool") or "default"+ if incoming_has_pool and incoming_pool != existing_pool:+ msg = f"Pool on model '{sie_id}' already exists with different value. Config API is append-only."+ raise ValueError(msg)existing_full_profiles = self._model_full_configs.get(sie_id, {}).get("profiles", {})conflicting_profiles: list[str] = []for profile_name, profile in profiles.items():diff --git a/packages/sie_config/tests/test_config_api.py b/packages/sie_config/tests/test_config_api.pyindex b1cf45bc3..c27d5990e 100644--- a/packages/sie_config/tests/test_config_api.py+++ b/packages/sie_config/tests/test_config_api.py@@ -30,7 +30,7 @@ def _write_bundle(bundles_dir: Path, name: str, adapters: list[str], priority: i(bundles_dir / f"{name}.yaml").write_text(yaml.dump(bundle))-def _write_model(models_dir: Path, sie_id: str, adapter_path: str) -> None:+def _write_model(models_dir: Path, sie_id: str, adapter_path: str, *, pool: str | None = None) -> None:config = {"sie_id": sie_id,"profiles": {@@ -40,6 +40,8 @@ def _write_model(models_dir: Path, sie_id: str, adapter_path: str) -> None:}},}+ if pool is not None:+ config["pool"] = poolfilename = sie_id.replace("/", "__") + ".yaml"(models_dir / filename).write_text(yaml.dump(config))@@ -90,6 +92,59 @@ class TestConfigAPIModels:assert data["model_id"] == "new/model"assert data["created_profiles"] == ["default"]+ def test_add_model_normalizes_pool_in_export(self) -> None:+ yaml_body = "sie_id: pool/model\npool: Customer-A\nprofiles:\n default:\n adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n max_batch_tokens: 8192\n"+ resp = self.client.post(+ "/v1/configs/models",+ content=yaml_body,+ headers={"Content-Type": "application/x-yaml"},+ )+ assert resp.status_code == 201++ export = self.client.get("/v1/configs/export")+ assert export.status_code == 200+ models = {m["model_id"]: m for m in export.json()["models"]}+ assert models["pool/model"]["model_config"]["pool"] == "customer-a"+ assert "pool: customer-a" in models["pool/model"]["raw_yaml"]++ def test_append_model_profile_preserves_pool_in_export(self) -> None:+ first = (+ "sie_id: pool/model\n"+ "pool: Customer-A\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n"+ " max_batch_tokens: 1024\n"+ )+ assert self.client.post("/v1/configs/models", content=first).status_code == 201++ appended = (+ "sie_id: pool/model\n"+ "profiles:\n"+ " fast:\n"+ " adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n"+ " max_batch_tokens: 8192\n"+ )+ assert self.client.post("/v1/configs/models", content=appended).status_code == 201++ export = self.client.get("/v1/configs/export")+ assert export.status_code == 200+ models = {m["model_id"]: m for m in export.json()["models"]}+ entry = models["pool/model"]+ assert entry["model_config"]["pool"] == "customer-a"+ assert set(entry["model_config"]["profiles"]) == {"default", "fast"}+ assert "pool: customer-a" in entry["raw_yaml"]++ def test_add_model_invalid_pool_returns_422(self) -> None:+ yaml_body = "sie_id: bad/model\npool: customer.a\nprofiles:\n default:\n adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n max_batch_tokens: 8192\n"+ resp = self.client.post(+ "/v1/configs/models",+ content=yaml_body,+ headers={"Content-Type": "application/x-yaml"},+ )+ assert resp.status_code == 422+ assert "pool" in str(resp.json()["detail"])+def test_add_model_unroutable_adapter(self) -> None:yaml_body = "sie_id: bad/model\nprofiles:\n default:\n adapter_path: sie_server.adapters.unknown:UnknownAdapter\n max_batch_tokens: 8192\n"resp = self.client.post(@@ -564,6 +619,34 @@ class TestConfigAPIExportNoConfigStore:assert profiles["default"]["max_batch_tokens"] == 1024assert profiles["fast"]["max_batch_tokens"] == 8192+ def test_export_preserves_pool_on_append_without_store(self) -> None:+ first = (+ "sie_id: mem/model\n"+ "pool: Customer-A\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:B\n"+ " max_batch_tokens: 1024\n"+ )+ assert self.client.post("/v1/configs/models", content=first).status_code == 201++ appended = (+ "sie_id: mem/model\n"+ "profiles:\n"+ " fast:\n"+ " adapter_path: sie_server.adapters.bert_flash:B\n"+ " max_batch_tokens: 8192\n"+ )+ assert self.client.post("/v1/configs/models", content=appended).status_code == 201++ resp = self.client.get("/v1/configs/export")+ assert resp.status_code == 200+ models = {m["model_id"]: m for m in resp.json()["models"]}+ entry = models["mem/model"]+ assert entry["model_config"]["pool"] == "customer-a"+ assert set(entry["model_config"]["profiles"]) == {"default", "fast"}+ assert "pool: customer-a" in entry["raw_yaml"]+def test_nats_delta_carries_merged_yaml_without_store(self) -> None:"""On the NATS publish path, the delta payload must be the fullmerged model YAML (not the incremental request body) so a fresh@@ -692,6 +775,8 @@ class TestConfigAPIEpoch:# the gateway and only compared as a string.assert isinstance(body["bundles_hash"], str)assert len(body["bundles_hash"]) == 64 # sha256 hex+ assert isinstance(body["bundle_config_hashes_hash"], str)+ assert len(body["bundle_config_hashes_hash"]) == 64 # sha256 hexdef test_epoch_bundles_hash_changes_when_bundles_reload(self) -> None:# The hash is the gateway's only signal that bundles need re-fetching@@ -708,6 +793,54 @@ class TestConfigAPIEpoch:assert before != afterassert len(after) == 64+ def test_epoch_bundle_config_hashes_hash_changes_when_model_hash_changes(self) -> None:+ # This is the compact signal the gateway uses to detect stale+ # expected bundle_config_hash values without polling the full export+ # snapshot on every interval.+ before = self.client.get("/v1/configs/epoch").json()["bundle_config_hashes_hash"]+ yaml_body = (+ "sie_id: hash/model\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:A\n"+ " max_batch_tokens: 1\n"+ )+ self.client.post("/v1/configs/models", content=yaml_body)+ after = self.client.get("/v1/configs/epoch").json()["bundle_config_hashes_hash"]+ assert before != after+ assert len(after) == 64++ def test_epoch_bundle_config_hashes_hash_changes_when_only_model_pool_changes(self) -> None:+ # A top-level pool assignment is routing/readiness state, not part of+ # the worker-parity bundle_config_hash. The compact /epoch fingerprint+ # must still move so no-store/same-epoch redeploys trigger export+ # recovery when only model ownership changes.+ _write_model(self._models, "pool/hash-model", "sie_server.adapters.bert_flash:A")+ registry: ModelRegistry = self.app.state.model_registry+ registry.reload()++ before_epoch = self.client.get("/v1/configs/epoch").json()+ before_export = self.client.get("/v1/configs/export").json()+ before_bundle_hash = before_export["bundle_config_hashes"]["default"]++ _write_model(+ self._models,+ "pool/hash-model",+ "sie_server.adapters.bert_flash:A",+ pool="customer-a",+ )+ registry.reload()++ after_epoch = self.client.get("/v1/configs/epoch").json()+ after_export = self.client.get("/v1/configs/export").json()+ after_bundle_hash = after_export["bundle_config_hashes"]["default"]++ assert before_epoch["epoch"] == after_epoch["epoch"] == 0+ assert before_bundle_hash == after_bundle_hash+ assert before_epoch["bundle_config_hashes_hash"] != after_epoch["bundle_config_hashes_hash"]+ models = {m["model_id"]: m for m in after_export["models"]}+ assert models["pool/hash-model"]["model_config"]["pool"] == "customer-a"+def test_epoch_advances_after_write(self) -> None:before = self.client.get("/v1/configs/epoch").json()["epoch"]yaml_body = (@@ -1300,7 +1433,11 @@ class TestMissingRegistryReturns503:client = TestClient(app)resp = client.get("/v1/configs/epoch")assert resp.status_code == 200, resp.text- assert resp.json() == {"epoch": 0, "bundles_hash": ""}+ assert resp.json() == {+ "epoch": 0,+ "bundles_hash": "",+ "bundle_config_hashes_hash": "",+ }def test_export_returns_503_when_registry_none(self) -> None:# /export reads from the registry so it must 503, matching thediff --git a/packages/sie_config/tests/test_model_registry_mutation.py b/packages/sie_config/tests/test_model_registry_mutation.pyindex 3cdfede92..5d85e0e5b 100644--- a/packages/sie_config/tests/test_model_registry_mutation.py+++ b/packages/sie_config/tests/test_model_registry_mutation.py@@ -56,6 +56,113 @@ class TestAddModelConfig:assert skipped == []assert "default" in bundles+ def test_add_model_config_normalizes_pool(self) -> None:+ registry, _ = _setup_registry(self._root / "pool")+ config = {+ "sie_id": "new/model",+ "pool": " Customer-A ",+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.bert_flash:BertAdapter",+ "max_batch_tokens": 8192,+ },+ },+ }+ registry.add_model_config(config)+ assert config["pool"] == "customer-a"++ def test_add_model_config_rejects_invalid_pool(self) -> None:+ registry, _ = _setup_registry(self._root / "bad_pool")+ config = {+ "sie_id": "bad/model",+ "pool": "customer.a",+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.bert_flash:BertAdapter",+ "max_batch_tokens": 8192,+ },+ },+ }+ with pytest.raises(ValueError, match="pool"):+ registry.add_model_config(config)++ def test_add_model_config_rejects_pool_move_on_profile_append(self) -> None:+ registry, _ = _setup_registry(+ self._root / "pool_move",+ models={"existing/model": "sie_server.adapters.bert_flash:B"},+ )+ config = {+ "sie_id": "existing/model",+ "pool": "customer-a",+ "profiles": {+ "custom": {+ "adapter_path": "sie_server.adapters.bert_flash:BertAdapter",+ "max_batch_tokens": 8192,+ },+ },+ }+ with pytest.raises(ValueError, match="Pool on model"):+ registry.add_model_config(config)++ def test_add_model_config_omitted_pool_append_preserves_existing_pool(self) -> None:+ registry, _ = _setup_registry(self._root / "pool_append_omitted")+ registry.add_model_config(+ {+ "sie_id": "tenant/model",+ "pool": "customer-a",+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.bert_flash:BertAdapter",+ "max_batch_tokens": 1024,+ },+ },+ }+ )+ registry.add_model_config(+ {+ "sie_id": "tenant/model",+ "profiles": {+ "fast": {+ "adapter_path": "sie_server.adapters.bert_flash:BertAdapter",+ "max_batch_tokens": 8192,+ },+ },+ }+ )++ full = registry.get_full_config("tenant/model")+ assert full is not None+ assert full["pool"] == "customer-a"+ assert set(full["profiles"]) == {"default", "fast"}++ def test_add_model_config_rejects_explicit_default_pool_move_on_profile_append(self) -> None:+ registry, _ = _setup_registry(self._root / "pool_append_default")+ registry.add_model_config(+ {+ "sie_id": "tenant/model",+ "pool": "customer-a",+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.bert_flash:BertAdapter",+ "max_batch_tokens": 1024,+ },+ },+ }+ )+ config = {+ "sie_id": "tenant/model",+ "pool": "default",+ "profiles": {+ "fast": {+ "adapter_path": "sie_server.adapters.bert_flash:BertAdapter",+ "max_batch_tokens": 8192,+ },+ },+ }++ with pytest.raises(ValueError, match="Pool on model"):+ registry.add_model_config(config)+def test_model_becomes_routable(self) -> None:registry, _ = _setup_registry(self._root / "routable")registry.add_model_config(diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lockindex 6981a7996..1cff01159 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -2960,7 +2960,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-gateway"-version = "0.6.4"+version = "0.6.5"dependencies = ["arc-swap","async-nats",diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 92898a618..e098ca36d 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.4"+version = "0.6.5"edition = "2021"publish = falsediff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.mdindex 4d0cff023..ce5d6c7e7 100644--- a/packages/sie_gateway/README.md+++ b/packages/sie_gateway/README.md@@ -156,7 +156,7 @@ Common headers:Common behaviors:- `404` for unknown models once the in-memory registry has bootstrapped from `sie-config` (fast-fail; avoids queueing requests for typo'd model ids)-- `202` + `Retry-After` on scale-from-zero, whether or not `X-SIE-MACHINE-PROFILE` was set (records pending demand for KEDA)+- `503` + `Retry-After` + `X-SIE-Error-Code: PROVISIONING` on scale-from-zero, whether or not `X-SIE-MACHINE-PROFILE` was set (records pending demand for KEDA)- `503` + `Retry-After` for no-consumer or backpressure publish failures- `503` + `X-SIE-Error-Code: MODEL_LOADING` + `Retry-After: 5` for queue result timeouts (typically a worker cold-loading the target model). SDK clients with `wait_for_capacity=True` retry under the existing `provision_timeout_s` budget.- `503` + `X-SIE-Error-Code: RESOURCE_EXHAUSTED` + `Retry-After: 5` when every item in a batch fails with the same retryable code (`RESOURCE_EXHAUSTED` from worker-side OOM recovery exhaustion, `MODEL_LOADING` from a worker still warming up). The SDK auto-retries with bounded exponential backoff. Mixed batches keep returning `500 all_items_failed` with per-item `code` fields in the response body so callers can see which items hit which failure mode.diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 69615c50f..398d92b7a 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -13,7 +13,7 @@ Top-level summary:The gateway's contract with `sie-config` is three shapes. Everything else below elaborates on them.1. `GET /v1/configs/export` — full snapshot, consumed on cold start and on drift detection.-2. `GET /v1/configs/epoch` — monotonic integer, polled every 30s to detect drift.+2. `GET /v1/configs/epoch` — monotonic integer plus compact fingerprints, polled every 30s to detect drift.3. `sie.config.models._all` (NATS Core) — live deltas; missed ones are caught by (2).The gateway's contract with admin tooling for post-write readiness is `GET /v1/configs/models/{id}/status`.@@ -58,8 +58,8 @@ Rules enforced on the inference path:- If the queue transport is unavailable (no usable NATS client at init), the gateway returns `503`. It does not fall back to direct mode.- Unknown model ids fast-fail with `404` whenever the in-memory `ModelRegistry` has been populated (either by the filesystem seed or by a successful bootstrap / delta from `sie-config`). In the pre-bootstrap edge case where the registry is still empty — no seed, no export applied yet — the proxy falls back to the caller-supplied bundle (or `"default"`) so an unseeded gateway can still publish work to a cold pool that a caller pinned via `X-SIE-Pool`. Once any model is registered, this fallback is disabled and the 404 contract applies.- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. Explicit `X-SIE-Pool` remains an operator override; deliveries with hashes unknown to the worker-sidecar are NAKed before Python IPC.-- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway returns `202 provisioning` with `Retry-After: 120` and records pending demand for KEDA. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.-- On no-consumer conditions for the JetStream publish the gateway returns `503` with `Retry-After: 120`. On backpressure conditions the gateway returns `503` with `Retry-After: 5`.+- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.+- On no-consumer conditions for the JetStream publish, the gateway treats the miss as the same pre-execution provisioning state and returns the same retryable `503 PROVISIONING` contract (`Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and surface-specific error envelope). On backpressure conditions the gateway returns `503` with `Retry-After: 5`.- On queue result timeouts the gateway returns `503` with `X-SIE-Error-Code: MODEL_LOADING` and `Retry-After: 5`. The most common trigger is a worker cold-loading the target model on demand (worker NAKs the JetStream message and redelivers after load); the SDK retries this under the same `provision_timeout_s` budget used for worker-emitted `MODEL_LOADING` responses.- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED` (worker-side OOM recovery exhausted — `Retry-After: 5`), `MODEL_LOADING`, and `LORA_LOADING`. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.- When **every** failed item carries **`MODEL_LOAD_FAILED`**, the gateway returns **`502 Bad Gateway`** with the SDK-style **`error`** object (`code`, `message`, `error_class`, `attempts`, `permanent`) — matching the terminal model-load contract consumed by SDK retry logic (no `Retry-After`; the SDK must not burn the `MODEL_LOADING` retry budget). The gateway synthesises conservative `attempts` / `permanent` fields on this queue path when the worker payload does not carry registry-shaped failure metadata.@@ -67,8 +67,12 @@ Rules enforced on the inference path:Encode / extract tuning fields (`output_types`, `instruction`, `options`, `labels`, `output_schema`, `is_query`) are read **only** from the nested JSON **`params`** object (and the msgpack analogue: a top-level **`params`** map). The score path continues to read `query` / `instruction` / `options` at the top level of the request body, matching `sie_server`.Work-item and result payloads on the wire are **msgpack** (`rmp_serde`). JSON is used only for the HTTP request/response envelope when the client negotiates it (via `Content-Type` / `Accept`); the gateway transcodes msgpack ↔ JSON at the edge so the hot path between gateway and workers is always binary.+On SIE-native JSON requests, media byte fields such as `items[].images[].data`+are accepted as base64 strings at the HTTP edge and decoded into msgpack `bin`+before the gateway publishes the worker item, preserving the worker-side typed+`bytes` contract behind gateway-fronted clusters.-Gateway-generated **JSON error** bodies (validation, routing, auth, config read, pools) use a FastAPI-like envelope **`{"detail":{"code":"<STABLE_CODE>","message":"…", …}}`**. Extra diagnostic keys (e.g. `compatible_bundles`, `gpu`, `model`) live **inside** `detail` when present. This is intentionally **not** the same shape as SDK retry contracts, which remain **`{"error":{"code","message"}}`** for **503** retryable worker signals and **`502`** **`MODEL_LOAD_FAILED`**. **202 provisioning** and **200** success payloads keep their existing top-level shapes.+Gateway-generated **JSON error** bodies (validation, routing, auth, config read, pools) use a FastAPI-like envelope **`{"detail":{"code":"<STABLE_CODE>","message":"…", …}}`**. Extra diagnostic keys (e.g. `compatible_bundles`, `gpu`, `model`) live **inside** `detail` when present. This is intentionally **not** the same shape as SDK retry contracts, which remain **`{"error":{"code","message"}}`** for **503** retryable worker signals, SIE-native provisioning, and **`502`** **`MODEL_LOAD_FAILED`**. OpenAI-compatible provisioning uses the OpenAI error envelope. **200** success payloads keep their existing top-level shapes.## 3. Configuration Write Path@@ -120,10 +124,10 @@ The gateway does not block startup on `sie-config`. Startup is:1. Construct `ModelRegistry`. In default Helm deploys, `SIE_BUNDLES_DIR` and `SIE_MODELS_DIR` are unset and the registry's filesystem reload is a no-op (warns once that the dirs are missing, then proceeds with empty bundle and model maps). The optional `gateway.embeddedConfigs` / `gateway.configMap` overlays mount a ConfigMap at `/configs/{bundles,models}` and set those env vars; in that mode the registry loads the seed before bootstrap runs.2. Initialize the other runtime subsystems that do not depend on `sie-config`: NATS manager (with config-delta subscription), worker health manager, optional filesystem config watcher, pool manager / K8s backend, and worker discovery.-3. Spawn two independent background tasks: `state::config_bootstrap::spawn_bootstrap_retry` and `state::config_poller::spawn`. They share the same `ModelRegistry`, `ConfigEpoch` (monotonic model-write counter), and `BundlesHash` (sha256 fingerprint of `sie-config`'s loaded bundle set). The poller skips its first tick (one `DEFAULT_POLL_INTERVAL` grace) so the initial bootstrap attempt can run first, and then reconciles on every subsequent tick regardless of whether the bootstrap task has completed yet.+3. Spawn two independent background tasks: `state::config_bootstrap::spawn_bootstrap_retry` and `state::config_poller::spawn`. They share the same `ModelRegistry`, `ConfigEpoch` (monotonic model-write counter), `BundlesHash` (sha256 fingerprint of `sie-config`'s loaded bundle set), and `BundleConfigHashesHash` (sha256 fingerprint of the per-bundle config-hash map). The poller skips its first tick (one `DEFAULT_POLL_INTERVAL` grace) so the initial bootstrap attempt can run first, and then reconciles on every subsequent tick regardless of whether the bootstrap task has completed yet.4. Bind the HTTP listener. Kubernetes probes use plain-text endpoints implemented in `handlers/health.rs`:- **`GET /healthz`** — liveness. Always **`200 OK`** with body **`ok`** and **`Content-Type: text/plain; charset=utf-8`** (same wire shape as `sie_server`'s `/healthz`).- - **`GET /readyz`** — readiness for **routing traffic to this gateway process**. Returns **`200 OK`** + **`ok`** once the gateway listener is serving. It is intentionally independent of worker health and `sie-config` reachability: a gateway with zero healthy workers must still receive the first inference request so it can return `202 + Retry-After` and emit `sie_gateway_pending_demand` for scale-from-zero. Worker availability is exposed on **`GET /health`** and by the inference response path itself.+ - **`GET /readyz`** — readiness for **routing traffic to this gateway process**. Returns **`200 OK`** + **`ok`** once the gateway listener is serving. It is intentionally independent of worker health and `sie-config` reachability: a gateway with zero healthy workers must still receive the first inference request so it can return a retryable provisioning response and emit `sie_gateway_pending_demand` for scale-from-zero. Worker availability is exposed on **`GET /health`** and by the inference response path itself.The bootstrap/poller tasks are spawned **before** the HTTP listener binds, so requests hitting a freshly-bound replica can observe either filesystem-seed-only state or a partially-applied snapshot depending on timing. That is by design. **`/readyz` does not wait for control-plane sync** (see §11 caveat 3); bootstrap completeness is tracked via **`GET /v1/configs/models/{id}/status`**, **`sie_gateway_config_bootstrap_degraded`**, and **`sie_gateway_config_epoch`** — not by `/readyz` alone.@@ -138,14 +142,14 @@ Startup short-circuits:`bootstrap_once` runs a three-call sequence, authenticated with `SIE_ADMIN_TOKEN` as a bearer token on `SIE_CONFIG_SERVICE_URL`:-1. `GET /v1/configs/epoch` — reads the bundle-set fingerprint BEFORE we fetch bundles, so the hash we store reflects the state we're about to catch up from (the pre-fetch ordering is load-bearing — see below).+1. `GET /v1/configs/epoch` — reads the compact control-plane fingerprints BEFORE we fetch bundles, so the hashes we store reflect the state we're about to catch up from (the pre-fetch ordering is load-bearing — see below). The `bundle_config_hashes_hash` fingerprint covers both worker-parity bundle config hashes and model-level pool ownership, because top-level `pool` changes affect routing/readiness even when the worker-applied profile hash is otherwise unchanged.2. `GET /v1/configs/bundles` and per-id `GET /v1/configs/bundles/{id}` — the two-phase bundle fetch. The YAML bodies are parsed into `BundleInfo` values and handed to `ModelRegistry::install_bundles`, which atomically replaces the registry's bundle set and recomputes every model's bundle associations.-3. `GET /v1/configs/export` — replays every exported model config into `ModelRegistry` via `add_model_config`. Malformed or unparseable entries are logged and counted as `failed`; they do not abort the loop. Export rows that carry no config body are skipped and are *not* counted as failed.+3. `GET /v1/configs/export` — parses every exported model config, then replaces the gateway `ModelRegistry` model set from that authoritative snapshot. Malformed, unparseable, or unroutable entries are logged and counted as `failed`; a failed export does not mutate the model set. Export rows that carry no config body are skipped and are *not* counted as failed.-Returns `BootstrapOutcome { epoch, bundles_hash, applied, failed, total }`.+Returns `BootstrapOutcome { epoch, bundles_hash, bundle_config_hashes_hash, applied, failed, total }`.-- If **any** model entry failed (`outcome.failed > 0`), `bootstrap_once` returns `BootstrapError::PartialApply` and **advances neither `ConfigEpoch` nor `BundlesHash`**. The poller will detect drift on the next tick and retry.-- If all entries applied, `bootstrap_once` advances `ConfigEpoch` via `set_max(outcome.epoch)`, stores `outcome.bundles_hash` into `BundlesHash`, and the retry task exits.+- If **any** model entry failed (`outcome.failed > 0`), `bootstrap_once` returns `BootstrapError::PartialApply` and **advances neither `ConfigEpoch`, `BundlesHash`, nor `BundleConfigHashesHash`**. The poller will detect drift on the next tick and retry.+- If all entries applied, `bootstrap_once` advances `ConfigEpoch` via `set_max(outcome.epoch)`, stores `outcome.bundles_hash` into `BundlesHash`, stores `outcome.bundle_config_hashes_hash` into `BundleConfigHashesHash`, and the retry task exits.Why fetch `/epoch` BEFORE `/bundles`: if a bundle is added on `sie-config` between our epoch read and our bundle list read, we install a bundle set *newer* than the hash reflects. The next poll tick sees `remote_hash != stored_hash` and re-fetches — a cheap self-heal. The inverse — storing a hash that's *newer* than the bundles we actually installed — would silently wedge the gateway on a stale registry, which is what the bundle-hash mechanism exists to prevent.@@ -165,19 +169,20 @@ During the bootstrap-retry window (before the first successful fetch):### 4.2 Epoch poll-`state::config_poller::spawn` runs independently of bootstrap with `DEFAULT_POLL_INTERVAL = 30s`. It skips its first tick (to let the initial bootstrap attempt run without contention), then on every tick calls `GET /v1/configs/epoch` on `sie-config` (always sending `SIE_ADMIN_TOKEN` as the bearer — the `/epoch` handler is read-auth and accepts either `SIE_AUTH_TOKEN` or `SIE_ADMIN_TOKEN`, but the gateway-as-client only presents the admin token). The `/epoch` response carries **two** drift signals:+`state::config_poller::spawn` runs independently of bootstrap with `DEFAULT_POLL_INTERVAL = 30s`. It skips its first tick (to let the initial bootstrap attempt run without contention), then on every tick calls `GET /v1/configs/epoch` on `sie-config` (always sending `SIE_ADMIN_TOKEN` as the bearer — the `/epoch` handler is read-auth and accepts either `SIE_AUTH_TOKEN` or `SIE_ADMIN_TOKEN`, but the gateway-as-client only presents the admin token). The `/epoch` response carries three drift signals:- `epoch` — monotonic counter bumped on every model-config write.- `bundles_hash` — sha256 fingerprint over `sie-config`'s loaded bundle set. Bundles are filesystem artifacts inside the `sie-config` image, so their effective "version" is redeploy time, which the model-write counter does not observe.+- `bundle_config_hashes_hash` — sha256 fingerprint over the per-bundle `bundle_config_hash` map from `sie-config` plus model-level pool ownership. This catches no-store/filesystem-baseline redeploys where the epoch and bundle set stay unchanged but the expected routing hashes or model pool assignment move.-Both signals funnel into the same `bootstrap_once` call — that function re-fetches bundles and models together, which is the correct blanket response to any control-plane drift.+All signals funnel into the same `bootstrap_once` call — that function re-fetches bundles and models together, which is the correct blanket response to any control-plane drift.Per-tick decisions:-- If `remote_epoch > local_epoch` **OR** `remote_bundles_hash != stored_bundles_hash` (with the empty-string "registry unavailable" sentinel skipped), the poller calls `bootstrap_once`. On success, `ConfigEpoch` advances and `BundlesHash` is updated.-- If `remote_epoch < local_epoch`, the local counter has run ahead of authority. Most innocent cause: `sie-config` lost its persisted epoch file and restarted at a lower value. Most worrying cause: a forged/untrusted NATS delta wedged the gateway ahead of authority (this is defense-in-depth alongside the producer allowlist — see §4.3). The poller refetches the full export first and only calls `ConfigEpoch::force_set(remote)` if the export succeeded; a failed recovery export keeps `local > remote`, so the next tick re-enters this branch and retries. Note: `ModelRegistry` is append-only for models (but not for bundles — `install_bundles` replaces), so any profiles admitted during the pre-recovery window remain in the registry after recovery — the export replay overlays authority on top of them rather than clearing them. A follow-up restart is the clean fix. Logged at ERROR.-- A remote `bundles_hash` of `""` is the documented "sie-config registry unavailable" sentinel (startup failure or hot reload in flight). The poller skips the hash-mismatch branch in that case rather than thrash fetching against a degraded control plane. The epoch branch still runs normally.-- Transient `/epoch` failures are logged and swallowed. The next tick retries. Neither the local epoch nor the stored bundles hash is reset on poll failure.+- If `remote_epoch > local_epoch`, `remote_bundles_hash != stored_bundles_hash`, or `remote_bundle_config_hashes_hash != stored_bundle_config_hashes_hash` (with empty-string sentinels skipped), the poller calls `bootstrap_once`. On success, `ConfigEpoch`, `BundlesHash`, and `BundleConfigHashesHash` are updated.+- If `remote_epoch < local_epoch`, the local counter has run ahead of authority. Most innocent cause: `sie-config` lost its persisted epoch file and restarted at a lower value. Most worrying cause: a forged/untrusted NATS delta wedged the gateway ahead of authority (this is defense-in-depth alongside the producer allowlist — see §4.3). The poller refetches the full export first and only calls `ConfigEpoch::force_set(remote)` if the export succeeded; a failed recovery export keeps `local > remote`, so the next tick re-enters this branch and retries. Successful recovery replaces the gateway model set with the authority's export, including removals. Logged at ERROR.+- A remote hash of `""` is the documented "sie-config registry unavailable" / legacy-field sentinel. The poller skips that hash-mismatch branch rather than thrash fetching against a degraded control plane. The epoch branch still runs normally.+- Transient `/epoch` failures are logged and swallowed. The next tick retries. Neither the local epoch nor the stored hashes are reset on poll failure.- The poller **always** compares local vs. remote, including when `local_epoch == 0` or `stored_bundles_hash == ""`. This matters for fresh clusters: if `sie-config`'s very first write (→ epoch 1) is lost on the wire, the gateway must catch `remote=1 > local=0` and trigger recovery. Gating on "non-zero local" would wedge a fresh gateway until a restart.Operational consequence: adding or changing a bundle in `sie-config` propagates to running gateways within one `DEFAULT_POLL_INTERVAL` (≤ 30s worst case). No `kubectl rollout restart deployment/sie-gateway` is required for the gateway to learn the updated bundle set.@@ -213,12 +218,12 @@ The gateway serves these endpoints directly out of its in-memory `ModelRegistry`Concurrency on the gateway's `ModelRegistry`:- Reads are lock-free. `ArcSwap<RegistrySnapshot>` lets readers clone an `Arc` pointer to the current snapshot without blocking.-- Writes (`add_model_config`, `reload`) hold `write_lock: Mutex<()>` across the `load → mutate → store` cycle. Without this lock, two concurrent writers could both load the same base snapshot and silently drop one set of changes.+- Writes (`add_model_config`, authoritative export replacement, `reload`) hold `write_lock: Mutex<()>` across the `load → mutate → store` cycle. Without this lock, two concurrent writers could both load the same base snapshot and silently drop one set of changes.- `RegistrySnapshot` caches `bundle_config_hashes: HashMap<String, String>`, so the per-request worker-ack hash lookup (§6) is an `O(1)` map read rather than a SHA-256 over tens of KB of JSON.## 6. Worker-Ack Status (`GET /v1/configs/models/{id}/status`)-Admin tooling uses this endpoint after a `sie-config` write to observe whether configured workers are reporting the expected `bundle_config_hash` for each affected bundle. Worker-sidecar containers advance that hash after their bundle-scoped NATS delta is accepted by Python IPC `ApplyModelConfig`, or after the worker export reconciler replays the missed bundle entry from `sie-config`.+Admin tooling uses this endpoint after a `sie-config` write to observe whether configured workers are reporting the expected `bundle_config_hash` for each affected bundle. Worker-sidecar containers advance that hash after their bundle-scoped NATS delta is accepted by Python IPC `ApplyModelConfig`, or after the worker export reconciler replaces the bundle-scoped Python registry view from `sie-config`.Response shape:@@ -231,6 +236,7 @@ Response shape:"bundles": [{"bundle_id": "default",+ "pool": "default","expected_bundle_config_hash": "sha256…","total_eligible_workers": 3,"acked_workers": ["worker-1", "worker-2", "worker-3"],@@ -382,7 +388,7 @@ The gateway has no persistent config store. `SIE_CONFIG_STORE_DIR` and `SIE_CONF1. **`sie-config` is a single point of failure for the control plane.** While the pod is down, config writes, authoritative config reads, and gateway catch-up fetches all fail. **The inference hot path is unaffected** — it never touches `sie-config`. New gateway pods enter the soft-degraded bootstrap-retry state (§4.1), serve filesystem-seed traffic until `sie-config` is reachable, and return **`200 ok`** from **`GET /readyz`** once the process is serving. The SPOF is rooted in `_IdempotencyState` (in-memory, per-process). Multi-replica requires moving idempotency state to a shared backend (Redis, JetStream KV, a DB row per key). Until then, `replicas: 1` is a deliberate trade of availability for a correct idempotency contract.-2. **Config deltas use NATS Core pub/sub; deltas published during a gateway-NATS disconnect are lost.** Recovery is automatic via the epoch poller (§4.2). The worst-case staleness window is `DEFAULT_POLL_INTERVAL` plus one export round-trip. No pod restart is required. Shortening `DEFAULT_POLL_INTERVAL` trades load on `sie-config` for recovery time.+2. **Config deltas use NATS Core pub/sub; deltas published during a gateway-NATS disconnect are lost.** Recovery is automatic via the config poller (§4.2). The worst-case staleness window is `DEFAULT_POLL_INTERVAL` plus one export round-trip. No pod restart is required. Shortening `DEFAULT_POLL_INTERVAL` trades load on `sie-config` for recovery time.3. **Bootstrap is background-retried, not blocking.** A gateway started while `sie-config` is unreachable will serve filesystem-seed traffic immediately. API-added models are missing until the first successful export. `ConfigEpoch` typically stays at `0` during this window — but a NATS delta that arrives before the first export can move it above `0`, so admin tooling should use the `sie_gateway_config_bootstrap_degraded` gauge (set after 10 failed attempts or 5 minutes of sustained failure, cleared on first success) as the authoritative "has this replica ever reconciled with `sie-config`?" signal rather than `config_epoch == 0`. **`GET /readyz` does not encode bootstrap completion or worker health**; it is process readiness (§4).@@ -509,7 +515,7 @@ Emitted from a Tower middleware (`MetricsLayer` in `middleware/metrics.rs`) that### 15.2 Routing outcomes — gateway-- `sie_gateway_provisioning_responses_total{machine_profile}` — counter. `202 Accepted` returned when no ready worker exists; paired with `sie_gateway_pending_demand` for KEDA scale-up.+- `sie_gateway_provisioning_responses_total{machine_profile}` — counter. A provisioning response was returned when no ready worker exists; paired with `sie_gateway_pending_demand` for KEDA scale-up.- `sie_gateway_rejected_requests_total{pool,machine_profile,bundle,reason}` — counter. In-handler emission because the `reason` label (`timeout`, `capacity`, `no_workers`, ...) is too granular for the middleware.- `sie_gateway_pending_demand{pool,machine_profile,bundle}` — gauge. KEDA trigger. Cleared by `clear_fulfilled_demand` when healthy workers appear on the exact queue lane.- `sie_gateway_active_lease_gpus{pool,machine_profile,bundle}` — gauge. KEDA trigger. Recomputed from the current pool list on every `update_pool_metrics`; bundle-pinned pools use the pool spec bundle, while unfiltered pools split by the assigned workers' actual bundles.@@ -540,7 +546,7 @@ Emitted from a Tower middleware (`MetricsLayer` in `middleware/metrics.rs`) that- `sie_gateway_config_bootstrap_failures_total` — counter. Background bootstrap retry failures (see §10).- `sie_gateway_config_bootstrap_degraded` — gauge, `0` or `1`. Set to `1` once the gateway has been serving the filesystem seed past the degraded threshold; cleared on the first successful bootstrap.-- `sie_gateway_config_epoch` — gauge. Highest-known control-plane epoch on this gateway. Updated by bootstrap fetch, NATS Core delta handler, and the epoch poller. Pairs with `sie_config_epoch` for drift alerting (§15.9).+- `sie_gateway_config_epoch` — gauge. Highest-known control-plane epoch on this gateway. Updated by bootstrap fetch, NATS Core delta handler, and the config poller. Pairs with `sie_config_epoch` for drift alerting (§15.9).- `sie_gateway_config_deltas_total{kind,result}` — counter. NATS Core config-delta processing outcomes. `kind` is the delta kind (`epoch_bump`, `model_added`); `result` is `applied`, `parse_error`, `apply_error`, or `rejected_untrusted`.- `sie_gateway_nats_connected` — gauge, `0` or `1`. Flipped by the NATS client's connect/disconnect event callbacks. Unlabeled: the gateway uses a single `async-nats` client for JetStream (work + results) and NATS Core (config deltas), so a single gauge accurately represents the only connection-state dimension that exists today. If we later split clients per purpose, re-introduce a `stream` label at that point.@@ -567,7 +573,7 @@ The most important alert across both services. Fires when any gateway's view of(sie_config_epoch - on() sie_gateway_config_epoch) > 0```-Sustained non-zero for >1 minute means either NATS Core deltas are not flowing (pub/sub has no replay, so a disconnected gateway silently falls behind) or the epoch poller is stuck. The poller normally closes this gap within its poll interval regardless of NATS health, so a sustained alert here is always an actionable incident.+Sustained non-zero for >1 minute means either NATS Core deltas are not flowing (pub/sub has no replay, so a disconnected gateway silently falls behind) or the config poller is stuck. The poller normally closes this gap within its poll interval regardless of NATS health, so a sustained alert here is always an actionable incident.## 16. Worked Example: end-to-end request@@ -724,8 +730,8 @@ POST /v1/poolsHelm publishes canonical machine profiles in `SIE_GATEWAY_CONFIGURED_GPUS`, request aliases in `SIE_GATEWAY_GPU_ALIASES`, and optional deploy-owned static queue pools in `SIE_GATEWAY_STATIC_QUEUE_POOLS`.-Each pool gets its own JetStream stream (`WORK_POOL_{name}`) with subjects `sie.work.{name}.*.*.*`. Workers are deployed with `SIE_POOL={name}`, `SIE_MACHINE_PROFILE={profile}`, and `SIE_BUNDLE={bundle}`; they consume only from their concrete `sie.work.{name}.{profile}.{bundle}.*` lane. The pool is the tenant/logical-capacity boundary; machine profile and bundle are the runtime lane inside that pool. Helm's baseline default puts enabled worker groups in `SIE_POOL=default`, so SDK calls can pass just the machine profile (`gpu="l4"`) for shared-cluster capacity. Dedicated pool deployments override `queuePool` and require callers to name the pool explicitly, for example `gpu="customer-acme/l4"`. A cold `X-SIE-POOL` request without `X-SIE-MACHINE-PROFILE` can emit lane-specific `pending_demand` only when the registered pool spec contains exactly one machine profile; multi-profile pools require the caller to send the profile because the gateway must not guess which StatefulSet KEDA should scale.+Each pool gets its own JetStream stream (`WORK_POOL_{name}`) with subjects `sie.work.{name}.*.*.*`. Pool names are validated against `[A-Za-z0-9_-]` and canonicalized to lowercase at the API, gateway request, K8s restore/watch, and Helm render boundaries, so NATS subjects and KEDA labels do not split by case. Workers are deployed with `SIE_POOL={name}`, `SIE_MACHINE_PROFILE={profile}`, and `SIE_BUNDLE={bundle}`; they consume only from their concrete `sie.work.{name}.{profile}.{bundle}.*` lane. The pool is the tenant/logical-capacity boundary; machine profile and bundle are the runtime lane inside that pool. Helm's baseline default puts enabled worker groups in `SIE_POOL=default`, so SDK calls can pass just the machine profile (`gpu="l4"`) for shared-cluster capacity. Dedicated pool deployments override `queuePool` and require callers to name the pool explicitly, for example `gpu="customer-acme/l4"`. A cold `X-SIE-POOL` request without `X-SIE-MACHINE-PROFILE` can emit lane-specific `pending_demand` only when the registered pool spec contains exactly one machine profile; multi-profile pools require the caller to send the profile because the gateway must not guess which StatefulSet KEDA should scale.Creating a usable custom pool has two supported shapes. For deploy-owned static pools, add the worker group to Helm values with `queuePool`/`SIE_POOL` set to the logical pool name and declare the same name under `queueRouting.staticQueuePools`; the gateway synthesizes a non-expiring pool object at startup for sidecar admission. For dynamic/lease-owned pools, add the worker group to Helm values and then register or renew the pool through `POST /v1/pools`; those pools expire after their TTL unless renewed with `POST /v1/pools/{name}/renew`. Clients target either shape with an explicit `X-SIE-POOL` header, for example `X-SIE-POOL: customer-acme`, or SDK `gpu="customer-acme/l4"`. The `default` pool is protected and cannot be deleted. Missing named pools intentionally fail closed so capped/dynamic pool isolation is not weakened by a silent fallback.-Model configs registered via the control plane (`sie-config`) are not tied to a pool — they describe what the cluster can serve, not who gets to serve it. Pool membership, worker counts, and GPU types are Helm-driven and independent of the config API.+Model configs registered via the control plane (`sie-config`) may carry a top-level `pool` field. That field is model routing/config assignment: omitted or empty means `default`, and a request that omits `X-SIE-POOL` defaults to the model's assigned pool. It does not create workers, KEDA ScaledObjects, or runtime pool leases. Pool membership, worker counts, machine profiles, bundles, and autoscaling lanes are still Helm-driven; `/v1/pools` and `queueRouting.staticQueuePools` only create or renew runtime admission/capacity state for already-rendered logical pool names.diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 1a4cd0a98..bfec41a07 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -938,6 +938,10 @@"type": "integer"},"name": {+ "description": "Pool name used in gpu=\"pool/machine_profile\" routing. Names are stored and routed in lowercase. Only ASCII letters, digits, '_' and '-' are allowed; '_default' is reserved.",+ "maxLength": 128,+ "minLength": 1,+ "pattern": "^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$","type": "string"},"ttl_seconds": {@@ -2399,32 +2403,6 @@},"type": "object"},- "ProvisioningResponse": {- "properties": {- "bundle": {- "type": "string"- },- "estimated_wait_s": {- "format": "int64",- "minimum": 0,- "type": "integer"- },- "gpu": {- "type": "string"- },- "message": {- "type": "string"- },- "status": {- "type": "string"- }- },- "required": [- "status",- "estimated_wait_s"- ],- "type": "object"- },"Relation": {"properties": {"head": {@@ -2908,7 +2886,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.4"+ "version": "0.6.5"},"openapi": "3.1.0","paths": {@@ -3092,7 +3070,7 @@},"/readyz": {"get": {- "description": "Process readiness only. Always returns 200 once the gateway is serving requests; never returns 503. Worker readiness is reported by GET /health and by inference responses (202 + Retry-After from a workerless gateway). This contract supports KEDA scale-from-zero.",+ "description": "Process readiness only. Always returns 200 once the gateway is serving requests; never returns 503. Worker readiness is reported by GET /health and by inference responses with retryable provisioning signals from a workerless gateway. This contract supports KEDA scale-from-zero.","operationId": "readyz","responses": {"200": {@@ -3230,7 +3208,33 @@}}},- "description": "Queue unavailable"+ "description": "Provisioning in progress, queue unavailable, or model loading",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds, when retryable",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }}},"tags": [@@ -3311,7 +3315,33 @@}}},- "description": "Queue unavailable"+ "description": "Provisioning in progress, queue unavailable, or model loading",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds, when retryable",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }}},"summary": "`/v1/completions` — legacy OpenAI Completions (single-candidate, raw-prompt).",@@ -3813,36 +3843,6 @@}}},- "202": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ProvisioningResponse"- }- }- },- "description": "Worker provisioning in progress",- "headers": {- "Retry-After": {- "description": "Suggested retry delay in seconds",- "schema": {- "type": "string"- }- },- "X-SIE-Server-Version": {- "description": "Gateway-compatible server version advertised by this gateway",- "schema": {- "type": "string"- }- },- "X-SIE-Version": {- "description": "Gateway package version that handled the request",- "schema": {- "type": "string"- }- }- }- },"400": {"content": {"application/json": {@@ -3954,7 +3954,7 @@}}},- "description": "Model loading, capacity, queue unavailable, or GPU not configured",+ "description": "Provisioning in progress, queue unavailable, GPU not configured, model loading, or capacity exhausted","headers": {"Retry-After": {"description": "Suggested retry delay in seconds, when retryable",@@ -4180,36 +4180,6 @@}}},- "202": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ProvisioningResponse"- }- }- },- "description": "Worker provisioning in progress",- "headers": {- "Retry-After": {- "description": "Suggested retry delay in seconds",- "schema": {- "type": "string"- }- },- "X-SIE-Server-Version": {- "description": "Gateway-compatible server version advertised by this gateway",- "schema": {- "type": "string"- }- },- "X-SIE-Version": {- "description": "Gateway package version that handled the request",- "schema": {- "type": "string"- }- }- }- },"400": {"content": {"application/json": {@@ -4321,7 +4291,7 @@}}},- "description": "Queue unavailable, GPU not configured, model loading, or capacity exhausted",+ "description": "Provisioning in progress, queue unavailable, GPU not configured, model loading, or capacity exhausted","headers": {"Retry-After": {"description": "Suggested retry delay in seconds, when retryable",@@ -4548,36 +4518,6 @@}}},- "202": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ProvisioningResponse"- }- }- },- "description": "Worker provisioning in progress",- "headers": {- "Retry-After": {- "description": "Suggested retry delay in seconds",- "schema": {- "type": "string"- }- },- "X-SIE-Server-Version": {- "description": "Gateway-compatible server version advertised by this gateway",- "schema": {- "type": "string"- }- },- "X-SIE-Version": {- "description": "Gateway package version that handled the request",- "schema": {- "type": "string"- }- }- }- },"400": {"content": {"application/json": {@@ -4689,7 +4629,7 @@}}},- "description": "Queue unavailable, GPU not configured, model loading, or capacity exhausted",+ "description": "Provisioning in progress, queue unavailable, GPU not configured, model loading, or capacity exhausted","headers": {"Retry-After": {"description": "Suggested retry delay in seconds, when retryable",@@ -4804,17 +4744,75 @@}}},- "description": "Generated text response"- },- "202": {- "content": {- "application/json": {+ "description": "Generated text response",+ "headers": {+ "X-Inference-Time": {+ "description": "Worker-reported inference time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Payload-Fetch-Time": {+ "description": "Worker-reported offloaded payload fetch time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Postprocessing-Time": {+ "description": "Worker-reported postprocessing time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Publish-Time": {+ "description": "Milliseconds spent publishing work to the queue","schema": {- "$ref": "#/components/schemas/ProvisioningResponse"+ "type": "string"+ }+ },+ "X-Queue-Time": {+ "description": "Worker-reported queue time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Wait-Time": {+ "description": "Milliseconds spent waiting for worker results",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Request-Id": {+ "description": "Gateway request id for queue-backed inference",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Worker": {+ "description": "Logical queue worker tag that produced the response",+ "schema": {+ "type": "string"+ }+ },+ "X-Tokenization-Time": {+ "description": "Worker-reported tokenization time in milliseconds, when available",+ "schema": {+ "type": "string"}}- },- "description": "Worker provisioning in progress"+ }},"400": {"content": {@@ -4871,7 +4869,33 @@}}},- "description": "Queue unavailable or model loading"+ "description": "Provisioning in progress, queue unavailable, or model loading",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds, when retryable",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }},"504": {"content": {@@ -5416,7 +5440,33 @@}}},- "description": "Queue unavailable"+ "description": "Provisioning in progress, queue unavailable, or model loading",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds, when retryable",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }}},"summary": "`/v1/responses` — OpenAI Responses API (MVP, stateless single-turn).",@@ -5607,36 +5657,6 @@}}},- "202": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ProvisioningResponse"- }- }- },- "description": "Worker provisioning in progress",- "headers": {- "Retry-After": {- "description": "Suggested retry delay in seconds",- "schema": {- "type": "string"- }- },- "X-SIE-Server-Version": {- "description": "Gateway-compatible server version advertised by this gateway",- "schema": {- "type": "string"- }- },- "X-SIE-Version": {- "description": "Gateway package version that handled the request",- "schema": {- "type": "string"- }- }- }- },"400": {"content": {"application/json": {@@ -5748,7 +5768,7 @@}}},- "description": "Queue unavailable, GPU not configured, model loading, or capacity exhausted",+ "description": "Provisioning in progress, queue unavailable, GPU not configured, model loading, or capacity exhausted","headers": {"Retry-After": {"description": "Suggested retry delay in seconds, when retryable",diff --git a/packages/sie_gateway/src/error.rs b/packages/sie_gateway/src/error.rsindex 128a7fdbd..77664c6df 100644--- a/packages/sie_gateway/src/error.rs+++ b/packages/sie_gateway/src/error.rs@@ -1,8 +1,11 @@-use axum::http::StatusCode;+use axum::http::{HeaderName, HeaderValue, StatusCode};use axum::response::{IntoResponse, Response};use crate::http_error::{code as err_code, json_detail};+const GATEWAY_VERSION: &str = env!("CARGO_PKG_VERSION");+const PROVISIONING_RETRY_AFTER: &str = "60";+#[allow(dead_code)]#[derive(Debug, thiserror::Error)]pub enum AppError {@@ -21,6 +24,7 @@ pub enum AppError {impl IntoResponse for AppError {fn into_response(self) -> Response {+ let is_gpu_provisioning = matches!(self, AppError::GpuProvisioning(_));let (status, code, message) = match &self {AppError::NoWorkerAvailable => (StatusCode::SERVICE_UNAVAILABLE,@@ -28,7 +32,7 @@ impl IntoResponse for AppError {self.to_string(),),AppError::GpuProvisioning(_) => (- StatusCode::ACCEPTED,+ StatusCode::SERVICE_UNAVAILABLE,err_code::PROVISIONING,self.to_string(),),@@ -45,7 +49,26 @@ impl IntoResponse for AppError {};let body = json_detail(code, message);- (status, axum::Json(body)).into_response()+ let mut response = (status, axum::Json(body)).into_response();+ if is_gpu_provisioning {+ response.headers_mut().insert(+ HeaderName::from_static("retry-after"),+ HeaderValue::from_static(PROVISIONING_RETRY_AFTER),+ );+ response.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(err_code::PROVISIONING),+ );+ response.headers_mut().insert(+ HeaderName::from_static("x-sie-version"),+ HeaderValue::from_static(GATEWAY_VERSION),+ );+ response.headers_mut().insert(+ HeaderName::from_static("x-sie-server-version"),+ HeaderValue::from_static(GATEWAY_VERSION),+ );+ }+ response}}@@ -66,11 +89,26 @@ mod tests {}#[test]- fn test_gpu_provisioning_is_202() {+ fn test_gpu_provisioning_is_503() {assert_eq!(response_status(AppError::GpuProvisioning("l4".into())),- StatusCode::ACCEPTED+ StatusCode::SERVICE_UNAVAILABLE+ );+ }++ #[test]+ fn test_gpu_provisioning_has_retry_headers() {+ let response = AppError::GpuProvisioning("l4".into()).into_response();+ assert_eq!(+ response.headers().get("retry-after").unwrap(),+ PROVISIONING_RETRY_AFTER+ );+ assert_eq!(+ response.headers().get("x-sie-error-code").unwrap(),+ err_code::PROVISIONING);+ assert!(response.headers().get("x-sie-version").is_some());+ assert!(response.headers().get("x-sie-server-version").is_some());}#[test]diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex d403259c4..a1eb5b7bf 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -190,9 +190,12 @@ async fn compute_model_status(// misreport, so `no_bundles` makes the distinction explicit and// `all_bundles_acked` stays false.let mut all_acked = !model_info.bundles.is_empty();+ let model_pool = model_info.pool.as_deref().unwrap_or("default");for bundle_id in &model_info.bundles {- let expected = state.model_registry.compute_bundle_config_hash(bundle_id);+ let expected = state+ .model_registry+ .compute_bundle_config_hash_for_pool(bundle_id, model_pool);let mut total_eligible = 0usize;let mut acked_workers: Vec<String> = Vec::new();@@ -208,6 +211,9 @@ async fn compute_model_status(if worker.bundle != *bundle_id {continue;}+ if !worker.pool_name.eq_ignore_ascii_case(model_pool) {+ continue;+ }if !worker.healthy() {continue;}@@ -226,6 +232,7 @@ async fn compute_model_status(bundles_out.push(json!({"bundle_id": bundle_id,+ "pool": model_pool,"expected_bundle_config_hash": expected,"total_eligible_workers": total_eligible,"acked_workers": acked_workers,@@ -723,6 +730,7 @@ mod tests {name: model_id.to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: None,@@ -799,7 +807,7 @@ mod tests {memory_used_bytes: Some(0),memory_total_bytes: Some(0),gpus: Vec::new(),- pool_name: String::new(),+ pool_name: "default".into(),saturated: false,terminated: false,}@@ -811,7 +819,9 @@ mod tests {let models_dir = tempfile::TempDir::new().unwrap();let (app, state) = build_test_router_with_state(&bundles_dir, &models_dir).await;seed_model(&state, "BAAI/bge-m3");- let expected_hash = state.model_registry.compute_bundle_config_hash("default");+ let expected_hash = state+ .model_registry+ .compute_bundle_config_hash_for_pool("default", "default");assert!(!expected_hash.is_empty(), "bundle hash should be populated");state@@ -917,6 +927,7 @@ mod tests {name: "empty/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: None,@@ -935,6 +946,7 @@ mod tests {// compute_model_status directly.let entry = crate::types::model::ModelEntry {name: "empty/model".to_string(),+ pool: None,bundles: Vec::new(),adapter_modules: Default::default(),profile_names: Default::default(),diff --git a/packages/sie_gateway/src/handlers/grammar.rs b/packages/sie_gateway/src/handlers/grammar.rsindex 43bac5a6f..d0af345cf 100644--- a/packages/sie_gateway/src/handlers/grammar.rs+++ b/packages/sie_gateway/src/handlers/grammar.rs@@ -7,7 +7,8 @@//! * Payload size cap (64 KiB)//! * JSON Schema nesting-depth cap (16)//! * Regex length cap (4 KiB)-//! * JSON Schema reject-list (``$ref``, ``$dynamicRef``, ``if/then/else``,+//! * Internal JSON Schema ``$ref`` dereferencing (``#/...`` only)+//! * JSON Schema reject-list (``$dynamicRef``, ``if/then/else``,//! ``unevaluatedProperties``, ``dependentSchemas``)//! * Mutual exclusivity of ``json_schema`` and ``regex``//!@@ -17,16 +18,14 @@//! The worker is downstream and assumes the gateway has already//! filtered — it does not re-check these caps.//!-//! ``$ref`` rejection note: the spec wording is "external ``$ref``";-//! v1 rejects **all** ``$ref`` (including internal ``#/...``) for-//! implementation simplicity. The error message and the OpenAPI spec-//! both call this out; this can be refined if customer pressure justifies-//! the JSON-pointer resolver.+//! ``$ref`` support is deliberately bounded to internal JSON pointers+//! (``#/...``). External documents, unresolved pointers, and recursive+//! reference cycles are rejected before the worker sees the schema.use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::Json;-use serde_json::Value;+use serde_json::{json, Value};use crate::http_error::{json_openai_error, openai_code as oai_code, openai_type as oai_type};use crate::metrics;@@ -117,7 +116,6 @@ pub const MAX_EBNF_LEN: usize = 8 * 1024;/// compile cost. Each rejection names the keyword in ``param`` so/// callers can fix their schema without trial-and-error.const UNSUPPORTED_KEYWORDS: &[&str] = &[- "$ref","$dynamicRef","if","then",@@ -226,11 +224,27 @@ pub fn parse_grammar(v: &Value) -> GrammarParseResult {if has_schema {let schema = obj.get("json_schema").expect("checked above");- if let Err(resp) = walk_schema(schema, "grammar.json_schema", 0) {+ let resolved_schema = match dereference_schema_refs(schema, "grammar.json_schema") {+ Ok(schema) => schema,+ Err(resp) => return GrammarParseResult::Err(resp),+ };+ let serialized_len =+ json_schema_grammar_len(&resolved_schema, label.as_deref(), strict).unwrap_or(0);+ if serialized_len > MAX_GRAMMAR_BYTES {+ metrics::record_grammar_reject("payload_size");+ return GrammarParseResult::Err(bad_request(+ format!(+ "grammar payload {serialized_len} bytes exceeds limit ({MAX_GRAMMAR_BYTES} bytes)"+ ),+ "grammar",+ oai_code::INVALID_REQUEST,+ ));+ }+ if let Err(resp) = walk_schema(&resolved_schema, "grammar.json_schema", 0) {return GrammarParseResult::Err(resp);}GrammarParseResult::Ok(GrammarSpec::JsonSchema {- value: schema.clone(),+ value: resolved_schema,label,strict,})@@ -290,6 +304,225 @@ pub fn parse_grammar(v: &Value) -> GrammarParseResult {}}+fn json_schema_grammar_len(+ schema: &Value,+ label: Option<&str>,+ strict: Option<bool>,+) -> Result<usize, serde_json::Error> {+ let mut obj = serde_json::Map::new();+ obj.insert("json_schema".to_string(), schema.clone());+ if let Some(label) = label {+ obj.insert("label".to_string(), Value::String(label.to_string()));+ }+ if let Some(strict) = strict {+ obj.insert("strict".to_string(), Value::Bool(strict));+ }+ serde_json::to_vec(&Value::Object(obj)).map(|b| b.len())+}++#[allow(clippy::result_large_err)]+fn dereference_schema_refs(schema: &Value, path: &str) -> Result<Value, Response> {+ let mut visited: usize = 0;+ let mut stack: Vec<String> = Vec::new();+ dereference_schema_refs_inner(+ schema,+ schema,+ path,+ &mut visited,+ &mut stack,+ SchemaResolveContext::Schema,+ )+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum SchemaResolveContext {+ Schema,+ SchemaMap,+ SchemaArray,+ Other,+}++#[allow(clippy::result_large_err)]+fn dereference_schema_refs_inner(+ root: &Value,+ v: &Value,+ path: &str,+ visited: &mut usize,+ stack: &mut Vec<String>,+ context: SchemaResolveContext,+) -> Result<Value, Response> {+ *visited = visited.saturating_add(1);+ if *visited > MAX_SCHEMA_NODES {+ metrics::record_grammar_reject("node_count");+ return Err(bad_request(+ format!("JSON Schema node count exceeds limit ({MAX_SCHEMA_NODES})"),+ path,+ oai_code::INVALID_REQUEST,+ ));+ }++ match v {+ Value::Object(map) => {+ if context == SchemaResolveContext::Schema && map.contains_key("$ref") {+ let ref_value = map.get("$ref").expect("checked above");+ let ref_param = format!("{path}.$ref");+ let Some(ref_str) = ref_value.as_str() else {+ metrics::record_grammar_reject("malformed");+ return Err(bad_request(+ "'$ref' must be a string".to_string(),+ &ref_param,+ oai_code::INVALID_REQUEST,+ ));+ };+ let Some(pointer) = ref_str.strip_prefix('#') else {+ metrics::record_grammar_reject("unsupported_keyword");+ return Err(bad_request(+ "external '$ref' is not supported".to_string(),+ &ref_param,+ oai_code::UNSUPPORTED_FIELD,+ ));+ };+ if !pointer.is_empty() && !pointer.starts_with('/') {+ metrics::record_grammar_reject("unsupported_keyword");+ return Err(bad_request(+ "only internal JSON-pointer '$ref' values are supported".to_string(),+ &ref_param,+ oai_code::UNSUPPORTED_FIELD,+ ));+ }+ if stack.iter().any(|p| p == pointer) {+ metrics::record_grammar_reject("ref_cycle");+ return Err(bad_request(+ format!("recursive '$ref' cycle detected at {ref_str:?}"),+ &ref_param,+ oai_code::INVALID_REQUEST,+ ));+ }+ let Some(target) = root.pointer(pointer) else {+ metrics::record_grammar_reject("ref_unresolved");+ return Err(bad_request(+ format!("unresolved internal '$ref' {ref_str:?}"),+ &ref_param,+ oai_code::INVALID_REQUEST,+ ));+ };++ stack.push(pointer.to_string());+ let resolved = dereference_schema_refs_inner(+ root,+ target,+ path,+ visited,+ stack,+ SchemaResolveContext::Schema,+ )?;+ stack.pop();++ let mut siblings = serde_json::Map::new();+ for (k, child) in map {+ if k == "$ref" || k == "$defs" || k == "definitions" {+ continue;+ }+ let child_path = format!("{path}.{k}");+ let child_context = schema_child_resolve_context(context, k);+ siblings.insert(+ k.clone(),+ dereference_schema_refs_inner(+ root,+ child,+ &child_path,+ visited,+ stack,+ child_context,+ )?,+ );+ }++ if siblings.is_empty() {+ return Ok(resolved);+ }++ // JSON Schema evaluates $ref siblings alongside the+ // referenced schema. Preserve that intersection instead+ // of overwriting same-named object keywords such as+ // properties, required, or allOf.+ Ok(json!({"allOf": [resolved, Value::Object(siblings)]}))+ } else {+ let mut out = serde_json::Map::new();+ for (k, child) in map {+ if context == SchemaResolveContext::Schema+ && (k == "$defs" || k == "definitions")+ {+ continue;+ }+ let child_path = format!("{path}.{k}");+ let child_context = schema_child_resolve_context(context, k);+ out.insert(+ k.clone(),+ dereference_schema_refs_inner(+ root,+ child,+ &child_path,+ visited,+ stack,+ child_context,+ )?,+ );+ }+ Ok(Value::Object(out))+ }+ }+ Value::Array(arr) => {+ let mut out = Vec::with_capacity(arr.len());+ for (i, child) in arr.iter().enumerate() {+ let child_path = format!("{path}[{i}]");+ let child_context = if matches!(+ context,+ SchemaResolveContext::Schema | SchemaResolveContext::SchemaArray+ ) {+ SchemaResolveContext::Schema+ } else {+ SchemaResolveContext::Other+ };+ out.push(dereference_schema_refs_inner(+ root,+ child,+ &child_path,+ visited,+ stack,+ child_context,+ )?);+ }+ Ok(Value::Array(out))+ }+ _ => Ok(v.clone()),+ }+}++fn schema_child_resolve_context(parent: SchemaResolveContext, key: &str) -> SchemaResolveContext {+ match parent {+ SchemaResolveContext::Schema => match key {+ "properties" | "patternProperties" | "$defs" | "definitions" | "dependentSchemas" => {+ SchemaResolveContext::SchemaMap+ }+ "oneOf" | "anyOf" | "allOf" | "prefixItems" => SchemaResolveContext::SchemaArray,+ "items"+ | "additionalProperties"+ | "contains"+ | "propertyNames"+ | "not"+ | "if"+ | "then"+ | "else" => SchemaResolveContext::Schema,+ _ => SchemaResolveContext::Other,+ },+ SchemaResolveContext::SchemaMap => SchemaResolveContext::Schema,+ SchemaResolveContext::SchemaArray | SchemaResolveContext::Other => {+ SchemaResolveContext::Other+ }+ }+}+/// Recursive walk over a JSON-Schema-shaped value. Enforces depth and/// rejects the unsupported keywords listed in/// :const:`UNSUPPORTED_KEYWORDS`.@@ -336,16 +569,7 @@ fn walk_schema_inner(if map.contains_key(kw) {metrics::record_grammar_reject("unsupported_keyword");let param = format!("{path}.{kw}");- let message = if kw == "$ref" {- // Grammar v1 blanket-rejects all ``$ref``,- // including internal ``#/...``. The spec- // wording is "external ``$ref``"; later revisions may- // refine. Documented in OpenAPI.- "'$ref' is not supported (the grammar surface rejects all $ref including internal)"- .to_string()- } else {- format!("JSON Schema keyword '{kw}' is not supported")- };+ let message = format!("JSON Schema keyword '{kw}' is not supported");return Err(bad_request(message, ¶m, oai_code::UNSUPPORTED_FIELD));}}@@ -485,14 +709,148 @@ mod tests {);}- #[tokio::test]- async fn test_parse_grammar_rejects_dollar_ref() {+ #[test]+ fn test_parse_grammar_dereferences_internal_dollar_ref() {let v = json!({"json_schema": {"type": "object",+ "$defs": {+ "Foo": {+ "type": "object",+ "properties": {"name": {"type": "string"}},+ "required": ["name"],+ }+ },"properties": {"a": {"$ref": "#/$defs/Foo"}},}});+ let spec = ok_or_panic(parse_grammar(&v));+ let GrammarSpec::JsonSchema { value, .. } = spec else {+ panic!("expected JsonSchema");+ };+ assert_eq!(+ value["properties"]["a"]["properties"]["name"]["type"],+ "string"+ );+ assert!(+ value.get("$defs").is_none(),+ "$defs should be stripped after inlining"+ );+ let encoded = serde_json::to_string(&value).unwrap();+ assert!(+ !encoded.contains("\"$ref\""),+ "schema should be fully dereferenced: {encoded}"+ );+ }++ #[test]+ fn test_parse_grammar_preserves_dollar_ref_sibling_constraints() {+ let v = json!({+ "json_schema": {+ "type": "object",+ "$defs": {+ "Foo": {+ "type": "object",+ "properties": {"base": {"type": "string"}},+ "required": ["base"],+ }+ },+ "properties": {+ "item": {+ "$ref": "#/$defs/Foo",+ "type": "object",+ "properties": {"extra": {"type": "integer"}},+ "required": ["extra"],+ }+ },+ }+ });+ let spec = ok_or_panic(parse_grammar(&v));+ let GrammarSpec::JsonSchema { value, .. } = spec else {+ panic!("expected JsonSchema");+ };+ let all_of = value["properties"]["item"]["allOf"]+ .as_array()+ .expect("ref sibling schema should be represented as allOf");+ assert_eq!(all_of.len(), 2);+ assert_eq!(all_of[0]["properties"]["base"]["type"], "string");+ assert_eq!(all_of[0]["required"], json!(["base"]));+ assert_eq!(all_of[1]["properties"]["extra"]["type"], "integer");+ assert_eq!(all_of[1]["required"], json!(["extra"]));+ let encoded = serde_json::to_string(&value).unwrap();+ assert!(+ !encoded.contains("\"$ref\"") && !encoded.contains("\"$defs\""),+ "schema should be fully dereferenced: {encoded}"+ );+ }++ #[test]+ fn test_parse_grammar_dereferences_pydantic_openai_style_schema() {+ let v = json!({+ "json_schema": {+ "$defs": {+ "Step": {+ "type": "object",+ "properties": {+ "explanation": {"type": "string"},+ "output": {"type": "string"},+ },+ "required": ["explanation", "output"],+ "additionalProperties": false,+ }+ },+ "type": "object",+ "properties": {+ "steps": {+ "type": "array",+ "items": {"$ref": "#/$defs/Step"},+ },+ "single": {+ "$ref": "#/$defs/Step",+ "description": "one step",+ },+ "final_answer": {"type": "string"},+ },+ "required": ["steps", "single", "final_answer"],+ "additionalProperties": false,+ }+ });+ let spec = ok_or_panic(parse_grammar(&v));+ let GrammarSpec::JsonSchema { value, .. } = spec else {+ panic!("expected JsonSchema");+ };+ assert_eq!(+ value["properties"]["steps"]["items"]["properties"]["explanation"]["type"],+ "string"+ );+ assert_eq!(+ value["properties"]["steps"]["items"]["additionalProperties"],+ false+ );+ let single_all_of = value["properties"]["single"]["allOf"]+ .as_array()+ .expect("Pydantic ref sibling should be preserved as allOf");+ assert_eq!(+ single_all_of[0]["properties"]["explanation"]["type"],+ "string"+ );+ assert_eq!(single_all_of[1]["description"], "one step");+ assert_eq!(value["additionalProperties"], false);+ let encoded = serde_json::to_string(&value).unwrap();+ assert!(+ !encoded.contains("\"$ref\"") && !encoded.contains("\"$defs\""),+ "schema should be fully dereferenced: {encoded}"+ );+ }++ #[tokio::test]+ async fn test_parse_grammar_rejects_external_dollar_ref() {+ let v = json!({+ "json_schema": {+ "type": "object",+ "properties": {"a": {"$ref": "https://example.com/schemas/foo.json"}},+ }+ });let body = err_or_panic(parse_grammar(&v)).await;assert_eq!(body["error"]["code"], "unsupported_field");assert_eq!(@@ -500,7 +858,31 @@ mod tests {"grammar.json_schema.properties.a.$ref");let msg = body["error"]["message"].as_str().unwrap_or("");- assert!(msg.contains("$ref"), "msg should mention $ref: {msg}");+ assert!(+ msg.contains("external"),+ "msg should mention external refs: {msg}"+ );+ }++ #[tokio::test]+ async fn test_parse_grammar_rejects_recursive_dollar_ref_cycle() {+ let v = json!({+ "json_schema": {+ "$defs": {+ "A": {"$ref": "#/$defs/B"},+ "B": {"$ref": "#/$defs/A"},+ },+ "properties": {"a": {"$ref": "#/$defs/A"}},+ }+ });+ let body = err_or_panic(parse_grammar(&v)).await;+ assert_eq!(body["error"]["code"], "invalid_request");+ assert_eq!(+ body["error"]["param"],+ "grammar.json_schema.properties.a.$ref"+ );+ let msg = body["error"]["message"].as_str().unwrap_or("");+ assert!(msg.contains("cycle"), "msg should mention cycle: {msg}");}#[tokio::test]diff --git a/packages/sie_gateway/src/handlers/health.rs b/packages/sie_gateway/src/handlers/health.rsindex 2c11fa6a5..cc34591e3 100644--- a/packages/sie_gateway/src/handlers/health.rs+++ b/packages/sie_gateway/src/handlers/health.rs@@ -98,7 +98,7 @@ pub async fn healthz() -> impl IntoResponse {get,path = "/readyz",tag = "health",- description = "Process readiness only. Always returns 200 once the gateway is serving requests; never returns 503. Worker readiness is reported by GET /health and by inference responses (202 + Retry-After from a workerless gateway). This contract supports KEDA scale-from-zero.",+ description = "Process readiness only. Always returns 200 once the gateway is serving requests; never returns 503. Worker readiness is reported by GET /health and by inference responses with retryable provisioning signals from a workerless gateway. This contract supports KEDA scale-from-zero.",responses((status = 200, description = "Gateway process is ready", body = String, content_type = "text/plain; charset=utf-8"))diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 38756b984..c75b402f5 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -163,6 +163,7 @@ fn canonical_worker_models(fn worker_only_model_info(name: &str, loaded: bool) -> Value {ModelEntry {name: name.to_string(),+ pool: None,bundles: Vec::new(),adapter_modules: HashSet::new(),profile_names: HashSet::new(),@@ -409,6 +410,7 @@ mod route_tests {name: model_id.to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,tasks: None,@@ -530,6 +532,7 @@ mod route_tests {name: model_id.to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,tasks: Some(serde_yaml::from_str("generate: {}").unwrap()),diff --git a/packages/sie_gateway/src/handlers/pools.rs b/packages/sie_gateway/src/handlers/pools.rsindex cefe1a8dd..d9d4f4840 100644--- a/packages/sie_gateway/src/handlers/pools.rs+++ b/packages/sie_gateway/src/handlers/pools.rs@@ -141,7 +141,7 @@ pub async fn delete_pool(State(state): State<Arc<AppState>>,Path(name): Path<String>,) -> impl IntoResponse {- if name == DEFAULT_POOL_NAME {+ if name.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {return (StatusCode::FORBIDDEN,Json(json_detail(diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 6aeceb93c..572efb83c 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -22,7 +22,7 @@ use crate::queue::publisher;use crate::server::AppState;use crate::state::model_registry::ResolveError;-use crate::state::pool_manager::{PoolManager, DEFAULT_POOL_NAME};+use crate::state::pool_manager::{normalize_pool_name, PoolManager, DEFAULT_POOL_NAME};use crate::state::worker_registry::{QueueRoute, WorkerRegistry};use crate::types::AuditEntry;@@ -55,7 +55,10 @@ pub(crate) fn system_fingerprint(model: &str) -> String {input.push_str(GATEWAY_VERSION);format!("fp_{:016x}", xxhash_rust::xxh3::xxh3_64(input.as_bytes()))}-const DEFAULT_RETRY_AFTER: &str = "120";+/// Provisioning is a retryable pre-execution capacity miss, not an accepted+/// asynchronous job. Keep the Retry-After hint within the range common OpenAI+/// SDKs honor directly.+pub(crate) const PROVISIONING_RETRY_AFTER: &str = "60";const BACKPRESSURE_RETRY_AFTER: &str = "5";const MODEL_LOADING_RETRY_AFTER: &str = "5";const MODEL_LOADING_ERROR_CODE: &str = "MODEL_LOADING";@@ -72,7 +75,6 @@ const RESOURCE_EXHAUSTED_RETRY_AFTER: &str = "5";/// see ``sie_sdk.client._shared.LORA_LOADING_*``.const LORA_LOADING_ERROR_CODE: &str = "LORA_LOADING";const LORA_LOADING_RETRY_AFTER: &str = "5";-const ESTIMATED_WAIT_S: u64 = 180;/// Terminal model load failure (non-retryable). Matches ``sie_server`` HTTP 502/// contract so ``sie_sdk`` can short-circuit before the ``MODEL_LOADING`` retry/// budget (see ``raise_if_model_load_failed``).@@ -193,11 +195,17 @@ enum PoolResolution {/// A healthy worker is registered and this is the pool to publish to.Route(QueueRoute),/// No healthy worker matches the requested `(pool, machine_profile,- /// bundle)` lane — the caller should emit `202 provisioning` and record- /// pending demand so KEDA scales up.+ /// bundle)` lane — the caller should emit the surface-specific+ /// provisioning response and record pending demand so KEDA scales up.Provisioning,}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ProvisioningSurface {+ Native,+ OpenAiCompat,+}+/// Result of `resolve_effective_pool` — bundles the routing decision/// with a flag telling the caller whether the registry had an exact/// `(bundle, machine_profile)` worker match.@@ -250,6 +258,28 @@ fn is_valid_pool_name(pool: &str) -> bool {.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))}+fn apply_model_pool_default(+ requested_pool: &mut String,+ model_pool: Option<&str>,+) -> Result<(), String> {+ let Some(model_pool) = model_pool else {+ if requested_pool.is_empty() {+ *requested_pool = DEFAULT_POOL_NAME.to_string();+ }+ return Ok(());+ };+ if requested_pool.is_empty() {+ *requested_pool = model_pool.to_string();+ return Ok(());+ }+ if requested_pool == model_pool {+ return Ok(());+ }+ Err(format!(+ "Model is assigned to pool '{model_pool}', but request targeted pool '{requested_pool}'"+ ))+}+/// Pure decision logic for the scale-from-zero branch of `proxy_request`./// Kept as a free function so it can be unit-tested without standing up/// an `AppState` / `WorkPublisher`.@@ -268,7 +298,7 @@ fn is_valid_pool_name(pool: &str) -> bool {/// provisioning for that cold lane; the gateway must not silently route to/// another machine profile./// - If nothing resolves, return `Provisioning` so the caller can emit-/// `202 + Retry-After` — regardless of whether the caller sent+/// provisioning response — regardless of whether the caller sent/// `X-SIE-MACHINE-PROFILE`. Before the fix this branch only fired when/// `gpu` was non-empty, which turned a normal cold start into a queue/// timeout for default-routing clients.@@ -284,9 +314,9 @@ async fn resolve_effective_pool(// Caller pinned a pool. With the new subject shape, a pool-only// pin is not enough to publish cold unless we can infer a single// machine-profile token from the pool spec. A pool+GPU pin names the- // exact cold lane KEDA is expected to scale, but we still return 202- // until a healthy worker is present so the gateway does not publish to- // a stream with no active consumer.+ // exact cold lane KEDA is expected to scale, but we still return a+ // retryable provisioning error until a healthy worker is present so+ // the gateway does not publish to a stream with no active consumer.if gpu.is_empty() {let route = registry.resolve_queue_route_in_pool(bundle, "", pool_name, bundle_config_hash)@@ -357,17 +387,8 @@ async fn infer_single_pool_profile(manager.single_machine_profile_for_pool(pool_name).await}-fn build_provisioning_response(gpu: &str, bundle: &str) -> Response {- let gpu_label = if gpu.is_empty() { "any" } else { gpu };- info!(- gpu = %gpu_label,- bundle = %bundle,- "no queue worker available, returning 202",- );- metrics::PROVISIONING_RESPONSES- .with_label_values(&[gpu_label])- .inc();- let message = if gpu.is_empty() {+fn provisioning_message(gpu: &str, bundle: &str) -> String {+ if gpu.is_empty() {format!("No worker available for bundle '{}'. Provisioning in progress.",bundle@@ -377,21 +398,13 @@ fn build_provisioning_response(gpu: &str, bundle: &str) -> Response {"No worker available for GPU type '{}'. Provisioning in progress.",gpu)- };- let mut resp = (- StatusCode::ACCEPTED,- Json(json!({- "status": "provisioning",- "gpu": gpu,- "bundle": bundle,- "estimated_wait_s": ESTIMATED_WAIT_S,- "message": message,- })),- )- .into_response();+ }+}++fn add_provisioning_headers(resp: &mut Response, retry_after: &'static str) {resp.headers_mut().insert(HeaderName::from_static("retry-after"),- HeaderValue::from_static(DEFAULT_RETRY_AFTER),+ HeaderValue::from_static(retry_after),);resp.headers_mut().insert(HeaderName::from_static("x-sie-version"),@@ -401,7 +414,79 @@ fn build_provisioning_response(gpu: &str, bundle: &str) -> Response {HeaderName::from_static("x-sie-server-version"),HeaderValue::from_static(GATEWAY_VERSION),);- resp+}++fn record_provisioning_response(gpu: &str, bundle: &str, status: StatusCode) {+ let gpu_label = if gpu.is_empty() { "any" } else { gpu };+ info!(+ gpu = %gpu_label,+ bundle = %bundle,+ http_status = status.as_u16(),+ "no queue worker available, returning provisioning response",+ );+ metrics::PROVISIONING_RESPONSES+ .with_label_values(&[gpu_label])+ .inc();+}++fn build_provisioning_response_for_surface(+ gpu: &str,+ bundle: &str,+ surface: ProvisioningSurface,+) -> Response {+ let message = provisioning_message(gpu, bundle);+ match surface {+ ProvisioningSurface::Native => {+ record_provisioning_response(gpu, bundle, StatusCode::SERVICE_UNAVAILABLE);+ let mut resp = (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json!({+ "error": {+ "code": err_code::PROVISIONING,+ "message": message,+ }+ })),+ )+ .into_response();+ add_provisioning_headers(&mut resp, PROVISIONING_RETRY_AFTER);+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(err_code::PROVISIONING),+ );+ resp+ }+ ProvisioningSurface::OpenAiCompat => {+ record_provisioning_response(gpu, bundle, StatusCode::SERVICE_UNAVAILABLE);+ let mut resp = (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json_openai_error(+ message,+ oai_type::SERVER_ERROR,+ None,+ oai_code::PROVISIONING,+ )),+ )+ .into_response();+ add_provisioning_headers(&mut resp, PROVISIONING_RETRY_AFTER);+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(err_code::PROVISIONING),+ );+ resp+ }+ }+}++fn build_openai_provisioning_response(gpu: &str, bundle: &str) -> Response {+ build_provisioning_response_for_surface(gpu, bundle, ProvisioningSurface::OpenAiCompat)+}++fn provisioning_surface_for_endpoint(endpoint: &str) -> ProvisioningSurface {+ if endpoint_uses_openai_envelope(endpoint) {+ ProvisioningSurface::OpenAiCompat+ } else {+ ProvisioningSurface::Native+ }}async fn capped_lane_admission_response(@@ -409,6 +494,7 @@ async fn capped_lane_admission_response(pool: &str,machine_profile: &str,bundle: &str,+ provisioning_surface: ProvisioningSurface,) -> Option<Response> {let admission = state.pool_manager@@ -417,30 +503,58 @@ async fn capped_lane_admission_response(if admission.cap == 0 {metrics::record_rejected_request_for_pool(pool, machine_profile, bundle, "pool_cap_zero");+ let message = format!(+ "Pool '{}' admits zero workers for GPU type '{}' and bundle '{}'.",+ pool, machine_profile, bundle+ );let mut m = Map::new();m.insert("pool".to_string(), json!(pool));m.insert("gpu".to_string(), json!(machine_profile));m.insert("bundle".to_string(), json!(bundle));m.insert("cap".to_string(), json!(admission.cap));- return Some(- (+ let mut resp = match provisioning_surface {+ ProvisioningSurface::Native => (StatusCode::SERVICE_UNAVAILABLE,Json(json_detail_merge(err_code::POOL_CAPACITY_UNAVAILABLE,- format!(- "Pool '{}' admits zero workers for GPU type '{}' and bundle '{}'.",- pool, machine_profile, bundle- ),+ message,m,)),).into_response(),+ ProvisioningSurface::OpenAiCompat => (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json_openai_error(+ message,+ oai_type::SERVER_ERROR,+ None,+ oai_code::TRANSPORT_FAILURE,+ )),+ )+ .into_response(),+ };+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(err_code::POOL_CAPACITY_UNAVAILABLE),+ );+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-version"),+ HeaderValue::from_static(GATEWAY_VERSION),+ );+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-server-version"),+ HeaderValue::from_static(GATEWAY_VERSION),);+ return Some(resp);}if admission.assigned_count == 0 {state.demand_tracker.record(pool, machine_profile, bundle);- return Some(build_provisioning_response(machine_profile, bundle));+ return Some(build_provisioning_response_for_surface(+ machine_profile,+ bundle,+ provisioning_surface,+ ));}None@@ -461,7 +575,6 @@ async fn capped_lane_admission_response(request_body = crate::openapi::EncodeRequest,responses((status = 200, description = "Encode response", body = crate::openapi::EncodeResponse),- (status = 202, description = "Worker provisioning in progress", body = crate::openapi::ProvisioningResponse),(status = 400, description = "Invalid request", body = crate::openapi::StandardApiError),(status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),(status = 404, description = "Model not found", body = crate::openapi::StandardApiError),@@ -469,7 +582,7 @@ async fn capped_lane_admission_response((status = 413, description = "Request body too large", body = crate::openapi::StandardApiError),(status = 500, description = "All batch items failed or gateway internal error", body = crate::openapi::InferenceInternalServerErrorResponse),(status = 502, description = "Terminal model load failure (MODEL_LOAD_FAILED)", body = crate::openapi::GatewayModelLoadFailedResponse),- (status = 503, description = "Queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::InferenceServiceUnavailableResponse),+ (status = 503, description = "Provisioning in progress, queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::InferenceServiceUnavailableResponse),(status = 504, description = "Result channel closed", body = crate::openapi::StandardApiError)))]@@ -492,7 +605,6 @@ pub async fn proxy_encode(state: State<Arc<AppState>>, req: Request) -> impl Intrequest_body = crate::openapi::ScoreRequest,responses((status = 200, description = "Score response", body = crate::openapi::ScoreResponse),- (status = 202, description = "Worker provisioning in progress", body = crate::openapi::ProvisioningResponse),(status = 400, description = "Invalid request", body = crate::openapi::StandardApiError),(status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),(status = 404, description = "Model not found", body = crate::openapi::StandardApiError),@@ -500,7 +612,7 @@ pub async fn proxy_encode(state: State<Arc<AppState>>, req: Request) -> impl Int(status = 413, description = "Request body too large", body = crate::openapi::StandardApiError),(status = 500, description = "All batch items failed or gateway internal error", body = crate::openapi::InferenceInternalServerErrorResponse),(status = 502, description = "Terminal model load failure (MODEL_LOAD_FAILED)", body = crate::openapi::GatewayModelLoadFailedResponse),- (status = 503, description = "Queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::InferenceServiceUnavailableResponse),+ (status = 503, description = "Provisioning in progress, queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::InferenceServiceUnavailableResponse),(status = 504, description = "Result channel closed", body = crate::openapi::StandardApiError)))]@@ -523,7 +635,6 @@ pub async fn proxy_score(state: State<Arc<AppState>>, req: Request) -> impl Intorequest_body = crate::openapi::ExtractRequest,responses((status = 200, description = "Extract response", body = crate::openapi::ExtractResponse),- (status = 202, description = "Worker provisioning in progress", body = crate::openapi::ProvisioningResponse),(status = 400, description = "Invalid request", body = crate::openapi::StandardApiError),(status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),(status = 404, description = "Model not found", body = crate::openapi::StandardApiError),@@ -531,7 +642,7 @@ pub async fn proxy_score(state: State<Arc<AppState>>, req: Request) -> impl Into(status = 413, description = "Request body too large", body = crate::openapi::StandardApiError),(status = 500, description = "All batch items failed or gateway internal error", body = crate::openapi::InferenceInternalServerErrorResponse),(status = 502, description = "Terminal model load failure (MODEL_LOAD_FAILED)", body = crate::openapi::GatewayModelLoadFailedResponse),- (status = 503, description = "Queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::InferenceServiceUnavailableResponse),+ (status = 503, description = "Provisioning in progress, queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::InferenceServiceUnavailableResponse),(status = 504, description = "Result channel closed", body = crate::openapi::StandardApiError)))]@@ -555,11 +666,10 @@ pub async fn proxy_extract(state: State<Arc<AppState>>, req: Request) -> impl In),responses((status = 200, description = "Generated text response", body = crate::openapi::GenerateResponse),- (status = 202, description = "Worker provisioning in progress", body = crate::openapi::ProvisioningResponse),(status = 400, description = "Invalid request", body = crate::openapi::OpenAIErrorEnvelope),(status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),(status = 500, description = "Worker emitted malformed response", body = crate::openapi::OpenAIErrorEnvelope),- (status = 503, description = "Queue unavailable or model loading", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 503, description = "Provisioning in progress, queue unavailable, or model loading", body = crate::openapi::OpenAIErrorEnvelope),(status = 504, description = "Generation timeout", body = crate::openapi::OpenAIErrorEnvelope),))]@@ -624,6 +734,7 @@ async fn proxy_request() -> Response {// SDK version skew detectioncheck_sdk_version(req.headers());+ let provisioning_surface = provisioning_surface_for_endpoint(endpoint);// Keep the pre-generation queue hot path untouched for encode /// score / extract. Native `/v1/generate/{model}` is the only route@@ -842,6 +953,22 @@ async fn proxy_request("Invalid pool name: only [A-Za-z0-9_-] are allowed (max 128 chars)",);}+ if !pool_name.is_empty() {+ pool_name = normalize_pool_name(&pool_name);+ }+ let model_pool = state.model_registry.get_model_pool_name(&model_name);+ if let Err(message) = apply_model_pool_default(&mut pool_name, model_pool.as_deref()) {+ metrics::record_rejected_request_for_pool(&pool_name, &gpu, &bundle, "pool_mismatch");+ return endpoint_error_response(+ endpoint,+ StatusCode::BAD_REQUEST,+ err_code::INVALID_REQUEST,+ oai_type::INVALID_REQUEST,+ oai_code::INVALID_REQUEST,+ Some("pool"),+ message,+ );+ }// Resolve bare GPU to spot variantif !gpu.is_empty() && !state.config.configured_gpus.is_empty() {@@ -935,7 +1062,9 @@ async fn proxy_request();};- let bundle_config_hash = state.model_registry.compute_bundle_config_hash(&bundle);+ let bundle_config_hash = state+ .model_registry+ .compute_bundle_config_hash_for_pool(&bundle, &pool_name);// Resolve the effective pool in one shot. `resolve_effective_pool`// folds the demand-tracking probe ("was there an exact@@ -967,16 +1096,6 @@ async fn proxy_request(let effective_route = match lookup.resolution {PoolResolution::Route(route) => route,PoolResolution::Provisioning => {- let gpu_label = if gpu.is_empty() { "any" } else { gpu.as_str() };- info!(- gpu = %gpu_label,- bundle = %bundle,- engine = %engine,- "no queue worker available, returning 202",- );- metrics::PROVISIONING_RESPONSES- .with_label_values(&[gpu_label])- .inc();// If route resolution named a concrete cold lane, demand was// recorded above with that machine-profile label. Otherwise keep// the legacy empty/unknown-profile series for observability even@@ -984,15 +1103,20 @@ async fn proxy_request(if pending_demand_profile.is_none() {state.demand_tracker.record(demand_pool, &gpu, &bundle);}- return build_provisioning_response(&gpu, &bundle);+ return build_provisioning_response_for_surface(&gpu, &bundle, provisioning_surface);}};let effective_pool = &effective_route.pool_name;let effective_machine_profile = &effective_route.machine_profile;- if let Some(resp) =- capped_lane_admission_response(&state, effective_pool, effective_machine_profile, &bundle)- .await+ if let Some(resp) = capped_lane_admission_response(+ &state,+ effective_pool,+ effective_machine_profile,+ &bundle,+ provisioning_surface,+ )+ .await{return resp;}@@ -1083,7 +1207,7 @@ fn should_trace_proxy_request(endpoint: &str) -> bool {////// `pool` is always pre-resolved by the caller via/// [`resolve_effective_pool`] and is guaranteed non-empty: the-/// `PoolResolution::Provisioning` branch returns `202` before we get+/// `PoolResolution::Provisioning` branch returns provisioning before we get/// here, and every `PoolResolution::Route(_)` path produces a non-empty/// string (either the caller-pinned `X-SIE-Pool`, or a `pool_name`/// harvested from the registry snapshot — route resolution filters out@@ -1338,6 +1462,15 @@ async fn queue_mode_proxy(.into_response();}+ if lower.contains("no consumers") {+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "no_consumers");+ return build_provisioning_response_for_surface(+ gpu,+ bundle,+ provisioning_surface_for_endpoint(endpoint),+ );+ }+let mut response = (StatusCode::SERVICE_UNAVAILABLE,Json(json_detail(@@ -1347,13 +1480,7 @@ async fn queue_mode_proxy().into_response();- if lower.contains("no consumers") {- metrics::record_rejected_request_for_pool(pool, gpu, bundle, "no_consumers");- response.headers_mut().insert(- HeaderName::from_static("retry-after"),- HeaderValue::from_static(DEFAULT_RETRY_AFTER),- );- } else if lower.contains("backpressure") {+ if lower.contains("backpressure") {metrics::record_rejected_request_for_pool(pool, gpu, bundle, "backpressure");response.headers_mut().insert(HeaderName::from_static("retry-after"),@@ -1504,7 +1631,7 @@ async fn queue_mode_proxy(// `REQUEST_COUNT` and `REQUEST_LATENCY` are now emitted by// `middleware::metrics::MetricsLayer` for *every* response on the// inference routes, including early returns (404, 413, 503, 504,- // 202 provisioning, ...). Do not re-emit them here or the success+ // provisioning, ...). Do not re-emit them here or the success// path would be double-counted. The worker-registry per-request// bookkeeping stays — it is independent of Prometheus.state.registry.record_request("queue").await;@@ -1888,7 +2015,7 @@ pub(crate) async fn run_streaming_generate(let lower = e.to_lowercase();let retry_after = if lower.contains("no consumers") {metrics::record_rejected_request_for_pool(pool, gpu, bundle, "no_consumers");- Some(DEFAULT_RETRY_AFTER)+ Some(PROVISIONING_RETRY_AFTER)} else if lower.contains("backpressure") {metrics::record_rejected_request_for_pool(pool, gpu, bundle, "backpressure");Some(BACKPRESSURE_RETRY_AFTER)@@ -2224,13 +2351,19 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {message,retry_after,} => {+ let is_no_consumers = message.to_lowercase().contains("no consumers");+ let openai_code = if is_no_consumers {+ oai_code::PROVISIONING+ } else {+ oai_code::TRANSPORT_FAILURE+ };let mut resp = (StatusCode::SERVICE_UNAVAILABLE,Json(json_openai_error(format!("Queue publish failed: {message}"),oai_type::SERVER_ERROR,None,- oai_code::TRANSPORT_FAILURE,+ openai_code,)),).into_response();@@ -2240,6 +2373,12 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {HeaderValue::from_static(ra),);}+ if is_no_consumers {+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(err_code::PROVISIONING),+ );+ }resp.headers_mut().insert(HeaderName::from_static("x-sie-version"),HeaderValue::from_static(GATEWAY_VERSION),@@ -2345,13 +2484,19 @@ pub(crate) fn build_streaming_publish_failed_for_sse(message: &str,retry_after: Option<&'static str>,) -> Response {+ let is_no_consumers = message.to_lowercase().contains("no consumers");+ let openai_code = if is_no_consumers {+ oai_code::PROVISIONING+ } else {+ oai_code::TRANSPORT_FAILURE+ };let mut resp = (StatusCode::SERVICE_UNAVAILABLE,Json(json_openai_error(format!("Queue publish failed: {message}"),oai_type::SERVER_ERROR,None,- oai_code::TRANSPORT_FAILURE,+ openai_code,)),).into_response();@@ -2361,6 +2506,12 @@ pub(crate) fn build_streaming_publish_failed_for_sse(HeaderValue::from_static(ra),);}+ if is_no_consumers {+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(err_code::PROVISIONING),+ );+ }resp.headers_mut().insert(HeaderName::from_static("x-sie-version"),HeaderValue::from_static(GATEWAY_VERSION),@@ -4398,14 +4549,15 @@ struct ResolvedRoute {}/// Resolve GPU/pool routing from headers, validate them, pick the effective-/// pool (or surface a 202 provisioning response), and bind the work publisher.-/// Shared by the chat + completions handlers; the OpenAI-shaped error/202-/// responses are identical across both.+/// pool (or surface an OpenAI-shaped 503 provisioning response), and bind the+/// work publisher. Shared by the chat + completions handlers; the OpenAI-shaped+/// errors are identical across both.#[allow(clippy::result_large_err)]async fn resolve_generation_route(state: &AppState,hdr: &HeaderMap,bundle: &str,+ model_name: &str,) -> Result<ResolvedRoute, Response> {let mut gpu = hdr.get("x-sie-machine-profile")@@ -4437,6 +4589,23 @@ async fn resolve_generation_route().into_response());}+ if !pool_name.is_empty() {+ pool_name = normalize_pool_name(&pool_name);+ }+ let model_pool = state.model_registry.get_model_pool_name(model_name);+ if let Err(message) = apply_model_pool_default(&mut pool_name, model_pool.as_deref()) {+ metrics::record_rejected_request_for_pool(&pool_name, &gpu, bundle, "pool_mismatch");+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ message,+ oai_type::INVALID_REQUEST,+ Some("X-SIE-Pool"),+ oai_code::INVALID_REQUEST,+ )),+ )+ .into_response());+ }if !gpu.is_empty() && !state.config.configured_gpus.is_empty() {gpu = resolve_machine_profile(&gpu, &state.config.gpu_profile_map);@@ -4492,7 +4661,9 @@ async fn resolve_generation_route(.into_response());};- let bundle_config_hash = state.model_registry.compute_bundle_config_hash(bundle);+ let bundle_config_hash = state+ .model_registry+ .compute_bundle_config_hash_for_pool(bundle, &pool_name);let engine = state.model_registry.get_bundle_info(bundle)@@ -4522,15 +4693,20 @@ async fn resolve_generation_route(if pending_demand_profile.is_none() {state.demand_tracker.record(demand_pool, &gpu, bundle);}- return Err(build_provisioning_response(&gpu, bundle));+ return Err(build_openai_provisioning_response(&gpu, bundle));}};let effective_pool = effective_route.pool_name;let effective_machine_profile = effective_route.machine_profile;- if let Some(resp) =- capped_lane_admission_response(state, &effective_pool, &effective_machine_profile, bundle)- .await+ if let Some(resp) = capped_lane_admission_response(+ state,+ &effective_pool,+ &effective_machine_profile,+ bundle,+ ProvisioningSurface::OpenAiCompat,+ )+ .await{return Err(resp);}@@ -4575,7 +4751,7 @@ async fn resolve_generation_route((status = 400, description = "Invalid or unsupported request", body = crate::openapi::OpenAIErrorEnvelope),(status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),(status = 500, description = "Worker emitted malformed response", body = crate::openapi::OpenAIErrorEnvelope),- (status = 503, description = "Queue unavailable", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 503, description = "Provisioning in progress, queue unavailable, or model loading", body = crate::openapi::OpenAIErrorEnvelope),))]pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Response {@@ -4882,7 +5058,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Reswork_publisher: work_publisher_arc,token_id,content_length,- } = match resolve_generation_route(&state, &hdr, &bundle).await {+ } = match resolve_generation_route(&state, &hdr, &bundle, &model_name).await {Ok(r) => r,Err(resp) => return resp,};@@ -5416,7 +5592,7 @@ fn build_text_completion_body((status = 400, description = "Invalid or unsupported request", body = crate::openapi::OpenAIErrorEnvelope),(status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),(status = 500, description = "Worker emitted malformed response", body = crate::openapi::OpenAIErrorEnvelope),- (status = 503, description = "Queue unavailable", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 503, description = "Provisioning in progress, queue unavailable, or model loading", body = crate::openapi::OpenAIErrorEnvelope),))]/// `/v1/completions` — legacy OpenAI Completions. Reuses the shared model/route@@ -5492,7 +5668,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)work_publisher: work_publisher_arc,token_id,content_length,- } = match resolve_generation_route(&state, &hdr, &bundle).await {+ } = match resolve_generation_route(&state, &hdr, &bundle, &model_name).await {Ok(r) => r,Err(resp) => return resp,};@@ -5997,7 +6173,7 @@ fn build_responses_body((status = 400, description = "Invalid or unsupported request", body = crate::openapi::OpenAIErrorEnvelope),(status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),(status = 500, description = "Worker emitted malformed response", body = crate::openapi::OpenAIErrorEnvelope),- (status = 503, description = "Queue unavailable", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 503, description = "Provisioning in progress, queue unavailable, or model loading", body = crate::openapi::OpenAIErrorEnvelope),))]/// `/v1/responses` — OpenAI Responses API (MVP). String `input` → raw-prompt@@ -6071,7 +6247,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -work_publisher: work_publisher_arc,token_id,content_length,- } = match resolve_generation_route(&state, &hdr, &bundle).await {+ } = match resolve_generation_route(&state, &hdr, &bundle, &model_name).await {Ok(r) => r,Err(resp) => return resp,};@@ -6777,9 +6953,10 @@ fn is_openai_embeddings_forwarded_header(name: &str) -> bool {/// envelope. The inner path emits ``{detail:{code,message}}`` (and, for the/// 502/503 SDK-stable shapes, ``{error:{…}}``); a client that wraps/// ``client.embeddings.create(...)`` in ``except openai.APIError`` cannot-/// parse those, so we map the inner ``detail.code`` (or, absent it, the HTTP-/// status) through [`crate::http_error::openai_error_from_detail_code`] and-/// rebuild the body. The upstream status, allowlisted ``x-…`` headers, and+/// parse those, so we map the inner ``detail.code`` / ``error.code`` (or,+/// absent both, the HTTP status) through+/// [`crate::http_error::openai_error_from_detail_code`] and rebuild the body.+/// The upstream status, allowlisted ``x-…`` headers, and/// ``Retry-After`` (so 429/503 auto-retry still works) are preserved. The/// inner ``message`` is already gateway-sanitized (field names + validation/// text, never request content or raw upstream internals); unparseable@@ -6792,10 +6969,12 @@ async fn translate_inner_encode_error(resp: Response) -> Response {Ok(b) => serde_json::from_slice(&b).unwrap_or(Value::Null),Err(_) => Value::Null,};- // SIE-native `detail.code` is the precise discriminator; fall back to the- // HTTP status when the body is the `{error:{…}}` shape or unparseable.+ // SIE-native `detail.code` / SDK-stable `error.code` is the precise+ // discriminator; fall back to the HTTP status only when the body is+ // unparseable or lacks a structured code.let sie_code = parsed.get("detail")+ .or_else(|| parsed.get("error")).and_then(|d| d.get("code")).and_then(|c| c.as_str()).map(str::to_string)@@ -6815,13 +6994,16 @@ async fn translate_inner_encode_error(resp: Response) -> Response {out.headers_mut().insert(k.clone(), v.clone());}}+ if let Ok(value) = HeaderValue::from_str(&sie_code) {+ out.headers_mut()+ .insert(HeaderName::from_static("x-sie-error-code"), value);+ }out}/// Map an HTTP status to the SIE-native ``code`` used as a fallback when an-/// inner error body carries no ``detail.code`` (e.g. the 502/503 SDK-stable-/// ``{error:{…}}`` shapes). Mirrors the status→code pairing in-/// [`crate::http_error::openai_error_from_detail_code`].+/// inner error body carries no ``detail.code`` / ``error.code``. Mirrors the+/// status-to-code pairing in [`crate::http_error::openai_error_from_detail_code`].fn sie_code_from_status(status: StatusCode) -> String {match status {StatusCode::BAD_REQUEST => err_code::INVALID_REQUEST,@@ -7081,8 +7263,10 @@ fn check_sdk_version(headers: &HeaderMap) {/// (which in particular blew every `bin` field up into a/// `Vec<serde_json::Value::Number>` — ~16 MiB of allocations per/// 1 MiB of binary input). JSON bodies are converted to `rmpv` once-/// via [`json_to_rmpv`]; JSON has no binary or ext types so that-/// conversion is cheap and lossless.+/// via [`json_item_to_rmpv`]. Known native media byte fields are+/// base64-decoded into msgpack `bin` to mirror the worker's typed JSON+/// decode; the rest of the JSON item shape is converted cheaply and+/// losslessly./// Failure modes for :func:`parse_queue_request`. ``Generic`` keeps/// the walking-skeleton's string-based wire-error behaviour (caller wraps in a/// generic 400). ``PreBuilt`` carries an already-shaped OpenAI error@@ -7137,10 +7321,7 @@ fn parse_queue_request_json());}- let params = match work_params_from_json(&parsed, endpoint) {- Ok(p) => p,- Err(resp) => return Err(QueueParseError::PreBuilt(resp)),- };+ let params = work_params_from_json(&parsed, endpoint)?;// Generate requests have no ``items`` array — the prompt and sampling// params travel under ``WorkParams.generate`` instead.@@ -7177,7 +7358,10 @@ fn parse_queue_request_json(vec![parsed]};- let items = items_json.into_iter().map(json_to_rmpv).collect();+ let items = items_json+ .into_iter()+ .map(json_item_to_rmpv)+ .collect::<Result<Vec<_>, _>>()?;Ok((items, params))}@@ -7383,7 +7567,7 @@ fn rmpv_to_json_owned(value: &rmpv::Value) -> serde_json::Value {fn work_params_from_json(parsed: &serde_json::Value,endpoint: &str,-) -> Result<publisher::WorkParams, Response> {+) -> Result<publisher::WorkParams, QueueParseError> {if endpoint == "score" {return Ok(publisher::WorkParams {output_types: None,@@ -7399,7 +7583,8 @@ fn work_params_from_json(parsed.get("query").cloned()- .map(json_to_rmpv)+ .map(json_item_to_rmpv)+ .transpose()?.unwrap_or_else(|| rmpv::Value::Map(Vec::new())),),generate: None,@@ -7410,7 +7595,7 @@ fn work_params_from_json(if endpoint == "generate" {return Ok(publisher::WorkParams {- generate: generate_params_from_json(parsed)?,+ generate: generate_params_from_json(parsed).map_err(QueueParseError::PreBuilt)?,..Default::default()});}@@ -8422,11 +8607,84 @@ fn generate_params_from_rmpv(}))}-/// One-shot conversion from `serde_json::Value` to `rmpv::Value`.+/// Convert a native JSON item to `rmpv::Value`, preserving the media bytes+/// contract before the item is published to workers as msgpack.+fn json_item_to_rmpv(value: serde_json::Value) -> Result<rmpv::Value, String> {+ let mut value = json_to_rmpv(value);+ decode_native_media_fields(&mut value)?;+ Ok(value)+}++fn decode_native_media_fields(item: &mut rmpv::Value) -> Result<(), String> {+ let rmpv::Value::Map(entries) = item else {+ return Ok(());+ };++ for (key, value) in entries {+ let Some(key) = rmpv_key_str(key) else {+ continue;+ };+ match key {+ "images" | "documents" => decode_native_media_array(value, key)?,+ "audio" | "video" | "document" => decode_native_media_object(value, key)?,+ _ => {}+ }+ }+ Ok(())+}++fn decode_native_media_array(value: &mut rmpv::Value, field: &str) -> Result<(), String> {+ let rmpv::Value::Array(items) = value else {+ return Ok(());+ };++ for (index, item) in items.iter_mut().enumerate() {+ decode_native_media_object_data(item, &format!("{field}[{index}].data"))?;+ }+ Ok(())+}++fn decode_native_media_object(value: &mut rmpv::Value, field: &str) -> Result<(), String> {+ decode_native_media_object_data(value, &format!("{field}.data"))+}++fn decode_native_media_object_data(value: &mut rmpv::Value, path: &str) -> Result<(), String> {+ let rmpv::Value::Map(entries) = value else {+ return Ok(());+ };++ let Some((_, data_value)) = entries+ .iter_mut()+ .find(|(key, _)| rmpv_key_str(key) == Some("data"))+ else {+ return Ok(());+ };++ let rmpv::Value::String(data) = data_value else {+ return Ok(());+ };+ let data = data+ .as_str()+ .ok_or_else(|| format!("{path} must be UTF-8 base64"))?;+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(data)+ .map_err(|e| format!("invalid base64 in {path}: {e}"))?;+ *data_value = rmpv::Value::Binary(bytes);+ Ok(())+}++fn rmpv_key_str(value: &rmpv::Value) -> Option<&str> {+ match value {+ rmpv::Value::String(s) => s.as_str(),+ _ => None,+ }+}++/// One-shot generic conversion from `serde_json::Value` to `rmpv::Value`./// Used for the JSON request-body path: workers all speak msgpack, so/// we normalize to `rmpv` once at ingress and avoid having two item/// representations flowing through the rest of the publisher.-/// JSON has no binary or ext types, so this is lossless and cheap+/// JSON has no binary or ext types, so this generic conversion is lossless and cheap/// (no per-byte blow-up like `rmpv_to_json` suffered in the opposite/// direction).fn json_to_rmpv(value: serde_json::Value) -> rmpv::Value {@@ -8978,7 +9236,6 @@ fn openai_embedding_items_to_data(),responses((status = 200, description = "OpenAI-compatible embeddings response", body = crate::openapi::OpenAIEmbeddingsListResponse),- (status = 202, description = "Worker provisioning in progress", body = crate::openapi::ProvisioningResponse),(status = 400, description = "Invalid request", body = crate::openapi::OpenAIErrorEnvelope),(status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),(status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),@@ -8986,7 +9243,7 @@ fn openai_embedding_items_to_data((status = 413, description = "Request body too large", body = crate::openapi::OpenAIErrorEnvelope),(status = 500, description = "All batch items failed or gateway internal error", body = crate::openapi::OpenAIErrorEnvelope),(status = 502, description = "MODEL_LOAD_FAILED", body = crate::openapi::OpenAIErrorEnvelope),- (status = 503, description = "Model loading, capacity, queue unavailable, or GPU not configured", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 503, description = "Provisioning in progress, queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::OpenAIErrorEnvelope),(status = 504, description = "Result channel closed", body = crate::openapi::OpenAIErrorEnvelope)))]@@ -9155,9 +9412,7 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Re// Genuine errors (4xx/5xx) from the SIE-native encode path arrive as// `{detail:{code,message}}` (or the 502/503 `{error:{...}}` shapes);// translate them into the OpenAI envelope so the embeddings surface- // stays parseable by `openai`-client error handling. Non-error- // statuses (notably 202 provisioning) are *not* errors — pass them- // through verbatim so provisioning semantics are preserved.+ // stays parseable by `openai`-client error handling.if inner_status.is_client_error() || inner_status.is_server_error() {return translate_inner_encode_error(resp).await;}@@ -9588,15 +9843,55 @@ mod tests {.unwrap();let state = admission_test_state(Arc::clone(&pm));- let resp = capped_lane_admission_response(&state, "tenant", "l4", "default")- .await- .expect("zero-cap lane should fail fast");+ let resp = capped_lane_admission_response(+ &state,+ "tenant",+ "l4",+ "default",+ ProvisioningSurface::Native,+ )+ .await+ .expect("zero-cap lane should fail fast");assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap();let value: serde_json::Value = serde_json::from_slice(&body).unwrap();assert_eq!(value["detail"]["code"], err_code::POOL_CAPACITY_UNAVAILABLE);}+ #[tokio::test]+ async fn test_capped_lane_admission_zero_cap_openai_uses_openai_envelope() {+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));+ let mut gpus = std::collections::HashMap::new();+ gpus.insert("l4".to_string(), 0);+ let mut caps = std::collections::HashMap::new();+ caps.insert("l4".to_string(), 0);+ pm.create_pool_with_caps("tenant", gpus, caps, None, None, 0)+ .await+ .unwrap();+ let state = admission_test_state(Arc::clone(&pm));++ let resp = capped_lane_admission_response(+ &state,+ "tenant",+ "l4",+ "default",+ ProvisioningSurface::OpenAiCompat,+ )+ .await+ .expect("zero-cap lane should fail fast");+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(+ resp.headers().get("x-sie-error-code").unwrap(),+ err_code::POOL_CAPACITY_UNAVAILABLE+ );++ let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(value.get("detail").is_none());+ assert_eq!(value["error"]["type"], oai_type::SERVER_ERROR);+ assert_eq!(value["error"]["code"], oai_code::TRANSPORT_FAILURE);+ }+#[tokio::test]async fn test_capped_lane_admission_zero_assigned_returns_provisioning() {let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));@@ -9609,10 +9904,29 @@ mod tests {.unwrap();let state = admission_test_state(Arc::clone(&pm));- let resp = capped_lane_admission_response(&state, "tenant", "l4", "default")- .await- .expect("capped lane with no admitted workers should provision");- assert_eq!(resp.status(), StatusCode::ACCEPTED);+ let resp = capped_lane_admission_response(+ &state,+ "tenant",+ "l4",+ "default",+ ProvisioningSurface::Native,+ )+ .await+ .expect("capped lane with no admitted workers should provision");+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(+ resp.headers().get("retry-after").unwrap(),+ PROVISIONING_RETRY_AFTER+ );+ assert_eq!(+ resp.headers().get("x-sie-error-code").unwrap(),+ err_code::PROVISIONING+ );+ let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(value["error"]["code"], err_code::PROVISIONING);+ assert!(value.get("status").is_none());+let pending_demand = metrics::PENDING_DEMAND.with_label_values(&["tenant", "l4", "default"]).get();@@ -9624,6 +9938,74 @@ mod tests {assert!((cleared_demand - 0.0).abs() < f64::EPSILON);}+ #[tokio::test]+ async fn test_capped_lane_admission_zero_assigned_openai_returns_retryable_503() {+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));+ let mut gpus = std::collections::HashMap::new();+ gpus.insert("l4".to_string(), 0);+ let mut caps = std::collections::HashMap::new();+ caps.insert("l4".to_string(), 1);+ pm.create_pool_with_caps("tenant", gpus, caps, None, None, 0)+ .await+ .unwrap();+ let state = admission_test_state(Arc::clone(&pm));++ let resp = capped_lane_admission_response(+ &state,+ "tenant",+ "l4",+ "default",+ ProvisioningSurface::OpenAiCompat,+ )+ .await+ .expect("OpenAI-compatible capped lane should provision");+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(+ resp.headers().get("retry-after").unwrap(),+ PROVISIONING_RETRY_AFTER+ );+ assert_eq!(+ resp.headers().get("x-sie-error-code").unwrap(),+ err_code::PROVISIONING+ );++ let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(value.get("detail").is_none());+ assert_eq!(value["error"]["type"], oai_type::SERVER_ERROR);+ assert_eq!(value["error"]["code"], oai_code::PROVISIONING);+ assert!(value["error"]["message"]+ .as_str()+ .unwrap_or("")+ .contains("Provisioning in progress"));+ }++ #[tokio::test]+ async fn test_openai_provisioning_response_empty_gpu_is_retryable_503() {+ let resp = build_openai_provisioning_response("", "default");+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(+ resp.headers().get("retry-after").unwrap(),+ PROVISIONING_RETRY_AFTER+ );+ assert_eq!(+ resp.headers().get("x-sie-error-code").unwrap(),+ err_code::PROVISIONING+ );+ assert!(resp.headers().get("x-sie-version").is_some());+ assert!(resp.headers().get("x-sie-server-version").is_some());++ let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(value.get("detail").is_none());+ assert!(value.get("status").is_none());+ assert_eq!(value["error"]["type"], oai_type::SERVER_ERROR);+ assert_eq!(value["error"]["code"], oai_code::PROVISIONING);+ let message = value["error"]["message"].as_str().unwrap_or("");+ assert!(message.contains("bundle 'default'"));+ assert!(message.contains("Provisioning in progress"));+ }+// ── is_valid_pool_name (pool subject-injection guard) ──────────#[test]@@ -9657,6 +10039,28 @@ mod tests {assert!(is_valid_pool_name(&"a".repeat(128)));}+ #[test]+ fn test_apply_model_pool_default() {+ let mut omitted = String::new();+ apply_model_pool_default(&mut omitted, Some("customer-a")).unwrap();+ assert_eq!(omitted, "customer-a");++ let mut matching = "customer-a".to_string();+ apply_model_pool_default(&mut matching, Some("customer-a")).unwrap();+ assert_eq!(matching, "customer-a");++ let mut mismatched = "default".to_string();+ assert!(apply_model_pool_default(&mut mismatched, Some("customer-a")).is_err());++ let mut unknown_omitted = String::new();+ apply_model_pool_default(&mut unknown_omitted, None).unwrap();+ assert_eq!(unknown_omitted, "default");++ let mut unknown_explicit = "customer-a".to_string();+ apply_model_pool_default(&mut unknown_explicit, None).unwrap();+ assert_eq!(unknown_explicit, "customer-a");+ }+#[test]fn test_decode_model_path_decodes_percent_encoded_slashes() {let model = decode_model_path("premium:%2FBAAI%2Fbge-m3").unwrap();@@ -9857,16 +10261,35 @@ mod tests {assert_eq!(v["error"]["param"], "grammar");}- #[tokio::test]- async fn test_generate_params_from_json_rejects_grammar_dollar_ref() {+ #[test]+ fn test_generate_params_from_json_dereferences_grammar_dollar_ref() {let body = serde_json::json!({"prompt": "Hi","max_new_tokens": 16,- "grammar": {"json_schema": {"$ref": "#/$defs/X"}},+ "grammar": {+ "json_schema": {+ "$defs": {+ "X": {"type": "object", "properties": {"x": {"type": "string"}}}+ },+ "properties": {"item": {"$ref": "#/$defs/X"}}+ }+ },});- let v = _expect_generate_err(&body).await;- assert_eq!(v["error"]["code"], "unsupported_field");- assert!(v["error"]["param"].as_str().unwrap_or("").ends_with("$ref"));+ let params = _expect_generate_ok(&body);+ match params.grammar {+ Some(publisher::GrammarSpec::JsonSchema { value, .. }) => {+ assert_eq!(+ value["properties"]["item"]["properties"]["x"]["type"],+ "string"+ );+ let encoded = serde_json::to_string(&value).unwrap();+ assert!(+ !encoded.contains("\"$ref\""),+ "schema should be dereferenced: {encoded}"+ );+ }+ other => panic!("expected JsonSchema grammar, got {other:?}"),+ }}#[test]@@ -10608,6 +11031,78 @@ mod tests {assert_eq!(body["error"]["message"], "pool saturated");}+ #[tokio::test]+ async fn test_translate_inner_encode_pool_capacity_error_to_openai_envelope() {+ let resp = (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json_detail(+ err_code::POOL_CAPACITY_UNAVAILABLE,+ "pool admits zero workers",+ )),+ )+ .into_response();+ let out = translate_inner_encode_error(resp).await;+ assert_eq!(out.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert!(+ out.headers().get("retry-after").is_none(),+ "hard cap-zero is not retryable provisioning"+ );+ assert_eq!(+ out.headers().get("x-sie-error-code").unwrap(),+ err_code::POOL_CAPACITY_UNAVAILABLE+ );++ let body_bytes = axum::body::to_bytes(out.into_body(), 64 * 1024)+ .await+ .expect("read body");+ let body: serde_json::Value = serde_json::from_slice(&body_bytes).expect("valid JSON");+ assert!(body.get("detail").is_none(), "no leaked detail shape");+ assert_eq!(body["error"]["type"], oai_type::SERVER_ERROR);+ assert_eq!(body["error"]["code"], oai_code::TRANSPORT_FAILURE);+ assert_eq!(body["error"]["message"], "pool admits zero workers");+ }++ #[tokio::test]+ async fn test_translate_inner_encode_provisioning_error_to_openai_503() {+ let mut resp = (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json!({+ "error": {+ "code": err_code::PROVISIONING,+ "message": "No worker available for GPU type 'l4'. Provisioning in progress.",+ },+ })),+ )+ .into_response();+ resp.headers_mut().insert(+ "retry-after",+ HeaderValue::from_static(PROVISIONING_RETRY_AFTER),+ );++ let out = translate_inner_encode_error(resp).await;+ assert_eq!(out.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(+ out.headers().get("retry-after").unwrap(),+ PROVISIONING_RETRY_AFTER+ );+ assert_eq!(+ out.headers().get("x-sie-error-code").unwrap(),+ err_code::PROVISIONING+ );++ let body_bytes = axum::body::to_bytes(out.into_body(), 64 * 1024)+ .await+ .expect("read body");+ let body: serde_json::Value = serde_json::from_slice(&body_bytes).expect("valid JSON");+ assert!(body.get("detail").is_none(), "no leaked detail shape");+ assert_eq!(body["error"]["type"], oai_type::SERVER_ERROR);+ assert_eq!(body["error"]["code"], oai_code::PROVISIONING);+ assert!(body["error"]["message"]+ .as_str()+ .unwrap_or("")+ .contains("l4"));+ }+#[tokio::test]async fn test_translate_inner_encode_error_falls_back_to_status_for_error_shape() {// 502/503 SDK-stable bodies are `{error:{…}}` with no `detail.code`;@@ -11203,6 +11698,87 @@ mod tests {assert_eq!(params.options.unwrap()["truncate"], true);}+ fn rmpv_map_get<'a>(value: &'a rmpv::Value, key: &str) -> Option<&'a rmpv::Value> {+ let rmpv::Value::Map(entries) = value else {+ return None;+ };+ entries.iter().find_map(|(entry_key, entry_value)| {+ if matches!(entry_key, rmpv::Value::String(s) if s.as_str() == Some(key)) {+ Some(entry_value)+ } else {+ None+ }+ })+ }++ fn assert_media_data(value: &rmpv::Value, field: &str, expected: &[u8]) {+ let media = rmpv_map_get(value, field).unwrap_or_else(|| panic!("{field} missing"));+ let data = rmpv_map_get(media, "data").unwrap_or_else(|| panic!("{field}.data missing"));+ assert_eq!(data, &rmpv::Value::Binary(expected.to_vec()));+ }++ #[test]+ fn test_parse_queue_request_json_decodes_native_media_data_to_binary() {+ let body = serde_json::to_vec(&json!({+ "items": [{+ "id": "t",+ "images": [{"data": "aGVsbG8=", "format": "png"}],+ "audio": {"data": "YXVkaW8=", "format": "wav"},+ "video": {"data": "dmlkZW8=", "format": "mp4"},+ "document": {"data": "ZG9j", "format": "pdf"},+ "metadata": {"data": "bm90LW1lZGlh"}+ }],+ "params": {"output_types": ["multivector"]}+ }))+ .unwrap();++ let (items, params) = parse_queue_request(&body, false, "encode").unwrap();+ assert_eq!(params.output_types, Some(vec!["multivector".to_string()]));+ let item = items.first().expect("one item");++ let images = rmpv_map_get(item, "images").expect("images missing");+ let rmpv::Value::Array(images) = images else {+ panic!("images must stay an array");+ };+ let image = images.first().expect("one image");+ let data = rmpv_map_get(image, "data").expect("images[0].data missing");+ assert_eq!(data, &rmpv::Value::Binary(b"hello".to_vec()));+ assert!(matches!(+ rmpv_map_get(image, "format"),+ Some(rmpv::Value::String(s)) if s.as_str() == Some("png")+ ));++ assert_media_data(item, "audio", b"audio");+ assert_media_data(item, "video", b"video");+ assert_media_data(item, "document", b"doc");+ assert!(matches!(+ rmpv_map_get(+ rmpv_map_get(item, "metadata").expect("metadata missing"),+ "data"+ ),+ Some(rmpv::Value::String(s)) if s.as_str() == Some("bm90LW1lZGlh")+ ));+ }++ #[test]+ fn test_parse_queue_request_json_rejects_invalid_native_media_base64() {+ let body = serde_json::to_vec(&json!({+ "items": [{"images": [{"data": "!!!", "format": "png"}]}]+ }))+ .unwrap();++ let err = parse_queue_request(&body, false, "encode").unwrap_err();+ match err {+ QueueParseError::Generic(message) => {+ assert!(+ message.contains("invalid base64 in images[0].data"),+ "unexpected error: {message}"+ );+ }+ QueueParseError::PreBuilt(_) => panic!("expected generic parse error"),+ }+ }+#[test]fn test_parse_queue_request_score_keeps_query_and_items() {let body = serde_json::to_vec(&json!({@@ -11820,12 +12396,12 @@ mod tests {// ── resolve_effective_pool (scale-from-zero decision) ──────────//- // These tests guard the contract that `proxy_request` emits- // `202 provisioning` whenever no healthy worker is registered for+ // These tests guard the contract that route resolution returns+ // `Provisioning` whenever no healthy worker is registered for// `(bundle, gpu)` — regardless of whether the caller sent an// `X-SIE-MACHINE-PROFILE` header. An earlier regression gated the- // 202 branch on `!gpu.is_empty()`, so default-routing cold starts- // fell through to a `"default"` pool publish and hung.+ // provisioning branch on `!gpu.is_empty()`, so default-routing cold+ // starts fell through to a `"default"` pool publish and hung.use crate::types::worker::{GpuStatus, ModelStatus, WorkerStatusMessage};use std::time::Duration as StdDuration;@@ -11869,8 +12445,8 @@ mod tests {// No workers at all. Caller sends no `X-SIE-MACHINE-PROFILE`.// Before the fix this returned `Pool("default")` and the gateway// published to a nonexistent consumer. After the fix we emit- // `Provisioning` so the caller returns `202 + Retry-After` and- // records pending demand for KEDA.+ // `Provisioning` so the caller returns its surface-specific+ // provisioning response and records pending demand for KEDA.let reg = pool_registry();let out = resolve_effective_pool(®, None, "default", "", "", "").await;assert_eq!(out.resolution, PoolResolution::Provisioning);@@ -11925,7 +12501,7 @@ mod tests {#[tokio::test]async fn test_resolve_effective_pool_returns_pool_when_worker_matches_no_gpu() {// Common default-routing flow: no GPU header, one worker on the- // requested bundle → route to its pool directly (no 202).+ // requested bundle → route to its pool directly (no provisioning error).let reg = pool_registry();reg.update_worker("http://w1:8080",@@ -12005,8 +12581,8 @@ mod tests {async fn test_resolve_effective_pool_provisions_explicit_pool_when_only_other_pool_exists() {// Explicit pool + GPU names a cold lane. A default or unrelated// isolation worker cannot consume the pinned pool's stream, so the- // gateway must return 202 instead of publishing to a lane with no- // active consumer.+ // gateway must return a retryable provisioning error instead of+ // publishing to a lane with no active consumer.let reg = pool_registry();reg.update_worker("http://w1:8080", worker_msg("default", "l4-spot", "pool-a")).await;@@ -12640,21 +13216,71 @@ mod tests {assert_eq!(v["error"]["param"], "response_format.type");}- /// The shared safety walker applies to the chat translator too:- /// a ``$ref`` inside ``json_schema.schema`` rejects with the- /// param path naming the keyword.- #[tokio::test]- async fn test_chat_params_from_json_response_format_rejects_dollar_ref() {+ /// The shared safety walker applies to the chat translator too, after+ /// internal ``$ref`` entries inside ``json_schema.schema`` are inlined.+ #[test]+ fn test_chat_params_from_json_response_format_dereferences_dollar_ref() {let mut body = _chat_body_min("m");body["response_format"] = serde_json::json!({"type": "json_schema","json_schema": {- "schema": {"$ref": "#/$defs/Foo"},+ "schema": {+ "$defs": {+ "Step": {+ "type": "object",+ "properties": {+ "explanation": {"type": "string"},+ "output": {"type": "string"}+ },+ "required": ["explanation", "output"],+ "additionalProperties": false+ }+ },+ "type": "object",+ "properties": {+ "steps": {+ "type": "array",+ "items": {"$ref": "#/$defs/Step"}+ },+ "single": {+ "$ref": "#/$defs/Step",+ "description": "one step"+ },+ "final_answer": {"type": "string"}+ },+ "required": ["steps", "single", "final_answer"],+ "additionalProperties": false+ },}});- let v = _expect_chat_err(body).await;- assert_eq!(v["error"]["code"], "unsupported_field");- assert!(v["error"]["param"].as_str().unwrap_or("").ends_with("$ref"));+ let p = _expect_chat_ok(body);+ match p.grammar {+ Some(publisher::GrammarSpec::JsonSchema { value, .. }) => {+ assert_eq!(+ value["properties"]["steps"]["items"]["properties"]["explanation"]["type"],+ "string"+ );+ assert_eq!(+ value["properties"]["steps"]["items"]["additionalProperties"],+ false+ );+ let single_all_of = value["properties"]["single"]["allOf"]+ .as_array()+ .expect("Pydantic ref sibling should be preserved as allOf");+ assert_eq!(+ single_all_of[0]["properties"]["explanation"]["type"],+ "string"+ );+ assert_eq!(single_all_of[1]["description"], "one step");+ assert_eq!(value["additionalProperties"], false);+ let encoded = serde_json::to_string(&value).unwrap();+ assert!(+ !encoded.contains("\"$ref\"") && !encoded.contains("\"$defs\""),+ "schema should be dereferenced: {encoded}"+ );+ }+ other => panic!("expected JsonSchema grammar, got {other:?}"),+ }}#[test]@@ -14416,6 +15042,55 @@ mod tests {// ── Fix 5: 429 rate_limit_error for KV-saturated + pool-full path+ #[tokio::test]+ async fn test_build_streaming_error_response_no_consumers_is_provisioning() {+ let err = StreamingDriverErr::PublishFailed {+ message: "nats: no consumers available".to_string(),+ retry_after: Some(PROVISIONING_RETRY_AFTER),+ };+ let resp = build_streaming_error_response(&err);+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(+ resp.headers().get("retry-after").unwrap(),+ PROVISIONING_RETRY_AFTER+ );+ assert_eq!(+ resp.headers().get("x-sie-error-code").unwrap(),+ err_code::PROVISIONING+ );++ let body = axum::body::to_bytes(resp.into_body(), 16 * 1024)+ .await+ .unwrap();+ let v: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(v["error"]["type"], oai_type::SERVER_ERROR);+ assert_eq!(v["error"]["code"], oai_code::PROVISIONING);+ }++ #[tokio::test]+ async fn test_build_streaming_publish_failed_for_sse_no_consumers_is_provisioning() {+ let resp = build_streaming_publish_failed_for_sse(+ "no consumers available for work stream",+ Some(PROVISIONING_RETRY_AFTER),+ );+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(+ resp.headers().get("retry-after").unwrap(),+ PROVISIONING_RETRY_AFTER+ );+ assert_eq!(+ resp.headers().get("x-sie-error-code").unwrap(),+ err_code::PROVISIONING+ );++ let body = axum::body::to_bytes(resp.into_body(), 16 * 1024)+ .await+ .unwrap();+ let v: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(v["error"]["type"], oai_type::SERVER_ERROR);+ assert_eq!(v["error"]["code"], oai_code::PROVISIONING);+ }+/// ``rate_limit_exceeded`` worker code maps to 429 with the OpenAI/// ``rate_limit_error`` envelope ``type`` and the/// ``rate_limit_exceeded`` ``code`` discriminator. The@@ -14598,6 +15273,7 @@ mod tests {};ModelEntry {name: "acme/multi".to_string(),+ pool: None,bundles: Vec::new(),adapter_modules: std::collections::HashSet::new(),profile_names: ["default".to_string(), "a100".to_string()]@@ -14676,6 +15352,7 @@ mod tests {use crate::types::model::{ModelEntry, ModelInfoExtras};let entry = ModelEntry {name: "acme/bare".to_string(),+ pool: None,bundles: Vec::new(),adapter_modules: std::collections::HashSet::new(),profile_names: std::collections::HashSet::new(),diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex ae462bcff..e3ea14f61 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -215,7 +215,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {let lower = e.to_lowercase();let retry_after = if lower.contains("no consumers") {metrics::record_rejected_request_for_pool(&pool, &gpu, &bundle, "no_consumers");- Some("120")+ Some(crate::handlers::proxy::PROVISIONING_RETRY_AFTER)} else if lower.contains("backpressure") {metrics::record_rejected_request_for_pool(&pool, &gpu, &bundle, "backpressure");Some("5")diff --git a/packages/sie_gateway/src/http_error.rs b/packages/sie_gateway/src/http_error.rsindex 498c9d7cd..c7cab4e65 100644--- a/packages/sie_gateway/src/http_error.rs+++ b/packages/sie_gateway/src/http_error.rs@@ -2,11 +2,12 @@//! SDK-stable responses (``502 MODEL_LOAD_FAILED``, ``503`` retryable ``{"error":{...}}``)//! intentionally stay on their existing shapes.//!-//! The OpenAI-compatible surface introduces a parallel OpenAI-shaped error envelope (see-//! :mod:`openai_code` / :func:`json_openai_error`) used by-//! ``/v1/generate/{model}`` and ``/v1/chat/completions``. The remaining-//! inference endpoints (encode/score/extract/embeddings) still use-//! ``json_detail`` to preserve existing SDK error-handling contracts.+//! The OpenAI-compatible surfaces introduce a parallel OpenAI-shaped error envelope+//! (see :mod:`openai_code` / :func:`json_openai_error`). Generation-compatible+//! endpoints build that envelope directly. ``/v1/embeddings`` calls the SIE-native+//! encode path internally and translates non-200 responses back into the OpenAI+//! envelope. Native encode/score/extract endpoints keep ``json_detail`` to preserve+//! existing SDK error-handling contracts.use serde_json::{json, Map, Value};@@ -95,6 +96,8 @@ pub mod openai_code {/// the NAK-then-pool-republish-fails path; future rate limiters/// (per-token-bucket, per-tenant-quota) would land here too.pub const RATE_LIMIT_EXCEEDED: &str = "rate_limit_exceeded";+ /// OpenAI-compatible scale-from-zero / worker provisioning signal.+ pub const PROVISIONING: &str = "provisioning";}/// OpenAI-shaped error body:@@ -141,7 +144,10 @@ pub fn openai_error_from_detail_code(code: &str) -> (&'static str, &'static str)(openai_type::INVALID_REQUEST, openai_code::INVALID_REQUEST)}// 503 — pool/queue saturated or unavailable.- "QUEUE_UNAVAILABLE" => (openai_type::SERVER_ERROR, openai_code::TRANSPORT_FAILURE),+ "QUEUE_UNAVAILABLE" | "POOL_CAPACITY_UNAVAILABLE" => {+ (openai_type::SERVER_ERROR, openai_code::TRANSPORT_FAILURE)+ }+ "PROVISIONING" => (openai_type::SERVER_ERROR, openai_code::PROVISIONING),// 504 — overall deadline blown."GATEWAY_TIMEOUT" => (openai_type::SERVER_ERROR, openai_code::OVERALL_TIMEOUT),// 429 — forward-compatible with Tier 0 rate limiting.@@ -214,6 +220,12 @@ mod tests {"model_not_found",),(code::QUEUE_UNAVAILABLE, "server_error", "transport_failure"),+ (+ code::POOL_CAPACITY_UNAVAILABLE,+ "server_error",+ "transport_failure",+ ),+ (code::PROVISIONING, "server_error", "provisioning"),(code::GATEWAY_TIMEOUT, "server_error", "overall_timeout"),("RATE_LIMIT", "rate_limit_error", "rate_limit_exceeded"),(code::INTERNAL_ERROR, "server_error", "transport_failure"),diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rsindex 9f2ceb32f..f86852c2e 100644--- a/packages/sie_gateway/src/main.rs+++ b/packages/sie_gateway/src/main.rs@@ -273,6 +273,7 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {// at 0 and advances on every successful bootstrap or delta.let config_epoch = state::config_epoch::ConfigEpoch::new();let bundles_hash = state::bundles_hash::BundlesHash::new();+ let bundle_config_hashes_hash = state::bundle_config_hashes_hash::BundleConfigHashesHash::new();// Config persistence lives in sie-config now; the gateway is pure// consumer. It gets its authoritative snapshot via the background@@ -497,6 +498,7 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {Arc::clone(&model_registry),config_epoch.clone(),bundles_hash.clone(),+ bundle_config_hashes_hash.clone(),);state::config_poller::spawn(config.config_service_url.as_deref(),@@ -504,6 +506,7 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {Arc::clone(&model_registry),config_epoch.clone(),bundles_hash.clone(),+ bundle_config_hashes_hash.clone(),state::config_poller::DEFAULT_POLL_INTERVAL,);diff --git a/packages/sie_gateway/src/metrics.rs b/packages/sie_gateway/src/metrics.rsindex 3d094c279..cd20607ec 100644--- a/packages/sie_gateway/src/metrics.rs+++ b/packages/sie_gateway/src/metrics.rs@@ -186,7 +186,7 @@ pub static PROVISIONING_RESPONSES: LazyLock<CounterVec> = LazyLock::new(|| {CounterVec::new(Opts::new("sie_gateway_provisioning_responses_total",- "202 provisioning responses",+ "Provisioning responses returned when no ready worker exists",),&["machine_profile"],)@@ -979,8 +979,9 @@ pub fn update_worker_metrics(workers: &[WorkerSnapshot]) {} else {unhealthy_count += 1;}+ let pool_name = w.pool_name.trim().to_ascii_lowercase();WORKER_QUEUE_DEPTH- .with_label_values(&[&w.pool_name, &w.name, &w.machine_profile, &w.bundle])+ .with_label_values(&[&pool_name, &w.name, &w.machine_profile, &w.bundle]).set(w.queue_depth as f64);WORKER_MEMORY_USED.with_label_values(&[&w.name, &w.machine_profile, &w.bundle])@@ -990,7 +991,7 @@ pub fn update_worker_metrics(workers: &[WorkerSnapshot]) {// `kv_reserved_tokens`; seeding 0.0 keeps the series visible// (and ghost-free, thanks to the reset above).KV_RESERVATION_KNOWN- .with_label_values(&[&w.pool_name, &w.name])+ .with_label_values(&[&pool_name, &w.name]).set(0.0);}@@ -1332,6 +1333,43 @@ mod tests {assert!((unhealthy - 1.0).abs() < f64::EPSILON);}+ #[test]+ fn test_update_worker_metrics_canonicalizes_pool_label_case() {+ let _guard = METRICS_TEST_LOCK.lock().unwrap();+ let _ = &*REGISTRY;+ reset_test_metrics();++ update_worker_metrics(&[WorkerSnapshot {+ name: "w1".to_string(),+ machine_profile: "l4".to_string(),+ bundle: "default".to_string(),+ pool_name: "Customer-Acme".to_string(),+ queue_depth: 5,+ memory_used_bytes: 1000,+ healthy: true,+ }]);++ let canonical = WORKER_QUEUE_DEPTH+ .with_label_values(&["customer-acme", "w1", "l4", "default"])+ .get();+ assert!((canonical - 5.0).abs() < f64::EPSILON);++ let families = REGISTRY.gather();+ let mixed_case_present = families+ .iter()+ .filter(|mf| mf.name() == "sie_gateway_worker_queue_depth")+ .flat_map(|mf| mf.get_metric().iter())+ .any(|m| {+ m.get_label()+ .iter()+ .any(|l| l.name() == "pool" && l.value() == "Customer-Acme")+ });+ assert!(+ !mixed_case_present,+ "worker queue-depth labels must use canonical lowercase pool names"+ );+ }+#[test]fn test_update_model_metrics() {let _guard = METRICS_TEST_LOCK.lock().unwrap();diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rsindex e8510ad8b..87f94883f 100644--- a/packages/sie_gateway/src/nats/manager.rs+++ b/packages/sie_gateway/src/nats/manager.rs@@ -638,6 +638,7 @@ adapters:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles: {let mut profiles = HashMap::new();profiles.insert(diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 40b423663..5ae67dda2 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -130,7 +130,6 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {crate::types::pool::PoolSpec,crate::types::pool::PoolStatus,crate::types::pool::PoolState,- ProvisioningResponse,Relation,ResolveBundleConflictDetail,ResolveBundleConflictResponse,@@ -259,6 +258,17 @@ fn apply_gateway_openapi_overrides(value: &mut Value) {.and_then(|schemas| schemas.get_mut("CreatePoolRequest")){create_pool["required"] = json!(["name"]);+ if let Some(name_schema) = create_pool+ .get_mut("properties")+ .and_then(|properties| properties.get_mut("name"))+ {+ name_schema["minLength"] = json!(1);+ name_schema["maxLength"] = json!(128);+ name_schema["pattern"] = json!("^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$");+ name_schema["description"] = json!(+ "Pool name used in gpu=\"pool/machine_profile\" routing. Names are stored and routed in lowercase. Only ASCII letters, digits, '_' and '-' are allowed; '_default' is reserved."+ );+ }create_pool["anyOf"] = json!([{"required": ["gpus"],@@ -1035,11 +1045,6 @@ fn inject_inference_response_headers(paths: &mut serde_json::Map<String, Value>)"X-Postprocessing-Time": header("Worker-reported postprocessing time in milliseconds, when available"),"X-Payload-Fetch-Time": header("Worker-reported offloaded payload fetch time in milliseconds, when available")});- let provisioning_headers = json!({- "Retry-After": header("Suggested retry delay in seconds"),- "X-SIE-Version": header("Gateway package version that handled the request"),- "X-SIE-Server-Version": header("Gateway-compatible server version advertised by this gateway")- });let retryable_error_headers = json!({"Retry-After": header("Suggested retry delay in seconds, when retryable"),"X-SIE-Error-Code": header("SDK-stable gateway or worker error code"),@@ -1057,6 +1062,7 @@ fn inject_inference_response_headers(paths: &mut serde_json::Map<String, Value>)"/v1/encode/{model}","/v1/score/{model}","/v1/extract/{model}",+ "/v1/generate/{model}",] {let Some(responses) = paths.get_mut(path)@@ -1069,9 +1075,6 @@ fn inject_inference_response_headers(paths: &mut serde_json::Map<String, Value>)if let Some(response) = responses.get_mut("200") {merge_headers(response, &queue_success_headers);}- if let Some(response) = responses.get_mut("202") {- merge_headers(response, &provisioning_headers);- }if let Some(response) = responses.get_mut("502") {merge_headers(response, &terminal_error_headers);}@@ -1089,9 +1092,6 @@ fn inject_inference_response_headers(paths: &mut serde_json::Map<String, Value>)if let Some(response) = responses.get_mut("200") {merge_headers(response, &queue_success_headers);}- if let Some(response) = responses.get_mut("202") {- merge_headers(response, &provisioning_headers);- }if let Some(response) = responses.get_mut("502") {merge_headers(response, &terminal_error_headers);}@@ -1099,6 +1099,19 @@ fn inject_inference_response_headers(paths: &mut serde_json::Map<String, Value>)merge_headers(response, &retryable_error_headers);}}++ for path in ["/v1/chat/completions", "/v1/completions", "/v1/responses"] {+ let Some(response) = paths+ .get_mut(path)+ .and_then(|path_item| path_item.get_mut("post"))+ .and_then(|post| post.get_mut("responses"))+ .and_then(|responses| responses.as_object_mut())+ .and_then(|responses| responses.get_mut("503"))+ else {+ continue;+ };+ merge_headers(response, &retryable_error_headers);+ }}/// Add documented auth responses for bearer-protected operations (spec completeness).@@ -2336,18 +2349,6 @@ pub struct InferenceErrorDetail {pub code: Option<String>,}-#[derive(Debug, Serialize, Deserialize, ToSchema)]-pub struct ProvisioningResponse {- pub status: String,- #[serde(default)]- pub gpu: String,- #[serde(default)]- pub bundle: String,- pub estimated_wait_s: u64,- #[serde(default)]- pub message: String,-}-#[cfg(test)]mod tests {use super::*;@@ -2443,6 +2444,16 @@ mod tests {let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();let create_pool = &spec["components"]["schemas"]["CreatePoolRequest"];assert_eq!(create_pool["required"], json!(["name"]));+ assert_eq!(create_pool["properties"]["name"]["minLength"], json!(1));+ assert_eq!(create_pool["properties"]["name"]["maxLength"], json!(128));+ assert_eq!(+ create_pool["properties"]["name"]["pattern"],+ json!("^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$")+ );+ assert!(create_pool["properties"]["name"]["description"]+ .as_str()+ .unwrap()+ .contains("lowercase"));assert_eq!(create_pool["anyOf"],json!([@@ -2610,20 +2621,42 @@ mod tests {.as_object().unwrap();for status in [- "200", "202", "400", "404", "409", "413", "500", "502", "503", "504",+ "200", "400", "404", "409", "413", "500", "502", "503", "504",] {assert!(responses.contains_key(status), "{path} missing {status}");}+ assert!(+ !responses.contains_key("202"),+ "{path} must not document 202 provisioning"+ );}+ let generate = &spec["paths"]["/v1/generate/{model}"]["post"]["responses"]+ .as_object()+ .unwrap();+ for status in ["200", "400", "404", "500", "503", "504"] {+ assert!(+ generate.contains_key(status),+ "/v1/generate/{{model}} missing {status}"+ );+ }+ assert!(+ !generate.contains_key("202"),+ "/v1/generate/{{model}} must not document 202 provisioning"+ );+let emb = &spec["paths"]["/v1/embeddings"]["post"]["responses"].as_object().unwrap();for status in [- "200", "202", "400", "401", "404", "409", "413", "500", "502", "503", "504",+ "200", "400", "401", "404", "409", "413", "500", "502", "503", "504",] {assert!(emb.contains_key(status), "/v1/embeddings missing {status}");}+ assert!(+ !emb.contains_key("202"),+ "/v1/embeddings must not document 202 as a success-like provisioning response"+ );}#[test]@@ -2746,11 +2779,34 @@ mod tests {assert!(config_resolve.as_object().unwrap().contains_key("403"));assert!(config_resolve.as_object().unwrap().contains_key("500"));- let embeddings_202_headers =- &spec["paths"]["/v1/embeddings"]["post"]["responses"]["202"]["headers"];- assert!(embeddings_202_headers.get("Retry-After").is_some());- assert!(embeddings_202_headers.get("X-SIE-Version").is_some());- assert!(embeddings_202_headers.get("X-SIE-Server-Version").is_some());+ for path in [+ "/v1/encode/{model}",+ "/v1/score/{model}",+ "/v1/extract/{model}",+ "/v1/generate/{model}",+ "/v1/embeddings",+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/responses",+ ] {+ let retryable_503_headers = &spec["paths"][path]["post"]["responses"]["503"]["headers"];+ assert!(+ retryable_503_headers.get("Retry-After").is_some(),+ "{path} 503 missing Retry-After"+ );+ assert!(+ retryable_503_headers.get("X-SIE-Error-Code").is_some(),+ "{path} 503 missing X-SIE-Error-Code"+ );+ assert!(+ retryable_503_headers.get("X-SIE-Version").is_some(),+ "{path} 503 missing X-SIE-Version"+ );+ assert!(+ retryable_503_headers.get("X-SIE-Server-Version").is_some(),+ "{path} 503 missing X-SIE-Server-Version"+ );+ }let embeddings_200_headers =&spec["paths"]["/v1/embeddings"]["post"]["responses"]["200"]["headers"];diff --git a/packages/sie_gateway/src/state/bundle_config_hashes_hash.rs b/packages/sie_gateway/src/state/bundle_config_hashes_hash.rsnew file mode 100644index 000000000..d09e2f47a--- /dev/null+++ b/packages/sie_gateway/src/state/bundle_config_hashes_hash.rs@@ -0,0 +1,72 @@+//! Last-known fingerprint of `sie-config`'s per-bundle config hashes.+//!+//! This is a sibling of [`crate::state::bundles_hash::BundlesHash`]. The+//! bundle-set hash answers "which bundles/adapters exist?", while this value+//! answers "which per-bundle config hashes has the gateway installed from the+//! control plane?". Both can drift while the model-write epoch stays at 0 in+//! no-store or filesystem-baseline deployments.++use std::sync::{Arc, Mutex};++#[derive(Debug, Clone, Default)]+pub struct BundleConfigHashesHash {+ inner: Arc<Mutex<String>>,+}++impl BundleConfigHashesHash {+ pub fn new() -> Self {+ Self::default()+ }++ /// Current best-known hash. Empty means "never installed successfully" or+ /// "sie-config reported no registry state"; any non-empty remote value is+ /// treated as drift by the poller.+ pub fn get(&self) -> String {+ self.inner+ .lock()+ .expect("BundleConfigHashesHash mutex poisoned")+ .clone()+ }++ /// Replace the stored hash. Returns `true` if the value changed.+ pub fn store(&self, value: String) -> bool {+ let mut guard = self+ .inner+ .lock()+ .expect("BundleConfigHashesHash mutex poisoned");+ if *guard == value {+ return false;+ }+ *guard = value;+ true+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn starts_empty() {+ let h = BundleConfigHashesHash::new();+ assert_eq!(h.get(), "");+ }++ #[test]+ fn store_returns_true_on_change_and_false_on_noop() {+ let h = BundleConfigHashesHash::new();+ assert!(h.store("abc".to_string()));+ assert_eq!(h.get(), "abc");+ assert!(!h.store("abc".to_string()));+ assert!(h.store("def".to_string()));+ assert_eq!(h.get(), "def");+ }++ #[test]+ fn clones_share_state() {+ let a = BundleConfigHashesHash::new();+ let b = a.clone();+ a.store("xyz".to_string());+ assert_eq!(b.get(), "xyz");+ }+}diff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex 7243ca3f2..a1488b043 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -13,21 +13,18 @@//! validation with `Adapter(s) not in any known bundle`. Pulling them//! over HTTP makes `sie-config` the single source of truth.//! 2. `GET /v1/configs/export` (admin-auth) — fetches every persisted model-//! config and replays each into the registry so the gateway's served view-//! matches `sie-config`'s view.+//! config and replaces the registry's model set so the gateway's served+//! view matches `sie-config`'s view, including removals.//!//! Live updates after bootstrap arrive via NATS deltas//! (`sie.config.models.*`), which the `NatsManager` feeds into//! `ModelRegistry::add_model_config` (append-only: a profile that already//! exists with a different `CanonicalProfile` is rejected, so single-epoch//! duplicate publishes are caught). The bootstrap and epoch-poller-//! catch-up paths here use the parallel `add_model_config_authoritative`-//! entry point instead, which overrides any conflicting profile and logs-//! a `warn!`. This is required so that a control-plane schema change-//! between the gateway's cold-start fetch (against an old `sie-config`-//! revision) and the next poll tick (after `sie-config` has rolled to a-//! new revision) doesn't lock the registry into a stale, unrecoverable-//! state.+//! catch-up paths here use `replace_model_configs_authoritative` instead,+//! which treats the export as the whole current model surface. This is+//! required so same-epoch filesystem-baseline drift cannot leave stale+//! models in the gateway after the new control-plane hash is stored.//!//! Failure handling://!@@ -40,9 +37,10 @@//! `sie-config` are missing. `GET /readyz` is process readiness only: once//! the gateway listener is serving it returns **200** + plain text `ok`, even//! with zero workers, so the first inference request can reach the gateway and-//! trigger scale-from-zero via `202 + Retry-After`. Bootstrap catch-up is-//! visible separately via `GET /v1/configs/models/{id}/status` (`config_epoch`-//! on that payload), the `sie_gateway_config_epoch` /+//! trigger scale-from-zero via a surface-specific provisioning response.+//! Bootstrap catch-up is visible separately via+//! `GET /v1/configs/models/{id}/status` (`config_epoch` on that payload), the+//! `sie_gateway_config_epoch` ///! `sie_gateway_config_bootstrap_degraded` metrics, and gateway logs — not//! via `/readyz` flipping on export completion.//! - `state::config_poller` runs in parallel, periodically reconciling@@ -73,6 +71,7 @@ const PATH_SEGMENT: &AsciiSet = &CONTROLS.add(b'/').add(b'%');+use crate::state::bundle_config_hashes_hash::BundleConfigHashesHash;use crate::state::bundles_hash::BundlesHash;use crate::state::config_epoch::ConfigEpoch;use crate::state::model_registry::ModelRegistry;@@ -93,7 +92,7 @@ struct ExportSnapshot {models: Vec<ExportedModel>,}-/// `GET /v1/configs/epoch` carries TWO independent drift signals:+/// `GET /v1/configs/epoch` carries independent drift signals:////// - `epoch` — monotonic counter of model-config writes. Drives the/// gateway's model-snapshot re-fetch path (existing behavior).@@ -103,6 +102,10 @@ struct ExportSnapshot {/// doesn't observe them. Without this signal a `sie-config` redeploy that/// adds a bundle would not propagate to the gateway until either the/// gateway pod restarts or a coincidental model write bumps the epoch.+/// - `bundle_config_hashes_hash` — sha256 fingerprint over the per-bundle+/// config hashes exported by `sie-config`. This catches filesystem-baseline+/// or no-store config drift where the model epoch stays unchanged but the+/// hashes workers advertise no longer match the stale gateway view.////// Empty string is the documented "nothing to sync" sentinel and is what/// `sie-config` returns when its registry is unavailable (degraded state).@@ -112,6 +115,8 @@ struct EpochResponse {epoch: u64,#[serde(default)]bundles_hash: String,+ #[serde(default)]+ bundle_config_hashes_hash: String,}/// What `fetch_epoch` returns to the caller. Public so the poller can pass@@ -121,6 +126,7 @@ struct EpochResponse {pub struct EpochSnapshot {pub epoch: u64,pub bundles_hash: String,+ pub bundle_config_hashes_hash: String,}#[derive(Debug, Deserialize)]@@ -187,9 +193,8 @@ pub enum BootstrapError {body: String,},/// The snapshot was fetched but one or more model entries failed to- /// parse or apply. The local registry may be partially updated but- /// `ConfigEpoch` was **not** advanced, so the poller will retry on the- /// next tick.+ /// parse or apply. `ConfigEpoch` was **not** advanced, so the poller will+ /// retry on the next tick.#[error("partial apply: {applied}/{total} models applied, {failed} failed (epoch {epoch} not advanced)")]PartialApply {epoch: u64,@@ -208,9 +213,8 @@ pub struct BootstrapClient {/// Outcome of a single `BootstrapClient::bootstrap` call.////// `epoch` is whatever `sie-config` reported in the snapshot envelope.-/// `applied` counts configs the registry accepted: new entries, profiles-/// the authoritative path overrode, and no-op replays where everything-/// already matched all count. The shared meaning is "this export entry is+/// `applied` counts configs the registry accepted into the authoritative+/// replacement snapshot. The shared meaning is "this export entry is/// reconciled against the current registry state", which is what the/// epoch-advance gate needs./// `failed` counts configs that could not be parsed or whose apply@@ -236,6 +240,10 @@ pub struct BootstrapOutcome {/// value and trigger a re-fetch on the next tick, which is the/// intended fail-safe.pub bundles_hash: String,+ /// sha256 fingerprint of the per-bundle config-hash map as observed on+ /// `GET /v1/configs/epoch` before this bootstrap. See `bundles_hash` for+ /// why storing the pre-fetch value is the conservative ordering.+ pub bundle_config_hashes_hash: String,pub applied: usize,pub failed: usize,pub total: usize,@@ -261,7 +269,7 @@ impl BootstrapClient {})}- /// Fetch the current epoch + bundles-hash from `GET /v1/configs/epoch`.+ /// Fetch the current epoch + drift fingerprints from `GET /v1/configs/epoch`./// Used by `state::config_poller` for bounded-staleness detection/// without pulling a full snapshot every tick.pub async fn fetch_epoch(&self) -> Result<EpochSnapshot, BootstrapError> {@@ -284,6 +292,7 @@ impl BootstrapClient {Ok(EpochSnapshot {epoch: payload.epoch,bundles_hash: payload.bundles_hash,+ bundle_config_hashes_hash: payload.bundle_config_hashes_hash,})}@@ -417,37 +426,11 @@ impl BootstrapClient {"received config export from sie-config");- let mut applied = 0usize;let mut failed = 0usize;+ let mut configs = Vec::new();for model in snapshot.models {match parse_exported_model(&model) {- // Bootstrap uses the AUTHORITATIVE apply path: when an- // existing profile config diverges from the export, the- // registry overrides the stored config (with a warn log)- // instead of returning an append-only conflict. The append-- // only invariant is still enforced on the NATS pub/sub- // delta path in `nats::manager::NatsManager`, so within a- // single epoch duplicate publishes are still caught. See- // `ModelRegistry::add_model_config_authoritative`.- Ok(Some(config)) => match registry.add_model_config_authoritative(config) {- Ok(_) => {- // Count any Ok as applied: created, overridden, or- // pure no-op replay all mean "registry accepted the- // entry against the current bundle/adapter set". A- // no-op replay still confirms the entry is current,- // which is what `applied == total` is meant to- // signal to the epoch-advance gate.- applied += 1;- }- Err(e) => {- warn!(- model = %model.model_id,- error = %e,- "failed to apply exported model config"- );- failed += 1;- }- },+ Ok(Some(config)) => configs.push(config),Ok(None) => {tracing::debug!(model = %model.model_id,@@ -465,13 +448,24 @@ impl BootstrapClient {}}+ let mut applied = 0usize;if failed == 0 {- registry.install_bundle_config_hashes(snapshot.bundle_config_hashes);+ match registry.replace_model_configs_authoritative(configs) {+ Ok(count) => {+ applied = count;+ registry.install_bundle_config_hashes(snapshot.bundle_config_hashes);+ }+ Err(e) => {+ warn!(error = %e, "failed to install authoritative config export");+ failed += 1;+ }+ }}Ok(BootstrapOutcome {epoch: snapshot.epoch,bundles_hash: pre_bootstrap.bundles_hash,+ bundle_config_hashes_hash: pre_bootstrap.bundle_config_hashes_hash,applied,failed,total,@@ -516,6 +510,7 @@ pub async fn bootstrap_once(registry: &ModelRegistry,config_epoch: &ConfigEpoch,bundles_hash: &BundlesHash,+ bundle_config_hashes_hash: &BundleConfigHashesHash,) -> Result<BootstrapOutcome, BootstrapError> {let outcome = client.bootstrap(registry).await?;if !outcome.is_complete() {@@ -539,12 +534,15 @@ pub async fn bootstrap_once(// bundle install or model apply failed we must keep the stored hash// stale so the poller re-enters the re-fetch branch on the next tick.let bundles_hash_changed = bundles_hash.store(outcome.bundles_hash.clone());+ let bundle_config_hashes_hash_changed =+ bundle_config_hashes_hash.store(outcome.bundle_config_hashes_hash.clone());info!(epoch = outcome.epoch,applied = outcome.applied,total = outcome.total,epoch_advanced = advanced,bundles_hash_changed,+ bundle_config_hashes_hash_changed,"bootstrap from sie-config complete",);Ok(outcome)@@ -588,6 +586,7 @@ pub fn spawn_bootstrap_retry(registry: Arc<ModelRegistry>,config_epoch: ConfigEpoch,bundles_hash: BundlesHash,+ bundle_config_hashes_hash: BundleConfigHashesHash,) -> tokio::task::JoinHandle<()> {let base_url = base_url.map(str::to_string);let admin_token = admin_token.map(str::to_string);@@ -616,7 +615,15 @@ pub fn spawn_bootstrap_retry(let started = std::time::Instant::now();let mut degraded = false;loop {- match bootstrap_once(&client, registry.as_ref(), &config_epoch, &bundles_hash).await {+ match bootstrap_once(+ &client,+ registry.as_ref(),+ &config_epoch,+ &bundles_hash,+ &bundle_config_hashes_hash,+ )+ .await+ {Ok(_) => {if degraded {info!(@@ -694,6 +701,30 @@ mod tests {(registry, temp)}+ fn model_config(name: &str) -> ModelConfig {+ ModelConfig {+ name: name.to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles: HashMap::from([(+ "default".to_string(),+ crate::types::model::ProfileConfig {+ adapter_path: Some(+ "sie_server.adapters.sentence_transformer:Adapter".to_string(),+ ),+ max_batch_tokens: None,+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ )]),+ inputs: None,+ max_sequence_length: None,+ tasks: None,+ }+ }+/// Mount minimal `/v1/configs/bundles*` endpoints on `server` returning a/// single `default` bundle that covers/// `sie_server.adapters.sentence_transformer`. Tests that exercise the@@ -734,6 +765,7 @@ mod tests {.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"epoch": epoch,"bundles_hash": bundles_hash,+ "bundle_config_hashes_hash": "bundle_config_hashes_hash",}))).mount(server).await;@@ -785,6 +817,59 @@ mod tests {);}+ #[tokio::test]+ async fn bootstrap_replaces_authoritative_model_set_and_drops_stale_models() {+ let server = MockServer::start().await;+ let (registry, _tmp) = make_registry();+ mount_default_bundles(&server).await;+ mount_default_epoch(&server, 0, "deadbeef").await;++ registry+ .add_model_config(model_config("stale/model"))+ .expect("seed stale gateway-local model");+ assert!(registry.get_model_info("stale/model").is_some());++ let body = serde_json::json!({+ "snapshot_version": 1,+ "epoch": 43,+ "generated_at": "2026-04-17T00:00:00Z",+ "bundle_config_hashes": {"default": "control-plane-hash"},+ "models": [+ {+ "model_id": "kept/model",+ "raw_yaml": "sie_id: kept/model\nprofiles:\n default:\n adapter_path: sie_server.adapters.sentence_transformer:Adapter\n",+ "affected_bundles": ["default"],+ }+ ],+ });++ Mock::given(method("GET"))+ .and(path("/v1/configs/export"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&body))+ .mount(&server)+ .await;++ let client = BootstrapClient::new(server.uri(), None).unwrap();+ let epoch = ConfigEpoch::new();+ let bundles_hash = BundlesHash::new();+ let bundle_config_hashes_hash = BundleConfigHashesHash::new();+ bootstrap_once(+ &client,+ registry.as_ref(),+ &epoch,+ &bundles_hash,+ &bundle_config_hashes_hash,+ )+ .await+ .unwrap();++ assert!(registry.get_model_info("kept/model").is_some());+ assert!(+ registry.get_model_info("stale/model").is_none(),+ "authoritative export replacement must remove models omitted from sie-config"+ );+ }+#[tokio::test]async fn bootstrap_soft_fails_on_5xx() {let server = MockServer::start().await;@@ -811,8 +896,14 @@ mod tests {// No URL configured → task exits immediately, never touching the// registry. We `await` the join handle to confirm it terminated.let (registry, _tmp) = make_registry();- let handle =- spawn_bootstrap_retry(None, None, registry, ConfigEpoch::new(), BundlesHash::new());+ let handle = spawn_bootstrap_retry(+ None,+ None,+ registry,+ ConfigEpoch::new(),+ BundlesHash::new(),+ BundleConfigHashesHash::new(),+ );tokio::time::timeout(Duration::from_secs(1), handle).await.expect("retry task should exit immediately when url is None")@@ -840,14 +931,22 @@ mod tests {let epoch = ConfigEpoch::new();let bundles_hash = BundlesHash::new();+ let bundle_config_hashes_hash = BundleConfigHashesHash::new();let client = BootstrapClient::new(server.uri(), None).unwrap();- bootstrap_once(&client, registry.as_ref(), &epoch, &bundles_hash)- .await- .unwrap();+ bootstrap_once(+ &client,+ registry.as_ref(),+ &epoch,+ &bundles_hash,+ &bundle_config_hashes_hash,+ )+ .await+ .unwrap();assert_eq!(epoch.get(), 77);// BootstrapOutcome carries the pre-bootstrap bundles_hash; confirm// the bridge into BundlesHash actually stored it.assert_eq!(bundles_hash.get(), "deadbeef");+ assert_eq!(bundle_config_hashes_hash.get(), "bundle_config_hashes_hash");// Re-run against a stale snapshot: epoch must not move backward.let stale_body = serde_json::json!({@@ -865,9 +964,15 @@ mod tests {.mount(&stale_server).await;let stale_client = BootstrapClient::new(stale_server.uri(), None).unwrap();- bootstrap_once(&stale_client, registry.as_ref(), &epoch, &bundles_hash)- .await- .unwrap();+ bootstrap_once(+ &stale_client,+ registry.as_ref(),+ &epoch,+ &bundles_hash,+ &bundle_config_hashes_hash,+ )+ .await+ .unwrap();assert_eq!(epoch.get(), 77);}@@ -879,6 +984,7 @@ mod tests {.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"epoch": 42,"bundles_hash": "cafebabe",+ "bundle_config_hashes_hash": "facefeed",}))).mount(&server).await;@@ -887,6 +993,7 @@ mod tests {let snapshot = client.fetch_epoch().await.unwrap();assert_eq!(snapshot.epoch, 42);assert_eq!(snapshot.bundles_hash, "cafebabe");+ assert_eq!(snapshot.bundle_config_hashes_hash, "facefeed");}#[tokio::test]@@ -906,6 +1013,7 @@ mod tests {let snapshot = client.fetch_epoch().await.unwrap();assert_eq!(snapshot.epoch, 7);assert_eq!(snapshot.bundles_hash, "");+ assert_eq!(snapshot.bundle_config_hashes_hash, "");}#[tokio::test]@@ -1002,6 +1110,7 @@ mod tests {"raw_yaml": null,"model_config": {"sie_id": "json/model",+ "pool": "customer-a","profiles": {"default": {"adapter_path": "sie_server.adapters.sentence_transformer:Adapter",@@ -1031,6 +1140,28 @@ mod tests {);}+ #[test]+ fn parse_exported_model_preserves_pool_from_json_fallback() {+ let model = ExportedModel {+ model_id: "json/model".to_string(),+ raw_yaml: None,+ model_config: Some(serde_json::json!({+ "sie_id": "json/model",+ "pool": "customer-a",+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.sentence_transformer:Adapter",+ }+ }+ })),+ };++ let config = parse_exported_model(&model).unwrap().unwrap();+ assert_eq!(config.pool, Some("customer-a".to_string()));+ let yaml = serde_yaml::to_string(&config).unwrap();+ assert!(yaml.contains("pool: customer-a"));+ }+#[tokio::test]async fn bootstrap_skips_entry_without_config_body() {let server = MockServer::start().await;@@ -1069,7 +1200,7 @@ mod tests {}#[tokio::test]- async fn bootstrap_continues_past_malformed_entry() {+ async fn bootstrap_refuses_partial_model_install_on_malformed_entry() {let server = MockServer::start().await;let (registry, _tmp) = make_registry();mount_default_bundles(&server).await;@@ -1101,14 +1232,14 @@ mod tests {let client = BootstrapClient::new(server.uri(), None).unwrap();let outcome = client.bootstrap(registry.as_ref()).await.unwrap();- assert_eq!(outcome.applied, 1);+ assert_eq!(outcome.applied, 0);assert_eq!(outcome.failed, 1);assert_eq!(outcome.total, 2);assert!(!outcome.is_complete());assert!(registry.get_model_profile_names("broken/model").is_empty());- assert_eq!(- registry.get_model_profile_names("good/model"),- vec!["default".to_string()],+ assert!(+ registry.get_model_profile_names("good/model").is_empty(),+ "authoritative export replacement must not partially install the valid rows when one row is malformed");}@@ -1144,10 +1275,17 @@ mod tests {let epoch = ConfigEpoch::new();let bundles_hash = BundlesHash::new();+ let bundle_config_hashes_hash = BundleConfigHashesHash::new();let client = BootstrapClient::new(server.uri(), None).unwrap();- let err = bootstrap_once(&client, registry.as_ref(), &epoch, &bundles_hash)- .await- .unwrap_err();+ let err = bootstrap_once(+ &client,+ registry.as_ref(),+ &epoch,+ &bundles_hash,+ &bundle_config_hashes_hash,+ )+ .await+ .unwrap_err();match err {BootstrapError::PartialApply {epoch: snap_epoch,@@ -1169,6 +1307,7 @@ mod tests {// next tick. Storing the fresh hash here would let the poller// believe the registry is caught up despite the failure.assert_eq!(bundles_hash.get(), "");+ assert_eq!(bundle_config_hashes_hash.get(), "");}/// Two-phase fetch: list endpoint enumerates IDs, per-bundle endpointdiff --git a/packages/sie_gateway/src/state/config_poller.rs b/packages/sie_gateway/src/state/config_poller.rsindex 34cdb4efe..7d26e08d9 100644--- a/packages/sie_gateway/src/state/config_poller.rs+++ b/packages/sie_gateway/src/state/config_poller.rs@@ -8,7 +8,7 @@//!//! This poller closes that gap by periodically calling//! `GET /v1/configs/epoch` on `sie-config` and comparing the response to-//! the gateway's last-known control-plane state on TWO axes:+//! the gateway's last-known control-plane state on three axes://!//! 1. **Model epoch** (`ConfigEpoch`, monotonic counter bumped on every//! model-config write). A remote-ahead value triggers a full@@ -20,8 +20,13 @@//! a full bootstrap so the gateway picks up bundle additions or changes//! without requiring a gateway pod restart (and without depending on a//! coincidental model write to bump the epoch).+//! 3. **Bundle config hashes hash** (`BundleConfigHashesHash`, sha256+//! fingerprint of `sie-config`'s per-bundle config-hash map). A mismatch+//! triggers the same full bootstrap so a gateway cannot stay wedged with+//! stale expected hashes while healthy workers advertise the current+//! control-plane hash.//!-//! Both axes funnel into the same `bootstrap_once` call — that function+//! All axes funnel into the same `bootstrap_once` call — that function//! re-fetches bundles and models together, which is the correct blanket//! response to any control-plane drift we observe.//!@@ -34,9 +39,9 @@//! arrives over NATS and is lost in flight, we need the poller to catch//! remote=1 vs local=0 and trigger a catch-up. Gating on `local != 0`//! would wedge the gateway silently until the next restart.-//! - The epoch endpoint is a deliberately tiny payload (one integer +-//! one short hex string). It is much cheaper than `/export` and can run-//! on a short cadence without stressing `sie-config`.+//! - The epoch endpoint is a deliberately tiny payload (one integer plus+//! short fingerprints). It is much cheaper than `/export` and can run on+//! a short cadence without stressing `sie-config`.//! - Errors are logged and swallowed. A transient epoch-endpoint failure//! does not reset the local epoch or the stored bundle hash; the next//! tick retries.@@ -46,16 +51,17 @@//! poller re-runs `bootstrap_once` and, on success, force-resets the//! local counter to the remote value. Without this branch the//! `remote > local` catch-up trigger would be permanently unreachable.-//! - Empty remote `bundles_hash` means `sie-config` is in a-//! registry-degraded state (startup failure or hot reload in flight).-//! We skip the hash-mismatch branch in that case rather than thrash-//! fetching an empty bundle set.+//! - Empty remote hashes mean `sie-config` is in a registry-degraded state+//! (startup failure or hot reload in flight), or the peer is too old to+//! emit that field. We skip that hash-mismatch branch rather than thrash+//! fetching an empty control-plane view.use std::sync::Arc;use std::time::Duration;use tracing::{debug, error, info, warn};+use crate::state::bundle_config_hashes_hash::BundleConfigHashesHash;use crate::state::bundles_hash::BundlesHash;use crate::state::config_bootstrap::{bootstrap_once, BootstrapClient, BootstrapError};use crate::state::config_epoch::ConfigEpoch;@@ -73,6 +79,7 @@ pub fn spawn(registry: Arc<ModelRegistry>,config_epoch: ConfigEpoch,bundles_hash: BundlesHash,+ bundle_config_hashes_hash: BundleConfigHashesHash,interval: Duration,) -> Option<tokio::task::JoinHandle<()>> {let base = base_url?.to_string();@@ -100,6 +107,7 @@ pub fn spawn(ticker.tick().await;let local_epoch_val = config_epoch.get();let local_bundles_hash = bundles_hash.get();+ let local_bundle_config_hashes_hash = bundle_config_hashes_hash.get();let snapshot = match client.fetch_epoch().await {Ok(s) => s,Err(BootstrapError::BadStatus { status, .. }) => {@@ -114,6 +122,7 @@ pub fn spawn(let remote_epoch = snapshot.epoch;let remote_bundles_hash = snapshot.bundles_hash;+ let remote_bundle_config_hashes_hash = snapshot.bundle_config_hashes_hash;// Skip the bundle-hash comparison when sie-config reported the// empty "registry unavailable" sentinel. Treating empty as a// real change would make us thrash every tick while the control@@ -121,8 +130,10 @@ pub fn spawn(// still runs normally.let bundles_hash_drift =!remote_bundles_hash.is_empty() && remote_bundles_hash != local_bundles_hash;+ let bundle_config_hashes_hash_drift = !remote_bundle_config_hashes_hash.is_empty()+ && remote_bundle_config_hashes_hash != local_bundle_config_hashes_hash;- // Branch priority matters when both axes drift in the same+ // Branch priority matters when multiple axes drift in the same// tick (e.g. sie-config restarts with an ephemeral store: the// epoch rewinds AND the bundles_hash shifts because the// restarted instance recomputed it from the baked baseline).@@ -163,9 +174,17 @@ pub fn spawn(local_epoch = local_epoch_val,remote_epoch = remote_epoch,bundles_hash_drift,+ bundle_config_hashes_hash_drift,"local epoch is ahead of sie-config authority; re-fetching export before force-reset");- match bootstrap_once(&client, registry.as_ref(), &config_epoch, &bundles_hash).await+ match bootstrap_once(+ &client,+ registry.as_ref(),+ &config_epoch,+ &bundles_hash,+ &bundle_config_hashes_hash,+ )+ .await{Ok(_) => {// `bootstrap_once` advanced via `set_max`, which is@@ -184,20 +203,32 @@ pub fn spawn();}}- } else if remote_epoch > local_epoch_val || bundles_hash_drift {+ } else if remote_epoch > local_epoch_val+ || bundles_hash_drift+ || bundle_config_hashes_hash_drift+ {info!(local_epoch = local_epoch_val,remote_epoch = remote_epoch,bundles_hash_drift,+ bundle_config_hashes_hash_drift,reason = if remote_epoch > local_epoch_val {"epoch ahead"- } else {+ } else if bundles_hash_drift {"bundle hash changed"+ } else {+ "bundle config hashes changed"},"control-plane drift detected; re-running bootstrap");- if let Err(e) =- bootstrap_once(&client, registry.as_ref(), &config_epoch, &bundles_hash).await+ if let Err(e) = bootstrap_once(+ &client,+ registry.as_ref(),+ &config_epoch,+ &bundles_hash,+ &bundle_config_hashes_hash,+ )+ .await{warn!(error = %e, "catch-up bootstrap failed; will retry next tick");}@@ -245,7 +276,7 @@ mod tests {(registry, temp)}- async fn mount_bundles(server: &MockServer) {+ async fn mount_bundle_endpoints(server: &MockServer) {Mock::given(method("GET")).and(path("/v1/configs/bundles")).respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({@@ -265,6 +296,10 @@ mod tests {)).mount(server).await;+ }++ async fn mount_bundles(server: &MockServer) {+ mount_bundle_endpoints(server).await;Mock::given(method("GET")).and(path("/v1/configs/export")).respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({@@ -299,6 +334,7 @@ mod tests {let (registry, _tmp) = make_registry();let config_epoch = ConfigEpoch::new();let bundles_hash = BundlesHash::new();+ let bundle_config_hashes_hash = BundleConfigHashesHash::new();// Pretend a prior bootstrap recorded a different hash — the// "before the sie-config redeploy" state.bundles_hash.store("stale_hash".to_string());@@ -309,6 +345,7 @@ mod tests {Arc::clone(®istry),config_epoch.clone(),bundles_hash.clone(),+ bundle_config_hashes_hash.clone(),Duration::from_millis(50),).expect("poller should spawn");@@ -334,6 +371,75 @@ mod tests {handle.abort();}+ /// Regression for stale gateway expected-hash state: a no-store+ /// `sie-config` redeploy can rebuild filesystem baseline model configs at+ /// epoch 0 while keeping the same bundle set. Workers and sie-config then+ /// agree on a new `bundle_config_hash`, but a gateway that only watches+ /// epoch + bundle-set hash keeps routing against the old value forever.+ #[tokio::test]+ async fn bundle_config_hashes_drift_triggers_bootstrap_without_epoch_or_bundle_drift() {+ let server = MockServer::start().await;+ mount_bundle_endpoints(&server).await;+ Mock::given(method("GET"))+ .and(path("/v1/configs/epoch"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "epoch": 0,+ "bundles_hash": "same_bundle_surface",+ "bundle_config_hashes_hash": "new_config_hashes_fingerprint",+ })))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/v1/configs/export"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "snapshot_version": 1,+ "epoch": 0,+ "generated_at": "2026-04-17T00:00:00Z",+ "bundle_config_hashes": {"default": "new_control_plane_hash"},+ "models": [],+ })))+ .mount(&server)+ .await;++ let (registry, _tmp) = make_registry();+ let config_epoch = ConfigEpoch::new();+ let bundles_hash = BundlesHash::new();+ bundles_hash.store("same_bundle_surface".to_string());+ let bundle_config_hashes_hash = BundleConfigHashesHash::new();+ bundle_config_hashes_hash.store("stale_config_hashes_fingerprint".to_string());++ let handle = spawn(+ Some(&server.uri()),+ None,+ Arc::clone(®istry),+ config_epoch.clone(),+ bundles_hash.clone(),+ bundle_config_hashes_hash.clone(),+ Duration::from_millis(50),+ )+ .expect("poller should spawn");++ tokio::time::timeout(Duration::from_secs(3), async {+ loop {+ if bundle_config_hashes_hash.get() == "new_config_hashes_fingerprint" {+ return;+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await+ .expect("poller should pick up bundle-config-hashes drift within 3s");++ assert_eq!(config_epoch.get(), 0);+ assert_eq!(bundles_hash.get(), "same_bundle_surface");+ assert_eq!(+ registry.compute_bundle_config_hash("default"),+ "new_control_plane_hash"+ );++ handle.abort();+ }+/// Defense-in-depth for the ephemeral-store `sie-config` restart/// case: if `sie-config` is deployed with `config.configStore.enabled=false`/// (the Helm default), its persisted epoch file is gone after every@@ -366,6 +472,7 @@ mod tests {config_epoch.set_max(10);assert_eq!(config_epoch.get(), 10);let bundles_hash = BundlesHash::new();+ let bundle_config_hashes_hash = BundleConfigHashesHash::new();bundles_hash.store("pre_restart_hash".to_string());let handle = spawn(@@ -374,6 +481,7 @@ mod tests {Arc::clone(®istry),config_epoch.clone(),bundles_hash.clone(),+ bundle_config_hashes_hash.clone(),Duration::from_millis(50),).expect("poller should spawn");@@ -463,6 +571,7 @@ mod tests {let config_epoch = ConfigEpoch::new();config_epoch.set_max(10);let bundles_hash = BundlesHash::new();+ let bundle_config_hashes_hash = BundleConfigHashesHash::new();bundles_hash.store("pre_restart_hash".to_string());let interval = Duration::from_millis(50);@@ -472,6 +581,7 @@ mod tests {Arc::clone(®istry),config_epoch.clone(),bundles_hash.clone(),+ bundle_config_hashes_hash.clone(),interval,).expect("poller should spawn");@@ -537,6 +647,7 @@ mod tests {let (registry, _tmp) = make_registry();let config_epoch = ConfigEpoch::new();let bundles_hash = BundlesHash::new();+ let bundle_config_hashes_hash = BundleConfigHashesHash::new();bundles_hash.store("stale_hash".to_string());let handle = spawn(@@ -545,6 +656,7 @@ mod tests {Arc::clone(®istry),config_epoch.clone(),bundles_hash.clone(),+ bundle_config_hashes_hash.clone(),Duration::from_millis(50),).expect("poller should spawn");diff --git a/packages/sie_gateway/src/state/mod.rs b/packages/sie_gateway/src/state/mod.rsindex e7698625b..955c7622b 100644--- a/packages/sie_gateway/src/state/mod.rs+++ b/packages/sie_gateway/src/state/mod.rs@@ -1,3 +1,4 @@+pub mod bundle_config_hashes_hash;pub mod bundles_hash;pub mod config_bootstrap;pub mod config_epoch;diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex d561f7f3e..aac81c23c 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -66,12 +66,16 @@ impl std::error::Error for ResolveError {}/// skipped, and which bundles need to be re-broadcast to workers.pub type AddModelConfigOutcome = (Vec<String>, Vec<String>, Vec<String>);+const DEFAULT_MODEL_POOL: &str = "default";+const MAX_POOL_NAME_LEN: usize = 128;+#[derive(Debug, Clone, Default)]struct RegistrySnapshot {bundles: HashMap<String, BundleInfo>,models: HashMap<String, ModelEntry>,model_names_lower: HashMap<String, String>,bundle_config_hashes: HashMap<String, String>,+ bundle_pool_config_hashes: HashMap<(String, String), String>,}pub struct ModelRegistry {@@ -218,14 +222,10 @@ impl ModelRegistry {}// Pre-compute bundle config hashes (expensive: sort + JSON + SHA-256).- // Cached here so compute_bundle_config_hash is a simple HashMap lookup.- let mut bundle_config_hashes = HashMap::new();- for bundle_name in new_bundles.keys() {- let hash = Self::hash_bundle_config(bundle_name, &new_bundles, &new_models);- if !hash.is_empty() {- bundle_config_hashes.insert(bundle_name.clone(), hash);- }- }+ // Cached here so route/status lookups are simple HashMap reads.+ let bundle_config_hashes = Self::rebuild_bundle_config_hashes(&new_bundles, &new_models);+ let bundle_pool_config_hashes =+ Self::rebuild_bundle_pool_config_hashes(&new_bundles, &new_models);info!(bundles = new_bundles.len(),@@ -238,6 +238,7 @@ impl ModelRegistry {models: new_models,model_names_lower: new_model_names_lower,bundle_config_hashes,+ bundle_pool_config_hashes,};self.snapshot.store(Arc::new(snap));}@@ -385,6 +386,7 @@ impl ModelRegistry {}entries.push(ModelEntry {name: format!("{}:{}", base_entry.name, profile_name),+ pool: base_entry.pool.clone(),bundles: Vec::new(),adapter_modules: variant_adapters,profile_names: variant_profile_names,@@ -436,6 +438,7 @@ impl ModelRegistry {fn model_entry_from_config(config: &ModelConfig) -> Result<ModelEntry, String> {let info_extras = crate::types::model::ModelInfoExtras::from_model_config(config);let model_name = config.name.clone();+ let pool = Self::normalize_model_pool(config.pool.as_deref())?;let mut adapter_modules: HashSet<String> = HashSet::new();let mut profile_names: HashSet<String> = HashSet::new();let mut profile_configs: HashMap<String, CanonicalProfile> = HashMap::new();@@ -457,6 +460,7 @@ impl ModelRegistry {Ok(ModelEntry {name: model_name,+ pool,bundles: Vec::new(),adapter_modules,profile_names,@@ -465,6 +469,31 @@ impl ModelRegistry {})}+ fn normalize_model_pool(pool: Option<&str>) -> Result<Option<String>, String> {+ let Some(raw_pool) = pool else {+ return Ok(None);+ };+ let pool = raw_pool.trim().to_lowercase();+ if pool.is_empty() || pool == DEFAULT_MODEL_POOL {+ return Ok(None);+ }+ if pool.len() > MAX_POOL_NAME_LEN+ || pool == "_default"+ || !pool+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')+ {+ return Err(+ "Field 'pool' must match [A-Za-z0-9_-]{1,128} and must not be _default".to_string(),+ );+ }+ Ok(Some(pool))+ }++ fn entry_pool_name(entry: &ModelEntry) -> &str {+ entry.pool.as_deref().unwrap_or(DEFAULT_MODEL_POOL)+ }+fn expand_model_entry_into_profile_variants(base_entry: &ModelEntry,) -> Result<Vec<ModelEntry>, String> {@@ -502,6 +531,7 @@ impl ModelRegistry {}entries.push(ModelEntry {name: format!("{}:{}", base_entry.name, profile_name),+ pool: base_entry.pool.clone(),bundles: Vec::new(),adapter_modules: variant_adapters,profile_names: variant_profile_names,@@ -900,13 +930,9 @@ impl ModelRegistry {model_entry.bundles = matching.into_iter().map(|(_, name)| name).collect();}- let mut bundle_config_hashes = HashMap::new();- for bundle_name in new_bundles.keys() {- let hash = Self::hash_bundle_config(bundle_name, &new_bundles, &snap.models);- if !hash.is_empty() {- bundle_config_hashes.insert(bundle_name.clone(), hash);- }- }+ let bundle_config_hashes = Self::rebuild_bundle_config_hashes(&new_bundles, &snap.models);+ let bundle_pool_config_hashes =+ Self::rebuild_bundle_pool_config_hashes(&new_bundles, &snap.models);info!(bundles = new_bundles.len(),@@ -916,6 +942,7 @@ impl ModelRegistry {snap.bundles = new_bundles;snap.bundle_config_hashes = bundle_config_hashes;+ snap.bundle_pool_config_hashes = bundle_pool_config_hashes;self.snapshot.store(Arc::new(snap));}@@ -949,6 +976,13 @@ impl ModelRegistry {snap.models.get(&canonical).cloned()}+ pub fn get_model_pool_name(&self, model: &str) -> Option<String> {+ let snap = self.snapshot.load();+ let canonical = Self::canonical_model_name(&snap, model)?;+ let entry = snap.models.get(&canonical)?;+ Some(Self::entry_pool_name(entry).to_string())+ }+pub fn get_model_profile_names(&self, model: &str) -> Vec<String> {let mut profiles: Vec<String> = self.get_model_info(model)@@ -960,6 +994,7 @@ impl ModelRegistry {/// Look up pre-computed bundle config hash (O(1) HashMap get)./// Hash is computed during reload() and add_model_config(), not per-request.+ #[allow(dead_code)]pub fn compute_bundle_config_hash(&self, bundle_id: &str) -> String {let snap = self.snapshot.load();snap.bundle_config_hashes@@ -968,6 +1003,20 @@ impl ModelRegistry {.unwrap_or_default()}+ pub fn compute_bundle_config_hash_for_pool(&self, bundle_id: &str, pool_name: &str) -> String {+ let snap = self.snapshot.load();+ let pool_name = pool_name.trim().to_lowercase();+ let pool_name = if pool_name.is_empty() {+ DEFAULT_MODEL_POOL.to_string()+ } else {+ pool_name+ };+ snap.bundle_pool_config_hashes+ .get(&(bundle_id.to_string(), pool_name))+ .cloned()+ .unwrap_or_default()+ }+pub fn install_bundle_config_hashes(&self, hashes: HashMap<String, String>) {if hashes.is_empty() {return;@@ -994,11 +1043,84 @@ impl ModelRegistry {bundle_id: &str,bundles: &HashMap<String, BundleInfo>,models: &HashMap<String, ModelEntry>,+ ) -> String {+ Self::hash_bundle_config_scoped(bundle_id, bundles, models, None)+ }++ fn hash_bundle_config_for_pool(+ bundle_id: &str,+ bundles: &HashMap<String, BundleInfo>,+ models: &HashMap<String, ModelEntry>,+ pool_name: &str,+ ) -> String {+ Self::hash_bundle_config_scoped(bundle_id, bundles, models, Some(pool_name))+ }++ fn rebuild_bundle_config_hashes(+ bundles: &HashMap<String, BundleInfo>,+ models: &HashMap<String, ModelEntry>,+ ) -> HashMap<String, String> {+ let mut hashes = HashMap::new();+ for bundle_name in bundles.keys() {+ let hash = Self::hash_bundle_config(bundle_name, bundles, models);+ if !hash.is_empty() {+ hashes.insert(bundle_name.clone(), hash);+ }+ }+ hashes+ }++ fn rebuild_bundle_pool_config_hashes(+ bundles: &HashMap<String, BundleInfo>,+ models: &HashMap<String, ModelEntry>,+ ) -> HashMap<(String, String), String> {+ let mut pools_by_bundle: HashMap<String, HashSet<String>> = HashMap::new();+ for (model_name, entry) in models {+ if Self::is_synthetic_profile_variant(model_name, models) {+ continue;+ }+ let pool = Self::entry_pool_name(entry).to_string();+ for bundle in &entry.bundles {+ pools_by_bundle+ .entry(bundle.clone())+ .or_default()+ .insert(pool.clone());+ }+ }++ let mut hashes = HashMap::new();+ for (bundle_name, pools) in pools_by_bundle {+ if !bundles.contains_key(&bundle_name) {+ continue;+ }+ for pool in pools {+ let hash = Self::hash_bundle_config_for_pool(&bundle_name, bundles, models, &pool);+ if !hash.is_empty() {+ hashes.insert((bundle_name.clone(), pool), hash);+ }+ }+ }+ hashes+ }++ fn hash_bundle_config_scoped(+ bundle_id: &str,+ bundles: &HashMap<String, BundleInfo>,+ models: &HashMap<String, ModelEntry>,+ pool_name: Option<&str>,) -> String {let bundle = match bundles.get(bundle_id) {Some(b) => b,None => return String::new(),};+ let normalized_pool = pool_name.map(|p| {+ let p = p.trim().to_lowercase();+ if p.is_empty() {+ DEFAULT_MODEL_POOL.to_string()+ } else {+ p+ }+ });let bundle_adapter_set: HashSet<&str> =bundle.adapters.iter().map(|s| s.as_str()).collect();@@ -1014,6 +1136,12 @@ impl ModelRegistry {}let model_entry = &models[model_name];+ if normalized_pool+ .as_deref()+ .is_some_and(|pool| Self::entry_pool_name(model_entry) != pool)+ {+ continue;+ }if !model_entry.bundles.contains(&bundle_id.to_string()) {continue;}@@ -1098,30 +1226,12 @@ impl ModelRegistry {self.add_model_config_inner(config, false)}- /// Like `add_model_config`, but treats the caller as the authoritative- /// view of the current epoch: when a profile already exists with a- /// different `CanonicalProfile`, the stored config is **overwritten**- /// with a `warn!` log instead of returning an append-only conflict- /// error.- ///- /// This is the path the cold-start bootstrap (`state::config_bootstrap`)- /// and the epoch poller's catch-up re-export use. The append-only- /// invariant on the NATS pub/sub delta path- /// (`nats::manager::NatsManager::apply_notification`) is still enforced- /// via the plain `add_model_config`, so single-epoch duplicate publishes- /// are still caught.+ /// Test-only entry point for the per-model authoritative merge branch.///- /// Why: `sie-config` is the source of truth for the current epoch. If- /// the gateway pod started against an old `sie-config` revision and- /// cached a stale profile config (e.g. v0.3.2 had nemotron-8b on- /// `sglang`), and `sie-config` then rolled to a new revision that- /// changed that same profile (e.g. v0.3.3 swapped it for- /// `pytorch_embedding`), the next bootstrap re-fetch hits the- /// append-only check and the entire export refuses to apply (failed=1- /// blocks epoch advance), the poller retries forever, and routing wedges- /// for every model. The authoritative path heals that on the next poll- /// tick by accepting the new config as the latest word from the control- /// plane.+ /// Production full-snapshot replay uses `replace_model_configs_authoritative`+ /// so removals are applied atomically. This helper keeps the older conflict+ /// override branch covered without exposing it as a runtime API.+ #[cfg(test)]pub fn add_model_config_authoritative(&self,config: ModelConfig,@@ -1129,6 +1239,103 @@ impl ModelRegistry {self.add_model_config_inner(config, true)}+ /// Replace the model surface with the exact exported control-plane set.+ ///+ /// This is the production full-snapshot replay path: it drops models and+ /// profile variants that disappeared from `sie-config` instead of overlaying+ /// exported rows onto the existing snapshot. Use this only for+ /// `/v1/configs/export`, never for live NATS deltas.+ pub fn replace_model_configs_authoritative(+ &self,+ configs: Vec<ModelConfig>,+ ) -> Result<usize, String> {+ let _write = self+ .write_lock+ .lock()+ .expect("ModelRegistry write_lock poisoned");+ let old_snap = self.snapshot.load();+ let mut new_models: HashMap<String, ModelEntry> = HashMap::new();+ let mut new_model_names_lower: HashMap<String, String> = HashMap::new();+ let applied = configs.len();++ for config in configs {+ let sie_id = &config.name;+ if sie_id.is_empty() {+ return Err("Missing required field: name/sie_id".to_string());+ }+ if sie_id.chars().any(|c| c.is_control()) {+ return Err(format!(+ "Invalid model id: contains control character (sie_id={:?})",+ sie_id+ ));+ }+ if config.profiles.is_empty() {+ return Err("Missing required field: profiles".to_string());+ }++ let mut adapter_modules: HashSet<String> = HashSet::new();+ for (profile_name, profile) in &config.profiles {+ if let Some(adapter_path) =+ Self::effective_adapter_path_from_profiles(&config.profiles, profile_name)+ {+ if let Some(module) = Self::adapter_module_from_path(adapter_path) {+ adapter_modules.insert(module);+ }+ } else if profile.extends.is_none() {+ return Err(format!("Profile '{}' missing adapter_path", profile_name));+ }+ }++ let all_bundle_adapters: HashSet<String> = old_snap+ .bundles+ .values()+ .flat_map(|b| b.adapters.iter().cloned())+ .collect();+ let unroutable: Vec<&String> = adapter_modules+ .iter()+ .filter(|a| !all_bundle_adapters.contains(a.as_str()))+ .collect();+ if !unroutable.is_empty() {+ return Err(format!(+ "Adapter(s) not in any known bundle: {}",+ unroutable+ .iter()+ .map(|s| s.as_str())+ .collect::<Vec<_>>()+ .join(", ")+ ));+ }++ for mut entry in Self::expand_model_config_into_profile_variants(&config)? {+ Self::assign_bundles(&mut entry, &old_snap.bundles);+ new_model_names_lower.insert(entry.name.to_lowercase(), entry.name.clone());+ new_models.insert(entry.name.clone(), entry);+ }+ }++ let bundle_config_hashes =+ Self::rebuild_bundle_config_hashes(&old_snap.bundles, &new_models);+ let bundle_pool_config_hashes =+ Self::rebuild_bundle_pool_config_hashes(&old_snap.bundles, &new_models);++ info!(+ old_models = old_snap.models.len(),+ models = new_models.len(),+ bundles = old_snap.bundles.len(),+ "replaced model configs from authoritative export"+ );++ self.snapshot.store(Arc::new(RegistrySnapshot {+ bundles: old_snap.bundles.clone(),+ models: new_models,+ model_names_lower: new_model_names_lower,+ bundle_config_hashes,+ bundle_pool_config_hashes,+ }));++ Ok(applied)+ }+fn add_model_config_inner(&self,config: ModelConfig,@@ -1206,12 +1413,19 @@ impl ModelRegistry {let mut created_profiles: Vec<String> = Vec::new();let mut skipped_profiles: Vec<String> = Vec::new();let mut overridden_profiles: Vec<String> = Vec::new();+ let incoming_pool = Self::normalize_model_pool(config.pool.as_deref())?;if let Some(existing) = snap.models.get_mut(sie_id) {+ if config.pool.is_some() && existing.pool != incoming_pool {+ return Err(format!(+ "Pool on model '{}' already exists with different value (append-only)",+ sie_id+ ));+ }// Append-only by default: add new profiles, skip identical,- // reject conflicts. When `authoritative` is true (bootstrap /- // epoch-poll catch-up), a conflicting profile is OVERWRITTEN- // with a warn so the control plane's latest word wins.+ // reject conflicts. The test-only authoritative branch preserves+ // the per-model overwrite behavior that predates full-snapshot+ // replacement.//// Resolution map: a delta update can carry a profile that// ``extends`` a profile only present in ``existing.profile_configs``@@ -1243,8 +1457,7 @@ impl ModelRegistry {new_max_batch_tokens = ?incoming.max_batch_tokens,old_compute_precision = ?stored.compute_precision,new_compute_precision = ?incoming.compute_precision,- "overriding existing profile config from authoritative source (sie-config); \- likely a control-plane schema change between bootstrap and catch-up",+ "overriding existing profile config from authoritative source (sie-config)",);overridden_profiles.push(profile_name.clone());continue;@@ -1292,6 +1505,7 @@ impl ModelRegistry {sie_id.clone(),ModelEntry {name: sie_id.clone(),+ pool: incoming_pool,bundles: Vec::new(),adapter_modules: new_adapter_modules,profile_names,@@ -1350,6 +1564,8 @@ impl ModelRegistry {snap.bundle_config_hashes.insert(bundle_name.clone(), hash);}}+ snap.bundle_pool_config_hashes =+ Self::rebuild_bundle_pool_config_hashes(&snap.bundles, &snap.models);info!(model = %sie_id,@@ -1486,6 +1702,7 @@ mod tests {name: "org/x".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: None,@@ -1542,6 +1759,7 @@ mod tests {name: "org/x".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: None,@@ -1724,6 +1942,7 @@ profiles:name: "org/broken".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: None,@@ -1780,6 +1999,7 @@ profiles:name: name.clone(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: None,@@ -2030,6 +2250,7 @@ adapters:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles: {let mut m = HashMap::new();m.insert(@@ -2094,6 +2315,7 @@ adapters:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: Some(512),@@ -2142,6 +2364,7 @@ encode:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: Some(1024),@@ -2197,6 +2420,7 @@ adapters:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: Some(512),@@ -2240,6 +2464,7 @@ encode:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles,inputs: None,max_sequence_length: None,@@ -2262,6 +2487,7 @@ encode:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles: {let mut m = HashMap::new();m.insert(@@ -2327,12 +2553,10 @@ adapters:);}- /// The authoritative path is what `state::config_bootstrap` uses on- /// cold-start and on epoch-poller catch-up. It treats the export as- /// the source of truth and overrides any divergent stored profile- /// config (with a warn log) instead of failing the entire bootstrap.- /// Reproduces the `nemotron-8b` adapter swap that wedged sie-test- /// until a manual gateway restart.+ /// The test-only authoritative merge path preserves the old per-model+ /// conflict override behavior. Production export replay now uses+ /// `replace_model_configs_authoritative`, but this still guards the shared+ /// merge code for divergent stored profiles.#[test]fn test_add_model_config_authoritative_overrides_conflicting_profile() {let (_dir, bundles_dir, models_dir) = create_test_dirs();@@ -2418,6 +2642,7 @@ adapters:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles: {let mut m = HashMap::new();m.insert(@@ -2442,8 +2667,8 @@ adapters:.expect("delta apply must resolve extends against existing.profile_configs");assert_eq!(created, vec!["a100-40gb".to_string()]);- // Same delta under the authoritative path must also succeed (the- // override path uses the same merged resolution map).+ // Same delta under the test-only authoritative path must also succeed+ // because the override path uses the same merged resolution map.registry.add_model_config_authoritative(delta).expect("authoritative replay of the same delta must also resolve cleanly");@@ -2477,6 +2702,7 @@ adapters:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles: {let mut m = HashMap::new();m.insert(@@ -2533,6 +2759,7 @@ adapters:name: "test/model".to_string(),adapter_module: None,default_bundle: None,+ pool: None,profiles: {let mut m = HashMap::new();m.insert(@@ -2680,6 +2907,67 @@ profiles:assert!(empty.is_empty());}+ #[test]+ fn test_compute_bundle_config_hash_for_pool_filters_model_pool() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();++ fs::write(+ bundles_dir.join("default.yaml"),+ r#"+name: default+priority: 10+adapters:+ - sie_server.adapters.sentence_transformer+"#,+ )+ .unwrap();++ fs::write(+ models_dir.join("default.yaml"),+ r#"+name: default/model+profiles:+ default:+ adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"+ max_batch_tokens: 4096+"#,+ )+ .unwrap();++ fs::write(+ models_dir.join("tenant.yaml"),+ r#"+name: tenant/model+pool: customer-a+profiles:+ default:+ adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"+ max_batch_tokens: 4096+"#,+ )+ .unwrap();++ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let global_hash = registry.compute_bundle_config_hash("default");+ let default_hash = registry.compute_bundle_config_hash_for_pool("default", "default");+ let tenant_hash = registry.compute_bundle_config_hash_for_pool("default", "customer-a");++ assert_eq!(+ registry.get_model_pool_name("tenant/model").as_deref(),+ Some("customer-a")+ );+ assert!(!global_hash.is_empty());+ assert!(!default_hash.is_empty());+ assert!(!tenant_hash.is_empty());+ assert_ne!(global_hash, default_hash);+ assert_ne!(global_hash, tenant_hash);+ assert_ne!(default_hash, tenant_hash);+ assert_eq!(+ registry.compute_bundle_config_hash_for_pool("default", "missing"),+ ""+ );+ }+#[test]fn test_compute_bundle_config_hash_ignores_profile_variant_aliases() {let (_dir, bundles_dir, models_dir) = create_test_dirs();@@ -2800,6 +3088,7 @@ adapters:name: format!("race/model-{i}"),adapter_module: None,default_bundle: None,+ pool: None,profiles: {let mut m = HashMap::new();m.insert(diff --git a/packages/sie_gateway/src/state/pool_manager.rs b/packages/sie_gateway/src/state/pool_manager.rsindex aa40f885e..6755b589e 100644--- a/packages/sie_gateway/src/state/pool_manager.rs+++ b/packages/sie_gateway/src/state/pool_manager.rs@@ -76,6 +76,23 @@ impl std::fmt::Display for InvalidMachineProfileError {impl std::error::Error for InvalidMachineProfileError {}+#[derive(Debug)]+pub struct InvalidPoolNameError {+ pub name: String,+}++impl std::fmt::Display for InvalidPoolNameError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "Invalid pool name '{}': only [A-Za-z0-9_-] are allowed (max 128 chars)",+ self.name+ )+ }+}++impl std::error::Error for InvalidPoolNameError {}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct PoolAdmissionStatus {pub cap: u32,@@ -120,14 +137,19 @@ impl PoolManager {let static_pool_names = self.static_pool_names.read().await.clone();let mut pools = self.pools.write().await;let mut count = 0;- for pool in k8s_pools {+ for mut pool in k8s_pools {if !Self::should_restore_pool_from_k8s(&pool) {continue;}+ if let Err(e) = validate_pool_name(&pool.spec.name) {+ warn!(pool = %pool.spec.name, error = %e, "skipping invalid pool from K8s restore");+ continue;+ }+ pool.spec.name = normalize_pool_name(&pool.spec.name);if static_pool_names.contains(&normalize_pool_name(&pool.spec.name)) {continue;}- if !pools.contains_key(&pool.spec.name) {+ if pool_key_for_name(&pools, &pool.spec.name).is_none() {info!(pool = %pool.spec.name, "restored pool from K8s");pools.insert(pool.spec.name.clone(), pool);count += 1;@@ -137,7 +159,7 @@ impl PoolManager {}fn should_restore_pool_from_k8s(pool: &Pool) -> bool {- pool.spec.name != DEFAULT_POOL_NAME+ !pool.spec.name.eq_ignore_ascii_case(DEFAULT_POOL_NAME)}fn now_secs() -> f64 {@@ -215,6 +237,7 @@ impl PoolManager {let mut normalized_specs = Vec::new();let mut desired_names = HashSet::new();for spec in specs {+ validate_pool_name(&spec.name)?;let name = normalize_pool_name(&spec.name);if name.is_empty() || name == DEFAULT_POOL_NAME {continue;@@ -391,27 +414,37 @@ impl PoolManager {ttl_seconds: Option<u64>,minimum_worker_count: u32,) -> Result<Pool, Box<dyn std::error::Error + Send + Sync>> {+ let raw_name = name;+ validate_pool_name(name)?;+ let name = normalize_pool_name(name);+ if name == DEFAULT_POOL_NAME && raw_name != DEFAULT_POOL_NAME {+ return Err(Box::new(DefaultPoolMutationError));+ }let gpus = Self::normalize_gpus_and_caps(gpus, &gpu_caps);self.validate_pool_profiles(&gpus, &gpu_caps)?;- let is_static_pool = self.is_static_pool(name).await;+ let is_static_pool = self.is_static_pool(&name).await;if is_static_pool {return Err(Box::new(StaticPoolMutationError {- name: name.to_string(),+ name: raw_name.to_string(),}));}let now = Self::now_secs();let mut pools = self.pools.write().await;- // Idempotent: return existing pool if found- if let Some(existing) = pools.get_mut(name) {+ // Idempotent: return/update the existing pool, including+ // case-variant requests for the same logical pool name.+ if let Some(pool_key) = pool_key_for_name(&pools, &name) {+ let existing = pools+ .get_mut(&pool_key)+ .expect("pool key resolved from the same map");let spec_changed = existing.spec.bundle != bundle|| existing.spec.gpus != gpus|| existing.spec.gpu_caps != gpu_caps|| existing.spec.ttl_seconds != ttl_seconds|| existing.spec.minimum_worker_count != minimum_worker_count;- if name == DEFAULT_POOL_NAME && spec_changed {+ if pool_key.eq_ignore_ascii_case(DEFAULT_POOL_NAME) && spec_changed {return Err(Box::new(DefaultPoolMutationError));}@@ -433,16 +466,16 @@ impl PoolManager {// Persist spec updates and renew the K8s Lease (best-effort,// skip default pool).- if name != DEFAULT_POOL_NAME {+ if !pool_key.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {if let Some(ref backend) = self.k8s_backend {if spec_changed {if let Err(e) = backend.save_pool(&result).await {- warn!(error = %e, pool = name, "failed to persist pool update to K8s");+ warn!(error = %e, pool = %pool_key, "failed to persist pool update to K8s");}}let ttl = Self::lease_ttl_seconds(&result);- if let Err(e) = backend.create_or_renew_lease(name, ttl).await {- warn!(error = %e, pool = name, "failed to renew K8s Lease");+ if let Err(e) = backend.create_or_renew_lease(&pool_key, ttl).await {+ warn!(error = %e, pool = %pool_key, "failed to renew K8s Lease");}}}@@ -455,7 +488,7 @@ impl PoolManager {let pool = Pool {spec: PoolSpec {- name: name.to_string(),+ name: name.clone(),bundle,gpus,gpu_caps,@@ -470,23 +503,23 @@ impl PoolManager {},};- pools.insert(name.to_string(), pool.clone());+ pools.insert(name.clone(), pool.clone());drop(pools); // release write lock before K8s call- info!(pool = name, "created pool");+ info!(pool = %name, "created pool");crate::metrics::POOL_EVENTS.with_label_values(&["created"]).inc();// Persist dynamic named pools to K8s. The default pool is synthetic// per gateway replica and is not a lease-owned runtime pool.- if name != DEFAULT_POOL_NAME {+ if !name.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {if let Some(ref backend) = self.k8s_backend {if let Err(e) = backend.save_pool(&pool).await {- warn!(error = %e, pool = name, "failed to persist pool to K8s");+ warn!(error = %e, pool = %name, "failed to persist pool to K8s");}let ttl = Self::lease_ttl_seconds(&pool);- if let Err(e) = backend.create_or_renew_lease(name, ttl).await {- warn!(error = %e, pool = name, "failed to create K8s Lease");+ if let Err(e) = backend.create_or_renew_lease(&name, ttl).await {+ warn!(error = %e, pool = %name, "failed to create K8s Lease");}}}@@ -612,7 +645,7 @@ impl PoolManager {}pub async fn delete_pool(&self, name: &str) -> Result<bool, PoolDeletionProtectedError> {- if name == DEFAULT_POOL_NAME {+ if name.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {return Err(PoolDeletionProtectedError::Default);}if self.is_static_pool(name).await {@@ -660,7 +693,7 @@ impl PoolManager {// Renew the K8s Lease (best-effort, skip default and static Helm pools)if let Some(key) = found_key.as_ref() {if let Some(ref backend) = self.k8s_backend {- if key != DEFAULT_POOL_NAME && !is_static_pool {+ if !key.eq_ignore_ascii_case(DEFAULT_POOL_NAME) && !is_static_pool {if let Err(e) = backend.renew_lease(key).await {warn!(error = %e, pool = %key, "failed to renew K8s Lease");}@@ -751,7 +784,7 @@ impl PoolManager {}}- let state = if pool_key == DEFAULT_POOL_NAME {+ let state = if pool_key.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {if assigned.is_empty() {PoolState::Pending} else {@@ -773,7 +806,7 @@ impl PoolManager {let backend = self.k8s_backend.clone();drop(pools);- if status_changed && pool_key != DEFAULT_POOL_NAME && !is_static_pool {+ if status_changed && !pool_key.eq_ignore_ascii_case(DEFAULT_POOL_NAME) && !is_static_pool {if let Some(ref backend) = backend {if let Err(e) = backend.update_pool_status(&pool_key, &new_status).await {warn!(error = %e, pool = %pool_key, "failed to persist pool assignment status to K8s");@@ -804,19 +837,29 @@ impl PoolManager {/// keep `last_renewed` unchanged, because assignment changes should not/// extend the pool lease./// Does NOT write back to K8s (the event already came from K8s).- pub async fn apply_remote_pool(&self, pool: Pool) {- let name = pool.spec.name.clone();+ pub async fn apply_remote_pool(&self, mut pool: Pool) {+ let raw_name = pool.spec.name.clone();// Skip the default pool -- each gateway manages its own default pool- if name == DEFAULT_POOL_NAME {+ if raw_name.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {return;}+ if let Err(e) = validate_pool_name(&raw_name) {+ warn!(pool = %raw_name, error = %e, "skipping invalid pool from K8s watch");+ return;+ }+ let name = normalize_pool_name(&raw_name);+ pool.spec.name = name.clone();if self.is_static_pool(&name).await {return;}let mut pools = self.pools.write().await;- if let Some(existing) = pools.get(&name) {+ let pool_key = pool_key_for_name(&pools, &name);+ if let Some(existing_key) = pool_key.as_ref() {+ let existing = pools+ .get(existing_key)+ .expect("pool key resolved from the same map");let renewed_delta = pool.status.last_renewed - existing.status.last_renewed;if renewed_delta < -TIMESTAMP_TOLERANCE_S {return;@@ -830,6 +873,10 @@ impl PoolManager {return;}}++ if existing_key != &name {+ pools.remove(existing_key);+ }}info!(pool = %name, "applied remote pool from K8s watch");@@ -840,7 +887,7 @@ impl PoolManager {/// Does NOT write back to K8s (the event already came from K8s).pub async fn remove_remote_pool(&self, name: &str) {// Never delete the default pool via watch events- if name == DEFAULT_POOL_NAME {+ if name.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {return;}if self.is_static_pool(name).await {@@ -848,8 +895,9 @@ impl PoolManager {}let mut pools = self.pools.write().await;- if pools.remove(name).is_some() {- info!(pool = %name, "removed remote pool via K8s watch");+ if let Some(key) = pool_key_for_name(&pools, name) {+ pools.remove(&key);+ info!(pool = %key, "removed remote pool via K8s watch");}}@@ -861,7 +909,7 @@ impl PoolManager {{let pools = self.pools.read().await;for (name, pool) in pools.iter() {- if name == DEFAULT_POOL_NAME+ if name.eq_ignore_ascii_case(DEFAULT_POOL_NAME)|| static_pool_names.contains(&normalize_pool_name(name)){continue;@@ -883,7 +931,7 @@ impl PoolManager {match backend.list_expired_leases().await {Ok(k8s_expired) => {for name in k8s_expired {- if name == DEFAULT_POOL_NAME+ if name.eq_ignore_ascii_case(DEFAULT_POOL_NAME)|| expired.contains(&name)|| static_pool_names.contains(&normalize_pool_name(&name)){@@ -946,10 +994,26 @@ fn worker_consumes_pool(worker_pool: &str, pool_name: &str) -> bool {normalize_pool_name(worker_pool) == normalize_pool_name(pool_name)}-fn normalize_pool_name(name: &str) -> String {+pub(crate) fn normalize_pool_name(name: &str) -> String {name.trim().to_ascii_lowercase()}+fn validate_pool_name(name: &str) -> Result<(), InvalidPoolNameError> {+ if !name.is_empty()+ && name.len() <= 128+ && !name.eq_ignore_ascii_case("_default")+ && name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))+ {+ Ok(())+ } else {+ Err(InvalidPoolNameError {+ name: name.to_string(),+ })+ }+}+fn pool_key_for_name(pools: &HashMap<String, Pool>, name: &str) -> Option<String> {if pools.contains_key(name) {return Some(name.to_string());@@ -990,6 +1054,24 @@ mod tests {)}+ #[test]+ fn test_validate_pool_name_matches_route_contract() {+ for name in ["default", "customer-acme", "bench_1", "A100Pool"] {+ validate_pool_name(name).unwrap();+ }++ for name in ["", "foo.bar", "foo*", "foo>", "foo bar", " foo", "_default"] {+ assert!(validate_pool_name(name).is_err(), "{name:?} should fail");+ }+ assert!(validate_pool_name(&"a".repeat(129)).is_err());+ validate_pool_name(&"a".repeat(128)).unwrap();+ }++ #[test]+ fn test_normalize_pool_name_canonicalizes_case() {+ assert_eq!(normalize_pool_name("Customer-Acme"), "customer-acme");+ }+#[tokio::test]async fn test_create_pool() {let pm = PoolManager::new(vec!["l4-spot".to_string()]);@@ -1062,6 +1144,65 @@ mod tests {assert!(result.is_err());}+ #[tokio::test]+ async fn test_create_pool_rejects_invalid_pool_names() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);++ for name in ["", "bench.l4", "bench*", "bench>", "bench pool", "_default"] {+ let mut gpus = HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ let result = pm.create_pool(name, gpus, None, None, 0).await;+ assert!(result.is_err(), "{name:?} should fail");+ assert!(result+ .unwrap_err()+ .to_string()+ .contains("Invalid pool name"));+ }+ }++ #[tokio::test]+ async fn test_create_pool_rejects_default_case_variant() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);+ pm.create_default_pool().await;++ let mut gpus = HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ let result = pm.create_pool("Default", gpus, None, None, 0).await;++ assert!(result.is_err());+ assert!(result.unwrap_err().to_string().contains("default pool"));+ let pools = pm.list_pools().await;+ assert_eq!(pools.len(), 1);+ assert_eq!(pools[0].spec.name, DEFAULT_POOL_NAME);++ let idempotent_case_variant = pm+ .create_pool("Default", HashMap::new(), None, None, 0)+ .await;+ assert!(idempotent_case_variant.is_err());+ }++ #[tokio::test]+ async fn test_create_pool_updates_case_variant_dynamic_pool() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);++ let mut gpus = HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ pm.create_pool("Bench", gpus, None, None, 0).await.unwrap();++ let mut updated_gpus = HashMap::new();+ updated_gpus.insert("l4-spot".to_string(), 2);+ let pool = pm+ .create_pool("bench", updated_gpus, None, Some(60), 0)+ .await+ .unwrap();++ assert_eq!(pool.spec.name, "bench");+ assert_eq!(pool.spec.gpus.get("l4-spot"), Some(&2));+ assert_eq!(pool.spec.ttl_seconds, Some(60));+ let pools = pm.list_pools().await;+ assert_eq!(pools.len(), 1);+ }+#[tokio::test]async fn test_delete_default_pool_fails() {let pm = PoolManager::new(vec!["l4-spot".to_string()]);@@ -1069,6 +1210,9 @@ mod tests {let result = pm.delete_pool(DEFAULT_POOL_NAME).await;assert!(result.is_err());++ let case_variant = pm.delete_pool("Default").await;+ assert!(case_variant.is_err());}#[tokio::test]@@ -1230,6 +1374,28 @@ mod tests {assert!(pm.renew_pool("BENCH").await);}+ #[tokio::test]+ async fn test_static_pool_rejects_invalid_name() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);++ let specs = vec![PoolSpec {+ name: " bench".to_string(),+ bundle: None,+ gpus: HashMap::from([("l4-spot".to_string(), 0)]),+ gpu_caps: HashMap::new(),+ ttl_seconds: None,+ minimum_worker_count: 0,+ }];++ let result = pm.sync_static_pools(&specs).await;+ assert!(result.is_err());+ assert!(result+ .unwrap_err()+ .to_string()+ .contains("Invalid pool name"));+ assert!(pm.list_pools().await.is_empty());+ }+#[tokio::test]async fn test_static_pool_rejects_duplicate_case_variants() {let pm = PoolManager::new(vec!["l4-spot".to_string()]);@@ -1928,6 +2094,10 @@ mod tests {};assert!(!PoolManager::should_restore_pool_from_k8s(&pool));++ let mut case_variant = pool;+ case_variant.spec.name = "Default".to_string();+ assert!(!PoolManager::should_restore_pool_from_k8s(&case_variant));}#[tokio::test]@@ -2042,6 +2212,57 @@ mod tests {assert_eq!(found.status.state, PoolState::Pending);}+ #[tokio::test]+ async fn test_apply_remote_pool_case_variant_updates_existing_logical_pool() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);++ let mut gpus = HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ let local = pm+ .create_pool("Bench", gpus, None, Some(60), 0)+ .await+ .unwrap();++ let mut remote = local.clone();+ remote.spec.name = "bench".to_string();+ remote.spec.ttl_seconds = Some(120);+ remote.status.last_renewed += 1.0;++ pm.apply_remote_pool(remote).await;++ let pools = pm.list_pools().await;+ assert_eq!(pools.len(), 1);+ let found = pm.get_pool("Bench").await.unwrap();+ assert_eq!(found.spec.name, "bench");+ assert_eq!(found.spec.ttl_seconds, Some(120));+ }++ #[tokio::test]+ async fn test_apply_remote_pool_skips_invalid_pool_name() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);++ let remote = Pool {+ spec: PoolSpec {+ name: "bench.l4".to_string(),+ bundle: None,+ gpus: HashMap::from([("l4-spot".to_string(), 1)]),+ gpu_caps: HashMap::new(),+ ttl_seconds: Some(60),+ minimum_worker_count: 0,+ },+ status: PoolStatus {+ state: PoolState::Pending,+ assigned_workers: Vec::new(),+ created_at: 1000.0,+ last_renewed: 1000.0,+ },+ };++ pm.apply_remote_pool(remote).await;++ assert!(pm.list_pools().await.is_empty());+ }+#[tokio::test]async fn test_remove_remote_pool_skips_default() {let pm = PoolManager::new(vec!["l4-spot".to_string()]);@@ -2052,6 +2273,21 @@ mod tests {assert!(pm.get_pool(DEFAULT_POOL_NAME).await.is_some());}+ #[tokio::test]+ async fn test_remove_remote_pool_case_variant_removes_existing_logical_pool() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);++ let mut gpus = HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ pm.create_pool("Bench", gpus, None, Some(60), 0)+ .await+ .unwrap();++ pm.remove_remote_pool("bench").await;++ assert!(pm.get_pool("Bench").await.is_none());+ }+#[tokio::test]async fn test_remove_remote_pool_nonexistent() {let pm = PoolManager::new(vec![]);diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rsindex 5f5b1fcbf..23210dc78 100644--- a/packages/sie_gateway/src/state/worker_registry.rs+++ b/packages/sie_gateway/src/state/worker_registry.rs@@ -7,6 +7,7 @@ use arc_swap::ArcSwap;use tokio::sync::RwLock;use crate::routing::hrw::RingSnapshot;+use crate::state::pool_manager::normalize_pool_name;use crate::types::{ClusterStatus, ModelInfo, WorkerHealth, WorkerInfo, WorkerState, WorkerStatusMessage,};@@ -625,7 +626,7 @@ impl WorkerRegistry {continue;}return Some(QueueRoute {- pool_name: w.pool_name.clone(),+ pool_name: normalize_pool_name(&w.pool_name),machine_profile: w.machine_profile.clone(),});}@@ -1420,6 +1421,21 @@ mod tests {assert_eq!(pool, Some("pool-a".to_string()));}+ #[tokio::test]+ async fn test_resolve_queue_pool_canonicalizes_worker_pool_case() {+ let reg = registry();+ let mut msg = make_msg(true);+ msg.pool_name = "Customer-Acme".into();+ msg.bundle = "default".into();+ msg.machine_profile = "l4-spot".into();+ reg.update_worker("http://w1:8080", msg).await;++ let pool = reg+ .resolve_queue_pool_in_pool("default", "l4-spot", "customer-acme", "")+ .await;+ assert_eq!(pool, Some("customer-acme".to_string()));+ }+#[tokio::test]async fn test_resolve_queue_pool_in_pool_filters_pool_name() {let reg = registry();diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex 4377b5ab0..c86f202d3 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -294,6 +294,8 @@ pub struct ModelConfig {#[serde(default)]pub default_bundle: Option<String>,#[serde(default)]+ pub pool: Option<String>,+ #[serde(default)]pub profiles: HashMap<String, ProfileConfig>,/// Model YAML ``inputs:`` map (e.g. ``text: true``).#[serde(default)]@@ -322,6 +324,7 @@ pub struct ProfileConfig {#[derive(Debug, Clone)]pub struct ModelEntry {pub name: String,+ pub pool: Option<String>,pub bundles: Vec<String>,pub adapter_modules: HashSet<String>,pub profile_names: HashSet<String>,@@ -583,9 +586,11 @@ profiles:default:adapter_path: "module:Adapter"max_batch_tokens: 4096+pool: customer-a"#;let config: ModelConfig = serde_yaml::from_str(yaml).unwrap();assert_eq!(config.name, "BAAI/bge-m3");+ assert_eq!(config.pool, Some("customer-a".into()));assert_eq!(config.profiles.len(), 1);assert_eq!(config.profiles["default"].adapter_path,@@ -609,6 +614,7 @@ profiles: {}name: "test/model".into(),adapter_module: Some("mod".into()),default_bundle: None,+ pool: Some("customer-a".into()),profiles: HashMap::new(),inputs: None,max_sequence_length: None,@@ -618,6 +624,7 @@ profiles: {}let back: ModelConfig = serde_json::from_str(&json).unwrap();assert_eq!(back.name, "test/model");assert_eq!(back.adapter_module, Some("mod".into()));+ assert_eq!(back.pool, Some("customer-a".into()));}#[test]@@ -914,6 +921,7 @@ tasks:let info_extras = ModelInfoExtras::from_yaml_raw(&raw);let entry = ModelEntry {name: "Qwen/Qwen3-4B-Instruct-2507".to_string(),+ pool: None,bundles: Vec::new(),adapter_modules: HashSet::new(),profile_names: HashSet::new(),@@ -1030,6 +1038,7 @@ profiles:let info_extras = ModelInfoExtras::from_yaml_raw(&raw);let entry = ModelEntry {name: "acme/multi-profile-lora".to_string(),+ pool: None,bundles: Vec::new(),adapter_modules: HashSet::new(),profile_names: ["default".to_string(), "a100".to_string()]@@ -1083,6 +1092,7 @@ profiles:let info_extras = ModelInfoExtras::from_yaml_raw(&raw);let entry = ModelEntry {name: "acme/multi-profile-lora".to_string(),+ pool: None,bundles: Vec::new(),adapter_modules: HashSet::new(),profile_names: ["default".to_string(), "a100".to_string()]diff --git a/packages/sie_gateway/src/types/worker.rs b/packages/sie_gateway/src/types/worker.rsindex 395cfccfc..bafaa2fe5 100644--- a/packages/sie_gateway/src/types/worker.rs+++ b/packages/sie_gateway/src/types/worker.rs@@ -111,17 +111,6 @@ pub struct MachineProfile {pub spot: bool,}-#[allow(dead_code)]-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ProvisioningResponse {- pub status: String,- #[serde(default, skip_serializing_if = "String::is_empty")]- pub gpu: String,- pub estimated_wait_s: i32,- #[serde(default, skip_serializing_if = "String::is_empty")]- pub message: String,-}-#[derive(Debug, Clone, Serialize, Deserialize)]pub struct AuditEntry {pub event: String,diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex b7683ac6f..a25d83b4b 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.4"+version = "0.6.5"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_sdk/src/sie_sdk/bundle_utils.py b/packages/sie_sdk/src/sie_sdk/bundle_utils.pyindex 459182ff2..1cf67dff3 100644--- a/packages/sie_sdk/src/sie_sdk/bundle_utils.py+++ b/packages/sie_sdk/src/sie_sdk/bundle_utils.py@@ -37,8 +37,9 @@ def _scan_model_adapters(models_dir: Path) -> dict[str, tuple[set[str], str | Noif module_path:modules.add(module_path)if modules:- pool = model_data.get("pool")- result[model_name] = (modules, pool if isinstance(pool, str) else None)+ raw_pool = model_data.get("pool")+ pool = raw_pool.strip().lower() if isinstance(raw_pool, str) else None+ result[model_name] = (modules, pool or None)return result@@ -66,8 +67,9 @@ def match_bundle_models(bundle_path: Path, models_dir: Path, *, pool_name: str |model_adapters = _scan_model_adapters(models_dir)matches: list[str] = []+ normalized_pool_name = pool_name.strip().lower() if pool_name is not None else Nonefor name, (modules, pool) in model_adapters.items():- if pool_name is not None and (pool or "default") != pool_name:+ if normalized_pool_name is not None and (pool or "default") != normalized_pool_name:continueif modules & adapter_modules:matches.append(name)@@ -108,9 +110,10 @@ def find_bundle_for_models(# Collect adapter modules needed by the requested modelsmodel_adapters = _scan_model_adapters(models_dir)needed_adapters: set[str] = set()+ normalized_pool_name = pool_name.strip().lower() if pool_name is not None else Nonefor name in model_names:modules, pool = model_adapters.get(name, (set(), None))- if pool_name is not None and (pool or "default") != pool_name:+ if normalized_pool_name is not None and (pool or "default") != normalized_pool_name:continueneeded_adapters |= modulesdiff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex fd2e24d5f..72e7f1a93 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -17,6 +17,8 @@ from typing import Any, Protocolimport msgpackimport numpy as np+from sie_sdk.images import convert_item_images+_logger = logging.getLogger(__name__)@@ -59,7 +61,6 @@ MSGPACK_CONTENT_TYPE = "application/msgpack"JSON_CONTENT_TYPE = "application/json"# HTTP status code thresholds-HTTP_ACCEPTED = 202HTTP_CLIENT_ERROR = 400HTTP_SERVER_ERROR = 500HTTP_SERVICE_UNAVAILABLE = 503@@ -81,6 +82,8 @@ LORA_LOADING_ERROR_CODE = "LORA_LOADING" # Error code from serverMODEL_LOADING_MAX_RETRIES = 60 # Max retries (60 * 5s = 5 min, matches provision timeout)MODEL_LOADING_DEFAULT_DELAY_S = 5.0 # Default retry delay (model loads take longer than LoRA)MODEL_LOADING_ERROR_CODE = "MODEL_LOADING" # Error code from server+PROVISIONING_ERROR_CODE = "PROVISIONING" # Gateway scale-from-zero / worker provisioning+SIE_ERROR_CODE_HEADER = "X-SIE-Error-Code"# Terminal load failure (non-retryable). Server returns this with HTTP 502# and *no* Retry-After header so the SDK can short-circuit immediately@@ -118,6 +121,16 @@ RETRY_JITTER_FRACTION = 0.25_retry_rng = random.Random() # noqa: S311 — non-cryptographic jitter only+def convert_score_images_for_wire(query: Any, items: Sequence[Any]) -> tuple[Any, list[Any]]:+ """Convert image-bearing score query/items to the SDK image wire shape."""+ query_for_wire = convert_item_images({**query}) if "images" in query else query+ items_for_wire = [+ convert_item_images({**item}) if "images" in item else item # ty: ignore[invalid-argument-type]+ for item in items+ ]+ return query_for_wire, items_for_wire++def apply_jitter(delay: float, *, rng: random.Random | None = None) -> float:"""Apply bounded downward jitter to a backoff ``delay``.@@ -322,6 +335,11 @@ def get_retry_after(response: _HttpResponse) -> float | None:return value+def retry_after_or_default(retry_after: float | None, default: float) -> float:+ """Return a parsed ``Retry-After`` hint, preserving explicit zero."""+ return retry_after if retry_after is not None else default++def compute_oom_backoff(retry_after: float | None,attempt: int,@@ -387,6 +405,19 @@ def compute_oom_backoff(return apply_jitter(capped, rng=rng)+def _header_value(headers: Any, name: str) -> Any:+ value = headers.get(name)+ if value is None:+ value = headers.get(name.lower())+ return value+++def normalize_error_code(code: str | None) -> str | None:+ if code == "provisioning":+ return PROVISIONING_ERROR_CODE+ return code++def get_error_code(response: _HttpResponse) -> str | None:"""Extract error code from response body.@@ -396,11 +427,15 @@ def get_error_code(response: _HttpResponse) -> str | None:Returns:Error code string, or None if not found."""+ header_code = _header_value(response.headers, SIE_ERROR_CODE_HEADER)+ if isinstance(header_code, str) and header_code:+ return header_code+detail = get_error_detail(response)if detail is None:return Nonecode = detail.get("code")- return code if isinstance(code, str) else None+ return normalize_error_code(code) if isinstance(code, str) else Nonedef get_error_detail(response: _HttpResponse) -> dict[str, Any] | None:@@ -547,8 +582,16 @@ def handle_error(response: _HttpResponse) -> None:# Fall back to raw textmessage = response.text or message+ header_code = _header_value(response.headers, SIE_ERROR_CODE_HEADER)+ if isinstance(header_code, str) and header_code:+ code = header_code+ else:+ code = normalize_error_code(code)+# Fallback dispatch — ``model`` is only attached by the helper-style# short-circuit (``raise_if_input_too_long``) on the extract path.+ if response.status_code == HTTP_SERVICE_UNAVAILABLE and code == PROVISIONING_ERROR_CODE:+ raise ProvisioningError(message, retry_after=get_retry_after(response))if response.status_code == HTTP_CLIENT_ERROR and code == INPUT_TOO_LONG_ERROR_CODE:raise InputTooLongError(message)if response.status_code >= HTTP_SERVER_ERROR:@@ -556,6 +599,29 @@ def handle_error(response: _HttpResponse) -> None:raise RequestError(message, code=code, status_code=response.status_code)+def provisioning_retry_delay(+ response: _HttpResponse,+ *,+ gpu: str | None,+ wait_for_capacity: bool,+ start_time: float,+ timeout: float,+) -> float:+ """Return a retry delay for ``503 PROVISIONING`` or raise ``ProvisioningError``."""+ retry_after = get_retry_after(response)+ if not wait_for_capacity:+ msg = f"No capacity available for GPU '{gpu}'. Server is provisioning."+ raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after)+ elapsed = time.monotonic() - start_time+ if elapsed >= timeout:+ msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{gpu}'"+ raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after)+ remaining = timeout - elapsed+ if retry_after is not None:+ return min(retry_after, remaining)+ return apply_jitter(min(DEFAULT_RETRY_DELAY_S, remaining))++def next_stream_retry_delay(response: _HttpResponse,*,@@ -576,25 +642,15 @@ def next_stream_retry_delay(body must already be available so :func:`get_error_code` can inspect it.Returns ``(delay_seconds, new_oom_retries)`` to sleep-then-retry, or- raises a terminal error. Only pre-execution signals are retried- (202 provisioning, 503 MODEL_LOADING / RESOURCE_EXHAUSTED, generic 503- under ``wait_for_capacity``); a 504 and any other error are terminal —+ raises a terminal error. Only explicit pre-execution signals are retried+ (503 PROVISIONING / MODEL_LOADING / RESOURCE_EXHAUSTED); a 504 and any+ other error are terminal —streaming generation is non-idempotent, so a post-publish retry coulddouble-bill."""elapsed = time.monotonic() - start_timestatus = response.status_code- if status == HTTP_ACCEPTED:- retry_after = get_retry_after(response)- if not wait_for_capacity:- msg = f"No capacity available for GPU '{gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after)- if elapsed >= timeout:- msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{gpu}'"- raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after)- return min(retry_after or DEFAULT_RETRY_DELAY_S, timeout - elapsed), oom_retries-# Non-retryable load failure / oversized input short-circuits (these# read the buffered body and raise their own typed errors).raise_if_model_load_failed(response, model=model)@@ -602,11 +658,21 @@ def next_stream_retry_delay(if status == HTTP_SERVICE_UNAVAILABLE:code = get_error_code(response)+ if code == PROVISIONING_ERROR_CODE:+ delay = provisioning_retry_delay(+ response,+ gpu=gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ )+ return delay, oom_retriesif code == MODEL_LOADING_ERROR_CODE:if elapsed >= timeout:msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"raise ModelLoadingError(msg, model=model)- delay = get_retry_after(response) or MODEL_LOADING_DEFAULT_DELAY_S+ retry_after = get_retry_after(response)+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)return min(delay, timeout - elapsed), oom_retriesif code == RESOURCE_EXHAUSTED_ERROR_CODE:if not wait_for_capacity or oom_retries >= max_oom_retries or elapsed >= timeout:@@ -614,9 +680,6 @@ def next_stream_retry_delay(raise ResourceExhaustedError(msg, model=model, retries=oom_retries)delay = compute_oom_backoff(get_retry_after(response), oom_retries)return min(delay, timeout - elapsed), oom_retries + 1- if wait_for_capacity and elapsed < timeout:- delay = get_retry_after(response) or DEFAULT_RETRY_DELAY_S- return min(delay, timeout - elapsed), oom_retriesif status == HTTP_GATEWAY_TIMEOUT:msg = (diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex 696c685d6..790ba0a5e 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -65,8 +65,6 @@ from sie_sdk.types import (from ._shared import (DEFAULT_LEASE_RENEWAL_INTERVAL_S,DEFAULT_PROVISION_TIMEOUT_S,- DEFAULT_RETRY_DELAY_S,- HTTP_ACCEPTED,HTTP_CLIENT_ERROR,HTTP_GATEWAY_TIMEOUT,JSON_CONTENT_TYPE,@@ -76,6 +74,7 @@ from ._shared import (MODEL_LOADING_DEFAULT_DELAY_S,MODEL_LOADING_ERROR_CODE,MSGPACK_CONTENT_TYPE,+ PROVISIONING_ERROR_CODE,RESOURCE_EXHAUSTED_ERROR_CODE,RESOURCE_EXHAUSTED_MAX_RETRIES,SDK_VERSION_HEADER,@@ -85,6 +84,7 @@ from ._shared import (check_version_skew,compute_oom_backoff,compute_retry_delay,+ convert_score_images_for_wire,get_error_code,get_retry_after,get_sdk_version,@@ -95,8 +95,10 @@ from ._shared import (parse_extract_results,parse_gpu_param,parse_score_result,+ provisioning_retry_delay,raise_if_input_too_long,raise_if_model_load_failed,+ retry_after_or_default,sse_chunk_error,sse_headers,)@@ -711,6 +713,7 @@ class SIEAsyncClient:Args:name: Pool name (used in gpu="pool_name/machine_profile" routing).+ The gateway stores and routes pool names in lowercase.gpus: Optional machine profile requirements for pool readiness, e.g.,{"l4": 2, "l4-spot": 1}.gpu_caps: Optional maximum assigned workers per machine profile, e.g.,@@ -1136,7 +1139,7 @@ class SIEAsyncClient:# Retry counter for server-side OOM (RESOURCE_EXHAUSTED).oom_retries = 0- # Retry loop for 202 (provisioning) responses+ # Retry loop for retryable provisioning/capacity responses.while True:# Compute per-request timeout: cap to remaining provision time# This ensures a single hanging request can't exceed the overall timeout@@ -1190,39 +1193,28 @@ class SIEAsyncClient:msg = f"Failed to connect to {self._base_url}: {e}"raise SIEConnectionError(msg) from e- # Handle 202 (provisioning) - capacity not available- if response.status_code == HTTP_ACCEPTED:- retry_after = get_retry_after(response)-- if not wait_for_capacity:- msg = f"No capacity available for GPU '{resolved_gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- # Check if we've exceeded the timeout- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{resolved_gpu}'"- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- # Wait and retry- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "Waiting %.1fs for capacity (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- 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:error_code = get_error_code(response)+ if error_code == PROVISIONING_ERROR_CODE:+ actual_delay = provisioning_retry_delay(+ response,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ )+ logger.debug(+ "Provisioning in progress, retrying in %.1fs (timeout: %.1fs)",+ actual_delay,+ timeout,+ )+ await asyncio.sleep(actual_delay)+ continue+if error_code == LORA_LOADING_ERROR_CODE:lora_retries += 1@@ -1234,7 +1226,7 @@ class SIEAsyncClient:# Wait and retryretry_after = get_retry_after(response)- delay = retry_after or LORA_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, LORA_LOADING_DEFAULT_DELAY_S)logger.debug("LoRA loading, retrying in %.1fs (attempt %d/%d)",delay,@@ -1253,7 +1245,7 @@ class SIEAsyncClient:# Wait and retry, respecting remaining timeretry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -1276,27 +1268,6 @@ class SIEAsyncClient:)continue- # Generic 503 (no healthy workers) - retry if wait_for_capacity- # This handles scale-from-zero when pools are PENDING and have no workers yet- if wait_for_capacity:- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- # Timeout exceeded, let handle_error raise the exception- pass- else:- retry_after = get_retry_after(response)- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "No healthy workers, retrying in %.1fs (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- await asyncio.sleep(actual_delay)- continue-# Handle 504 (gateway timeout) — defense-in-depth for older# gateways that don't yet map an upstream timeout to# 503 + MODEL_LOADING. A cold-start request that triggers a@@ -1308,7 +1279,7 @@ class SIEAsyncClient:elapsed = time.monotonic() - start_timeif elapsed < timeout:retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -1571,11 +1542,12 @@ class SIEAsyncClient:# Resolve defaults and poolpool_name, resolved_gpu = await self._resolve_pool_and_gpu(gpu)resolved_options = self._resolve_options(options)+ query_for_wire, items_for_wire = convert_score_images_for_wire(query, items)# Build request bodyrequest_body: dict[str, Any] = {- "query": query,- "items": items,+ "query": query_for_wire,+ "items": items_for_wire,}if instruction is not None:request_body["instruction"] = instruction@@ -1600,7 +1572,7 @@ class SIEAsyncClient:# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.oom_retries = 0- # Retry loop for 202 (provisioning) responses+ # Retry loop for retryable provisioning/capacity responses.while True:# Compute per-request timeout: cap to remaining provision time# This ensures a single hanging request can't exceed the overall timeout@@ -1654,37 +1626,28 @@ class SIEAsyncClient:msg = f"Failed to connect to {self._base_url}: {e}"raise SIEConnectionError(msg) from e- # Handle 202 (provisioning) - capacity not available- if response.status_code == HTTP_ACCEPTED:- retry_after = get_retry_after(response)-- if not wait_for_capacity:- msg = f"No capacity available for GPU '{resolved_gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{resolved_gpu}'"- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "Waiting %.1fs for capacity (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- 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:error_code = get_error_code(response)+ if error_code == PROVISIONING_ERROR_CODE:+ actual_delay = provisioning_retry_delay(+ response,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ )+ logger.debug(+ "Provisioning in progress, retrying in %.1fs (timeout: %.1fs)",+ actual_delay,+ timeout,+ )+ await asyncio.sleep(actual_delay)+ continue+if error_code == MODEL_LOADING_ERROR_CODE:elapsed = time.monotonic() - start_timeif elapsed >= timeout:@@ -1692,7 +1655,7 @@ class SIEAsyncClient:raise ModelLoadingError(msg, model=model)retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -1715,24 +1678,6 @@ class SIEAsyncClient:)continue- if wait_for_capacity:- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- pass- else:- retry_after = get_retry_after(response)- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "No healthy workers, retrying in %.1fs (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- await asyncio.sleep(actual_delay)- continue-# Handle 504 (gateway timeout) — defense-in-depth for older# gateways that don't yet map an upstream timeout to# 503 + MODEL_LOADING. See encode() above for rationale.@@ -1740,7 +1685,7 @@ class SIEAsyncClient:elapsed = time.monotonic() - start_timeif elapsed < timeout:retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -1863,30 +1808,28 @@ class SIEAsyncClient:msg = f"Request failed: {e}"raise SIEConnectionError(msg) from e- if response.status_code == HTTP_ACCEPTED:- retry_after = get_retry_after(response)- if not wait_for_capacity:- msg = f"No capacity available for GPU '{resolved_gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{resolved_gpu}'"- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)- delay = retry_after or DEFAULT_RETRY_DELAY_S- await asyncio.sleep(min(delay, timeout - elapsed))- continue-raise_if_model_load_failed(response, model=model)if response.status_code == 503:error_code = get_error_code(response)+ if error_code == PROVISIONING_ERROR_CODE:+ delay = provisioning_retry_delay(+ response,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ )+ await asyncio.sleep(delay)+ continue+if error_code == MODEL_LOADING_ERROR_CODE:elapsed = time.monotonic() - start_timeif elapsed >= timeout:msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"raise ModelLoadingError(msg, model=model)retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)await asyncio.sleep(min(delay, timeout - elapsed))continueif error_code == RESOURCE_EXHAUSTED_ERROR_CODE:@@ -1899,13 +1842,6 @@ class SIEAsyncClient:model=model,)continue- if wait_for_capacity:- elapsed = time.monotonic() - start_time- if elapsed < timeout:- retry_after = get_retry_after(response)- delay = retry_after or DEFAULT_RETRY_DELAY_S- await asyncio.sleep(min(delay, timeout - elapsed))- continue# Do NOT retry 504 here. Unlike the idempotent encode/score/extract# paths (which keep the 504 retry block), generation is NOT@@ -1915,7 +1851,7 @@ class SIEAsyncClient:# issue a SECOND billable generation with a different completion, so# surface it as a terminal ServerError instead (same reasoning as# the mid-flight transport-error block above). The pre-execution- # 503 MODEL_LOADING / 202 provisioning retries above remain because+ # 503 MODEL_LOADING / PROVISIONING retries above remain because# those fire *before* any generation can have started.if response.status_code == HTTP_GATEWAY_TIMEOUT:msg = (@@ -1974,7 +1910,7 @@ class SIEAsyncClient:Async counterpart of :meth:`SIEClient.chat_completions`. For tokenstreaming use :meth:`stream_chat_completions`. Generation is- non-idempotent, so only pre-execution 202 / 503 responses are retried;+ non-idempotent, so only pre-execution 503 PROVISIONING / MODEL_LOADING responses are retried;a 504 surfaces as :class:`ServerError`.Typed kwargs cover the full gateway-supported field set (see@@ -2224,7 +2160,7 @@ class SIEAsyncClient:"""Open an aiohttp SSE stream (with pre-stream provisioning retry) and yield chunks.Shared by :meth:`stream_chat_completions` and :meth:`stream_generate`.- Only the *pre-stream* response is retried (202 / 503); once bytes flow+ Only the *pre-stream* response is retried (503 PROVISIONING / MODEL_LOADING); once bytes flowa failure is terminal (non-idempotent). The ``async with`` keeps theconnection open while the caller consumes the generator."""@@ -2393,7 +2329,7 @@ class SIEAsyncClient:# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.oom_retries = 0- # Retry loop for 202 (provisioning) responses+ # Retry loop for retryable provisioning/capacity responses.while True:# Compute per-request timeout: cap to remaining provision time# This ensures a single hanging request can't exceed the overall timeout@@ -2447,31 +2383,6 @@ class SIEAsyncClient:msg = f"Failed to connect to {self._base_url}: {e}"raise SIEConnectionError(msg) from e- # Handle 202 (provisioning) - capacity not available- if response.status_code == HTTP_ACCEPTED:- retry_after = get_retry_after(response)-- if not wait_for_capacity:- msg = f"No capacity available for GPU '{resolved_gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{resolved_gpu}'"- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "Waiting %.1fs for capacity (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- await asyncio.sleep(actual_delay)- continue-# Short-circuit terminal load failures (sie-test#85).raise_if_model_load_failed(response, model=model)@@ -2481,6 +2392,22 @@ class SIEAsyncClient:# Handle 503 with MODEL_LOADING - auto-retryif response.status_code == 503:error_code = get_error_code(response)+ if error_code == PROVISIONING_ERROR_CODE:+ actual_delay = provisioning_retry_delay(+ response,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ )+ logger.debug(+ "Provisioning in progress, retrying in %.1fs (timeout: %.1fs)",+ actual_delay,+ timeout,+ )+ await asyncio.sleep(actual_delay)+ continue+if error_code == MODEL_LOADING_ERROR_CODE:elapsed = time.monotonic() - start_timeif elapsed >= timeout:@@ -2488,7 +2415,7 @@ class SIEAsyncClient:raise ModelLoadingError(msg, model=model)retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -2511,24 +2438,6 @@ class SIEAsyncClient:)continue- if wait_for_capacity:- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- pass- else:- retry_after = get_retry_after(response)- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "No healthy workers, retrying in %.1fs (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- await asyncio.sleep(actual_delay)- continue-# Handle 504 (gateway timeout) — defense-in-depth for older# gateways that don't yet map an upstream timeout to# 503 + MODEL_LOADING. See encode() above for rationale.@@ -2536,7 +2445,7 @@ class SIEAsyncClient:elapsed = time.monotonic() - start_timeif elapsed < timeout:retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(diff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.pyindex e314203e5..580fe322d 100644--- a/packages/sie_sdk/src/sie_sdk/client/errors.py+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py@@ -33,7 +33,7 @@ class ProvisioningError(SIEError):"""Error when capacity is not available and provisioning timed out.Raised when:- - Server returns 202 (no capacity, provisioning)+ - Server returns 503 with PROVISIONING code- wait_for_capacity=False (caller doesn't want to wait)- Or provisioning timeout exceededdiff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 06267cbdc..ada564274 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -20,7 +20,7 @@ GPU Selection and Auto-Retry:... "bge-m3",... {"text": "Hello"},... gpu="l4",- ... wait_for_capacity=True, # Auto-retry on 202/503/504 and transient transport errors+ ... wait_for_capacity=True, # Auto-retry explicit capacity 503s and transient transport errors... provision_timeout_s=900, # Wait up to 15 min... )@@ -72,8 +72,6 @@ from sie_sdk.types import (from ._shared import (DEFAULT_LEASE_RENEWAL_INTERVAL_S,DEFAULT_PROVISION_TIMEOUT_S,- DEFAULT_RETRY_DELAY_S,- HTTP_ACCEPTED,HTTP_CLIENT_ERROR,HTTP_GATEWAY_TIMEOUT,JSON_CONTENT_TYPE,@@ -83,6 +81,7 @@ from ._shared import (MODEL_LOADING_DEFAULT_DELAY_S,MODEL_LOADING_ERROR_CODE,MSGPACK_CONTENT_TYPE,+ PROVISIONING_ERROR_CODE,RESOURCE_EXHAUSTED_ERROR_CODE,RESOURCE_EXHAUSTED_MAX_RETRIES,SDK_VERSION_HEADER,@@ -92,6 +91,7 @@ from ._shared import (check_version_skew,compute_oom_backoff,compute_retry_delay,+ convert_score_images_for_wire,get_error_code,get_retry_after,get_sdk_version,@@ -102,8 +102,10 @@ from ._shared import (parse_extract_results,parse_gpu_param,parse_score_result,+ provisioning_retry_delay,raise_if_input_too_long,raise_if_model_load_failed,+ retry_after_or_default,sse_chunk_error,sse_headers,)@@ -590,6 +592,7 @@ class SIEClient:Args:name: Pool name (used in gpu="pool_name/machine_profile" routing).+ The gateway stores and routes pool names in lowercase.gpus: Optional machine profile requirements for pool readiness, e.g.,{"l4": 2, "l4-spot": 1}.Keys are machine profile names from cluster config.@@ -940,8 +943,7 @@ class SIEClient:with matching GPU. Required when using the gateway with multiple GPU pools.wait_for_capacity: When True (default), auto-retry transient "notenough capacity yet" responses under ``provision_timeout_s`` —- ``202`` (scale-from-zero provisioning); generic ``503`` (no- healthy workers for the (bundle, machine_profile) tuple);+ ``503 PROVISIONING`` (scale-from-zero provisioning);``504`` (defense-in-depth for older gateways that haven't yetmapped upstream timeouts to ``503 MODEL_LOADING``); local``httpx`` read/connect/pool timeouts; and transient@@ -981,7 +983,7 @@ class SIEClient:ServerError: If the server encounters an error (5xx response).SIEConnectionError: If unable to connect to the server.ProvisioningError: If ``wait_for_capacity=False`` and the gateway- returns ``202`` (scale-from-zero provisioning), or if ``202``+ returns ``503 PROVISIONING`` (scale-from-zero provisioning), or if provisioningretries exceed ``provision_timeout_s``.ModelLoadingError: If ``503`` ``MODEL_LOADING`` retries exceed``provision_timeout_s`` during worker-side cold-loading of the@@ -1091,7 +1093,7 @@ class SIEClient:# backoff via ``compute_oom_backoff``.oom_retries = 0- # Retry loop for 202 (provisioning) responses+ # Retry loop for retryable provisioning/capacity responses.while True:# Compute per-request timeout: cap to remaining provision time# This ensures a single hanging request can't exceed the overall timeout@@ -1139,33 +1141,6 @@ class SIEClient:)raise SIEConnectionError(msg) from e- # Handle 202 (provisioning) - capacity not available- if response.status_code == HTTP_ACCEPTED:- retry_after = get_retry_after(response)-- if not wait_for_capacity:- msg = f"No capacity available for GPU '{resolved_gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- # Check if we've exceeded the timeout- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{resolved_gpu}'"- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- # Wait and retry- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "Waiting %.1fs for capacity (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- 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,@@ -1176,6 +1151,22 @@ class SIEClient:# Handle 503 with LORA_LOADING or MODEL_LOADING - auto-retryif response.status_code == 503:error_code = get_error_code(response)+ if error_code == PROVISIONING_ERROR_CODE:+ actual_delay = provisioning_retry_delay(+ response,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ )+ logger.debug(+ "Provisioning in progress, retrying in %.1fs (timeout: %.1fs)",+ actual_delay,+ timeout,+ )+ time.sleep(actual_delay)+ continue+if error_code == LORA_LOADING_ERROR_CODE:lora_retries += 1@@ -1187,7 +1178,7 @@ class SIEClient:# Wait and retryretry_after = get_retry_after(response)- delay = retry_after or LORA_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, LORA_LOADING_DEFAULT_DELAY_S)logger.debug("LoRA loading, retrying in %.1fs (attempt %d/%d)",delay,@@ -1206,7 +1197,7 @@ class SIEClient:# Wait and retry, respecting remaining timeretry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -1229,27 +1220,6 @@ class SIEClient:)continue- # Generic 503 (no healthy workers) - retry if wait_for_capacity- # This handles scale-from-zero when pools are PENDING and have no workers yet- if wait_for_capacity:- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- # Timeout exceeded, let handle_error raise the exception- pass- else:- retry_after = get_retry_after(response)- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "No healthy workers, retrying in %.1fs (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- time.sleep(actual_delay)- continue-# Handle 504 (gateway timeout) — defense-in-depth for older# gateways that don't yet map an upstream timeout to# 503 + MODEL_LOADING. A cold-start request that triggers a@@ -1261,7 +1231,7 @@ class SIEClient:elapsed = time.monotonic() - start_timeif elapsed < timeout:retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -1642,8 +1612,7 @@ class SIEClient:with matching GPU.wait_for_capacity: When True (default), auto-retry transient "notenough capacity yet" responses under ``provision_timeout_s`` —- ``202`` (scale-from-zero provisioning); generic ``503`` (no- healthy workers for the (bundle, machine_profile) tuple);+ ``503 PROVISIONING`` (scale-from-zero provisioning);``504`` (defense-in-depth for older gateways that haven't yetmapped upstream timeouts to ``503 MODEL_LOADING``); local``httpx`` read/connect/pool timeouts; and transient@@ -1682,7 +1651,7 @@ class SIEClient:ServerError: If the server encounters an error (5xx response).SIEConnectionError: If unable to connect to the server.ProvisioningError: If ``wait_for_capacity=False`` and the gateway- returns ``202`` (scale-from-zero provisioning), or if ``202``+ returns ``503 PROVISIONING`` (scale-from-zero provisioning), or if provisioningretries exceed ``provision_timeout_s``.ModelLoadingError: If ``503`` ``MODEL_LOADING`` retries exceed``provision_timeout_s`` during worker-side cold-loading of the@@ -1704,11 +1673,12 @@ class SIEClient:# Resolve defaults and poolpool_name, resolved_gpu = self._resolve_pool_and_gpu(gpu)resolved_options = self._resolve_options(options)+ query_for_wire, items_for_wire = convert_score_images_for_wire(query, items)# Build request bodyrequest_body: dict[str, Any] = {- "query": query,- "items": items,+ "query": query_for_wire,+ "items": items_for_wire,}if instruction is not None:request_body["instruction"] = instruction@@ -1733,7 +1703,7 @@ class SIEClient:# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.oom_retries = 0- # Retry loop for 202 (provisioning) responses+ # Retry loop for retryable provisioning/capacity responses.while True:# Compute per-request timeout: cap to remaining provision time# This ensures a single hanging request can't exceed the overall timeout@@ -1781,39 +1751,28 @@ class SIEClient:)raise SIEConnectionError(msg) from e- # Handle 202 (provisioning) - capacity not available- if response.status_code == HTTP_ACCEPTED:- retry_after = get_retry_after(response)-- if not wait_for_capacity:- msg = f"No capacity available for GPU '{resolved_gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- # Check if we've exceeded the timeout- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{resolved_gpu}'"- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- # Wait and retry- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "Waiting %.1fs for capacity (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- 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:error_code = get_error_code(response)+ if error_code == PROVISIONING_ERROR_CODE:+ actual_delay = provisioning_retry_delay(+ response,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ )+ logger.debug(+ "Provisioning in progress, retrying in %.1fs (timeout: %.1fs)",+ actual_delay,+ timeout,+ )+ time.sleep(actual_delay)+ continue+if error_code == MODEL_LOADING_ERROR_CODE:# Check if we've exceeded the provision timeoutelapsed = time.monotonic() - start_time@@ -1823,7 +1782,7 @@ class SIEClient:# Wait and retry, respecting remaining timeretry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -1846,27 +1805,6 @@ class SIEClient:)continue- # Generic 503 (no healthy workers) - retry if wait_for_capacity- # This handles scale-from-zero when pools are PENDING and have no workers yet- if wait_for_capacity:- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- # Timeout exceeded, let handle_error raise the exception- pass- else:- retry_after = get_retry_after(response)- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "No healthy workers, retrying in %.1fs (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- time.sleep(actual_delay)- continue-# Handle 504 (gateway timeout) — defense-in-depth for older# gateways that don't yet map an upstream timeout to# 503 + MODEL_LOADING. A cold-start request that triggers a@@ -1878,7 +1816,7 @@ class SIEClient:elapsed = time.monotonic() - start_timeif elapsed < timeout:retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -1940,7 +1878,7 @@ class SIEClient:top_p: Nucleus sampling cutoff.stop: Optional list of stop strings.gpu: Target GPU type / pool spec; see ``encode``.- wait_for_capacity: Auto-retry 202 / 503 MODEL_LOADING responses+ wait_for_capacity: Auto-retry 503 PROVISIONING / MODEL_LOADING responsesunder ``provision_timeout_s``. See ``encode``. Unlike theidempotent encode/score/extract paths, a ``504`` gatewaytimeout is NOT retried here: generation is non-idempotent@@ -2028,31 +1966,28 @@ class SIEClient:)raise SIEConnectionError(msg) from e- if response.status_code == HTTP_ACCEPTED:- retry_after = get_retry_after(response)- if not wait_for_capacity:- msg = f"No capacity available for GPU '{resolved_gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{resolved_gpu}'"- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)- delay = retry_after or DEFAULT_RETRY_DELAY_S- actual_delay = min(delay, timeout - elapsed)- time.sleep(actual_delay)- continue-raise_if_model_load_failed(response, model=model)if response.status_code == 503:error_code = get_error_code(response)+ if error_code == PROVISIONING_ERROR_CODE:+ actual_delay = provisioning_retry_delay(+ response,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ )+ time.sleep(actual_delay)+ continue+if error_code == MODEL_LOADING_ERROR_CODE:elapsed = time.monotonic() - start_timeif elapsed >= timeout:msg = f"Model loading timeout after {elapsed:.1f}s for '{model}'"raise ModelLoadingError(msg, model=model)retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)actual_delay = min(delay, timeout - elapsed)time.sleep(actual_delay)continue@@ -2066,14 +2001,6 @@ class SIEClient:model=model,)continue- if wait_for_capacity:- elapsed = time.monotonic() - start_time- if elapsed < timeout:- retry_after = get_retry_after(response)- delay = retry_after or DEFAULT_RETRY_DELAY_S- actual_delay = min(delay, timeout - elapsed)- time.sleep(actual_delay)- continue# Do NOT retry 504 here. Unlike the idempotent encode/score/extract# paths (which keep the 504 retry block), generation is NOT@@ -2083,7 +2010,7 @@ class SIEClient:# issue a SECOND billable generation with a different completion, so# surface it as a terminal ServerError instead (same reasoning as# the mid-flight transport-error block above). The pre-execution- # 503 MODEL_LOADING / 202 provisioning retries above remain because+ # 503 MODEL_LOADING / PROVISIONING retries above remain because# those fire *before* any generation can have started.if response.status_code == HTTP_GATEWAY_TIMEOUT:msg = (@@ -2144,7 +2071,7 @@ class SIEClient:Mirrors the subset of OpenAI's ``chat.completions.create`` the gatewayhonours. For token streaming use :meth:`stream_chat_completions`.Generation is non-idempotent, so — like :meth:`generate` — only- pre-execution 202 / 503 responses are retried; a 504 (post-publish)+ pre-execution 503 PROVISIONING / MODEL_LOADING responses are retried; a 504 (post-publish)surfaces as :class:`ServerError`.Typed kwargs cover the full gateway-supported field set (see@@ -2391,7 +2318,7 @@ class SIEClient:"""Open an SSE stream (with pre-stream provisioning retry) and yield chunks.Shared by :meth:`stream_chat_completions` and :meth:`stream_generate`.- Only the *pre-stream* response is retried (202 / 503); once bytes start+ Only the *pre-stream* response is retried (503 PROVISIONING / MODEL_LOADING); once bytes startflowing a failure is terminal (non-idempotent). Yielding inside the``with`` keeps the stream open while the caller consumes it; an early``break`` tears the context down and the worker sees the disconnect.@@ -2516,8 +2443,7 @@ class SIEClient:with matching GPU.wait_for_capacity: When True (default), auto-retry transient "notenough capacity yet" responses under ``provision_timeout_s`` —- ``202`` (scale-from-zero provisioning); generic ``503`` (no- healthy workers for the (bundle, machine_profile) tuple);+ ``503 PROVISIONING`` (scale-from-zero provisioning);``504`` (defense-in-depth for older gateways that haven't yetmapped upstream timeouts to ``503 MODEL_LOADING``); local``httpx`` read/connect/pool timeouts; and transient@@ -2556,7 +2482,7 @@ class SIEClient:ServerError: If the server encounters an error (5xx response).SIEConnectionError: If unable to connect to the server.ProvisioningError: If ``wait_for_capacity=False`` and the gateway- returns ``202`` (scale-from-zero provisioning), or if ``202``+ returns ``503 PROVISIONING`` (scale-from-zero provisioning), or if provisioningretries exceed ``provision_timeout_s``.ModelLoadingError: If ``503`` ``MODEL_LOADING`` retries exceed``provision_timeout_s`` during worker-side cold-loading of the@@ -2639,7 +2565,7 @@ class SIEClient:# OOM retry counter (RESOURCE_EXHAUSTED) — bounded with exponential backoff.oom_retries = 0- # Retry loop for 202 (provisioning) responses+ # Retry loop for retryable provisioning/capacity responses.while True:# Compute per-request timeout: cap to remaining provision time# This ensures a single hanging request can't exceed the overall timeout@@ -2687,33 +2613,6 @@ class SIEClient:)raise SIEConnectionError(msg) from e- # Handle 202 (provisioning) - capacity not available- if response.status_code == HTTP_ACCEPTED:- retry_after = get_retry_after(response)-- if not wait_for_capacity:- msg = f"No capacity available for GPU '{resolved_gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- # Check if we've exceeded the timeout- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{resolved_gpu}'"- raise ProvisioningError(msg, gpu=resolved_gpu, retry_after=retry_after)-- # Wait and retry- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "Waiting %.1fs for capacity (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- time.sleep(actual_delay)- continue-# Short-circuit terminal load failures (sie-test#85).raise_if_model_load_failed(response, model=model)@@ -2723,6 +2622,22 @@ class SIEClient:# Handle 503 with MODEL_LOADING - auto-retryif response.status_code == 503:error_code = get_error_code(response)+ if error_code == PROVISIONING_ERROR_CODE:+ actual_delay = provisioning_retry_delay(+ response,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ )+ logger.debug(+ "Provisioning in progress, retrying in %.1fs (timeout: %.1fs)",+ actual_delay,+ timeout,+ )+ time.sleep(actual_delay)+ continue+if error_code == MODEL_LOADING_ERROR_CODE:# Check if we've exceeded the provision timeoutelapsed = time.monotonic() - start_time@@ -2732,7 +2647,7 @@ class SIEClient:# Wait and retry, respecting remaining timeretry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(@@ -2755,27 +2670,6 @@ class SIEClient:)continue- # Generic 503 (no healthy workers) - retry if wait_for_capacity- # This handles scale-from-zero when pools are PENDING and have no workers yet- if wait_for_capacity:- elapsed = time.monotonic() - start_time- if elapsed >= timeout:- # Timeout exceeded, let handle_error raise the exception- pass- else:- retry_after = get_retry_after(response)- delay = retry_after or DEFAULT_RETRY_DELAY_S- remaining = timeout - elapsed- actual_delay = min(delay, remaining)- logger.debug(- "No healthy workers, retrying in %.1fs (elapsed: %.1fs, timeout: %.1fs)",- actual_delay,- elapsed,- timeout,- )- time.sleep(actual_delay)- continue-# Handle 504 (gateway timeout) — defense-in-depth for older# gateways that don't yet map an upstream timeout to# 503 + MODEL_LOADING. A cold-start request that triggers a@@ -2787,7 +2681,7 @@ class SIEClient:elapsed = time.monotonic() - start_timeif elapsed < timeout:retry_after = get_retry_after(response)- delay = retry_after or MODEL_LOADING_DEFAULT_DELAY_S+ delay = retry_after_or_default(retry_after, MODEL_LOADING_DEFAULT_DELAY_S)remaining = timeout - elapsedactual_delay = min(delay, remaining)logger.info(diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex 378ba6c2b..9211e35c5 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -563,7 +563,8 @@ class PoolSpec(TypedDict, total=False):renews the lease.Attributes:- name: Pool name (required). Used in GPU param as "pool_name/machine_profile".+ name: Pool name (required). Used in GPU param as "pool_name/machine_profile";+ the gateway stores and routes pool names in lowercase.gpus: Optional GPU requirements for pool readiness, e.g., {"l4": 2, "a100-40gb": 1}.gpu_caps: Optional maximum assigned workers per GPU type.bundle: Optional bundle filter for worker assignment.diff --git a/packages/sie_sdk/tests/client/test_async.py b/packages/sie_sdk/tests/client/test_async.pyindex c57ca85a0..2d81da313 100644--- a/packages/sie_sdk/tests/client/test_async.py+++ b/packages/sie_sdk/tests/client/test_async.py@@ -319,6 +319,35 @@ class TestAsyncScore:assert result["scores"][0]["item_id"] == "doc-1"await client.close()+ @pytest.mark.asyncio+ async def test_score_converts_image_query_and_items_to_wire_format(self) -> None:+ """Async score converts image query/items before msgpack serialization."""+ resp = _make_msgpack_response(+ {+ "model": "qwen3-vl-reranker",+ "scores": [{"item_id": "page-1", "score": 0.8, "rank": 0}],+ }+ )++ query_image = b"\xff\xd8\xff\xe0query"+ item_image = b"\xff\xd8\xff\xe0item"+ query = {"text": "rocket nozzle", "images": [query_image]}+ item = {"id": "page-1", "images": [item_image]}++ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(return_value=resp) # type: ignore+ await client.score("qwen3-vl-reranker", query=query, items=[item])++ body = client._post.call_args.kwargs["data"]+ request_body = msgpack.unpackb(body, raw=False)+ query_wire = request_body["query"]["images"][0]+ item_wire = request_body["items"][0]["images"][0]+ assert query_wire == {"data": query_image, "format": "jpeg"}+ assert item_wire == {"data": item_image, "format": "jpeg"}+ assert query["images"][0] == query_image+ assert item["images"][0] == item_image+ await client.close()+class TestAsyncExtract:"""Tests for async extract() method."""diff --git a/packages/sie_sdk/tests/client/test_chat.py b/packages/sie_sdk/tests/client/test_chat.pyindex 38e3f6099..60c5eb858 100644--- a/packages/sie_sdk/tests/client/test_chat.py+++ b/packages/sie_sdk/tests/client/test_chat.py@@ -6,7 +6,7 @@ Mocks the httpx layer; exercises:- ``stream_chat_completions`` SSE chunk yielding + ``stream:true`` body.- ``stream_generate`` SSE chunk yielding + HF-id path normalization.- A mid-stream error chunk raises ``ServerError``.-- A 202 pre-stream response is retried, then the stream is consumed.+- A 503 PROVISIONING pre-stream response is retried, then the stream is consumed."""from __future__ import annotations@@ -171,11 +171,15 @@ def test_stream_raises_server_error_on_error_chunk() -> None:client.close()-def test_stream_chat_retries_202_then_streams() -> None:- s202 = _FakeStream(status_code=202, headers={"Retry-After": "0.01"}, json_body={"detail": {"message": "prov"}})+def test_stream_chat_retries_503_provisioning_then_streams() -> None:+ s503 = _FakeStream(+ status_code=503,+ headers={"Retry-After": "0.01", "content-type": "application/json"},+ json_body={"error": {"code": "PROVISIONING", "message": "prov"}},+ )s200 = _FakeStream(lines=_sse(_chat_chunk("ok", finish="stop")))with patch("sie_sdk.client.sync.httpx.Client") as mc:- mc.return_value.stream.side_effect = [s202, s200]+ mc.return_value.stream.side_effect = [s503, s200]client = SIEClient("http://localhost:8080")out = list(client.stream_chat_completions("m", [{"role": "user", "content": "hi"}], provision_timeout_s=5.0))assert [c["choices"][0]["delta"].get("content") for c in out] == ["ok"]diff --git a/packages/sie_sdk/tests/client/test_chat_async.py b/packages/sie_sdk/tests/client/test_chat_async.pyindex 620c95c40..45e95ab01 100644--- a/packages/sie_sdk/tests/client/test_chat_async.py+++ b/packages/sie_sdk/tests/client/test_chat_async.py@@ -2,7 +2,7 @@Mocks the aiohttp session; exercises the async mirror of ``test_chat.py``:buffered ``chat_completions``, ``stream_chat_completions``, ``stream_generate``,-mid-stream error -> ``ServerError``, and a 202 pre-stream retry.+mid-stream error -> ``ServerError``, and a 503 PROVISIONING pre-stream retry."""from __future__ import annotations@@ -158,11 +158,15 @@ async def test_async_stream_raises_on_error_chunk() -> None:@pytest.mark.asyncio-async def test_async_stream_chat_retries_202_then_streams() -> None:- s202 = _FakeRaw(status=202, headers={"Retry-After": "0.01"}, body={"detail": {"message": "prov"}})+async def test_async_stream_chat_retries_503_provisioning_then_streams() -> None:+ s503 = _FakeRaw(+ status=503,+ headers={"Retry-After": "0.01", "content-type": "application/json"},+ body={"error": {"code": "PROVISIONING", "message": "prov"}},+ )s200 = _FakeRaw(status=200, line_bytes=_sse_bytes(_chat_chunk("ok", finish="stop")))client = SIEAsyncClient("http://localhost:8080")- session = _patch_session(client, post_side_effect=[s202, s200])+ session = _patch_session(client, post_side_effect=[s503, s200])out = [casync for c in client.stream_chat_completions("m", [{"role": "user", "content": "hi"}], provision_timeout_s=5.0)diff --git a/packages/sie_sdk/tests/client/test_generate.py b/packages/sie_sdk/tests/client/test_generate.pyindex f867d3390..70eb01537 100644--- a/packages/sie_sdk/tests/client/test_generate.py+++ b/packages/sie_sdk/tests/client/test_generate.py@@ -16,7 +16,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytestfrom sie_sdk import SIEAsyncClient, SIEClient, SIEConnectionError-from sie_sdk.client.errors import RequestError, ServerError+from sie_sdk.client.errors import ProvisioningError, RequestError, ServerErrordef _ok_response(payload: dict) -> MagicMock:@@ -48,11 +48,24 @@ def _resp_503_model_loading() -> MagicMock:return response-def _resp_202() -> MagicMock:+def _resp_503_provisioning() -> MagicMock:response = MagicMock()- response.status_code = 202+ response.status_code = 503response.headers = {"Retry-After": "0.01", "content-type": "application/json"}- response.json.return_value = {"detail": {"message": "provisioning"}}+ response.json.return_value = {"error": {"code": "PROVISIONING", "message": "provisioning"}}+ response.content = json.dumps(response.json.return_value).encode("utf-8")+ return response+++def _resp_503_openai_provisioning() -> MagicMock:+ response = MagicMock()+ response.status_code = 503+ response.headers = {+ "Retry-After": "0.01",+ "X-SIE-Error-Code": "PROVISIONING",+ "content-type": "application/json",+ }+ response.json.return_value = {"error": {"code": "provisioning", "message": "provisioning"}}response.content = json.dumps(response.json.return_value).encode("utf-8")return response@@ -73,6 +86,15 @@ def _aio_resp(status: int, body: dict, headers: dict | None = None) -> object:return _AioResponse(status, json.dumps(body).encode("utf-8"), 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++ response = _resp_503_openai_provisioning()+ assert get_error_code(response) == "PROVISIONING"+ with pytest.raises(ProvisioningError):+ handle_error(response)++def _make_session_post(seq_source: AsyncMock):"""Build a ``session.post`` that yields a raw aiohttp-like response per call.@@ -237,14 +259,17 @@ class TestSyncGenerate:assert excinfo.value.status_code == 504client.close()- def test_generate_still_retries_202_provisioning(self) -> None:- # 202 is pre-execution (no capacity yet, nothing generated), so it is- # safe to retry under wait_for_capacity even on the non-idempotent path.+ def test_generate_still_retries_503_provisioning(self) -> None:+ # 503 PROVISIONING is pre-execution (no capacity yet, nothing+ # generated), so it is safe to retry under wait_for_capacity even on+ # the non-idempotent path.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_202(), _ok_response(_ok_envelope())])+ mock_client.return_value.post = MagicMock(+ side_effect=[_resp_503_provisioning(), _ok_response(_ok_envelope())]+ )client = SIEClient("http://localhost:8080")result = client.generate("m", prompt="hi", max_new_tokens=8, provision_timeout_s=10)assert result["text"] == "ok"diff --git a/packages/sie_sdk/tests/client/test_malformed_retry_after.py b/packages/sie_sdk/tests/client/test_malformed_retry_after.pyindex 7ea173ea3..3e3ba3645 100644--- a/packages/sie_sdk/tests/client/test_malformed_retry_after.py+++ b/packages/sie_sdk/tests/client/test_malformed_retry_after.py@@ -23,7 +23,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom sie_sdk import SIEAsyncClient, SIEClient-from sie_sdk.client._shared import get_retry_after+from sie_sdk.client._shared import get_retry_after, provisioning_retry_delayfrom sie_sdk.client.errors import ModelLoadingError, ProvisioningError@@ -105,20 +105,35 @@ class TestGetRetryAfterHttpDate:assert get_retry_after(_resp_with_retry_after("not-a-date")) is None+class TestProvisioningRetryDelay:+ def test_retry_after_zero_means_immediate_retry(self) -> None:+ response = _resp_with_retry_after("0")+ assert (+ provisioning_retry_delay(+ response,+ gpu="l4",+ wait_for_capacity=True,+ start_time=time.monotonic(),+ timeout=10.0,+ )+ == 0.0+ )++class TestSyncGenerateMalformedRetryAfter:- """(b) sync ``generate()`` against a perpetual ``202 Retry-After: nan``+ """(b) sync ``generate()`` against a perpetual ``503 PROVISIONING Retry-After: nan``must NOT raise ``ValueError`` (no ``time.sleep(nan)`` crash) and mustterminate within the provision budget with a bounded number of HTTP calls."""- def test_perpetual_202_nan_does_not_crash_and_is_bounded(self) -> None:+ def test_perpetual_503_provisioning_nan_does_not_crash_and_is_bounded(self) -> None:from sie_sdk.client.errors import ProvisioningError- def _resp_202_nan() -> MagicMock:+ def _resp_503_provisioning_nan() -> MagicMock:response = MagicMock()- response.status_code = 202+ response.status_code = 503response.headers = {"Retry-After": "nan", "content-type": "application/json"}- response.json.return_value = {"detail": {"message": "provisioning"}}+ response.json.return_value = {"error": {"code": "PROVISIONING", "message": "provisioning"}}response.content = json.dumps(response.json.return_value).encode("utf-8")return response@@ -136,7 +151,7 @@ class TestSyncGenerateMalformedRetryAfter:patch("sie_sdk.client.sync.httpx.Client") as mock_client,patch("sie_sdk.client.sync.time.sleep", side_effect=_fake_sleep),):- mock_client.return_value.post.return_value = _resp_202_nan()+ mock_client.return_value.post.return_value = _resp_503_provisioning_nan()client = SIEClient("http://localhost:8080")# Must terminate (ProvisioningError) within the budget — NOT ValueError.with pytest.raises(ProvisioningError):diff --git a/packages/sie_sdk/tests/client/test_provisioning.py b/packages/sie_sdk/tests/client/test_provisioning.pyindex 2a90d516a..3d756b012 100644--- a/packages/sie_sdk/tests/client/test_provisioning.py+++ b/packages/sie_sdk/tests/client/test_provisioning.py@@ -8,7 +8,7 @@ from sie_sdk import ServerError, SIEAsyncClient, SIEClientclass TestProvisioningRetry:- """Tests for 202 provisioning retry functionality."""+ """Tests for 503 PROVISIONING retry functionality."""def test_machine_profile_header_sent_when_gpu_specified(self) -> None:"""X-SIE-MACHINE-PROFILE header is sent when gpu parameter provided."""@@ -28,13 +28,17 @@ class TestProvisioningRetry:assert call_args.kwargs["headers"]["X-SIE-MACHINE-PROFILE"] == "l4"client.close()- def test_202_raises_provisioning_error_without_wait(self) -> None:- """202 response raises ProvisioningError when wait_for_capacity=False."""+ def test_503_provisioning_raises_provisioning_error_without_wait(self) -> None:+ """503 PROVISIONING raises ProvisioningError when wait_for_capacity=False."""from sie_sdk import ProvisioningError+ from sie_sdk.client._shared import PROVISIONING_ERROR_CODEmock_response = MagicMock()- mock_response.status_code = 202- mock_response.headers = {"Retry-After": "30"}+ mock_response.status_code = 503+ mock_response.headers = {"Retry-After": "30", "content-type": "application/json"}+ mock_response.json.return_value = {+ "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}+ }with patch("sie_sdk.client.sync.httpx.Client") as mock_client:mock_client.return_value.post = MagicMock(return_value=mock_response)@@ -47,12 +51,17 @@ class TestProvisioningRetry:assert exc_info.value.retry_after == 30.0client.close()- def test_202_retries_with_wait_for_capacity(self) -> None:- """202 response is retried when wait_for_capacity=True."""- # First response is 202, second is 200- mock_response_202 = MagicMock()- mock_response_202.status_code = 202- mock_response_202.headers = {"Retry-After": "0.01"} # Short delay for test+ def test_503_provisioning_retries_with_wait_for_capacity(self) -> None:+ """503 PROVISIONING is retried when wait_for_capacity=True."""+ from sie_sdk.client._shared import PROVISIONING_ERROR_CODE++ # First response is 503 PROVISIONING, second is 200+ mock_response_503 = MagicMock()+ mock_response_503.status_code = 503+ mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}+ mock_response_503.json.return_value = {+ "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}+ }mock_response_200 = MagicMock()mock_response_200.status_code = 200@@ -60,7 +69,7 @@ class TestProvisioningRetry:mock_response_200.content = msgpack.packb({"items": [{"dense": {"values": np.zeros(1024)}}]}, use_bin_type=True)with patch("sie_sdk.client.sync.httpx.Client") as mock_client:- mock_client.return_value.post = MagicMock(side_effect=[mock_response_202, mock_response_200])+ mock_client.return_value.post = MagicMock(side_effect=[mock_response_503, mock_response_200])client = SIEClient("http://localhost:8080")result = client.encode(@@ -76,17 +85,21 @@ class TestProvisioningRetry:assert mock_client.return_value.post.call_count == 2client.close()- def test_202_timeout_raises_provisioning_error(self) -> None:+ def test_503_provisioning_timeout_raises_provisioning_error(self) -> None:"""Provisioning timeout raises ProvisioningError."""from sie_sdk import ProvisioningError+ from sie_sdk.client._shared import PROVISIONING_ERROR_CODE- mock_response_202 = MagicMock()- mock_response_202.status_code = 202- mock_response_202.headers = {"Retry-After": "0.01"}+ mock_response_503 = MagicMock()+ mock_response_503.status_code = 503+ mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}+ mock_response_503.json.return_value = {+ "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}+ }with patch("sie_sdk.client.sync.httpx.Client") as mock_client:- # Always return 202- mock_client.return_value.post = MagicMock(return_value=mock_response_202)+ # Always return 503 PROVISIONING+ mock_client.return_value.post = MagicMock(return_value=mock_response_503)client = SIEClient("http://localhost:8080")with pytest.raises(ProvisioningError) as exc_info:@@ -104,10 +117,14 @@ class TestProvisioningRetry:def test_retry_after_header_parsed(self) -> None:"""Retry-After header is correctly parsed."""from sie_sdk import ProvisioningError+ from sie_sdk.client._shared import PROVISIONING_ERROR_CODEmock_response = MagicMock()- mock_response.status_code = 202- mock_response.headers = {"Retry-After": "60"}+ mock_response.status_code = 503+ mock_response.headers = {"Retry-After": "60", "content-type": "application/json"}+ mock_response.json.return_value = {+ "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}+ }with patch("sie_sdk.client.sync.httpx.Client") as mock_client:mock_client.return_value.post = MagicMock(return_value=mock_response)@@ -122,10 +139,14 @@ class TestProvisioningRetry:def test_missing_retry_after_uses_default(self) -> None:"""Missing Retry-After header uses None."""from sie_sdk import ProvisioningError+ from sie_sdk.client._shared import PROVISIONING_ERROR_CODEmock_response = MagicMock()- mock_response.status_code = 202- mock_response.headers = {} # No Retry-After+ mock_response.status_code = 503+ mock_response.headers = {"content-type": "application/json"} # No Retry-After+ mock_response.json.return_value = {+ "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}+ }with patch("sie_sdk.client.sync.httpx.Client") as mock_client:mock_client.return_value.post = MagicMock(return_value=mock_response)@@ -138,10 +159,15 @@ class TestProvisioningRetry:client.close()def test_default_wait_for_capacity_is_true(self) -> None:- """Default wait_for_capacity is True, so 202 is retried automatically."""- mock_response_202 = MagicMock()- mock_response_202.status_code = 202- mock_response_202.headers = {"Retry-After": "0.01"}+ """Default wait_for_capacity is True, so 503 PROVISIONING is retried automatically."""+ from sie_sdk.client._shared import PROVISIONING_ERROR_CODE++ mock_response_503 = MagicMock()+ mock_response_503.status_code = 503+ mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}+ mock_response_503.json.return_value = {+ "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}+ }mock_response_200 = MagicMock()mock_response_200.status_code = 200@@ -149,7 +175,7 @@ class TestProvisioningRetry:mock_response_200.content = msgpack.packb({"items": [{"dense": {"values": np.zeros(1024)}}]}, use_bin_type=True)with patch("sie_sdk.client.sync.httpx.Client") as mock_client:- mock_client.return_value.post = MagicMock(side_effect=[mock_response_202, mock_response_200])+ mock_client.return_value.post = MagicMock(side_effect=[mock_response_503, mock_response_200])client = SIEClient("http://localhost:8080")# No explicit wait_for_capacity -- default should be True now@@ -165,12 +191,16 @@ class TestProvisioningRetry:client.close()def test_explicit_wait_for_capacity_false_still_works(self) -> None:- """Explicitly setting wait_for_capacity=False still raises ProvisioningError on 202."""+ """Explicitly setting wait_for_capacity=False raises ProvisioningError on 503 PROVISIONING."""from sie_sdk import ProvisioningError+ from sie_sdk.client._shared import PROVISIONING_ERROR_CODEmock_response = MagicMock()- mock_response.status_code = 202- mock_response.headers = {"Retry-After": "30"}+ mock_response.status_code = 503+ mock_response.headers = {"Retry-After": "30", "content-type": "application/json"}+ mock_response.json.return_value = {+ "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}+ }with patch("sie_sdk.client.sync.httpx.Client") as mock_client:mock_client.return_value.post = MagicMock(return_value=mock_response)diff --git a/packages/sie_sdk/tests/client/test_sync.py b/packages/sie_sdk/tests/client/test_sync.pyindex 4aca5bdda..bbc82b2b6 100644--- a/packages/sie_sdk/tests/client/test_sync.py+++ b/packages/sie_sdk/tests/client/test_sync.py@@ -627,6 +627,38 @@ class TestScore:assert request_body["instruction"] == "Rank by relevance to the query"client.close()+ def test_score_converts_image_query_and_items_to_wire_format(self) -> None:+ """score() converts image query/items before msgpack serialization."""+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.content = msgpack.packb(+ {+ "model": "qwen3-vl-reranker",+ "scores": [{"item_id": "page-1", "score": 0.8, "rank": 0}],+ },+ use_bin_type=True,+ )++ query_image = b"\xff\xd8\xff\xe0query"+ item_image = b"\xff\xd8\xff\xe0item"+ query = {"text": "rocket nozzle", "images": [query_image]}+ item = {"id": "page-1", "images": [item_image]}++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = mock_response+ client = SIEClient("http://localhost:8080")+ client.score("qwen3-vl-reranker", query=query, items=[item])++ call_args = mock_client.return_value.post.call_args+ request_body = msgpack.unpackb(call_args.kwargs["content"], raw=False)+ query_wire = request_body["query"]["images"][0]+ item_wire = request_body["items"][0]["images"][0]+ assert query_wire == {"data": query_image, "format": "jpeg"}+ assert item_wire == {"data": item_image, "format": "jpeg"}+ assert query["images"][0] == query_image+ assert item["images"][0] == item_image+ client.close()+def test_score_with_query_id(self) -> None:"""score() preserves query_id in result."""mock_response = MagicMock()diff --git a/packages/sie_sdk/tests/test_bundle_utils.py b/packages/sie_sdk/tests/test_bundle_utils.pyindex ee93a9ec0..bb3b1659a 100644--- a/packages/sie_sdk/tests/test_bundle_utils.py+++ b/packages/sie_sdk/tests/test_bundle_utils.py@@ -24,8 +24,9 @@ def test_match_bundle_models_filters_by_pool(tmp_path: Path) -> None:models_dir.mkdir()_write_model(models_dir, "org/generation")- _write_model(models_dir, "org/embedding", pool="sglang-embedding")+ _write_model(models_dir, "org/embedding", pool="SGLang-Embedding")assert set(match_bundle_models(bundle_path, models_dir)) == {"org/generation", "org/embedding"}assert match_bundle_models(bundle_path, models_dir, pool_name="default") == ["org/generation"]assert match_bundle_models(bundle_path, models_dir, pool_name="sglang-embedding") == ["org/embedding"]+ assert match_bundle_models(bundle_path, models_dir, pool_name="SGLANG-EMBEDDING") == ["org/embedding"]diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex a6945032c..c7edc2773 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -32,7 +32,7 @@ sie-server serve --port 8080 --device cuda:0| Env var | Default | Effect ||--|--|--|-| `SIE_MEMORY_PRESSURE_THRESHOLD_PERCENT` | `85` | VRAM utilisation that triggers reactive LRU eviction by the pressure monitor. |+| `SIE_MEMORY_PRESSURE_THRESHOLD_PERCENT` | `95` | VRAM utilisation that triggers reactive LRU eviction by the pressure monitor. || `SIE_OOM_RECOVERY__ENABLED` | `true` | Master switch for reactive OOM recovery in the worker dispatch path (`cache_clear → evict_lru → split_batch`). || `SIE_OOM_RECOVERY__STRATEGY` | `cache_clear,evict_lru,split_batch` | Ordered recovery actions. Earlier actions tried first. || `SIE_OOM_RECOVERY__MAX_SPLIT_DEPTH` | `4` | Cap on recursive batch halving (≤16 sub-batches). |diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 4b246e3ef..84bae5929 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.4"+ "version": "0.6.5"},"paths": {"/": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex 7a6e3374e..8e48cd0e2 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.4"+version = "0.6.5"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/src/sie_server/adapters/base.py b/packages/sie_server/src/sie_server/adapters/base.pyindex 6166f2e38..25da18384 100644--- a/packages/sie_server/src/sie_server/adapters/base.py+++ b/packages/sie_server/src/sie_server/adapters/base.py@@ -61,11 +61,18 @@ class ModelAdapter(ABC):mechanism (e.g., engine.shutdown()) that fully releases memory.Main Thread Requirement:- Some adapters (e.g., SGLang) use signal handlers that only work in+ Some adapters may use parent-process signal handlers that only work inthe main thread. Set requires_main_thread = True for these adapters.The registry will run load() directly in the event loop instead ofin a thread pool, which blocks but ensures main thread execution.+ Adapter-Owned Load Timeout:+ Subprocess-backed adapters may own a cleanup-safe startup timeout. Set+ manages_own_load_timeout = True for those adapters so the registry runs+ the load + warmup marker path in the model-load executor without+ wrapping it in the generic Python wait_for timeout, which cannot kill+ the underlying thread.+Device-Aware Factory Method:Adapters can override create_for_device() to return different adapterimplementations based on device compatibility. Flash adapters inherit@@ -73,9 +80,12 @@ class ModelAdapter(ABC):properties (fallback_adapter_path, fallback_kwargs_overrides)."""- # Set to True for adapters that need main thread (e.g., SGLang signal handlers)+ # Set to True only for adapters that need parent-process main-thread execution.requires_main_thread: bool = False+ # Set to True for adapters with their own cleanup-safe load/warmup timeout.+ manages_own_load_timeout: bool = False+@classmethoddef create_for_device(cls, device: str, **kwargs: Any) -> "ModelAdapter":"""Factory method for device-aware adapter instantiation.diff --git a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.pyindex 3da2f454a..74295eb59 100644--- a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py@@ -26,6 +26,10 @@ _ERR_NO_INPUT = "Qwen3VLRerankerAdapter requires text or images input"# Chat template markers used by the reranker to structure (query, document) pairs._DEFAULT_INSTRUCTION = "Retrieve relevant documents for the query."+_SYSTEM_PROMPT = (+ "Judge whether the Document meets the requirements based on the Query and the Instruct provided. "+ 'Note that the answer can only be "yes" or "no".'+)def _build_reranker_conversation(@@ -38,35 +42,32 @@ def _build_reranker_conversation() -> list[dict[str, Any]]:"""Build chat conversation for reranking a (query, document) pair.- The reranker model expects:- system: <instruction>- user: <query content>- assistant: <document content>-- Both query and document can contain text, image, or both.+ The Qwen3-VL-Reranker reference format puts instruction, query, and+ document content in one user message. The model chat template emits vision+ placeholder tokens for images in user content, but not assistant content."""- # Build query content- query_content: list[dict[str, Any]] = []+ content: list[dict[str, Any]] = [+ {"type": "text", "text": "<Instruct>: " + instruction},+ {"type": "text", "text": "<Query>:"},+ ]if query_image is not None:- query_content.append({"type": "image", "image": query_image})+ content.append({"type": "image", "image": query_image})if query_text:- query_content.append({"type": "text", "text": query_text})- if not query_content:- query_content.append({"type": "text", "text": ""})+ content.append({"type": "text", "text": query_text})+ if not query_text and query_image is None:+ content.append({"type": "text", "text": "NULL"})- # Build document content- doc_content: list[dict[str, Any]] = []+ content.append({"type": "text", "text": "\n<Document>:"})if doc_image is not None:- doc_content.append({"type": "image", "image": doc_image})+ content.append({"type": "image", "image": doc_image})if doc_text:- doc_content.append({"type": "text", "text": doc_text})- if not doc_content:- doc_content.append({"type": "text", "text": ""})+ content.append({"type": "text", "text": doc_text})+ if not doc_text and doc_image is None:+ content.append({"type": "text", "text": "NULL"})return [- {"role": "system", "content": [{"type": "text", "text": instruction}]},- {"role": "user", "content": query_content},- {"role": "assistant", "content": doc_content},+ {"role": "system", "content": [{"type": "text", "text": _SYSTEM_PROMPT}]},+ {"role": "user", "content": content},]diff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.pyindex 1e99cdddb..12c237c00 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py@@ -51,7 +51,8 @@ class SGLangEmbeddingAdapter(BaseAdapter):- Supports last-token pooling only (standard for LLM embeddings)Note: This adapter starts SGLang as a subprocess server during load().- Signal handlers in SGLang require main thread execution.+ The child process owns its own main thread and signal handlers, so parent+ load can run in the registry's model-load executor.Example:adapter = SGLangEmbeddingAdapter(@@ -64,8 +65,10 @@ class SGLangEmbeddingAdapter(BaseAdapter):spec = AdapterSpec(inputs=("text",), outputs=("dense",), unload_fields=("_process", "_server_url", "_dense_dim"))- # SGLang uses signal handlers that require main thread execution- requires_main_thread: bool = True+ # The SGLang child process owns signal handling; parent load must not block+ # the uvicorn event loop while polling child readiness.+ requires_main_thread: bool = False+ manages_own_load_timeout: bool = Truedef _check_loaded(self) -> None:if self._server_url is None:diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 5fe3221e3..eaeb7a507 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -162,8 +162,10 @@ class SGLangGenerationAdapter(GenerationAdapter):unload_fields=("_process", "_server_url"),)- # SGLang uses signal handlers that require main thread execution.- requires_main_thread: bool = True+ # The SGLang child process owns signal handling; parent load must not block+ # the uvicorn event loop while polling child readiness.+ requires_main_thread: bool = False+ manages_own_load_timeout: bool = Truedef __init__(self,diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.pyindex 8e975841b..1e1d0c9d2 100644--- a/packages/sie_server/src/sie_server/app/app_factory.py+++ b/packages/sie_server/src/sie_server/app/app_factory.py@@ -158,6 +158,7 @@ class AppFactory:memory_config=memory_config,device=config.device,engine_config=engine_config,+ pool_name=config.pool_name,)try:# Start background services (memory monitor, idle evictor, hot reload).diff --git a/packages/sie_server/src/sie_server/app/app_state_config.py b/packages/sie_server/src/sie_server/app/app_state_config.pyindex 782f82638..82d4efd87 100644--- a/packages/sie_server/src/sie_server/app/app_state_config.py+++ b/packages/sie_server/src/sie_server/app/app_state_config.py@@ -9,6 +9,7 @@ ENV_DEVICE = "SIE_DEVICE"ENV_MODELS_DIR = "SIE_MODELS_DIR"ENV_MODEL_FILTER = "SIE_MODEL_FILTER"ENV_PRELOAD_MODELS = "SIE_PRELOAD_MODELS"+ENV_POOL = "SIE_POOL"@dataclass@@ -31,6 +32,9 @@ class AppStateConfig:preload_models: list[str] | None = None"""Optional list of model names to eagerly load at startup. If None, all models are lazy-loaded."""+ pool_name: str | None = None+ """Optional worker pool identity used by ModelRegistry pool-isolation checks."""+def save_to_env_vars(self) -> None:"""Serialize configuration to environment variables for uvicorn reload mode."""if self.models_dir:@@ -50,6 +54,11 @@ class AppStateConfig:elif ENV_PRELOAD_MODELS in os.environ:del os.environ[ENV_PRELOAD_MODELS]+ if self.pool_name:+ os.environ[ENV_POOL] = self.pool_name+ elif ENV_POOL in os.environ:+ del os.environ[ENV_POOL]+@classmethoddef from_env_vars(cls) -> AppStateConfig:"""Deserialize configuration from environment variables."""@@ -59,10 +68,12 @@ class AppStateConfig:model_filter = [m.strip() for m in model_filter_str.split(",") if m.strip()] if model_filter_str else Nonepreload_str = os.environ.get(ENV_PRELOAD_MODELS)preload_models = [m.strip() for m in preload_str.split(",") if m.strip()] if preload_str else None+ pool_name = os.environ.get(ENV_POOL) or Nonereturn cls(models_dir=models_dir,device=device,model_filter=model_filter,preload_models=preload_models,+ pool_name=pool_name,)diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.pyindex 4b8f8db50..24c1be1cf 100644--- a/packages/sie_server/src/sie_server/cli.py+++ b/packages/sie_server/src/sie_server/cli.py@@ -22,7 +22,7 @@ import typerfrom sie_sdk.bundle_utils import find_bundle_for_models, match_bundle_modelsimport sie_server-from sie_server.app.app_state_config import AppStateConfig+from sie_server.app.app_state_config import ENV_POOL, AppStateConfigfrom sie_server.core.loader import load_model_configsfrom sie_server.main import run_server@@ -76,7 +76,13 @@ def callback() -> None:"""Search Inference Engine - GPU inference server for search workloads."""-def load_bundle(bundle_name: str, bundles_dir: Path, models_dir: str | None = None) -> list[str]:+def load_bundle(+ bundle_name: str,+ bundles_dir: Path,+ models_dir: str | None = None,+ *,+ pool_name: str | None = None,+) -> list[str]:"""Load model names from a bundle file using adapter-based matching.Args:@@ -97,7 +103,7 @@ def load_bundle(bundle_name: str, bundles_dir: Path, models_dir: str | None = Noraise FileNotFoundError(msg)resolved_models_dir = Path(models_dir) if models_dir else Path(DEFAULT_MODELS_DIR)- return match_bundle_models(bundle_path, resolved_models_dir)+ return match_bundle_models(bundle_path, resolved_models_dir, pool_name=pool_name)@app.command("resolve-deps")@@ -120,6 +126,7 @@ def resolve_deps(models_path = Path(models_dir).resolve()bundles_dir = _DEFAULT_BUNDLES_DIR+ pool_name = os.environ.get(ENV_POOL) or Noneif bundle and models:typer.echo("Error: Cannot specify both --bundle and --models", err=True)@@ -134,13 +141,13 @@ def resolve_deps(resolved_bundle = bundleelse:model_list = [m.strip() for m in models.split(",") if m.strip()] # type: ignore- matched = find_bundle_for_models(model_list, bundles_dir, models_path)+ matched = find_bundle_for_models(model_list, bundles_dir, models_path, pool_name=pool_name)if not matched:typer.echo(f"Error: No bundle found covering models: {', '.join(model_list)}", err=True)raise typer.Exit(1)resolved_bundle = matched- result = collect_bundle_deps(resolved_bundle, bundles_dir, models_path, exclude_cuda=cpu)+ result = collect_bundle_deps(resolved_bundle, bundles_dir, models_path, exclude_cuda=cpu, pool_name=pool_name)if result.conflicts:if output_json:@@ -268,6 +275,7 @@ def serve(# Resolve device (auto-detect if needed)resolved_device = resolve_device(device)+ pool_name = os.environ.get(ENV_POOL) or None# Handle bundle/models filtermodel_filter: list[str] | None = None@@ -281,7 +289,7 @@ def serve(typer.echo(f"Error: Bundles directory not found: {bundles_dir}", err=True)raise typer.Exit(1)try:- model_filter = load_bundle(bundle, bundles_dir)+ model_filter = load_bundle(bundle, bundles_dir, models_dir_resolved, pool_name=pool_name)typer.echo(f"Bundle '{bundle}': {len(model_filter)} models")except FileNotFoundError as e:typer.echo(f"Error: {e}", err=True)@@ -385,6 +393,7 @@ def serve(device=resolved_device,model_filter=model_filter,preload_models=preload_models,+ pool_name=pool_name,)uvicorn_log = "debug" if verbose else log_level.strip().lower()diff --git a/packages/sie_server/src/sie_server/config/engine.py b/packages/sie_server/src/sie_server/config/engine.pyindex 311ca4ffc..a9dfc854f 100644--- a/packages/sie_server/src/sie_server/config/engine.py+++ b/packages/sie_server/src/sie_server/config/engine.py@@ -307,7 +307,7 @@ class EngineConfig(BaseSettings):memory_pressure_threshold_percent: Annotated[int,Field(ge=50, le=99, description="VRAM usage percent that triggers LRU eviction"),- ] = 85+ ] = 95idle_evict_s: Annotated[int | None,Field(@@ -315,7 +315,7 @@ class EngineConfig(BaseSettings):le=86400,description=("Unload models that have been idle (no requests) for this many seconds. "- "Additive to the 85% pressure monitor: catches cold models before they "+ "Additive to the pressure monitor: catches cold models before they ""build up and become eviction candidates under load. ""None disables (default); set ``SIE_IDLE_EVICT_S=300`` for a 5-minute TTL."),diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.pyindex 8ea5c9bcb..9b075381c 100644--- a/packages/sie_server/src/sie_server/config/model.py+++ b/packages/sie_server/src/sie_server/config/model.py@@ -15,6 +15,7 @@ OutputType = Literal["dense", "sparse", "multivector", "score", "json", "tokens"PoolingStrategy = Literal["cls", "mean", "last_token", "splade", "none"]_MODALITY_NAMES = ("text", "image", "audio", "video", "document")+_MAX_POOL_NAME_LEN = 128class InputModalities(BaseModel):@@ -428,11 +429,33 @@ class ModelConfig(BaseModel):hf_revision: str | None = Noneweights_path: Path | None = Nonepackage_backed: bool = False+ pool: str | None = Noneinputs: InputModalities = InputModalities()tasks: Tasksmax_sequence_length: int | None = Noneprofiles: dict[str, ProfileConfig]+ @model_validator(mode="after")+ def validate_pool_name(self) -> "ModelConfig":+ if self.pool is None:+ return self++ pool = self.pool.strip().lower()+ if not pool:+ self.pool = None+ return self++ if (+ len(pool) > _MAX_POOL_NAME_LEN+ or pool == "_default"+ or not all(c.isascii() and (c.isalnum() or c in "_-") for c in pool)+ ):+ msg = "pool must use only [A-Za-z0-9_-], be at most 128 chars, and not be '_default'"+ raise ValueError(msg)++ self.pool = pool+ return self+@model_validator(mode="after")def validate_weight_source(self) -> "ModelConfig":if self.package_backed:diff --git a/packages/sie_server/src/sie_server/core/deps.py b/packages/sie_server/src/sie_server/core/deps.pyindex 14b6b2832..4b7709217 100644--- a/packages/sie_server/src/sie_server/core/deps.py+++ b/packages/sie_server/src/sie_server/core/deps.py@@ -117,6 +117,7 @@ def collect_bundle_deps(models_dir: Path,*,exclude_cuda: bool = False,+ pool_name: str | None = None,) -> BundleDepResult:"""Collect all dependencies for a bundle from its deps section.@@ -177,7 +178,7 @@ def collect_bundle_deps(requirements.append(pkg)# Discover model names that match this bundle's adapters (for the result)- model_names = match_bundle_models(bundle_path, models_dir)+ model_names = match_bundle_models(bundle_path, models_dir, pool_name=pool_name)return BundleDepResult(requirements=requirements,diff --git a/packages/sie_server/src/sie_server/core/memory.py b/packages/sie_server/src/sie_server/core/memory.pyindex 7291342bc..cd963b84a 100644--- a/packages/sie_server/src/sie_server/core/memory.py+++ b/packages/sie_server/src/sie_server/core/memory.py@@ -189,7 +189,7 @@ class MemoryConfig:# Memory pressure threshold (0.0 to 1.0)# Evict LRU model when usage exceeds this ratio- pressure_threshold: float = 0.85+ pressure_threshold: float = 0.95# Minimum free memory to maintain (in bytes)# Alternative to ratio-based thresholddiff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.pyindex 11ceb69f3..3329f8548 100644--- a/packages/sie_server/src/sie_server/core/model_loader.py+++ b/packages/sie_server/src/sie_server/core/model_loader.py@@ -365,7 +365,6 @@ class ModelLoader:LoadedModel containing the loaded state."""if adapter.requires_main_thread:- # SGLang and similar adapters need main thread for signal handlerslogger.info("Loading '%s' in main thread (adapter.requires_main_thread=True)",name,@@ -398,23 +397,27 @@ class ModelLoader:cannot register stale preprocessors or set ``sie_model_loaded=1``for a model the registry has marked failed.- ``requires_main_thread`` adapters (e.g. SGLang) are routed through- :meth:`_load_main_thread` instead, which intentionally does NOT- apply this timeout — those adapters have their own bounded- subprocess startup timeout and double-bounding causes spurious- mid-startup failures.+ Adapters that set ``manages_own_load_timeout`` are also run in this+ executor, but without the generic ``wait_for`` wrapper. That keeps the+ event loop responsive while preserving adapter-owned cleanup semantics+ for subprocess-backed loaders whose startup timeout can terminate the+ child process cleanly."""def _deserialize_and_warmup() -> None:logger.info("Loading model '%s' onto %s", name, device)_run_load_with_markers(name, device, adapter)- await self._run_with_timeout(- stage="load",- name=name,- func=_deserialize_and_warmup,- args=(),- )+ if getattr(adapter, "manages_own_load_timeout", False) is True:+ loop = asyncio.get_running_loop()+ await loop.run_in_executor(self._load_executor, _deserialize_and_warmup)+ else:+ await self._run_with_timeout(+ stage="load",+ name=name,+ func=_deserialize_and_warmup,+ args=(),+ )# Registry-state side effects (preprocessor/postprocessor# registration, metrics, worker creation, LoRA preloading) run# OUTSIDE the executor so an orphan thread from a wait_for@@ -501,11 +504,11 @@ class ModelLoader:) -> LoadedModel:"""Load adapter in main thread (for adapters with signal handlers).- This blocks the event loop but is required for adapters like SGLang- that use Python signal handlers which only work in the main thread.+ This blocks the event loop and is reserved for adapters that truly need+ parent-process main-thread execution.- Adapter-internal startup timeouts (e.g. SGLang's subprocess health- poll) are rewrapped into :class:`ModelLoadTimeoutError` so the+ Adapter-internal startup timeouts are rewrapped into+ :class:`ModelLoadTimeoutError` so theregistry's failure classifier buckets them as``LoadErrorClass.TIMEOUT`` (30 s cooldown) rather than``UNKNOWN`` (permanent) — consistent with the executor path.@@ -524,22 +527,7 @@ class ModelLoader:try:_run_load_with_markers(name, device, adapter)except RuntimeError as exc:- # SGLang raises ``RuntimeError("SGLang server failed to start- # within timeout")`` from ``_wait_for_server``. Pattern-match- # on the message; narrow enough to not bucket genuine runtime- # failures as timeouts. Other adapters that grow their own- # startup timeouts should follow the same convention.- msg = str(exc).lower()- if "failed to start within timeout" in msg or "startup timeout" in msg:- elapsed = time.monotonic() - started- increment_model_load_timeout(name, "load")- logger.error(- "Main-thread adapter startup timeout: model=%s elapsed_s=%.1f msg=%s",- name,- elapsed,- exc,- )- raise ModelLoadTimeoutError(model=name, stage="load", elapsed_s=elapsed, timeout_s=elapsed) from exc+ _raise_if_adapter_startup_timeout(name, started, exc)raisereturn self._finish_load(name, device, adapter, config)@@ -728,13 +716,41 @@ def _run_load_with_markers(name: str, device: str, adapter: ModelAdapter) -> Nonconsistently across adapters (the resulting ``warmup_s`` is just ~0)."""logger.info("Model deserialize start: '%s' on %s", name, device)- adapter.load(device)+ started = time.monotonic()+ try:+ adapter.load(device)+ except RuntimeError as exc:+ _raise_if_adapter_startup_timeout(name, started, exc)+ raiselogger.info("Model deserialize end: '%s' on %s", name, device)logger.info("Model warmup start: '%s' on %s", name, device)adapter.warmup()logger.info("Model warmup end: '%s' on %s", name, device)+def _raise_if_adapter_startup_timeout(name: str, started: float, exc: RuntimeError) -> None:+ """Reclassify adapter-owned startup timeout errors.++ SGLang raises ``RuntimeError("SGLang server failed to start within timeout")``+ from its subprocess health poll. Pattern-match on the message; narrow enough+ to not bucket genuine runtime failures as timeouts. Other adapters that grow+ their own startup timeouts should follow the same convention.+ """+ msg = str(exc).lower()+ if "failed to start within timeout" not in msg and "startup timeout" not in msg:+ return++ elapsed = time.monotonic() - started+ increment_model_load_timeout(name, "load")+ logger.error(+ "Adapter startup timeout: model=%s elapsed_s=%.1f msg=%s",+ name,+ elapsed,+ exc,+ )+ raise ModelLoadTimeoutError(model=name, stage="load", elapsed_s=elapsed, timeout_s=elapsed) from exc++def _merge_adaptive_params(engine: AdaptiveBatchingParams,profile: ProfileAdaptiveBatching | None,diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex 8fda0348f..14d4c46a7 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport asyncioimport loggingimport time+from collections.abc import Iterablefrom pathlib import Pathfrom typing import Any@@ -100,7 +101,7 @@ class ModelRegistry:self._model_filter = set(model_filter) if model_filter else Noneself._device = deviceself._enable_hot_reload = enable_hot_reload- self._pool_name = pool_name+ self._pool_name = pool_name.strip().lower() if pool_name else Noneself._configs: dict[str, ModelConfig] = {}self._model_dirs: dict[str, Path] = {}self._loaded: dict[str, LoadedModel] = {}@@ -237,6 +238,18 @@ class ModelRegistry:else:self._configs = all_configs+ if self._pool_name is not None:+ before_count = len(self._configs)+ self._configs = {name: config for name, config in self._configs.items() if self.accepts_config_pool(config)}+ filtered_count = before_count - len(self._configs)+ if filtered_count:+ logger.info(+ "Pool filter applied for SIE_POOL=%s: %d/%d models available",+ self._pool_name,+ len(self._configs),+ before_count,+ )+# Pool isolation. With the post-filter set in hand,# reject mixed generation/non-generation pools loudly. The# check is best-effort when ``pool_name`` is None (tests).@@ -1019,6 +1032,13 @@ class ModelRegistry:config: The model configuration.model_dir: Optional directory for custom adapter resolution."""+ if not self.accepts_config_pool(config):+ if config.sie_id in self._configs:+ del self._configs[config.sie_id]+ self._loader.update_configs(self._configs)+ self._failed.pop(config.sie_id, None)+ self._config_version += 1+ return# Pool isolation. Validate before mutating# ``self._configs`` so a rejected add does not leave the# registry in a half-mutated state. ``None`` pool skips the@@ -1047,6 +1067,69 @@ class ModelRegistry:self._failed.pop(config.sie_id, None)self._config_version += 1+ async def replace_configs_async(+ self,+ configs: Iterable[ModelConfig],+ model_dir: Path | None = None,+ ) -> set[str]:+ """Replace the registry config set from an authoritative snapshot.++ Used by worker-sidecar export reconciliation. Removed or changed+ loaded models are unloaded under the registry load lock before the+ config map is swapped, so a worker cannot keep serving a model that+ disappeared from the authoritative bundle export.+ """+ new_configs: dict[str, ModelConfig] = {}+ for config in configs:+ if not self.accepts_config_pool(config):+ continue+ if config.sie_id in new_configs:+ msg = f"duplicate model config in authoritative snapshot: {config.sie_id}"+ raise ValueError(msg)+ new_configs[config.sie_id] = config++ if self._pool_name is not None:+ accepted: dict[str, ModelConfig] = {}+ for name, config in new_configs.items():+ validate_pool_isolation(+ candidate_name=name,+ candidate_config=config,+ existing_configs=accepted,+ pool_name=self._pool_name,+ )+ accepted[name] = config+ for name, config in new_configs.items():+ validate_no_legacy_scalar_lora_id(name=name, config=config)++ lock = self._get_load_lock()+ async with lock:+ removed = set(self._configs) - set(new_configs)+ changed = {name for name, config in new_configs.items() if self._configs.get(name) != config}+ invalidated = removed | changed++ for name in sorted(invalidated):+ if name in self._loaded:+ await self._do_unload(name)++ self._configs = dict(new_configs)+ self._loader.update_configs(self._configs)+ if self._model_filter is not None:+ self._model_filter = set(new_configs)+ self._model_dirs = {name: path for name, path in self._model_dirs.items() if name in new_configs}+ if model_dir is not None:+ for name in new_configs:+ self._model_dirs[name] = model_dir+ for name in invalidated:+ self._failed.pop(name, None)+ self._config_version += 1+ return invalidated++ def accepts_config_pool(self, config: ModelConfig) -> bool:+ if self._pool_name is None:+ return True+ config_pool = (config.pool or "default").strip().lower()+ return config_pool == self._pool_name+def get_model_info(self, name: str) -> dict[str, Any]:"""Get information about a model.diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.pyindex 2390cab23..ab62e4bee 100644--- a/packages/sie_server/src/sie_server/ipc_server.py+++ b/packages/sie_server/src/sie_server/ipc_server.py@@ -23,6 +23,7 @@ from sie_server.ipc_types import (METHOD_PROCESS_EXTRACT_BATCH,METHOD_PROCESS_GENERATE,METHOD_PROCESS_SCORE_BATCH,+ METHOD_REPLACE_MODEL_CONFIGS,METHOD_RUN_BATCH,METHOD_SIGNAL_GENERATE_CANCEL,METHOD_WORKER_CAPABILITIES,@@ -39,6 +40,8 @@ from sie_server.ipc_types import (ProcessExtractBatchRequest,ProcessGenerateRequest,ProcessScoreBatchRequest,+ ReplaceModelConfigsRequest,+ ReplaceModelConfigsResponse,ResponseEnvelope,RunBatchRequest,SignalGenerateCancelRequest,@@ -430,6 +433,8 @@ class IpcServer:resp_body = await self._handle_run_batch(msgspec.convert(body, RunBatchRequest))elif method == METHOD_APPLY_MODEL_CONFIG:resp_body = self._handle_apply_model_config(msgspec.convert(body, ApplyModelConfigRequest))+ elif method == METHOD_REPLACE_MODEL_CONFIGS:+ resp_body = await self._handle_replace_model_configs(msgspec.convert(body, ReplaceModelConfigsRequest))elif method == METHOD_SIGNAL_GENERATE_CANCEL:resp_body = await self._handle_signal_generate_cancel(msgspec.convert(body, SignalGenerateCancelRequest)@@ -522,6 +527,12 @@ class IpcServer:def _handle_apply_model_config(self, req: ApplyModelConfigRequest) -> ApplyModelConfigResponse:return self._executor.apply_model_config(req)+ async def _handle_replace_model_configs(+ self,+ req: ReplaceModelConfigsRequest,+ ) -> ReplaceModelConfigsResponse:+ return await self._executor.replace_model_configs(req)+def _handle_worker_capabilities(self, _req: WorkerCapabilitiesRequest) -> WorkerCapabilitiesResponse:generation_models: list[str] = []try:diff --git a/packages/sie_server/src/sie_server/ipc_types.py b/packages/sie_server/src/sie_server/ipc_types.pyindex c2c33d615..2bce92b67 100644--- a/packages/sie_server/src/sie_server/ipc_types.py+++ b/packages/sie_server/src/sie_server/ipc_types.py@@ -45,6 +45,7 @@ METHOD_SIGNAL_GENERATE_CANCEL = "SignalGenerateCancel"# Direct ``sie-server`` HTTP execution does not use this IPC boundary.METHOD_RUN_BATCH = "RunBatch"METHOD_APPLY_MODEL_CONFIG = "ApplyModelConfig"+METHOD_REPLACE_MODEL_CONFIGS = "ReplaceModelConfigs"METHOD_DRAIN = "Drain"@@ -162,6 +163,25 @@ class ApplyModelConfigResponse(msgspec.Struct):config_version: int = 0+class ReplaceModelConfigEntry(msgspec.Struct):+ model_id: str+ model_config: str+++class ReplaceModelConfigsRequest(msgspec.Struct):+ bundle_id: str+ epoch: int+ bundle_config_hash: str+ models: list[ReplaceModelConfigEntry]+++class ReplaceModelConfigsResponse(msgspec.Struct):+ applied: bool+ bundle_config_hash: str+ config_version: int = 0+ applied_models: list[str] = msgspec.field(default_factory=list)++# -----------------------------------------------------------------------------# ProcessGenerate — streaming generation over IPC# -----------------------------------------------------------------------------diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 85fb3a031..4bdcc2e85 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -31,6 +31,8 @@ from sie_server.ipc_types import (ProcessScoreBatchRequest,RawOutput,ReadinessState,+ ReplaceModelConfigsRequest,+ ReplaceModelConfigsResponse,ScoreBatchItem,ScoreOutputRaw,SparseOutput,@@ -527,6 +529,43 @@ class QueueExecutor:return ""return compute_bundle_config_hash_cached(self._registry, bundle_id)+ async def replace_model_configs(self, req: ReplaceModelConfigsRequest) -> ReplaceModelConfigsResponse:+ """Replace the bundle-scoped registry view from a full export snapshot."""+ if not req.bundle_id:+ msg = "bundle_id is required"+ raise ValueError(msg)++ configs: list[ModelConfig] = []+ for entry in req.models:+ if not entry.model_config.strip():+ msg = "model_config is required"+ raise ValueError(msg)++ raw = yaml.safe_load(entry.model_config)+ if not isinstance(raw, dict):+ msg = "model_config must decode to a YAML mapping"+ raise ValueError(msg)++ model_config = ModelConfig(**raw)+ if entry.model_id and model_config.sie_id != entry.model_id:+ msg = f"model_id mismatch: export={entry.model_id!r} config={model_config.sie_id!r}"+ raise ValueError(msg)+ configs.append(model_config)++ invalidated = await self._registry.replace_configs_async(configs)+ for model_id in invalidated:+ self.invalidate_model_descriptor(model_id)+ for config in configs:+ self.invalidate_model_descriptor(config.sie_id)+ bundle_hash = compute_bundle_config_hash_cached(self._registry, req.bundle_id)+ applied_models = sorted(self._registry.get_configs_snapshot(req.bundle_id))+ return ReplaceModelConfigsResponse(+ applied=True,+ bundle_config_hash=bundle_hash,+ config_version=int(getattr(self._registry, "_config_version", 0)),+ applied_models=applied_models,+ )+# -- Readiness ---------------------------------------------------------async def ensure_model_ready(self, model_id: str) -> ReadinessState:@@ -538,6 +577,9 @@ class QueueExecutor:- ``loading_in_progress``: NAK with longer delay (already loading)- ``retry_later``: NAK with base delay (unknown error path)"""+ if not self._registry.has_model(model_id):+ return "retry_later"+if self._registry.is_loaded(model_id):return "ready"diff --git a/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.py b/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.pynew file mode 100644index 000000000..fd0c3f450--- /dev/null+++ b/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.py@@ -0,0 +1,95 @@+from __future__ import annotations++from typing import Any++from sie_server.adapters.qwen3_vl_reranker import _build_reranker_conversation++_IMAGE_PLACEHOLDER = "<|vision_start|><|image_pad|><|vision_end|>"+++def _render_user_image_tokens(messages: list[dict[str, Any]]) -> str:+ """Render the image-token behavior relevant to Qwen3-VL-Reranker's template."""+ tokens = []+ for message in messages:+ if message.get("role") != "user":+ continue+ content = message.get("content", [])+ if not isinstance(content, list):+ continue+ for part in content:+ if isinstance(part, dict) and part.get("type") == "image":+ tokens.append(_IMAGE_PLACEHOLDER)+ return "".join(tokens)+++def test_document_image_is_in_user_message_for_vision_token_rendering() -> None:+ """Document images render in user content so Qwen emits image placeholders."""+ doc_image: Any = object()++ conversation = _build_reranker_conversation(+ query_text="solid propellant rocket nozzle cross-section",+ doc_image=doc_image,+ instruction="Retrieve images or text relevant to the user's query.",+ )++ assert [message["role"] for message in conversation] == ["system", "user"]+ assert _render_user_image_tokens(conversation).count(_IMAGE_PLACEHOLDER) == 1+ assert [+ part["image"]+ for message in conversation+ if message["role"] == "user"+ for part in message["content"]+ if isinstance(part, dict) and part.get("type") == "image"+ ] == [doc_image]+++def test_non_empty_query_with_image_document_places_image_after_document_marker() -> None:+ """Document images stay under the document section, not the query section."""+ doc_image: Any = object()++ conversation = _build_reranker_conversation(+ query_text="solid propellant rocket nozzle cross-section",+ doc_image=doc_image,+ instruction="Retrieve images or text relevant to the user's query.",+ )++ user_content = conversation[1]["content"]+ text_parts = [part["text"] for part in user_content if isinstance(part, dict) and part.get("type") == "text"]+ document_marker_index = next(+ idx+ for idx, part in enumerate(user_content)+ if isinstance(part, dict) and part.get("type") == "text" and part.get("text") == "\n<Document>:"+ )+ image_index = next(+ idx+ for idx, part in enumerate(user_content)+ if isinstance(part, dict) and part.get("type") == "image" and part.get("image") is doc_image+ )++ assert text_parts == [+ "<Instruct>: Retrieve images or text relevant to the user's query.",+ "<Query>:",+ "solid propellant rocket nozzle cross-section",+ "\n<Document>:",+ ]+ assert image_index > document_marker_index+ assert _render_user_image_tokens(conversation).count(_IMAGE_PLACEHOLDER) == 1+++def test_empty_query_or_document_side_uses_null_placeholder() -> None:+ """Empty query or document sides use the upstream reranker NULL sentinel."""+ conversation = _build_reranker_conversation(+ doc_text="Cross-section drawing of a solid propellant rocket motor nozzle.",+ instruction="Retrieve relevant documents for the query.",+ )++ user_content = conversation[1]["content"]+ rendered_text = [part["text"] for part in user_content if isinstance(part, dict) and part.get("type") == "text"]++ assert rendered_text == [+ "<Instruct>: Retrieve relevant documents for the query.",+ "<Query>:",+ "NULL",+ "\n<Document>:",+ "Cross-section drawing of a solid propellant rocket motor nozzle.",+ ]diff --git a/packages/sie_server/tests/adapters/test_sglang.py b/packages/sie_server/tests/adapters/test_sglang.pyindex a649f61d2..0d9d6c089 100644--- a/packages/sie_server/tests/adapters/test_sglang.py+++ b/packages/sie_server/tests/adapters/test_sglang.py@@ -35,6 +35,10 @@ class TestSGLangEmbeddingAdapter:assert caps.inputs == ["text"]assert caps.outputs == ["dense"]+ def test_load_contract_flags(self) -> None:+ assert SGLangEmbeddingAdapter.requires_main_thread is False+ assert SGLangEmbeddingAdapter.manages_own_load_timeout is True+def test_dims_before_load_returns_none(self) -> None:"""Dims returns None before first encode."""adapter = SGLangEmbeddingAdapter("test-model")diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex 8c360ed57..98931dbec 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -46,6 +46,11 @@ def test_capabilities_declare_tokens(adapter) -> None:assert caps.outputs == ["tokens"]+def test_load_contract_flags() -> None:+ assert SGLangGenerationAdapter.requires_main_thread is False+ assert SGLangGenerationAdapter.manages_own_load_timeout is True++def test_unloaded_generate_raises(adapter) -> None:# ``generate`` is now an async generator function; the loaded-check# fires when we first try to drive the iterator, not at call time.diff --git a/packages/sie_server/tests/app/test_app_factory.py b/packages/sie_server/tests/app/test_app_factory.pyindex 7a6515f9b..74960a80e 100644--- a/packages/sie_server/tests/app/test_app_factory.py+++ b/packages/sie_server/tests/app/test_app_factory.py@@ -273,6 +273,7 @@ class TestPreloadModelsEnvRoundTrip:monkeypatch.delenv("SIE_MODELS_DIR", raising=False)monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)monkeypatch.delenv("SIE_DEVICE", raising=False)+ monkeypatch.delenv("SIE_POOL", raising=False)config = AppStateConfig(preload_models=["model-a", "model-b"])config.save_to_env_vars()@@ -285,11 +286,65 @@ class TestPreloadModelsEnvRoundTrip:monkeypatch.delenv("SIE_MODELS_DIR", raising=False)monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)monkeypatch.delenv("SIE_DEVICE", raising=False)+ monkeypatch.delenv("SIE_POOL", raising=False)config = AppStateConfig(preload_models=None)config.save_to_env_vars()restored = AppStateConfig.from_env_vars()assert restored.preload_models is None+ assert restored.pool_name is None++ def test_pool_name_env_round_trip(self, monkeypatch) -> None:+ """SIE_POOL survives save_to_env_vars / from_env_vars cycle."""+ monkeypatch.delenv("SIE_PRELOAD_MODELS", raising=False)+ monkeypatch.delenv("SIE_MODELS_DIR", raising=False)+ monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)+ monkeypatch.delenv("SIE_DEVICE", raising=False)+ monkeypatch.delenv("SIE_POOL", raising=False)++ config = AppStateConfig(pool_name="customer-a")+ config.save_to_env_vars()+ restored = AppStateConfig.from_env_vars()+ assert restored.pool_name == "customer-a"+++class TestModelRegistryConfig:+ @pytest.mark.asyncio+ async def test_model_registry_receives_pool_name(self, monkeypatch: pytest.MonkeyPatch) -> None:+ created_kwargs: dict[str, Any] = {}++ class FakeRegistry:+ async def start_memory_monitor(self) -> None:+ pass++ async def start_idle_evictor(self) -> None:+ pass++ async def start_hot_reload(self) -> None:+ pass++ async def stop_memory_monitor(self) -> None:+ pass++ async def stop_idle_evictor(self) -> None:+ pass++ async def stop_hot_reload(self) -> None:+ pass++ async def unload_all_async(self) -> None:+ pass++ def fake_model_registry(**kwargs: Any) -> FakeRegistry:+ created_kwargs.update(kwargs)+ return FakeRegistry()++ monkeypatch.setattr("sie_server.app.app_factory.ModelRegistry", fake_model_registry)++ async with AppFactory._model_registry(AppStateConfig(pool_name="pool-a")):+ pass++ assert created_kwargs["pool_name"] == "pool-a"class TestConfigureTorchThreads:diff --git a/packages/sie_server/tests/config/test_config.py b/packages/sie_server/tests/config/test_config.pyindex 2f2a69f17..5d533f2f9 100644--- a/packages/sie_server/tests/config/test_config.py+++ b/packages/sie_server/tests/config/test_config.py@@ -31,7 +31,7 @@ class TestEngineConfig:assert config.coalesce_ms == 15.0assert config.coalesce_ratio == 0.5assert config.max_concurrent_requests == 512- assert config.memory_pressure_threshold_percent == 85+ assert config.memory_pressure_threshold_percent == 95assert config.max_loras_per_model == 10assert config.preprocessor_workers == 4assert config.attention_backend == "auto"@@ -164,6 +164,7 @@ def _make_config(max_sequence_length: int | None = None,compute_precision: str | None = None,profiles: dict[str, ProfileConfig] | None = None,+ pool: str | None = None,) -> ModelConfig:encode = Noneif any(dim is not None for dim in (dense_dim, sparse_dim, multivector_dim)):@@ -190,6 +191,7 @@ def _make_config(hf_id=hf_id,weights_path=weights_path,tasks=tasks,+ pool=pool,max_sequence_length=max_sequence_length,profiles=profiles,)@@ -331,6 +333,16 @@ class TestModelConfig:unknown_field="value", # type: ignore)+ def test_pool_field_normalized(self) -> None:+ """ModelConfig accepts pool assignment and canonicalizes casing."""+ config = _make_config(pool="Customer-A")+ assert config.pool == "customer-a"++ def test_pool_field_rejects_invalid_subject_token(self) -> None:+ """Model pool names must be safe for routing labels and subjects."""+ with pytest.raises(ValidationError, match="pool must use only"):+ _make_config(pool="customer.a")+def test_inputs_default(self) -> None:"""Default inputs is text-only."""config = _make_config()diff --git a/packages/sie_server/tests/core/test_lora_generation_exclusion.py b/packages/sie_server/tests/core/test_lora_generation_exclusion.pyindex c9157351e..842eeaf73 100644--- a/packages/sie_server/tests/core/test_lora_generation_exclusion.py+++ b/packages/sie_server/tests/core/test_lora_generation_exclusion.py@@ -94,6 +94,11 @@ def _encode_config()+def _with_pool(config: ModelConfig, pool: str) -> ModelConfig:+ config.pool = pool+ return config++def _gen_config_multi_profile(sie_id: str = "Qwen/Qwen3-4B-Instruct-2507",*,@@ -230,15 +235,15 @@ class TestRegistryHook:def test_add_config_generation_with_scalar_lora_id_rejects(self) -> None:registry = ModelRegistry(pool_name="p1")with pytest.raises(LegacyScalarLoraIdError):- registry.add_config(_gen_config(lora_id="org/qwen-lora"))+ registry.add_config(_with_pool(_gen_config(lora_id="org/qwen-lora"), "p1"))def test_add_config_generation_without_scalar_lora_id_accepted(self) -> None:registry = ModelRegistry(pool_name="p1")- registry.add_config(_gen_config())+ registry.add_config(_with_pool(_gen_config(), "p1"))def test_add_config_encode_with_scalar_lora_id_accepted(self) -> None:registry = ModelRegistry(pool_name="p1")- registry.add_config(_encode_config(lora_id="org/bge-lora"))+ registry.add_config(_with_pool(_encode_config(lora_id="org/bge-lora"), "p1"))def test_validator_fires_without_pool_name(self) -> None:"""Legacy scalar check is not pool-scoped — fires when SIE_POOL unset."""@@ -249,7 +254,7 @@ class TestRegistryHook:def test_failed_add_does_not_mutate_state(self) -> None:registry = ModelRegistry(pool_name="p1")try:- registry.add_config(_gen_config(lora_id="org/qwen-lora"))+ registry.add_config(_with_pool(_gen_config(lora_id="org/qwen-lora"), "p1"))except LegacyScalarLoraIdError:passassert "Qwen/Qwen3-4B-Instruct-2507" not in registry.model_namesdiff --git a/packages/sie_server/tests/core/test_memory.py b/packages/sie_server/tests/core/test_memory.pyindex 4ddb0a811..30bf3b1b4 100644--- a/packages/sie_server/tests/core/test_memory.py+++ b/packages/sie_server/tests/core/test_memory.py@@ -140,7 +140,7 @@ class TestMemoryConfig:"""Test default configuration values."""config = MemoryConfig()- assert config.pressure_threshold == 0.85+ assert config.pressure_threshold == 0.95assert config.min_free_bytes is Noneassert config.proactive_eviction is True@@ -308,6 +308,25 @@ class TestMemoryManager:assert manager.check_pressure() is True+ def test_default_threshold_tolerates_sglang_static_pool_overhead(self) -> None:+ """Default threshold stays above 85% static pools plus normal overhead."""+ manager = MemoryManager(device="cpu")++ manager._tracker = MagicMock()+ manager._tracker.get_stats.return_value = MemoryStats(+ used_bytes=866,+ total_bytes=1000,+ device_type="cpu",+ )+ assert manager.check_pressure() is False++ manager._tracker.get_stats.return_value = MemoryStats(+ used_bytes=96,+ total_bytes=100,+ device_type="cpu",+ )+ assert manager.check_pressure() is True+def test_check_pressure_min_free_bytes(self) -> None:"""Test pressure check with min_free_bytes threshold."""manager = MemoryManager(@@ -327,8 +346,8 @@ class TestMemoryManager:# Mock high memory usagemock_stats = MemoryStats(- used_bytes=9 * (1024**3),- total_bytes=10 * (1024**3),+ used_bytes=96,+ total_bytes=100,device_type="cpu",)manager._tracker = MagicMock()@@ -363,8 +382,8 @@ class TestMemoryManager:# Mock high memory usagemock_stats = MemoryStats(- used_bytes=9 * (1024**3),- total_bytes=10 * (1024**3),+ used_bytes=96,+ total_bytes=100,device_type="cpu",)manager._tracker = MagicMock()diff --git a/packages/sie_server/tests/core/test_model_load_timeout.py b/packages/sie_server/tests/core/test_model_load_timeout.pyindex 507d6797f..4cfd2134b 100644--- a/packages/sie_server/tests/core/test_model_load_timeout.py+++ b/packages/sie_server/tests/core/test_model_load_timeout.py@@ -17,11 +17,13 @@ from __future__ import annotationsimport asyncioimport os+import threadingimport timefrom concurrent.futures import ThreadPoolExecutorfrom unittest.mock import patchimport pytest+from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasksfrom sie_server.core.hf_env import set_hf_default_timeoutsfrom sie_server.core.load_errors import (LoadErrorClass,@@ -48,6 +50,20 @@ def _make_loader(timeout_s: float | None = None) -> ModelLoader:)+def _make_embedding_config(name: str = "t") -> ModelConfig:+ return ModelConfig(+ sie_id=name,+ hf_id=f"org/{name}",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=8))),+ profiles={+ "default": ProfileConfig(+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",+ max_batch_tokens=8,+ )+ },+ )++class TestResolveLoadTimeout:"""``_resolve_load_timeout`` precedence and parsing."""@@ -313,6 +329,74 @@ class TestRegistryIntegration:"orphan thread mutated MODEL_LOADED gauge — _finish_load must not run from the executor thread")+ async def test_adapter_owned_timeout_load_runs_in_executor_without_generic_wait_for(self) -> None:+ """Subprocess-backed adapters own child cleanup and startup timeout.++ They still need to load away from the event loop, but wrapping them in+ the generic ``wait_for`` can orphan a still-loading subprocess. This+ test proves the adapter-owned path runs in the model-load executor and+ is not cut off by ``SIE_MODEL_LOAD_TIMEOUT_S``.+ """+ from unittest.mock import MagicMock++ loader = _make_loader(timeout_s=0.01)+ loop = asyncio.get_running_loop()+ loop_thread_id = threading.get_ident()+ load_started = asyncio.Event()+ release_load = threading.Event()+ load_thread_id: int | None = None++ def _slow_load(device: str) -> None:+ nonlocal load_thread_id+ load_thread_id = threading.get_ident()+ loop.call_soon_threadsafe(load_started.set)+ if not release_load.wait(timeout=1.0):+ raise AssertionError("test bug: load was not released")++ adapter = MagicMock()+ adapter.load.side_effect = _slow_load+ adapter.warmup.return_value = None+ adapter.requires_main_thread = False+ adapter.manages_own_load_timeout = True+ adapter.get_preprocessor.return_value = None+ adapter.get_postprocessors.return_value = None+ adapter.memory_footprint.return_value = 0+ adapter.supports_lora.return_value = False++ started = time.monotonic()+ load_task = asyncio.create_task(+ loader.load_and_register_async("managed", "cpu", adapter, _make_embedding_config("managed"))+ )+ try:+ await asyncio.wait_for(load_started.wait(), timeout=0.5)++ assert load_started.is_set()+ assert time.monotonic() - started < 0.25+ assert not load_task.done()+ finally:+ release_load.set()++ loaded = await asyncio.wait_for(load_task, timeout=1.0)++ assert loaded.adapter is adapter+ assert load_thread_id is not None+ assert load_thread_id != loop_thread_id++ async def test_adapter_owned_startup_timeout_classifies_from_executor(self) -> None:+ from unittest.mock import MagicMock++ loader = _make_loader(timeout_s=0.01)+ adapter = MagicMock()+ adapter.load.side_effect = RuntimeError("SGLang server failed to start within timeout")+ adapter.warmup.return_value = None+ adapter.requires_main_thread = False+ adapter.manages_own_load_timeout = True++ with pytest.raises(ModelLoadTimeoutError) as exc_info:+ await loader.load_and_register_async("sg", "cuda:0", adapter, _make_embedding_config("sg"))++ assert exc_info.value.stage == "load"+async def test_sglang_startup_timeout_classifies_as_timeout(self) -> None:"""Regression: ``_load_main_thread`` rewraps SGLang's``RuntimeError('SGLang server failed to start within timeout')``diff --git a/packages/sie_server/tests/core/test_pool_isolation.py b/packages/sie_server/tests/core/test_pool_isolation.pyindex 75dc282e4..e64093c9e 100644--- a/packages/sie_server/tests/core/test_pool_isolation.py+++ b/packages/sie_server/tests/core/test_pool_isolation.py@@ -8,6 +8,7 @@ config-load and at :meth:`ModelRegistry.add_config` time.from __future__ import annotationsimport pytest+import yamlfrom sie_server.config.model import (EmbeddingDim,EncodeTask,@@ -57,6 +58,16 @@ def _encode_config(sie_id: str = "BAAI/bge-m3") -> ModelConfig:)+def _with_pool(config: ModelConfig, pool: str) -> ModelConfig:+ config.pool = pool+ return config+++def _write_config(models_dir, config: ModelConfig) -> None:+ path = models_dir / f"{config.sie_id.replace('/', '__')}.yaml"+ path.write_text(yaml.safe_dump(config.model_dump(mode="json", exclude_none=True), sort_keys=False))++class TestIsGenerationModel:def test_gen_model_detected(self) -> None:assert is_generation_model(_gen_config()) is True@@ -135,15 +146,15 @@ class TestValidatePoolIsolation:class TestRegistryHook:def test_add_config_gen_then_encode_rejects(self, tmp_path: object) -> None:registry = ModelRegistry(pool_name="p1")- registry.add_config(_gen_config())+ registry.add_config(_with_pool(_gen_config(), "p1"))with pytest.raises(PoolIsolationError):- registry.add_config(_encode_config())+ registry.add_config(_with_pool(_encode_config(), "p1"))def test_add_config_encode_then_gen_rejects(self) -> None:registry = ModelRegistry(pool_name="p1")- registry.add_config(_encode_config())+ registry.add_config(_with_pool(_encode_config(), "p1"))with pytest.raises(PoolIsolationError):- registry.add_config(_gen_config())+ registry.add_config(_with_pool(_gen_config(), "p1"))def test_add_config_no_pool_skips_validator(self) -> None:"""When pool_name is None (tests/no-cluster), validator is skipped."""@@ -153,14 +164,47 @@ class TestRegistryHook:def test_add_config_same_task_class_ok(self) -> None:registry = ModelRegistry(pool_name="p1")- registry.add_config(_gen_config("qwen-a"))- registry.add_config(_gen_config("qwen-b")) # should not raise+ registry.add_config(_with_pool(_gen_config("qwen-a"), "p1"))+ registry.add_config(_with_pool(_gen_config("qwen-b"), "p1")) # should not raise++ def test_add_config_skips_different_model_pool(self) -> None:+ registry = ModelRegistry(pool_name="customer-a")+ default_config = _encode_config("default/model")+ tenant_config = _encode_config("tenant/model")+ tenant_config.pool = "customer-a"++ registry.add_config(default_config)+ registry.add_config(tenant_config)++ assert "default/model" not in registry.model_names+ assert "tenant/model" in registry.model_names++ def test_load_configs_from_dir_filters_different_model_pool(self, tmp_path) -> None:+ default_config = _encode_config("default/model")+ tenant_config = _with_pool(_encode_config("tenant/model"), "Customer-A")+ _write_config(tmp_path, default_config)+ _write_config(tmp_path, tenant_config)++ registry = ModelRegistry(models_dir=tmp_path, pool_name="customer-a")++ assert registry.model_names == ["tenant/model"]++ @pytest.mark.asyncio+ async def test_replace_configs_filters_different_model_pool(self) -> None:+ registry = ModelRegistry(pool_name="customer-a")+ default_config = _encode_config("default/model")+ tenant_config = _encode_config("tenant/model")+ tenant_config.pool = "customer-a"++ await registry.replace_configs_async([default_config, tenant_config])++ assert registry.model_names == ["tenant/model"]def test_failed_add_does_not_mutate_state(self) -> None:registry = ModelRegistry(pool_name="p1")- registry.add_config(_gen_config())+ registry.add_config(_with_pool(_gen_config(), "p1"))try:- registry.add_config(_encode_config())+ registry.add_config(_with_pool(_encode_config(), "p1"))except PoolIsolationError:pass# bge-m3 should not have been addeddiff --git a/packages/sie_server/tests/core/test_registry_async.py b/packages/sie_server/tests/core/test_registry_async.pyindex 528e5d2fd..b96eacdd3 100644--- a/packages/sie_server/tests/core/test_registry_async.py+++ b/packages/sie_server/tests/core/test_registry_async.py@@ -1,8 +1,10 @@+import asynciofrom pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytestfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.memory import MemoryConfigfrom sie_server.core.registry import ModelRegistry@@ -366,6 +368,33 @@ class TestProactiveEviction:finally:await registry.stop_memory_monitor()+ @patch("sie_server.core.model_loader.load_adapter")+ async def test_memory_monitor_does_not_evict_only_loaded_model(+ self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock+ ) -> None:+ """Pressure monitor keeps a sole resident model to avoid reload loops."""+ registry = ModelRegistry(+ memory_config=MemoryConfig(+ pressure_threshold=0.95,+ memory_check_interval_s=0.005,+ ),+ )+ registry.add_config(_make_config(name="model-a", hf_id="org/model-a"))+ mock_adapter = mock_adapter_factory()+ mock_load_adapter.return_value = mock_adapter++ await registry.load_async("model-a", "cpu")+ registry._memory_manager.check_pressure = MagicMock(return_value=True)++ await registry.start_memory_monitor()+ try:+ await asyncio.sleep(0.02)+ finally:+ await registry.stop_memory_monitor()++ assert registry.is_loaded("model-a")+ mock_adapter.unload.assert_not_called()+async def test_memory_monitor_starts_and_stops(self) -> None:"""Memory monitor can be started and stopped cleanly."""from sie_server.core.memory import MemoryConfigdiff --git a/packages/sie_server/tests/test_cli_pool.py b/packages/sie_server/tests/test_cli_pool.pynew file mode 100644index 000000000..7ad70eade--- /dev/null+++ b/packages/sie_server/tests/test_cli_pool.py@@ -0,0 +1,88 @@+from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest+import yaml+from sie_server import cli+from sie_server.app.app_state_config import AppStateConfig+from sie_server.core.deps import collect_bundle_deps+++def test_serve_passes_sie_pool_to_app_config(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ captured: dict[str, Any] = {}++ def fake_run_server(*, config: AppStateConfig, **kwargs: Any) -> None:+ captured["config"] = config+ captured["kwargs"] = kwargs++ monkeypatch.setenv("SIE_POOL", "customer-a")+ 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=None,+ 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)++ assert captured["config"].pool_name == "customer-a"+++def _write_bundle(path: Path) -> None:+ path.write_text(+ yaml.safe_dump(+ {+ "name": "shared",+ "adapters": ["sie_server.adapters.fake"],+ }+ )+ )+++def _write_model(path: Path, *, sie_id: str, pool: str | None = None) -> None:+ data: dict[str, Any] = {+ "sie_id": sie_id,+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.fake:FakeAdapter",+ }+ },+ }+ if pool is not None:+ data["pool"] = pool+ path.write_text(yaml.safe_dump(data))+++def test_load_bundle_filters_models_by_sie_pool(tmp_path: Path) -> None:+ bundles_dir = tmp_path / "bundles"+ models_dir = tmp_path / "models"+ bundles_dir.mkdir()+ models_dir.mkdir()+ _write_bundle(bundles_dir / "shared.yaml")+ _write_model(models_dir / "default.yaml", sie_id="org/default")+ _write_model(models_dir / "tenant.yaml", sie_id="org/tenant", pool="customer-a")++ assert cli.load_bundle("shared", bundles_dir, str(models_dir), pool_name="default") == ["org/default"]+ assert cli.load_bundle("shared", bundles_dir, str(models_dir), pool_name="customer-a") == ["org/tenant"]++ deps = collect_bundle_deps("shared", bundles_dir, models_dir, pool_name="customer-a")+ assert deps.models == ["org/tenant"]diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex 92ab0d53e..d33215686 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -19,7 +19,12 @@ from sie_server.core.registry import ModelRegistryfrom sie_server.core.timing import RequestTimingfrom sie_server.core.worker.types import WorkerResultfrom sie_server.ipc_server import IpcServer, IpcServerError-from sie_server.ipc_types import IPC_VERSION, ApplyModelConfigRequest+from sie_server.ipc_types import (+ IPC_VERSION,+ ApplyModelConfigRequest,+ ReplaceModelConfigEntry,+ ReplaceModelConfigsRequest,+)from sie_server.queue_executor import QueueExecutor_LEN_STRUCT = struct.Struct("!I")@@ -79,6 +84,7 @@ def _make_executor() -> tuple[QueueExecutor, MagicMock]:reg.is_loaded.return_value = Truereg.is_loading.return_value = Falsereg.get_config.return_value = MagicMock()+ reg.get_configs_snapshot.return_value = {}return QueueExecutor(reg), reg@@ -340,6 +346,164 @@ profiles:finally:await srv.stop(drain_timeout_s=1.0)+ @pytest.mark.asyncio+ async def test_replace_model_configs_requires_models_field(self) -> None:+ registry = ModelRegistry(models_dir=None)+ executor = QueueExecutor(registry)++ model_config = """+sie_id: kept/model+hf_id: sentence-transformers/all-MiniLM-L6-v2+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+ max_batch_tokens: 4096+"""+ await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=7,+ bundle_config_hash="",+ models=[+ ReplaceModelConfigEntry(+ model_id="kept/model",+ model_config=model_config,+ )+ ],+ )+ )+ assert registry.has_model("kept/model")++ sock = _short_sock_path()+ srv = IpcServer(sock, executor, worker_id="worker-test", stale_after_ms=10_000)+ await srv.start()+ try:+ client = await _Client.connect(sock)+ try:+ resp = await client.rpc(+ "ReplaceModelConfigs",+ {+ "bundle_id": "default",+ "epoch": 8,+ "bundle_config_hash": "",+ },+ )+ assert resp["ok"] is False+ assert "Object missing required field `models`" in (resp["error"] or "")+ assert registry.has_model("kept/model")+ finally:+ await client.close()+ finally:+ await srv.stop(drain_timeout_s=1.0)++ @pytest.mark.asyncio+ async def test_replace_model_configs_drops_removed_registry_config(self) -> None:+ registry = ModelRegistry(models_dir=None, model_filter=["existing/model"])+ executor = QueueExecutor(registry)++ def model_yaml(model_id: str) -> str:+ return f"""+sie_id: {model_id}+hf_id: sentence-transformers/all-MiniLM-L6-v2+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+ max_batch_tokens: 4096+"""++ await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=7,+ bundle_config_hash="",+ models=[+ ReplaceModelConfigEntry(+ model_id="stale/model",+ model_config=model_yaml("stale/model"),+ ),+ ReplaceModelConfigEntry(+ model_id="kept/model",+ model_config=model_yaml("kept/model"),+ ),+ ],+ )+ )+ assert registry.has_model("stale/model")+ assert registry.has_model("kept/model")+ registry._loaded["stale/model"] = MagicMock()+ registry._do_unload = AsyncMock()++ resp = await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=8,+ bundle_config_hash="",+ models=[+ ReplaceModelConfigEntry(+ model_id="kept/model",+ model_config=model_yaml("kept/model"),+ )+ ],+ )+ )++ assert resp.applied is True+ assert resp.applied_models == ["kept/model"]+ registry._do_unload.assert_awaited_once_with("stale/model")+ assert not registry.has_model("stale/model")+ assert registry.has_model("kept/model")++ @pytest.mark.asyncio+ async def test_replace_model_configs_reports_pool_filtered_models(self) -> None:+ registry = ModelRegistry(models_dir=None, pool_name="customer-a")+ executor = QueueExecutor(registry)++ def model_yaml(model_id: str, *, pool: str | None = None) -> str:+ pool_line = f"pool: {pool}\n" if pool is not None else ""+ return f"""+sie_id: {model_id}+hf_id: sentence-transformers/all-MiniLM-L6-v2+{pool_line}tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+ max_batch_tokens: 4096+"""++ resp = await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=8,+ bundle_config_hash="",+ models=[+ ReplaceModelConfigEntry(+ model_id="default/model",+ model_config=model_yaml("default/model"),+ ),+ ReplaceModelConfigEntry(+ model_id="tenant/model",+ model_config=model_yaml("tenant/model", pool="customer-a"),+ ),+ ],+ )+ )++ assert resp.applied is True+ assert resp.applied_models == ["tenant/model"]+ assert not registry.has_model("default/model")+ assert registry.has_model("tenant/model")+# -----------------------------------------------------------------------------# ProcessEncodeBatchdiff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.pyindex 39d6b3706..6dc969c66 100644--- a/packages/sie_server/tests/test_queue_executor.py+++ b/packages/sie_server/tests/test_queue_executor.py@@ -25,6 +25,7 @@ def _make_registry(*, loaded: bool = True, loading: bool = False) -> MagicMock:reg = MagicMock()reg.model_names = ["test/model"]reg.device = "cpu"+ reg.has_model.return_value = Truereg.is_loaded.return_value = loadedreg.is_loading.return_value = loadingreg.get_config.return_value = MagicMock()@@ -92,6 +93,14 @@ class TestEnsureModelReady:assert await ex.ensure_model_ready("test/model") == "ready"reg.start_load_async.assert_not_called()+ @pytest.mark.asyncio+ async def test_loaded_but_no_config_returns_retry_later(self) -> None:+ reg = _make_registry(loaded=True)+ reg.has_model.return_value = False+ ex = QueueExecutor(reg)+ assert await ex.ensure_model_ready("test/model") == "retry_later"+ reg.start_load_async.assert_not_called()+@pytest.mark.asyncioasync def test_already_loading_returns_in_progress(self) -> None:reg = _make_registry(loaded=False, loading=True)diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lockindex ce2007adc..4e10c1b67 100644--- a/packages/sie_server_sidecar/Cargo.lock+++ b/packages/sie_server_sidecar/Cargo.lock@@ -1558,22 +1558,21 @@ dependencies = [[[package]]name = "procfs"-version = "0.16.0"+version = "0.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "731e0d9356b0c25f16f33b5be79b1c57b562f141ebfcdb0ad8ac2c13a24293b4"+checksum = "cc5b72d8145275d844d4b5f6d4e1eef00c8cd889edb6035c21675d1bb1f45c9f"dependencies = ["bitflags","hex",- "lazy_static","procfs-core","rustix 0.38.44",][[package]]name = "procfs-core"-version = "0.16.0"+version = "0.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2d3554923a69f4ce04c4a754260c338f505ce22642d3830e049a399fc2059a29"+checksum = "239df02d8349b06fc07398a3a1697b06418223b1c7725085e801e7c0fc6a12ec"dependencies = ["bitflags","hex",@@ -1581,9 +1580,9 @@ dependencies = [[[package]]name = "prometheus"-version = "0.13.4"+version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3d33c28a30771f7f96db69893f78b857f7450d7e0237e9c8fc6427a81bae7ed1"+checksum = "3ca5326d8d0b950a9acd87e6a3f94745394f62e4dae1b1ee22b2bc0c394af43a"dependencies = ["cfg-if","fnv",@@ -1593,14 +1592,28 @@ dependencies = ["parking_lot","procfs","protobuf",- "thiserror 1.0.69",+ "thiserror 2.0.18",][[package]]name = "protobuf"-version = "2.28.0"+version = "3.7.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "106dd99e98437432fed6519dedecfade6a06a73bb7b2a1e019fdd2bee5778d94"+checksum = "d65a1d4ddae7d8b5de68153b48f6aa3bba8cb002b243dbdbc55a5afbc98f99f4"+dependencies = [+ "once_cell",+ "protobuf-support",+ "thiserror 1.0.69",+]++[[package]]+name = "protobuf-support"+version = "3.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e36c2f31e0a47f9280fb347ef5e461ffcd2c52dd520d8e216b52f93b0b0d7d6"+dependencies = [+ "thiserror 1.0.69",+][[package]]name = "quick-xml"@@ -2195,7 +2208,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-server-sidecar"-version = "0.6.4"+version = "0.6.5"dependencies = ["anyhow","async-nats",diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex 939ca39b5..b8f04b5c5 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.4"+version = "0.6.5"edition = "2021"description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."@@ -49,7 +49,7 @@ uuid = { version = "1", features = ["v4"] }reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }# Metrics server (matches gateway)-prometheus = { version = "0.13", features = ["process"] }+prometheus = { version = "0.14", features = ["process"] }hyper = { version = "1", features = ["server", "http1"] }hyper-util = { version = "0.1", features = ["tokio"] }http-body-util = "0.1"diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 03e5c55d9..dbfc18c35 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -283,11 +283,13 @@ the model descriptor cache, and returns the bundle hash it computes locally.When `SIE_CONFIG_SERVICE_URL` is set, the sidecar also runs an exportreconciler. It performs a startup `GET /v1/configs/export`, then polls-`GET /v1/configs/epoch`. If the control-plane epoch is ahead, or if the slow-full-export reconcile is due for an epoch-0/no-config-store deployment, it replays-only export entries whose `affected_bundles` include this worker's bundle. The-advertised hash advances only after every relevant export entry applies-successfully, so a partial replay does not produce a false worker ACK.+`GET /v1/configs/epoch`. If the control-plane epoch is ahead, if the+control-plane `bundle_config_hashes_hash` changes, or if the slow full-export+reconcile is due for an epoch-0/no-config-store deployment, it sends the full+bundle-relevant export set to Python over IPC `ReplaceModelConfigs`. Python+validates every entry, unloads removed or changed loaded models, and replaces+the bundle-scoped registry view. The advertised hash advances only after that+replacement succeeds, so a partial export does not produce a false worker ACK.The NATS health publisher reads that hash dynamically, so the gateway's`/v1/configs/models/{id}/status` endpoint observes worker convergence without@@ -311,7 +313,7 @@ task, then creates the worker-specific generation stream.- **Durable config drift.** The sidecar cleans up overlapping consumers, but apure durable config change may still need operator cleanup if JetStreamrejects an update.-- **Config replay scope.** Worker-side export reconciliation replays model+- **Config replay scope.** Worker-side export reconciliation replaces modelconfigs, not bundle definitions or adapter code. Bundle changes still requirea matching `sie-config`/worker image rollout; the running sidecar can onlyapply configs for adapters already present in the co-located Python image.diff --git a/packages/sie_server_sidecar/src/config_reconciler.rs b/packages/sie_server_sidecar/src/config_reconciler.rsindex 99a46a6b6..9c549eb46 100644--- a/packages/sie_server_sidecar/src/config_reconciler.rs+++ b/packages/sie_server_sidecar/src/config_reconciler.rs@@ -4,8 +4,9 @@//! `sie.config.models.<bundle>`, but it does not replay messages that were//! published while a worker was disconnected. This module closes that gap by//! polling `GET /v1/configs/epoch` and fetching `GET /v1/configs/export` when-//! the control plane is ahead. A slower full-export pass also covers-//! no-config-store deployments where `sie-config` keeps epoch at `0`.+//! the control plane is ahead or when its compact per-bundle config fingerprint+//! changes. A slower full-export pass also covers legacy/no-config-store+//! deployments where `sie-config` keeps epoch at `0`.use std::collections::HashMap;use std::future::Future;@@ -19,10 +20,12 @@ use tokio::time::interval;use tracing::{debug, info, warn};use crate::config_subscriber::{- apply_via_ipc_with_retry, ConfigApplyState, MAX_MODEL_CONFIG_BYTES,+ replace_via_ipc_with_retry, ConfigApplyState, MAX_MODEL_CONFIG_BYTES,};use crate::ipc_client::{IpcClient, IpcError};-use crate::ipc_types::{ApplyModelConfigRequest, ApplyModelConfigResponse};+use crate::ipc_types::{+ ReplaceModelConfigEntry, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,+};use crate::metrics::MetricsRegistry;use crate::shutdown::Shutdown;@@ -40,9 +43,11 @@ pub struct ReconcilerConfig {}#[derive(Debug, Deserialize)]-struct EpochResponse {+struct EpochSnapshot {#[serde(default)]epoch: u64,+ #[serde(default)]+ bundle_config_hashes_hash: String,}#[derive(Debug, Deserialize)]@@ -133,7 +138,7 @@ impl ReconcileClient {})}- async fn fetch_epoch(&self) -> Result<u64, ReconcileError> {+ async fn fetch_epoch(&self) -> Result<EpochSnapshot, ReconcileError> {let url = format!("{}/v1/configs/epoch", self.base_url.trim_end_matches('/'));let mut req = self.http.get(&url);if let Some(token) = &self.admin_token {@@ -149,8 +154,7 @@ impl ReconcileClient {body,});}- let payload: EpochResponse = resp.json().await?;- Ok(payload.epoch)+ Ok(resp.json().await?)}async fn fetch_export(&self) -> Result<ExportSnapshot, ReconcileError> {@@ -180,6 +184,29 @@ fn record_reconcile(metrics: &MetricsRegistry, result: &str) {.inc();}+fn drift_reason(+ local_epoch: u64,+ remote: &EpochSnapshot,+ local_bundle_config_hashes_hash: &str,+ full_export_due: bool,+) -> Option<&'static str> {+ if remote.epoch > local_epoch {+ return Some("epoch_ahead");+ }+ if remote.epoch < local_epoch {+ return Some("epoch_rewind");+ }+ if !remote.bundle_config_hashes_hash.is_empty()+ && remote.bundle_config_hashes_hash != local_bundle_config_hashes_hash+ {+ return Some("bundle_config_hashes_hash");+ }+ if remote.epoch == 0 && full_export_due {+ return Some("periodic_export");+ }+ None+}+/// Spawn the optional export reconciler.////// The task is disabled when `config.base_url` is empty. The caller owns the@@ -225,6 +252,16 @@ pub fn spawn(shutdown: Arc::clone(&shutdown),};let mut last_successful_export: Option<Instant> = None;+ let mut last_bundle_config_hashes_hash = match client.fetch_epoch().await {+ Ok(snapshot) => snapshot.bundle_config_hashes_hash,+ Err(e) => {+ warn!(+ error = %e,+ "worker-config: initial epoch fingerprint poll failed; startup export will proceed"+ );+ String::new()+ }+ };match reconcile_export(&runtime, false, "startup").await {Ok(outcome) if outcome.shutdown => return,Ok(outcome) if outcome.failed == 0 => {@@ -267,40 +304,40 @@ pub fn spawn(_ = shutdown.wait() => return,_ = ticker.tick() => {let local_epoch = state.epoch();- let remote_epoch = match client.fetch_epoch().await {- Ok(epoch) => epoch,+ let remote = match client.fetch_epoch().await {+ Ok(snapshot) => snapshot,Err(e) => {warn!(error = %e, "worker-config: epoch poll failed");record_reconcile(&metrics, "epoch_error");continue;}};+ let remote_epoch = remote.epoch;+ let remote_bundle_config_hashes_hash =+ remote.bundle_config_hashes_hash.clone();let full_export_due = config.full_export_interval.is_some_and(|interval| {last_successful_export.map(|last| last.elapsed() >= interval).unwrap_or(true)});- let needs_export =- remote_epoch != local_epoch || (remote_epoch == 0 && full_export_due);- if !needs_export {+ let Some(reason) = drift_reason(+ local_epoch,+ &remote,+ &last_bundle_config_hashes_hash,+ full_export_due,+ ) else {debug!(local_epoch,remote_epoch,+ bundle_config_hashes_hash = %remote_bundle_config_hashes_hash,"worker-config: epoch poll in sync");continue;- }+ };let force_epoch = remote_epoch < local_epoch;- let reason = if remote_epoch > local_epoch {- "epoch_ahead"- } else if remote_epoch < local_epoch {- "epoch_rewind"- } else {- "periodic_export"- };if force_epoch {warn!(local_epoch,@@ -312,6 +349,7 @@ pub fn spawn(local_epoch,remote_epoch,reason,+ bundle_config_hashes_hash = %remote_bundle_config_hashes_hash,"worker-config: drift detected; fetching export");}@@ -322,6 +360,10 @@ pub fn spawn(Ok(outcome) if outcome.shutdown => return,Ok(outcome) if outcome.failed == 0 => {last_successful_export = Some(Instant::now());+ if !remote_bundle_config_hashes_hash.is_empty() {+ last_bundle_config_hashes_hash =+ remote_bundle_config_hashes_hash.clone();+ }if outcome.applied > 0 {if let Some(notify) = generation_reconcile.as_ref() {notify.notify_one();@@ -372,10 +414,10 @@ async fn reconcile_export(&runtime.metrics,force_epoch,reason,- move |req, model_id, epoch| {+ move |req, epoch| {let ipc = Arc::clone(&ipc);let shutdown = Arc::clone(&shutdown);- async move { apply_via_ipc_with_retry(ipc, shutdown, req, &model_id, epoch).await }+ async move { replace_via_ipc_with_retry(ipc, shutdown, req, epoch).await }},).await)@@ -391,8 +433,8 @@ async fn reconcile_export_snapshot<F, Fut>(mut apply: F,) -> ExportOutcomewhere- F: FnMut(ApplyModelConfigRequest, String, u64) -> Fut,- Fut: Future<Output = Result<Option<ApplyModelConfigResponse>, IpcError>>,+ F: FnMut(ReplaceModelConfigsRequest, u64) -> Fut,+ Fut: Future<Output = Result<Option<ReplaceModelConfigsResponse>, IpcError>>,{let _apply_guard = state.lock_apply().await;@@ -411,12 +453,8 @@ wherelet mut applied = 0usize;let mut failed = 0usize;let mut skipped = 0usize;- let control_plane_hash = snapshot- .bundle_config_hashes- .get(bundle)- .filter(|hash| !hash.is_empty())- .cloned();- let mut last_bundle_hash: Option<String> = None;+ let mut exported_models = Vec::new();+ let control_plane_hash = snapshot.bundle_config_hashes.get(bundle).cloned();let mut first_hash_mismatch: Option<String> = None;for model in snapshot.models {@@ -453,16 +491,20 @@ wherecontinue;}- let req = ApplyModelConfigRequest {- bundle_id: bundle.to_string(),+ exported_models.push(ReplaceModelConfigEntry {model_id: model.model_id.clone(),- epoch: snapshot.epoch,- bundle_config_hash: String::new(),- profiles_added: vec![],model_config,- };+ });+ }- let resp = match apply(req, model.model_id.clone(), snapshot.epoch).await {+ let state_updated = if failed == 0 {+ let req = ReplaceModelConfigsRequest {+ bundle_id: bundle.to_string(),+ epoch: snapshot.epoch,+ bundle_config_hash: control_plane_hash.clone().unwrap_or_default(),+ models: exported_models,+ };+ let resp = match apply(req, snapshot.epoch).await {Ok(Some(resp)) => resp,Ok(None) => {record_reconcile(metrics, "shutdown");@@ -477,41 +519,46 @@ where}Err(e) => {warn!(- model = %model.model_id,epoch = snapshot.epoch,error = %e,- "worker-config: exported model apply failed"+ "worker-config: exported model replace failed");- failed += 1;- continue;+ record_reconcile(metrics, "partial");+ return ExportOutcome {+ epoch: snapshot.epoch,+ applied,+ failed: failed + 1,+ skipped,+ shutdown: false,+ state_updated: false,+ };}};if !resp.applied {warn!(- model = %model.model_id,epoch = snapshot.epoch,- "worker-config: exported model apply returned applied=false"+ "worker-config: exported model replace returned applied=false");- failed += 1;- continue;+ record_reconcile(metrics, "partial");+ return ExportOutcome {+ epoch: snapshot.epoch,+ applied,+ failed: failed + 1,+ skipped,+ shutdown: false,+ state_updated: false,+ };}if let Some(hash) = &control_plane_hash {- if !resp.bundle_config_hash.is_empty()- && resp.bundle_config_hash != *hash- && first_hash_mismatch.is_none()- {+ if !resp.bundle_config_hash.is_empty() && resp.bundle_config_hash != *hash {first_hash_mismatch = Some(resp.bundle_config_hash.clone());}- last_bundle_hash = Some(hash.clone());- } else if !resp.bundle_config_hash.is_empty() {- last_bundle_hash = Some(resp.bundle_config_hash);}- applied += 1;- }+ let applied_bundle_hash = resp.bundle_config_hash.clone();+ applied = resp.applied_models.len();- let state_updated = if failed == 0 {if let (Some(control_hash), Some(applied_hash)) = (control_plane_hash.as_deref(),first_hash_mismatch.as_deref(),@@ -520,11 +567,11 @@ whereepoch = snapshot.epoch,advertised_hash = %control_hash,applied_hash = %applied_hash,- "worker-config: Python registry hash differs from control-plane export hash; advertising control-plane hash"+ "worker-config: Python registry hash differs from control-plane export hash; advertising Python-applied hash");}let state_updated =- state.mark_export_reconciled(snapshot.epoch, last_bundle_hash, force_epoch);+ state.mark_export_reconciled(snapshot.epoch, Some(applied_bundle_hash), force_epoch);if state_updated {metrics.config_epoch.set(snapshot.epoch as i64);}@@ -584,6 +631,29 @@ mod tests {MetricsRegistry::new().expect("metrics registry")}+ #[test]+ fn drift_reason_detects_same_epoch_bundle_config_hashes_hash_change() {+ let remote = EpochSnapshot {+ epoch: 9,+ bundle_config_hashes_hash: "new-fingerprint".into(),+ };++ assert_eq!(+ drift_reason(9, &remote, "old-fingerprint", false),+ Some("bundle_config_hashes_hash")+ );+ assert_eq!(drift_reason(9, &remote, "new-fingerprint", true), None);++ let legacy_remote = EpochSnapshot {+ epoch: 9,+ bundle_config_hashes_hash: String::new(),+ };+ assert_eq!(+ drift_reason(9, &legacy_remote, "old-fingerprint", false),+ None+ );+ }+#[test]fn exported_model_targets_exact_bundle_only() {let model = ExportedModel {@@ -639,14 +709,15 @@ mod tests {let outcome =reconcile_export_snapshot(snapshot, "default", &state, &metrics, false, "test", {let applied = Arc::clone(&applied);- move |req, _model_id, _epoch| {+ move |req, _epoch| {let applied = Arc::clone(&applied);async move {applied.lock().await.push(req);- Ok(Some(ApplyModelConfigResponse {+ Ok(Some(ReplaceModelConfigsResponse {applied: true,bundle_config_hash: "hash-7".into(),config_version: 7,+ applied_models: vec!["target-model".into()],}))}}@@ -665,9 +736,10 @@ mod tests {let applied = applied.lock().await;assert_eq!(applied.len(), 1);- assert_eq!(applied[0].model_id, "target-model");assert_eq!(applied[0].bundle_id, "default");assert_eq!(applied[0].epoch, 7);+ assert_eq!(applied[0].models.len(), 1);+ assert_eq!(applied[0].models[0].model_id, "target-model");}#[tokio::test]@@ -690,21 +762,26 @@ mod tests {&metrics,false,"test",- |req, _model_id, _epoch| async move {- if req.model_id == "bad-model" {+ |req, _epoch| async move {+ if req.models.iter().any(|model| model.model_id == "bad-model") {Err(IpcError::Server("apply failed".into()))} else {- Ok(Some(ApplyModelConfigResponse {+ Ok(Some(ReplaceModelConfigsResponse {applied: true,bundle_config_hash: "hash-8".into(),config_version: 8,+ applied_models: req+ .models+ .into_iter()+ .map(|model| model.model_id)+ .collect(),}))}},).await;- assert_eq!(outcome.applied, 1);+ assert_eq!(outcome.applied, 0);assert_eq!(outcome.failed, 1);assert!(!outcome.state_updated);assert_eq!(state.epoch(), 0);@@ -729,11 +806,12 @@ mod tests {&metrics,true,"test",- |_req, _model_id, _epoch| async move {- Ok(Some(ApplyModelConfigResponse {+ |_req, _epoch| async move {+ Ok(Some(ReplaceModelConfigsResponse {applied: true,bundle_config_hash: "hash-3".into(),config_version: 3,+ applied_models: vec!["target-model".into()],}))},)@@ -750,7 +828,7 @@ mod tests {}#[tokio::test]- async fn export_reconcile_prefers_control_plane_bundle_hash() {+ async fn export_reconcile_prefers_python_applied_bundle_hash() {let snapshot = ExportSnapshot {epoch: 11,bundle_config_hashes: HashMap::from([(@@ -769,11 +847,12 @@ mod tests {&metrics,false,"test",- |_req, _model_id, _epoch| async move {- Ok(Some(ApplyModelConfigResponse {+ |_req, _epoch| async move {+ Ok(Some(ReplaceModelConfigsResponse {applied: true,bundle_config_hash: "python-hash".into(),config_version: 11,+ applied_models: vec!["target-model".into()],}))},)@@ -784,7 +863,47 @@ mod tests {assert_eq!(state.epoch(), 11);assert_eq!(state.bundle_config_hash().read().unwrap().as_str(),- "control-hash"+ "python-hash");}++ #[tokio::test]+ async fn export_reconcile_replaces_with_empty_bundle_snapshot() {+ let snapshot = ExportSnapshot {+ epoch: 12,+ bundle_config_hashes: HashMap::from([("default".to_string(), String::new())]),+ models: vec![exported_model("other-model", &["vision"])],+ };+ let state = ConfigApplyState::new("old".into());+ let metrics = metrics();+ let replace_calls = Arc::new(Mutex::new(Vec::new()));++ let outcome =+ reconcile_export_snapshot(snapshot, "default", &state, &metrics, false, "test", {+ let replace_calls = Arc::clone(&replace_calls);+ move |req, _epoch| {+ let replace_calls = Arc::clone(&replace_calls);+ async move {+ replace_calls.lock().await.push(req);+ Ok(Some(ReplaceModelConfigsResponse {+ applied: true,+ bundle_config_hash: String::new(),+ config_version: 12,+ applied_models: vec![],+ }))+ }+ }+ })+ .await;++ assert_eq!(outcome.applied, 0);+ assert_eq!(outcome.failed, 0);+ assert_eq!(outcome.skipped, 1);+ assert!(outcome.state_updated);+ assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "");++ let replace_calls = replace_calls.lock().await;+ assert_eq!(replace_calls.len(), 1);+ assert!(replace_calls[0].models.is_empty());+ }}diff --git a/packages/sie_server_sidecar/src/config_subscriber.rs b/packages/sie_server_sidecar/src/config_subscriber.rsindex a511e5d61..d4c3020c5 100644--- a/packages/sie_server_sidecar/src/config_subscriber.rs+++ b/packages/sie_server_sidecar/src/config_subscriber.rs@@ -21,7 +21,9 @@ use tracing::{debug, info, warn};use crate::health_publisher::SharedBundleConfigHash;use crate::ipc_client::{IpcClient, IpcError};-use crate::ipc_types::ApplyModelConfigRequest;+use crate::ipc_types::{+ ApplyModelConfigRequest, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,+};use crate::metrics::MetricsRegistry;use crate::shutdown::Shutdown;@@ -137,9 +139,7 @@ impl ConfigApplyState {fn mark_applied(&self, epoch: u64, bundle_config_hash: String) {if epoch == 0 {- if !bundle_config_hash.is_empty() {- self.set_bundle_hash(bundle_config_hash);- }+ self.set_bundle_hash(bundle_config_hash);return;}@@ -150,9 +150,7 @@ impl ConfigApplyState {.compare_exchange(current, epoch, Ordering::AcqRel, Ordering::Acquire){Ok(_) => {- if !bundle_config_hash.is_empty() {- self.set_bundle_hash(bundle_config_hash);- }+ self.set_bundle_hash(bundle_config_hash);return;}Err(observed) => current = observed,@@ -176,9 +174,7 @@ impl ConfigApplyState {self.set_epoch_max(epoch);}if let Some(hash) = bundle_config_hash {- if !hash.is_empty() {- self.set_bundle_hash(hash);- }+ self.set_bundle_hash(hash);}true}@@ -319,14 +315,6 @@ async fn wait_retry_or_shutdown(shutdown: &Shutdown, delay: Duration) -> bool {}}-fn authoritative_bundle_hash(notification_hash: &str, applied_hash: &str) -> String {- if notification_hash.is_empty() {- applied_hash.to_string()- } else {- notification_hash.to_string()- }-}-/// Spawn the long-lived subscription task. Failures are logged and leave the/// worker serving its startup config; inference should not crash just because/// live config apply is temporarily unavailable.@@ -477,6 +465,45 @@ pub(crate) async fn apply_via_ipc_with_retry(}}+pub(crate) async fn replace_via_ipc_with_retry(+ ipc: Arc<IpcClient>,+ shutdown: Arc<Shutdown>,+ req: ReplaceModelConfigsRequest,+ epoch: u64,+) -> Result<Option<ReplaceModelConfigsResponse>, IpcError> {+ let mut retry_delay = RETRY_BASE_DELAY;+ let mut attempt = 0_u64;+ loop {+ match ipc.replace_model_configs(req.clone()).await {+ Ok(resp) => return Ok(Some(resp)),+ Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {+ attempt = attempt.saturating_add(1);+ if attempt == 1 || attempt == 5 || attempt == 30 || attempt.is_multiple_of(120) {+ warn!(+ epoch,+ attempt,+ retry_delay_ms = retry_delay.as_millis() as u64,+ error = %e,+ "worker-config: transient Python registry replace failure; retrying"+ );+ } else {+ debug!(+ epoch,+ attempt,+ error = %e,+ "worker-config: Python registry replace still waiting"+ );+ }+ if wait_retry_or_shutdown(&shutdown, retry_delay).await {+ return Ok(None);+ }+ retry_delay = next_retry_delay(retry_delay);+ }+ Err(e) => return Err(e),+ }+ }+}+async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotification) {let bundle = runtime.bundle.as_str();let trusted_producers = runtime.trusted_producers.as_slice();@@ -621,8 +648,7 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotreturn;}- let applied_bundle_hash =- authoritative_bundle_hash(¬ification.bundle_config_hash, &resp.bundle_config_hash);+ let applied_bundle_hash = resp.bundle_config_hash.clone();if !notification.bundle_config_hash.is_empty()&& !resp.bundle_config_hash.is_empty()@@ -633,7 +659,7 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotepoch = notification.epoch,advertised_hash = %notification.bundle_config_hash,applied_hash = %resp.bundle_config_hash,- "worker-config: Python registry hash differs from control-plane hash; advertising control-plane hash"+ "worker-config: Python registry hash differs from control-plane hash; advertising Python-applied hash");record_delta(metrics, kind, "hash_mismatch");} else {@@ -738,6 +764,22 @@ mod tests {assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "h0");}+ #[test]+ fn live_apply_can_clear_bundle_hash() {+ let state = ConfigApplyState::new("old".into());+ state.mark_applied(4, String::new());+ assert_eq!(state.epoch(), 4);+ assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "");+ }++ #[test]+ fn export_reconcile_can_clear_bundle_hash() {+ let state = ConfigApplyState::new("old".into());+ assert!(state.mark_export_reconciled(4, Some(String::new()), false));+ assert_eq!(state.epoch(), 4);+ assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "");+ }+#[test]fn accepted_hash_history_keeps_inflight_work_processable() {let state = ConfigApplyState::new("h0".into());@@ -751,18 +793,6 @@ mod tests {assert!(!state.accepts_bundle_config_hash("missing"));}- #[test]- fn advertised_notification_hash_wins_after_successful_apply() {- assert_eq!(- authoritative_bundle_hash("control-plane", "python-local"),- "control-plane"- );- assert_eq!(- authoritative_bundle_hash("", "python-local"),- "python-local"- );- }-#[test]fn retryable_ipc_errors_are_transport_or_timeout_only() {let refused = IpcError::Io(std::io::Error::from(std::io::ErrorKind::ConnectionRefused));diff --git a/packages/sie_server_sidecar/src/ipc_client.rs b/packages/sie_server_sidecar/src/ipc_client.rsindex 97596258a..b2e0b7188 100644--- a/packages/sie_server_sidecar/src/ipc_client.rs+++ b/packages/sie_server_sidecar/src/ipc_client.rs@@ -49,12 +49,13 @@ use crate::ipc_types::{ApplyModelConfigRequest, ApplyModelConfigResponse, BatchOutcome, DrainRequest, DrainResponse,EnsureModelReadyRequest, EnsureModelReadyResponse, GenerateEvent, PingRequest, PingResponse,ProcessEncodeBatchRequest, ProcessExtractBatchRequest, ProcessGenerateRequest,- ProcessScoreBatchRequest, RequestEnvelope, ResponseEnvelope, RunBatchRequest,- SignalGenerateCancelRequest, SignalGenerateCancelResponse, WorkerCapabilitiesRequest,- WorkerCapabilitiesResponse, IPC_VERSION, METHOD_APPLY_MODEL_CONFIG, METHOD_DRAIN,- METHOD_ENSURE_MODEL_READY, METHOD_PING, METHOD_PROCESS_ENCODE_BATCH,- METHOD_PROCESS_EXTRACT_BATCH, METHOD_PROCESS_GENERATE, METHOD_PROCESS_SCORE_BATCH,- METHOD_RUN_BATCH, METHOD_SIGNAL_GENERATE_CANCEL, METHOD_WORKER_CAPABILITIES,+ ProcessScoreBatchRequest, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,+ RequestEnvelope, ResponseEnvelope, RunBatchRequest, SignalGenerateCancelRequest,+ SignalGenerateCancelResponse, WorkerCapabilitiesRequest, WorkerCapabilitiesResponse,+ IPC_VERSION, METHOD_APPLY_MODEL_CONFIG, METHOD_DRAIN, METHOD_ENSURE_MODEL_READY, METHOD_PING,+ METHOD_PROCESS_ENCODE_BATCH, METHOD_PROCESS_EXTRACT_BATCH, METHOD_PROCESS_GENERATE,+ METHOD_PROCESS_SCORE_BATCH, METHOD_REPLACE_MODEL_CONFIGS, METHOD_RUN_BATCH,+ METHOD_SIGNAL_GENERATE_CANCEL, METHOD_WORKER_CAPABILITIES,};use crate::log_util::ErrChain;use crate::metrics::MetricsRegistry;@@ -967,6 +968,13 @@ impl IpcClient {self.call(METHOD_APPLY_MODEL_CONFIG, req).await}+ pub async fn replace_model_configs(+ &self,+ req: ReplaceModelConfigsRequest,+ ) -> Result<ReplaceModelConfigsResponse, IpcError> {+ self.call(METHOD_REPLACE_MODEL_CONFIGS, req).await+ }+pub async fn drain(&self, deadline_ms: u64) -> Result<DrainResponse, IpcError> {self.call(METHOD_DRAIN, DrainRequest { deadline_ms }).await}diff --git a/packages/sie_server_sidecar/src/metrics.rs b/packages/sie_server_sidecar/src/metrics.rsindex ab90583f9..4922e2d64 100644--- a/packages/sie_server_sidecar/src/metrics.rs+++ b/packages/sie_server_sidecar/src/metrics.rs@@ -724,7 +724,7 @@ mod tests {m.pull_model_loads_total.with_label_values(&["m1"]).inc();let families = m.registry.gather();- let names: Vec<&str> = families.iter().map(|f| f.get_name()).collect();+ let names: Vec<&str> = families.iter().map(|f| f.name()).collect();for expected in ["sie_worker_messages_received_total","sie_pull_loop_items_fetched",@@ -825,7 +825,7 @@ mod tests {let families = m.registry.gather();let fam = families.iter()- .find(|f| f.get_name() == "sie_worker_backend_phase_seconds")+ .find(|f| f.name() == "sie_worker_backend_phase_seconds").expect("backend_phase_seconds not registered in shared registry");// Expect exactly four time-series (one per distinct label@@ -846,7 +846,7 @@ mod tests {let labels: std::collections::HashMap<&str, &str> = metric.get_label().iter()- .map(|lp| (lp.get_name(), lp.get_value()))+ .map(|lp| (lp.name(), lp.value())).collect();assert!(labels.contains_key("operation"));assert!(labels.contains_key("model"));diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex 87046f0b3..713cf5f3b 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -40,6 +40,7 @@ pub const METHOD_SIGNAL_GENERATE_CANCEL: &str = "SignalGenerateCancel";/// that don't wire a scheduler.pub const METHOD_RUN_BATCH: &str = "RunBatch";pub const METHOD_APPLY_MODEL_CONFIG: &str = "ApplyModelConfig";+pub const METHOD_REPLACE_MODEL_CONFIGS: &str = "ReplaceModelConfigs";pub const METHOD_DRAIN: &str = "Drain";// -----------------------------------------------------------------------------@@ -284,6 +285,30 @@ pub struct ApplyModelConfigResponse {pub config_version: u64,}+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ReplaceModelConfigEntry {+ pub model_id: String,+ pub model_config: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ReplaceModelConfigsRequest {+ pub bundle_id: String,+ pub epoch: u64,+ pub bundle_config_hash: String,+ pub models: Vec<ReplaceModelConfigEntry>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ReplaceModelConfigsResponse {+ pub applied: bool,+ pub bundle_config_hash: String,+ #[serde(default)]+ pub config_version: u64,+ #[serde(default)]+ pub applied_models: Vec<String>,+}+// -----------------------------------------------------------------------------// ProcessGenerate: streaming generation over IPC// -----------------------------------------------------------------------------@@ -1112,4 +1137,28 @@ mod tests {assert_eq!(back.timestamp_ms, 123.0);assert_eq!(back.bundle_config_hash, "");}++ #[test]+ fn replace_model_configs_request_requires_models_field() {+ let missing_models = rmp_serde::to_vec_named(&serde_json::json!({+ "bundle_id": "default",+ "epoch": 7,+ "bundle_config_hash": "",+ }))+ .unwrap();+ assert!(+ rmp_serde::from_slice::<ReplaceModelConfigsRequest>(&missing_models).is_err(),+ "missing models must not decode as an authoritative empty snapshot"+ );++ let explicit_empty = rmp_serde::to_vec_named(&serde_json::json!({+ "bundle_id": "default",+ "epoch": 7,+ "bundle_config_hash": "",+ "models": [],+ }))+ .unwrap();+ let decoded: ReplaceModelConfigsRequest = rmp_serde::from_slice(&explicit_empty).unwrap();+ assert!(decoded.models.is_empty());+ }}diff --git a/packages/sie_server_sidecar/src/scheduler/metrics.rs b/packages/sie_server_sidecar/src/scheduler/metrics.rsindex 8288a2530..f94ee8ac7 100644--- a/packages/sie_server_sidecar/src/scheduler/metrics.rs+++ b/packages/sie_server_sidecar/src/scheduler/metrics.rs@@ -295,9 +295,7 @@ mod tests {let r = Registry::new();let _ = SchedulerMetrics::register(&r).unwrap();for mf in r.gather() {- // `prometheus::proto::MetricFamily::name` is a private- // field, but the protobuf accessor `get_name` is public.- let name = mf.get_name();+ let name = mf.name();assert!(name.starts_with("sie_worker_scheduler_"),"scheduler metric '{name}' must use the sie_worker_scheduler_ prefix"diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex a06b2db44..1baaa376b 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.4",+ "version": "0.6.5","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 518912a08..daa03037d 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -37,12 +37,13 @@ import {SIEConnectionError,SIEStreamError,} from "./errors.js";+import { toImageWireFormat } from "./images.js";+import type { ImageInput, ImageWireFormat } from "./images.js";import {DEFAULT_LEASE_RENEWAL_INTERVAL,DEFAULT_PROVISION_TIMEOUT,DEFAULT_RETRY_DELAY,DEFAULT_TIMEOUT,- HTTP_ACCEPTED,HTTP_CLIENT_ERROR_MIN,JSON_CONTENT_TYPE,LORA_LOADING_DEFAULT_DELAY,@@ -51,6 +52,7 @@ import {MODEL_LOADING_DEFAULT_DELAY,MODEL_LOADING_ERROR_CODE,MSGPACK_CONTENT_TYPE,+ PROVISIONING_ERROR_CODE,SDK_VERSION_HEADER,SERVER_VERSION_HEADER,} from "./internal/constants.js";@@ -67,6 +69,7 @@ import {throwIfModelLoadFailed,} from "./internal/parsing.js";import { withProvisioningRetry } from "./internal/provisioning.js";+import { applyRetryJitter } from "./internal/retry.js";import { packMessage, unpackMessage } from "./msgpack.js";import { parseSseStream } from "./sse.js";import type {@@ -115,6 +118,31 @@ function abortableSleep(ms: number, signal: AbortSignal): Promise<boolean> {const _LEASE_RENEWAL_MAX_RETRIES = 5;+type ItemWithWireImages = Omit<Item, "images"> & { images?: ImageWireFormat[] };+type ItemForWire = Item | ItemWithWireImages;++function isImageWireFormat(image: ImageInput | ImageWireFormat): image is ImageWireFormat {+ return typeof image === "object" && image !== null && "data" in image;+}++async function imageForWire(image: ImageInput | ImageWireFormat): Promise<ImageWireFormat> {+ if (isImageWireFormat(image)) {+ return image;+ }+ return toImageWireFormat(image);+}++async function itemImagesForWire(item: Item): Promise<ItemForWire> {+ if (!item.images || item.images.length === 0) {+ return item;+ }+ return { ...item, images: await Promise.all(item.images.map(imageForWire)) };+}++async function itemsImagesForWire(items: Item[]): Promise<ItemForWire[]> {+ return Promise.all(items.map(itemImagesForWire));+}+/*** Pluck a mid-stream `error` block out of a `ChatCompletionChunk` and* convert it to `SIEStreamError`, mirroring the shape `sse.rs` emits:@@ -246,11 +274,12 @@ export class SIEClient {): Promise<EncodeResult | EncodeResult[]> {const isSingleItem = !Array.isArray(items);const itemsArray = isSingleItem ? [items] : items;+ const itemsForWire = await itemsImagesForWire(itemsArray);// Build request body - model is in URL path, not body// Wire format uses snake_caseconst body: Record<string, unknown> = {- items: itemsArray,+ items: itemsForWire,};// Add params if any are specified@@ -583,7 +612,7 @@ export class SIEClient {// connect-time refusal. Retrying a mid-flight drop would// double-bill, so surface as `SIEConnectionError` and let the// retry loop propagate it. The SAFE pre-execution capacity- // signals (202 / 503 MODEL_LOADING) are HTTP statuses, not+ // signals (503 PROVISIONING / MODEL_LOADING) are HTTP statuses, not// exceptions, so the retry loop still handles them.throw new SIEConnectionError(`Connection failed: ${err.message}`, "connect");}@@ -641,13 +670,11 @@ export class SIEClient {const waitForCapacity = options.waitForCapacity ?? this.defaultWaitForCapacity;const provisionTimeoutMs = options.provisionTimeoutMs ?? this.provisionTimeout;- // H1: pre-execution capacity signals (202 / 503 MODEL_LOADING /- // generic 503) MUST be handled by the shared provisioning loop —- // otherwise a 202 slipped through as `response.ok === true` and the- // SDK returned the provisioning envelope cast as `ChatCompletion`- // (no `choices`, no `id`). The loop also surfaces `ProvisioningError`- // when the caller opted out (`waitForCapacity: false`) or the- // provision budget is exhausted, matching `generate()`.+ // H1: pre-execution capacity signals (503 PROVISIONING /+ // MODEL_LOADING) MUST be handled by the shared provisioning loop.+ // The loop also surfaces `ProvisioningError` when the caller opted out+ // (`waitForCapacity: false`) or the provision budget is exhausted,+ // matching `generate()`.const response = await withProvisioningRetry(() => this.performJsonPost(url, body, headers), {model: req.model,gpu: undefined,@@ -795,11 +822,11 @@ export class SIEClient {* if the consumer-supplied `extractError` returns an `SIEStreamError`, the* generator throws it instead of yielding the chunk.*- * Retry policy mirrors {@link generate}: only the SAFE pre-execution- * capacity signals — `202` (provisioning) and `503 MODEL_LOADING` — are- * retried, and only while `waitForCapacity` is set and the provision- * budget remains. Once the body opens we never retry (the call is- * non-idempotent; a mid-stream failure must not re-issue generation).+ * Retry policy mirrors {@link generate}: only explicit SAFE+ * pre-execution capacity signals — `503 PROVISIONING` and+ * `503 MODEL_LOADING` — are retried while the provision budget remains.+ * Once the body opens we never retry (the call is non-idempotent; a+ * mid-stream failure must not re-issue generation).** @internal*/@@ -834,8 +861,8 @@ export class SIEClient {const startTime = Date.now();let response: Response | undefined;- // Pre-stream provisioning retry loop. We re-fetch on the SAFE- // pre-execution capacity signals only (202 / 503 MODEL_LOADING),+ // Pre-stream provisioning retry loop. We re-fetch on explicit SAFE+ // pre-execution capacity signals only (503 PROVISIONING / MODEL_LOADING),// parallel to `generate()`. The loop terminates by `break`-ing on a// 200 (the only status that opens a body) or by throwing.while (true) {@@ -871,57 +898,35 @@ export class SIEClient {clearTimeout(preStreamTimeoutId);}- // BUG 13a: `Response.ok` is true for 202, so the old `!response.ok`- // gate let a 202 slip through to `response.body` (null) and throw a- // misleading "no body" RequestError. Handle 202 explicitly as the- // provisioning path (retry under `waitForCapacity`, else throw- // ProvisioningError honoring Retry-After).- if (attemptResponse.status === HTTP_ACCEPTED) {- if (!waitForCapacity) {- throw new ProvisioningError(- "No capacity available. Server is provisioning.",- gpu,- getRetryAfter(attemptResponse),- );- }- const elapsed = Date.now() - startTime;- if (elapsed >= this.provisionTimeout) {- throw new ProvisioningError(- `Provisioning timeout after ${elapsed}ms`,- gpu,- getRetryAfter(attemptResponse),- );- }- const delay = getRetryAfter(attemptResponse) ?? DEFAULT_RETRY_DELAY;- // Abortable: a long Retry-After sleep must yield promptly if the- // caller aborts (`controller.signal` fires on caller-abort), not- // wait out the full delay before the next loop's abort check.- if (- await abortableSleep(- Math.min(delay, this.provisionTimeout - elapsed),- controller.signal,- )- ) {- throw new SIEConnectionError("Stream aborted while provisioning", "other");- }- continue;- }-// 502 MODEL_LOAD_FAILED is terminal — surface immediately.await throwIfModelLoadFailed(attemptResponse, model);- // BUG 13b: retry 503 MODEL_LOADING (a SAFE pre-execution signal)- // when the caller opted into waiting for capacity, parallel to- // `generate()`. Without `waitForCapacity` we fall through to- // `handleError` and reject immediately (no retry).+ // Retry explicit SAFE pre-execution signals before the stream opens.+ // Without `waitForCapacity`, provisioning falls through to+ // `handleError` and rejects immediately.if (attemptResponse.status === 503) {const errorCode = await getErrorCode(attemptResponse.clone());- if (errorCode === MODEL_LOADING_ERROR_CODE && waitForCapacity) {+ if (errorCode === PROVISIONING_ERROR_CODE) {+ if (!waitForCapacity) {+ throw new ProvisioningError(+ "No capacity available. Server is provisioning.",+ gpu,+ getRetryAfter(attemptResponse),+ );+ }const elapsed = Date.now() - startTime;if (elapsed >= this.provisionTimeout) {- throw new ModelLoadingError(`Model loading timeout for '${model}'`, model);+ throw new ProvisioningError(+ `Provisioning timeout after ${elapsed}ms`,+ gpu,+ getRetryAfter(attemptResponse),+ );}- const delay = getRetryAfter(attemptResponse) ?? MODEL_LOADING_DEFAULT_DELAY;+ const retryAfter = getRetryAfter(attemptResponse);+ const delay = retryAfter ?? applyRetryJitter(DEFAULT_RETRY_DELAY);+ // Abortable: a long Retry-After sleep must yield promptly if the+ // caller aborts (`controller.signal` fires on caller-abort), not+ // wait out the full delay before the next loop's abort check.if (await abortableSleep(Math.min(delay, this.provisionTimeout - elapsed),@@ -932,31 +937,25 @@ export class SIEClient {}continue;}- // Generic 503 (scale-from-zero: no / non-MODEL_LOADING error code).- // Retry under `waitForCapacity`, mirroring non-streaming- // `generate()`. This is still a SAFE pre-execution signal — the- // body has not started, so no partial generation is at risk — so- // the non-idempotency reasoning (never retry a mid-stream failure)- // is preserved.- if (waitForCapacity) {+ if (errorCode === MODEL_LOADING_ERROR_CODE) {const elapsed = Date.now() - startTime;- if (elapsed < this.provisionTimeout) {- const delay = getRetryAfter(attemptResponse) ?? DEFAULT_RETRY_DELAY;- if (- await abortableSleep(- Math.min(delay, this.provisionTimeout - elapsed),- controller.signal,- )- ) {- throw new SIEConnectionError("Stream aborted while provisioning", "other");- }- continue;+ if (elapsed >= this.provisionTimeout) {+ throw new ModelLoadingError(`Model loading timeout for '${model}'`, model);}+ const delay = getRetryAfter(attemptResponse) ?? MODEL_LOADING_DEFAULT_DELAY;+ if (+ await abortableSleep(+ Math.min(delay, this.provisionTimeout - elapsed),+ controller.signal,+ )+ ) {+ throw new SIEConnectionError("Stream aborted while provisioning", "other");+ }+ continue;}}- // Any remaining non-200 is an error: don't rely on `!response.ok`- // (which would also be false for the already-handled 202).+ // Any remaining non-200 is an error.if (attemptResponse.status !== 200) {await handleError(attemptResponse);}@@ -1016,10 +1015,13 @@ export class SIEClient {items: Item[],options: ScoreOptions = {},): Promise<ScoreResult> {+ const queryForWire = await itemImagesForWire(query);+ const itemsForWire = await itemsImagesForWire(items);+// Build request bodyconst body: Record<string, unknown> = {- query,- items,+ query: queryForWire,+ items: itemsForWire,};const waitForCapacity = options.waitForCapacity ?? this.defaultWaitForCapacity;@@ -1086,10 +1088,11 @@ export class SIEClient {): Promise<ExtractResult | ExtractResult[]> {const isSingleItem = !Array.isArray(items);const itemsArray = isSingleItem ? [items] : items;+ const itemsForWire = await itemsImagesForWire(itemsArray);// Build request bodyconst body: Record<string, unknown> = {- items: itemsArray,+ items: itemsForWire,};// Add params@@ -1574,9 +1577,9 @@ export class SIEClient {/*** Make a msgpack HTTP request with retry logic.*- * Retried (only when `waitForCapacity: true`, capped by `provisionTimeout`):- * - 202 Accepted (provisioning)- * - 503 `MODEL_LOADING` / `LORA_LOADING` / no error code (scale-from-zero)+ * Retried (capped by `provisionTimeout`):+ * - 503 `PROVISIONING` when `waitForCapacity: true`+ * - 503 `MODEL_LOADING` / `LORA_LOADING`* - `SIEConnectionError` with `kind === "connect"` (issue #95)** `kind === "timeout"` is NOT retried — would extend the user-visible@@ -1614,36 +1617,6 @@ export class SIEClient {throw err;}- // Handle 202 (provisioning) - capacity not available- if (response.status === HTTP_ACCEPTED) {- const retryAfter = getRetryAfter(response);-- if (!waitForCapacity) {- throw new ProvisioningError(- `No capacity available for GPU '${gpu}'. Server is provisioning.`,- gpu,- retryAfter,- );- }-- // Check if we've exceeded the timeout- const elapsed = Date.now() - startTime;- if (elapsed >= this.provisionTimeout) {- throw new ProvisioningError(- `Provisioning timeout after ${elapsed}ms waiting for GPU '${gpu}'`,- gpu,- retryAfter,- );- }-- // Wait and retry- const delay = retryAfter ?? DEFAULT_RETRY_DELAY;- const remaining = this.provisionTimeout - elapsed;- const actualDelay = Math.min(delay, remaining);- await sleep(actualDelay);- 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@@ -1654,11 +1627,38 @@ export class SIEClient {// Short-circuit token-budget overruns (#849).await throwIfInputTooLong(response, model);- // Handle 503 with LORA_LOADING or MODEL_LOADING - auto-retry+ // Handle explicit retryable 503 signals.if (response.status === 503) {const clonedResponse = response.clone();const errorCode = await getErrorCode(clonedResponse);+ if (errorCode === PROVISIONING_ERROR_CODE) {+ const retryAfter = getRetryAfter(response);++ if (!waitForCapacity) {+ throw new ProvisioningError(+ `No capacity available for GPU '${gpu}'. Server is provisioning.`,+ gpu,+ retryAfter,+ );+ }++ const elapsed = Date.now() - startTime;+ if (elapsed >= this.provisionTimeout) {+ throw new ProvisioningError(+ `Provisioning timeout after ${elapsed}ms waiting for GPU '${gpu}'`,+ gpu,+ retryAfter,+ );+ }++ const delay = retryAfter ?? applyRetryJitter(DEFAULT_RETRY_DELAY);+ const remaining = this.provisionTimeout - elapsed;+ const actualDelay = Math.min(delay, remaining);+ await sleep(actualDelay);+ continue;+ }+if (errorCode === LORA_LOADING_ERROR_CODE) {loraRetries += 1;@@ -1695,20 +1695,6 @@ export class SIEClient {await sleep(actualDelay);continue;}-- // Generic 503 fall-through (router/gateway scale-from-zero).- // New code-specific 503 branches MUST go ABOVE this block.- if (waitForCapacity) {- const elapsed = Date.now() - startTime;- if (elapsed < this.provisionTimeout) {- const retryAfter = getRetryAfter(response);- const delay = retryAfter ?? DEFAULT_RETRY_DELAY;- const remaining = this.provisionTimeout - elapsed;- const actualDelay = Math.min(delay, remaining);- await sleep(actualDelay);- continue;- }- }}// Handle other errorsdiff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.tsindex 89149f1fa..a28ae48cf 100644--- a/packages/sie_ts_sdk/src/errors.ts+++ b/packages/sie_ts_sdk/src/errors.ts@@ -110,7 +110,7 @@ export class ServerError extends SIEError {* Error when capacity is not available and provisioning timed out.** Raised when:- * - Server returns 202 (no capacity, provisioning)+ * - Server returns 503 with PROVISIONING code* - waitForCapacity is false (caller doesn't want to wait)* - Or provisioning timeout exceeded*diff --git a/packages/sie_ts_sdk/src/internal/constants.ts b/packages/sie_ts_sdk/src/internal/constants.tsindex a899f806f..5e5221415 100644--- a/packages/sie_ts_sdk/src/internal/constants.ts+++ b/packages/sie_ts_sdk/src/internal/constants.ts@@ -5,7 +5,6 @@export const MSGPACK_CONTENT_TYPE = "application/msgpack";export const JSON_CONTENT_TYPE = "application/json";-export const HTTP_ACCEPTED = 202;export const HTTP_CLIENT_ERROR_MIN = 400;export const HTTP_CLIENT_ERROR_MAX = 499;export const HTTP_SERVER_ERROR_MIN = 500;@@ -27,6 +26,7 @@ export const LORA_LOADING_ERROR_CODE = "LORA_LOADING"; // Error code from serverexport const MODEL_LOADING_MAX_RETRIES = 60; // Max retries (60 * 5s = 5 min)export const MODEL_LOADING_DEFAULT_DELAY = 5_000; // 5 seconds default retry delayexport const MODEL_LOADING_ERROR_CODE = "MODEL_LOADING"; // Error code from server+export const PROVISIONING_ERROR_CODE = "PROVISIONING"; // Error code from gateway provisioning// Version negotiation headersexport const SDK_VERSION_HEADER = "X-SIE-SDK-Version";diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.tsindex 142cb689a..443e16425 100644--- a/packages/sie_ts_sdk/src/internal/parsing.ts+++ b/packages/sie_ts_sdk/src/internal/parsing.ts@@ -25,16 +25,23 @@ import type {WorkerInfo,} from "../types.js";import {- HTTP_ACCEPTED,HTTP_CLIENT_ERROR_MAX,HTTP_CLIENT_ERROR_MIN,HTTP_SERVER_ERROR_MAX,HTTP_SERVER_ERROR_MIN,MSGPACK_CONTENT_TYPE,+ PROVISIONING_ERROR_CODE,} from "./constants.js";import { getRetryAfter as getRetryAfterFromHeader } from "./retry.js";+const SIE_ERROR_CODE_HEADER = "X-SIE-Error-Code";++function normalizeErrorCode(code: string | undefined): string | undefined {+ if (code === "provisioning") return PROVISIONING_ERROR_CODE;+ return code;+}+/*** Parse GPU parameter from "pool/gpu" format*/@@ -94,10 +101,13 @@ export async function getErrorDetail(* Extract error code from response body (handles both JSON and msgpack)*/export async function getErrorCode(response: Response): Promise<string | undefined> {+ const headerCode = response.headers.get(SIE_ERROR_CODE_HEADER);+ if (headerCode) return headerCode;+const detail = await getErrorDetail(response);if (!detail) return undefined;const code = detail.code;- return typeof code === "string" ? code : undefined;+ return typeof code === "string" ? normalizeErrorCode(code) : undefined;}/**@@ -173,7 +183,7 @@ export async function handleError(response: Response, gpu?: string): Promise<nev// Prefer nested ``error`` / ``detail`` objects (gateway + FastAPI dict detail),// same as Python ``handle_error``. Legacy: string ``detail``, or top-level- // ``message`` (e.g. gateway 202 provisioning body).+ // ``message``.const detail = await getErrorDetail(response.clone());let code: string | undefined;@@ -202,8 +212,9 @@ export async function handleError(response: Response, gpu?: string): Promise<nevmessage = response.statusText;}}+ code = response.headers.get(SIE_ERROR_CODE_HEADER) ?? normalizeErrorCode(code);- if (status === HTTP_ACCEPTED) {+ if (status === 503 && code === PROVISIONING_ERROR_CODE) {const retryAfter = getRetryAfter(response);throw new ProvisioningError(message, gpu, retryAfter);}diff --git a/packages/sie_ts_sdk/src/internal/provisioning.ts b/packages/sie_ts_sdk/src/internal/provisioning.tsindex d1a1ff62f..8333250e5 100644--- a/packages/sie_ts_sdk/src/internal/provisioning.ts+++ b/packages/sie_ts_sdk/src/internal/provisioning.ts@@ -3,10 +3,10 @@** Both {@link SIEClient.generate} and {@link SIEClient.chatCompletions}* receive identical pre-execution capacity signals from the gateway —- * `202 Accepted` (provisioning) and `503` with a known error code- * (`MODEL_LOADING`) or a generic 503 (scale-from-zero). They both need- * to retry those SAFE pre-execution signals while honouring a caller-- * supplied `waitForCapacity` flag plus a `provisionTimeout` budget.+ * `503` with a known error code (`PROVISIONING` or `MODEL_LOADING`).+ * They both need to retry those SAFE pre-execution signals while+ * honouring a caller-supplied `waitForCapacity` flag plus a+ * `provisionTimeout` budget.** This helper centralises that loop. Callers supply a `performFetch`* callback that issues a fresh `fetch` per attempt (the request must be@@ -22,11 +22,12 @@import { ModelLoadingError, ProvisioningError, RequestError } from "../errors.js";import {DEFAULT_RETRY_DELAY,- HTTP_ACCEPTED,MODEL_LOADING_DEFAULT_DELAY,MODEL_LOADING_ERROR_CODE,+ PROVISIONING_ERROR_CODE,} from "./constants.js";import { getErrorCode, getRetryAfter, handleError, throwIfModelLoadFailed } from "./parsing.js";+import { applyRetryJitter } from "./retry.js";/** Options controlling the provisioning retry loop. */export interface ProvisioningOptions {@@ -35,9 +36,9 @@ export interface ProvisioningOptions {/** GPU label passed through to `ProvisioningError`. May be `undefined`. */gpu: string | undefined;/**- * When `true`, the loop retries 202 / `503 MODEL_LOADING` / generic 503- * until the provision budget is exhausted. When `false`, the first such- * signal throws (the call-site opted out of waiting).+ * When `true`, the loop retries `503 PROVISIONING` / `503 MODEL_LOADING`+ * until the provision budget is exhausted. When `false`, the first+ * provisioning signal throws (the call-site opted out of waiting).*/waitForCapacity: boolean;/**@@ -76,48 +77,40 @@ export async function withProvisioningRetry(while (true) {const response = await performFetch();- if (response.status === HTTP_ACCEPTED) {- if (!opts.waitForCapacity) {- throw new ProvisioningError(- "No capacity available. Server is provisioning.",- opts.gpu,- getRetryAfter(response),- );- }- const elapsed = Date.now() - startTime;- if (elapsed >= opts.provisionTimeoutMs) {- throw new ProvisioningError(- `Provisioning timeout after ${elapsed}ms`,- opts.gpu,- getRetryAfter(response),- );- }- const delay = getRetryAfter(response) ?? DEFAULT_RETRY_DELAY;- await sleep(Math.min(delay, opts.provisionTimeoutMs - elapsed));- continue;- }-// 502 MODEL_LOAD_FAILED is terminal — surface immediately.await throwIfModelLoadFailed(response, opts.model);if (response.status === 503) {const errorCode = await getErrorCode(response.clone());- if (errorCode === MODEL_LOADING_ERROR_CODE) {+ if (errorCode === PROVISIONING_ERROR_CODE) {+ if (!opts.waitForCapacity) {+ throw new ProvisioningError(+ "No capacity available. Server is provisioning.",+ opts.gpu,+ getRetryAfter(response),+ );+ }const elapsed = Date.now() - startTime;if (elapsed >= opts.provisionTimeoutMs) {- throw new ModelLoadingError(`Model loading timeout for '${opts.model}'`, opts.model);+ throw new ProvisioningError(+ `Provisioning timeout after ${elapsed}ms`,+ opts.gpu,+ getRetryAfter(response),+ );}- const delay = getRetryAfter(response) ?? MODEL_LOADING_DEFAULT_DELAY;+ const retryAfter = getRetryAfter(response);+ const delay = retryAfter ?? applyRetryJitter(DEFAULT_RETRY_DELAY);await sleep(Math.min(delay, opts.provisionTimeoutMs - elapsed));continue;}- if (opts.waitForCapacity) {+ if (errorCode === MODEL_LOADING_ERROR_CODE) {const elapsed = Date.now() - startTime;- if (elapsed < opts.provisionTimeoutMs) {- const delay = getRetryAfter(response) ?? DEFAULT_RETRY_DELAY;- await sleep(Math.min(delay, opts.provisionTimeoutMs - elapsed));- continue;+ if (elapsed >= opts.provisionTimeoutMs) {+ throw new ModelLoadingError(`Model loading timeout for '${opts.model}'`, opts.model);}+ const delay = getRetryAfter(response) ?? MODEL_LOADING_DEFAULT_DELAY;+ await sleep(Math.min(delay, opts.provisionTimeoutMs - elapsed));+ continue;}}diff --git a/packages/sie_ts_sdk/src/internal/retry.ts b/packages/sie_ts_sdk/src/internal/retry.tsindex 99b0f2e72..79c122b0c 100644--- a/packages/sie_ts_sdk/src/internal/retry.ts+++ b/packages/sie_ts_sdk/src/internal/retry.ts@@ -4,6 +4,8 @@import { DEFAULT_MAX_RETRY_DELAY, DEFAULT_RETRY_DELAY } from "./constants.js";+const RETRY_JITTER_FRACTION = 0.25;+/*** Compute backoff with decorrelated jitter* @param attempt - The current attempt number (0-indexed)@@ -21,6 +23,19 @@ export function computeBackoffWithJitter(return Math.random() * cappedDelay;}+/**+ * Apply bounded downward jitter to a fixed retry delay.+ *+ * The jittered value is drawn from [delay * 0.75, delay], so it never+ * exceeds the caller's existing timeout cap. A zero Retry-After hint+ * remains an immediate retry.+ */+export function applyRetryJitter(delay: number): number {+ if (delay <= 0) return Math.max(delay, 0);+ const low = delay * (1 - RETRY_JITTER_FRACTION);+ return Math.max(0, low + Math.random() * (delay - low));+}+/*** Parse Retry-After header value* @param header - The Retry-After header valuediff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex 41114913d..a55f2a44e 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -5,6 +5,8 @@* for full feature parity.*/+import type { ImageInput, ImageWireFormat } from "./images.js";+/*** Output dtype options for quantized embeddings.* Matches Python DType literal.@@ -56,8 +58,8 @@ export interface Item {id?: string;/** Text content to encode */text?: string;- /** Images as byte arrays (JPEG/PNG) for multimodal models */- images?: Uint8Array[];+ /** Images for multimodal models; converted to wire format by the client */+ images?: (ImageInput | ImageWireFormat)[];/** Document for composite-document extractors (PDF, DOCX, HTML, ...) */document?: DocumentInput;/** Pre-encoded multivector (for use with maxsim utility) */@@ -445,7 +447,7 @@ export interface SIEClientOptions {gpu?: string;/** API key for authentication (sent as Bearer token) */apiKey?: string;- /** Whether to auto-retry on 202 (provisioning) responses */+ /** Whether to auto-retry on 503 PROVISIONING responses */waitForCapacity?: boolean;/** Maximum time to wait for provisioning in milliseconds (default: 300000) */provisionTimeout?: number;@@ -778,7 +780,7 @@ export interface ChatCompletionChunk {export interface ChatCompletionOptions {/*** When `true`, retry the SAFE pre-execution capacity signals- * (`202 Accepted`, `503 MODEL_LOADING`, generic `503`) until+ * (`503 PROVISIONING`, `503 MODEL_LOADING`) until* `provisionTimeoutMs` elapses. When `false`, the first such signal* throws (`ProvisioningError` / `ModelLoadingError` / `ServerError`).* Defaults to the client's `waitForCapacity` (false unless thediff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 45d40d236..8eaa6643f 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.4"; // x-release-please-version+export const SDK_VERSION = "0.6.5"; // x-release-please-versiondiff --git a/packages/sie_ts_sdk/tests/chat.test.ts b/packages/sie_ts_sdk/tests/chat.test.tsindex fb54968e7..d502a691a 100644--- a/packages/sie_ts_sdk/tests/chat.test.ts+++ b/packages/sie_ts_sdk/tests/chat.test.ts@@ -139,13 +139,12 @@ describe("SIEClient.chatCompletions", () => {expect(init.headers.Authorization).toBe("Bearer sk-test");});- // H1: a 202 (provisioning) MUST not slip through `response.ok` and be cast- // to `ChatCompletion`. With `waitForCapacity: false` (the default-ish- // semantics for this method) the SDK must throw `ProvisioningError`.- it("throws ProvisioningError on 202 when waitForCapacity is false (H1)", async () => {+ // H1: provisioning must be a non-2xx typed capacity signal, not a successful+ // response that can be cast to `ChatCompletion`.+ it("throws ProvisioningError on 503 PROVISIONING when waitForCapacity is false (H1)", async () => {mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ detail: "provisioning" }), {- status: 202,+ new Response(JSON.stringify({ error: { code: "PROVISIONING", message: "provisioning" } }), {+ status: 503,headers: { "Content-Type": "application/json", "Retry-After": "7" },}),);@@ -160,15 +159,18 @@ describe("SIEClient.chatCompletions", () => {expect(mockFetch).toHaveBeenCalledOnce();});- it("retries a 202 then returns the parsed completion when waitForCapacity is true (H1)", async () => {+ it("retries 503 PROVISIONING then returns the parsed completion when waitForCapacity is true (H1)", async () => {vi.useFakeTimers();try {mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ detail: "provisioning" }), {- status: 202,- headers: { "Content-Type": "application/json" },- }),+ new Response(+ JSON.stringify({ error: { code: "PROVISIONING", message: "provisioning" } }),+ {+ status: 503,+ headers: { "Content-Type": "application/json" },+ },+ ),).mockResolvedValueOnce(jsonResponse(SAMPLE_COMPLETION));@@ -197,7 +199,7 @@ describe("SIEClient.chatCompletions", () => {try {mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ code: "MODEL_LOADING", message: "loading" }), {+ new Response(JSON.stringify({ error: { code: "MODEL_LOADING", message: "loading" } }), {status: 503,headers: { "Content-Type": "application/json" },}),@@ -223,17 +225,33 @@ describe("SIEClient.chatCompletions", () => {}});+ it("does not retry a generic 503 when waitForCapacity is true (H1)", async () => {+ mockFetch.mockResolvedValueOnce(jsonResponse({ detail: "service unavailable" }, 503));++ const client = new SIEClient("http://localhost:8080");+ await expect(+ client.chatCompletions(+ { model: "m", messages: [{ role: "user", content: "hi" }] },+ { waitForCapacity: true },+ ),+ ).rejects.toBeInstanceOf(ServerError);+ expect(mockFetch).toHaveBeenCalledOnce();+ });+it("throws ProvisioningError when provisioning exceeds provisionTimeoutMs (H1)", async () => {vi.useFakeTimers();try {- // Always answer 202 so the loop keeps looping until the budget is- // exhausted.+ // Always answer 503 PROVISIONING so the loop keeps looping until the+ // budget is exhausted.mockFetch.mockImplementation(() =>Promise.resolve(- new Response(JSON.stringify({ detail: "provisioning" }), {- status: 202,- headers: { "Content-Type": "application/json", "Retry-After": "5" },- }),+ new Response(+ JSON.stringify({ error: { code: "PROVISIONING", message: "provisioning" } }),+ {+ status: 503,+ headers: { "Content-Type": "application/json", "Retry-After": "5" },+ },+ ),),);diff --git a/packages/sie_ts_sdk/tests/client.test.ts b/packages/sie_ts_sdk/tests/client.test.tsindex 95c251477..d1d19bd94 100644--- a/packages/sie_ts_sdk/tests/client.test.ts+++ b/packages/sie_ts_sdk/tests/client.test.ts@@ -12,7 +12,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { SIEClient } from "../src/client.js";-import { RequestError, SIEConnectionError, ServerError } from "../src/errors.js";+import { ProvisioningError, RequestError, SIEConnectionError, ServerError } from "../src/errors.js";import { packMessage, unpackMessage } from "../src/msgpack.js";// Mock fetch globally@@ -545,7 +545,7 @@ describe("SIEClient.close()", () => {});});-describe("SIEClient retry on connection errors and generic 503s", () => {+describe("SIEClient retry on connection errors and provisioning 503s", () => {beforeEach(() => {mockFetch.mockClear();// Fake timers also fake Date.now(), which requestWithRetry uses.@@ -636,7 +636,7 @@ describe("SIEClient retry on connection errors and generic 503s", () => {await client.close();});- it("should retry on generic 503 (no error code) when waitForCapacity is true", async () => {+ it("should retry on 503 PROVISIONING when waitForCapacity is true", async () => {const client = new SIEClient("http://localhost:8080", {timeout: 30_000,provisionTimeout: 60_000,@@ -644,10 +644,18 @@ describe("SIEClient retry on connection errors and generic 503s", () => {mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ detail: "no healthy workers" }), {- status: 503,- headers: { "Content-Type": "application/json" },- }),+ new Response(+ JSON.stringify({+ error: {+ code: "PROVISIONING",+ message: "No capacity available. Server is provisioning.",+ },+ }),+ {+ status: 503,+ headers: { "Content-Type": "application/json" },+ },+ ),).mockResolvedValueOnce(createMsgpackResponse({@@ -667,25 +675,51 @@ describe("SIEClient retry on connection errors and generic 503s", () => {await client.close();});- it("should not retry on generic 503 when waitForCapacity is false", async () => {+ it("should throw ProvisioningError on 503 PROVISIONING when waitForCapacity is false", async () => {+ const client = new SIEClient("http://localhost:8080", { timeout: 1000 });++ mockFetch.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ error: {+ code: "PROVISIONING",+ message: "No capacity available. Server is provisioning.",+ },+ }),+ {+ status: 503,+ headers: { "Content-Type": "application/json", "Retry-After": "7" },+ },+ ),+ );++ await expect(+ client.encode("bge-m3", { text: "test" }, { waitForCapacity: false }),+ ).rejects.toThrow(ProvisioningError);+ expect(mockFetch).toHaveBeenCalledTimes(1);++ await client.close();+ });++ it("should not retry on generic 503 even when waitForCapacity is true", async () => {const client = new SIEClient("http://localhost:8080", { timeout: 1000 });mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ detail: "no healthy workers" }), {+ new Response(JSON.stringify({ detail: "service unavailable" }), {status: 503,headers: { "Content-Type": "application/json" },}),);await expect(- client.encode("bge-m3", { text: "test" }, { waitForCapacity: false }),+ client.encode("bge-m3", { text: "test" }, { waitForCapacity: true }),).rejects.toThrow(ServerError);expect(mockFetch).toHaveBeenCalledTimes(1);await client.close();});- it("should honor Retry-After header on generic 503", async () => {+ it("should honor Retry-After header on 503 PROVISIONING", async () => {const client = new SIEClient("http://localhost:8080", {timeout: 30_000,provisionTimeout: 60_000,@@ -693,13 +727,21 @@ describe("SIEClient retry on connection errors and generic 503s", () => {mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ detail: "no healthy workers" }), {- status: 503,- headers: {- "Content-Type": "application/json",- "Retry-After": "2", // < DEFAULT_RETRY_DELAY (5s)+ new Response(+ JSON.stringify({+ error: {+ code: "PROVISIONING",+ message: "No capacity available. Server is provisioning.",+ },+ }),+ {+ status: 503,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": "2", // < DEFAULT_RETRY_DELAY (5s)+ },},- }),+ ),).mockResolvedValueOnce(createMsgpackResponse({@@ -817,6 +859,30 @@ describe("Real-world usage patterns", () => {await client.close();});++ it("should convert images to wire format before encode serialization", async () => {+ const client = new SIEClient("http://localhost:8080");+ const imageBytes = new Uint8Array([0xff, 0xd8, 0xff, 0xe0]);++ mockFetch.mockResolvedValueOnce(+ createMsgpackResponse({+ items: [{ dense: { values: new Float32Array([0.1, 0.2]) } }],+ }),+ );++ await client.encode("colpali-v1.3", { id: "page-1", images: [imageBytes] });++ const fetchCall = mockFetch.mock.calls[0];+ const body = fetchCall?.[1]?.body as Uint8Array;+ const parsed = unpackMessage<{+ items?: { images?: { data: Uint8Array; format: string }[] }[];+ }>(body);++ expect(parsed.items?.[0]?.images?.[0]?.data).toEqual(imageBytes);+ expect(parsed.items?.[0]?.images?.[0]?.format).toBe("jpeg");++ await client.close();+ });});describe("SIEClient.score() - reranking", () => {@@ -904,6 +970,34 @@ describe("SIEClient.score() - reranking", () => {const headers = fetchCall?.[1]?.headers as Record<string, string>;expect(headers["X-SIE-MACHINE-PROFILE"]).toBe("a100-80gb");});++ it("should convert image query and items to wire format before score serialization", async () => {+ const queryImage = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 1]);+ const itemImage = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 2]);++ mockFetch.mockResolvedValueOnce(+ createMsgpackResponse({+ model: "qwen3-vl-reranker",+ scores: [{ item_id: "page-1", score: 0.9, rank: 0 }],+ }),+ );++ await client.score("qwen3-vl-reranker", { text: "rocket nozzle", images: [queryImage] }, [+ { id: "page-1", images: [itemImage] },+ ]);++ const fetchCall = mockFetch.mock.calls[0];+ const body = fetchCall?.[1]?.body as Uint8Array;+ const parsed = unpackMessage<{+ query?: { images?: { data: Uint8Array; format: string }[] };+ items?: { images?: { data: Uint8Array; format: string }[] }[];+ }>(body);++ expect(parsed.query?.images?.[0]?.data).toEqual(queryImage);+ expect(parsed.query?.images?.[0]?.format).toBe("jpeg");+ expect(parsed.items?.[0]?.images?.[0]?.data).toEqual(itemImage);+ expect(parsed.items?.[0]?.images?.[0]?.format).toBe("jpeg");+ });});describe("SIEClient.extract() - NER", () => {@@ -1014,6 +1108,27 @@ describe("SIEClient.extract() - NER", () => {expect(parsed.params?.labels).toEqual(["person", "organization", "location"]);});+ it("should convert images to wire format before extract serialization", async () => {+ const imageBytes = new Uint8Array([0xff, 0xd8, 0xff, 0xe0]);++ mockFetch.mockResolvedValueOnce(+ createMsgpackResponse({+ items: [{ entities: [] }],+ }),+ );++ await client.extract("docling", { id: "page-1", images: [imageBytes] }, { labels: [] });++ const fetchCall = mockFetch.mock.calls[0];+ const body = fetchCall?.[1]?.body as Uint8Array;+ const parsed = unpackMessage<{+ items?: { images?: { data: Uint8Array; format: string }[] }[];+ }>(body);++ expect(parsed.items?.[0]?.images?.[0]?.data).toEqual(imageBytes);+ expect(parsed.items?.[0]?.images?.[0]?.format).toBe("jpeg");+ });+it("should pass threshold option in params", async () => {mockFetch.mockResolvedValueOnce(createMsgpackResponse({diff --git a/packages/sie_ts_sdk/tests/generate.test.ts b/packages/sie_ts_sdk/tests/generate.test.tsindex ac15992a9..22eb3174d 100644--- a/packages/sie_ts_sdk/tests/generate.test.ts+++ b/packages/sie_ts_sdk/tests/generate.test.ts@@ -200,7 +200,7 @@ describe("SIEClient.generate", () => {* `fetch` `TypeError` — which can be raised for a connection dropped* AFTER the request body was sent (mid-flight) — must NOT be retried.* Retrying would issue a SECOND billable generation. The safe- * pre-execution capacity signals (202 provisioning, 503 MODEL_LOADING)+ * pre-execution capacity signals (503 PROVISIONING, 503 MODEL_LOADING)* are detected from the HTTP status and ARE still retried.*/describe("SIEClient.generate retry semantics (B1c)", () => {@@ -242,22 +242,29 @@ describe("SIEClient.generate retry semantics (B1c)", () => {expect(mockFetch).toHaveBeenCalledOnce();});- it("still retries the safe 202 provisioning status path under waitForCapacity", async () => {+ it("still retries the safe 503 PROVISIONING status path under waitForCapacity", async () => {vi.useFakeTimers();const client = new SIEClient("http://localhost:8080", {timeout: 30_000,provisionTimeout: 60_000,});- mockFetch.mockResolvedValueOnce(new Response(null, { status: 202 })).mockResolvedValueOnce(- jsonResponse({- model: "m",- text: "ok",- finish_reason: "stop",- usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },- attempt_id: "a",- }),- );+ mockFetch+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ error: { code: "PROVISIONING", message: "provisioning" } }), {+ status: 503,+ headers: { "Content-Type": "application/json" },+ }),+ )+ .mockResolvedValueOnce(+ jsonResponse({+ model: "m",+ text: "ok",+ finish_reason: "stop",+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ attempt_id: "a",+ }),+ );const promise = client.generate("m", "hi", { maxNewTokens: 8, waitForCapacity: true });// DEFAULT_RETRY_DELAY = 5_000ms.@@ -276,7 +283,7 @@ describe("SIEClient.generate retry semantics (B1c)", () => {});const modelLoading = new Response(- JSON.stringify({ code: "MODEL_LOADING", message: "loading" }),+ JSON.stringify({ error: { code: "MODEL_LOADING", message: "loading" } }),{status: 503,headers: { "Content-Type": "application/json" },diff --git a/packages/sie_ts_sdk/tests/internal.test.ts b/packages/sie_ts_sdk/tests/internal.test.tsindex f7a95be16..fca65da9f 100644--- a/packages/sie_ts_sdk/tests/internal.test.ts+++ b/packages/sie_ts_sdk/tests/internal.test.ts@@ -10,6 +10,7 @@import { describe, expect, it } from "vitest";import {+ getErrorCode,handleError,parseCapacityInfo,parseGenerateResult,@@ -200,7 +201,7 @@ describe("GPU parameter parsing", () => {});describe("Real-world retry scenarios", () => {- it("should provide reasonable delays for 202 provisioning retries", () => {+ it("should provide reasonable delays for provisioning retries", () => {// User scenario: GPU is provisioning, need to retry with backoff// Typical provisioning takes 30-60 seconds, we should have reasonable delays@@ -249,17 +250,16 @@ describe("handleError (gateway / FastAPI bodies)", () => {});});- it("reads top-level message for 202 provisioning (no detail object)", async () => {+ it("reads 503 PROVISIONING error envelope", async () => {const res = new Response(JSON.stringify({- status: "provisioning",- gpu: "l4",- bundle: "default",- estimated_wait_s: 30,- message: "No worker available for GPU type 'l4'. Provisioning in progress.",+ error: {+ code: "PROVISIONING",+ message: "No worker available for GPU type 'l4'. Provisioning in progress.",+ },}),{- status: 202,+ status: 503,headers: { "Content-Type": "application/json", "Retry-After": "5" },},);@@ -271,15 +271,44 @@ describe("handleError (gateway / FastAPI bodies)", () => {});});- it("parses HTTP-date Retry-After for 202 provisioning", async () => {+ it("prefers X-SIE-Error-Code for OpenAI provisioning envelopes", async () => {+ const res = new Response(+ JSON.stringify({+ error: {+ code: "provisioning",+ message: "Provisioning in progress.",+ },+ }),+ {+ status: 503,+ headers: {+ "Content-Type": "application/json",+ "Retry-After": "5",+ "X-SIE-Error-Code": "PROVISIONING",+ },+ },+ );++ expect(await getErrorCode(res.clone())).toBe("PROVISIONING");+ await expect(handleError(res, "l4")).rejects.toMatchObject({+ name: "ProvisioningError",+ message: "Provisioning in progress.",+ gpu: "l4",+ retryAfter: 5000,+ });+ });++ it("parses HTTP-date Retry-After for 503 PROVISIONING", async () => {const retryAt = new Date(Date.now() + 60_000).toUTCString();const res = new Response(JSON.stringify({- status: "provisioning",- message: "Provisioning in progress.",+ error: {+ code: "PROVISIONING",+ message: "Provisioning in progress.",+ },}),{- status: 202,+ status: 503,headers: { "Content-Type": "application/json", "Retry-After": retryAt },},);diff --git a/packages/sie_ts_sdk/tests/streaming.test.ts b/packages/sie_ts_sdk/tests/streaming.test.tsindex f6634da38..52c428e2b 100644--- a/packages/sie_ts_sdk/tests/streaming.test.ts+++ b/packages/sie_ts_sdk/tests/streaming.test.ts@@ -532,13 +532,12 @@ describe("SIEClient.streamGenerate", () => {expect(cancelled()).toBe(true);});- // BUG 13a (MEDIUM): a 202 on the streaming path with waitForCapacity:false- // must reject with ProvisioningError, NOT a generic "no body" RequestError- // (Response.ok is true for 202 so it previously slipped through to the body).- it("rejects a 202 with ProvisioningError on the streaming path (BUG 13a)", async () => {+ // BUG 13a (MEDIUM): provisioning on the streaming path with+ // waitForCapacity:false must reject with ProvisioningError.+ it("rejects 503 PROVISIONING with ProvisioningError on the streaming path (BUG 13a)", async () => {mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ detail: "provisioning" }), {- status: 202,+ new Response(JSON.stringify({ error: { code: "PROVISIONING", message: "provisioning" } }), {+ status: 503,headers: { "Content-Type": "application/json", "Retry-After": "7" },}),);@@ -559,15 +558,14 @@ describe("SIEClient.streamGenerate", () => {}});- // BUG 13b (MEDIUM): the streaming path must honor waitForCapacity by- // retrying the SAFE pre-execution capacity signals (503 MODEL_LOADING / 202)- // before opening the stream — parallel to generate().+ // BUG 13b (MEDIUM): the streaming path must retry SAFE pre-execution+ // model-loading signals before opening the stream — parallel to generate().it("retries 503 MODEL_LOADING then streams the 200 when waitForCapacity:true (BUG 13b)", async () => {vi.useFakeTimers();try {mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ code: "MODEL_LOADING", message: "loading" }), {+ new Response(JSON.stringify({ error: { code: "MODEL_LOADING", message: "loading" } }), {status: 503,headers: { "Content-Type": "application/json" },}),@@ -603,41 +601,19 @@ describe("SIEClient.streamGenerate", () => {}});- it("does NOT retry 503 MODEL_LOADING when waitForCapacity:false (BUG 13b)", async () => {- mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ error: { code: "MODEL_LOADING", message: "loading" } }), {- status: 503,- headers: { "Content-Type": "application/json" },- }),- );-- const client = new SIEClient("http://localhost:8080");- const gen = client.streamGenerate(- "m",- "hi",- { maxNewTokens: 8, waitForCapacity: false },- undefined,- );- await expect(gen.next()).rejects.toBeTruthy();- expect(mockFetch.mock.calls.length).toBe(1);- });-- // A generic 503 (scale-from-zero: no / non-MODEL_LOADING error code) must- // be retried under waitForCapacity on the streaming path, matching the- // non-streaming generate() behavior.- it("retries a generic 503 then streams the 200 when waitForCapacity:true", async () => {+ it("retries 503 MODEL_LOADING even when waitForCapacity:false (BUG 13b)", async () => {vi.useFakeTimers();try {mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ detail: "no capacity" }), {+ new Response(JSON.stringify({ error: { code: "MODEL_LOADING", message: "loading" } }), {status: 503,headers: { "Content-Type": "application/json" },}),).mockResolvedValueOnce(sseResponse([- generateChunk(0, "Hello"),+ generateChunk(0, "Loaded"),generateChunk(1, "", { done: true, finish_reason: "stop" }),]),);@@ -648,27 +624,49 @@ describe("SIEClient.streamGenerate", () => {});const chunks: GenerateChunk[] = [];const consume = (async () => {- for await (const chunk of client.streamGenerate("m", "hi", {- maxNewTokens: 8,- waitForCapacity: true,- })) {+ for await (const chunk of client.streamGenerate(+ "m",+ "hi",+ { maxNewTokens: 8, waitForCapacity: false },+ undefined,+ )) {chunks.push(chunk);}})();- // DEFAULT_RETRY_DELAY between attempts for a generic 503.await vi.advanceTimersByTimeAsync(5_000);await consume;expect(mockFetch.mock.calls.length).toBe(2);- expect(chunks.map((c) => c.text_delta).join("")).toBe("Hello");+ expect(chunks.map((c) => c.text_delta).join("")).toBe("Loaded");} finally {vi.useRealTimers();}});+ // A generic 503 is not a provisioning contract. It must stay terminal even+ // when the caller opts into capacity waiting.+ it("does NOT retry a generic 503 when waitForCapacity:true", async () => {+ mockFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ detail: "service unavailable" }), {+ status: 503,+ headers: { "Content-Type": "application/json" },+ }),+ );++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamGenerate(+ "m",+ "hi",+ { maxNewTokens: 8, waitForCapacity: true },+ undefined,+ );+ await expect(gen.next()).rejects.toBeTruthy();+ expect(mockFetch.mock.calls.length).toBe(1);+ });+it("does NOT retry a generic 503 when waitForCapacity:false", async () => {mockFetch.mockResolvedValueOnce(- new Response(JSON.stringify({ detail: "no capacity" }), {+ new Response(JSON.stringify({ detail: "service unavailable" }), {status: 503,headers: { "Content-Type": "application/json" },}),@@ -692,13 +690,16 @@ describe("SIEClient.streamGenerate", () => {it("aborts promptly during a provisioning Retry-After sleep", { timeout: 3_000 }, async () => {vi.useFakeTimers();try {- // Always answer 202 so the loop stays in the provisioning sleep.+ // Always answer 503 PROVISIONING so the loop stays in the provisioning sleep.mockFetch.mockImplementation(() =>Promise.resolve(- new Response(JSON.stringify({ detail: "provisioning" }), {- status: 202,- headers: { "Content-Type": "application/json", "Retry-After": "300" },- }),+ new Response(+ JSON.stringify({ error: { code: "PROVISIONING", message: "provisioning" } }),+ {+ status: 503,+ headers: { "Content-Type": "application/json", "Retry-After": "300" },+ },+ ),),);diff --git a/pyproject.toml b/pyproject.tomlindex deb2f2d96..2bea10750 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -93,6 +93,7 @@ sie-sdk = { workspace = true }sie-bench = { workspace = true }sie-admin = { workspace = true }sie-config = { workspace = true }+sie-mcp = { workspace = true }[tool.uv.workspace]# Note: packages/sie_ts_sdk is TypeScript, not Python@@ -101,8 +102,10 @@ members = ["packages/sie_admin","packages/sie_bench","packages/sie_config",+ "packages/sie_mcp","packages/sie_sdk","packages/sie_server",+ "packages/sie_tools","integrations/sie_chroma","integrations/sie_crewai","integrations/sie_dspy",@@ -117,8 +120,8 @@ members = [[tool.pytest.ini_options]# Note: integrations are NOT in testpaths because each has its own conftest.py# which causes pytest plugin conflicts. Run with: mise run test integrations/-testpaths = ["packages/sie_server/tests", "packages/sie_sdk/tests", "packages/sie_bench/tests", "packages/sie_admin/tests", "packages/sie_config/tests", "tools/mise_tasks/tests", "tools/quality_eval/tests"]-pythonpath = ["packages/sie_server/src", "packages/sie_sdk/src", "packages/sie_bench/src", "packages/sie_admin/src", "packages/sie_config/src", "tools/mise_tasks"]+testpaths = ["packages/sie_server/tests", "packages/sie_sdk/tests", "packages/sie_bench/tests", "packages/sie_admin/tests", "packages/sie_config/tests", "packages/sie_mcp/tests", "packages/sie_tools/tests", "tools/mise_tasks/tests", "tools/quality_eval/tests"]+pythonpath = ["packages/sie_server/src", "packages/sie_sdk/src", "packages/sie_bench/src", "packages/sie_admin/src", "packages/sie_config/src", "packages/sie_mcp/src", "packages/sie_tools/src", "tools/mise_tasks"]addopts = "-m 'not integration and not docker and not model' --import-mode=importlib"asyncio_mode = "auto"markers = [@@ -381,6 +384,11 @@ ignore = ["S311", # Pseudo-random generator is fine for synthetic text generation"T201", # Script output is intentional]+# Token-reduction benchmark — self-contained `uv run --script` tools (issue #1311)+"tools/token_bench/**/*" = [+ "INP001", # Standalone scripts, not a package+ "S603", # subprocess.run with literal soffice argv (no shell, full path)+]# Rust scheduler replay harness (dev tool, not production)"scripts/perf/replay-scheduler-trace.py" = ["ANN", # Annotations relaxed in dev scriptsdiff --git a/uv.lock b/uv.lockindex 40574d463..97b151754 100644--- a/uv.lock+++ b/uv.lock@@ -21,9 +21,11 @@ members = ["sie-lancedb","sie-langchain","sie-llamaindex",+ "sie-mcp","sie-qdrant","sie-sdk","sie-server",+ "sie-tools","sie-weaviate",]overrides = [{ name = "opencv-python", marker = "sys_platform == 'never'" }]@@ -58,7 +60,7 @@ wheels = [[[package]]name = "aiohttp"-version = "3.13.5"+version = "3.14.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "aiohappyeyeballs" },@@ -67,27 +69,29 @@ dependencies = [{ name = "frozenlist" },{ name = "multidict" },{ name = "propcache" },+ { name = "typing-extensions" },{ name = "yarl" },]-sdist = { url = "https://files.pythonhosted.org/packages/77/9a/152096d4808df8e4268befa55fba462f440f14beab85e8ad9bf990516918/aiohttp-3.13.5.tar.gz", hash = "sha256:9d98cc980ecc96be6eb4c1994ce35d28d8b1f5e5208a23b421187d1209dbb7d1", size = 7858271 }-wheels = [- { url = "https://files.pythonhosted.org/packages/be/6f/353954c29e7dcce7cf00280a02c75f30e133c00793c7a2ed3776d7b2f426/aiohttp-3.13.5-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:023ecba036ddd840b0b19bf195bfae970083fd7024ce1ac22e9bba90464620e9", size = 748876 },- { url = "https://files.pythonhosted.org/packages/f5/1b/428a7c64687b3b2e9cd293186695affc0e1e54a445d0361743b231f11066/aiohttp-3.13.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:15c933ad7920b7d9a20de151efcd05a6e38302cbf0e10c9b2acb9a42210a2416", size = 499557 },- { url = "https://files.pythonhosted.org/packages/29/47/7be41556bfbb6917069d6a6634bb7dd5e163ba445b783a90d40f5ac7e3a7/aiohttp-3.13.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab2899f9fa2f9f741896ebb6fa07c4c883bfa5c7f2ddd8cf2aafa86fa981b2d2", size = 500258 },- { url = "https://files.pythonhosted.org/packages/67/84/c9ecc5828cb0b3695856c07c0a6817a99d51e2473400f705275a2b3d9239/aiohttp-3.13.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a60eaa2d440cd4707696b52e40ed3e2b0f73f65be07fd0ef23b6b539c9c0b0b4", size = 1749199 },- { url = "https://files.pythonhosted.org/packages/f0/d3/3c6d610e66b495657622edb6ae7c7fd31b2e9086b4ec50b47897ad6042a9/aiohttp-3.13.5-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:55b3bdd3292283295774ab585160c4004f4f2f203946997f49aac032c84649e9", size = 1721013 },- { url = "https://files.pythonhosted.org/packages/49/a0/24409c12217456df0bae7babe3b014e460b0b38a8e60753d6cb339f6556d/aiohttp-3.13.5-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c2b2355dc094e5f7d45a7bb262fe7207aa0460b37a0d87027dcf21b5d890e7d5", size = 1781501 },- { url = "https://files.pythonhosted.org/packages/98/9d/b65ec649adc5bccc008b0957a9a9c691070aeac4e41cea18559fef49958b/aiohttp-3.13.5-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b38765950832f7d728297689ad78f5f2cf79ff82487131c4d26fe6ceecdc5f8e", size = 1878981 },- { url = "https://files.pythonhosted.org/packages/57/d8/8d44036d7eb7b6a8ec4c5494ea0c8c8b94fbc0ed3991c1a7adf230df03bf/aiohttp-3.13.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b18f31b80d5a33661e08c89e202edabf1986e9b49c42b4504371daeaa11b47c1", size = 1767934 },- { url = "https://files.pythonhosted.org/packages/31/04/d3f8211f273356f158e3464e9e45484d3fb8c4ce5eb2f6fe9405c3273983/aiohttp-3.13.5-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:33add2463dde55c4f2d9635c6ab33ce154e5ecf322bd26d09af95c5f81cfa286", size = 1566671 },- { url = "https://files.pythonhosted.org/packages/41/db/073e4ebe00b78e2dfcacff734291651729a62953b48933d765dc513bf798/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:327cc432fdf1356fb4fbc6fe833ad4e9f6aacb71a8acaa5f1855e4b25910e4a9", size = 1705219 },- { url = "https://files.pythonhosted.org/packages/48/45/7dfba71a2f9fd97b15c95c06819de7eb38113d2cdb6319669195a7d64270/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:7c35b0bf0b48a70b4cb4fc5d7bed9b932532728e124874355de1a0af8ec4bc88", size = 1743049 },- { url = "https://files.pythonhosted.org/packages/18/71/901db0061e0f717d226386a7f471bb59b19566f2cae5f0d93874b017271f/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:df23d57718f24badef8656c49743e11a89fd6f5358fa8a7b96e728fda2abf7d3", size = 1749557 },- { url = "https://files.pythonhosted.org/packages/08/d5/41eebd16066e59cd43728fe74bce953d7402f2b4ddfdfef2c0e9f17ca274/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:02e048037a6501a5ec1f6fc9736135aec6eb8a004ce48838cb951c515f32c80b", size = 1558931 },- { url = "https://files.pythonhosted.org/packages/30/e6/4a799798bf05740e66c3a1161079bda7a3dd8e22ca392481d7a7f9af82a6/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:31cebae8b26f8a615d2b546fee45d5ffb76852ae6450e2a03f42c9102260d6fe", size = 1774125 },- { url = "https://files.pythonhosted.org/packages/84/63/7749337c90f92bc2cb18f9560d67aa6258c7060d1397d21529b8004fcf6f/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:888e78eb5ca55a615d285c3c09a7a91b42e9dd6fc699b166ebd5dee87c9ccf14", size = 1732427 },- { url = "https://files.pythonhosted.org/packages/98/de/cf2f44ff98d307e72fb97d5f5bbae3bfcb442f0ea9790c0bf5c5c2331404/aiohttp-3.13.5-cp312-cp312-win32.whl", hash = "sha256:8bd3ec6376e68a41f9f95f5ed170e2fcf22d4eb27a1f8cb361d0508f6e0557f3", size = 433534 },- { url = "https://files.pythonhosted.org/packages/aa/ca/eadf6f9c8fa5e31d40993e3db153fb5ed0b11008ad5d9de98a95045bed84/aiohttp-3.13.5-cp312-cp312-win_amd64.whl", hash = "sha256:110e448e02c729bcebb18c60b9214a87ba33bac4a9fa5e9a5f139938b56c6cb1", size = 460446 },+sdist = { url = "https://files.pythonhosted.org/packages/ee/ab/93ce242f899b68c51b0578c027aafa791ab3614cb9345fa5d37b5f5c8e3e/aiohttp-3.14.0.tar.gz", hash = "sha256:2882de819734c715fd1b9c11c97e09fa020d14438203d1d354d8ed1702791c9b", size = 7940674 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/89/97/2b6889bfb6b6847520d50d95eb8c4307a45e28aaca39faf4a9454b3d1b2f/aiohttp-3.14.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:b29518c9c2ec7e373e68259206a137c7f4f5439c58baaec4b5ab3ab799850a4e", size = 750194 },+ { url = "https://files.pythonhosted.org/packages/21/e2/62634b7fff918ed98c3c6b2f0e70d520f7f28846cb412d451b04354c6459/aiohttp-3.14.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:dbec68ce61b64cb73cab4d33df9433427b1713c8bcccb181dce695c1b6f8e87c", size = 506966 },+ { url = "https://files.pythonhosted.org/packages/dd/fb/5ce075150828c797a5106f1c2fb26034e709d4289b9d2bf8b07f1e59fac6/aiohttp-3.14.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3cdf534aa455593e589302990c5097aa5c92c06c4262a20da22934f9186a5fff", size = 507527 },+ { url = "https://files.pythonhosted.org/packages/01/d5/405a0ae4e6b081754a3609c1c97c63a950e000a2def16046f1e736933a0e/aiohttp-3.14.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cb6c657104393b5fbff01a5f59b2023db74058a8077d94475d6c25d03882a108", size = 1762420 },+ { url = "https://files.pythonhosted.org/packages/ae/1d/e05a7c896b15a6bc6fb8fc5319eb437861c2c49c34559ef928add6590315/aiohttp-3.14.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:46fbbec4e4fab7428d4396a3823f9320e4560aa3113b89eeebce712c27c9ed5a", size = 1733672 },+ { url = "https://files.pythonhosted.org/packages/cc/22/a72f7c459e195fa41bf4f7abd1f925b91fe91f8097e51c654229ba144a33/aiohttp-3.14.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2c2c7e05dd5335b298085abf45ddf98673934c3ee1c083d0b9ea13d4186ad500", size = 1805064 },+ { url = "https://files.pythonhosted.org/packages/80/50/e85bdaba0be59ca4838005ebfef4048fcdd5f35a02b07057a9a123394440/aiohttp-3.14.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3c7139100fbaae76515b73051d8f0aa3a3ff02e415eec8a8eee8e2223d9ba955", size = 1902125 },+ { url = "https://files.pythonhosted.org/packages/19/d8/51de5c6b971c27bb1ef620293b8d1ca611ec78736b34b3f6ccf68e4c8785/aiohttp-3.14.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78d6f9286a629ce52728430afe18f8ed2b6c39a1fddb3802d7244b9983910ad2", size = 1783112 },+ { url = "https://files.pythonhosted.org/packages/73/ae/b4402bfde77e43dfb1b6ccff83c7b7ab63ed06b50c4754f0c5423fb374fe/aiohttp-3.14.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cc3c3e12cdaeb92d7dcf13db00e9f6b1956b910e47256e696df1cfa946d02159", size = 1586356 },+ { url = "https://files.pythonhosted.org/packages/bc/05/750a3265ca4dc54a460bd0cb1121a8f2ce9171fce4a135fb47ea7fd594d2/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4d6a998191f5ebe3b8c28463ff72bc030250008b3193c402464efadd08b5ca02", size = 1723119 },+ { url = "https://files.pythonhosted.org/packages/37/01/8c0812c50b3b1b1c37b323bf170d6be8847a8f234060485b7d1e71953f60/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:0fc2b75ae8d169d853be2862d960be8550da6c5c65711d5476407eb3fdb006bd", size = 1757216 },+ { url = "https://files.pythonhosted.org/packages/47/2a/50fb98028a26887cbe48dcc1df92a90825615bc73b5584301304090cded8/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:16eee56bcc72d04600bc56c1759982c2385ec0b41d3fd3521f836bf64a0957ef", size = 1770500 },+ { url = "https://files.pythonhosted.org/packages/bd/32/0ffd598a2fa2b9a423daf242e700cfdabda35d6e602394ad9ae58972c1c7/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:5a2e7ca615c3ddc15b82687e05a624e5f5cba3f1d6c20cb81172d70ea498451e", size = 1576224 },+ { url = "https://files.pythonhosted.org/packages/0b/f9/b9fc381dd9b66afb33f2634c40e229d106467be0afcabe79648631ab6712/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:f0b7b8bbbec3ce9467ee0ebe334622fd90624f593edd3136c567811453fc4fae", size = 1794252 },+ { url = "https://files.pythonhosted.org/packages/a8/fb/05d9214c975f23225a8cd5c439325e338c7c377b315480ef3871db51f54e/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5ba10966d4f03dd96a14365be4b8e37c327c76f11c3ca867116966cdd9f98066", size = 1760193 },+ { url = "https://files.pythonhosted.org/packages/d9/4b/02992fc4fb9e1b6673ee3f888a8e587a6447afda1f6f4aca776c148c2876/aiohttp-3.14.0-cp312-cp312-win32.whl", hash = "sha256:101df7779c80c0636014a6b2c6642acd3efb5b355d48347c9d7dfb720aee9430", size = 448650 },+ { url = "https://files.pythonhosted.org/packages/39/e9/246532214c3abda518477cbaaf16d420295ad8effa5233844cbb38f299ab/aiohttp-3.14.0-cp312-cp312-win_amd64.whl", hash = "sha256:b0a5747586d4467efd1f932710b269131c9717a872dce082cd92a00c1c13123a", size = 476145 },+ { url = "https://files.pythonhosted.org/packages/2b/c3/63f8c20090048915711598b0adf475b149216d736157961de06480a45b15/aiohttp-3.14.0-cp312-cp312-win_arm64.whl", hash = "sha256:5f1c5be60add78fabb4aacd13c5a348ae79d2fcbfc7fa78da8f1eb192273b370", size = 444250 },][[package]]@@ -2019,6 +2023,15 @@ http2 = [{ name = "h2" },]+[[package]]+name = "httpx-sse"+version = "0.4.3"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/0f/4c/751061ffa58615a32c31b2d82e8482be8dd4a89154f003147acee90f2be9/httpx_sse-0.4.3.tar.gz", hash = "sha256:9b1ed0127459a66014aec3c56bebd93da3c1bc8bb6618c8082039a44889a755d", size = 15943 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960 },+]+[[package]]name = "huey"version = "2.6.0"@@ -3075,6 +3088,31 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/af/33/ee4519fa02ed11a94aef9559552f3b17bb863f2ecfe1a35dc7f548cde231/matplotlib_inline-0.2.1-py3-none-any.whl", hash = "sha256:d56ce5156ba6085e00a9d54fead6ed29a9c47e215cd1bba2e976ef39f5710a76", size = 9516 },]+[[package]]+name = "mcp"+version = "1.27.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "anyio" },+ { name = "httpx" },+ { name = "httpx-sse" },+ { name = "jsonschema" },+ { name = "pydantic" },+ { name = "pydantic-settings" },+ { name = "pyjwt", extra = ["crypto"] },+ { name = "python-multipart" },+ { name = "pywin32", marker = "sys_platform == 'win32'" },+ { name = "sse-starlette" },+ { name = "starlette" },+ { name = "typing-extensions" },+ { name = "typing-inspection" },+ { name = "uvicorn", marker = "sys_platform != 'emscripten'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/27/3c/347cf965d313f5d41764e7d46bea6ffe7d9ef13b983cc429b0340962a082/mcp-1.27.2.tar.gz", hash = "sha256:8e02db104096d1c25b28e64bde29a5c32b31bc241710213e12fd4d84985bdfef", size = 621116 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c9/11/252c6f971dc4f16af1d98a1c469d8ba523aab00d1bb76b4d3bc1ff32eacc/mcp-1.27.2-py3-none-any.whl", hash = "sha256:d6ff5160c6ca65d93013626efb3fc249de683c30b2d8570755ceddd490344de5", size = 220498 },+]+[[package]]name = "mdit-py-plugins"version = "0.5.0"@@ -5017,6 +5055,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/6c/73/9f872cb81fc5c3bb48f7227872c28975f998f3e7c2b1c16e95e6432bbb90/python_magic-0.4.27-py2.py3-none-any.whl", hash = "sha256:c212960ad306f700aa0d01e5d7a325d20548ff97eb9920dcd29513174f0294d3", size = 13840 },]+[[package]]+name = "python-multipart"+version = "0.0.32"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/5b/42/55c32bb9b12693c092ad250a0e82edb5b31ddeda6eb772de5f308b3804ad/python_multipart-0.0.32.tar.gz", hash = "sha256:be54b7f3fa167bb83e4fcd936b887b708f4e57fe75911c02aebf53efaf8d938e", size = 46881 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23", size = 30042 },+]+[[package]]name = "python-pptx"version = "1.0.2"@@ -5671,7 +5718,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.6.4"+version = "0.6.5"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5704,7 +5751,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.6.4"+version = "0.6.5"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5789,7 +5836,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.6.4"+version = "0.6.5"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5861,7 +5908,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.4"+version = "0.6.5"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5886,7 +5933,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.4"+version = "0.6.5"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5911,7 +5958,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.4"+version = "0.6.5"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5938,7 +5985,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.4"+version = "0.6.5"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -5965,7 +6012,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.4"+version = "0.6.5"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -5992,7 +6039,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.4"+version = "0.6.5"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -6017,9 +6064,48 @@ requires-dist = [{ name = "sie-sdk", editable = "packages/sie_sdk" },]+[[package]]+name = "sie-mcp"+version = "0.1.0"+source = { editable = "packages/sie_mcp" }+dependencies = [+ { name = "jsonschema" },+ { name = "mcp" },+ { name = "pillow" },+ { name = "pypdfium2" },+ { name = "sie-sdk" },+ { name = "starlette" },+ { name = "typer" },+ { name = "uvicorn", extra = ["standard"] },+]++[package.dev-dependencies]+dev = [+ { name = "pytest" },+ { name = "pytest-asyncio" },+]++[package.metadata]+requires-dist = [+ { name = "jsonschema", specifier = ">=4" },+ { name = "mcp", specifier = ">=1.9,<2" },+ { name = "pillow", specifier = ">=12.2.0" },+ { name = "pypdfium2", specifier = ">=5.6.0" },+ { name = "sie-sdk", editable = "packages/sie_sdk" },+ { name = "starlette", specifier = ">=0.40" },+ { name = "typer", specifier = ">=0.14,<1" },+ { name = "uvicorn", extras = ["standard"], specifier = ">=0.32,<1" },+]++[package.metadata.requires-dev]+dev = [+ { name = "pytest", specifier = ">=9.0.3" },+ { name = "pytest-asyncio", specifier = ">=1.0" },+]+[[package]]name = "sie-qdrant"-version = "0.6.4"+version = "0.6.5"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -6042,7 +6128,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.4"+version = "0.6.5"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -6095,7 +6181,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.4"+version = "0.6.5"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -6208,9 +6294,24 @@ requires-dist = [[package.metadata.requires-dev]dev = []+[[package]]+name = "sie-tools"+version = "0.1.0"+source = { editable = "packages/sie_tools" }+dependencies = [+ { name = "sie-sdk" },+ { name = "typer" },+]++[package.metadata]+requires-dist = [+ { name = "sie-sdk", editable = "packages/sie_sdk" },+ { name = "typer", specifier = ">=0.12,<1" },+]+[[package]]name = "sie-weaviate"-version = "0.6.4"+version = "0.6.5"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },@@ -6355,6 +6456,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/49/4b/359f28a903c13438ef59ebeee215fb25da53066db67b305c125f1c6d2a25/sqlparse-0.5.5-py3-none-any.whl", hash = "sha256:12a08b3bf3eec877c519589833aed092e2444e68240a3577e8e26148acc7b1ba", size = 46138 },]+[[package]]+name = "sse-starlette"+version = "3.4.4"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "anyio" },+ { name = "starlette" },+]+sdist = { url = "https://files.pythonhosted.org/packages/f7/2b/58abc2d1fd397e7dde08e947e05c884d8ef2f78d5e2588c17a12d42d6994/sse_starlette-3.4.4.tar.gz", hash = "sha256:07e0fa0460138baf25cdd5fb28683472c3995dc1642225191b3832d62526bcb0", size = 31819 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/dc/67/805710444ea8cc75fbf70b920ed431a560c4bf9c57f7d5a3117213189399/sse_starlette-3.4.4-py3-none-any.whl", hash = "sha256:3f4dd50d8aed2771a091f3a83000323fc3844541c16b4fe585ae2420cc6df973", size = 16514 },+]+[[package]]name = "stack-data"version = "0.6.3"@@ -6391,15 +6505,15 @@ wheels = [[[package]]name = "starlette"-version = "1.0.0"+version = "1.0.1"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "anyio" },{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/81/69/17425771797c36cded50b7fe44e850315d039f28b15901ab44839e70b593/starlette-1.0.0.tar.gz", hash = "sha256:6a4beaf1f81bb472fd19ea9b918b50dc3a77a6f2e190a12954b25e6ed5eea149", size = 2655289 }+sdist = { url = "https://files.pythonhosted.org/packages/08/a3/84e821cc54b4ab50ae6dbc6ac3800a651b65ec35f045cc73785380654057/starlette-1.0.1.tar.gz", hash = "sha256:512399c5f1de7fac99c88572212ded9ddeddef2fb32afa82d724000e88b38f4f", size = 2659596 }wheels = [- { url = "https://files.pythonhosted.org/packages/0b/c9/584bc9651441b4ba60cc4d557d8a547b5aff901af35bda3a4ee30c819b82/starlette-1.0.0-py3-none-any.whl", hash = "sha256:d3ec55e0bb321692d275455ddfd3df75fff145d009685eb40dc91fc66b03d38b", size = 72651 },+ { url = "https://files.pythonhosted.org/packages/ec/e1/b2df4bc09a1e51ff664c1e17018a4274b42e5e9352e4a478ea540512dc88/starlette-1.0.1-py3-none-any.whl", hash = "sha256:7c0e69b2ee1c848bd54669d908500117a3ee13de603a21427e5c6fc1adf98dcd", size = 72802 },][[package]]@@ -7137,28 +7251,28 @@ wheels = [[[package]]name = "uv"-version = "0.11.7"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/9b/7d/17750123a8c8e324627534fe1ae2e7a46689db8492f1a834ab4fd229a7d8/uv-0.11.7.tar.gz", hash = "sha256:46d971489b00bdb27e0aa715e4a5cd4ef2c28ea5b6ef78f2b67bf861eb44b405", size = 4083385 }-wheels = [- { url = "https://files.pythonhosted.org/packages/b2/5b/2bb2ab6fe6c78c2be10852482ef0cae5f3171460a6e5e24c32c9a0843163/uv-0.11.7-py3-none-linux_armv6l.whl", hash = "sha256:f422d39530516b1dfb28bb6e90c32bb7dacd50f6a383cd6e40c1a859419fbc8c", size = 23757265 },- { url = "https://files.pythonhosted.org/packages/b2/f5/36ff27b01e60a88712628c8a5a6003b8e418883c24e084e506095844a797/uv-0.11.7-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:8b2fe1ec6775dad10183e3fdce430a5b37b7857d49763c884f3a67eaa8ca6f8a", size = 23184529 },- { url = "https://files.pythonhosted.org/packages/8a/fa/f379be661316698f877e78f4c51e5044be0b6f390803387237ad92c4057f/uv-0.11.7-py3-none-macosx_11_0_arm64.whl", hash = "sha256:162fa961a9a081dcea6e889c79f738a5ae56507047e4672964972e33c301bea9", size = 21780167 },- { url = "https://files.pythonhosted.org/packages/f2/7f/fbed29775b0612f4f5679d3226268f1a347161abc1727b4080fb41d9f46f/uv-0.11.7-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:5985a15a92bd9a170fc1947abb1fbc3e9828c5a430ad85b5bed8356c20b67a71", size = 23609640 },- { url = "https://files.pythonhosted.org/packages/ad/de/989a69634a869a22322770120557c2d8cbba5b77ec7cfad326b4ec0f0547/uv-0.11.7-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.musllinux_1_1_armv7l.whl", hash = "sha256:fab0bb43fbbc0ee5b5fee212078d2300c371b725faff7cf72eeaafa0bff0606b", size = 23322484 },- { url = "https://files.pythonhosted.org/packages/24/08/c1af05ea602eb4eb75d86badb6b0594cc104c3ca83ccf06d9ed4dd2186ad/uv-0.11.7-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:23d457d6731ebdb83f1bffebe4894edab2ef43c1ec5488433c74300db4958924", size = 23326385 },- { url = "https://files.pythonhosted.org/packages/68/99/e246962da06383e992ecab55000c62a50fb36efef855ea7264fad4816bf4/uv-0.11.7-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7d6a17507b8139b8803f445a03fd097f732ce8356b1b7b13cdb4dd8ef7f4b2e0", size = 24985751 },- { url = "https://files.pythonhosted.org/packages/45/2d/b0b68083859579ce811996c1480765ec6a2442b44c451eaef53e6218fbae/uv-0.11.7-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dd48823ca4b505124389f49ae50626ba9f57212b9047738efc95126ed5f3844d", size = 25724160 },- { url = "https://files.pythonhosted.org/packages/4e/19/5970e89d9e458fd3c4966bbc586a685a1c0ab0a8bf334503f63fa20b925b/uv-0.11.7-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:eb91f52ee67e10d5290f2c2897e2171357f1a10966de38d83eefa93d96843b0c", size = 25028512 },- { url = "https://files.pythonhosted.org/packages/83/eb/4e1557daf6693cb446ed28185664ad6682fd98c6dbac9e433cbc35df450a/uv-0.11.7-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e4d5e31bea86e1b6e0f5a0f95e14e80018e6f6c0129256d2915a4b3d793644d", size = 24933975 },- { url = "https://files.pythonhosted.org/packages/68/55/3b517ec8297f110d6981f525cccf26f86e30883fbb9c282769cffbcdcfca/uv-0.11.7-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:ceae53b202ea92bc954759bc7c7570cdcd5c3512fce15701198c19fd2dfb8605", size = 23706403 },- { url = "https://files.pythonhosted.org/packages/dc/30/7d93a0312d60e147722967036dc8ea37baab4802784bddc22464cb707deb/uv-0.11.7-py3-none-manylinux_2_31_riscv64.musllinux_1_1_riscv64.whl", hash = "sha256:f97e9f4e4d44fb5c4dfaa05e858ef3414a96416a2e4af270ecd88a3e5fb049a9", size = 24495797 },- { url = "https://files.pythonhosted.org/packages/8c/89/d49480bdab7725d36982793857e461d471bde8e1b7f438ffccee677a7bf8/uv-0.11.7-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:750ee5b96959b807cf442b73dd8b55111862d63f258f896787ea5f06b68aaca9", size = 24580471 },- { url = "https://files.pythonhosted.org/packages/b6/9f/c57dc03b48be17b564e304eb9ff982890c12dfb888b1ce370788733329ab/uv-0.11.7-py3-none-musllinux_1_1_i686.whl", hash = "sha256:f394331f0507e80ee732cb3df737589de53bed999dd02a6d24682f08c2f8ac4f", size = 24113637 },- { url = "https://files.pythonhosted.org/packages/13/ba/b87e358b629a68258527e3490e73b7b148770f4d2257842dea3b7981d4e8/uv-0.11.7-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:0df59ab0c6a4b14a763e8445e1c303af9abeb53cdfa4428daf9ff9642c0a3cce", size = 25119850 },- { url = "https://files.pythonhosted.org/packages/4b/74/16d229e1d8574bcbafa6dc643ac20b70c3e581f42ac31a6f4fd53035ffe3/uv-0.11.7-py3-none-win32.whl", hash = "sha256:553e67cc766d013ce24353fecd4ea5533d2aedcfd35f9fac430e07b1d1f23ed4", size = 22918454 },- { url = "https://files.pythonhosted.org/packages/a6/1d/b73e473da616ac758b8918fb218febcc46ddf64cba9e03894dfa226b28bd/uv-0.11.7-py3-none-win_amd64.whl", hash = "sha256:5674dfb5944513f4b3735b05c2deba6b1b01151f46729d533d413a9a905f8c5d", size = 25447744 },- { url = "https://files.pythonhosted.org/packages/1b/bb/e6bfdea92ed270f3445a5a3c17599d041b3f2dbc5026c09e02830a03bbaf/uv-0.11.7-py3-none-win_arm64.whl", hash = "sha256:6158b7e39464f1aa1e040daa0186cae4749a78b5cd80ac769f32ca711b8976b1", size = 23941816 },+version = "0.11.15"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/da/34/609d5d01ba21dc8f0974610ca7802fbb2c946a0c38665cfe5c5aeddbefb5/uv-0.11.15.tar.gz", hash = "sha256:755f959ec6a2fd8ccb6ee76ad90ab759d2eb1f4797444078645dd1ee4bca92d6", size = 4159545 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a6/7c/dcc230c5911884d8848145dabcac8fb95a5ed6f9fe1c57fae8242618f28a/uv-0.11.15-py3-none-linux_armv6l.whl", hash = "sha256:83b04ab49514a0a761ffedb36a748ee81f87746671e72088e5f32c9585e5f1a9", size = 23110183 },+ { url = "https://files.pythonhosted.org/packages/f4/f3/efd4e044b60eb9c3c12ee386be098d56c335538ccec7caa49349cfba9344/uv-0.11.15-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b6cae61f737be075b90be9e3f07d961072aed7019f4c9b8ed5c5d41c4d6cade3", size = 22637941 },+ { url = "https://files.pythonhosted.org/packages/a6/b8/48627f895a1569e576822e0a8416aa4797eb4a4551de21a4ad97b9b5819d/uv-0.11.15-py3-none-macosx_11_0_arm64.whl", hash = "sha256:9accae33619a9166e5c48531deb455d672cfb89f9357a00975e669c76b0bd49f", size = 21258803 },+ { url = "https://files.pythonhosted.org/packages/af/50/4bc8a148274feabee2d9c9f1fa15009e10c0228dfe57981ee3ea2ef1d481/uv-0.11.15-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:c0cf52cd6d50bb9e05e2d968f45f80761107e4cbc8d4a26d9758f9d8274aaec1", size = 23066178 },+ { url = "https://files.pythonhosted.org/packages/a9/56/139fc3bec9a8b0a25bfe2196123adb9f16124da437bf4fbcf0d21cfcafb2/uv-0.11.15-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.musllinux_1_1_armv7l.whl", hash = "sha256:49dc6ed70bff00937384f96cdc4b1a4742d18e5504ec2c4a1214dba2dee5687a", size = 22705332 },+ { url = "https://files.pythonhosted.org/packages/ca/b0/b18b3dd204f8c213236a1ebd148e009861637129a8cce34df0e9aa22ed40/uv-0.11.15-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:adb9a89352539fdd8f7cd5f9966cf9f94fc5b98e0ccdf5003a04123dc6423bec", size = 22707534 },+ { url = "https://files.pythonhosted.org/packages/76/36/3ca09f95572df99d361b49c96b1297149e96e120d8d1ecf074095a4b6da4/uv-0.11.15-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40ff67e3f8e8a7533781a2e892a534975a93acb83ea35460e64e7b2bf2111774", size = 24096607 },+ { url = "https://files.pythonhosted.org/packages/64/be/3bdee21a296bbf5336a526e3613d0e7d4538dacc39c62d7fcba55d15f6b0/uv-0.11.15-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c6463a299ed7e6b5a800ed6f108af8e1588352629424133ddef7572b0e1e1118", size = 25082562 },+ { url = "https://files.pythonhosted.org/packages/cd/73/f371f3689ffe741066468d001d85f739fc4b5574de83b639ef19b5e8a7f4/uv-0.11.15-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:68c1e62d4b78578b90b833553286b65d6a7e327537716441068583ba652ec4f5", size = 24253391 },+ { url = "https://files.pythonhosted.org/packages/d3/16/fe392d618af6b00c064b3e718d585dcf791546a77c5123a5bec07ce53a0a/uv-0.11.15-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:98edf1bdaf82447014852051d93e3ee95012509c567bf057fd117e6bdbd9a807", size = 24415871 },+ { url = "https://files.pythonhosted.org/packages/6e/24/2e92a052fb6334fcd746d1c7cb57847c204b118c84f5da53c0f9e129f7b7/uv-0.11.15-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:be8f76d25bcf4c92bb384240ac1bf9aa7f51063d0bdeca4c9cf0ec3ed8b145e0", size = 23159007 },+ { url = "https://files.pythonhosted.org/packages/3d/2e/6923d0658d164bb2c435ed1868aa2d49b3074594679917a001ff92dc95bb/uv-0.11.15-py3-none-manylinux_2_31_riscv64.musllinux_1_1_riscv64.whl", hash = "sha256:f9f4fbbf4fe485522054f3c7496c6e8e932d6436e4200ff3daf718db0b7c7bd5", size = 23769385 },+ { url = "https://files.pythonhosted.org/packages/a4/99/7e34cd949e57360814e8064cc9fb7104df445d0f6a663504e5f7473480aa/uv-0.11.15-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:0ed920e896b2fd13a35031707e307e42fbb2681458b967440a17272d86d49137", size = 23860973 },+ { url = "https://files.pythonhosted.org/packages/28/98/8fe1f5f9d816e94569a0298dd8e0936801097625fa1952162951f0d628b6/uv-0.11.15-py3-none-musllinux_1_1_i686.whl", hash = "sha256:41d907611f3e6a13262807fd7f0a17849f76285ca80f536f6b3943732bdc6656", size = 23431392 },+ { url = "https://files.pythonhosted.org/packages/cc/6b/76a1ce2fa860026913a5941700cdc7d715fce9c3277a3fa3489cf2523ca0/uv-0.11.15-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:e3b68f8bf1a4568710f77e5bda9182ce7682811d89a8e7468c22460e032b234d", size = 24519478 },+ { url = "https://files.pythonhosted.org/packages/43/60/1d58e8a05718cb50494763115710b73846cacb651fd735d285233fd72c59/uv-0.11.15-py3-none-win32.whl", hash = "sha256:8e2da3076761086a5b76869c3f38ef0509c836046ef41ddd19485dfd7271dca9", size = 22020178 },+ { url = "https://files.pythonhosted.org/packages/55/53/40fcefcb348af660488597ed3c01363df7344e60611f8883750dc596f5c6/uv-0.11.15-py3-none-win_amd64.whl", hash = "sha256:cc3915ab291a1ecaf31de05f5d8bd70d09c66fe9911a53f70d9efa62ff0dbd8a", size = 24668779 },+ { url = "https://files.pythonhosted.org/packages/e5/7d/fa3a9960c95af9bbe2a629048760d0b9b4fead8ccd4f2235af747ec7cdf0/uv-0.11.15-py3-none-win_arm64.whl", hash = "sha256:4f39426a13dee24897aed60c4b98058c66f18bd983885ac5f4a54a04b24fbddf", size = 23198178 },][[package]]