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.11
github-actions[bot]b401a978964f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex efef53714..6e11a4ce0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,42 @@# Changelog+## v0.6.11++- chore(main): release 0.6.11+- fix: handle sidecar progress ack failures+- fix: harden worker-direct batch fallback+- fix: align retryable generation review feedback+- fix: preserve queue delivery budget+- fix: return retryable model loading for generation+- test: cover default-backed pinned pool gauge+- fix: harden logical pool queue routing+- docs: clarify logical pool backing queues+- feat: support logical pools backed by queue pools+- refactor(bench): re-task Florence-2-base to COCO detection (card metric), keep OCR fallback (#1437)+- fix(ci): raise uv HTTP timeout for the gemma cu130 wheel downloads+- docs(deploy): note machineProfiles entry for the gemma example pool+- feat(deploy): fail fast when a bundle is placed on the wrong platform+- docs(server): accurately scope what the gemma cuda13 CI smoke covers+- fix(server): correct stale cuda13/gemma platform references+- refactor(bench): re-task Florence-2-base to OCR, measure on olmOCR-bench not KIE (#1437)+- feat(server): first-class cuda13 platform for the gemma bundle+- fix(server): make transformers version bundle-controlled+- docs(server): correct the gemma cu130 Docker validation comments+- fix(server): parse --mamba-scheduler-strategy value exactly in spec guard+- fix(server): route grammar off :mtp for Gemma 4 via grammar_profile+- test(server): surface errors and non-settling tasks in pinned-load drain helper+- fix(worker): make pinned models profile-aware and reconcile on config arrival+- docs(helm): trim staticQueuePools pinnedModels comment to effect-only+- feat(worker): bridge gateway pinned-model set to the worker at runtime+- docs(server): mark gemma-4-26B-A4B mtp profile validated (Modal H200)+- feat(server): extend pinned-model protection to the disk cache+- fix(server): gemma Docker builder — effective uv cache, skip bytecode, fix comment+- fix(server): drop FP8 from gemma-4-26B-A4B (BF16 only)+- feat(server): keep pinned models loaded and exclude them from LRU eviction+- fix(server): require extra_buffer value in the speculative mamba-scheduler guard+- fix(server): wire per-bundle CUDA indexes into the cuda12 Docker builder+- feat(server): add Gemma 4 generation models (E2B, E4B, 26B-A4B)+## v0.6.10- chore(main): release 0.6.10diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex b741b695c..daa243f2c 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.10 # x-release-please-version-appVersion: v0.6.10 # x-release-please-version+version: 0.6.11 # x-release-please-version+appVersion: v0.6.11 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex da84e1f80..f1927abf7 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -135,7 +135,7 @@ one machine profile. Multi-profile tenant pools should send both headers.|--------|--------|---------|| `sie_gateway_pending_demand` | Gateway | Trigger scale from 0 || `sie_gateway_worker_queue_depth` | Gateway worker registry | Scale up on queued work in the exact pool/profile/bundle lane |-| `sie_gateway_active_lease_gpus` | Gateway pool manager | Hold capacity for active pool leases in the exact pool/profile/bundle lane |+| `sie_gateway_active_lease_gpus` | Gateway pool manager | Hold distinct assigned-worker capacity for active pool leases in the exact pool/profile/bundle lane || `sie_gateway_rejected_requests_total` | Gateway | Scale up on sustained capacity/no-worker rejections after retryable cold-load reasons are excluded |### Worker-sidecar Metrics@@ -172,15 +172,16 @@ rtx6000 default bundle scales 3–10 — see# Worker pool configuration (must explicitly enable pools)# The map key is the Kubernetes capacity family/resource name. When# machineProfile is omitted, it defaults to that map key. machineProfile is the-# runtime lane label used by routing and metrics. queuePool is the logical-# queue namespace / tenant boundary; by default all worker groups use the-# shared `default` queue pool so SDK calls can pass just gpu="<profile>".-# Set queuePool on a worker group only for a dedicated tenant/logical pool,-# then target it explicitly as gpu="<queuePool>/<machineProfile>".-# With poolAdmission enabled, named non-default queue pools must also exist as-# gateway-visible pool objects. For deploy-owned pools, declare them under-# queueRouting.staticQueuePools. For API-owned pools, create/renew them through-# /v1/pools.+# runtime lane label used by routing and metrics. queuePool is the physical+# NATS queue namespace consumed by the workers; by default all worker groups+# use the shared `default` queue pool so SDK calls can pass just+# gpu="<profile>". Set queuePool on a worker group only for dedicated physical+# capacity, then create logical pools backed by it through `/v1/pools`+# (`queue_pool: "<queuePool>"`) and target them as+# gpu="<logicalPool>/<machineProfile>".+# With poolAdmission enabled, named non-default queue pools pull only when+# their physical queue pool is admitted directly (staticQueuePools) or when an+# assigned logical pool is backed by that queue.# Each worker group renders its own StatefulSet + ScaledObject named# worker-<pool>-<bundle>.workers:@@ -197,15 +198,15 @@ workers:default: # embedding/rerank baselineminReplicas: 1maxReplicas: 5- sglang: # generation, scale-from-zero on same GPUs- minReplicas: 0+ sglang: # generation, warm baseline on same GPUs+ minReplicas: 1maxReplicas: 5preloadModels:- - Qwen/Qwen3.6-27B:rtx-pro-6000+ - Qwen/Qwen3-4B-Instruct-2507# Gateway configurationgateway:- replicaCount: 2 # HA by default+ replicas: 2# Autoscalingautoscaling:@@ -220,6 +221,8 @@ Use one of these patterns deliberately:- **Shared baseline pool**: leave `workers.common.queuePool: default`.Workers render with `SIE_POOL=default` and their own`SIE_MACHINE_PROFILE`; SDK calls use `gpu="<machineProfile>"`.+ API-created logical pools can use arbitrary valid names over this lane by+ omitting `queue_pool`.- **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@@ -242,16 +245,21 @@ Use one of these patterns deliberately:`gpuCaps: {}` means uncapped admission for matching workers. Use`gpuCaps: {l4: 10}` to cap admission for that machine profile.- **Dynamic isolated pool**: set a worker group's `queuePool` to the dedicated- pool name, keep `queueRouting.poolAdmission.enabled=true`, and create/renew- the matching pool through `/v1/pools`. SDK calls use- `gpu="<queuePool>/<machineProfile>"`.+ physical queue name, declare the same name under+ `queueRouting.staticQueuePools`, keep+ `queueRouting.poolAdmission.enabled=true`, and create/renew logical pools+ through `/v1/pools` with `queue_pool` set to that physical queue. Use a+ logical pool name that does not collide with the protected static queue-pool+ name, or target the static pool directly. SDK calls use+ `gpu="<logicalPool>/<machineProfile>"`.Missing named pools intentionally do not fail open. Falling back from`pool=default,machineProfile=l4` to `pool=l4,machineProfile=l4` would cross thelogical capacity boundary without an explicit caller request.For emergency or legacy static namespaces that are not backed by either-`queueRouting.staticQueuePools` or `/v1/pools`, disabling+`queueRouting.staticQueuePools` or a logical `/v1/pools` object with matching+`queue_pool`, disabling`queueRouting.poolAdmission.enabled` lets workers pull without the admissiongate. Prefer declaring static pools instead, so capped/dynamic pools keep theirfail-closed isolation behavior.diff --git a/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml b/deploy/helm/sie-cluster/files/alerts/sie-rules.yamlindex 9688b5ac5..be2af88ee 100644--- a/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml+++ b/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml@@ -92,9 +92,9 @@ groups:# All three are auto-retried by the SDK under the SDK's# ``provision_timeout_s`` / ``max_oom_retries`` budgets — see# ``packages/sie_sdk/src/sie_sdk/client/_shared.py``. Operators- # still see these events via the dedicated- # ``SIEResourceExhaustedSpike`` informational alert and the- # ``sie_gateway_rejected_requests_total`` counter.+ # still see these events via the dedicated informational alerts+ # ``SIEResourceExhaustedSpike`` / ``SIEModelLoadingRetrySpike``+ # and the ``sie_gateway_rejected_requests_total`` counter.## PromQL ``=~`` is full-string anchored (RE2 with implicit# ``^…$``); the list below matches exact reasons only. Keep in@@ -122,6 +122,30 @@ groups:summary: "SIE p95 latency > 5s"description: "95th percentile latency is {{ $value | humanizeDuration }}."+ - alert: SIEGenerationFirstChunkTimeoutSpike+ expr: |+ sum by (model, pool) (+ rate(sie_gateway_generation_timeout_total{kind="first_chunk"}[5m])+ ) > 0.02+ for: 5m+ labels:+ severity: warning+ annotations:+ summary: "SIE generation first-chunk timeouts for {{ $labels.model }}"+ description: "Generation requests for model {{ $labels.model }} in pool {{ $labels.pool }} are timing out before the first chunk at {{ $value | humanize }} req/s. Check worker-side MODEL_LOADING, SGLang startup, and preload/warm-floor policy for the matching bundle."++ - alert: SIEModelLoadingRetrySpike+ expr: |+ sum by (pool, machine_profile, bundle, reason) (+ rate(sie_gateway_rejected_requests_total{reason=~"upstream_model_loading|upstream_timeout_model_loading"}[5m])+ ) > 0.05+ for: 10m+ labels:+ severity: info+ annotations:+ summary: "SIE retryable model-loading responses on {{ $labels.pool }}/{{ $labels.machine_profile }}/{{ $labels.bundle }}"+ description: "The gateway is returning retryable MODEL_LOADING responses at {{ $value | humanize }} req/s for reason {{ $labels.reason }}. This is expected during cold lazy-loads, but sustained traffic usually means the model should be preloaded, pinned, or served from a warmer lane."+- alert: SIEResourceExhaustedSpike# Informational signal: workers are exhausting OOM recovery and# the gateway is collapsing whole batches into 503diff --git a/deploy/helm/sie-cluster/files/dashboards/generation.json b/deploy/helm/sie-cluster/files/dashboards/generation.jsonindex 102161ffb..beeeb951a 100644--- a/deploy/helm/sie-cluster/files/dashboards/generation.json+++ b/deploy/helm/sie-cluster/files/dashboards/generation.json@@ -322,7 +322,7 @@},"id": 20,"type": "timeseries",- "title": "Timeouts / sec by kind",+ "title": "Timeouts / sec by model, pool, kind","fieldConfig": {"defaults": {"unit": "ops"@@ -346,8 +346,8 @@"pluginVersion": "10.0.0","targets": [{- "expr": "sum by (kind) (rate(sie_gateway_generation_timeout_total{namespace=\"$namespace\"}[$rate_window]))",- "legendFormat": "{{kind}}",+ "expr": "sum by (model, pool, kind) (rate(sie_gateway_generation_timeout_total{namespace=\"$namespace\"}[$rate_window]))",+ "legendFormat": "{{model}} / {{pool}} / {{kind}}","refId": "A"}]diff --git a/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml b/deploy/helm/sie-cluster/templates/worker-image-prepull.yamlindex d33a7412d..9163c8fff 100644--- a/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml+++ b/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml@@ -11,6 +11,13 @@{{- $bundle := $bundleName }}{{- /* See worker-statefulset.yaml for the imageBundle rationale. */ -}}{{- $imageBundle := default $bundle $bundleCfg.imageBundle }}+{{- /* Mirror the worker-statefulset bundle->platform guard so prepull never+ references an image the release pipeline does not build. */ -}}+{{- $bundlePlatforms := $root.Values.workers.common.bundlePlatforms | default dict }}+{{- $requiredPlatform := index $bundlePlatforms $imageBundle | default "" }}+{{- if and $requiredPlatform (ne $requiredPlatform $platform) }}+{{- fail (printf "workers.pools.%s.bundles.%s: image bundle %q is built only for platform %q, but this pool resolves to %q. Set this pool's `platform: %s`." $poolName $bundleName $imageBundle $requiredPlatform $platform $requiredPlatform) }}+{{- end }}{{- $imageTag := default $root.Chart.AppVersion $root.Values.workers.common.image.tag }}{{- $workerImage := printf "%s:%s-%s-%s" $root.Values.workers.common.image.repository $imageTag $platform $imageBundle }}---diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex 92087b8fe..d1e0f6f52 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -63,6 +63,14 @@ fast at render time.`sglang`) set this to the bundle whose image they reuse. Labels, envvars, --bundle flag, and metrics still use $bundle. */ -}}{{- $imageBundle := default $bundle $bundleCfg.imageBundle }}+{{- /* Fail fast when a bundle is placed on a platform whose image the release+ pipeline does not build — mirrors docker_task.platform_supports_bundle and+ .github/release-matrix.json. Inert for bundles absent from bundlePlatforms. */ -}}+{{- $bundlePlatforms := $root.Values.workers.common.bundlePlatforms | default dict }}+{{- $requiredPlatform := index $bundlePlatforms $imageBundle | default "" }}+{{- if and $requiredPlatform (ne $requiredPlatform $platform) }}+{{- fail (printf "workers.pools.%s.bundles.%s: image bundle %q is built only for platform %q, but this pool resolves to %q. The release pipeline publishes %s-%s (not %s-%s), so the worker image would ImagePullBackOff. Set this pool's `platform: %s`." $poolName $bundleName $imageBundle $requiredPlatform $platform $requiredPlatform $imageBundle $platform $imageBundle $requiredPlatform) }}+{{- end }}---apiVersion: apps/v1kind: StatefulSetdiff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex b3b8a79ac..ea710417d 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -328,6 +328,17 @@ workers:# -- Platform variant for worker images (e.g. "cuda12", "cpu")platform: cuda12+ # -- Map of imageBundle -> required platform. Mirrors each bundle's+ # -- `platform:` field in packages/sie_server/bundles/*.yaml and the+ # -- `.github/release-matrix.json` `include` pairs (KEEP IN SYNC). The chart+ # -- fails fast if a pool places a listed bundle on a different platform:+ # -- the release pipeline only builds the matching `<platform>-<bundle>`+ # -- image, so a mismatch would otherwise ImagePullBackOff at runtime.+ # -- Bundles not listed here default to the common `platform` above.+ bundlePlatforms:+ # gemma 4 (sglang 0.5.13 / torch 2.11 cu130) ships only as a CUDA 13 image.+ gemma: cuda13+# -- Image pre-pull DaemonSet (caches worker image on GPU nodes before worker pods schedule)imagePrepull:# -- Enable image pre-pull DaemonSets for worker pools@@ -355,16 +366,19 @@ workers:# the pod with no batcher at all.passthroughMode: true- # -- Logical queue pool consumed by workers in queue-routing mode.+ # -- Physical NATS queue pool consumed by workers in queue-routing mode.# The default baseline queue pool is `default`, so SDK calls like# `gpu="l4"` route to `(pool=default, machineProfile=l4)` without# requiring callers to spell the pool as `gpu="default/l4"`.# Routing, metrics, and KEDA still stay lane-specific because the# NATS subject and Prometheus labels include machineProfile and bundle.+ # API-created logical pools draw from this `default` queue unless their+ # PoolSpec sets `queue_pool` to a dedicated Helm queue namespace.# Set per-pool `workers.pools.<name>.queuePool` only when a worker group- # 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"`).+ # should consume from a dedicated physical queue namespace such as+ # `customer-acme`; declare the same name under+ # `queueRouting.staticQueuePools` before callers create logical pools+ # backed by it with `queue_pool: "customer-acme"`.# Queue pool values are rendered and routed in lowercase so NATS/KEDA# labels stay canonical even if an override uses mixed case.queuePool: default@@ -757,6 +771,38 @@ workers:minReplicas: 0maxReplicas: 3+ # Gemma 4 (CUDA 13 / cu130). NOTE the `platform: cuda13` — the gemma image+ # is built/tagged cuda13-gemma; omitting this (defaulting to cuda12) makes+ # the chart fail fast (see workers.common.bundlePlatforms). The 26B-A4B model+ # needs a 96 GB+ card (H200 / RTX PRO 6000); E2B/E4B fit smaller GPUs.+ # When productionizing, also add a matching entry under the top-level+ # `machineProfiles:` map so it surfaces in the machine-profiles ConfigMap,+ # and set `gpu.product` to your node's actual GPU label.+ gemma:+ enabled: false+ machineProfile: gemma+ gpuType: h200+ platform: cuda13+ nodeSelector: {}+ gpu:+ count: 1+ product: NVIDIA-H200+ resources:+ requests:+ cpu: "8"+ memory: "128Gi"+ limits:+ cpu: "16"+ memory: "256Gi"+ tolerations:+ - key: nvidia.com/gpu+ operator: Exists+ effect: NoSchedule+ bundles:+ gemma:+ minReplicas: 0+ maxReplicas: 2+# CPU (local testing with kind, no GPU)cpu:@@ -1101,19 +1147,21 @@ clusterRouting: "queue"# -- Queue routing tuning knobs (only used when clusterRouting=queue).queueRouting:- # -- NAK delay (seconds) for items targeting unloaded models.- # JetStream redelivers after this delay, giving time for model loading.- # Effective retry budget = nakDelay * maxDeliver (default: 5 * 20 = 100s).+ # -- NAK delay (seconds) for retryable queue failures and model-unavailable+ # states. Workers use JetStream progress ACKs, not NAKs, while a local model+ # load is actively running so cold starts do not consume maxDeliver budget;+ # the progress ACK sleep is clamped below the pool consumer ack_wait.nakDelaySec: 5# -- Maximum delivery attempts before a message is sent to the DLQ.- # Must be high enough to cover cold model downloads (10-60s+).+ # Must be high enough to cover retryable failures; active model loads are+ # kept alive by progress ACKs instead of redelivery attempts.maxDeliver: 20# -- Maximum age (seconds) for messages in the pool-level stream.# Keep above maxDeliver * 30s so failed work remains fetchable# after the retry/DLQ envelope for operator inspection.streamMaxAgeSec: 1800# -- Non-expiring pool objects synthesized by the gateway for Helm-declared- # queue namespaces. Keys are queue pool names; names are normalized to+ # physical 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@@ -1128,19 +1176,22 @@ queueRouting:# # Per-pool warm floor: minimum machines kept warm via KEDA.# # Default 0 = scale to zero.# minimumWorkerCount: 0+ # # Per-pool always-loaded models: kept loaded and never evicted on the+ # # pool's workers. Ids may be profile-qualified (model:profile). Default empty.+ # pinnedModels: []staticQueuePools: {}# -- NATS fetch budget: max messages pulled per fetch() call.# This is the primary driver of GPU batch size in queue mode; the worker# groups fetched messages by model and dispatches them as a single forward pass.# Higher values improve GPU utilization under load but increase per-request latency.natsFetchBudget: 64- # -- Worker admission gate for capped pools. Workers ask the gateway whether- # their pod is in the pool's assigned_workers before pulling from NATS.- # The baseline `default` pool fails open. Named non-default queue pools are- # runtime pool/admission boundaries: if you set `workers.pools.<name>.queuePool`- # to a custom value without declaring the matching `staticQueuePools` entry- # or creating the matching `/v1/pools/<queuePool>` object, workers will pause- # instead of pulling.+ # -- Worker admission gate for physical queue pools and logical API pools.+ # Workers poll `GET /v1/pools` before pulling from NATS. The baseline+ # `default` queue pool fails open during transient gateway/status errors.+ # For non-default queue pools, workers pull only when their physical queue+ # pool is admitted directly (usually via `staticQueuePools`) or when at least+ # one assigned logical pool has `queue_pool` set to that physical queue; each+ # work item is still checked against its logical `admission_pool`.poolAdmission:enabled: truecheckIntervalSec: 10diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex 5ede6f83c..76be77c29 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.10"+version = "0.6.11"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 40bea516f..565022e11 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.10"+version = "0.6.11"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 bf1de361d..9ecbed39e 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.10"+version = "0.6.11"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 4de266f27..b21f01b52 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.10"+version = "0.6.11"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 f5b375f86..5d04d8609 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.10"+version = "0.6.11"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex ff2db9ab8..79ffb88b0 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.10"+version = "0.6.11"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex 7b07b896c..8bd710ad9 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.10"+version = "0.6.11"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 58e87cbbf..7c93998b8 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.10"+version = "0.6.11"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 e77dd5404..0f69e8dae 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.10",+ "version": "0.6.11","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 342209c98..e70d56063 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.10",+ "version": "0.6.11","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 54e9697ae..0814c3524 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.10",+ "version": "0.6.11","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 91fcebc4d..184f9259e 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.10",+ "version": "0.6.11","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 80d2f5d7e..140520118 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.10"+version = "0.6.11"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lockindex dd947edeb..e076c539e 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.10"+version = "0.6.11"dependencies = ["arc-swap","async-nats",diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 9815baa34..29e2ae96e 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.10"+version = "0.6.11"edition = "2021"publish = falsediff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 1f6980887..309faf8c1 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -45,9 +45,9 @@ Key terms used throughout this document:- `POST /v1/score/{*model}`- `POST /v1/extract/{*model}`- `POST /v1/embeddings` — OpenAI-compatible JSON surface; the gateway accepts **string** or **list of strings** for `input`, supports `encoding_format=float` (default) or `base64`, translates to an internal **`POST /v1/encode/{model}`** with `items[].text` and `params.output_types=["dense"]`, then maps encode `items[].dense` vectors into OpenAI `data[].embedding` plus a rough `usage` estimate. Token-id / nested-array inputs are rejected with **`400`**.-2. Gateway resolves the request to a model, a bundle, a machine profile, and a queue pool using its in-memory registry.-3. Gateway publishes work to JetStream on `sie.work.{pool}.{machine_profile}.{bundle}.{model}`.-4. A matching worker consumes the work item and executes inference.+2. Gateway resolves the request to a model, a bundle, a machine profile, a logical API pool, and the backing queue pool using its in-memory registry.+3. Gateway publishes work to JetStream on the backing queue subject `sie.work.{pool}.{machine_profile}.{bundle}.{model}` and carries the logical pool as `admission_pool` in the work item.+4. A matching worker consumes the work item, verifies its logical pool assignment when `admission_pool` differs from its physical queue pool, and executes inference.5. Worker publishes the result on `_INBOX.{router_id}.{request_id}` (NATS Core).6. Gateway collects the result and returns the HTTP response.@@ -57,7 +57,7 @@ Rules enforced on the inference path:- The inference hot path is queue-only. There is no direct-HTTP fallback. `src/handlers/proxy.rs` is the queue-submission handler despite its name.- 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.+- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. Explicit `X-SIE-Pool` selects a logical pool; the gateway publishes to that pool's backing queue pool (`PoolSpec.queue_pool`, default `default`) and stamps the logical pool into the work item as `admission_pool`. Deliveries with hashes unknown to the worker-sidecar, or logical pools that do not assign that worker, 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 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.@@ -258,7 +258,7 @@ Computation rules:## 7. Cross-Service Hash Parity-`bundle_config_hash` is computed independently by `sie-config`, the gateway, and workers. The `sie-config` export/epoch surface keeps the global per-bundle hash for bootstrap and drift detection. Gateway hot routing/readiness compares workers against the hash for the same materialized scope the worker serves: the default pool scope for unfiltered workers, or the named pool scope for workers filtered by `SIE_POOL`. For the admin-tooling readiness flow to work, gateway and worker hashes must be byte-identical for that same bundle/pool scope.+`bundle_config_hash` is computed independently by `sie-config`, the gateway, and workers. The `sie-config` export/epoch surface keeps the global per-bundle hash for bootstrap and drift detection. Gateway hot routing/readiness compares workers against the hash for the same materialized scope the worker serves: the default pool scope for unfiltered workers, or the named physical queue-pool scope for workers filtered by `SIE_POOL`. Logical API pools may draw from a different backing queue pool via `PoolSpec.queue_pool`; for the admin-tooling readiness flow to work, gateway and worker hashes must be byte-identical for that backing bundle/pool scope. A model config's top-level `pool` must therefore match the physical queue scope that will materialize it; dynamic logical pools backed by `default` should use default-scoped model configs unless a dedicated worker queue exists.The hash is a SHA-256 over a JSON-serialized, sort-keys representation of a structured object. The outer shape is an array of models, each with `sie_id` and `profiles: [{name, config: {...4 fields...}}]`, where the inner `config` for each profile is strictly the four routable-profile fields: `adapter_path`, `max_batch_tokens`, `compute_precision`, `adapter_options`. Any field outside that whitelist is excluded from the hash so that non-routable edits (e.g. comments, description-style metadata) cannot unnecessarily invalidate worker acks. Python uses `orjson.dumps(..., OPT_SORT_KEYS)`; Rust mirrors this via `serde_json::to_vec` over `BTreeMap`-backed canonical types.@@ -286,8 +286,8 @@ Per-subject transport:| Path | Subject pattern | Transport | Notes ||---|---|---|---|-| Inference work (`encode` / `score` / `extract`) | `sie.work.{pool}.{machine_profile}.{bundle}.{model}` | JetStream | Durability and max-delivery semantics required. Work-item payload is msgpack. One stream per pool (`WORK_POOL_{pool}`) captures all non-generation work for the pool, while worker consumers filter one concrete machine-profile/bundle lane; see §8.2. |-| Generation direct-dispatch | `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}` | JetStream | Worker-specific stream used only by pools that host generation-capable models. Non-generation workers must not create or poll this stream; keeping them pool-only preserves queue batching for `encode` / `score` / `extract`. |+| Pool inference work (`encode` / `score` / `extract`) | `sie.work.{pool}.{machine_profile}.{bundle}.{model}` | JetStream | Durability and max-delivery semantics required. Work-item payload is msgpack. One stream per pool (`WORK_POOL_{pool}`) captures ordinary non-generation work for the pool, while worker consumers filter one concrete machine-profile/bundle lane; see §8.2. |+| Worker direct-dispatch | `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}` | JetStream | Worker-specific stream used by generation and by capped logical batch pools that must target an assigned worker instead of allowing unassigned workers on the same backing queue to burn JetStream delivery attempts. || Inference results | `_INBOX.{router_id}.{request_id}` | NATS Core | Gateway is waiting synchronously; a brief blip after publish but before delivery means the result is lost and the client retries (the gateway returns `503` with `X-SIE-Error-Code: MODEL_LOADING` and `Retry-After: 5` — see §2). Result payload is msgpack. || Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (§4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through Python IPC. || Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`) and supervises the subscriber task: reconnects normally resume in `async-nats`, but a terminated subscription stream is recreated with bounded backoff because there is no full-state health poller. Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply; the **default `health_mode=ws`** still uses the Python WebSocket path. |@@ -320,9 +320,9 @@ The stream's subject filter `sie.work.{pool}.*.*.*` matches exactly one token eaTo prevent that, the Rust gateway's `work_subject(pool, machine_profile, bundle, model)` in `packages/sie_gateway/src/queue/publisher.rs` calls a private `normalize_model_id` helper that mirrors the Python SDK (`sie_sdk.queue_types.normalize_model_id`): `/` → `__`, `.` → `_dot_`, and `*`/`>`/space → `_`. So `vidore/colqwen2.5-v0.2` on the default RTX 6000 default-bundle lane publishes on `sie.work.default.rtx6000.default.vidore__colqwen2_dot_5-v0_dot_2` — exactly six tokens, matches the lane consumer filter. The DLQ token extractor in `queue/dlq.rs` splits the advisory subject on `.` and takes `parts[5]`, which with the normalization in place is already a single safe token.-Generation adds a worker-specific subject, `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`, which has one additional token after the model. That subject intentionally does not match the pool stream's `sie.work.{pool}.*.*.*` filter. The worker runtime binds the worker-specific stream only when the local pool hosts a generation model; encode-only pools keep the pre-generation queue runtime: exactly one hot JetStream consumer, the pool pull loop, the existing adaptive fetch timeout, and the existing dispatch path. This is a batching invariant, not just a resource optimization: generation-only machinery, including the streaming processor, cancel subscription, grammar prewarm, and direct-dispatch pull loop, must not start on encode-only workers because it can perturb shared NATS intake and collapse queue-side batch size. If live config reconciliation adds a generation model to a previously encode-only sidecar, the sidecar rechecks `WorkerCapabilities` and activates this worker-specific stream exactly once.+Worker direct-dispatch uses `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`, which has one additional token after the model. That subject intentionally does not match the pool stream's `sie.work.{pool}.*.*.*` filter. The sidecar binds this worker-specific stream at startup. It stays idle for ordinary pool-queued encode/score/extract traffic, but it is required for two cases: generation direct-dispatch and capped logical batch pools whose `admission_pool` assigns only a subset of workers on a shared backing queue. In the capped logical case the gateway builds an HRW ring from the assigned healthy workers for that lane and publishes to one worker subject, allowing lazy model load without unassigned peers repeatedly NAKing the same message into `max_deliver`. If a non-streaming worker-direct publish fails, the gateway immediately retries on the pool subject; if published work is still missing after the short fallback delay, it republishes the missing items once to the pool subject so a disappeared worker-specific consumer does not strand the request until the client timeout.-The same isolation applies in the gateway. `encode` / `score` / `extract` and `/v1/embeddings` must not pay generation-specific proxy spans, HRW/direct-dispatch routing, per-worker subjects, or trace-context envelope injection. Their work items stay on the pool JetStream subject and keep the pre-generation queue-publish hot path. Generation endpoints may open gateway spans and inject W3C trace context only on generation direct-dispatch or generation fallback work. New gateway hot-path decisions should use the shared endpoint classifier and its regression tests, not one-off string checks.+The same isolation applies in the gateway. Ordinary `encode` / `score` / `extract` and `/v1/embeddings` requests stay on the pool JetStream subject and keep the pre-generation queue-publish hot path. Capped logical pool requests may use worker direct-dispatch to preserve admission semantics; they still do not pay generation-specific proxy spans or trace-context envelope injection. Generation endpoints may open gateway spans and inject W3C trace context only on generation direct-dispatch or generation fallback work. New gateway hot-path decisions should use the shared endpoint classifier and its regression tests, not one-off string checks.### 8.3 Publisher/consumer ownership@@ -518,7 +518,7 @@ Emitted from a Tower middleware (`MetricsLayer` in `middleware/metrics.rs`) that- `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.+- `sie_gateway_active_lease_gpus{pool,machine_profile,bundle}` — gauge. KEDA trigger. Recomputed from distinct assigned workers in the current pool list on every `update_pool_metrics`; `pool` is the backing queue pool (`PoolSpec.queue_pool`, default `default`) so API-created logical pools reserve the KEDA lane they actually draw from. Workers assigned to multiple logical pools sharing the same backing lane are counted once.### 15.3 Worker and model state — gateway@@ -661,6 +661,7 @@ WorkItem {model_id: "BAAI/bge-m3",profile_id: "default",pool_name: "default",+ admission_pool: "default",machine_profile: "default",item: { "text": "..." }, // or omitted + payload_ref if >1MBreply_subject: "_INBOX.gw-1.abc-123",@@ -726,16 +727,16 @@ POST /v1/pools}```-`gpus` is required capacity; `gpu_caps` is an optional assignment cap. `bundle` is an optional assignment filter: when omitted, the logical pool may span multiple worker bundles and `status.assigned_workers[]` records each worker's actual bundle so `active_lease_gpus` can stay lane-aware. The `default` pool has zero requirements and no caps. The worker-sidecar polls pool status every 10 seconds before NATS pulls when the admission gate is enabled. Capped named pools fail closed unless this pod appears in `status.assigned_workers`; the `default` pool fails open during transient gateway/status errors so baseline capacity remains available. HA gateways sort workers deterministically and persist named-pool assignment status.+`gpus` is required capacity; `gpu_caps` is an optional assignment/view cap for that pool. `gpu_caps` is not an aggregate quota across several logical pools sharing the same backing queue; use separate physical queue pools for hard capacity separation. `bundle` is an optional assignment filter: when omitted, the logical pool may span multiple worker bundles and `status.assigned_workers[]` records each worker's actual bundle so `active_lease_gpus` can stay lane-aware. The `default` pool has zero requirements and no caps. The worker-sidecar polls pool status every 10 seconds before NATS pulls when the admission gate is enabled. Capped named physical pools fail closed unless this pod appears in `status.assigned_workers`; the `default` pool fails open during transient gateway/status errors so baseline capacity remains available. For logical API pools backed by a shared physical queue, the sidecar also tracks assigned logical pools from `GET /v1/pools` and NAKs work whose `admission_pool` does not assign this worker. HA gateways sort workers deterministically and persist named-pool assignment status.Helm 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}.*.*.*`. 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.+Each physical queue pool gets its own JetStream stream (`WORK_POOL_{queue_pool}`) with subjects `sie.work.{queue_pool}.*.*.*`. Pool and queue-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={queue_pool}`, `SIE_MACHINE_PROFILE={profile}`, and `SIE_BUNDLE={bundle}`; they consume only from their concrete `sie.work.{queue_pool}.{profile}.{bundle}.*` lane. A logical API pool names the tenant/workload boundary and carries `PoolSpec.queue_pool` to select the physical queue lane; omitted `queue_pool` means `default`. 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, and API-created pools can borrow that same base capacity with `gpu="pool/l4"`. Dedicated queue deployments override Helm `queuePool` and must declare the same name under `queueRouting.staticQueuePools` before API pools can use it as a non-default `queue_pool`; callers can target the protected static pool directly or create a differently named logical pool backed by that queue, for example `{"name":"customer-acme-workload","queue_pool":"customer-acme"}` plus SDK `gpu="customer-acme-workload/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.-A pool spec may also carry `minimum_worker_count` (a per-pool warm floor, default `0`). It keeps the first request from hitting a cold VM: every 30 seconds the gateway re-emits `sie_gateway_pool_warm_floor{pool,machine_profile,bundle}` = `minimum_worker_count` for each lane the pool can name (clearing lanes that disappear), and a per-lane KEDA trigger reads it with `or vector(0)` so KEDA keeps that many machines warm. Default `0` emits nothing and leaves scale-from-zero unchanged.+A pool spec may also carry `minimum_worker_count` (a per-pool warm floor, default `0`). It keeps the first request from hitting a cold VM: every 30 seconds the gateway re-emits `sie_gateway_pool_warm_floor{pool,machine_profile,bundle}` for each backing queue lane the pool can name (clearing lanes that disappear), and a per-lane KEDA trigger reads it with `or vector(0)` so KEDA keeps machines warm. When multiple logical pools share one backing lane, the emitted value is the maximum requested floor for that physical lane, not a sum. Active lease capacity is labeled the same way. Default `0` emits nothing and leaves scale-from-zero unchanged.A pool spec may also carry `pinned_models` (a per-pool set of always-loaded models, default empty), chosen from the models the gateway already tracks (`GET /v1/configs/models`); ids may be profile-qualified (`model-name:profile_name`, the registry's `{base}:{profile}` variant entries, with `model:default` folding to the base). The API validates each id against the registry and stores it canonicalized; every 30 seconds the gateway re-emits `sie_gateway_pool_pinned_model_loaded{pool,model}` = 1 when a healthy assigned worker has the model loaded, else 0 (clearing lanes that disappear). This makes the pinned set declarative and observable; actually keeping the models loaded (worker preload) and lazy-load/LRU using spare capacity around the pinned set are worker-side and tracked separately. Default empty leaves lazy-loading unchanged.-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.+Creating a usable custom pool has two supported shapes. For a dynamic logical pool over base capacity, call `POST /v1/pools` with the logical name and GPU requirements and omit `queue_pool`; it defaults to `default`, so no additional Helm worker group is required. Pool `name` is user/dynamic. Non-default `queue_pool` is infra/admin: it must name a Helm-rendered `queuePool`/`SIE_POOL` backing lane declared under `queueRouting.staticQueuePools`. For a dedicated physical queue, first add that worker group to Helm values and declare the same name under `queueRouting.staticQueuePools`, then create logical pools with `queue_pool` set to that queue. Lease-owned dynamic 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`) 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.+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. Worker counts, machine profiles, bundles, and autoscaling lanes are still Helm-driven physical capacity; `/v1/pools` and `queueRouting.staticQueuePools` only create or renew runtime admission/capacity state, optionally backed by existing `default` capacity through `PoolSpec.queue_pool`. Because workers filter materialized model configs by their physical `SIE_POOL`, a model config for a dedicated queue should use the physical queue pool name; gateway requests may still target a logical pool whose `queue_pool` resolves to that physical name. A default-backed logical pool should not use a non-default model-config `pool` unless a matching dedicated worker queue exists.diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex cf2a45dec..03dfc121c 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -952,6 +952,16 @@},"type": "array"},+ "queue_pool": {+ "description": "Physical Helm/NATS queue namespace to draw workers from. Omit for normal\ndynamic logical pools; they use `default`. Set only to an\noperator-provisioned Helm queue pool declared under\n`queueRouting.staticQueuePools` for dedicated capacity.",+ "maxLength": 128,+ "minLength": 1,+ "pattern": "^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$",+ "type": [+ "string",+ "null"+ ]+ },"ttl_seconds": {"format": "int64","minimum": 0,@@ -2442,6 +2452,13 @@},"type": "array"},+ "queue_pool": {+ "description": "Physical Helm/NATS queue namespace backing this logical API pool.\n\nAPI-created pools default to the Helm `default` queue pool. Pool `name`\nis user/dynamic; a non-default `queue_pool` is infra/admin and must\nmatch a Helm worker queue declared under `queueRouting.staticQueuePools`.",+ "maxLength": 128,+ "minLength": 1,+ "pattern": "^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$",+ "type": "string"+ },"ttl_seconds": {"format": "int64","minimum": 0,@@ -2980,7 +2997,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.10"+ "version": "0.6.11"},"openapi": "3.1.0","paths": {diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex 313bb7d46..a5aaac92d 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -194,6 +194,7 @@ fn env_static_queue_pools(key: &str) -> Vec<PoolSpec> {}});Some(PoolSpec {+ queue_pool: name.clone(),name,bundle,gpus: spec.gpus,diff --git a/packages/sie_gateway/src/handlers/pools.rs b/packages/sie_gateway/src/handlers/pools.rsindex cb3a282fb..ce7eb0adc 100644--- a/packages/sie_gateway/src/handlers/pools.rs+++ b/packages/sie_gateway/src/handlers/pools.rs@@ -17,6 +17,12 @@ use crate::state::pool_manager::DEFAULT_POOL_NAME;#[derive(Debug, Deserialize, ToSchema)]pub struct CreatePoolRequest {pub name: String,+ /// Physical Helm/NATS queue namespace to draw workers from. Omit for normal+ /// dynamic logical pools; they use `default`. Set only to an+ /// operator-provisioned Helm queue pool declared under+ /// `queueRouting.staticQueuePools` for dedicated capacity.+ #[serde(default)]+ pub queue_pool: Option<String>,#[serde(default)]pub gpus: HashMap<String, u32>,#[serde(default)]@@ -136,8 +142,9 @@ pub async fn create_pool(match state.pool_manager- .create_pool_with_caps(+ .create_pool_with_caps_on_queue(&req.name,+ req.queue_pool.as_deref().unwrap_or(DEFAULT_POOL_NAME),req.gpus,req.gpu_caps,req.bundle,diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex be8fa4ebe..73734cb45 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -194,6 +194,8 @@ fn parse_engine_pin(headers: &HeaderMap) -> EnginePinParse {enum PoolResolution {/// A healthy worker is registered and this is the pool to publish to.Route(QueueRoute),+ /// Caller pinned a logical pool that is not present in the pool manager.+ PoolNotFound(String),/// No healthy worker matches the requested `(pool, machine_profile,/// bundle)` lane — the caller should emit the surface-specific/// provisioning response and record pending demand so KEDA scales up.@@ -218,6 +220,10 @@ enum ProvisioningSurface {#[derive(Debug, PartialEq, Eq)]struct PoolLookup {resolution: PoolResolution,+ /// Logical pool whose spec/status should be used for admission decisions.+ admission_pool: String,+ /// Physical queue pool label for pending-demand metrics/KEDA.+ demand_pool: String,/// `true` iff a healthy worker with a non-empty pool name and/// machine-profile existed for the exact `(bundle, gpu)` tuple at/// lookup time.@@ -258,10 +264,19 @@ fn is_valid_pool_name(pool: &str) -> bool {.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))}-fn apply_model_pool_default(+async fn apply_model_pool_default(requested_pool: &mut String,model_pool: Option<&str>,+ pool_manager: Option<&PoolManager>,) -> Result<(), String> {+ let model_pool = model_pool.and_then(|pool| {+ let pool = pool.trim();+ if pool.is_empty() || pool.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {+ None+ } else {+ Some(normalize_pool_name(pool))+ }+ });let Some(model_pool) = model_pool else {if requested_pool.is_empty() {*requested_pool = DEFAULT_POOL_NAME.to_string();@@ -269,12 +284,21 @@ fn apply_model_pool_default(return Ok(());};if requested_pool.is_empty() {- *requested_pool = model_pool.to_string();+ *requested_pool = model_pool.clone();return Ok(());}- if requested_pool == model_pool {+ if *requested_pool == model_pool {return Ok(());}+ if let Some(manager) = pool_manager {+ if manager+ .queue_pool_for_pool(requested_pool)+ .await+ .is_some_and(|queue_pool| queue_pool == model_pool)+ {+ return Ok(());+ }+ }Err(format!("Model is assigned to pool '{model_pool}', but request targeted pool '{requested_pool}'"))@@ -311,6 +335,16 @@ async fn resolve_effective_pool(bundle_config_hash: &str,) -> PoolLookup {if !pool_name.is_empty() {+ let normalized_pool = normalize_pool_name(pool_name);+ let Some(queue_pool) = queue_pool_for_request(pool_manager, pool_name).await else {+ return PoolLookup {+ resolution: PoolResolution::PoolNotFound(normalized_pool.clone()),+ admission_pool: normalized_pool,+ demand_pool: DEFAULT_POOL_NAME.to_string(),+ exact_gpu_match: false,+ pending_demand_profile: None,+ };+ };// 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@@ -318,11 +352,13 @@ async fn resolve_effective_pool(// 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 inferred_profile = infer_single_pool_profile(pool_manager, pool_name).await;+ let lookup_gpu = inferred_profile.as_deref().unwrap_or("");let route = registry- .resolve_queue_route_in_pool(bundle, "", pool_name, bundle_config_hash)+ .resolve_queue_route_in_pool(bundle, lookup_gpu, &queue_pool, bundle_config_hash).await;let pending_demand_profile = if route.is_none() {- infer_single_pool_profile(pool_manager, pool_name).await+ inferred_profile} else {None};@@ -331,13 +367,15 @@ async fn resolve_effective_pool(Some(route) => PoolResolution::Route(route),None => PoolResolution::Provisioning,},+ admission_pool: normalize_pool_name(pool_name),+ demand_pool: queue_pool,exact_gpu_match: false,pending_demand_profile,};}let route = registry- .resolve_queue_route_in_pool(bundle, gpu, pool_name, bundle_config_hash)+ .resolve_queue_route_in_pool(bundle, gpu, &queue_pool, bundle_config_hash).await;let exact_gpu_match = route.is_some();return PoolLookup {@@ -345,6 +383,8 @@ async fn resolve_effective_pool(Some(route) => PoolResolution::Route(route),None => PoolResolution::Provisioning,},+ admission_pool: normalize_pool_name(pool_name),+ demand_pool: queue_pool,exact_gpu_match,pending_demand_profile: if exact_gpu_match {None@@ -374,11 +414,27 @@ async fn resolve_effective_pool(};PoolLookup {resolution,+ admission_pool: DEFAULT_POOL_NAME.to_string(),+ demand_pool: DEFAULT_POOL_NAME.to_string(),exact_gpu_match,pending_demand_profile,}}+async fn queue_pool_for_request(+ pool_manager: Option<&PoolManager>,+ pool_name: &str,+) -> Option<String> {+ let normalized = normalize_pool_name(pool_name);+ if normalized.is_empty() {+ return Some(DEFAULT_POOL_NAME.to_string());+ }+ let Some(manager) = pool_manager else {+ return Some(normalized);+ };+ manager.queue_pool_for_pool(&normalized).await+}+async fn infer_single_pool_profile(pool_manager: Option<&PoolManager>,pool_name: &str,@@ -481,6 +537,31 @@ fn build_openai_provisioning_response(gpu: &str, bundle: &str) -> Response {build_provisioning_response_for_surface(gpu, bundle, ProvisioningSurface::OpenAiCompat)}+fn pool_not_found_message(pool: &str) -> String {+ format!("Pool '{}' not found", pool)+}++fn build_pool_not_found_response_for_surface(pool: &str, surface: ProvisioningSurface) -> Response {+ let message = pool_not_found_message(pool);+ match surface {+ ProvisioningSurface::Native => (+ StatusCode::NOT_FOUND,+ Json(json_detail(err_code::POOL_NOT_FOUND, message)),+ )+ .into_response(),+ ProvisioningSurface::OpenAiCompat => (+ StatusCode::NOT_FOUND,+ Json(json_openai_error(+ message,+ oai_type::INVALID_REQUEST,+ Some("pool"),+ oai_code::INVALID_REQUEST,+ )),+ )+ .into_response(),+ }+}+fn provisioning_surface_for_endpoint(endpoint: &str) -> ProvisioningSurface {if endpoint_uses_openai_envelope(endpoint) {ProvisioningSurface::OpenAiCompat@@ -491,24 +572,30 @@ fn provisioning_surface_for_endpoint(endpoint: &str) -> ProvisioningSurface {async fn capped_lane_admission_response(state: &AppState,- pool: &str,+ admission_pool: &str,+ demand_pool: &str,machine_profile: &str,bundle: &str,provisioning_surface: ProvisioningSurface,) -> Option<Response> {let admission = state.pool_manager- .capped_lane_status(pool, machine_profile, bundle)+ .capped_lane_status(admission_pool, machine_profile, bundle).await?;if admission.cap == 0 {- metrics::record_rejected_request_for_pool(pool, machine_profile, bundle, "pool_cap_zero");+ metrics::record_rejected_request_for_pool(+ admission_pool,+ machine_profile,+ bundle,+ "pool_cap_zero",+ );let message = format!("Pool '{}' admits zero workers for GPU type '{}' and bundle '{}'.",- pool, machine_profile, bundle+ admission_pool, machine_profile, bundle);let mut m = Map::new();- m.insert("pool".to_string(), json!(pool));+ m.insert("pool".to_string(), json!(admission_pool));m.insert("gpu".to_string(), json!(machine_profile));m.insert("bundle".to_string(), json!(bundle));m.insert("cap".to_string(), json!(admission.cap));@@ -549,7 +636,9 @@ async fn capped_lane_admission_response(}if admission.assigned_count == 0 {- state.demand_tracker.record(pool, machine_profile, bundle);+ state+ .demand_tracker+ .record(demand_pool, machine_profile, bundle);return Some(build_provisioning_response_for_surface(machine_profile,bundle,@@ -560,6 +649,60 @@ async fn capped_lane_admission_response(None}+async fn batch_publish_target(+ state: &AppState,+ pool: &str,+ admission_pool: &str,+ model: &str,+ machine_profile: &str,+ bundle: &str,+ bundle_config_hash: &str,+) -> Result<publisher::PublishTarget, ()> {+ let pool_target = publisher::PublishTarget::Pool {+ pool: pool.to_string(),+ machine_profile: machine_profile.to_string(),+ bundle: bundle.to_string(),+ model: model.to_string(),+ };+ let Some(admitted_worker_names) = state+ .pool_manager+ .admitted_worker_names_for_capped_lane(admission_pool, machine_profile, bundle)+ .await+ else {+ return Ok(pool_target);+ };+ if admitted_worker_names.is_empty() {+ return Err(());+ }++ let ring = state.registry.lazy_lane_ring_snapshot_for_admitted(+ model,+ pool,+ machine_profile,+ bundle,+ bundle_config_hash,+ &admitted_worker_names,+ );+ let seed = uuid::Uuid::now_v7().to_string();+ let key = crate::routing::key::RoutingKeyResolved {+ hash: Some(crate::routing::key::hash_bytes(&seed)),+ source: crate::routing::key::KeySource::RoutingKey,+ #[cfg(feature = "raw-routing-logs")]+ raw_for_debug: None,+ };+ let Some(worker_id) = crate::routing::pick_worker(&ring, &key) else {+ return Err(());+ };++ Ok(publisher::PublishTarget::Worker {+ pool: pool.to_string(),+ machine_profile: machine_profile.to_string(),+ bundle: bundle.to_string(),+ model: model.to_string(),+ worker_id: worker_id.to_string(),+ })+}+#[utoipa::path(post,path = "/v1/encode/{model}",@@ -957,7 +1100,13 @@ async fn proxy_request(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()) {+ if let Err(message) = apply_model_pool_default(+ &mut pool_name,+ model_pool.as_deref(),+ Some(&state.pool_manager),+ )+ .await+ {metrics::record_rejected_request_for_pool(&pool_name, &gpu, &bundle, "pool_mismatch");return endpoint_error_response(endpoint,@@ -1062,9 +1211,15 @@ async fn proxy_request();};+ let Some(hash_pool) = queue_pool_for_request(Some(&state.pool_manager), &pool_name).await+ else {+ let requested_pool = normalize_pool_name(&pool_name);+ metrics::record_rejected_request_for_pool(&requested_pool, &gpu, &bundle, "pool_not_found");+ return build_pool_not_found_response_for_surface(&requested_pool, provisioning_surface);+ };let bundle_config_hash = state.model_registry- .compute_bundle_config_hash_for_pool(&bundle, &pool_name);+ .compute_bundle_config_hash_for_pool(&bundle, &hash_pool);// Resolve the effective pool in one shot. `resolve_effective_pool`// folds the demand-tracking probe ("was there an exact@@ -1083,25 +1238,26 @@ async fn proxy_request(&bundle_config_hash,).await;- let demand_pool = if pool_name.is_empty() {- DEFAULT_POOL_NAME- } else {- pool_name.as_str()- };+ let demand_pool = lookup.demand_pool.clone();+ let admission_pool = lookup.admission_pool.clone();let pending_demand_profile = lookup.pending_demand_profile.clone();if let Some(profile) = pending_demand_profile.as_deref() {- state.demand_tracker.record(demand_pool, profile, &bundle);+ state.demand_tracker.record(&demand_pool, profile, &bundle);}let effective_route = match lookup.resolution {PoolResolution::Route(route) => route,+ PoolResolution::PoolNotFound(pool) => {+ metrics::record_rejected_request_for_pool(&pool, &gpu, &bundle, "pool_not_found");+ return build_pool_not_found_response_for_surface(&pool, provisioning_surface);+ }PoolResolution::Provisioning => {// 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// though KEDA cannot scale a lane without a profile token.if pending_demand_profile.is_none() {- state.demand_tracker.record(demand_pool, &gpu, &bundle);+ state.demand_tracker.record(&demand_pool, &gpu, &bundle);}return build_provisioning_response_for_surface(&gpu, &bundle, provisioning_surface);}@@ -1111,7 +1267,8 @@ async fn proxy_request(if let Some(resp) = capped_lane_admission_response(&state,- effective_pool,+ &admission_pool,+ &demand_pool,effective_machine_profile,&bundle,provisioning_surface,@@ -1121,6 +1278,34 @@ async fn proxy_request(return resp;}+ let batch_target = if endpoint == "generate" {+ None+ } else {+ match batch_publish_target(+ &state,+ effective_pool,+ &admission_pool,+ &model_name,+ effective_machine_profile,+ &bundle,+ &bundle_config_hash,+ )+ .await+ {+ Ok(target) => Some(target),+ Err(()) => {+ state+ .demand_tracker+ .record(&demand_pool, effective_machine_profile, &bundle);+ return build_provisioning_response_for_surface(+ effective_machine_profile,+ &bundle,+ provisioning_surface,+ );+ }+ }+ };+let token_id = extract_bearer_token(req.headers()).map(|t| mask_token(&t)).unwrap_or_default();@@ -1188,6 +1373,7 @@ async fn proxy_request(&engine,effective_machine_profile,effective_pool,+ &admission_pool,&body_bytes,is_msgpack_in,use_msgpack_out,@@ -1195,6 +1381,7 @@ async fn proxy_request(content_length,Instant::now(),&bundle_config_hash,+ batch_target,).await}@@ -1223,6 +1410,7 @@ async fn queue_mode_proxy(engine: &str,gpu: &str,pool: &str,+ admission_pool: &str,body_bytes: &[u8],is_msgpack_in: bool,use_msgpack_out: bool,@@ -1230,6 +1418,7 @@ async fn queue_mode_proxy(content_length: i64,start: Instant,bundle_config_hash: &str,+ batch_target: Option<publisher::PublishTarget>,) -> Response {// Parse body once, extract items + params (avoids double parse)let (items, params) = match parse_queue_request(body_bytes, is_msgpack_in, endpoint) {@@ -1444,6 +1633,7 @@ async fn queue_mode_proxy(engine: engine.to_string(),gpu: gpu.to_string(),pool: pool.to_string(),+ admission_pool: admission_pool.to_string(),bundle_config_hash: bundle_config_hash.to_string(),work_params: params,endpoint: super::sse::SseEndpoint::Generate,@@ -1462,6 +1652,7 @@ async fn queue_mode_proxy(engine,gpu,pool,+ admission_pool,bundle_config_hash,¶ms,use_msgpack_out,@@ -1473,14 +1664,21 @@ async fn queue_mode_proxy(}let publish_start = Instant::now();+ let target = batch_target.unwrap_or_else(|| publisher::PublishTarget::Pool {+ pool: pool.to_string(),+ machine_profile: gpu.to_string(),+ bundle: bundle.to_string(),+ model: model.to_string(),+ });+ let direct_batch_fallback =+ matches!(target, publisher::PublishTarget::Worker { .. }) && endpoint != "generate";let (request_id, rx) = match work_publisher.publish_work(- pool,+ target,+ admission_pool,endpoint,model,- bundle,engine,- gpu,bundle_config_hash,items,¶ms,@@ -1544,6 +1742,14 @@ async fn queue_mode_proxy(return response;}};+ if direct_batch_fallback {+ if let Some(work_publisher_arc) = state.work_publisher.clone() {+ work_publisher_arc.spawn_batch_direct_fallback(+ request_id.clone(),+ batch_direct_fallback_delay(state.config.request_timeout),+ );+ }+ }let publish_elapsed = publish_start.elapsed();// Wait for results (use configured request_timeout instead of hardcoded 300s)@@ -1925,6 +2131,7 @@ pub(crate) async fn run_streaming_generate(engine: &str,gpu: &str,pool: &str,+ admission_pool: &str,bundle_config_hash: &str,params: &publisher::WorkParams,) -> Result<StreamingDriverOk, StreamingDriverErr> {@@ -1981,7 +2188,7 @@ pub(crate) async fn run_streaming_generate(} else {let admitted_worker_names = state.pool_manager- .admitted_worker_names_for_capped_lane(pool, gpu, bundle)+ .admitted_worker_names_for_capped_lane(admission_pool, gpu, bundle).await;let fallback_lane_worker_count = state.registry.pool_fallback_lane_worker_count(pool,@@ -2049,7 +2256,14 @@ pub(crate) async fn run_streaming_generate(// Capture this before the move into `publish_generate_streaming`.let was_direct_dispatched = matches!(target, publisher::PublishTarget::Worker { .. });let (request_id, rx, activity) = match work_publisher- .publish_generate_streaming(target, model, engine, bundle_config_hash, params)+ .publish_generate_streaming(+ target,+ model,+ engine,+ bundle_config_hash,+ params,+ admission_pool,+ ).await{Ok(r) => r,@@ -2336,7 +2550,12 @@ pub(crate) async fn run_streaming_generate(// If the worker emitted an error terminal, surface it as a typed// failure. The caller chooses the HTTP status / wire envelope.if let Some(err) = outcome.error.as_ref() {- metrics::record_rejected_request_for_pool(pool, gpu, bundle, "generate_worker_error");+ metrics::record_rejected_request_for_pool(+ pool,+ gpu,+ bundle,+ generation_worker_error_metric_reason(&err.code),+ );return Err(StreamingDriverErr::WorkerError {code: err.code.clone(),message: err.message.clone(),@@ -2362,6 +2581,9 @@ pub(crate) fn worker_error_http_status(code: &str) -> StatusCode {match code {"invalid_request" | "unsupported_field" => StatusCode::BAD_REQUEST,"context_exceeded" => StatusCode::BAD_REQUEST,+ RESOURCE_EXHAUSTED_ERROR_CODE | MODEL_LOADING_ERROR_CODE | LORA_LOADING_ERROR_CODE => {+ StatusCode::SERVICE_UNAVAILABLE+ }"transport_failure" => StatusCode::SERVICE_UNAVAILABLE,"cancelled" => StatusCode::REQUEST_TIMEOUT,"rate_limit_exceeded" => StatusCode::TOO_MANY_REQUESTS,@@ -2482,6 +2704,9 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {"invalid_request" => oai_code::INVALID_REQUEST,"unsupported_field" => oai_code::UNSUPPORTED_FIELD,"context_exceeded" => oai_code::CONTEXT_EXCEEDED,+ RESOURCE_EXHAUSTED_ERROR_CODE => RESOURCE_EXHAUSTED_ERROR_CODE,+ MODEL_LOADING_ERROR_CODE => MODEL_LOADING_ERROR_CODE,+ LORA_LOADING_ERROR_CODE => LORA_LOADING_ERROR_CODE,"transport_failure" => oai_code::TRANSPORT_FAILURE,"cancelled" => oai_code::CANCELLED,"rate_limit_exceeded" => oai_code::RATE_LIMIT_EXCEEDED,@@ -2512,6 +2737,29 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {HeaderValue::from_static("1"),);}+ let retryable = match code.as_str() {+ RESOURCE_EXHAUSTED_ERROR_CODE => Some((+ RESOURCE_EXHAUSTED_RETRY_AFTER,+ RESOURCE_EXHAUSTED_ERROR_CODE,+ )),+ MODEL_LOADING_ERROR_CODE => {+ Some((MODEL_LOADING_RETRY_AFTER, MODEL_LOADING_ERROR_CODE))+ }+ LORA_LOADING_ERROR_CODE => {+ Some((LORA_LOADING_RETRY_AFTER, LORA_LOADING_ERROR_CODE))+ }+ _ => None,+ };+ if let Some((retry_after, error_code)) = retryable {+ resp.headers_mut().insert(+ HeaderName::from_static("retry-after"),+ HeaderValue::from_static(retry_after),+ );+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(error_code),+ );+ }resp}}@@ -2579,6 +2827,7 @@ async fn queue_mode_streaming_generate(engine: &str,gpu: &str,pool: &str,+ admission_pool: &str,bundle_config_hash: &str,params: &publisher::WorkParams,use_msgpack_out: bool,@@ -2595,6 +2844,7 @@ async fn queue_mode_streaming_generate(engine,gpu,pool,+ admission_pool,bundle_config_hash,params,)@@ -4588,6 +4838,7 @@ pub(crate) fn resolve_model_and_bundle(struct ResolvedRoute {gpu: String,engine: String,+ admission_pool: String,effective_pool: String,effective_machine_profile: String,bundle_config_hash: String,@@ -4641,7 +4892,13 @@ async fn resolve_generation_route(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()) {+ if let Err(message) = apply_model_pool_default(+ &mut pool_name,+ model_pool.as_deref(),+ Some(&state.pool_manager),+ )+ .await+ {metrics::record_rejected_request_for_pool(&pool_name, &gpu, bundle, "pool_mismatch");return Err((StatusCode::BAD_REQUEST,@@ -4709,9 +4966,18 @@ async fn resolve_generation_route(.into_response());};+ let Some(hash_pool) = queue_pool_for_request(Some(&state.pool_manager), &pool_name).await+ else {+ let requested_pool = normalize_pool_name(&pool_name);+ metrics::record_rejected_request_for_pool(&requested_pool, &gpu, bundle, "pool_not_found");+ return Err(build_pool_not_found_response_for_surface(+ &requested_pool,+ ProvisioningSurface::OpenAiCompat,+ ));+ };let bundle_config_hash = state.model_registry- .compute_bundle_config_hash_for_pool(bundle, &pool_name);+ .compute_bundle_config_hash_for_pool(bundle, &hash_pool);let engine = state.model_registry.get_bundle_info(bundle)@@ -4726,20 +4992,24 @@ async fn resolve_generation_route(&bundle_config_hash,).await;- let demand_pool = if pool_name.is_empty() {- DEFAULT_POOL_NAME- } else {- pool_name.as_str()- };+ let demand_pool = lookup.demand_pool.clone();+ let admission_pool = lookup.admission_pool.clone();let pending_demand_profile = lookup.pending_demand_profile.clone();if let Some(profile) = pending_demand_profile.as_deref() {- state.demand_tracker.record(demand_pool, profile, bundle);+ state.demand_tracker.record(&demand_pool, profile, bundle);}let effective_route = match lookup.resolution {PoolResolution::Route(route) => route,+ PoolResolution::PoolNotFound(pool) => {+ metrics::record_rejected_request_for_pool(&pool, &gpu, bundle, "pool_not_found");+ return Err(build_pool_not_found_response_for_surface(+ &pool,+ ProvisioningSurface::OpenAiCompat,+ ));+ }PoolResolution::Provisioning => {if pending_demand_profile.is_none() {- state.demand_tracker.record(demand_pool, &gpu, bundle);+ state.demand_tracker.record(&demand_pool, &gpu, bundle);}return Err(build_openai_provisioning_response(&gpu, bundle));}@@ -4749,7 +5019,8 @@ async fn resolve_generation_route(if let Some(resp) = capped_lane_admission_response(state,- &effective_pool,+ &admission_pool,+ &demand_pool,&effective_machine_profile,bundle,ProvisioningSurface::OpenAiCompat,@@ -4771,6 +5042,7 @@ async fn resolve_generation_route(Ok(ResolvedRoute {gpu,engine,+ admission_pool,effective_pool,effective_machine_profile,bundle_config_hash,@@ -5169,6 +5441,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Reslet ResolvedRoute {gpu,engine,+ admission_pool,effective_pool,effective_machine_profile,bundle_config_hash,@@ -5239,6 +5512,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Resengine: engine.clone(),gpu: effective_machine_profile.clone(),pool: effective_pool.clone(),+ admission_pool: admission_pool.clone(),bundle_config_hash: bundle_config_hash.clone(),work_params,endpoint: super::sse::SseEndpoint::Chat {@@ -5257,6 +5531,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res&engine,&effective_machine_profile,&effective_pool,+ &admission_pool,&bundle_config_hash,&work_params,)@@ -5781,6 +6056,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)let ResolvedRoute {gpu,engine,+ admission_pool,effective_pool,effective_machine_profile,bundle_config_hash,@@ -5824,6 +6100,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)engine: engine.clone(),gpu: effective_machine_profile.clone(),pool: effective_pool.clone(),+ admission_pool: admission_pool.clone(),bundle_config_hash: bundle_config_hash.clone(),work_params,endpoint: super::sse::SseEndpoint::Completion,@@ -5840,6 +6117,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)&engine,&effective_machine_profile,&effective_pool,+ &admission_pool,&bundle_config_hash,&work_params,)@@ -6364,6 +6642,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -let ResolvedRoute {gpu,engine,+ admission_pool,effective_pool,effective_machine_profile,bundle_config_hash,@@ -6399,6 +6678,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -&engine,&effective_machine_profile,&effective_pool,+ &admission_pool,&bundle_config_hash,&work_params,)@@ -6680,6 +6960,24 @@ fn retryable_metric_reason(code: &str) -> &'static str {}}+fn generation_worker_error_metric_reason(code: &str) -> &'static str {+ match code {+ RESOURCE_EXHAUSTED_ERROR_CODE | MODEL_LOADING_ERROR_CODE | LORA_LOADING_ERROR_CODE => {+ retryable_metric_reason(code)+ }+ _ => "generate_worker_error",+ }+}++fn batch_direct_fallback_delay(request_timeout_s: f64) -> Duration {+ let timeout_s = if request_timeout_s.is_finite() && request_timeout_s > 0.0 {+ request_timeout_s+ } else {+ 30.0+ };+ Duration::from_secs_f64((timeout_s / 3.0).clamp(1.0, 10.0))+}+/// Build a ``503 + <code>`` response that mirrors the worker-side HTTP/// contract (see ``packages/sie_server/src/sie_server/api/helpers.py``).///@@ -10022,6 +10320,7 @@ mod tests {let resp = capped_lane_admission_response(&state,"tenant",+ DEFAULT_POOL_NAME,"l4","default",ProvisioningSurface::Native,@@ -10049,6 +10348,7 @@ mod tests {let resp = capped_lane_admission_response(&state,"tenant",+ DEFAULT_POOL_NAME,"l4","default",ProvisioningSurface::OpenAiCompat,@@ -10079,12 +10379,15 @@ mod tests {.await.unwrap();let state = admission_test_state(Arc::clone(&pm));+ let demand_pool = "test-zero-assigned-native";+ let bundle = "test-zero-assigned-native-bundle";let resp = capped_lane_admission_response(&state,"tenant",+ demand_pool,"l4",- "default",+ bundle,ProvisioningSurface::Native,).await@@ -10104,12 +10407,12 @@ mod tests {assert!(value.get("status").is_none());let pending_demand = metrics::PENDING_DEMAND- .with_label_values(&["tenant", "l4", "default"])+ .with_label_values(&[demand_pool, "l4", bundle]).get();assert!((pending_demand - 1.0).abs() < f64::EPSILON);- state.demand_tracker.clear("tenant", "l4", "default");+ state.demand_tracker.clear(demand_pool, "l4", bundle);let cleared_demand = metrics::PENDING_DEMAND- .with_label_values(&["tenant", "l4", "default"])+ .with_label_values(&[demand_pool, "l4", bundle]).get();assert!((cleared_demand - 0.0).abs() < f64::EPSILON);}@@ -10125,12 +10428,15 @@ mod tests {.await.unwrap();let state = admission_test_state(Arc::clone(&pm));+ let demand_pool = "test-zero-assigned-openai";+ let bundle = "test-zero-assigned-openai-bundle";let resp = capped_lane_admission_response(&state,"tenant",+ demand_pool,"l4",- "default",+ bundle,ProvisioningSurface::OpenAiCompat,).await@@ -10154,6 +10460,86 @@ mod tests {.as_str().unwrap_or("").contains("Provisioning in progress"));+ state.demand_tracker.clear(demand_pool, "l4", bundle);+ }++ #[tokio::test]+ async fn test_batch_publish_target_directs_capped_logical_pool_to_assigned_cold_worker() {+ 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, vec![])+ .await+ .unwrap();+ pm.assign_workers(+ "tenant",+ &[(+ "assigned-cold".to_string(),+ "http://assigned-cold:8080".to_string(),+ "l4".to_string(),+ "default".to_string(),+ DEFAULT_POOL_NAME.to_string(),+ )],+ )+ .await;++ let state = admission_test_state(Arc::clone(&pm));+ state+ .registry+ .update_worker(+ "http://assigned-cold:8080",+ crate::types::WorkerStatusMessage {+ name: "assigned-cold".to_string(),+ ready: true,+ gpu_count: 1,+ machine_profile: "l4".to_string(),+ pool_name: DEFAULT_POOL_NAME.to_string(),+ bundle: "default".to_string(),+ bundle_config_hash: "h1".to_string(),+ loaded_models: Vec::new(),+ models: Vec::new(),+ gpus: Vec::new(),+ queue_depth: None,+ memory_used_bytes: None,+ memory_total_bytes: None,+ saturated: false,+ terminated: false,+ },+ )+ .await;++ let target = batch_publish_target(+ &state,+ DEFAULT_POOL_NAME,+ "tenant",+ "BAAI/bge-m3",+ "l4",+ "default",+ "h1",+ )+ .await+ .expect("assigned capped lane should have a direct target");++ match target {+ publisher::PublishTarget::Worker {+ pool,+ machine_profile,+ bundle,+ model,+ worker_id,+ } => {+ assert_eq!(pool, DEFAULT_POOL_NAME);+ assert_eq!(machine_profile, "l4");+ assert_eq!(bundle, "default");+ assert_eq!(model, "BAAI/bge-m3");+ assert_eq!(worker_id, "assigned-cold");+ }+ publisher::PublishTarget::Pool { .. } => {+ panic!("capped logical batch work must not publish to the shared pool subject")+ }+ }}#[tokio::test]@@ -10215,26 +10601,87 @@ mod tests {assert!(is_valid_pool_name(&"a".repeat(128)));}- #[test]- fn test_apply_model_pool_default() {+ #[tokio::test]+ async fn test_apply_model_pool_default() {let mut omitted = String::new();- apply_model_pool_default(&mut omitted, Some("customer-a")).unwrap();+ apply_model_pool_default(&mut omitted, Some("customer-a"), None)+ .await+ .unwrap();assert_eq!(omitted, "customer-a");let mut matching = "customer-a".to_string();- apply_model_pool_default(&mut matching, Some("customer-a")).unwrap();+ apply_model_pool_default(&mut matching, Some("customer-a"), None)+ .await+ .unwrap();assert_eq!(matching, "customer-a");let mut mismatched = "default".to_string();- assert!(apply_model_pool_default(&mut mismatched, Some("customer-a")).is_err());+ assert!(+ apply_model_pool_default(&mut mismatched, Some("customer-a"), None)+ .await+ .is_err()+ );let mut unknown_omitted = String::new();- apply_model_pool_default(&mut unknown_omitted, None).unwrap();+ apply_model_pool_default(&mut unknown_omitted, None, None)+ .await+ .unwrap();assert_eq!(unknown_omitted, "default");let mut unknown_explicit = "customer-a".to_string();- apply_model_pool_default(&mut unknown_explicit, None).unwrap();+ apply_model_pool_default(&mut unknown_explicit, None, None)+ .await+ .unwrap();assert_eq!(unknown_explicit, "customer-a");++ let mut default_model_explicit_runtime_pool = "customer-a".to_string();+ apply_model_pool_default(+ &mut default_model_explicit_runtime_pool,+ Some("default"),+ None,+ )+ .await+ .unwrap();+ assert_eq!(default_model_explicit_runtime_pool, "customer-a");++ let mut default_model_omitted = String::new();+ apply_model_pool_default(&mut default_model_omitted, Some("default"), None)+ .await+ .unwrap();+ assert_eq!(default_model_omitted, "default");+ }++ #[tokio::test]+ async fn test_apply_model_pool_allows_logical_pool_backed_by_model_pool() {+ let pm = PoolManager::new(vec!["l4".to_string()]);+ sync_static_queue_pool(&pm, "customer-queue", "l4").await;+ let mut gpus = std::collections::HashMap::new();+ gpus.insert("l4".to_string(), 1);+ pm.create_pool_with_caps_on_queue(+ "tenant-a",+ "customer-queue",+ gpus,+ std::collections::HashMap::new(),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .unwrap();++ let mut backed_logical_pool = "tenant-a".to_string();+ apply_model_pool_default(&mut backed_logical_pool, Some("customer-queue"), Some(&pm))+ .await+ .unwrap();+ assert_eq!(backed_logical_pool, "tenant-a");++ let mut unrelated_pool = "tenant-b".to_string();+ assert!(+ apply_model_pool_default(&mut unrelated_pool, Some("customer-queue"), Some(&pm))+ .await+ .is_err()+ );}#[test]@@ -11659,6 +12106,37 @@ mod tests {assert_eq!(retryable_metric_reason("anything-else"), "all_items_failed");}+ #[test]+ fn test_generation_worker_error_metric_reason_keeps_model_loading_retryable() {+ assert_eq!(+ generation_worker_error_metric_reason(MODEL_LOADING_ERROR_CODE),+ "upstream_model_loading"+ );+ assert_eq!(+ generation_worker_error_metric_reason(RESOURCE_EXHAUSTED_ERROR_CODE),+ "resource_exhausted"+ );+ assert_eq!(+ generation_worker_error_metric_reason(LORA_LOADING_ERROR_CODE),+ "upstream_lora_loading"+ );+ assert_eq!(+ generation_worker_error_metric_reason("invalid_request"),+ "generate_worker_error"+ );+ }++ #[test]+ fn test_batch_direct_fallback_delay_leaves_request_budget() {+ assert_eq!(batch_direct_fallback_delay(0.5), Duration::from_secs(1));+ assert_eq!(batch_direct_fallback_delay(30.0), Duration::from_secs(10));+ assert_eq!(batch_direct_fallback_delay(300.0), Duration::from_secs(10));+ assert_eq!(+ batch_direct_fallback_delay(f64::NAN),+ Duration::from_secs(10)+ );+ }+#[test]fn test_parse_model_spec_with_bundle() {let (bundle, model) = parse_model_spec("premium:/BAAI/bge-m3");@@ -12609,6 +13087,23 @@ mod tests {}}+ async fn sync_static_queue_pool(pm: &PoolManager, name: &str, profile: &str) {+ let mut gpus = std::collections::HashMap::new();+ gpus.insert(profile.to_string(), 0);+ pm.sync_static_pools(&[crate::types::pool::PoolSpec {+ name: name.to_string(),+ queue_pool: name.to_string(),+ bundle: None,+ gpus,+ gpu_caps: std::collections::HashMap::new(),+ ttl_seconds: None,+ minimum_worker_count: 0,+ pinned_models: Vec::new(),+ }])+ .await+ .unwrap();+ }+fn route(pool: &str, gpu: &str) -> PoolResolution {PoolResolution::Route(QueueRoute {pool_name: pool.to_string(),@@ -12717,6 +13212,30 @@ mod tests {assert_eq!(out.pending_demand_profile, None);}+ #[tokio::test]+ async fn test_resolve_effective_pool_unknown_api_pool_fails_closed() {+ let reg = pool_registry();+ reg.update_worker(+ "http://w1:8080",+ worker_msg("default", "l4-spot", "customer-acme"),+ )+ .await;+ let pm = PoolManager::new(vec!["l4-spot".into()]);++ let out =+ resolve_effective_pool(®, Some(&pm), "default", "l4-spot", "customer-acme", "")+ .await;++ assert_eq!(+ out.resolution,+ PoolResolution::PoolNotFound("customer-acme".to_string())+ );+ assert_eq!(out.admission_pool, "customer-acme");+ assert_eq!(out.demand_pool, DEFAULT_POOL_NAME);+ assert_eq!(out.pending_demand_profile, None);+ assert!(!out.exact_gpu_match);+ }+#[tokio::test]async fn test_resolve_effective_pool_infers_cold_profile_from_single_profile_pool() {// A tenant pool with exactly one configured machine profile can scale@@ -12781,6 +13300,114 @@ mod tests {assert!(out.exact_gpu_match);}+ #[tokio::test]+ async fn test_resolve_effective_pool_api_pool_routes_to_default_backing_queue() {+ let reg = pool_registry();+ reg.update_worker(+ "http://w1:8080",+ worker_msg("default", "l4-spot", DEFAULT_POOL_NAME),+ )+ .await;+ let pm = PoolManager::new(vec!["l4-spot".into()]);+ let mut gpus = std::collections::HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ pm.create_pool("my-bench", gpus, None, None, 0, vec![])+ .await+ .unwrap();++ let out =+ resolve_effective_pool(®, Some(&pm), "default", "l4-spot", "my-bench", "").await;+ assert_eq!(out.resolution, route(DEFAULT_POOL_NAME, "l4-spot"));+ assert_eq!(out.admission_pool, "my-bench");+ assert_eq!(out.demand_pool, DEFAULT_POOL_NAME);+ assert!(out.exact_gpu_match);+ }++ #[tokio::test]+ async fn test_resolve_effective_pool_pool_only_respects_single_profile_api_pool() {+ let reg = pool_registry();+ reg.update_worker(+ "http://w1:8080",+ worker_msg("default", "a100", DEFAULT_POOL_NAME),+ )+ .await;+ let pm = PoolManager::new(vec!["l4".into(), "a100".into()]);+ let mut gpus = std::collections::HashMap::new();+ gpus.insert("l4".to_string(), 1);+ pm.create_pool("tenant-l4", gpus, None, None, 0, vec![])+ .await+ .unwrap();++ let out = resolve_effective_pool(®, Some(&pm), "default", "", "tenant-l4", "").await;++ assert_eq!(out.resolution, PoolResolution::Provisioning);+ assert_eq!(out.admission_pool, "tenant-l4");+ assert_eq!(out.demand_pool, DEFAULT_POOL_NAME);+ assert_eq!(out.pending_demand_profile.as_deref(), Some("l4"));+ }++ #[tokio::test]+ async fn test_resolve_effective_pool_api_pool_routes_to_custom_backing_queue() {+ let reg = pool_registry();+ reg.update_worker(+ "http://w1:8080",+ worker_msg("default", "l4-spot", "customer-queue"),+ )+ .await;+ let pm = PoolManager::new(vec!["l4-spot".into()]);+ sync_static_queue_pool(&pm, "customer-queue", "l4-spot").await;+ let mut gpus = std::collections::HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ pm.create_pool_with_caps_on_queue(+ "tenant-a",+ "customer-queue",+ gpus,+ std::collections::HashMap::new(),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .unwrap();++ let out =+ resolve_effective_pool(®, Some(&pm), "default", "l4-spot", "tenant-a", "").await;+ assert_eq!(out.resolution, route("customer-queue", "l4-spot"));+ assert_eq!(out.admission_pool, "tenant-a");+ assert_eq!(out.demand_pool, "customer-queue");+ assert!(out.exact_gpu_match);+ }++ #[tokio::test]+ async fn test_resolve_effective_pool_api_pool_uses_custom_backing_queue_for_cold_demand() {+ let reg = pool_registry();+ let pm = PoolManager::new(vec!["l4-spot".into()]);+ sync_static_queue_pool(&pm, "customer-queue", "l4-spot").await;+ let mut gpus = std::collections::HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ pm.create_pool_with_caps_on_queue(+ "tenant-a",+ "customer-queue",+ gpus,+ std::collections::HashMap::new(),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .unwrap();++ let out =+ resolve_effective_pool(®, Some(&pm), "default", "l4-spot", "tenant-a", "").await;+ assert_eq!(out.resolution, PoolResolution::Provisioning);+ assert_eq!(out.admission_pool, "tenant-a");+ assert_eq!(out.demand_pool, "customer-queue");+ assert_eq!(out.pending_demand_profile.as_deref(), Some("l4-spot"));+ assert!(!out.exact_gpu_match);+ }+#[tokio::test]async fn test_resolve_effective_pool_pinned_pool_with_missing_gpu_tuple_reports_no_match() {// Caller pinned a pool AND expressed a GPU preference, but no@@ -15576,6 +16203,50 @@ mod tests {assert_eq!(err_obj["attempt_id"], "att-rl-1");}+ async fn assert_streaming_worker_error_is_retryable(+ code: &'static str,+ retry_after: &'static str,+ ) {+ let err = StreamingDriverErr::WorkerError {+ code: code.to_string(),+ message: "Retryable worker error; retry later.".to_string(),+ request_id: "req-retry-1".to_string(),+ attempt_id: "att-retry-1".to_string(),+ };+ let resp = build_streaming_error_response(&err);++ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(resp.headers().get("retry-after").unwrap(), retry_after);+ assert_eq!(resp.headers().get("x-sie-error-code").unwrap(), code);+ let body = axum::body::to_bytes(resp.into_body(), 16 * 1024)+ .await+ .unwrap();+ let v: serde_json::Value = serde_json::from_slice(&body).unwrap();+ let err_obj = v.get("error").expect("error envelope");+ assert_eq!(err_obj["type"], oai_type::SERVER_ERROR);+ assert_eq!(err_obj["code"], code);+ assert_eq!(err_obj["attempt_id"], "att-retry-1");+ }++ #[tokio::test]+ async fn test_build_streaming_error_response_retryable_worker_errors_return_503() {+ assert_streaming_worker_error_is_retryable(+ RESOURCE_EXHAUSTED_ERROR_CODE,+ RESOURCE_EXHAUSTED_RETRY_AFTER,+ )+ .await;+ assert_streaming_worker_error_is_retryable(+ MODEL_LOADING_ERROR_CODE,+ MODEL_LOADING_RETRY_AFTER,+ )+ .await;+ assert_streaming_worker_error_is_retryable(+ LORA_LOADING_ERROR_CODE,+ LORA_LOADING_RETRY_AFTER,+ )+ .await;+ }+/// HTTP status mapping unit test — guards against an off-by-one/// edit that drops the 429 mapping without touching/// ``build_streaming_error_response``.diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex d9d91870b..f9a15f390 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -88,6 +88,7 @@ pub struct SseParams<'a> {pub engine: String,pub gpu: String,pub pool: String,+ pub admission_pool: String,pub bundle_config_hash: String,pub work_params: publisher::WorkParams,pub endpoint: SseEndpoint,@@ -113,6 +114,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {engine,gpu,pool,+ admission_pool,bundle_config_hash,work_params,endpoint,@@ -161,7 +163,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {} else {let admitted_worker_names = state.pool_manager- .admitted_worker_names_for_capped_lane(&pool, &gpu, &bundle)+ .admitted_worker_names_for_capped_lane(&admission_pool, &gpu, &bundle).await;let fallback_lane_worker_count = state.registry.pool_fallback_lane_worker_count(&pool,@@ -212,7 +214,14 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {let was_direct_dispatched = matches!(target, publisher::PublishTarget::Worker { .. });let (request_id, outcome_rx, chunk_rx) = match work_publisher- .publish_generate_streaming_sse(target, &model, &engine, &bundle_config_hash, &work_params)+ .publish_generate_streaming_sse(+ target,+ &model,+ &engine,+ &bundle_config_hash,+ &work_params,+ &admission_pool,+ ).await{Ok(triple) => triple,diff --git a/packages/sie_gateway/src/metrics.rs b/packages/sie_gateway/src/metrics.rsindex 5d5eeeae4..1cfcc531d 100644--- a/packages/sie_gateway/src/metrics.rs+++ b/packages/sie_gateway/src/metrics.rs@@ -1183,30 +1183,42 @@ pub fn update_pool_metrics(pools: &[crate::types::Pool]) {ACTIVE_LEASE_GPUS.reset();ACTIVE_LEASE_GPUS.with_label_values(&["", "", ""]).set(0.0);+ let mut active_workers_by_lane: std::collections::HashMap<+ (String, String, String),+ std::collections::HashSet<String>,+ > = std::collections::HashMap::new();+for pool in pools {if pool.status.state == PoolState::Active && pool.spec.name != DEFAULT_POOL_NAME {- if let Some(bundle) = pool.spec.bundle.as_deref() {- for (gpu_type, count) in &pool.spec.gpus {- ACTIVE_LEASE_GPUS- .with_label_values(&[&pool.spec.name, gpu_type, bundle])- .add(*count as f64);- }+ let queue_pool = pool.spec.queue_pool.trim();+ let metric_pool = if queue_pool.is_empty() {+ DEFAULT_POOL_NAME} else {- let mut assigned_by_lane: std::collections::HashMap<(&str, &str), usize> =- std::collections::HashMap::new();- for worker in &pool.status.assigned_workers {- *assigned_by_lane- .entry((&worker.gpu, &worker.bundle))- .or_default() += 1;- }- for ((gpu_type, bundle), count) in assigned_by_lane {- ACTIVE_LEASE_GPUS- .with_label_values(&[&pool.spec.name, gpu_type, bundle])- .add(count as f64);- }+ queue_pool+ };+ for worker in &pool.status.assigned_workers {+ let worker_key = if worker.name.trim().is_empty() {+ worker.url.clone()+ } else {+ worker.name.clone()+ };+ active_workers_by_lane+ .entry((+ metric_pool.to_string(),+ worker.gpu.clone(),+ worker.bundle.clone(),+ ))+ .or_default()+ .insert(worker_key);}}}++ for ((metric_pool, gpu_type, bundle), workers) in active_workers_by_lane {+ ACTIVE_LEASE_GPUS+ .with_label_values(&[&metric_pool, &gpu_type, &bundle])+ .set(workers.len() as f64);+ }}#[cfg(test)]@@ -1236,6 +1248,7 @@ mod tests {Pool {spec: PoolSpec {name: name.to_string(),+ queue_pool: name.to_string(),bundle,gpus,gpu_caps: HashMap::new(),@@ -1261,12 +1274,27 @@ mod tests {let mut gpus = HashMap::new();gpus.insert("l4-spot".to_string(), 2);- let pools = vec![make_pool(+ let mut pool = make_pool("eval-pool",PoolState::Active,gpus,Some("premium".to_string()),- )];+ );+ pool.status.assigned_workers = vec![+ AssignedWorker {+ name: "worker-1".to_string(),+ url: "http://worker-1:8080".to_string(),+ gpu: "l4-spot".to_string(),+ bundle: "premium".to_string(),+ },+ AssignedWorker {+ name: "worker-2".to_string(),+ url: "http://worker-2:8080".to_string(),+ gpu: "l4-spot".to_string(),+ bundle: "premium".to_string(),+ },+ ];+ let pools = vec![pool];update_pool_metrics(&pools);@@ -1312,6 +1340,113 @@ mod tests {assert!((sglang_val - 1.0).abs() < f64::EPSILON);}+ #[test]+ fn test_update_pool_metrics_logical_pool_uses_backing_queue_pool() {+ let _guard = METRICS_TEST_LOCK.lock().unwrap();+ let _ = &*REGISTRY;+ reset_test_metrics();++ let mut gpus = HashMap::new();+ gpus.insert("l4".to_string(), 1);+ let mut pool = make_pool(+ "tenant-a",+ PoolState::Active,+ gpus,+ Some("default".to_string()),+ );+ pool.spec.queue_pool = "default".to_string();+ pool.status.assigned_workers = vec![AssignedWorker {+ name: "worker-default".to_string(),+ url: "http://worker-default:8080".to_string(),+ gpu: "l4".to_string(),+ bundle: "default".to_string(),+ }];++ update_pool_metrics(&[pool]);++ let backing_val = ACTIVE_LEASE_GPUS+ .with_label_values(&["default", "l4", "default"])+ .get();+ let logical_val = ACTIVE_LEASE_GPUS+ .with_label_values(&["tenant-a", "l4", "default"])+ .get();+ assert!((backing_val - 1.0).abs() < f64::EPSILON);+ assert!((logical_val - 0.0).abs() < f64::EPSILON);+ }++ #[test]+ fn test_update_pool_metrics_logical_pool_uses_custom_backing_queue_pool() {+ let _guard = METRICS_TEST_LOCK.lock().unwrap();+ let _ = &*REGISTRY;+ reset_test_metrics();++ let mut gpus = HashMap::new();+ gpus.insert("l4".to_string(), 1);+ let mut pool = make_pool(+ "tenant-a",+ PoolState::Active,+ gpus,+ Some("default".to_string()),+ );+ pool.spec.queue_pool = "customer-queue".to_string();+ pool.status.assigned_workers = vec![AssignedWorker {+ name: "worker-customer".to_string(),+ url: "http://worker-customer:8080".to_string(),+ gpu: "l4".to_string(),+ bundle: "default".to_string(),+ }];++ update_pool_metrics(&[pool]);++ let backing_val = ACTIVE_LEASE_GPUS+ .with_label_values(&["customer-queue", "l4", "default"])+ .get();+ let logical_val = ACTIVE_LEASE_GPUS+ .with_label_values(&["tenant-a", "l4", "default"])+ .get();+ assert!((backing_val - 1.0).abs() < f64::EPSILON);+ assert!((logical_val - 0.0).abs() < f64::EPSILON);+ }++ #[test]+ fn test_update_pool_metrics_deduplicates_shared_backing_queue_workers() {+ let _guard = METRICS_TEST_LOCK.lock().unwrap();+ let _ = &*REGISTRY;+ reset_test_metrics();++ let mut gpus = HashMap::new();+ gpus.insert("l4".to_string(), 1);+ let assigned = AssignedWorker {+ name: "worker-default".to_string(),+ url: "http://worker-default:8080".to_string(),+ gpu: "l4".to_string(),+ bundle: "default".to_string(),+ };+ let mut pool_a = make_pool(+ "tenant-a",+ PoolState::Active,+ gpus.clone(),+ Some("default".to_string()),+ );+ pool_a.spec.queue_pool = "default".to_string();+ pool_a.status.assigned_workers = vec![assigned.clone()];+ let mut pool_b = make_pool(+ "tenant-b",+ PoolState::Active,+ gpus,+ Some("default".to_string()),+ );+ pool_b.spec.queue_pool = "default".to_string();+ pool_b.status.assigned_workers = vec![assigned];++ update_pool_metrics(&[pool_a, pool_b]);++ let backing_val = ACTIVE_LEASE_GPUS+ .with_label_values(&["default", "l4", "default"])+ .get();+ assert!((backing_val - 1.0).abs() < f64::EPSILON);+ }+#[test]fn test_update_pool_metrics_skips_default_pool() {let _guard = METRICS_TEST_LOCK.lock().unwrap();diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 7fa9f4beb..7d153913c 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -271,6 +271,15 @@ fn apply_gateway_openapi_overrides(value: &mut Value) {"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.");}+ if let Some(queue_pool_schema) = create_pool+ .get_mut("properties")+ .and_then(|properties| properties.get_mut("queue_pool"))+ {+ queue_pool_schema["minLength"] = json!(1);+ queue_pool_schema["maxLength"] = json!(128);+ queue_pool_schema["pattern"] =+ json!("^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$");+ }create_pool["anyOf"] = json!([{"required": ["gpus"],@@ -291,6 +300,18 @@ fn apply_gateway_openapi_overrides(value: &mut Value) {]);}+ if let Some(queue_pool_schema) = value+ .get_mut("components")+ .and_then(|components| components.get_mut("schemas"))+ .and_then(|schemas| schemas.get_mut("PoolSpec"))+ .and_then(|pool_spec| pool_spec.get_mut("properties"))+ .and_then(|properties| properties.get_mut("queue_pool"))+ {+ queue_pool_schema["minLength"] = json!(1);+ queue_pool_schema["maxLength"] = json!(128);+ queue_pool_schema["pattern"] = json!("^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$");+ }+patch_chat_completion_schema(value);let paths = value["paths"]@@ -2458,6 +2479,18 @@ mod tests {create_pool["properties"]["name"]["pattern"],json!("^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$"));+ assert_eq!(+ create_pool["properties"]["queue_pool"]["minLength"],+ json!(1)+ );+ assert_eq!(+ create_pool["properties"]["queue_pool"]["maxLength"],+ json!(128)+ );+ assert_eq!(+ create_pool["properties"]["queue_pool"]["pattern"],+ json!("^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$")+ );assert!(create_pool["properties"]["name"]["description"].as_str().unwrap()@@ -2483,6 +2516,17 @@ mod tests {}]));++ let pool_spec = &spec["components"]["schemas"]["PoolSpec"];+ assert_eq!(pool_spec["properties"]["queue_pool"]["minLength"], json!(1));+ assert_eq!(+ pool_spec["properties"]["queue_pool"]["maxLength"],+ json!(128)+ );+ assert_eq!(+ pool_spec["properties"]["queue_pool"]["pattern"],+ json!("^(?!_[dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$")+ );}#[test]diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex 024c05209..b909730c3 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -439,6 +439,8 @@ struct WorkItemRef<'a> {pub profile_id: &'a str,pub engine: &'a str,pub pool_name: &'a str,+ #[serde(skip_serializing_if = "str::is_empty")]+ pub admission_pool: &'a str,pub machine_profile: &'a str,pub item: Option<&'a rmpv::Value>,pub payload_ref: Option<&'a str>,@@ -479,6 +481,7 @@ struct WorkItemShared<'a> {endpoint: &'a str,model: &'a str,pool: &'a str,+ admission_pool: &'a str,gpu: &'a str,engine: &'a str,bundle_config_hash: &'a str,@@ -659,6 +662,43 @@ struct ResultCollector {deadline: Instant,operation: String,published_at: Instant,+ pool_label: String,+ model_label: String,+ pool_fallback_subject: Option<String>,+ direct_fallback_payloads: Vec<Option<Vec<u8>>>,+ direct_fallback_republished: bool,+}++struct PublishedWorkItem {+ index: usize,+ ack: jetstream::context::PublishAckFuture,+ encoded: Vec<u8>,+}++type DirectFallbackPayload = (usize, Vec<u8>);+type DirectFallbackPayloads = Vec<DirectFallbackPayload>;++fn take_direct_fallback_payloads(+ collector: &mut ResultCollector,+) -> Option<(String, DirectFallbackPayloads)> {+ if collector.direct_fallback_republished {+ return None;+ }+ let subject = collector.pool_fallback_subject.clone()?;+ let mut payloads = Vec::new();+ for (index, payload) in collector.direct_fallback_payloads.iter().enumerate() {+ let still_missing = collector.results.get(index).is_some_and(Option::is_none);+ if still_missing {+ if let Some(bytes) = payload.clone() {+ payloads.push((index, bytes));+ }+ }+ }+ if payloads.is_empty() {+ return None;+ }+ collector.direct_fallback_republished = true;+ Some((subject, payloads))}fn stream_name(pool: &str) -> String {@@ -1408,23 +1448,24 @@ impl WorkPublisher {#[allow(clippy::too_many_arguments)]pub async fn publish_work(&self,- pool: &str,+ target: PublishTarget,+ admission_pool: &str,endpoint: &str,model: &str,- bundle: &str,engine: &str,- gpu: &str,bundle_config_hash: &str,items: Vec<rmpv::Value>,params: &WorkParams,) -> Result<(String, oneshot::Receiver<Vec<WorkResult>>), String> {let start = Instant::now();+ let pool = target.pool().to_string();+ let gpu = target.machine_profile().to_string();// Ensure stream exists (cached — first call per pool does admin API, subsequent are free)- self.ensure_stream(pool).await?;+ self.ensure_stream(&pool).await?;// Check backpressure (lock-free read from background-updated cache)- self.check_backpressure(pool)?;+ self.check_backpressure(&pool)?;// UUIDv7 keeps the leading 48 bits as a big-endian Unix// millisecond timestamp, so lexicographic / B-tree-indexed@@ -1439,7 +1480,18 @@ impl WorkPublisher {items.len() as u32};- let subject = work_subject(pool, gpu, bundle, model);+ let subject = target.subject();+ let pool_fallback_subject = match (&target, endpoint) {+ (PublishTarget::Worker { .. }, "generate") => None,+ (PublishTarget::Worker { .. }, _) => Some(target.as_pool_fallback().subject()),+ (PublishTarget::Pool { .. }, _) => None,+ };+ let direct_publish_fallback_subject = pool_fallback_subject.clone();+ let direct_publish_retry_items = if direct_publish_fallback_subject.is_some() {+ Some(items.clone())+ } else {+ None+ };// Set up result collector (DashMap — lock-free per-key insert)let (tx, rx) = oneshot::channel();@@ -1452,6 +1504,11 @@ impl WorkPublisher {deadline: Instant::now() + self.result_timeout,operation: endpoint.to_string(),published_at: Instant::now(),+ pool_label: pool.clone(),+ model_label: model.to_string(),+ pool_fallback_subject,+ direct_fallback_payloads: vec![None; total_items as usize],+ direct_fallback_republished: false,},);@@ -1470,12 +1527,13 @@ impl WorkPublisher {// params block. `WorkItemRef` borrows these values so we don't// pay N × `Option<Vec<String>> / Option<serde_json::Value>`// deep clones on the hot path.- let shared = WorkItemShared {+ let shared = Arc::new(WorkItemShared {request_id: &request_id,endpoint,model,- pool,- gpu,+ pool: &pool,+ admission_pool,+ gpu: &gpu,engine,bundle_config_hash,router_id: &self.router_id,@@ -1484,7 +1542,7 @@ impl WorkPublisher {timestamp,traceparent: traceparent.as_deref(),tracestate: tracestate.as_deref(),- };+ });// Running publishes concurrently via `try_join_all` means// a late-failing item can race ahead of earlier successes —@@ -1492,39 +1550,77 @@ impl WorkPublisher {// and whatever payloads the successful siblings already// wrote to the offload store, otherwise both leak until// the result-timeout sweep kicks in.- let publish_outcome = if endpoint == "score" {- self.publish_score(&shared, items, &subject)- .await- .map(|ack| vec![ack])- } else if endpoint == "generate" {- // Discard the cached encoded bytes — this code path is- // the batch-style publish used by other callers; the- // streaming generate path takes its own dedicated branch- // in `publish_generate_streaming` and is the only place- // that needs the bytes for direct-dispatch republishing.- self.publish_generate(&shared, &subject)- .await- .map(|(ack, _encoded)| vec![ack])- } else {- // JetStream publishes issue the send-and-receive-ack cycle- // asynchronously per message, so a batch of N items that- // used to serialize on `.await` now overlap their network- // round trips. Each future in the set borrows `shared` +- // owns its per-item `rmpv::Value`.- let publishes = items.into_iter().enumerate().map(|(index, item_value)| {- self.publish_single(&shared, total_items, index, item_value, &subject)- });- try_join_all(publishes).await- };- let ack_futures = match publish_outcome {- Ok(acks) => acks,+ let publish_outcome = self+ .publish_batch_items(endpoint, Arc::clone(&shared), total_items, items, &subject)+ .await;+ let published_items = match publish_outcome {+ Ok(items) => items,Err(e) => {- self.pending_results.remove(&request_id);- self.cleanup_offloaded_payloads(&request_id, total_items)- .await;- return Err(e);+ if let (Some(fallback_subject), Some(retry_items)) =+ (direct_publish_fallback_subject, direct_publish_retry_items)+ {+ warn!(+ request_id = %request_id,+ subject = %subject,+ fallback_subject = %fallback_subject,+ error = %e,+ "worker-direct publish failed; retrying non-streaming work on pool subject"+ );+ match self+ .publish_batch_items(+ endpoint,+ Arc::clone(&shared),+ total_items,+ retry_items,+ &fallback_subject,+ )+ .await+ {+ Ok(items) => {+ metrics::ROUTING_FALLBACK_TOTAL+ .with_label_values(&[+ &metrics::sanitize_model_label(model),+ &metrics::sanitize_label(&pool),+ "batch_direct_publish_error",+ ])+ .inc();+ items+ }+ Err(fallback_err) => {+ self.pending_results.remove(&request_id);+ self.cleanup_offloaded_payloads(&request_id, total_items)+ .await;+ return Err(format!(+ "{}; pool fallback publish failed: {}",+ e, fallback_err+ ));+ }+ }+ } else {+ self.pending_results.remove(&request_id);+ self.cleanup_offloaded_payloads(&request_id, total_items)+ .await;+ return Err(e);+ }}};+ let mut ack_futures = Vec::with_capacity(published_items.len());+ let should_cache_direct_fallback = self+ .pending_results+ .get(&request_id)+ .is_some_and(|entry| entry.pool_fallback_subject.is_some());+ if should_cache_direct_fallback {+ if let Some(mut entry) = self.pending_results.get_mut(&request_id) {+ for item in &published_items {+ if item.index < entry.direct_fallback_payloads.len() {+ entry.direct_fallback_payloads[item.index] = Some(item.encoded.clone());+ }+ }+ }+ }+ for item in published_items {+ ack_futures.push(item.ack);+ }// Fire-and-forget: spawn background task to monitor acks.// The request handler proceeds immediately to wait for inbox results.@@ -1553,6 +1649,7 @@ impl WorkPublisher {request_id = %request_id,items = total_items,pool = %pool,+ target = target.label(),endpoint = %endpoint,latency_ms = elapsed.as_millis(),"published work items"@@ -1561,6 +1658,145 @@ impl WorkPublisher {Ok((request_id, rx))}+ async fn publish_batch_items(+ &self,+ endpoint: &str,+ shared: Arc<WorkItemShared<'_>>,+ total_items: u32,+ items: Vec<rmpv::Value>,+ subject: &str,+ ) -> Result<Vec<PublishedWorkItem>, String> {+ if endpoint == "score" {+ self.publish_score(shared.as_ref(), items, subject)+ .await+ .map(|(ack, encoded)| {+ vec![PublishedWorkItem {+ index: 0,+ ack,+ encoded,+ }]+ })+ } else if endpoint == "generate" {+ self.publish_generate(shared.as_ref(), subject)+ .await+ .map(|(ack, encoded)| {+ vec![PublishedWorkItem {+ index: 0,+ ack,+ encoded,+ }]+ })+ } else {+ // JetStream publishes issue the send-and-receive-ack cycle+ // asynchronously per message, so a batch of N items that+ // used to serialize on `.await` now overlap their network+ // round trips. Each future in the set borrows `shared` ++ // owns its per-item `rmpv::Value`.+ let publishes = items.into_iter().enumerate().map(|(index, item_value)| {+ let subject = subject.to_string();+ let shared = Arc::clone(&shared);+ async move {+ self.publish_single(shared.as_ref(), total_items, index, item_value, &subject)+ .await+ .map(|(ack, encoded)| PublishedWorkItem {+ index,+ ack,+ encoded,+ })+ }+ });+ try_join_all(publishes).await+ }+ }++ /// Arm a one-shot recovery for non-streaming worker-direct batch work.+ ///+ /// Capped logical pools direct-dispatch encode/score/extract to one+ /// admitted worker so unassigned peers do not burn the JetStream+ /// delivery budget. If that worker or its private consumer disappears+ /// after the gateway publishes, the worker-specific stream cannot fail+ /// over by itself. This timer republishes any still-missing items to the+ /// lane's pool subject once; late duplicate results are harmless because+ /// the result collector removes itself on first complete response.+ pub fn spawn_batch_direct_fallback(self: &Arc<Self>, request_id: String, delay: Duration) {+ let publisher = Arc::clone(self);+ tokio::spawn(async move {+ tokio::time::sleep(delay).await;+ if let Err(e) = publisher+ .republish_pending_result_to_pool(&request_id, "batch_direct_timeout")+ .await+ {+ warn!(+ request_id = %request_id,+ error = %e,+ "batch direct-dispatch fallback failed"+ );+ }+ });+ }++ pub async fn republish_pending_result_to_pool(+ &self,+ request_id: &str,+ reason: &'static str,+ ) -> Result<bool, String> {+ let (subject, payloads, operation, pool, model) = {+ let Some(mut entry) = self.pending_results.get_mut(request_id) else {+ return Ok(false);+ };+ let Some((subject, payloads)) = take_direct_fallback_payloads(entry.value_mut()) else {+ return Ok(false);+ };+ let operation = entry.operation.clone();+ let pool = entry.pool_label.clone();+ let model = entry.model_label.clone();+ (subject, payloads, operation, pool, model)+ };++ let mut acks = Vec::with_capacity(payloads.len());+ for (index, payload) in payloads {+ let ack = self+ .jetstream+ .publish(subject.clone(), payload.into())+ .await+ .map_err(|e| {+ format!(+ "publish batch fallback item {} for {}: {}",+ index, request_id, e+ )+ })?;+ acks.push(ack);+ }++ metrics::ROUTING_FALLBACK_TOTAL+ .with_label_values(&[+ &metrics::sanitize_model_label(&model),+ &metrics::sanitize_label(&pool),+ reason,+ ])+ .inc();+ info!(+ request_id = %request_id,+ operation = %operation,+ subject = %subject,+ reason,+ "republished non-streaming direct-dispatch work to pool fallback"+ );++ for ack in acks {+ if let Err(e) = ack.await {+ warn!(+ request_id = %request_id,+ error = %e,+ "JetStream ack failed for batch direct fallback"+ );+ metrics::QUEUE_ACK_FAILURES.inc();+ }+ }++ Ok(true)+ }+fn trace_context_for_endpoint(endpoint: &str) -> (Option<String>, Option<String>) {if Self::should_propagate_queue_trace(endpoint) {crate::observability::propagation::inject_current_context()@@ -1584,7 +1820,7 @@ impl WorkPublisher {shared: &WorkItemShared<'_>,score_items: Vec<rmpv::Value>,subject: &str,- ) -> Result<jetstream::context::PublishAckFuture, String> {+ ) -> Result<(jetstream::context::PublishAckFuture, Vec<u8>), String> {let query_item = shared.params.query_item@@ -1602,6 +1838,7 @@ impl WorkPublisher {profile_id: "default",engine: shared.engine,pool_name: shared.pool,+ admission_pool: shared.admission_pool,machine_profile: shared.gpu,item: None,payload_ref: None,@@ -1660,10 +1897,12 @@ impl WorkPublisher {}}- self.jetstream- .publish(subject.to_string(), encoded.into())+ let ack = self+ .jetstream+ .publish(subject.to_string(), encoded.clone().into()).await- .map_err(|e| format!("publish score work item: {}", e))+ .map_err(|e| format!("publish score work item: {}", e))?;+ Ok((ack, encoded))}/// Publish a generation work item and wire up a streaming collector.@@ -1688,6 +1927,7 @@ impl WorkPublisher {engine: &str,bundle_config_hash: &str,params: &WorkParams,+ admission_pool: &str,) -> Result<(String,@@ -1740,6 +1980,7 @@ impl WorkPublisher {endpoint: "generate",model: &model,pool: &pool,+ admission_pool,gpu: &machine_profile,engine,bundle_config_hash,@@ -1802,6 +2043,7 @@ impl WorkPublisher {engine: &str,bundle_config_hash: &str,params: &WorkParams,+ admission_pool: &str,) -> Result<(String,@@ -1849,6 +2091,7 @@ impl WorkPublisher {endpoint: "generate",model: &model,pool: &pool,+ admission_pool,gpu: &machine_profile,engine,bundle_config_hash,@@ -2020,6 +2263,7 @@ impl WorkPublisher {profile_id: "default",engine: shared.engine,pool_name: shared.pool,+ admission_pool: shared.admission_pool,machine_profile: shared.gpu,item: None,payload_ref: None,@@ -2278,7 +2522,7 @@ impl WorkPublisher {index: usize,item_value: rmpv::Value,subject: &str,- ) -> Result<jetstream::context::PublishAckFuture, String> {+ ) -> Result<(jetstream::context::PublishAckFuture, Vec<u8>), String> {let work_item_id = format!("{}.{}", shared.request_id, index);let mut ref_item = WorkItemRef {work_item_id: &work_item_id,@@ -2290,6 +2534,7 @@ impl WorkPublisher {profile_id: "default",engine: shared.engine,pool_name: shared.pool,+ admission_pool: shared.admission_pool,machine_profile: shared.gpu,item: Some(&item_value),payload_ref: None,@@ -2337,10 +2582,12 @@ impl WorkPublisher {}}- self.jetstream- .publish(subject.to_string(), encoded.into())+ let ack = self+ .jetstream+ .publish(subject.to_string(), encoded.clone().into()).await- .map_err(|e| format!("publish work item {}/{}: {}", index, total_items, e))+ .map_err(|e| format!("publish work item {}/{}: {}", index, total_items, e))?;+ Ok((ack, encoded))}/// Handle an incoming result message (called from inbox subscription).@@ -2888,6 +3135,8 @@ mod tests {#[serde(default)]pub engine: String,pub pool_name: String,+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub admission_pool: String,pub machine_profile: String,#[serde(default)]pub item: Option<rmpv::Value>,@@ -2966,6 +3215,50 @@ mod tests {);}+ #[test]+ fn test_direct_batch_fallback_payloads_only_include_missing_items_once() {+ let (tx, _rx) = oneshot::channel();+ let mut collector = ResultCollector {+ _total_items: 3,+ results: vec![+ None,+ Some(WorkResult {+ work_item_id: "req.1".into(),+ request_id: "req".into(),+ item_index: 1,+ success: true,+ result_msgpack: Vec::new(),+ error: None,+ error_code: None,+ inference_ms: None,+ queue_ms: None,+ processing_ms: None,+ worker_id: None,+ tokenization_ms: None,+ postprocessing_ms: None,+ payload_fetch_ms: None,+ }),+ None,+ ],+ sender: Some(tx),+ deadline: Instant::now() + Duration::from_secs(30),+ operation: "encode".into(),+ published_at: Instant::now(),+ pool_label: "default".into(),+ model_label: "BAAI/bge-m3".into(),+ pool_fallback_subject: Some("sie.work.default.l4.default.BAAI__bge-m3".into()),+ direct_fallback_payloads: vec![Some(vec![0]), Some(vec![1]), Some(vec![2])],+ direct_fallback_republished: false,+ };++ let (subject, payloads) =+ take_direct_fallback_payloads(&mut collector).expect("fallback payloads");+ assert_eq!(subject, "sie.work.default.l4.default.BAAI__bge-m3");+ assert_eq!(payloads, vec![(0, vec![0]), (2, vec![2])]);+ assert!(collector.direct_fallback_republished);+ assert!(take_direct_fallback_payloads(&mut collector).is_none());+ }+#[test]fn test_pending_generation_snapshot_groups_collectors() {let now = Instant::now();@@ -3123,6 +3416,7 @@ mod tests {profile_id: String::new(),engine: "pytorch".to_string(),pool_name: "default".to_string(),+ admission_pool: "default".to_string(),machine_profile: "l4-spot".to_string(),item: Some(rmpv::Value::Map(vec![(rmpv::Value::from("text"),@@ -3159,6 +3453,7 @@ mod tests {assert_eq!(decoded.operation, "encode");assert_eq!(decoded.model_id, "BAAI/bge-m3");assert_eq!(decoded.pool_name, "default");+ assert_eq!(decoded.admission_pool, "default");assert_eq!(decoded.machine_profile, "l4-spot");assert_eq!(decoded.item,@@ -3210,6 +3505,7 @@ mod tests {profile_id: "default".to_string(),engine: "pytorch".to_string(),pool_name: "default".to_string(),+ admission_pool: "tenant".to_string(),machine_profile: "l4-spot".to_string(),item: Some(rmpv::Value::Map(vec![(rmpv::Value::from("text"),@@ -3252,6 +3548,7 @@ mod tests {profile_id: &owned.profile_id,engine: &owned.engine,pool_name: &owned.pool_name,+ admission_pool: &owned.admission_pool,machine_profile: &owned.machine_profile,item: Some(&item_value),payload_ref: None,@@ -3329,6 +3626,7 @@ mod tests {profile_id: String::new(),engine: String::new(),pool_name: "default".to_string(),+ admission_pool: String::new(),machine_profile: String::new(),item: None,payload_ref: Some("/tmp/payload_req-2_0.bin".to_string()),@@ -3763,6 +4061,7 @@ mod tests {profile_id: "default".to_string(),engine: "pytorch".to_string(),pool_name: "p".to_string(),+ admission_pool: String::new(),machine_profile: "g".to_string(),item: None,payload_ref: None,@@ -3911,6 +4210,7 @@ mod tests {profile_id: "default".to_string(),engine: "pytorch".to_string(),pool_name: "p".to_string(),+ admission_pool: String::new(),machine_profile: "g".to_string(),item: None,payload_ref: None,@@ -3954,6 +4254,7 @@ mod tests {profile_id: "default".to_string(),engine: "pytorch".to_string(),pool_name: "p".to_string(),+ admission_pool: String::new(),machine_profile: "g".to_string(),item: None,payload_ref: None,diff --git a/packages/sie_gateway/src/queue/streaming.rs b/packages/sie_gateway/src/queue/streaming.rsindex 376005ecd..82b1951f5 100644--- a/packages/sie_gateway/src/queue/streaming.rs+++ b/packages/sie_gateway/src/queue/streaming.rs@@ -885,6 +885,32 @@ mod tests {}}+ #[test]+ fn test_terminal_model_loading_error_chunk_builds_error_outcome() {+ let (tx, _rx) = oneshot::channel();+ let mut c = StreamCollector::new(+ tx,+ "Qwen/Qwen3-4B-Instruct-2507".to_string(),+ "default".to_string(),+ );+ let mut term = _make_chunk("req-load.0:model-loading", 0, "", true);+ term.finish_reason = Some("error".to_string());+ term.usage = None;+ term.error = Some(ChunkError {+ code: "MODEL_LOADING".to_string(),+ message: "Model 'Qwen/Qwen3-4B-Instruct-2507' is loading; retry later.".to_string(),+ });++ assert_eq!(c.apply(term), ChunkApplied::Terminal);+ let outcome = c.build_outcome().expect("terminal");+ let err = outcome.error.expect("terminal error");+ assert_eq!(outcome.text, "");+ assert_eq!(outcome.finish_reason, "error");+ assert_eq!(outcome.attempt_id, "req-load.0:model-loading");+ assert_eq!(err.code, "MODEL_LOADING");+ assert!(err.message.contains("retry later"));+ }+/// Multi-candidate (`n>1`): the terminal chunk carries a `candidates`/// array which the collector passes through verbatim onto the/// `StreamOutcome` for the body builder to expand into `choices[]`.diff --git a/packages/sie_gateway/src/state/k8s_pool_backend.rs b/packages/sie_gateway/src/state/k8s_pool_backend.rsindex 77099b32d..a9a253e47 100644--- a/packages/sie_gateway/src/state/k8s_pool_backend.rs+++ b/packages/sie_gateway/src/state/k8s_pool_backend.rs@@ -495,6 +495,7 @@ mod tests {let pool = Pool {spec: PoolSpec {name: "test".to_string(),+ queue_pool: "default".to_string(),bundle: Some("default".to_string()),gpus: {let mut m = HashMap::new();@@ -587,6 +588,7 @@ mod tests {Pool {spec: PoolSpec {name: name.to_string(),+ queue_pool: "default".to_string(),bundle: Some("default".to_string()),gpus: {let mut m = HashMap::new();diff --git a/packages/sie_gateway/src/state/k8s_pool_watcher.rs b/packages/sie_gateway/src/state/k8s_pool_watcher.rsindex 7c74953ed..3e2e0c457 100644--- a/packages/sie_gateway/src/state/k8s_pool_watcher.rs+++ b/packages/sie_gateway/src/state/k8s_pool_watcher.rs@@ -177,6 +177,7 @@ mod tests {Pool {spec: PoolSpec {name: name.to_string(),+ queue_pool: "default".to_string(),bundle: None,gpus: HashMap::new(),gpu_caps: HashMap::new(),diff --git a/packages/sie_gateway/src/state/pinned_models.rs b/packages/sie_gateway/src/state/pinned_models.rsindex 250d4cb89..cc96b06e4 100644--- a/packages/sie_gateway/src/state/pinned_models.rs+++ b/packages/sie_gateway/src/state/pinned_models.rs@@ -121,6 +121,7 @@ mod tests {Pool {spec: PoolSpec {name: name.to_string(),+ queue_pool: "default".to_string(),bundle: None,gpus: HashMap::new(),gpu_caps: HashMap::new(),@@ -171,6 +172,21 @@ mod tests {assert_eq!(prev.get("tenant").unwrap().len(), 1);}+ #[test]+ fn default_backed_logical_pool_reports_loaded_pinned_model() {+ let mut prev = PinnedLanes::new();+ let mut tenant = pool("tenant", &["BAAI/bge-m3"]);+ tenant.spec.queue_pool = "default".to_string();++ let actions = reconcile_pinned_models(+ &[tenant],+ &loaded(&[("tenant", &["BAAI/bge-m3"])]),+ &mut prev,+ );++ assert_eq!(actions, vec![set_action("tenant", "BAAI/bge-m3", 1.0)]);+ }+#[test]fn unloaded_model_reports_zero() {let mut prev = PinnedLanes::new();diff --git a/packages/sie_gateway/src/state/pool_manager.rs b/packages/sie_gateway/src/state/pool_manager.rsindex c055911f2..4a723eb1f 100644--- a/packages/sie_gateway/src/state/pool_manager.rs+++ b/packages/sie_gateway/src/state/pool_manager.rs@@ -93,6 +93,23 @@ impl std::fmt::Display for InvalidPoolNameError {impl std::error::Error for InvalidPoolNameError {}+#[derive(Debug)]+pub struct UnknownQueuePoolError {+ pub queue_pool: String,+}++impl std::fmt::Display for UnknownQueuePoolError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "Unknown backing queue_pool '{}': non-default queue pools must be declared under queueRouting.staticQueuePools",+ self.queue_pool+ )+ }+}++impl std::error::Error for UnknownQueuePoolError {}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct PoolAdmissionStatus {pub cap: u32,@@ -146,6 +163,19 @@ impl PoolManager {continue;}pool.spec.name = normalize_pool_name(&pool.spec.name);+ pool.spec.queue_pool = normalize_queue_pool(&pool.spec.queue_pool);+ if let Err(e) = validate_pool_name(&pool.spec.queue_pool) {+ warn!(pool = %pool.spec.name, queue_pool = %pool.spec.queue_pool, error = %e, "skipping pool with invalid backing queue pool from K8s restore");+ continue;+ }+ if !known_queue_pool_from_names(&static_pool_names, &pool.spec.queue_pool) {+ warn!(+ pool = %pool.spec.name,+ queue_pool = %pool.spec.queue_pool,+ "skipping pool with unknown backing queue pool from K8s restore"+ );+ continue;+ }if static_pool_names.contains(&normalize_pool_name(&pool.spec.name)) {continue;}@@ -230,6 +260,11 @@ impl PoolManager {.contains(&normalize_pool_name(name))}+ async fn is_known_queue_pool(&self, name: &str) -> bool {+ let static_pool_names = self.static_pool_names.read().await;+ known_queue_pool_from_names(&static_pool_names, name)+ }+pub async fn sync_static_pools(&self,specs: &[PoolSpec],@@ -255,6 +290,7 @@ impl PoolManager {});let static_spec = PoolSpec {name: name.clone(),+ queue_pool: name.clone(),bundle,gpus,gpu_caps: spec.gpu_caps.clone(),@@ -418,6 +454,31 @@ impl PoolManager {ttl_seconds: Option<u64>,minimum_worker_count: u32,pinned_models: Vec<String>,+ ) -> Result<Pool, Box<dyn std::error::Error + Send + Sync>> {+ self.create_pool_with_caps_on_queue(+ name,+ DEFAULT_POOL_NAME,+ gpus,+ gpu_caps,+ bundle,+ ttl_seconds,+ minimum_worker_count,+ pinned_models,+ )+ .await+ }++ #[allow(clippy::too_many_arguments)]+ pub async fn create_pool_with_caps_on_queue(+ &self,+ name: &str,+ queue_pool: &str,+ gpus: HashMap<String, u32>,+ gpu_caps: HashMap<String, u32>,+ bundle: Option<String>,+ ttl_seconds: Option<u64>,+ minimum_worker_count: u32,+ pinned_models: Vec<String>,) -> Result<Pool, Box<dyn std::error::Error + Send + Sync>> {let raw_name = name;validate_pool_name(name)?;@@ -425,6 +486,8 @@ impl PoolManager {if name == DEFAULT_POOL_NAME && raw_name != DEFAULT_POOL_NAME {return Err(Box::new(DefaultPoolMutationError));}+ validate_pool_name(queue_pool)?;+ let queue_pool = normalize_queue_pool(queue_pool);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;@@ -433,6 +496,11 @@ impl PoolManager {name: raw_name.to_string(),}));}+ if !self.is_known_queue_pool(&queue_pool).await {+ return Err(Box::new(UnknownQueuePoolError {+ queue_pool: queue_pool.clone(),+ }));+ }let now = Self::now_secs();let mut pools = self.pools.write().await;@@ -444,6 +512,7 @@ impl PoolManager {.get_mut(&pool_key).expect("pool key resolved from the same map");let spec_changed = existing.spec.bundle != bundle+ || existing.spec.queue_pool != queue_pool|| existing.spec.gpus != gpus|| existing.spec.gpu_caps != gpu_caps|| existing.spec.ttl_seconds != ttl_seconds@@ -457,6 +526,7 @@ impl PoolManager {existing.status.last_renewed = now;let event = if spec_changed {existing.spec.bundle = bundle;+ existing.spec.queue_pool = queue_pool.clone();existing.spec.gpus = gpus;existing.spec.gpu_caps = gpu_caps;existing.spec.ttl_seconds = ttl_seconds;@@ -496,6 +566,7 @@ impl PoolManager {let pool = Pool {spec: PoolSpec {name: name.clone(),+ queue_pool,bundle,gpus,gpu_caps,@@ -638,6 +709,13 @@ impl PoolManager {}}+ pub async fn queue_pool_for_pool(&self, pool_name: &str) -> Option<String> {+ let pools = self.pools.read().await;+ let key = pool_key_for_name(&pools, pool_name)?;+ let pool = pools.get(&key)?;+ Some(normalize_queue_pool(&pool.spec.queue_pool))+ }+pub async fn list_pools(&self) -> Vec<Pool> {let pools = self.pools.read().await;pools.values().cloned().collect()@@ -722,10 +800,13 @@ impl PoolManager {let pool = pools.get_mut(&pool_key).expect("pool key resolved from the same map");+ let queue_pool = normalize_queue_pool(&pool.spec.queue_pool);let filtered: Vec<&WorkerAssignment> = available_workers.iter()- .filter(|(_, _, _, _, queue_pool)| worker_consumes_pool(queue_pool, pool_name))+ .filter(|(_, _, _, _, worker_queue_pool)| {+ worker_consumes_pool(worker_queue_pool, &queue_pool)+ }).filter(|(_, _, _, bundle, _)| match pool.spec.bundle.as_ref() {Some(bundle_filter) => bundle == bundle_filter,None => true,@@ -849,6 +930,19 @@ impl PoolManager {}let name = normalize_pool_name(&raw_name);pool.spec.name = name.clone();+ pool.spec.queue_pool = normalize_queue_pool(&pool.spec.queue_pool);+ if let Err(e) = validate_pool_name(&pool.spec.queue_pool) {+ warn!(pool = %name, queue_pool = %pool.spec.queue_pool, error = %e, "skipping invalid backing queue pool from K8s watch");+ return;+ }+ if !self.is_known_queue_pool(&pool.spec.queue_pool).await {+ warn!(+ pool = %name,+ queue_pool = %pool.spec.queue_pool,+ "skipping pool with unknown backing queue pool from K8s watch"+ );+ return;+ }if self.is_static_pool(&name).await {return;}@@ -997,6 +1091,20 @@ pub(crate) fn normalize_pool_name(name: &str) -> String {name.trim().to_ascii_lowercase()}+fn normalize_queue_pool(name: &str) -> String {+ let normalized = normalize_pool_name(name);+ if normalized.is_empty() {+ DEFAULT_POOL_NAME.to_string()+ } else {+ normalized+ }+}++fn known_queue_pool_from_names(static_pool_names: &HashSet<String>, name: &str) -> bool {+ let queue_pool = normalize_queue_pool(name);+ queue_pool == DEFAULT_POOL_NAME || static_pool_names.contains(&queue_pool)+}+/// Deduplicated, lowercased machine-profile set for a pool, taken from the/// union of `spec.gpus` (requirements) and `spec.gpu_caps` (admission caps)./// This is the same set `single_machine_profile_for_pool` collapses to one;@@ -1072,6 +1180,21 @@ mod tests {)}+ fn static_queue_pool(name: &str, profile: &str) -> PoolSpec {+ let mut gpus = HashMap::new();+ gpus.insert(profile.to_string(), 0);+ PoolSpec {+ name: name.to_string(),+ queue_pool: name.to_string(),+ bundle: None,+ gpus,+ gpu_caps: HashMap::new(),+ ttl_seconds: None,+ minimum_worker_count: 0,+ pinned_models: Vec::new(),+ }+ }+#[test]fn test_validate_pool_name_matches_route_contract() {for name in ["default", "customer-acme", "bench_1", "A100Pool"] {@@ -1102,10 +1225,61 @@ mod tests {.await.unwrap();assert_eq!(pool.spec.name, "test");+ assert_eq!(pool.spec.queue_pool, DEFAULT_POOL_NAME);assert_eq!(pool.status.state, PoolState::Pending);assert_eq!(pool.spec.minimum_worker_count, 0);}+ #[tokio::test]+ async fn test_create_pool_rejects_unknown_non_default_queue_pool() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);++ let mut gpus = HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ let err = pm+ .create_pool_with_caps_on_queue(+ "tenant",+ "missing-queue",+ gpus,+ HashMap::new(),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .unwrap_err();++ assert!(err.to_string().contains("Unknown backing queue_pool"));+ }++ #[tokio::test]+ async fn test_create_pool_accepts_static_non_default_queue_pool() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);+ pm.sync_static_pools(&[static_queue_pool("bench", "l4-spot")])+ .await+ .unwrap();++ let mut gpus = HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ let pool = pm+ .create_pool_with_caps_on_queue(+ "tenant",+ "bench",+ gpus,+ HashMap::new(),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .unwrap();++ assert_eq!(pool.spec.name, "tenant");+ assert_eq!(pool.spec.queue_pool, "bench");+ }+#[tokio::test]async fn test_create_pool_stores_minimum_worker_count() {let pm = PoolManager::new(vec!["l4-spot".to_string()]);@@ -1301,6 +1475,7 @@ mod tests {gpus.insert("l4-spot".to_string(), 0);let specs = vec![PoolSpec {name: "company-a".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus,gpu_caps: HashMap::new(),@@ -1339,6 +1514,7 @@ mod tests {gpu_caps.insert("l4-spot".to_string(), 1);let specs = vec![PoolSpec {name: "bench".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus: HashMap::new(),gpu_caps,@@ -1373,6 +1549,7 @@ mod tests {gpus.insert("l4-spot".to_string(), 0);let specs = vec![PoolSpec {name: "bench".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus,gpu_caps: HashMap::new(),@@ -1410,6 +1587,7 @@ mod tests {gpus.insert("l4-spot".to_string(), 0);let specs = vec![PoolSpec {name: "Bench".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus,gpu_caps: HashMap::new(),@@ -1447,6 +1625,7 @@ mod tests {let specs = vec![PoolSpec {name: " bench".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus: HashMap::from([("l4-spot".to_string(), 0)]),gpu_caps: HashMap::new(),@@ -1473,6 +1652,7 @@ mod tests {let specs = vec![PoolSpec {name: "Bench".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus: gpus.clone(),gpu_caps: HashMap::new(),@@ -1482,6 +1662,7 @@ mod tests {},PoolSpec {name: "bench".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus,gpu_caps: HashMap::new(),@@ -1514,6 +1695,7 @@ mod tests {static_gpus.insert("l4-spot".to_string(), 0);let specs = vec![PoolSpec {name: "bench".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus: static_gpus,gpu_caps: HashMap::new(),@@ -1538,6 +1720,7 @@ mod tests {gpus.insert("l4-spot".to_string(), 0);let specs = vec![PoolSpec {name: "bench".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus,gpu_caps: HashMap::new(),@@ -1552,6 +1735,7 @@ mod tests {let remote = Pool {spec: PoolSpec {name: "bench".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: Some("other".to_string()),gpus: remote_gpus,gpu_caps: HashMap::new(),@@ -1595,9 +1779,9 @@ mod tests {.unwrap();let workers = vec![- worker_in_pool("w1", "http://w1:8080", "l4-spot", "default", "test"),- worker_in_pool("w2", "http://w2:8080", "l4-spot", "default", "test"),- worker_in_pool("w3", "http://w3:8080", "a100", "default", "test"),+ worker("w1", "http://w1:8080", "l4-spot", "default"),+ worker("w2", "http://w2:8080", "l4-spot", "default"),+ worker("w3", "http://w3:8080", "a100", "default"),];let all_met = pm.assign_workers("test", &workers).await;@@ -1625,7 +1809,7 @@ mod tests {&format!("http://w{}:8080", i),"l4-spot","default",- "test",+ DEFAULT_POOL_NAME,)}).collect();@@ -1657,7 +1841,7 @@ mod tests {&format!("http://w{}:8080", i),"l4-spot","default",- "test",+ DEFAULT_POOL_NAME,)}).collect();@@ -1683,9 +1867,9 @@ mod tests {.unwrap();let workers = vec![- worker_in_pool("w3", "http://w3:8080", "l4-spot", "default", "test"),- worker_in_pool("w1", "http://w1:8080", "l4-spot", "default", "test"),- worker_in_pool("w2", "http://w2:8080", "l4-spot", "default", "test"),+ worker("w3", "http://w3:8080", "l4-spot", "default"),+ worker("w1", "http://w1:8080", "l4-spot", "default"),+ worker("w2", "http://w2:8080", "l4-spot", "default"),];let all_met = pm.assign_workers("test", &workers).await;@@ -1702,7 +1886,7 @@ mod tests {}#[tokio::test]- async fn test_assign_workers_ignores_other_queue_pools_when_capped() {+ async fn test_dynamic_pool_assigns_default_backing_queue_when_capped() {let pm = PoolManager::new(vec!["l4-spot".to_string()]);let mut gpus = HashMap::new();@@ -1730,11 +1914,11 @@ mod tests {let pool = pm.get_pool("bench").await.unwrap();assert_eq!(pool.status.state, PoolState::Active);assert_eq!(pool.status.assigned_workers.len(), 1);- assert_eq!(pool.status.assigned_workers[0].name, "bench-worker");+ assert_eq!(pool.status.assigned_workers[0].name, "default-worker");}#[tokio::test]- async fn test_assign_workers_ignores_other_queue_pools_without_caps() {+ async fn test_dynamic_pool_assigns_default_backing_queue_without_caps() {let pm = PoolManager::new(vec!["l4-spot".to_string()]);let mut gpus = HashMap::new();@@ -1751,11 +1935,55 @@ mod tests {)];let all_met = pm.assign_workers("bench", &workers).await;- assert!(!all_met);+ assert!(all_met);let pool = pm.get_pool("bench").await.unwrap();- assert_eq!(pool.status.state, PoolState::Pending);- assert!(pool.status.assigned_workers.is_empty());+ assert_eq!(pool.status.state, PoolState::Active);+ assert_eq!(pool.status.assigned_workers.len(), 1);+ assert_eq!(pool.status.assigned_workers[0].name, "default-worker");+ }++ #[tokio::test]+ async fn test_assign_workers_honors_custom_backing_queue_pool() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);+ pm.sync_static_pools(&[static_queue_pool("bench", "l4-spot")])+ .await+ .unwrap();++ let mut gpus = HashMap::new();+ gpus.insert("l4-spot".to_string(), 1);+ pm.create_pool_with_caps_on_queue(+ "tenant",+ "bench",+ gpus,+ HashMap::new(),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .unwrap();++ let workers = vec![+ worker("default-worker", "http://w1:8080", "l4-spot", "default"),+ worker_in_pool(+ "bench-worker",+ "http://w2:8080",+ "l4-spot",+ "default",+ "bench",+ ),+ ];++ let all_met = pm.assign_workers("tenant", &workers).await;+ assert!(all_met);++ let pool = pm.get_pool("tenant").await.unwrap();+ assert_eq!(pool.spec.queue_pool, "bench");+ assert_eq!(pool.status.state, PoolState::Active);+ assert_eq!(pool.status.assigned_workers.len(), 1);+ assert_eq!(pool.status.assigned_workers[0].name, "bench-worker");}#[tokio::test]@@ -1776,7 +2004,7 @@ mod tests {&format!("http://w{}:8080", i),"l4-spot","default",- "test",+ DEFAULT_POOL_NAME,)}).collect();@@ -1826,7 +2054,7 @@ mod tests {"http://w1:8080","l4-spot","default",- "test",+ DEFAULT_POOL_NAME,)];pm.assign_workers("test", &workers).await;@@ -1855,8 +2083,8 @@ mod tests {.unwrap();let workers = vec![- worker_in_pool("w1", "http://w1:8080", "l4-spot", "default", "test"),- worker_in_pool("w2", "http://w2:8080", "l4-spot", "default", "test"),+ worker("w1", "http://w1:8080", "l4-spot", "default"),+ worker("w2", "http://w2:8080", "l4-spot", "default"),];pm.assign_workers("test", &workers).await;@@ -1880,8 +2108,8 @@ mod tests {.unwrap();let workers = vec![- worker_in_pool("w1", "http://w1:8080", "l4-spot", "default", "test"),- worker_in_pool("w2", "http://w2:8080", "l4-spot", "sglang", "test"),+ worker("w1", "http://w1:8080", "l4-spot", "default"),+ worker("w2", "http://w2:8080", "l4-spot", "sglang"),];pm.assign_workers("test", &workers).await;@@ -2117,6 +2345,7 @@ mod tests {let pool = Pool {spec: PoolSpec {name: DEFAULT_POOL_NAME.to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus: HashMap::new(),gpu_caps: HashMap::new(),@@ -2155,6 +2384,7 @@ mod tests {let pool = Pool {spec: PoolSpec {name: DEFAULT_POOL_NAME.to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus: HashMap::new(),gpu_caps: HashMap::new(),@@ -2298,6 +2528,7 @@ mod tests {let remote = Pool {spec: PoolSpec {name: "bench.l4".to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),bundle: None,gpus: HashMap::from([("l4-spot".to_string(), 1)]),gpu_caps: HashMap::new(),diff --git a/packages/sie_gateway/src/state/warm_floor.rs b/packages/sie_gateway/src/state/warm_floor.rsindex 6309b182e..830fecd1a 100644--- a/packages/sie_gateway/src/state/warm_floor.rs+++ b/packages/sie_gateway/src/state/warm_floor.rs@@ -8,8 +8,8 @@ use crate::types::pool::Pool;/// Tracks the warm-floor lanes the emitter set on the previous tick so it/// can clear lanes that disappear (pool deleted, `minimum_worker_count`-/// dropped to 0, or the profile/bundle set changed). Keyed by pool name; each-/// value is the set of `(machine_profile, bundle)` lanes that pool emitted+/// dropped to 0, or the profile/bundle set changed). Keyed by queue pool; each+/// value is the set of `(machine_profile, bundle)` lanes that queue pool emitted/// last tick.pub type WarmFloorLanes = HashMap<String, HashSet<(String, String)>>;@@ -45,13 +45,24 @@ fn bundle_label(pool: &Pool) -> String {.to_lowercase()}+fn queue_pool_label(pool: &Pool) -> String {+ let queue_pool = pool.spec.queue_pool.trim().to_ascii_lowercase();+ if queue_pool.is_empty() {+ "default".to_string()+ } else {+ queue_pool+ }+}+/// Reconcile the warm-floor gauge for the current set of pools.////// For every pool with `minimum_worker_count > 0` and at least one nameable-/// machine profile, emit one `Set` per `(machine_profile, bundle)` lane. Any lane-/// present last tick but absent now is emitted as a `Clear`. `prev` is-/// updated in place to the lanes emitted this tick so the next call can-/// detect disappearances.+/// machine profile, emit one `Set` per `(queue_pool, machine_profile, bundle)`+/// lane. Multiple logical pools sharing the same backing lane collapse to the+/// maximum requested floor, not a sum, because KEDA scales physical lanes. Any+/// lane present last tick but absent now is emitted as a `Clear`. `prev` is+/// updated in place to the lanes emitted this tick so the next call can detect+/// disappearances.////// A pool with no nameable machine profile (e.g. the bare `default` pool/// with empty `gpus`/`gpu_caps`) cannot name a lane; it emits nothing, and@@ -64,6 +75,7 @@ fn bundle_label(pool: &Pool) -> String {pub fn reconcile_warm_floor(pools: &[Pool], prev: &mut WarmFloorLanes) -> Vec<WarmFloorAction> {let mut actions = Vec::new();let mut current: WarmFloorLanes = HashMap::new();+ let mut values: HashMap<(String, String, String), f64> = HashMap::new();for pool in pools {if pool.spec.minimum_worker_count == 0 {@@ -79,19 +91,53 @@ pub fn reconcile_warm_floor(pools: &[Pool], prev: &mut WarmFloorLanes) -> Vec<Wacontinue;}let bundle = bundle_label(pool);+ let queue_pool = queue_pool_label(pool);let value = f64::from(pool.spec.minimum_worker_count);- let lanes = current.entry(pool.spec.name.clone()).or_default();for profile in profiles {- lanes.insert((profile.clone(), bundle.clone()));- actions.push(WarmFloorAction::Set {- pool: pool.spec.name.clone(),- machine_profile: profile,- bundle: bundle.clone(),- value,- });+ let lane = values+ .entry((queue_pool.clone(), profile, bundle.clone()))+ .or_default();+ *lane = f64::max(*lane, value);}}+ let mut set_actions: Vec<WarmFloorAction> = values+ .into_iter()+ .map(|((pool, machine_profile, bundle), value)| {+ current+ .entry(pool.clone())+ .or_default()+ .insert((machine_profile.clone(), bundle.clone()));+ WarmFloorAction::Set {+ pool,+ machine_profile,+ bundle,+ value,+ }+ })+ .collect();+ set_actions.sort_by(|a, b| match (a, b) {+ (+ WarmFloorAction::Set {+ pool: a_pool,+ machine_profile: a_profile,+ bundle: a_bundle,+ ..+ },+ WarmFloorAction::Set {+ pool: b_pool,+ machine_profile: b_profile,+ bundle: b_bundle,+ ..+ },+ ) => a_pool+ .cmp(b_pool)+ .then_with(|| a_profile.cmp(b_profile))+ .then_with(|| a_bundle.cmp(b_bundle)),+ _ => std::cmp::Ordering::Equal,+ });+ actions.extend(set_actions);+// Clear lanes we set last tick that are no longer present this tick.for (pool, lanes) in prev.iter() {let now = current.get(pool);@@ -145,6 +191,7 @@ mod tests {Pool {spec: PoolSpec {name: name.to_string(),+ queue_pool: name.to_string(),bundle: bundle.map(|b| b.to_string()),gpus,gpu_caps: HashMap::new(),@@ -173,6 +220,18 @@ mod tests {}}+ fn logical_pool(+ name: &str,+ queue_pool: &str,+ minimum_worker_count: u32,+ gpus: &[&str],+ bundle: Option<&str>,+ ) -> Pool {+ let mut pool = pool(name, minimum_worker_count, gpus, bundle);+ pool.spec.queue_pool = queue_pool.to_string();+ pool+ }+#[test]fn single_profile_emits_one_lane() {let mut prev = WarmFloorLanes::new();@@ -249,4 +308,34 @@ mod tests {let actions = reconcile_warm_floor(&[pool("tenant", 2, &["l4"], None)], &mut prev);assert_eq!(actions, vec![set_action("tenant", "l4", "default", 2.0)]);}++ #[test]+ fn logical_pools_share_backing_queue_floor_without_summing() {+ let mut prev = WarmFloorLanes::new();+ let actions = reconcile_warm_floor(+ &[+ logical_pool("tenant-a", "default", 2, &["l4"], None),+ logical_pool("tenant-b", "default", 1, &["l4"], None),+ ],+ &mut prev,+ );+ assert_eq!(actions, vec![set_action("default", "l4", "default", 2.0)]);+ assert_eq!(prev.get("default").unwrap().len(), 1);+ }++ #[test]+ fn logical_pool_uses_custom_backing_queue_floor() {+ let mut prev = WarmFloorLanes::new();+ let actions = reconcile_warm_floor(+ &[logical_pool("tenant-a", "customer-queue", 2, &["l4"], None)],+ &mut prev,+ );++ assert_eq!(+ actions,+ vec![set_action("customer-queue", "l4", "default", 2.0)]+ );+ assert_eq!(prev.get("customer-queue").unwrap().len(), 1);+ assert!(!prev.contains_key("tenant-a"));+ }}diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rsindex 368ba536c..8f27233c8 100644--- a/packages/sie_gateway/src/state/worker_registry.rs+++ b/packages/sie_gateway/src/state/worker_registry.rs@@ -390,25 +390,18 @@ impl WorkerRegistry {.collect()}- /// Workers that can receive a pool fallback for this concrete lane.- ///- /// Unlike [`Self::dispatch_workers_for`], this intentionally does not- /// require `model` to already be present in `loaded_models`: the pool- /// fallback path can land on a healthy same-lane worker that lazy-loads- /// the model. This count is used only to decide whether first-chunk- /// failover has an alternate consumer.- pub fn pool_fallback_lane_worker_count(+ fn lazy_lane_workers_for_matching(&self,pool: &str,machine_profile: &str,bundle: &str,bundle_config_hash: &str,admitted_worker_names: Option<&HashSet<String>>,- ) -> usize {+ ) -> Vec<WorkerState> {let snap = self.snapshot.load();let bundle_lower = bundle.to_lowercase();let Some(candidates) = snap.by_bundle.get(&bundle_lower) else {- return 0;+ return Vec::new();};candidates.iter()@@ -420,7 +413,64 @@ impl WorkerRegistry {&& w.machine_profile.eq_ignore_ascii_case(machine_profile)&& bundle_config_hash_matches(&w.bundle_config_hash, bundle_config_hash)})- .count()+ .cloned()+ .collect()+ }++ /// Workers that can receive a pool fallback for this concrete lane.+ ///+ /// Unlike [`Self::dispatch_workers_for`], this intentionally does not+ /// require `model` to already be present in `loaded_models`: the pool+ /// fallback path can land on a healthy same-lane worker that lazy-loads+ /// the model. This count is used only to decide whether first-chunk+ /// failover has an alternate consumer.+ pub fn pool_fallback_lane_worker_count(+ &self,+ pool: &str,+ machine_profile: &str,+ bundle: &str,+ bundle_config_hash: &str,+ admitted_worker_names: Option<&HashSet<String>>,+ ) -> usize {+ self.lazy_lane_workers_for_matching(+ pool,+ machine_profile,+ bundle,+ bundle_config_hash,+ admitted_worker_names,+ )+ .len()+ }++ /// Build a worker ring for capped logical batch dispatch.+ ///+ /// Unlike [`Self::ring_snapshot_for_admitted`], this intentionally does not+ /// require the target model to already be in `loaded_models`: encode/score/+ /// extract pool work is allowed to lazy-load the model. The admission filter+ /// still keeps the ring restricted to workers assigned to the logical pool.+ pub fn lazy_lane_ring_snapshot_for_admitted(+ &self,+ model: &str,+ pool: &str,+ machine_profile: &str,+ bundle: &str,+ bundle_config_hash: &str,+ admitted_worker_names: &HashSet<String>,+ ) -> RingSnapshot {+ let mut workers = self.lazy_lane_workers_for_matching(+ pool,+ machine_profile,+ bundle,+ bundle_config_hash,+ Some(admitted_worker_names),+ );+ workers.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.url.cmp(&b.url)));+ let before = workers.len();+ workers.dedup_by(|a, b| a.name == b.name);+ if workers.len() != before {+ warn_duplicate_worker_names(model, pool, before - workers.len());+ }+ RingSnapshot::new(workers.into_iter().map(|w| w.name))}/// Build a [`RingSnapshot`] for the given concrete queue lane. Uses@@ -1722,6 +1772,45 @@ mod tests {assert_eq!(ring.entries[0].worker_id, "assigned");}+ #[tokio::test]+ async fn test_lazy_lane_ring_snapshot_for_admitted_includes_cold_assigned_worker() {+ let reg = registry();+ let mut assigned = make_dispatch_msg(true, false, "p1", &[]).await;+ assigned.name = "assigned-cold".into();+ assigned.bundle_config_hash = "h1".into();+ reg.update_worker("http://assigned-cold:8080", assigned)+ .await;++ let mut unassigned = make_dispatch_msg(true, false, "p1", &[]).await;+ unassigned.name = "unassigned-cold".into();+ unassigned.bundle_config_hash = "h1".into();+ reg.update_worker("http://unassigned-cold:8080", unassigned)+ .await;++ let admitted = HashSet::from(["assigned-cold".to_string()]);++ let loaded_ring = reg.ring_snapshot_for_admitted(+ "BAAI/bge-m3",+ "p1",+ "l4",+ "default",+ "h1",+ Some(&admitted),+ );+ assert_eq!(loaded_ring.len(), 0);++ let lazy_ring = reg.lazy_lane_ring_snapshot_for_admitted(+ "BAAI/bge-m3",+ "p1",+ "l4",+ "default",+ "h1",+ &admitted,+ );+ assert_eq!(lazy_ring.len(), 1);+ assert_eq!(lazy_ring.entries[0].worker_id, "assigned-cold");+ }+#[tokio::test]async fn test_ring_snapshot_for_contains_eligible_only() {let reg = registry();diff --git a/packages/sie_gateway/src/types/pool.rs b/packages/sie_gateway/src/types/pool.rsindex 3e25fda5a..a5b18cabd 100644--- a/packages/sie_gateway/src/types/pool.rs+++ b/packages/sie_gateway/src/types/pool.rs@@ -23,6 +23,13 @@ impl std::fmt::Display for PoolState {#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]pub struct PoolSpec {pub name: String,+ /// Physical Helm/NATS queue namespace backing this logical API pool.+ ///+ /// API-created pools default to the Helm `default` queue pool. Pool `name`+ /// is user/dynamic; a non-default `queue_pool` is infra/admin and must+ /// match a Helm worker queue declared under `queueRouting.staticQueuePools`.+ #[serde(default = "default_queue_pool")]+ pub queue_pool: String,#[serde(default)]pub bundle: Option<String>,#[serde(default)]@@ -46,6 +53,10 @@ pub struct PoolSpec {pub pinned_models: Vec<String>,}+pub fn default_queue_pool() -> String {+ "default".to_string()+}+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]pub struct AssignedWorker {pub name: String,@@ -117,6 +128,7 @@ mod tests {Pool {spec: PoolSpec {name: "test".into(),+ queue_pool: default_queue_pool(),bundle: None,gpus: HashMap::new(),gpu_caps: HashMap::new(),@@ -237,6 +249,15 @@ mod tests {assert_eq!(spec.minimum_worker_count, 0);}+ #[test]+ fn test_pool_spec_queue_pool_defaults_to_default_when_absent() {+ // Older persisted ConfigMap state omits `queue_pool`; restore must keep+ // those logical pools backed by the default physical queue pool.+ let json = r#"{"name":"test","gpus":{"l4":1}}"#;+ let spec: PoolSpec = serde_json::from_str(json).unwrap();+ assert_eq!(spec.queue_pool, default_queue_pool());+ }+#[test]fn test_pool_spec_pinned_models_roundtrips() {let mut pool = make_pool(PoolState::Pending, vec![]);diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex 7893b2efe..b235315af 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.10"+version = "0.6.11"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex cf70d3198..dab03c047 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -571,6 +571,8 @@ class SIEAsyncClient:request_body["gpus"] = self._pool_spec["gpus"]if "gpu_caps" in self._pool_spec:request_body["gpu_caps"] = self._pool_spec["gpu_caps"]+ if "queue_pool" in self._pool_spec:+ request_body["queue_pool"] = self._pool_spec["queue_pool"]if "bundle" in self._pool_spec:request_body["bundle"] = self._pool_spec["bundle"]if self._pool_spec.get("minimum_worker_count") is not None:@@ -711,6 +713,8 @@ class SIEAsyncClient:bundle: str | None = None,minimum_worker_count: int | None = None,pinned_models: list[str] | None = None,+ *,+ queue_pool: str | None = None,) -> None:"""Create or update a resource pool for isolated capacity.@@ -730,6 +734,8 @@ class SIEAsyncClient:request to them pays no cold model-load. Each id must be a model thegateway already tracks and may be profile-qualified(``model-name:profile_name``); unknown ids are rejected. Defaults to none.+ queue_pool: Optional Helm/NATS queue namespace backing this logical+ pool. Defaults to "default", drawing from base capacity.Raises:PoolError: If pool creation fails (e.g., invalid machine profile).@@ -774,6 +780,8 @@ class SIEAsyncClient:request_body["gpus"] = gpusif gpu_caps is not None:request_body["gpu_caps"] = gpu_caps+ if queue_pool:+ request_body["queue_pool"] = queue_poolif bundle:request_body["bundle"] = bundleif minimum_worker_count is not None:diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 88e1c1596..402e85234 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -455,6 +455,8 @@ class SIEClient:request_body["gpus"] = self._pool_spec["gpus"]if "gpu_caps" in self._pool_spec:request_body["gpu_caps"] = self._pool_spec["gpu_caps"]+ if "queue_pool" in self._pool_spec:+ request_body["queue_pool"] = self._pool_spec["queue_pool"]if "bundle" in self._pool_spec:request_body["bundle"] = self._pool_spec["bundle"]if self._pool_spec.get("minimum_worker_count") is not None:@@ -585,6 +587,8 @@ class SIEClient:bundle: str | None = None,minimum_worker_count: int | None = None,pinned_models: list[str] | None = None,+ *,+ queue_pool: str | None = None,) -> None:"""Create or update a resource pool for isolated capacity.@@ -610,6 +614,8 @@ class SIEClient:request to them pays no cold model-load. Each id must be a model thegateway already tracks and may be profile-qualified(``model-name:profile_name``); unknown ids are rejected. Defaults to none.+ queue_pool: Optional Helm/NATS queue namespace backing this logical+ pool. Defaults to "default", drawing from base capacity.Raises:PoolError: If pool creation fails (e.g., invalid machine profile).@@ -641,6 +647,8 @@ class SIEClient:request_body["gpus"] = gpusif gpu_caps is not None:request_body["gpu_caps"] = gpu_caps+ if queue_pool:+ request_body["queue_pool"] = queue_poolif bundle:request_body["bundle"] = bundleif minimum_worker_count is not None:diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex 21ca750b5..87e43a993 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -565,6 +565,9 @@ class PoolSpec(TypedDict, total=False):Attributes:name: Pool name (required). Used in GPU param as "pool_name/machine_profile";the gateway stores and routes pool names in lowercase.+ queue_pool: Optional Helm/NATS queue namespace backing this logical pool.+ Defaults to "default", so API-created pools can draw from base+ capacity deployed once by operators.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.@@ -579,6 +582,7 @@ class PoolSpec(TypedDict, total=False):"""name: str+ queue_pool: strgpus: dict[str, int]gpu_caps: dict[str, int]bundle: str@@ -625,6 +629,8 @@ class PoolSpecResponse(TypedDict, total=False):"""Pool specification in API response.Attributes:+ name: Pool name.+ queue_pool: Helm/NATS queue namespace backing this logical pool.gpus: 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.@@ -632,6 +638,8 @@ class PoolSpecResponse(TypedDict, total=False):pinned_models: Per-pool set of model ids kept loaded (no cold model-load)."""+ name: str+ queue_pool: strgpus: dict[str, int]gpu_caps: dict[str, int]bundle: str | Nonediff --git a/packages/sie_server/Dockerfile.cuda12 b/packages/sie_server/Dockerfile.cuda12index 4328e28c6..b98f70416 100644--- a/packages/sie_server/Dockerfile.cuda12+++ b/packages/sie_server/Dockerfile.cuda12@@ -139,20 +139,35 @@ RUN .venv/bin/python -m sie_server.cli resolve-deps \&& echo "Bundle ${BUNDLE} requirements:" \&& cat /tmp/bundle-requirements.txt-# Bundle-specific deps go into a separate site-packages tree so the shared-# venv layer stays byte-identical across bundles (default, sglang,-# transformers5) of the same platform. `.venv/bin/pip` is used as the-# resolver so shared torch/transformers/nvidia wheels are visible on-# sys.path and only novel packages land under --target.-# flash-attn deps carry `sys_platform == 'linux'` markers so they install on-# Linux (this image) but not on developer machines.+# Bundle-specific deps go into a separate site-packages tree (``bundle-libs``,+# prepended to sys.path via a .pth) so the shared venv layer stays+# byte-identical across bundles. Branches resolve with ``.venv/bin/pip`` (shared+# torch/transformers/nvidia wheels visible on the venv's sys.path); bundle-libs+# carries each bundle's closure for any package whose version differs from the+# shared venv. flash-attn deps carry `sys_platform == 'linux'` markers so they+# install on Linux (this image) but not on developer machines.+#+# Per-bundle CUDA wheel index. SGLang's sgl-kernel/flashinfer wheels live on the+# docs.sglang.ai cu129 index (not PyPI), so the SGLang-family bundles add it.+# The gemma bundle (sglang 0.5.13 / torch 2.11 / cu130, CUDA 13) is built by the+# separate ``cuda13`` platform — see Dockerfile.cuda13 — not here.RUN --mount=type=cache,target=/root/.cache/pip \+ --mount=type=cache,target=/root/.cache/uv \mkdir -p /app/bundle-libs; \if [ -s /tmp/bundle-requirements.txt ]; then \- .venv/bin/pip install \- --target=/app/bundle-libs \- --no-compile \- -r /tmp/bundle-requirements.txt; \+ case "$BUNDLE" in \+ sglang | sglang-embedding) \+ .venv/bin/pip install \+ --target=/app/bundle-libs \+ --no-compile \+ --extra-index-url https://docs.sglang.ai/whl/cu129/ \+ -r /tmp/bundle-requirements.txt ;; \+ *) \+ .venv/bin/pip install \+ --target=/app/bundle-libs \+ --no-compile \+ -r /tmp/bundle-requirements.txt ;; \+ esac; \fi# bundle-libs cleanup (symmetric to the .venv cleanup in base). The .venv@@ -184,6 +199,10 @@ FROM nvidia/cuda:12.9.1-cudnn-devel-ubuntu22.04 AS runtime-sglangENV CUDA_HOME=/usr/local/cuda \LD_LIBRARY_PATH="/usr/local/cuda/lib64:$LD_LIBRARY_PATH"FROM runtime-sglang AS runtime-sglang-embedding+# NOTE: the gemma bundle (CUDA 13 / sglang 0.5.13 / torch 2.11 cu130) is built by+# the separate ``cuda13`` platform — packages/sie_server/Dockerfile.cuda13 — so+# this CUDA-12 image never produces a (mislabelled) CUDA-13 ``cuda12-gemma``+# image. See #1415.FROM runtime-${BUNDLE} AS runtimediff --git a/packages/sie_server/Dockerfile.cuda13 b/packages/sie_server/Dockerfile.cuda13new file mode 100644index 000000000..2119dfc6b--- /dev/null+++ b/packages/sie_server/Dockerfile.cuda13@@ -0,0 +1,280 @@+# syntax=docker/dockerfile:1+# SIE Server - CUDA 13 Image (Gemma 4 / cu130 bundles)+# Build from repo root:+# docker build -f packages/sie_server/Dockerfile.cuda13 --build-arg BUNDLE=gemma -t sie-server:cuda13-gemma .+#+# WHY A SEPARATE PLATFORM: the gemma bundle needs sglang 0.5.13, which pins+# torch==2.11.0 (cu130) + transformers 5.8.x and JIT-compiles cu130 kernels+# (flashinfer / tvm_ffi) through nvcc on first decode — so it requires a CUDA 13+# devel runtime. Keeping it here (platform ``cuda13``) instead of inside+# Dockerfile.cuda12 means a ``cuda13-gemma`` image is honestly labelled CUDA 13,+# not a CUDA-13 image hiding under a ``cuda12-*`` tag (see #1415).+#+# STRUCTURE: mirrors Dockerfile.cuda12's deps→base→builder→runtime stages so the+# shared logic (standalone Python, editable installs, bundle-libs .pth shadow,+# venv cleanup, --link COPY caching) stays consistent — KEEP THE TWO IN SYNC when+# editing shared stages. Differences vs cuda12: CUDA 13 bases throughout, and the+# builder uses the cu130 ``uv`` path unconditionally (every cuda13 bundle is a+# cu130 bundle), so there is no per-bundle runtime indirection.+#+# DUAL-TORCH CARRY: the shared base venv still installs torch 2.9 (cu129) from+# pyproject, and the gemma bundle overlays torch 2.11 (cu130) into bundle-libs+# (~+3 GB). Slimming torch out of sie-server core to drop the carry is a tracked+# follow-up (#1415).++ARG BUNDLE=gemma+ARG UV_VERSION=0.9.28++# =============================================================================+# Dependency image: uv and standalone Python 3.12 (CUDA 13 devel base)+# =============================================================================+FROM nvidia/cuda:13.0.0-cudnn-devel-ubuntu22.04 AS deps++ENV DEBIAN_FRONTEND=noninteractive \+ UV_NO_CACHE=1 \+ UV_COMPILE_BYTECODE=1 \+ UV_LINK_MODE=copy \+ UV_PYTHON_INSTALL_DIR=/opt/python \+ PIP_DISABLE_PIP_VERSION_CHECK=1++# Minimal apt footprint: just enough for curl + git; no deadsnakes PPA.+RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \+ --mount=type=cache,target=/var/lib/apt/lists,sharing=locked \+ apt-get update && apt-get install -y --no-install-recommends \+ ca-certificates \+ curl \+ git++ARG UV_VERSION+RUN curl -LsSf https://astral.sh/uv/${UV_VERSION}/install.sh | sh \+ && mv /root/.local/bin/uv /bin/uv \+ && mv /root/.local/bin/uvx /bin/uvx++# Install a standalone Python 3.12 from python-build-standalone (fully relocatable,+# glibc 2.17+ compat). This replaces the deadsnakes PPA entirely.+RUN uv python install 3.12 \+ && ln -s "$(uv python find 3.12)" /usr/local/bin/python3.12 \+ && ln -sf /usr/local/bin/python3.12 /usr/local/bin/python3 \+ && ln -sf /usr/local/bin/python3.12 /usr/local/bin/python++WORKDIR /app++COPY packages/sie_sdk/pyproject.toml /tmp/sie_sdk/pyproject.toml+COPY packages/sie_server/pyproject.toml ./pyproject.toml++# Stubs for editable metadata generation — bundles/ and models/ are referenced+# by force-include in pyproject.toml and must exist; real contents are copied+# in the base stage.+RUN mkdir -p /tmp/sie_sdk/src/sie_sdk src/sie_server bundles models \+ && touch /tmp/sie_sdk/src/sie_sdk/__init__.py \+ && touch src/sie_server/__init__.py++RUN --mount=type=cache,target=/root/.cache/pip \+ python3.12 -m venv .venv \+ && .venv/bin/pip install --upgrade pip \+ && .venv/bin/pip install \+ -e "/tmp/sie_sdk[storage]" \+ -e ".[gpu-metrics]"++# =============================================================================+# Shared CUDA base: source install and venv finalization+# =============================================================================+FROM deps AS base++# Source-layer cache key — forces source layers (and the editable reinstall) to+# rebuild per commit while the expensive dependency install in ``deps`` stays+# cached. CI passes ``--build-arg SIE_SRC_REV=$(git rev-parse --short HEAD)``.+ARG SIE_SRC_REV=dev+RUN echo "sie source revision: ${SIE_SRC_REV}"++COPY packages/sie_sdk/src /tmp/sie_sdk/src+COPY packages/sie_server/src src/+COPY packages/sie_server/bundles bundles/+COPY packages/sie_server/models models/++# Editable reinstall over the stub stage so runtime path-based lookups+# (e.g. sie_server.cli resolve-deps reading ./bundles) keep working.+RUN --mount=type=cache,target=/root/.cache/pip \+ .venv/bin/pip install --no-deps \+ -e /tmp/sie_sdk \+ -e .++# Sanity-check shared venv imports.+RUN .venv/bin/python -c "import torch; print(torch.__version__)"++# Register bundle-libs on sys.path via a .pth executed by site.py at startup.+# sys.path.insert(0, ...) puts bundle-libs at position 0 so bundle-specific+# versions SHADOW the shared venv (the gemma cu130 torch/transformers/sglang+# overlay). Content is identical for every bundle, so writing it here keeps the+# shared venv layer byte-identical.+RUN echo "import sys; sys.path.insert(0, '/app/bundle-libs')" \+ > /app/.venv/lib/python3.12/site-packages/_sie_bundle.pth++# Conservative venv cleanup — only runtime-safe removals. Keep torch/include+# (triton JIT compiles against torch C++ headers for sglang/flashinfer custom+# ops) and gcc/libc6-dev at runtime.+RUN set -eux; \+ cd /app/.venv/lib/python3.12/site-packages; \+ find . -type d -name '__pycache__' -prune -exec rm -rf {} +; \+ find . -type f \( -name '*.pyc' -o -name '*.pyo' \) -delete; \+ find . -type d -name 'tests' -prune -exec rm -rf {} +; \+ rm -rf torch/test torch/utils/tensorboard torch/utils/bottleneck 2>/dev/null || true; \+ find torch -type f -name '*.a' -delete 2>/dev/null || true; \+ find . -type f -name 'RECORD' -path '*dist-info*' -delete; \+ find nvidia -type f -name '*.a' -delete 2>/dev/null || true; \+ rm -rf /app/.venv/share/jupyter 2>/dev/null || true; \+ find /app/.venv -exec touch -h -d @0 {} + 2>/dev/null || true++# =============================================================================+# Bundle dependency builder: cu130 bundle-specific deps+# =============================================================================+FROM base AS builder++ARG BUNDLE++RUN .venv/bin/python -m sie_server.cli resolve-deps \+ --bundle "${BUNDLE}" \+ --models-dir models \+ > /tmp/bundle-requirements.txt \+ && echo "Bundle ${BUNDLE} requirements:" \+ && cat /tmp/bundle-requirements.txt++# cu130 bundle deps go into a separate site-packages tree (``bundle-libs``,+# prepended to sys.path via the .pth above). The gemma bundle needs torch 2.11+# from the cu130 PyTorch index, where the only ``2.11.0`` is the ``+cu130``+# local-version wheel; pip's multi-index resolution does not reliably prefer it+# over PyPI's default-CUDA build, so cuda13 bundles resolve with ``uv`` and+# ``--index-strategy unsafe-best-match`` against the cu130 PyTorch + sglang+# indexes (so torch 2.11 + sgl-kernel/flashinfer land for cu130). This uv ++# cu130-index resolution was validated by a manual Modal GPU session (sglang+# 0.5.13 / torch 2.11 / cu130 in a fresh venv).+#+# COVERAGE NOTE: the cuda13 image CI smoke (.github/workflows/gemma-image.yml)+# builds this image and asserts on CPU that the bundle-libs cu130 overlay+# SHADOWS the base venv (import torch -> 2.11+cu130, transformers 5.x). It does+# NOT exercise GPU init: the cu12 base venv + cu130 bundle-libs both expose the+# ``nvidia/`` namespace package, and a cu130-missing submodule could in theory+# fall through to a cu12 ``.so`` at first decode. That dual-torch GPU path is+# covered only by live GPU runs (Modal; first release health-check) — slimming+# torch out of sie-server core to remove the carry is the tracked fix (#1415).+# UV_NO_CACHE=0 makes the --mount uv cache effective; UV_COMPILE_BYTECODE=0 for+# --no-compile parity. UV_HTTP_TIMEOUT=600 raises uv's per-request timeout from+# the 30s default: the cu130 closure pulls several very large NVIDIA wheels from+# pypi.nvidia.com (cufft ~204 MB, cusolver ~191 MB, nccl/cusparselt/nvshmem+# 130-190 MB), and downloading them concurrently over a congested link exceeds+# 30s, which previously failed the build with "nvidia-nvshmem-cu13 ... operation+# timed out" after retries.+RUN --mount=type=cache,target=/root/.cache/pip \+ --mount=type=cache,target=/root/.cache/uv \+ mkdir -p /app/bundle-libs; \+ if [ -s /tmp/bundle-requirements.txt ]; then \+ UV_NO_CACHE=0 UV_COMPILE_BYTECODE=0 UV_HTTP_TIMEOUT=600 uv pip install \+ --python /app/.venv/bin/python \+ --target=/app/bundle-libs \+ --index-strategy unsafe-best-match \+ --prerelease=allow \+ --extra-index-url https://download.pytorch.org/whl/cu130 \+ --extra-index-url https://docs.sglang.ai/whl/cu130/ \+ -r /tmp/bundle-requirements.txt ; \+ fi++# bundle-libs cleanup (symmetric to the .venv cleanup in base).+RUN set -eux; \+ if [ -d /app/bundle-libs ]; then \+ cd /app/bundle-libs; \+ find . -type d -name '__pycache__' -prune -exec rm -rf {} +; \+ find . -type f \( -name '*.pyc' -o -name '*.pyo' \) -delete; \+ find . -type d -name 'tests' -prune -exec rm -rf {} +; \+ rm -rf torch/test torch/utils/tensorboard torch/utils/bottleneck 2>/dev/null || true; \+ find torch -type f -name '*.a' -delete 2>/dev/null || true; \+ find . -type f -name 'RECORD' -path '*dist-info*' -delete; \+ find nvidia -type f -name '*.a' -delete 2>/dev/null || true; \+ fi; \+ find /app/bundle-libs -exec touch -h -d @0 {} + 2>/dev/null || true++# =============================================================================+# Runtime image (CUDA 13 devel — nvcc for flashinfer/tvm_ffi first-decode JIT)+# =============================================================================+FROM nvidia/cuda:13.0.0-cudnn-devel-ubuntu22.04 AS runtime+ENV CUDA_HOME=/usr/local/cuda \+ LD_LIBRARY_PATH="/usr/local/cuda/lib64:$LD_LIBRARY_PATH"++ENV DEBIAN_FRONTEND=noninteractive++# gcc + libc6-dev: triton JIT compiles CUDA kernels at first use.+# libnuma1: required by sgl_kernel; import fails with a misleading SM-arch error+# without it.+# libgomp1: torch OpenMP runtime.+# libspatialindex-c6 / libgl1 / libglib2.0-0 / libice6 / libsm6 / libx11-6 /+# libxcb1 / libxext6: docling/opencv dlopen chain (kept symmetric with the+# cuda12 runtime so the same model bundle deps import cleanly).+# ninja-build: flashinfer invokes ninja during first-use SGLang kernel JIT.+RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \+ --mount=type=cache,target=/var/lib/apt/lists,sharing=locked \+ apt-get update && apt-get install -y --no-install-recommends \+ ca-certificates \+ gcc \+ libc6-dev \+ libgl1 \+ libglib2.0-0 \+ libgomp1 \+ libice6 \+ libnuma1 \+ libsm6 \+ libspatialindex-c6 \+ ninja-build \+ libx11-6 \+ libxcb1 \+ libxext6++RUN groupadd -g 1000 sie && useradd -u 1000 -g sie -m sie++WORKDIR /app++# Standalone Python 3.12 tree + symlinks. Pulled from `base` since /opt/python+# is established in the deps stage and never touched later.+COPY --link --from=base /opt/python /opt/python+RUN set -e; \+ py=$(ls -d /opt/python/cpython-3.12*/bin/python3.12 | head -1); \+ [ -x "$py" ] || { echo "no standalone python found under /opt/python"; exit 1; }; \+ ln -sf "$py" /usr/local/bin/python3.12; \+ ln -sf /usr/local/bin/python3.12 /usr/local/bin/python3; \+ ln -sf /usr/local/bin/python3.12 /usr/local/bin/python++# Shared content — identical across bundles of this platform. Ordered BEFORE the+# per-bundle COPY so bundle-libs is the only invalidating layer.+COPY --link --from=base --chown=1000:1000 /app/.venv /app/.venv+# Source trees copied WITHOUT --link (buildx --link cached on a digest that did+# not reliably invalidate on source change — see Dockerfile.cuda12).+COPY --from=base --chown=1000:1000 /app/src /app/src+COPY --from=base --chown=1000:1000 /tmp/sie_sdk/src /tmp/sie_sdk/src+COPY --link --from=base --chown=1000:1000 /app/models /app/models+COPY --link --from=base --chown=1000:1000 /app/bundles /app/bundles+# Bundle-specific extras — last layer so shared layers above stay cached.+COPY --link --from=builder --chown=1000:1000 /app/bundle-libs /app/bundle-libs++RUN mkdir -p /app/evals /app/.cache/huggingface && chown -R sie:sie /app/evals /app/.cache++# Declare BUNDLE only here (LABEL + ENV) so layers above are bundle-agnostic.+ARG BUNDLE++LABEL org.opencontainers.image.title="SIE Server" \+ org.opencontainers.image.description="Search Inference Engine - ${BUNDLE} bundle (CUDA 13)" \+ sie.bundle="${BUNDLE}"++ENV PATH="/app/.venv/bin:$PATH" \+ PYTHONUNBUFFERED=1 \+ PYTHONDONTWRITEBYTECODE=1 \+ HF_HOME=/app/.cache/huggingface \+ NVIDIA_VISIBLE_DEVICES=all \+ NVIDIA_DRIVER_CAPABILITIES=compute,utility \+ SIE_BUNDLE="${BUNDLE}"++USER sie+EXPOSE 8080++HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \+ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/healthz')" || exit 1++ENTRYPOINT ["python", "-m", "sie_server.cli"]+CMD ["serve", "--host", "0.0.0.0", "--port", "8080", "--models-dir", "/app/models"]diff --git a/packages/sie_server/bundles/gemma.yaml b/packages/sie_server/bundles/gemma.yamlnew file mode 100644index 000000000..a2be23bc5--- /dev/null+++ b/packages/sie_server/bundles/gemma.yaml@@ -0,0 +1,59 @@+name: gemma+priority: 20+default: false+# GPU platform this bundle targets — selects packages/sie_server/Dockerfile.cuda13+# and tags images ``cuda13-gemma`` (not ``cuda12-*``). Gemma 4 needs sglang+# 0.5.13 / torch 2.11 cu130 on a CUDA 13 devel runtime (see below). Read by the+# docker build task (tools/mise_tasks/docker_task.py) and mirrored by the release+# matrix (.github/release-matrix.json). Bundles without this field default to+# ``cuda12``.+platform: cuda13+# Dedicated worker image for Google Gemma 4 (see issue #1415).+#+# VALIDATED on a Modal L4 (driver 580.95.05 / CUDA 13.0) on 2026-06-18:+# google/gemma-4-E2B-it serves end-to-end on sglang 0.5.13 — the gemma4+# reasoning/tool parsers load, Gemma4ForConditionalGeneration loads weights,+# and /v1/chat/completions returns 200 (with --disable-cuda-graph, which the+# model configs set via adapter_options.loadtime.disable_cuda_graph).+#+# Kept SEPARATE from the `sglang` bundle so the Qwen3.x stack there stays on+# its sglang 0.5.10.post1 / torch 2.9.1 toolchain, untouched.+#+# VERSION NOTE: Gemma 4 first shipped in sglang 0.5.11, but 0.5.11's bundled+# JIT kernel (jit_kernel/csrc/elementwise/activation.cuh) fails to compile+# under strict nvcc — "select_kernel ... expected a type, got+# ActivationKind::kSiLU" — confirmed broken on BOTH CUDA 12.9 and 13.0. 0.5.13+# fixes it. Both 0.5.11 and 0.5.13 require torch 2.11 (the torch 2.9->2.11 bump+# landed at 0.5.11, not 0.5.12), so there is no torch-2.9 path to Gemma 4 —+# this bundle's image carries torch 2.11 (cu130) on a CUDA 13 base — built by+# the dedicated ``cuda13`` platform (packages/sie_server/Dockerfile.cuda13),+# selected via the ``platform: cuda13`` field above. The shared base venv still+# ships torch 2.9.1, so the gemma image carries two torches (~+3 GB); slimming+# torch out of sie-server core would remove that (tracked follow-up in #1415).+#+# The distinct adapter module (a thin SGLangGenerationAdapter subclass) scopes+# routing here: bundle compatibility keys on the adapter module path, so Gemma+# models reference `...sglang.gemma` and only this bundle declares it — Qwen3.x+# keep routing to `sglang`.+adapters:+- sie_server.adapters.sglang.gemma+deps:+ # sglang 0.5.13 = the validated Gemma 4 engine (0.5.11 has the activation.cuh+ # JIT bug above). Verified transitive resolution on the Modal L4 cu130 image:+ # torch==2.11.0 (cu130), transformers==5.8.1, kernels==0.14.1,+ # sglang-kernel + flashinfer-python (0.5.13 builds).+ # These resolve from the cu130 wheel indexes at build/serve time+ # (download.pytorch.org/whl/cu130 + https://docs.sglang.ai/whl/cu130/),+ # supplied by the build (Dockerfile.cuda13 / Modal image). torch,+ # transformers, and kernels are intentionally NOT re-pinned here — sglang+ # 0.5.13's own exact pins drive them. (Pinning kernels<0.13 makes the resolve+ # unsatisfiable: 0.5.13 requires kernels>=0.14.1,<0.15. sglang declares a+ # bare unpinned `kernels`, so without 0.5.13's transitive pin uv would grab+ # the latest, which breaks sglang's import — let sglang constrain it.)+ sglang: '==0.5.13'+ # Structured-output backend the Gemma model configs select+ # (tasks.generate ... grammar_backend: xgrammar). Pinned to the version+ # sglang 0.5.13 resolves, to prevent silent drift (mirrors the sglang+ # bundle's rationale). NOTE: 0.5.13 uses xgrammar 0.2.x, not the 0.1.32 the+ # sglang bundle pins for the older engine.+ xgrammar: '==0.2.1'diff --git a/packages/sie_server/models/google__gemma-4-26B-A4B-it.yaml b/packages/sie_server/models/google__gemma-4-26B-A4B-it.yamlnew file mode 100644index 000000000..51f306825--- /dev/null+++ b/packages/sie_server/models/google__gemma-4-26B-A4B-it.yaml@@ -0,0 +1,132 @@+sie_id: google/gemma-4-26B-A4B-it+hf_id: google/gemma-4-26B-A4B-it+# ── Engine (see issue #1415) ──+#+# Served by the dedicated ``gemma`` bundle (packages/sie_server/bundles/+# gemma.yaml): sglang 0.5.13 + torch 2.11 (cu130) on a CUDA 13 base. 0.5.13 is+# the validated engine; 0.5.11 (first release with Gemma 4) has a JIT-kernel+# compile bug. Smoke-validated on a Modal H100-80GB 2026-06-19: the ``default``+# profile shape (BF16, mem_fraction 0.90, --disable-cuda-graph) loads the MoE+# and /v1/chat/completions generates correctly. ``kv_budget_tokens`` /+# ``mem_fraction_static`` / ``context_length`` remain conservative placeholders+# pending KV calibration. FP8 was dropped: BF16 (~52 GB) already fits the serving+# cards, and online FP8 quant of this MoE is lossy + runs unoptimized kernels (it+# does serve on H200, just slower) — so it isn't worth it here.+#+# gemma-4-26B-A4B-it is a Mixture-of-Experts model (26B total / ~4B active).+# BF16 weights (~52 GB) do not fit L4 (24 GB) or A100-40GB; the ``default``+# profile targets H100-80GB (BF16), and the ``mtp`` variant (BF16 + NEXTN draft+# + cuda graph) needs a 96 GB+ card (RTX PRO 6000 / H200).+inputs:+ # Vision-language; text+image via OpenAI ``image_url`` content parts.+ # Video is not wired through the SIE gateway.+ text: true+ image: true+ audio: false+ video: false+tasks:+ generate:+ # Conservative contract pending calibration on a Gemma-4-capable engine.+ context_length: 8192+ max_output_tokens: 4096+ # Grammar (response_format / json_schema / regex) is served by the+ # non-speculative ``no-spec`` profile — validated with xgrammar. NEXTN/MTP+ # bypasses SGLang's grammar FSM (leaks/truncates), so grammar must never run+ # on ``:mtp``. ``grammar_profile`` makes the gateway reroute every grammar+ # request — INCLUDING an explicit ``…:mtp`` pin — to the named variant (it+ # strips the pinned suffix and rewrites to the base's grammar_profile). The+ # validator forbids naming ``default``, so the route is a thin non-spec+ # ``no-spec`` profile (mirrors Qwen3.5-4B).+ grammar_profile: no-spec+ capabilities:+ # xgrammar supports json_schema/regex/ebnf; advertise the universally+ # safe subset until a GPU smoke validates ebnf for this model.+ grammar: ["json_schema", "regex"]+ streaming: true+ tools: true+ # Gemma 4 thinking is off by default; set explicitly so the OpenAI-compat+ # path returns the answer only. Operators wanting CoT flip this+ # profile-side or pass chat_template_kwargs.enable_thinking=true per request.+ chat_template_kwargs:+ enable_thinking: false+max_sequence_length: 8192+profiles:+ # H100-80GB BF16. ~52 GB weights leave room for KV at the conservative 8K+ # window; recalibrate ``mem_fraction_static`` / ``kv_budget_tokens`` via a+ # GPU smoke once SGLang supports Gemma 4.+ default:+ max_batch_tokens: 16384+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.gemma:SGLangGemmaAdapter+ kv_budget_tokens: 8192+ adapter_options:+ loadtime:+ mem_fraction_static: 0.90+ served_model_name: google/gemma-4-26B-A4B-it+ disable_cuda_graph: true+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4+ # Speculative OFF (Gemma 4 MTP needs a separate ``-it-assistant`` draft+ # model). No ``--mamba-scheduler-strategy`` — Gemma 4 is not the Qwen3.x+ # Gated-DeltaNet family.+ runtime:+ first_chunk_timeout_s: 90+ inter_chunk_timeout_s: 15+ overall_timeout_s: 600+ # Gemma-family recommended sampling defaults; a request-supplied value+ # still wins (the adapter merges this dict via setdefault).+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 64+ # Conservative floor against an empty-first-token EOS completion.+ min_new_tokens: 1+ stop_tokens:+ - "<end_of_turn>"+ # ``no-spec`` — the grammar-safe route (see tasks.generate.grammar_profile).+ # Identical to ``default`` (non-speculative, H100-80GB BF16); named distinctly+ # so ``grammar_profile`` can point here (the validator forbids naming+ # ``default``).+ no-spec:+ extends: default+ # ``mtp`` variant — Gemma 4 MTP for the 26B MoE: NEXTN with the paired draft+ # ``google/gemma-4-26B-A4B-it-assistant``, BF16 (FP8 dropped — see header).+ # BF16 weights + the draft + the MTP cuda graph need more headroom than the+ # 80 GB ``default``, so target a 96 GB+ card (RTX PRO 6000 / H200). VALIDATED+ # on a Modal H200 2026-06-19: serves as FROZEN_KV_MTP (num_steps 5, eagle_topk+ # 1, num_draft_tokens 6) with the paired draft loaded and its cuda graph+ # captured ("Capture Frozen-KV MTP draft cuda graph end"), BF16+ # (quantization=None, disable_cuda_graph=False); /v1/chat/completions returns+ # correct output, max_total_num_tokens=444103. (MTP cuda-graph capture JIT-+ # compiles a fused_rope kernel needing the full CUDA devel toolkit — nvcc, CCCL+ # headers, lib dev symlinks — all present in this bundle's+ # ``cuda:13.0.0-...-devel`` base, so no extra wiring is needed in the image.)+ # ``speculative_needs_extra_buffer: false`` opts out of the Qwen Gated-DeltaNet+ # mamba-scheduler guard (Gemma 4 is hybrid attention).+ mtp:+ extends: default+ max_batch_tokens: 32768+ kv_budget_tokens: 16384+ adapter_options:+ # loadtime FULL-REPLACED on extend (restated in full); runtime inherited.+ loadtime:+ mem_fraction_static: 0.90+ served_model_name: google/gemma-4-26B-A4B-it+ # MTP REQUIRES cuda graph ON: the eager path (--disable-cuda-graph)+ # crashes in sglang's speculative buffer view (validated on E4B, Modal+ # H100 2026-06-19).+ disable_cuda_graph: false+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4+ speculative_needs_extra_buffer: false+ speculative:+ enabled: true+ algorithm: nextn+ num_steps: 5+ eagle_topk: 1+ num_draft_tokens: 6+ draft_model: google/gemma-4-26B-A4B-it-assistantdiff --git a/packages/sie_server/models/google__gemma-4-E2B-it.yaml b/packages/sie_server/models/google__gemma-4-E2B-it.yamlnew file mode 100644index 000000000..1f9d4c829--- /dev/null+++ b/packages/sie_server/models/google__gemma-4-E2B-it.yaml@@ -0,0 +1,118 @@+sie_id: google/gemma-4-E2B-it+hf_id: google/gemma-4-E2B-it+# ── Engine (see issue #1415) ──+#+# Served by the dedicated ``gemma`` bundle (packages/sie_server/bundles/+# gemma.yaml): sglang 0.5.13 + torch 2.11 (cu130) on a CUDA 13 base. 0.5.13 is+# the validated engine; 0.5.11 (first release with Gemma 4) has a JIT-kernel+# compile bug. E2B was smoke-validated on a Modal L4 2026-06-18 (serves ++# /v1/chat/completions 200). ``kv_budget_tokens`` / ``mem_fraction_static`` /+# ``context_length`` remain conservative placeholders pending per-variant KV+# calibration.+inputs:+ # Gemma 4 is a vision-language model; the wire surface accepts text+image+ # via the OpenAI chat-completions ``image_url`` content parts. The E-models+ # additionally accept 16 kHz mono audio per the cookbook, but audio/video are+ # not wired through the SIE gateway yet (same stance as the Qwen3.x configs).+ text: true+ image: true+ audio: false+ video: false+tasks:+ generate:+ # Conservative contract pending calibration on a Gemma-4-capable engine.+ context_length: 8192+ max_output_tokens: 4096+ # Grammar (response_format / json_schema / regex) is served by the+ # non-speculative ``no-spec`` profile — validated with xgrammar. NEXTN/MTP+ # bypasses SGLang's grammar FSM (leaks/truncates), so grammar must never run+ # on ``:mtp``. ``grammar_profile`` makes the gateway reroute every grammar+ # request — INCLUDING an explicit ``…:mtp`` pin — to the named variant (it+ # strips the pinned suffix and rewrites to the base's grammar_profile). The+ # validator forbids naming ``default``, so the route is a thin non-spec+ # ``no-spec`` profile (mirrors Qwen3.5-4B).+ grammar_profile: no-spec+ capabilities:+ # xgrammar supports json_schema/regex/ebnf; advertise the universally+ # safe subset until a GPU smoke validates ebnf for this model.+ grammar: ["json_schema", "regex"]+ streaming: true+ tools: true+ # Gemma 4 thinking is off by default; set explicitly so the OpenAI-compat+ # path returns the answer only. Operators wanting CoT flip this+ # profile-side or pass chat_template_kwargs.enable_thinking=true per request.+ chat_template_kwargs:+ enable_thinking: false+max_sequence_length: 8192+profiles:+ # Single ``default`` profile — E2B (~2B) fits comfortably on L4/A100/H100.+ default:+ max_batch_tokens: 8192+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.gemma:SGLangGemmaAdapter+ # Placeholder — recalibrate via a GPU smoke once SGLang supports Gemma 4.+ kv_budget_tokens: 8192+ adapter_options:+ loadtime:+ mem_fraction_static: 0.85+ served_model_name: google/gemma-4-E2B-it+ disable_cuda_graph: true+ # triton attention matches the cookbook recommendation for Gemma 4's+ # bidirectional image attention.+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4+ # Speculative OFF here; the ``mtp`` variant below enables Gemma 4 MTP+ # (NEXTN + the ``-it-assistant`` draft). No ``--mamba-scheduler-strategy``+ # — that is the Qwen3.x Gated-DeltaNet recipe, not Gemma 4.+ runtime:+ first_chunk_timeout_s: 60+ inter_chunk_timeout_s: 10+ overall_timeout_s: 300+ # Gemma-family recommended sampling defaults; a request-supplied value+ # still wins (the adapter merges this dict via setdefault).+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 64+ # Conservative floor against an empty-first-token EOS completion.+ min_new_tokens: 1+ stop_tokens:+ - "<end_of_turn>"+ # ``no-spec`` — the grammar-safe route (see tasks.generate.grammar_profile).+ # Identical to ``default`` (non-speculative); named distinctly so+ # ``grammar_profile`` can point here (the validator forbids naming ``default``).+ no-spec:+ extends: default+ # ``mtp`` variant — Gemma 4 multi-token prediction (speculative decoding):+ # NEXTN with the paired external draft ``google/gemma-4-E2B-it-assistant``+ # (sglang 0.5.12+ Gemma 4 MTP; cookbook recipe num_steps=5 / num_draft_tokens=6+ # / eagle_topk=1). Same engine path as the E4B ``mtp`` variant validated on a+ # Modal H100 2026-06-19. ``speculative_needs_extra_buffer: false`` opts out of+ # the Qwen Gated-DeltaNet mamba-scheduler guard (Gemma 4 is hybrid attention).+ mtp:+ extends: default+ kv_budget_tokens: 6144+ adapter_options:+ # loadtime is FULL-REPLACED when extending, so restated in full; runtime+ # is identical to default and inherited (omitted here).+ loadtime:+ mem_fraction_static: 0.80+ served_model_name: google/gemma-4-E2B-it+ # MTP REQUIRES cuda graph ON: the eager path (--disable-cuda-graph)+ # crashes in sglang's speculative buffer view. Same engine path as the+ # E4B mtp variant validated cuda-graph-on (Modal H100 2026-06-19).+ disable_cuda_graph: false+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4+ speculative_needs_extra_buffer: false+ speculative:+ enabled: true+ algorithm: nextn+ num_steps: 5+ eagle_topk: 1+ num_draft_tokens: 6+ draft_model: google/gemma-4-E2B-it-assistantdiff --git a/packages/sie_server/models/google__gemma-4-E4B-it.yaml b/packages/sie_server/models/google__gemma-4-E4B-it.yamlnew file mode 100644index 000000000..b3bf0b555--- /dev/null+++ b/packages/sie_server/models/google__gemma-4-E4B-it.yaml@@ -0,0 +1,124 @@+sie_id: google/gemma-4-E4B-it+hf_id: google/gemma-4-E4B-it+# ── Engine (see issue #1415) ──+#+# Served by the dedicated ``gemma`` bundle (packages/sie_server/bundles/+# gemma.yaml): sglang 0.5.13 + torch 2.11 (cu130) on a CUDA 13 base. 0.5.13 is+# the validated engine; 0.5.11 (first release with Gemma 4) has a JIT-kernel+# compile bug. Smoke-validated on a Modal H100 2026-06-19 (serves ++# /v1/chat/completions generates correctly; E2B was likewise validated on an+# L4). ``kv_budget_tokens`` / ``mem_fraction_static`` / ``context_length``+# remain conservative placeholders pending per-variant KV calibration.+inputs:+ # Gemma 4 is a vision-language model; the wire surface accepts text+image+ # via the OpenAI chat-completions ``image_url`` content parts. The E-models+ # additionally accept 16 kHz mono audio per the cookbook, but audio/video are+ # not wired through the SIE gateway yet (same stance as the Qwen3.x configs).+ text: true+ image: true+ audio: false+ video: false+tasks:+ generate:+ # Conservative contract pending calibration on a Gemma-4-capable engine.+ context_length: 8192+ max_output_tokens: 4096+ # Grammar (response_format / json_schema / regex) is served by the+ # non-speculative ``no-spec`` profile — validated with xgrammar. NEXTN/MTP+ # bypasses SGLang's grammar FSM (leaks/truncates), so grammar must never run+ # on ``:mtp``. ``grammar_profile`` makes the gateway reroute every grammar+ # request — INCLUDING an explicit ``…:mtp`` pin — to the named variant (it+ # strips the pinned suffix and rewrites to the base's grammar_profile). The+ # validator forbids naming ``default``, so the route is a thin non-spec+ # ``no-spec`` profile (mirrors Qwen3.5-4B).+ grammar_profile: no-spec+ capabilities:+ # xgrammar supports json_schema/regex/ebnf; advertise the universally+ # safe subset until a GPU smoke validates ebnf for this model.+ grammar: ["json_schema", "regex"]+ streaming: true+ tools: true+ # Gemma 4 thinking is off by default; set explicitly so the OpenAI-compat+ # path returns the answer only. Operators wanting CoT flip this+ # profile-side or pass chat_template_kwargs.enable_thinking=true per request.+ chat_template_kwargs:+ enable_thinking: false+max_sequence_length: 8192+profiles:+ # Single ``default`` profile — E4B (~4B) fits comfortably on L4/A100/H100.+ default:+ max_batch_tokens: 8192+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.gemma:SGLangGemmaAdapter+ # Placeholder — recalibrate via a GPU smoke once SGLang supports Gemma 4.+ kv_budget_tokens: 8192+ adapter_options:+ loadtime:+ mem_fraction_static: 0.85+ served_model_name: google/gemma-4-E4B-it+ disable_cuda_graph: true+ # triton attention matches the cookbook recommendation for Gemma 4's+ # bidirectional image attention.+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4+ # Speculative OFF here; the ``mtp`` variant below enables Gemma 4 MTP+ # (NEXTN + the ``-it-assistant`` draft). No ``--mamba-scheduler-strategy``+ # — that is the Qwen3.x Gated-DeltaNet recipe, not Gemma 4.+ runtime:+ first_chunk_timeout_s: 60+ inter_chunk_timeout_s: 10+ overall_timeout_s: 300+ # Gemma-family recommended sampling defaults; a request-supplied value+ # still wins (the adapter merges this dict via setdefault).+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 64+ # Conservative floor against an empty-first-token EOS completion.+ min_new_tokens: 1+ stop_tokens:+ - "<end_of_turn>"+ # ``no-spec`` — the grammar-safe route (see tasks.generate.grammar_profile).+ # Identical to ``default`` (non-speculative); named distinctly so+ # ``grammar_profile`` can point here (the validator forbids naming ``default``).+ no-spec:+ extends: default+ # ``mtp`` variant — Gemma 4 multi-token prediction (speculative decoding):+ # NEXTN with the paired external draft ``google/gemma-4-E4B-it-assistant``+ # (sglang 0.5.12+ Gemma 4 MTP; cookbook recipe num_steps=5 / num_draft_tokens=6+ # / eagle_topk=1). Validated on a Modal H100 2026-06-19 (serves + generates).+ # ``speculative_needs_extra_buffer: false`` opts out of the Qwen Gated-DeltaNet+ # mamba-scheduler guard — Gemma 4 is standard hybrid attention, not DeltaNet.+ # Route latency-sensitive traffic here via the ``:mtp`` variant suffix.+ mtp:+ extends: default+ # Lower than ``default`` — the draft model shares GPU memory. Recalibrate.+ kv_budget_tokens: 6144+ adapter_options:+ # loadtime is FULL-REPLACED (not merged) when extending, so it is restated+ # in full; runtime is identical to default and inherited (omitted here).+ loadtime:+ mem_fraction_static: 0.80+ served_model_name: google/gemma-4-E4B-it+ # MTP REQUIRES cuda graph ON: the eager path (--disable-cuda-graph)+ # crashes in sglang's speculative buffer view ("output with shape [1]+ # doesn't match broadcast shape [N]"). Validated cuda-graph-on on a+ # Modal H100 2026-06-19 (draft graph captures: "Frozen-KV MTP draft+ # cuda graph"). 0.5.13 fixed the activation.cuh bug that forced+ # --disable-cuda-graph on 0.5.11, so capture works here.+ disable_cuda_graph: false+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4+ # Opt out of the DeltaNet mamba-scheduler guard (see adapter).+ speculative_needs_extra_buffer: false+ speculative:+ enabled: true+ algorithm: nextn+ num_steps: 5+ eagle_topk: 1+ num_draft_tokens: 6+ draft_model: google/gemma-4-E4B-it-assistantdiff --git a/packages/sie_server/models/microsoft__Florence-2-base.yaml b/packages/sie_server/models/microsoft__Florence-2-base.yamlindex 682502220..fa6bbf067 100644--- a/packages/sie_server/models/microsoft__Florence-2-base.yaml+++ b/packages/sie_server/models/microsoft__Florence-2-base.yaml@@ -18,6 +18,11 @@ profiles:loadtime:trust_remote_code: trueruntime:- task: <OCR_WITH_REGION>+ # Default task is object detection: Florence-2-base is measured on COCO+ # detection (its model-card metric, like Florence-2-base-ft / large; #1437).+ # The same model is also the sie_tools image OCR fallback — that call+ # passes options={"task": "<OCR>"} explicitly, so one model serves both OD+ # and OCR. This default only sets the no-task-specified behaviour.+ task: <OD>max_new_tokens: 1024num_beams: 1diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 0dd256374..b48e8e231 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.10"+ "version": "0.6.11"},"paths": {"/": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex 4e95f7541..936867460 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.10"+version = "0.6.11"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }@@ -16,6 +16,10 @@ dependencies = [# ML / Inference# torch 2.9.x required - flash-attn prebuilt wheels are version-specific"torch>=2.9,<2.10",+ # Bundle-controlled: each bundle overlays its exact transformers into+ # bundle-libs (bundles/default.yaml >=4.57,<5; transformers5.yaml / gemma via+ # sglang >=5). The base range is bounded <6 so the >=5 overlays resolve while+ # the base venv can't silently jump to a transformers 6 major."transformers>=4.57,<6","tokenizers>=0.20,<1","sentence-transformers>=5.0,<6",diff --git a/packages/sie_server/src/sie_server/_ipc_test_harness.py b/packages/sie_server/src/sie_server/_ipc_test_harness.pyindex 166f4ea68..6042a1669 100644--- a/packages/sie_server/src/sie_server/_ipc_test_harness.py+++ b/packages/sie_server/src/sie_server/_ipc_test_harness.py@@ -122,6 +122,9 @@ class _StubExecutor:def get_model_descriptor(self, model_id: str) -> ModelDescriptor | None: # noqa: ARG002return self._descriptor+ def loaded_model_names(self) -> list[str]:+ return []+async def _maybe_sleep(self) -> None:if self._per_request_delay_ms > 0:await asyncio.sleep(self._per_request_delay_ms / 1000.0)diff --git a/packages/sie_server/src/sie_server/adapters/sglang/gemma.py b/packages/sie_server/src/sie_server/adapters/sglang/gemma.pynew file mode 100644index 000000000..237fc1968--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/sglang/gemma.py@@ -0,0 +1,16 @@+from sie_server.adapters.sglang.generation import SGLangGenerationAdapter+++class SGLangGemmaAdapter(SGLangGenerationAdapter):+ """Bundle-routing seam for the Gemma worker image.++ Behaviour is identical to :class:`SGLangGenerationAdapter` — Gemma 4 is+ served through the same ``sglang serve`` subprocess with the ``gemma4``+ reasoning/tool parsers set via the model YAML. The only reason this+ subclass exists is routing: bundle compatibility keys on the adapter+ *module* path, and the ``sglang`` bundle declares only+ ``sie_server.adapters.sglang.generation``. Giving Gemma 4 a distinct+ module lets the ``gemma`` bundle (sglang 0.5.13 + transformers 5.8) own+ it without making every Qwen3.x model compatible with that bundle too —+ so the Qwen serving stack on the ``sglang`` bundle stays untouched.+ """diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 95951d653..c0250facc 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -93,6 +93,28 @@ def _resolve_read_timeout() -> float | None:_GENERATE_READ_TIMEOUT_S: float | None = _resolve_read_timeout()+def _mamba_scheduler_strategy_value(extra_launch_args: list[str]) -> str | None:+ """Return the value passed to ``--mamba-scheduler-strategy``, or ``None``.++ Parses both the two-token form (``["--mamba-scheduler-strategy",+ "extra_buffer"]``) and the ``--mamba-scheduler-strategy=value`` form; the+ last occurrence wins (argparse semantics). Returns ``None`` when the flag is+ absent. The speculative guard uses this to require the value be *exactly*+ ``extra_buffer`` — substring-matching the joined args would let a wrong value+ (e.g. ``--mamba-scheduler-strategy default``) slip past if the token+ ``extra_buffer`` happened to appear elsewhere in the args.+ """+ flag = "--mamba-scheduler-strategy"+ prefix = f"{flag}="+ value: str | None = None+ for i, arg in enumerate(extra_launch_args):+ if arg == flag:+ value = extra_launch_args[i + 1] if i + 1 < len(extra_launch_args) else None+ elif arg.startswith(prefix):+ value = arg[len(prefix) :]+ return value++# Format hints we re-embed into the SGLang ``image_data`` MIME type. Anything# else falls back to ``jpeg`` (the engine sniffs the real format from bytes)._ALLOWED_IMAGE_FORMATS = frozenset({"png", "jpeg", "jpg", "webp", "gif"})@@ -192,6 +214,14 @@ class SGLangGenerationAdapter(GenerationAdapter):# this, so it is inert for every other model.guard: dict[str, Any] | None = None,speculative: dict[str, Any] | None = None,+ # When ``speculative.enabled``, the adapter normally REQUIRES+ # ``--mamba-scheduler-strategy extra_buffer`` in ``extra_launch_args``+ # — the Qwen3.x Gated-DeltaNet NEXTN + radix-cache pairing. Models whose+ # speculative path doesn't need it (e.g. Gemma 4 MTP — a standard+ # hybrid-attention model using an external ``-it-assistant`` NEXTN draft)+ # set this ``False`` so the guard doesn't reject an otherwise-valid+ # launch. Default ``True`` keeps the Qwen3.x contract unchanged.+ speculative_needs_extra_buffer: bool = True,extra_launch_args: list[str] | None = None,extra_env: dict[str, str] | None = None,startup_timeout_s: float | None = None,@@ -250,6 +280,7 @@ class SGLangGenerationAdapter(GenerationAdapter):# Qwen3-4B-Instruct-2507 (no NEXTN heads — see the# speculative-decoding investigation result).self._speculative = speculative+ self._speculative_needs_extra_buffer = speculative_needs_extra_bufferself._extra_launch_args = list(extra_launch_args or [])self._extra_env = dict(extra_env or {})self._startup_timeout_s = _server.resolve_startup_timeout(startup_timeout_s)@@ -392,11 +423,21 @@ class SGLangGenerationAdapter(GenerationAdapter):# buffer" trace. Refuse to launch when the YAML omits the# flag so the misconfiguration surfaces as a startup error# instead of a runtime OOM that pages oncall.- if not any("mamba-scheduler-strategy" in str(arg) for arg in self._extra_launch_args):+ # Require the flag AND its exact ``extra_buffer`` value — a present+ # flag with a wrong value (e.g. ``--mamba-scheduler-strategy default``)+ # must not bypass the guard. Parse the flag's value precisely (both+ # the two-token and ``flag=value`` forms; last occurrence wins) rather+ # than substring-matching the joined args, which a stray+ # ``extra_buffer`` token elsewhere could satisfy.+ if (+ self._speculative_needs_extra_buffer+ and _mamba_scheduler_strategy_value(self._extra_launch_args) != "extra_buffer"+ ):raise RuntimeError("speculative decoding requires '--mamba-scheduler-strategy extra_buffer' "- "in extra_launch_args (see Qwen3.5-4B model YAML). Add the flag or "- "disable speculative.enabled in the model config."+ "in extra_launch_args (see Qwen3.5-4B model YAML). Add the flag, set "+ "speculative_needs_extra_buffer=false (non-DeltaNet models e.g. Gemma 4 "+ "MTP), or disable speculative.enabled in the model config.")logger.warning("Resolved SGLang generation command: %s",diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.pyindex 1e1d0c9d2..671ecf5bd 100644--- a/packages/sie_server/src/sie_server/app/app_factory.py+++ b/packages/sie_server/src/sie_server/app/app_factory.py@@ -159,6 +159,7 @@ class AppFactory:device=config.device,engine_config=engine_config,pool_name=config.pool_name,+ pinned_models=config.pinned_models,)try:# Start background services (memory monitor, idle evictor, hot reload).@@ -169,6 +170,8 @@ class AppFactory:# Preload models (shifts weight download from first-request to startup)await cls._preload_models(registry, config)+ # Eager-load pinned models (models already loaded by preload are skipped)+ await cls._load_pinned_models(registry, config)yield registryfinally:@@ -283,6 +286,56 @@ class AppFactory:logger.info("Preload complete: %d/%d models loaded", succeeded, len(config.preload_models))logger.info("lifespan.stage preload_models elapsed_s=%.3f", elapsed)+ @classmethod+ async def _load_pinned_models(cls, registry: ModelRegistry, config: AppStateConfig) -> None:+ """Eager-load pinned models at startup (non-fatal on failure).++ Models already loaded by ``_preload_models`` are skipped so a model+ in both lists is loaded exactly once. Runs inside _model_registry()+ which enters before _readiness_handling(), keeping the pod NotReady+ until pinned models are resident.+ """+ if not config.pinned_models:+ logger.info("lifespan.stage load_pinned_models elapsed_s=0.000")+ return++ t0 = time.perf_counter()+ logger.info("Loading %d pinned model(s): %s", len(config.pinned_models), ", ".join(config.pinned_models))++ succeeded = 0+ for raw in config.pinned_models:+ # Pinned ids may be profile-qualified (``sie_id:profile``) or+ # differently-cased; resolve to the config's bare sie_id so the+ # eager-load matches the same set the eviction guard protects.+ name = registry.resolve_model_id(raw)+ if name is None:+ logger.warning(+ "Pinned model '%s' has no matching config on this worker, skipping eager-load "+ "(it stays eviction-protected if it loads later). "+ "Check that the model name matches a config in the models directory.",+ raw,+ )+ continue+ if registry.is_loaded(name):+ logger.info("Pinned model '%s' already loaded (skipping duplicate load)", name)+ succeeded += 1+ continue+ try:+ await registry.load_async(name, config.device)+ succeeded += 1+ logger.info("Pinned model '%s' loaded", name)+ except Exception:+ logger.exception(+ "Failed to load pinned model '%s', skipping (it will lazy-load on "+ "request and stay eviction-protected once resident). "+ "Check that the model name matches a config in the models directory.",+ name,+ )++ elapsed = time.perf_counter() - t0+ logger.info("Pinned model load complete: %d/%d models loaded", succeeded, len(config.pinned_models))+ logger.info("lifespan.stage load_pinned_models elapsed_s=%.3f", elapsed)+@staticmethoddef _configure_cuda_defaults() -> None:"""Enable TF32 and cudnn autotuning for faster matmuls on Ampere+ GPUs.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 82d4efd87..42db30e99 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_PINNED_MODELS = "SIE_PINNED_MODELS"ENV_POOL = "SIE_POOL"@@ -32,6 +33,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."""+ pinned_models: list[str] | None = None+ """Optional list of model names to pin in memory (eager-loaded and never LRU-evicted). If None, no models are pinned."""+pool_name: str | None = None"""Optional worker pool identity used by ModelRegistry pool-isolation checks."""@@ -54,6 +58,11 @@ class AppStateConfig:elif ENV_PRELOAD_MODELS in os.environ:del os.environ[ENV_PRELOAD_MODELS]+ if self.pinned_models:+ os.environ[ENV_PINNED_MODELS] = ",".join(self.pinned_models)+ elif ENV_PINNED_MODELS in os.environ:+ del os.environ[ENV_PINNED_MODELS]+if self.pool_name:os.environ[ENV_POOL] = self.pool_nameelif ENV_POOL in os.environ:@@ -68,6 +77,8 @@ 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+ pinned_str = os.environ.get(ENV_PINNED_MODELS)+ pinned_models = [m.strip() for m in pinned_str.split(",") if m.strip()] if pinned_str else Nonepool_name = os.environ.get(ENV_POOL) or Nonereturn cls(@@ -75,5 +86,6 @@ class AppStateConfig:device=device,model_filter=model_filter,preload_models=preload_models,+ pinned_models=pinned_models,pool_name=pool_name,)diff --git a/packages/sie_server/src/sie_server/core/disk_cache.py b/packages/sie_server/src/sie_server/core/disk_cache.pyindex 6e45dd552..d91a3ee12 100644--- a/packages/sie_server/src/sie_server/core/disk_cache.py+++ b/packages/sie_server/src/sie_server/core/disk_cache.py@@ -16,6 +16,7 @@ from __future__ import annotationsimport loggingimport osimport shutil+from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -118,15 +119,23 @@ class ModelDiskCacheManager:manager.touch("BAAI/bge-m3")"""- def __init__(self, config: DiskCacheConfig) -> None:+ def __init__(+ self,+ config: DiskCacheConfig,+ pinned_provider: Callable[[], set[str]] | None = None,+ ) -> None:"""Initialize the disk cache manager.Args:config: Disk cache configuration.+ pinned_provider: Optional callback returning the HF repo ids whose+ weights must never be evicted from disk (the pinned set).+ Evaluated lazily at eviction time so it tracks config changes."""self._config = configself._cache_dir = config.cache_dirself._threshold = config.pressure_threshold+ self._pinned_provider = pinned_provider@propertydef cache_dir(self) -> Path:@@ -288,7 +297,11 @@ class ModelDiskCacheManager:List of evicted model IDs."""evicted: list[str] = []+ # Never evict the model being downloaded, nor any pinned model's weights:+ # re-downloading a pinned model on reload would reintroduce the cold start.exclude = {model_id}+ if self._pinned_provider is not None:+ exclude |= self._pinned_provider()while self.check_pressure():lru_model = self.get_lru_model(exclude=exclude)diff --git a/packages/sie_server/src/sie_server/core/memory.py b/packages/sie_server/src/sie_server/core/memory.pyindex cd963b84a..c44816fa5 100644--- a/packages/sie_server/src/sie_server/core/memory.py+++ b/packages/sie_server/src/sie_server/core/memory.py@@ -14,6 +14,7 @@ import loggingimport timefrom abc import ABC, abstractmethodfrom collections import OrderedDict+from collections.abc import Containerfrom dataclasses import dataclass, fieldlogger = logging.getLogger(__name__)@@ -195,9 +196,6 @@ class MemoryConfig:# Alternative to ratio-based thresholdmin_free_bytes: int | None = None- # Whether to enable proactive eviction- proactive_eviction: bool = True-# Background memory monitor check interval (seconds)memory_check_interval_s: float = 1.0@@ -353,33 +351,30 @@ class MemoryManager:return False- def get_lru_model(self) -> str | None:- """Get the least-recently-used model name.-- Returns:- Name of the LRU model, or None if no models are loaded.- """- if not self._models:- return None- # First item in OrderedDict is the least recently used- return next(iter(self._models))-- def get_eviction_candidates(self, count: int = 1) -> list[str]:- """Get a list of models to evict (in LRU order).+ def get_lru_model(self, *, exclude: Container[str] = frozenset()) -> str | None:+ """Get the least-recently-used model name that is not in ``exclude``.Args:- count: Number of candidates to return.+ exclude: Lowercased model names to skip (e.g. the pinned set).+ Matched case-insensitively against the loaded names.Returns:- List of model names to evict (oldest first).+ Name of the LRU non-excluded model, or None if all models are+ excluded or no models are loaded."""- return list(self._models.keys())[:count]+ # First item in OrderedDict is the least recently used. Loaded names+ # preserve case (HF ids), so lowercase before testing the set.+ for name in self._models:+ if name.lower() not in exclude:+ return name+ return Nonedef get_idle_models(self,*,idle_threshold_s: float,now: float | None = None,+ exclude: Container[str] = frozenset(),) -> list[str]:"""Return loaded models whose ``last_used_at`` is older than the threshold.@@ -394,9 +389,12 @@ class MemoryManager:tracked model (intended for tests, not production).now: Override the reference time (for tests). Defaults to``time.monotonic()``.+ exclude: Lowercased model names to skip (e.g. the pinned set).+ Matched case-insensitively against the loaded names.Returns:- Model names sorted oldest-first (longest-idle leads).+ Model names sorted oldest-first (longest-idle leads), excluding+ any name in ``exclude``."""if idle_threshold_s < 0:msg = f"idle_threshold_s must be >= 0, got {idle_threshold_s}"@@ -404,6 +402,9 @@ class MemoryManager:ref = time.monotonic() if now is None else nowidle: list[tuple[float, str]] = []for name, info in self._models.items():+ # Loaded names preserve case (HF ids); lowercase before the test.+ if name.lower() in exclude:+ continueage = ref - info.last_used_atif age >= idle_threshold_s:idle.append((info.last_used_at, name))@@ -437,35 +438,3 @@ class MemoryManager:return Truereturn False-- def get_eviction_candidates_if_needed(self) -> list[str]:- """Check memory pressure and return models that should be evicted.-- Synchronous version for callers that don't need async.-- Returns:- List of model names that should be evicted (caller must handle eviction).- """- if not self._config.proactive_eviction:- return []-- if not self.check_pressure() or not self._models:- return []-- lru = self.get_lru_model()- if lru is None:- return []-- logger.info("Memory pressure detected, recommending eviction of: %s", lru)- return [lru]-- async def check_memory_pressure(self) -> list[str]:- """Check memory pressure and return models that should be evicted.-- Async wrapper for use in async request handlers.- The underlying check is fast and non-blocking.-- Returns:- List of model names that should be evicted (caller must handle eviction).- """- return self.get_eviction_candidates_if_needed()diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex d125ecaaa..dda85ff95 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -55,6 +55,49 @@ _ERR_MODEL_NOT_LOADED = "Model '{name}' is not loaded"_ERR_MODEL_ALREADY_LOADED = "Model '{name}' is already loaded"+def _base_model_id(raw: str) -> str:+ """Bare ``sie_id`` with any ``:profile`` suffix removed, lowercased.++ HuggingFace org/model ids contain ``/`` but never ``:``, so the part before+ the first ``:`` is the base model and the rest is a profile name. Used where+ the base model is what matters (e.g. disk weights, which a profile variant+ shares with its base).+ """+ return raw.split(":", maxsplit=1)[0].strip().lower()+++def _canonical_pinned_id(raw: str) -> str:+ """Canonicalise a pinned id, preserving non-default profile variants.++ The worker keys ``_loaded`` / configs / memory by the FULL profile-qualified+ id for non-default profiles (``loader._expand_profile_variants`` materialises+ each as its own ``{base}:{profile}`` config), so the pinned set must keep+ that granularity to load and protect the right unit. Mirrors the gateway's+ canonicalization (``pools.rs``): the literal ``:default`` folds to the bare+ base; any other ``:profile`` is preserved. Everything is lowercased for+ case-insensitive matching against the loaded keys.++ Splits on the first ``:`` (HF ids contain ``/`` but never ``:``, and profile+ names are single-segment), so a single-colon id is the only valid shape.+ """+ base, sep, profile = raw.strip().lower().partition(":")+ base = base.strip()+ profile = profile.strip()+ if not sep or not profile or profile == "default":+ return base+ return f"{base}:{profile}"+++def _normalize_pinned(pinned: Iterable[str] | None) -> frozenset[str]:+ """Normalise a raw pinned-model list into a lowercase canonical-id frozenset.++ Profile-qualified ids are preserved (only ``:default`` folds to the base).+ """+ if not pinned:+ return frozenset()+ return frozenset(canonical for raw in pinned if (canonical := _canonical_pinned_id(raw)))++def _model_config_semantic_hash(config: ModelConfig) -> str:"""Stable hash for config equality that ignores Pydantic private attrs."""payload = json.dumps(config.model_dump(mode="json"), sort_keys=True, separators=(",", ":"))@@ -91,6 +134,7 @@ class ModelRegistry:engine_config: EngineConfig | None = None,enable_hot_reload: bool = True,pool_name: str | None = None,+ pinned_models: Iterable[str] | None = None,) -> None:"""Initialize the registry.@@ -107,6 +151,11 @@ class ModelRegistry:generation and non-generation models on the same worker. When``None`` the validator is skipped (e.g. unit tests without apool context).+ pinned_models: Optional list of model ids to pin in memory. Pinned models are+ eager-loaded and never chosen as LRU/idle/OOM eviction victims. Ids may be+ bare (``org/name``) or profile-qualified (``org/name:profile``); non-default+ profiles are first-class variants and are preserved, while ``:default`` folds+ to the base. Matching is case-insensitive against the full canonical id."""# Store as string to handle cloud URLsself._models_dir: str | None = str(models_dir) if models_dir is not None else None@@ -114,6 +163,8 @@ class ModelRegistry:self._device = deviceself._enable_hot_reload = enable_hot_reloadself._pool_name = pool_name.strip().lower() if pool_name else None+ # Normalised pinned set: bare lowercase sie_ids, never chosen for eviction.+ self._pinned_models: frozenset[str] = _normalize_pinned(pinned_models)self._configs: dict[str, ModelConfig] = {}self._model_dirs: dict[str, Path] = {}self._loaded: dict[str, LoadedModel] = {}@@ -136,7 +187,8 @@ class ModelRegistry:DiskCacheConfig(cache_dir=cache_config.local_cache,pressure_threshold=threshold,- )+ ),+ pinned_provider=self._pinned_disk_repo_ids,)logger.info("Disk cache manager enabled (threshold=%.0f%%, cache_dir=%s)",@@ -233,6 +285,110 @@ class ModelRegistry:registry_callbacks=self,)+ def _is_pinned(self, name: str) -> bool:+ """Return True if ``name`` is in the pinned set (case-insensitive)."""+ return name.strip().lower() in self._pinned_models++ def _pinned_disk_repo_ids(self) -> set[str]:+ """HF repo ids of pinned models, for disk-cache eviction protection.++ Matched at BASE-model granularity: a profile variant shares its base+ model's ``hf_id`` (disk weights), so a pinned ``org/model:fp8`` protects+ the same repo as ``org/model``. Mapping pinned ids to the configs'+ ``hf_id`` keeps a long-tail download from evicting a pinned model's+ weights and reintroducing its cold start.++ The disk cache matches by exact ``hf_id`` (no case-folding, unlike the+ in-memory sie_id path), which is safe because the cache key also derives+ from ``config.hf_id`` (model_loader passes it to ``ensure_space_before_download``+ and ``touch``).+ """+ if not self._pinned_models:+ return set()+ pinned_bases = {_base_model_id(pinned_id) for pinned_id in self._pinned_models}+ return {+ config.hf_id+ for sie_id, config in self._configs.items()+ if config.hf_id and _base_model_id(sie_id) in pinned_bases+ }++ async def _eager_load_pinned(self) -> None:+ """Eager-load every pinned model that has a config and is not yet resident.++ Idempotent and best-effort (``start_load_async`` skips loaded/loading and+ failed-in-cooldown models). Called whenever the pinned set or the config+ set changes, so a pin recorded before its config existed (default Helm+ workers receive configs at runtime via the sidecar) becomes resident once+ the config is known, and a pinned model unloaded by a config replacement+ is reloaded.+ """+ for pinned_id in sorted(self._pinned_models):+ name = self.resolve_model_id(pinned_id)+ if name is None:+ logger.debug("Pinned model '%s' has no local config yet; skipping eager-load", pinned_id)+ continue+ if self.is_loaded(name):+ continue+ try:+ await self.start_load_async(name, self._device)+ except Exception:+ logger.exception("Failed to start eager-load of pinned model '%s'", name)++ def _maybe_schedule_pinned_load(self, name: str) -> None:+ """Schedule a background pinned-load reconcile if ``name`` is pinned (sync callers).++ Used by the synchronous ``add_config`` to bridge into the async loader+ when a pinned model's config arrives at runtime, mirroring the+ ``start_load_async`` / ``_load_lora`` create-task pattern. Schedules the+ guarded ``_eager_load_pinned`` (so a load-validation error can't surface+ as an unretrieved task exception). A no-op when ``name`` is not pinned or+ when there is no running loop (e.g. sync tests / CLI), where the async+ reconcile paths cover it.+ """+ if not self._is_pinned(name):+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return+ task = loop.create_task(self._eager_load_pinned())+ self._background_tasks.add(task)+ task.add_done_callback(self._background_tasks.discard)++ async def set_pinned_models(self, raw_ids: Iterable[str]) -> frozenset[str]:+ """Replace the pinned set at runtime from the gateway's authoritative pool spec.++ ``raw_ids`` are gateway-canonical (bare ``sie_id`` or profile-qualified+ ``sie_id:profile``); they are normalized to lowercased canonical ids+ (profile variants preserved, ``:default`` folded to base). The new set+ fully REPLACES the current one (an empty set un-pins everything), so+ removing a model from the pool API actually un-pins it on the worker.++ On change: pinned models with a local config are eager-loaded in the+ background (non-blocking, best-effort) so the first request pays no cold+ start; un-pinned models are simply demoted to LRU/idle-evictable again+ (no forced unload). The frozenset is reassigned atomically, so every+ eviction path and the disk-cache provider see the new protection+ immediately. Idempotent: an unchanged set is a no-op.++ Returns the normalized pinned set now in effect.+ """+ new_pinned = _normalize_pinned(raw_ids)+ if new_pinned == self._pinned_models:+ return new_pinned++ newly_pinned = new_pinned - self._pinned_models+ # Reassign before loading so newly-pinned models are eviction-protected+ # the instant they are pinned, even before their weights are resident.+ self._pinned_models = new_pinned+ logger.info(+ "Pinned set updated: %d model(s) pinned (%d newly pinned)",+ len(new_pinned),+ len(newly_pinned),+ )+ await self._eager_load_pinned()+ return new_pinned+def _load_configs_from_dir(self, models_dir: str) -> None:"""Load all model configs from a directory (local or cloud)."""from sie_sdk.storage import is_cloud_path@@ -476,6 +632,25 @@ class ModelRegistry:raise KeyError(msg)return self._configs[name]+ def resolve_model_id(self, raw_id: str) -> str | None:+ """Resolve a raw model id to a known config's ``sie_id``.++ Accepts profile-qualified (``sie_id:profile``) and differently-cased ids,+ which the pinned set may carry per the deployment design. Non-default+ profiles are first-class config entries keyed by the full ``base:profile``+ id (``loader._expand_profile_variants``), so this matches the FULL+ canonical id case-insensitively and returns that variant's original-case+ ``sie_id`` (not the base). ``:default`` folds to the base. Returns+ ``None`` when no config matches.+ """+ canonical = _canonical_pinned_id(raw_id)+ if not canonical:+ return None+ for sie_id in self._configs:+ if sie_id.strip().lower() == canonical:+ return sie_id+ return None+def get(self, name: str) -> ModelAdapter:"""Get a loaded model's adapter.@@ -542,10 +717,10 @@ class ModelRegistry:if not self._is_oom_error(e):raise- # OOM - try to evict LRU model and retry- lru_model = self._memory_manager.get_lru_model()+ # OOM - try to evict LRU non-pinned model and retry+ lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)if lru_model is None:- logger.error("OOM loading '%s' but no models to evict", name)+ logger.error("OOM loading '%s' but no non-pinned models to evict", name)raiselogger.warning(@@ -609,11 +784,11 @@ class ModelRegistry:msg = f"Model '{name}' is currently being unloaded"raise RuntimeError(msg)- # Pre-load eviction: evict LRU models until below pressure threshold+ # Pre-load eviction: evict LRU non-pinned models until below pressure thresholdwhile self._memory_manager.check_pressure():- lru_model = self._memory_manager.get_lru_model()+ lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)if lru_model is None:- break # No models to evict, proceed with load attempt+ break # No non-pinned models to evict, proceed with load attemptstats = self._memory_manager.get_stats()logger.info(@@ -650,10 +825,10 @@ class ModelRegistry:if not self._is_oom_error(e):raise- # OOM despite pre-load eviction: evict LRU and retry once- lru_model = self._memory_manager.get_lru_model()+ # OOM despite pre-load eviction: evict LRU non-pinned model and retry once+ lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)if lru_model is None:- logger.error("OOM loading '%s' but no models to evict", name)+ logger.error("OOM loading '%s' but no non-pinned models to evict", name)raiselogger.warning(@@ -1078,6 +1253,10 @@ class ModelRegistry:# request retries with the new config.self._failed.pop(config.sie_id, None)self._config_version += 1+ # The config for an already-pinned model may have just arrived at runtime+ # (default Helm workers receive configs via the sidecar after a pin was+ # recorded). Eager-load it now so the pin actually keeps it resident.+ self._maybe_schedule_pinned_load(config.sie_id)async def replace_configs_async(self,@@ -1143,7 +1322,12 @@ class ModelRegistry:for name in invalidated:self._failed.pop(name, None)self._config_version += 1- return invalidated++ # Outside the load lock (``start_load_async`` acquires it): reload pinned+ # models that were just unloaded because their config changed, and load+ # any pinned model whose config arrived in this snapshot.+ await self._eager_load_pinned()+ return invalidateddef accepts_config_pool(self, config: ModelConfig) -> bool:if self._pool_name is None:@@ -1324,12 +1508,14 @@ class ModelRegistry:return Falsetry:- # Walk LRU order and pick the first that is not ``exclude_name``- # and is still loaded (the OrderedDict in the memory manager- # may include entries already torn down by another path).+ # Walk LRU order and pick the first that is not ``exclude_name``,+ # not pinned, and is still loaded (the OrderedDict in the memory+ # manager may include entries already torn down by another path).for candidate in self._memory_manager.loaded_models:if candidate == exclude_name:continue+ if self._is_pinned(candidate):+ continueif candidate not in self._loaded:continueif candidate in self._unloading:@@ -1451,7 +1637,7 @@ class ModelRegistry:while self._idle_evict_running:try:await asyncio.sleep(interval)- stale = self._memory_manager.get_idle_models(idle_threshold_s=threshold)+ stale = self._memory_manager.get_idle_models(idle_threshold_s=threshold, exclude=self._pinned_models)if not stale:continue@@ -1557,8 +1743,11 @@ class ModelRegistry:)break- lru_model = self._memory_manager.get_lru_model()+ lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)if lru_model is None:+ logger.debug(+ "Memory pressure detected but no non-pinned models to evict, skipping",+ )breakstats = self._memory_manager.get_stats()diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.pyindex b960a39d1..c2e846c8c 100644--- a/packages/sie_server/src/sie_server/ipc_server.py+++ b/packages/sie_server/src/sie_server/ipc_server.py@@ -25,6 +25,7 @@ from sie_server.ipc_types import (METHOD_PROCESS_SCORE_BATCH,METHOD_REPLACE_MODEL_CONFIGS,METHOD_RUN_BATCH,+ METHOD_SET_PINNED_MODELS,METHOD_SIGNAL_GENERATE_CANCEL,METHOD_WORKER_CAPABILITIES,ApplyModelConfigRequest,@@ -44,6 +45,8 @@ from sie_server.ipc_types import (ReplaceModelConfigsResponse,ResponseEnvelope,RunBatchRequest,+ SetPinnedModelsRequest,+ SetPinnedModelsResponse,SignalGenerateCancelRequest,SignalGenerateCancelResponse,WorkerCapabilitiesRequest,@@ -458,6 +461,8 @@ class IpcServer: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_SET_PINNED_MODELS:+ resp_body = await self._handle_set_pinned_models(msgspec.convert(body, SetPinnedModelsRequest))elif method == METHOD_SIGNAL_GENERATE_CANCEL:resp_body = await self._handle_signal_generate_cancel(msgspec.convert(body, SignalGenerateCancelRequest)@@ -513,10 +518,16 @@ class IpcServer:bundle_config_hash = self._executor.compute_bundle_config_hash(self._bundle_id)except Exception: # noqa: BLE001logger.debug("Could not compute bundle_config_hash for ping", exc_info=True)+ loaded_models: list[str] = []+ try:+ loaded_models = self._executor.loaded_model_names()+ except Exception: # noqa: BLE001+ logger.debug("Could not compute loaded_models for ping", exc_info=True)return PingResponse(timestamp_ms=req.timestamp_ms,worker_id=self._worker_id,bundle_config_hash=bundle_config_hash,+ loaded_models=loaded_models,)async def _handle_ensure_ready(self, req: EnsureModelReadyRequest) -> EnsureModelReadyResponse:@@ -556,6 +567,9 @@ class IpcServer:) -> ReplaceModelConfigsResponse:return await self._executor.replace_model_configs(req)+ async def _handle_set_pinned_models(self, req: SetPinnedModelsRequest) -> SetPinnedModelsResponse:+ return await self._executor.set_pinned_models(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 2bce92b67..f704e61cf 100644--- a/packages/sie_server/src/sie_server/ipc_types.py+++ b/packages/sie_server/src/sie_server/ipc_types.py@@ -46,6 +46,7 @@ METHOD_SIGNAL_GENERATE_CANCEL = "SignalGenerateCancel"METHOD_RUN_BATCH = "RunBatch"METHOD_APPLY_MODEL_CONFIG = "ApplyModelConfig"METHOD_REPLACE_MODEL_CONFIGS = "ReplaceModelConfigs"+METHOD_SET_PINNED_MODELS = "SetPinnedModels"METHOD_DRAIN = "Drain"@@ -62,6 +63,7 @@ class PingResponse(msgspec.Struct):timestamp_ms: floatworker_id: strbundle_config_hash: str = ""+ loaded_models: list[str] = msgspec.field(default_factory=list)# -----------------------------------------------------------------------------@@ -182,6 +184,27 @@ class ReplaceModelConfigsResponse(msgspec.Struct):applied_models: list[str] = msgspec.field(default_factory=list)+# -----------------------------------------------------------------------------+# SetPinnedModels+# -----------------------------------------------------------------------------+#+# Runtime delivery of a pool's pinned-model set from the gateway to the worker.+# The worker-sidecar polls the pool's ``PoolSpec.pinned_models`` (the single+# source of truth, set via the /v1/pools API or SIE_GATEWAY_STATIC_QUEUE_POOLS)+# and pushes it here on change. ``models`` carries gateway-canonical ids (bare+# ``sie_id`` or profile-qualified ``sie_id:profile``); the registry normalizes+# them. The set is authoritative and REPLACES the worker's current pinned set.+++class SetPinnedModelsRequest(msgspec.Struct):+ models: list[str]+++class SetPinnedModelsResponse(msgspec.Struct):+ applied: bool+ pinned_count: int = 0++# -----------------------------------------------------------------------------# 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 a0e8ca32c..49086ff09 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -36,6 +36,8 @@ from sie_server.ipc_types import (ReplaceModelConfigsResponse,ScoreBatchItem,ScoreOutputRaw,+ SetPinnedModelsRequest,+ SetPinnedModelsResponse,SparseOutput,)from sie_server.observability.metrics import record_ipc_batch_shape@@ -486,6 +488,10 @@ class QueueExecutor:def registry(self) -> ModelRegistry:return self._registry+ def loaded_model_names(self) -> list[str]:+ """Return sorted currently loaded model ids for sidecar health heartbeats."""+ return sorted(self._registry.loaded_model_names)+def invalidate_model_descriptor(self, model_id: str) -> None:"""Drop the cached descriptor for ``model_id``.@@ -565,6 +571,11 @@ class QueueExecutor:applied_models=applied_models,)+ async def set_pinned_models(self, req: SetPinnedModelsRequest) -> SetPinnedModelsResponse:+ """Apply the gateway's authoritative pinned-model set to the local registry."""+ pinned = await self._registry.set_pinned_models(req.models)+ return SetPinnedModelsResponse(applied=True, pinned_count=len(pinned))+# -- Readiness ---------------------------------------------------------async def ensure_model_ready(self, model_id: str) -> ReadinessState:@@ -572,8 +583,8 @@ class QueueExecutor:Mapping (for the Rust side):- ``ready``: continue processing- - ``loading_started``: NAK with base delay (this call triggered a new load)- - ``loading_in_progress``: NAK with longer delay (already loading)+ - ``loading_started``: progress-ACK and recheck (this call triggered a new load)+ - ``loading_in_progress``: progress-ACK and recheck with a longer delay- ``retry_later``: NAK with base delay (unknown error path)"""if not self._registry.has_model(model_id):diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex f04bd248b..c4c2ded67 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -22,6 +22,7 @@ from sie_server.adapters.sglang.generation import (SGLangGenerationAdapter,_chunk_from_sglang_event,_encode_image_data,+ _mamba_scheduler_strategy_value,_p_unsafe_from_verdict_logprobs,_parse_sglang_generate_response,_thresholded_verdict,@@ -51,6 +52,33 @@ def test_load_contract_flags() -> None:assert SGLangGenerationAdapter.manages_own_load_timeout is True+ ("args", "expected"),+ [+ # two-token form (Qwen3.5-4B YAML shape) → exact value+ (["--mamba-scheduler-strategy", "extra_buffer"], "extra_buffer"),+ (["--mamba-scheduler-strategy", "default"], "default"),+ # flag=value form+ (["--mamba-scheduler-strategy=extra_buffer"], "extra_buffer"),+ (["--mamba-scheduler-strategy=default"], "default"),+ # absent → None+ (["--disable-overlap-schedule"], None),+ ([], None),+ # trailing flag with no value → None (no crash)+ (["--mamba-scheduler-strategy"], None),+ # a stray ``extra_buffer`` token elsewhere must NOT be read as the value+ (["--some-other-flag", "extra_buffer", "--mamba-scheduler-strategy", "default"], "default"),+ # last occurrence wins (argparse semantics)+ (+ ["--mamba-scheduler-strategy", "default", "--mamba-scheduler-strategy", "extra_buffer"],+ "extra_buffer",+ ),+ ],+)+def test_mamba_scheduler_strategy_value(args: list[str], expected: str | None) -> None:+ assert _mamba_scheduler_strategy_value(args) == expected++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 74960a80e..1c95f1d37 100644--- a/packages/sie_server/tests/app/test_app_factory.py+++ b/packages/sie_server/tests/app/test_app_factory.py@@ -263,6 +263,87 @@ class TestPreloadModels:assert registry.load_async.call_count == 2+class TestPinnedModels:+ """Tests for pinned model startup behavior."""++ @pytest.mark.asyncio+ async def test_pinned_models_are_loaded_at_startup(self) -> None:+ """_load_pinned_models calls load_async for each pinned model."""+ registry = AsyncMock()+ # is_loaded and resolve_model_id are sync; sync mocks avoid truthy coroutines.+ registry.is_loaded = MagicMock(return_value=False)+ registry.resolve_model_id = MagicMock(side_effect=lambda raw: raw)+ config = AppStateConfig(device="cpu", pinned_models=["model-a", "model-b"])++ await AppFactory._load_pinned_models(registry, config)++ assert registry.load_async.call_count == 2+ registry.load_async.assert_any_call("model-a", "cpu")+ registry.load_async.assert_any_call("model-b", "cpu")++ @pytest.mark.asyncio+ async def test_pinned_models_skips_when_none(self) -> None:+ """_load_pinned_models is a no-op when pinned_models is None."""+ registry = AsyncMock()+ config = AppStateConfig(device="cpu", pinned_models=None)++ await AppFactory._load_pinned_models(registry, config)++ registry.load_async.assert_not_called()++ @pytest.mark.asyncio+ async def test_pinned_models_continues_on_failure(self) -> None:+ """A failed pinned model load does not crash startup."""+ registry = AsyncMock()+ registry.is_loaded = MagicMock(return_value=False)+ registry.resolve_model_id = MagicMock(side_effect=lambda raw: raw)+ registry.load_async.side_effect = [RuntimeError("OOM"), AsyncMock()]+ config = AppStateConfig(device="cpu", pinned_models=["model-a", "model-b"])++ await AppFactory._load_pinned_models(registry, config) # must not raise++ assert registry.load_async.call_count == 2++ @pytest.mark.asyncio+ async def test_pinned_model_in_preload_loaded_only_once(self) -> None:+ """A model in both preload and pinned is loaded exactly once."""+ registry = AsyncMock()+ # Simulate already loaded after preload (sync mocks: not async methods)+ registry.is_loaded = MagicMock(return_value=True)+ registry.resolve_model_id = MagicMock(side_effect=lambda raw: raw)+ config = AppStateConfig(device="cpu", pinned_models=["model-a"])++ await AppFactory._load_pinned_models(registry, config)++ # Already loaded, so load_async must NOT be called again+ registry.load_async.assert_not_called()++ @pytest.mark.asyncio+ async def test_pinned_profile_qualified_id_loads_bare_sie_id(self) -> None:+ """A profile-qualified pin (``sie_id:profile``) eager-loads the bare sie_id."""+ registry = AsyncMock()+ registry.is_loaded = MagicMock(return_value=False)+ # resolve_model_id strips the :profile suffix to the config's bare id.+ registry.resolve_model_id = MagicMock(return_value="org/model")+ config = AppStateConfig(device="cpu", pinned_models=["org/model:fast"])++ await AppFactory._load_pinned_models(registry, config)++ registry.resolve_model_id.assert_called_once_with("org/model:fast")+ registry.load_async.assert_called_once_with("org/model", "cpu")++ @pytest.mark.asyncio+ async def test_pinned_unresolved_id_skipped(self) -> None:+ """A pin with no matching config is skipped without crashing startup."""+ registry = AsyncMock()+ registry.resolve_model_id = MagicMock(return_value=None)+ config = AppStateConfig(device="cpu", pinned_models=["does/not-exist"])++ await AppFactory._load_pinned_models(registry, config) # must not raise++ registry.load_async.assert_not_called()++class TestPreloadModelsEnvRoundTrip:"""Tests for preload_models env var serialization."""@@ -274,6 +355,7 @@ class TestPreloadModelsEnvRoundTrip:monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)monkeypatch.delenv("SIE_DEVICE", raising=False)monkeypatch.delenv("SIE_POOL", raising=False)+ monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)config = AppStateConfig(preload_models=["model-a", "model-b"])config.save_to_env_vars()@@ -287,6 +369,7 @@ class TestPreloadModelsEnvRoundTrip:monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)monkeypatch.delenv("SIE_DEVICE", raising=False)monkeypatch.delenv("SIE_POOL", raising=False)+ monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)config = AppStateConfig(preload_models=None)config.save_to_env_vars()@@ -301,43 +384,81 @@ class TestPreloadModelsEnvRoundTrip:monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)monkeypatch.delenv("SIE_DEVICE", raising=False)monkeypatch.delenv("SIE_POOL", raising=False)+ monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)config = AppStateConfig(pool_name="customer-a")config.save_to_env_vars()restored = AppStateConfig.from_env_vars()assert restored.pool_name == "customer-a"+ def test_pinned_models_env_round_trip(self, monkeypatch) -> None:+ """SIE_PINNED_MODELS='a,b' round-trips to pinned_models == ['a', 'b']."""+ 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)+ monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)++ config = AppStateConfig(pinned_models=["a", "b"])+ config.save_to_env_vars()+ restored = AppStateConfig.from_env_vars()+ assert restored.pinned_models == ["a", "b"]++ def test_pinned_models_none_round_trip(self, monkeypatch) -> None:+ """pinned_models=None survives env round-trip (unset => None)."""+ 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)+ monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)++ config = AppStateConfig(pinned_models=None)+ config.save_to_env_vars()+ restored = AppStateConfig.from_env_vars()+ assert restored.pinned_models is None+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- class FakeRegistry:- async def start_memory_monitor(self) -> None:- pass+ async def start_hot_reload(self) -> None:+ pass++ async def stop_memory_monitor(self) -> None:+ pass- async def start_idle_evictor(self) -> None:- pass+ async def stop_idle_evictor(self) -> None:+ pass- async def start_hot_reload(self) -> None:- pass+ async def stop_hot_reload(self) -> None:+ pass- async def stop_memory_monitor(self) -> None:- pass+ async def unload_all_async(self) -> None:+ pass- async def stop_idle_evictor(self) -> None:- pass+ def is_loaded(self, name: str) -> bool:+ return False- async def stop_hot_reload(self) -> None:- pass+ def resolve_model_id(self, raw_id: str) -> str | None:+ return raw_id- async def unload_all_async(self) -> None:- pass+ async def load_async(self, name: str, device: str) -> None:+ pass++ @pytest.mark.asyncio+ async def test_model_registry_receives_pool_name(self, monkeypatch: pytest.MonkeyPatch) -> None:+ created_kwargs: dict[str, Any] = {}- def fake_model_registry(**kwargs: Any) -> FakeRegistry:+ def fake_model_registry(**kwargs: Any) -> TestModelRegistryConfig._FakeRegistry:created_kwargs.update(kwargs)- return FakeRegistry()+ return TestModelRegistryConfig._FakeRegistry()monkeypatch.setattr("sie_server.app.app_factory.ModelRegistry", fake_model_registry)@@ -346,6 +467,22 @@ class TestModelRegistryConfig:assert created_kwargs["pool_name"] == "pool-a"+ @pytest.mark.asyncio+ async def test_model_registry_receives_pinned_models(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """ModelRegistry constructor receives pinned_models from AppStateConfig."""+ created_kwargs: dict[str, Any] = {}++ def fake_model_registry(**kwargs: Any) -> TestModelRegistryConfig._FakeRegistry:+ created_kwargs.update(kwargs)+ return TestModelRegistryConfig._FakeRegistry()++ monkeypatch.setattr("sie_server.app.app_factory.ModelRegistry", fake_model_registry)++ async with AppFactory._model_registry(AppStateConfig(pinned_models=["model-x", "model-y"])):+ pass++ assert created_kwargs["pinned_models"] == ["model-x", "model-y"]+class TestConfigureTorchThreads:def test_default_uses_half_cpu_count(self, monkeypatch) -> None:diff --git a/packages/sie_server/tests/core/test_disk_cache.py b/packages/sie_server/tests/core/test_disk_cache.pyindex b619df957..3007e6466 100644--- a/packages/sie_server/tests/core/test_disk_cache.py+++ b/packages/sie_server/tests/core/test_disk_cache.py@@ -425,6 +425,46 @@ class TestModelDiskCacheManager:assert evicted == []assert model_dir.exists()+ def test_ensure_space_excludes_pinned_models(self, cache_dir: Path) -> None:+ """Pinned models' weights are never evicted from disk, even under sustained pressure."""+ base = time.time()+ # The pinned model is the oldest, so it would be the first victim if unprotected.+ pinned_dir = create_hf_cache_model(cache_dir, "pinned/model", commit_hash="pin", access_time=base - 7200)+ evictable_dir = create_hf_cache_model(cache_dir, "evictable/model", commit_hash="evi", access_time=base - 3600)++ config = DiskCacheConfig(cache_dir=cache_dir, pressure_threshold=0.85)+ manager = ModelDiskCacheManager(config, pinned_provider=lambda: {"pinned/model"})++ # Sustained high pressure: the loop evicts the only non-pinned model, then stops+ # because the pinned model is excluded (no infinite loop, pinned untouched).+ mock_usage = MagicMock()+ mock_usage.used = 90 * (1024**3)+ mock_usage.total = 100 * (1024**3)++ with patch("shutil.disk_usage", return_value=mock_usage):+ evicted = manager.ensure_space_before_download("new/model")++ assert evicted == ["evictable/model"]+ assert pinned_dir.exists()+ assert not evictable_dir.exists()++ def test_ensure_space_all_pinned_returns_empty_without_hanging(self, cache_dir: Path) -> None:+ """When every cached model is pinned, eviction is a no-op and the loop terminates."""+ pinned_dir = create_hf_cache_model(cache_dir, "pinned/model", commit_hash="pin", access_time=time.time() - 3600)++ config = DiskCacheConfig(cache_dir=cache_dir, pressure_threshold=0.85)+ manager = ModelDiskCacheManager(config, pinned_provider=lambda: {"pinned/model"})++ mock_usage = MagicMock()+ mock_usage.used = 90 * (1024**3) # Sustained high pressure+ mock_usage.total = 100 * (1024**3)++ with patch("shutil.disk_usage", return_value=mock_usage):+ evicted = manager.ensure_space_before_download("new/model")++ assert evicted == []+ assert pinned_dir.exists()+def test_ensure_space_evicts_multiple_until_below_threshold(self, manager: ModelDiskCacheManager, cache_dir: Path) -> None:diff --git a/packages/sie_server/tests/core/test_idle_evict.py b/packages/sie_server/tests/core/test_idle_evict.pyindex 5ebc3973f..58159d9f2 100644--- a/packages/sie_server/tests/core/test_idle_evict.py+++ b/packages/sie_server/tests/core/test_idle_evict.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport asyncioimport time+from collections.abc import Containerfrom pathlib import Pathfrom unittest.mock import AsyncMock, MagicMock, patch@@ -53,6 +54,7 @@ def _build_registry(*,idle_evict_s: int | None,check_interval_s: float = 0.01,+ pinned_models: list[str] | None = None,) -> ModelRegistry:"""Construct a registry wired with ``EngineConfig.idle_evict_s`` set.@@ -70,6 +72,7 @@ def _build_registry(return ModelRegistry(memory_config=MemoryConfig(memory_check_interval_s=check_interval_s),engine_config=engine_config,+ pinned_models=pinned_models,)@@ -288,8 +291,10 @@ async def test_idle_eviction_skips_already_unloaded(mock_load_adapter: MagicMock# is genuinely gone. Exercises the snapshot-vs-recheck race path.original_get_idle = reg._memory_manager.get_idle_models- def racing_get_idle(*, idle_threshold_s: float, now: float | None = None) -> list[str]:- result = original_get_idle(idle_threshold_s=idle_threshold_s, now=now)+ def racing_get_idle(+ *, idle_threshold_s: float, now: float | None = None, exclude: Container[str] = frozenset()+ ) -> list[str]:+ result = original_get_idle(idle_threshold_s=idle_threshold_s, now=now, exclude=exclude)# Synchronous unload: drop from the loaded dict directly to avoid# awaiting an async call from a sync side-effect. This mimics what# any other sync code path that mutated `_loaded` would do.@@ -305,3 +310,39 @@ async def test_idle_eviction_skips_already_unloaded(mock_load_adapter: MagicMock# No crash, model stays unloaded, and crucially the loop did not try# to call ``_do_unload`` on a model that was already gone.assert not reg.is_loaded("model-y")+++@patch("sie_server.core.model_loader.load_adapter")+async def test_idle_evictor_skips_pinned_model(mock_load_adapter: MagicMock) -> None:+ """Idle evictor must not unload a pinned model even when it is stale.++ Both models are forced stale; only the non-pinned one should be evicted.+ """++ def make_adapter() -> MagicMock:+ m = MagicMock()+ m.capabilities.outputs = ["dense"]+ return m++ mock_load_adapter.side_effect = [make_adapter(), make_adapter()]++ reg = _build_registry(idle_evict_s=1, pinned_models=["model-pinned"])+ for name in ["model-pinned", "model-evictable"]:+ reg.add_config(_make_config(name=name, hf_id=f"org/{name}"))+ await reg.load_async(name, device="cpu")++ # Force both models stale+ now = time.monotonic()+ for name in ["model-pinned", "model-evictable"]:+ info = reg._memory_manager.get_model_info(name)+ assert info is not None+ info.last_used_at = now - 200.0++ await reg.start_idle_evictor()+ await asyncio.sleep(0.05)+ await reg.stop_idle_evictor()++ # Non-pinned model evicted; pinned model kept+ assert not reg.is_loaded("model-evictable")+ assert reg.is_loaded("model-pinned")diff --git a/packages/sie_server/tests/core/test_memory.py b/packages/sie_server/tests/core/test_memory.pyindex 30bf3b1b4..6ceb32cc8 100644--- a/packages/sie_server/tests/core/test_memory.py+++ b/packages/sie_server/tests/core/test_memory.py@@ -142,19 +142,16 @@ class TestMemoryConfig:assert config.pressure_threshold == 0.95assert config.min_free_bytes is None- assert config.proactive_eviction is Truedef test_custom_values(self) -> None:"""Test custom configuration values."""config = MemoryConfig(pressure_threshold=0.9,min_free_bytes=4 * (1024**3),- proactive_eviction=False,)assert config.pressure_threshold == 0.9assert config.min_free_bytes == 4 * (1024**3)- assert config.proactive_eviction is Falseclass TestMemoryManager:@@ -234,15 +231,58 @@ class TestMemoryManager:"""Test LRU with no models."""assert manager.get_lru_model() is None- def test_get_eviction_candidates(self, manager: MemoryManager) -> None:- """Test getting eviction candidates."""- manager.register_model("model-a")- manager.register_model("model-b")- manager.register_model("model-c")+ def test_get_lru_model_excludes_pinned(self, manager: MemoryManager) -> None:+ """get_lru_model skips names in the exclude set."""+ manager.register_model("a")+ manager.register_model("b")+ manager.register_model("c")+ # a is oldest (LRU); b is second-oldest; c is newest++ # Excluding {a} must return b (the next oldest)+ assert manager.get_lru_model(exclude={"a"}) == "b"++ # Excluding all must return None+ assert manager.get_lru_model(exclude={"a", "b", "c"}) is None++ # Default (no exclude) still returns a+ assert manager.get_lru_model() == "a"++ def test_get_idle_models_excludes_pinned(self, manager: MemoryManager) -> None:+ """get_idle_models skips names in the exclude set."""+ manager.register_model("pinned")+ manager.register_model("evictable")++ now = time.monotonic()+ # Both stale+ manager.get_model_info("pinned").last_used_at = now - 500.0 # type: ignore[union-attr]+ manager.get_model_info("evictable").last_used_at = now - 200.0 # type: ignore[union-attr]++ # Without exclude: both returned (oldest first)+ idle_all = manager.get_idle_models(idle_threshold_s=50.0, now=now)+ assert idle_all == ["pinned", "evictable"]++ # With exclude: only evictable returned+ idle_filtered = manager.get_idle_models(idle_threshold_s=50.0, now=now, exclude={"pinned"})+ assert idle_filtered == ["evictable"]++ def test_get_lru_model_exclude_is_case_insensitive(self, manager: MemoryManager) -> None:+ """Loaded names keep their case (HF ids); the lowercased exclude set still matches."""+ manager.register_model("Org/Model-A") # uppercase, oldest (LRU)+ manager.register_model("org/model-b")++ # The pinned set is normalised to lowercase, but the loaded key is not.+ assert manager.get_lru_model(exclude={"org/model-a"}) == "org/model-b"++ def test_get_idle_models_exclude_is_case_insensitive(self, manager: MemoryManager) -> None:+ """Idle exclusion lowercases the loaded name before testing the set."""+ manager.register_model("Org/Pinned")+ manager.register_model("org/evictable")+ now = time.monotonic()+ manager.get_model_info("Org/Pinned").last_used_at = now - 500.0 # type: ignore[union-attr]+ manager.get_model_info("org/evictable").last_used_at = now - 200.0 # type: ignore[union-attr]- # Get 2 candidates (oldest first)- candidates = manager.get_eviction_candidates(2)- assert candidates == ["model-a", "model-b"]+ idle = manager.get_idle_models(idle_threshold_s=50.0, now=now, exclude={"org/pinned"})+ assert idle == ["org/evictable"]def test_get_idle_models_returns_sorted_by_age(self, manager: MemoryManager) -> None:"""Stale models are returned oldest-first regardless of insertion order."""@@ -374,49 +414,6 @@ class TestMemoryManager:# Need less than availableassert manager.should_evict_for_load(required_bytes=4 * (1024**3)) is False- @pytest.mark.asyncio- async def test_check_memory_pressure_async(self) -> None:- """Test async memory pressure check."""- manager = MemoryManager(device="cpu")- manager.register_model("model-a")-- # Mock high memory usage- mock_stats = MemoryStats(- used_bytes=96,- total_bytes=100,- device_type="cpu",- )- manager._tracker = MagicMock()- manager._tracker.get_stats.return_value = mock_stats-- candidates = await manager.check_memory_pressure()-- assert len(candidates) == 1- assert candidates[0] == "model-a"-- @pytest.mark.asyncio- async def test_check_memory_pressure_disabled(self) -> None:- """Test that proactive eviction can be disabled."""- manager = MemoryManager(- device="cpu",- config=MemoryConfig(proactive_eviction=False),- )- manager.register_model("model-a")-- # Mock high memory usage- mock_stats = MemoryStats(- used_bytes=9 * (1024**3),- total_bytes=10 * (1024**3),- device_type="cpu",- )- manager._tracker = MagicMock()- manager._tracker.get_stats.return_value = mock_stats-- candidates = await manager.check_memory_pressure()-- # Should return empty because proactive eviction is disabled- assert candidates == []-class TestCUDAMemoryTracker:"""Tests for CUDAMemoryTracker (mocked)."""diff --git a/packages/sie_server/tests/core/test_registry_async.py b/packages/sie_server/tests/core/test_registry_async.pyindex b4218e4aa..cfbb9d85d 100644--- a/packages/sie_server/tests/core/test_registry_async.py+++ b/packages/sie_server/tests/core/test_registry_async.py@@ -36,6 +36,25 @@ def patch_ensure_model_cached():yield mock+async def _drain_background_tasks(registry: ModelRegistry) -> None:+ """Await the registry's background tasks (pinned eager-load reconciles and the+ model-load tasks they spawn), so a test can observe the eventual effect.++ Fails loudly rather than hiding a regression: surfaces any task exception and+ asserts the set settles within the bounded retries (the spawned tasks are all+ fast/mocked in these tests, so a non-settling set means a real bug).+ """+ for _ in range(10):+ pending = [task for task in list(registry._background_tasks) if not task.done()]+ if not pending:+ return+ results = await asyncio.gather(*pending, return_exceptions=True)+ errors = [r for r in results if isinstance(r, BaseException)]+ assert not errors, f"background task(s) failed: {errors!r}"+ still_pending = [task for task in list(registry._background_tasks) if not task.done()]+ assert not still_pending, f"background tasks did not settle: {len(still_pending)} pending"++class TestAsyncLoading:"""Tests for async model loading."""@@ -452,3 +471,162 @@ class TestProactiveEviction:await registry_with_models.unload_async("model-a")mock_adapter.unload.assert_called_once()+++class TestSetPinnedModels:+ """Tests for the runtime pinned-set mutator (gateway -> worker bridge)."""++ def _registry(self, pinned: list[str] | None = None) -> ModelRegistry:+ registry = ModelRegistry(pinned_models=pinned)+ registry.add_config(_make_config(name="model-a", hf_id="org/model-a"))+ registry.add_config(_make_config(name="model-b", hf_id="org/model-b"))+ # Spy on eager-load so tests assert intent without driving real loads.+ registry.start_load_async = AsyncMock(return_value=True) # type: ignore[method-assign]+ return registry++ async def test_sets_pinned_and_eager_loads_new(self) -> None:+ registry = self._registry()+ result = await registry.set_pinned_models(["model-a"])++ assert result == frozenset({"model-a"})+ assert registry._pinned_models == frozenset({"model-a"})+ registry.start_load_async.assert_awaited_once_with("model-a", "cpu")++ async def test_replaces_set_and_demotes_removed(self) -> None:+ registry = self._registry(pinned=["model-a"])+ registry.start_load_async.reset_mock()++ await registry.set_pinned_models(["model-b"])++ # model-a is no longer pinned (demoted to evictable); model-b is now pinned.+ assert registry._pinned_models == frozenset({"model-b"})+ assert not registry._is_pinned("model-a")+ registry.start_load_async.assert_awaited_once_with("model-b", "cpu")++ async def test_empty_set_unpins_all(self) -> None:+ registry = self._registry(pinned=["model-a"])+ registry.start_load_async.reset_mock()++ await registry.set_pinned_models([])++ assert registry._pinned_models == frozenset()+ registry.start_load_async.assert_not_awaited()++ async def test_idempotent_noop_when_unchanged(self) -> None:+ registry = self._registry(pinned=["model-a"])+ registry.start_load_async.reset_mock()++ await registry.set_pinned_models(["model-a"])++ # Already loaded-or-pinned: unchanged set must not re-trigger eager-load.+ registry.start_load_async.assert_not_awaited()++ async def test_profile_variant_pin_loads_and_protects_the_variant(self) -> None:+ # A non-default profile is a first-class config entry keyed by the full+ # "base:profile" id; pinning it must load/protect the VARIANT, not the base.+ registry = ModelRegistry()+ registry.add_config(_make_config(name="Org/Model-A", hf_id="org/model-a"))+ registry.add_config(_make_config(name="Org/Model-A:fp8", hf_id="org/model-a"))+ registry.start_load_async = AsyncMock(return_value=True) # type: ignore[method-assign]++ await registry.set_pinned_models(["Org/Model-A:FP8"])++ # Stored as the lowercased profile-qualified id; eager-load targets the variant.+ assert registry._pinned_models == frozenset({"org/model-a:fp8"})+ registry.start_load_async.assert_awaited_once_with("Org/Model-A:fp8", "cpu")+ # The variant is protected from eviction; the base (never pinned) is not.+ assert registry._is_pinned("Org/Model-A:fp8")+ assert not registry._is_pinned("Org/Model-A")++ async def test_default_profile_folds_to_base(self) -> None:+ registry = ModelRegistry()+ registry.add_config(_make_config(name="org/model-a", hf_id="org/model-a"))+ registry.start_load_async = AsyncMock(return_value=True) # type: ignore[method-assign]++ await registry.set_pinned_models(["org/model-a:default"])++ assert registry._pinned_models == frozenset({"org/model-a"})+ registry.start_load_async.assert_awaited_once_with("org/model-a", "cpu")++ async def test_unknown_config_is_pinned_but_not_loaded(self) -> None:+ registry = self._registry()++ await registry.set_pinned_models(["missing/model"])++ # Pinned (protected if it ever loads) but not eager-loaded (no local config).+ assert registry._pinned_models == frozenset({"missing/model"})+ registry.start_load_async.assert_not_awaited()++ async def test_already_loaded_pinned_not_reloaded(self) -> None:+ registry = self._registry()+ registry._loaded["model-a"] = MagicMock() # simulate already resident++ await registry.set_pinned_models(["model-a"])++ assert registry._pinned_models == frozenset({"model-a"})+ registry.start_load_async.assert_not_awaited()++ async def test_add_config_eager_loads_already_pinned_model(self) -> None:+ # P1b: a pin recorded before its config arrives must load once the config+ # is added at runtime (default Helm workers receive configs via the sidecar).+ registry = ModelRegistry(pinned_models=["late/model"])+ registry.start_load_async = AsyncMock(return_value=True) # type: ignore[method-assign]++ # No config yet: nothing to load.+ await registry._eager_load_pinned()+ registry.start_load_async.assert_not_awaited()++ # Config arrives -> add_config schedules a background eager-load reconcile.+ registry.add_config(_make_config(name="late/model", hf_id="late/hf"))+ await _drain_background_tasks(registry)++ registry.start_load_async.assert_any_await("late/model", "cpu")++ async def test_add_config_ignores_non_pinned_model(self) -> None:+ registry = ModelRegistry(pinned_models=["pinned/model"])+ registry.start_load_async = AsyncMock(return_value=True) # type: ignore[method-assign]++ registry.add_config(_make_config(name="other/model", hf_id="other/hf"))+ await _drain_background_tasks(registry)++ registry.start_load_async.assert_not_awaited()++ @patch("sie_server.core.model_loader.load_adapter")+ async def test_replace_configs_reloads_changed_pinned_model(+ self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock+ ) -> None:+ # P1b: replace_configs_async unloads a changed pinned model; it must reload it.+ mock_load_adapter.side_effect = [mock_adapter_factory(), mock_adapter_factory()]+ registry = ModelRegistry(pinned_models=["org/model"])+ registry.add_config(_make_config(name="org/model", hf_id="org/model-hf"))+ await registry.load_async("org/model", "cpu")+ assert registry.is_loaded("org/model")++ # Replace with a semantically-changed config (different dim) -> unload + reload.+ await registry.replace_configs_async([_make_config(name="org/model", hf_id="org/model-hf", dense_dim=512)])+ await _drain_background_tasks(registry)++ assert registry.is_loaded("org/model")++ @patch("sie_server.core.model_loader.load_adapter")+ async def test_replace_configs_loads_newly_known_pinned_model(+ self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock+ ) -> None:+ # P1b: a pin whose config first appears via replace_configs must load.+ mock_load_adapter.return_value = mock_adapter_factory()+ registry = ModelRegistry(pinned_models=["org/model"])++ await registry.replace_configs_async([_make_config(name="org/model", hf_id="org/model-hf")])+ await _drain_background_tasks(registry)++ assert registry.is_loaded("org/model")++ @pytest.fixture+ def mock_adapter_factory(self) -> MagicMock:+ def make_mock():+ mock = MagicMock()+ mock.capabilities.outputs = ["dense"]+ mock.memory_footprint.return_value = 1_000_000+ return mock++ return make_mockdiff --git a/packages/sie_server/tests/core/test_registry_memory.py b/packages/sie_server/tests/core/test_registry_memory.pyindex 6961a38f4..544caa168 100644--- a/packages/sie_server/tests/core/test_registry_memory.py+++ b/packages/sie_server/tests/core/test_registry_memory.py@@ -200,6 +200,146 @@ class TestRegistryMemoryManagerIntegration:adapter_a.unload.assert_not_called()+class TestRegistryPinnedModels:+ """Tests for pinned-model LRU/OOM protection."""++ @pytest.fixture+ def mock_adapter_factory(self) -> MagicMock:+ def make_mock():+ mock = MagicMock()+ mock.capabilities.outputs = ["dense"]+ return mock++ return make_mock++ @patch("sie_server.core.model_loader.load_adapter")+ def test_empty_pinned_set_unchanged(self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock) -> None:+ """pinned_models=None preserves true LRU behaviour (regression guard)."""+ mock_load_adapter.side_effect = [mock_adapter_factory(), mock_adapter_factory()]++ registry = ModelRegistry(pinned_models=None)+ for name in ["model-a", "model-b"]:+ config = _make_config(name=name, hf_id=f"org/{name}")+ registry.add_config(config)+ registry.load(name, device="cpu")++ # model-a loaded first, so it is the LRU+ assert registry.memory_manager.get_lru_model() == "model-a"++ @patch("sie_server.core.model_loader.load_adapter")+ def test_oom_evicts_non_pinned_keeps_pinned(+ self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock+ ) -> None:+ """OOM during load evicts the oldest non-pinned model, never the pinned one."""+ adapter_pinned = mock_adapter_factory()+ adapter_nonpinned = mock_adapter_factory()++ # Third adapter fails OOM on first try+ adapter_c_fail = mock_adapter_factory()+ adapter_c_fail.load.side_effect = RuntimeError("CUDA out of memory")++ # Retry adapter succeeds+ adapter_c_success = mock_adapter_factory()++ mock_load_adapter.side_effect = [adapter_pinned, adapter_nonpinned, adapter_c_fail, adapter_c_success]++ # pinned is "model-pinned", loaded first (oldest)+ registry = ModelRegistry(pinned_models=["model-pinned"])+ for name in ["model-pinned", "model-non-pinned", "model-c"]:+ config = _make_config(name=name, hf_id=f"org/{name}")+ registry.add_config(config)++ registry.load("model-pinned", device="cuda:0")+ registry.load("model-non-pinned", device="cuda:0")++ # model-pinned is LRU but pinned; OOM must evict model-non-pinned instead+ assert registry.memory_manager.get_lru_model() == "model-pinned"++ registry.load("model-c", device="cuda:0")++ # Pinned model stays; non-pinned was evicted+ assert registry.is_loaded("model-pinned")+ assert not registry.is_loaded("model-non-pinned")+ assert registry.is_loaded("model-c")+ adapter_pinned.unload.assert_not_called()+ adapter_nonpinned.unload.assert_called_once()++ @patch("sie_server.core.model_loader.load_adapter")+ def test_oom_eviction_skips_pinned(self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock) -> None:+ """When only pinned models are loaded and OOM occurs, the error propagates."""+ adapter_pinned = mock_adapter_factory()+ adapter_fail = mock_adapter_factory()+ adapter_fail.load.side_effect = RuntimeError("CUDA out of memory")++ mock_load_adapter.side_effect = [adapter_pinned, adapter_fail]++ registry = ModelRegistry(pinned_models=["model-pinned"])+ for name in ["model-pinned", "model-other"]:+ config = _make_config(name=name, hf_id=f"org/{name}")+ registry.add_config(config)++ registry.load("model-pinned", device="cuda:0")++ # Only pinned model loaded; OOM must propagate since there is nothing to evict+ with pytest.raises(RuntimeError, match="CUDA out of memory"):+ registry.load("model-other", device="cuda:0")++ # Pinned model must not have been touched+ assert registry.is_loaded("model-pinned")+ adapter_pinned.unload.assert_not_called()++ def test_resolve_model_id_preserves_profile_and_case(self) -> None:+ """resolve_model_id matches the FULL profile-qualified config key; :default folds to base."""+ registry = ModelRegistry()+ registry.add_config(_make_config(name="BAAI/bge-m3", hf_id="BAAI/bge-m3"))+ # Non-default profiles are first-class config entries (loader expands them).+ registry.add_config(_make_config(name="BAAI/bge-m3:fp8", hf_id="BAAI/bge-m3"))++ # Base id (exact + case-insensitive) -> base config.+ assert registry.resolve_model_id("BAAI/bge-m3") == "BAAI/bge-m3"+ assert registry.resolve_model_id("baai/bge-m3") == "BAAI/bge-m3"+ # ":default" folds to the base config (matches the gateway canonicalization).+ assert registry.resolve_model_id("baai/bge-m3:default") == "BAAI/bge-m3"+ # A non-default profile resolves to the VARIANT config, not the base.+ assert registry.resolve_model_id("baai/bge-m3:fp8") == "BAAI/bge-m3:fp8"+ # A profile with no variant config must NOT collapse to the base.+ assert registry.resolve_model_id("baai/bge-m3:missing") is None+ assert registry.resolve_model_id("org/missing") is None++ def test_pinned_disk_repo_ids_maps_sie_id_to_hf_id(self) -> None:+ """_pinned_disk_repo_ids resolves pinned sie_ids to their configs' hf_ids (case-insensitive)."""+ registry = ModelRegistry(pinned_models=["Org/Pinned"])+ registry.add_config(_make_config(name="Org/Pinned", hf_id="org/pinned-hf"))+ registry.add_config(_make_config(name="other/model", hf_id="other/hf"))++ # Only the pinned model's hf_id is returned (the disk cache keys by hf repo id).+ assert registry._pinned_disk_repo_ids() == {"org/pinned-hf"}++ def test_pinned_disk_repo_ids_empty_when_no_pinned_set(self) -> None:+ """No pinned set means no disk-eviction protection (regression guard)."""+ registry = ModelRegistry()+ registry.add_config(_make_config(name="org/model", hf_id="org/model-hf"))+ assert registry._pinned_disk_repo_ids() == set()++ def test_pinned_disk_repo_ids_profile_pin_protects_base_weights(self) -> None:+ """A profile-qualified pin protects the base model's disk weights (shared hf_id)."""+ registry = ModelRegistry(pinned_models=["Org/Model:fp8"])+ # Only the base config is present (the variant config may not have arrived yet);+ # the variant shares the base hf_id, so the base weights must be protected.+ registry.add_config(_make_config(name="Org/Model", hf_id="org/model-hf"))+ assert registry._pinned_disk_repo_ids() == {"org/model-hf"}++ def test_disk_cache_manager_wired_with_pinned_provider(self) -> None:+ """The registry feeds its pinned set into the disk cache manager's eviction guard."""+ registry = ModelRegistry(pinned_models=["org/pinned"])+ registry.add_config(_make_config(name="org/pinned", hf_id="org/pinned-hf"))++ assert registry._disk_cache_manager is not None+ # The callback wired at construction resolves to the pinned models' hf_ids.+ assert registry._disk_cache_manager._pinned_provider is not None+ assert registry._disk_cache_manager._pinned_provider() == {"org/pinned-hf"}++class TestRegistryOOMDetection:"""Tests for _is_oom_error detection."""diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex c62f2bd76..a3d8bd255 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -25,6 +25,7 @@ from sie_server.ipc_types import (ProcessGenerateRequest,ReplaceModelConfigEntry,ReplaceModelConfigsRequest,+ SetPinnedModelsRequest,SignalGenerateCancelRequest,)from sie_server.queue_executor import QueueExecutor@@ -116,6 +117,7 @@ def _make_executor() -> tuple[QueueExecutor, MagicMock]:reg = MagicMock()reg.model_names = ["test/model"]reg.device = "cpu"+ reg.loaded_model_names = ["test/model"]reg.is_loaded.return_value = Truereg.is_loading.return_value = Falsereg.get_config.return_value = MagicMock()@@ -153,6 +155,7 @@ class TestFraming:assert resp["body"]["timestamp_ms"] == 123.0assert resp["body"]["worker_id"] == "worker-test"assert resp["body"]["bundle_config_hash"] == ""+ assert resp["body"]["loaded_models"] == ["test/model"]assert srv.is_heartbeat_fresh()finally:await client.close()@@ -255,6 +258,7 @@ class TestEnsureModelReady:reg.device = "cpu"reg.is_loaded.return_value = Truereg.is_loading.return_value = False+ reg.loaded_model_names = []worker = MagicMock()worker._batch_config = MagicMock(max_batch_requests=42)reg.get_worker.return_value = worker@@ -665,6 +669,48 @@ profiles:assert registry.has_model("tenant/model")+# -----------------------------------------------------------------------------+# SetPinnedModels+# -----------------------------------------------------------------------------+++class TestSetPinnedModels:+ @pytest.mark.asyncio+ async def test_executor_passthrough_returns_count(self) -> None:+ registry = ModelRegistry(models_dir=None)+ registry.start_load_async = AsyncMock(return_value=True) # type: ignore[method-assign]+ executor = QueueExecutor(registry)++ resp = await executor.set_pinned_models(SetPinnedModelsRequest(models=["org/a", "org/b"]))++ assert resp.applied is True+ assert resp.pinned_count == 2+ assert registry._pinned_models == frozenset({"org/a", "org/b"})++ @pytest.mark.asyncio+ async def test_set_pinned_models_roundtrip_over_ipc(self) -> None:+ registry = ModelRegistry(models_dir=None)+ registry.start_load_async = AsyncMock(return_value=True) # type: ignore[method-assign]+ executor = QueueExecutor(registry)++ 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("SetPinnedModels", {"models": ["org/a:fast", "Org/B"]})+ assert resp["ok"] is True+ assert resp["body"]["applied"] is True+ assert resp["body"]["pinned_count"] == 2+ # Lowercased; non-default profile preserved, base kept as-is.+ assert registry._pinned_models == frozenset({"org/a:fast", "org/b"})+ finally:+ await client.close()+ finally:+ await srv.stop(drain_timeout_s=1.0)++# -----------------------------------------------------------------------------# ProcessEncodeBatch# -----------------------------------------------------------------------------diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lockindex e043e1bdd..a93b21a81 100644--- a/packages/sie_server_sidecar/Cargo.lock+++ b/packages/sie_server_sidecar/Cargo.lock@@ -2208,7 +2208,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-server-sidecar"-version = "0.6.10"+version = "0.6.11"dependencies = ["anyhow","async-nats",diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex b991312df..03ad25d01 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.10"+version = "0.6.11"edition = "2021"description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 206d076cc..e83fe443f 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -68,6 +68,10 @@ Message settlement:- Malformed subjects and bad msgpack payloads are NAKed.- Unknown operations publish per-item error outcomes when reply publicationsucceeds.+- Active local model loads are held with JetStream progress ACKs until+ `EnsureModelReady` returns ready; this preserves the delivery budget during+ cold starts. The progress delay is clamped below the pool consumer `ack_wait`+ even if the retry NAK delay is configured higher.- Transient backend, decode, stream, and drain failures are NAKed.- Reply publication failure leaves the JetStream message unacked.@@ -107,8 +111,9 @@ subject tokens by the gateway and sidecar helpers.The sidecar creates one long-lived async-nats pull stream for pool work. A slowreconciler re-ensures stream and durable metadata outside the fetch loop.-When generation direct dispatch is active, the sidecar also creates and polls-the worker-specific generation stream and subscribes to `cancel.>`.+The sidecar also creates and polls the worker-specific direct-dispatch stream.+Generation uses that stream for HRW placement; capped logical batch pools use it+when the gateway must target one assigned worker on a shared backing queue.Source: [`nats_consumer.rs`](../src/nats_consumer.rs),[`subject.rs`](../src/subject.rs), and the gateway@@ -117,8 +122,16 @@ Source: [`nats_consumer.rs`](../src/nats_consumer.rs),## Pool AdmissionWhen `SIE_GATEWAY_URL` is configured and pool admission is enabled, the sidecar-checks gateway pool status before pulling from the pool stream or the-worker-specific generation stream.+polls `GET /v1/pools` before pulling from the pool stream or the+worker-specific direct-dispatch stream. It may pull when its physical `SIE_POOL` is+admitted directly, or when at least one assigned logical pool is backed by that+same queue; each work item is then checked against its `admission_pool` before+Python IPC. The gateway normally direct-dispatches capped logical batch work to+an assigned worker, so unassigned peers do not spend the item's JetStream+delivery budget. Work items rejected by this per-item logical gate are still+NAKed and counted in `sie_worker_pool_admission_naks_total` as a defensive+backstop for stale assignments, direct NATS publishes, and rolling-version+mismatches.Capped named pools require the worker to appear in`status.assigned_workers`. The default pool continues pulling during transient@@ -136,10 +149,6 @@ subject. Worker-specific routing uses HRW over eligible workers. The gatewaystores a pool fallback subject for streaming work and uses it for republishpaths such as NAK handling and first-chunk timeout handling.-The sidecar starts generation direct dispatch after `WorkerCapabilities`-reports generation models. The generation capability reconciler repeats that-probe after live config apply when direct dispatch is not active.-The sidecar subscribes to `cancel.>`. Subjects shaped as`cancel.{router_id}.{request_id}` are forwarded to Python through`SignalGenerateCancel`.@@ -177,6 +186,9 @@ The Rust and Python protocol copies define the same method names:`EnsureModelReady` returns readiness state and an optional `ModelDescriptor`.The descriptor carries tokenizer path, tokenizer content hash, maximum sequencelength, output types, default text templates, and `supports_run_batch`.+`loading_started` and `loading_in_progress` mean the same worker is actively+loading the model; the dispatcher progress-ACKs and rechecks instead of NAKing+those deliveries. `retry_later` remains a NAK path.Source: [`protocol/ipc_types.rs`](../src/protocol/ipc_types.rs),[`ipc_client.rs`](../src/ipc_client.rs), and@@ -232,7 +244,9 @@ The sidecar HTTP server exposes:Readiness state is shared with the NATS health publisher. The health publisheremits worker identity, bundle, machine profile, readiness, and the current-bundle config hash.+bundle config hash. It also mirrors the latest `loaded_models` list reported by+the Python IPC heartbeat so gateway pool/model gauges reflect live residency in+NATS health mode.Source: [`metrics.rs`](../src/metrics.rs),[`readiness.rs`](../src/readiness.rs), anddiff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rsindex 0f16fd43a..69c8e7151 100644--- a/packages/sie_server_sidecar/src/config.rs+++ b/packages/sie_server_sidecar/src/config.rs@@ -47,8 +47,10 @@ pub struct WorkerConfig {pub payload_store_url: Option<String>,/// Optional gateway URL used by the worker-side pool admission gate.- /// When set and admission is enabled, the sidecar asks- /// `/v1/pools/{pool}` before pulling from NATS.+ /// When set and admission is enabled, the sidecar polls `/v1/pools`+ /// before pulling from NATS so it can enforce both the physical+ /// `SIE_POOL` assignment and logical `admission_pool` assignments backed+ /// by that queue.pub gateway_url: Option<String>,/// Optional bearer token for gateway pool-status reads.diff --git a/packages/sie_server_sidecar/src/config_reconciler.rs b/packages/sie_server_sidecar/src/config_reconciler.rsindex 7e8e64926..737a9ce6c 100644--- a/packages/sie_server_sidecar/src/config_reconciler.rs+++ b/packages/sie_server_sidecar/src/config_reconciler.rs@@ -14,7 +14,6 @@ use std::sync::Arc;use std::time::{Duration, Instant};use serde::Deserialize;-use tokio::sync::Notify;use tokio::task::JoinHandle;use tokio::time::interval;use tracing::{debug, info, warn};@@ -253,7 +252,6 @@ pub fn spawn(state: Arc<ConfigApplyState>,metrics: Arc<MetricsRegistry>,shutdown: Arc<Shutdown>,- generation_reconcile: Option<Arc<Notify>>,) -> Option<JoinHandle<()>> {let config = config?;if config.base_url.trim().is_empty() {@@ -305,11 +303,6 @@ pub fn spawn(if let Some(signature) = outcome.export_signature {last_export_signature = Some(signature);}- if outcome.applied > 0 {- if let Some(notify) = generation_reconcile.as_ref() {- notify.notify_one();- }- }info!(epoch = outcome.epoch,applied = outcome.applied,@@ -406,11 +399,6 @@ pub fn spawn(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();- }- }info!(epoch = outcome.epoch,applied = outcome.applied,diff --git a/packages/sie_server_sidecar/src/config_subscriber.rs b/packages/sie_server_sidecar/src/config_subscriber.rsindex d4c3020c5..82ae9704d 100644--- a/packages/sie_server_sidecar/src/config_subscriber.rs+++ b/packages/sie_server_sidecar/src/config_subscriber.rs@@ -14,7 +14,7 @@ use std::sync::{Arc, RwLock};use async_nats::Client;use futures_util::StreamExt;use serde::{Deserialize, Serialize};-use tokio::sync::{Mutex, MutexGuard, Notify};+use tokio::sync::{Mutex, MutexGuard};use tokio::task::JoinHandle;use tokio::time::{sleep, Duration};use tracing::{debug, info, warn};@@ -232,7 +232,6 @@ pub fn trusted_producers_from_env() -> Vec<String> {#[derive(Debug, Clone)]pub struct ConfigSubscriberOptions {pub trusted_producers: Vec<String>,- pub generation_reconcile: Option<Arc<Notify>>,}struct SubscriberRuntime {@@ -242,7 +241,6 @@ struct SubscriberRuntime {state: Arc<ConfigApplyState>,metrics: Arc<MetricsRegistry>,shutdown: Arc<Shutdown>,- generation_reconcile: Option<Arc<Notify>>,}pub fn bundle_subject(bundle: &str) -> Result<String, String> {@@ -343,7 +341,6 @@ pub fn spawn(state,metrics,shutdown,- generation_reconcile: options.generation_reconcile,};if runtime.trusted_producers.is_empty() {@@ -668,9 +665,6 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotstate.mark_applied(notification.epoch, applied_bundle_hash);metrics.config_epoch.set(notification.epoch as i64);- if let Some(notify) = runtime.generation_reconcile.as_ref() {- notify.notify_one();- }}#[cfg(test)]diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 1b21da05f..7cff90c22 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -14,7 +14,7 @@use std::collections::{BTreeMap, HashMap, HashSet};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;-use std::time::Instant;+use std::time::{Duration, Instant};use async_nats::jetstream::Message;use futures_util::future::join_all;@@ -37,6 +37,7 @@ use crate::latency::LatencyTracker;use crate::log_util::ErrChain;use crate::metrics::MetricsRegistry;use crate::payload_store::{PayloadError, PayloadStore};+use crate::pool_admission::PoolAdmissionGate;use crate::publisher::{should_publish, Timings, WorkPublisher};use crate::scheduler::{lora_from_options, Op as SchedOp, ProductionScheduler, ProductionSchedulerRegistry,@@ -47,6 +48,26 @@ use crate::subject::extract_model_id;use crate::tokenize::TokenizerRegistry;use crate::work_types::WorkItem;+const MODEL_LOADING_ERROR_CODE: &str = "MODEL_LOADING";++#[derive(serde::Serialize)]+struct GenerateTerminalErrorChunk<'a> {+ kind: &'static str,+ request_id: &'a str,+ attempt_id: String,+ seq: u32,+ text_delta: &'static str,+ done: bool,+ finish_reason: &'static str,+ error: GenerateTerminalError<'a>,+}++#[derive(serde::Serialize)]+struct GenerateTerminalError<'a> {+ code: &'a str,+ message: &'a str,+}+#[derive(Debug, Clone)]struct DeliveryContext {subject: String,@@ -94,14 +115,14 @@ struct GenerateDeliveryLogContext {delivery: DeliveryContext,}-/// Base NAK delay in milliseconds. Mirrors Python's `_NAK_DELAY_S`+/// Base retry delay in milliseconds. Mirrors Python's `_NAK_DELAY_S`/// (default 5 000 ms, overridable via `SIE_NAK_DELAY_S`). Used for:///-/// * `loading_started` readiness (just kicked off a load)/// * `retry_later` readiness (unknown error path)/// * generic transient IPC / executor failures///-/// `loading_in_progress` uses `2 × base`.+/// Local model-loading waits use JetStream progress ACKs instead of NAKs, with+/// `loading_in_progress` sleeping for `2 × base` between readiness probes.pub(crate) fn base_nak_delay_ms() -> u64 {std::env::var("SIE_NAK_DELAY_S").ok()@@ -122,6 +143,7 @@ const NAK_DELAY_OVERFLOW_MS: u64 = 100;/// `base_nak_delay_ms` (~5s) that is intended for transient retryable/// errors. Holding the message back longer just starves redelivery.const NAK_DELAY_DRAINING_MS: u64 = 100;+const READINESS_PROGRESS_ACK_WAIT_FRACTION: u64 = 2;/// Pick the right NAK delay for a given backend error — `Draining` is/// fast because we want redelivery to another worker, everything else@@ -133,6 +155,21 @@ pub(crate) fn nak_delay_for_backend_error(err: &BackendError) -> u64 {}}+fn readiness_progress_delay_ms(state: &ReadinessState, base_delay_ms: u64) -> Option<u64> {+ let max_delay_ms = crate::nats_consumer::ACK_WAIT_SECS+ .saturating_mul(1000)+ .checked_div(READINESS_PROGRESS_ACK_WAIT_FRACTION)+ .unwrap_or(1)+ .max(1);+ match state {+ ReadinessState::LoadingStarted => Some(base_delay_ms.min(max_delay_ms)),+ ReadinessState::LoadingInProgress => {+ Some(base_delay_ms.saturating_mul(2).min(max_delay_ms))+ }+ ReadinessState::Ready | ReadinessState::RetryLater => None,+ }+}+/// Reply subjects must live under `_INBOX.` (NATS conventions). Non-empty/// subjects outside this prefix are rejected as a crude anti-injection/// check — a malicious producer could otherwise aim results at an@@ -302,6 +339,9 @@ pub struct Dispatcher {/// Current sidecar-applied bundle config state. Shared with the live config/// subscriber/reconciler and NATS health publisher.pub config_apply_state: Option<Arc<ConfigApplyState>>,+ /// Optional admission gate for both the physical queue and logical+ /// `admission_pool` labels carried on default-backed work items.+ pub pool_admission: Option<Arc<PoolAdmissionGate>>,/// Per-model scheduler drain handles, populated lazily when a/// new scheduler is materialised on first traffic. The shutdown/// path in `lib.rs` drains this map and awaits every handle so@@ -335,6 +375,7 @@ impl Dispatcher {scheduler_registry: Option<Arc<ProductionSchedulerRegistry>>,shutdown: Option<Arc<Shutdown>>,config_apply_state: Option<Arc<ConfigApplyState>>,+ pool_admission: Option<Arc<PoolAdmissionGate>>,) -> Self {debug_assert_eq!(scheduler_registry.is_some(),@@ -353,6 +394,7 @@ impl Dispatcher {scheduler_registry,shutdown,config_apply_state,+ pool_admission,scheduler_drain_handles: Arc::new(Mutex::new(HashMap::new())),generation_handles: Arc::new(Mutex::new(Vec::new())),}@@ -463,6 +505,24 @@ impl Dispatcher {}continue;}+ if let Some(gate) = self.pool_admission.as_ref() {+ let admission_pool = wi.admission_pool.trim();+ if !gate.admits_work_item_pool(admission_pool) {+ debug!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ admission_pool = %admission_pool,+ physical_pool = %wi.pool_name,+ "WorkItem admission_pool does not assign this worker — NAKing for redelivery"+ );+ self.metrics+ .pool_admission_naks_total+ .with_label_values(&["logical_pool_not_assigned"])+ .inc();+ nak_one(&msg, base_delay_ms, &self.metrics).await;+ continue;+ }+ }if wi.model_id != subject_model {warn!(work_item_id = %wi.work_item_id,@@ -607,7 +667,71 @@ impl Dispatcher {};match &readiness_resp.state {ReadinessState::Ready => {}- ReadinessState::LoadingStarted | ReadinessState::RetryLater => {+ ReadinessState::LoadingStarted => {+ info!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ readiness = ?readiness_resp.state,+ delay_ms = base_delay_ms,+ subject = %delivery.subject,+ stream = %delivery.stream,+ consumer = %delivery.consumer,+ stream_seq = delivery.stream_sequence,+ consumer_seq = delivery.consumer_sequence,+ delivery_count = delivery.delivered,+ pending = delivery.pending,+ "generate model started loading — publishing MODEL_LOADING chunk + ACK"+ );+ let message = format!("Model '{model_id}' is loading; retry later.");+ match self+ .publish_generate_terminal_error(&wi, MODEL_LOADING_ERROR_CODE, &message)+ .await+ {+ Ok(_) => match ack(&msg).await {+ Ok(()) => {+ self.metrics.messages_acked_total.inc();+ self.metrics+ .generate_model_loading_responses_total+ .with_label_values(&[+ &model_lbl,+ "loading_started",+ "published_acked",+ ])+ .inc();+ }+ Err(e) => {+ warn!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ stream_seq = delivery.stream_sequence,+ delivery_count = delivery.delivered,+ error = %e,+ "ack after MODEL_LOADING chunk publish failed"+ );+ self.metrics.jetstream_ack_failures_total.inc();+ self.metrics+ .generate_model_loading_responses_total+ .with_label_values(&[+ &model_lbl,+ "loading_started",+ "published_ack_failed",+ ])+ .inc();+ }+ },+ Err(_) => {+ self.metrics+ .generate_model_loading_responses_total+ .with_label_values(&[&model_lbl, "loading_started", "publish_failed"])+ .inc();+ nak_one(&msg, base_delay_ms, &self.metrics).await;+ }+ }+ return;+ }+ ReadinessState::RetryLater => {info!(work_item_id = %wi.work_item_id,request_id = %wi.request_id,@@ -621,13 +745,14 @@ impl Dispatcher {consumer_seq = delivery.consumer_sequence,delivery_count = delivery.delivered,pending = delivery.pending,- "generate model not ready — NAKing"+ "generate model retry requested — NAKing");nak_one(&msg, base_delay_ms, &self.metrics).await;return;}ReadinessState::LoadingInProgress => {- let delay_ms = base_delay_ms.saturating_mul(2);+ let delay_ms = readiness_progress_delay_ms(&readiness_resp.state, base_delay_ms)+ .unwrap_or_else(|| base_delay_ms.saturating_mul(2));info!(work_item_id = %wi.work_item_id,request_id = %wi.request_id,@@ -641,9 +766,58 @@ impl Dispatcher {consumer_seq = delivery.consumer_sequence,delivery_count = delivery.delivered,pending = delivery.pending,- "generate model still loading — NAKing"+ "generate model still loading — publishing MODEL_LOADING chunk + ACK");- nak_one(&msg, delay_ms, &self.metrics).await;+ let message = format!("Model '{model_id}' is still loading; retry later.");+ match self+ .publish_generate_terminal_error(&wi, MODEL_LOADING_ERROR_CODE, &message)+ .await+ {+ Ok(_) => match ack(&msg).await {+ Ok(()) => {+ self.metrics.messages_acked_total.inc();+ self.metrics+ .generate_model_loading_responses_total+ .with_label_values(&[+ &model_lbl,+ "loading_in_progress",+ "published_acked",+ ])+ .inc();+ }+ Err(e) => {+ warn!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ stream_seq = delivery.stream_sequence,+ delivery_count = delivery.delivered,+ error = %e,+ "ack after MODEL_LOADING chunk publish failed"+ );+ self.metrics.jetstream_ack_failures_total.inc();+ self.metrics+ .generate_model_loading_responses_total+ .with_label_values(&[+ &model_lbl,+ "loading_in_progress",+ "published_ack_failed",+ ])+ .inc();+ }+ },+ Err(_) => {+ self.metrics+ .generate_model_loading_responses_total+ .with_label_values(&[+ &model_lbl,+ "loading_in_progress",+ "publish_failed",+ ])+ .inc();+ nak_one(&msg, delay_ms, &self.metrics).await;+ }+ }return;}}@@ -867,72 +1041,85 @@ impl Dispatcher {nak_all(&items, base_delay_ms, &self.metrics).await;return Ok(());}- // `ipc_requests_total` / `ipc_failures_total` identify the IPC- // transport counters even though the backend trait is generic (see- // `crate::backend::InferenceBackend`).- self.metrics.ipc_requests_total.inc();- let readiness_resp = match self.backend.ensure_model_ready(model_id).await {- Ok(r) => r,- Err(e) => {- self.metrics.ipc_failures_total.inc();- warn!(+ let readiness_resp = loop {+ // `ipc_requests_total` / `ipc_failures_total` identify the IPC+ // transport counters even though the backend trait is generic (see+ // `crate::backend::InferenceBackend`).+ self.metrics.ipc_requests_total.inc();+ let readiness_resp = match self.backend.ensure_model_ready(model_id).await {+ Ok(r) => r,+ Err(e) => {+ self.metrics.ipc_failures_total.inc();+ warn!(+ model = %model_id,+ group_size,+ error = %ErrChain(&e),+ "EnsureModelReady failed — NAKing group"+ );+ nak_all(&items, base_delay_ms, &self.metrics).await;+ return Err(e.into());+ }+ };+ if readiness_resp.state == ReadinessState::Ready {+ break readiness_resp;+ }+ if let Some(delay_ms) =+ readiness_progress_delay_ms(&readiness_resp.state, base_delay_ms)+ {+ info!(model = %model_id,group_size,- error = %ErrChain(&e),- "EnsureModelReady failed — NAKing group"+ readiness = ?readiness_resp.state,+ delay_ms,+ "model loading — progress ACKing group before retry");- nak_all(&items, base_delay_ms, &self.metrics).await;- return Err(e.into());+ if !progress_all(&items, &self.metrics).await {+ nak_all(&items, base_delay_ms, &self.metrics).await;+ return Ok(());+ }+ if self.sleep_or_shutdown(delay_ms).await {+ warn!(+ model = %model_id,+ group_size,+ "shutdown while waiting for model load — NAKing group"+ );+ nak_all(&items, NAK_DELAY_DRAINING_MS, &self.metrics).await;+ return Ok(());+ }+ continue;}+ info!(model = %model_id, "model not available — NAKing group");+ nak_all(&items, base_delay_ms, &self.metrics).await;+ return Ok(());};- match readiness_resp.state {- ReadinessState::Ready => {- // Adapter handshake: fold the adapter's `ModelDescriptor`- // (if any) into our local registries. Idempotent on- // re-handshake — the registry hashes the loaded- // tokenizer.json and short-circuits if the declared- // `tokenizer_id` already matches what's cached.- if let Some(descriptor) = readiness_resp.descriptor.as_ref() {- match self- .tokenizer_registry- .register_from_descriptor(model_id, descriptor)- {- Ok(true) => {- debug!(- model = %model_id,- "rust-tokenize: registered tokeniser from EnsureModelReady descriptor"- );- }- Ok(false) => {} // no path, idempotent, or hash mismatch (warning logged inside)- Err(e) => {- // Non-fatal: model just falls back to Python- // tokenisation, exactly the same as if no- // descriptor had been declared at all.- warn!(- model = %model_id,- error = %e,- "rust-tokenize: descriptor load failed — Python will tokenise this model"- );- }- }++ // Adapter handshake: fold the adapter's `ModelDescriptor`+ // (if any) into our local registries. Idempotent on+ // re-handshake — the registry hashes the loaded+ // tokenizer.json and short-circuits if the declared+ // `tokenizer_id` already matches what's cached.+ if let Some(descriptor) = readiness_resp.descriptor.as_ref() {+ match self+ .tokenizer_registry+ .register_from_descriptor(model_id, descriptor)+ {+ Ok(true) => {+ debug!(+ model = %model_id,+ "rust-tokenize: registered tokeniser from EnsureModelReady descriptor"+ );+ }+ Ok(false) => {} // no path, idempotent, or hash mismatch (warning logged inside)+ Err(e) => {+ // Non-fatal: model just falls back to Python+ // tokenisation, exactly the same as if no+ // descriptor had been declared at all.+ warn!(+ model = %model_id,+ error = %e,+ "rust-tokenize: descriptor load failed — Python will tokenise this model"+ );}- }- ReadinessState::LoadingStarted => {- info!(model = %model_id, "model load started — NAKing group for retry");- nak_all(&items, base_delay_ms, &self.metrics).await;- return Ok(());- }- ReadinessState::LoadingInProgress => {- // 2× base so we don't burn through max_deliver while a slow- // model is loading (Python uses the same multiplier).- info!(model = %model_id, "model load in progress — NAKing group with 2x delay");- nak_all(&items, base_delay_ms.saturating_mul(2), &self.metrics).await;- return Ok(());- }- ReadinessState::RetryLater => {- info!(model = %model_id, "model not available — NAKing group");- nak_all(&items, base_delay_ms, &self.metrics).await;- return Ok(());}}@@ -1413,6 +1600,18 @@ impl Dispatcher {Ok(())}+ async fn sleep_or_shutdown(&self, delay_ms: u64) -> bool {+ let delay = Duration::from_millis(delay_ms);+ let Some(shutdown) = self.shutdown.as_ref() else {+ tokio::time::sleep(delay).await;+ return false;+ };+ tokio::select! {+ _ = tokio::time::sleep(delay) => false,+ _ = shutdown.wait() => true,+ }+ }+// -- outcome / publish helpers ---------------------------------------async fn apply_outcomes(&self, outcome: BatchOutcome, resolved: Vec<(WorkItem, Message, f64)>) {@@ -1669,6 +1868,46 @@ impl Dispatcher {}}+ /// Publish a terminal generation chunk error on `wi.reply_subject`.+ ///+ /// Generation requests are tracked by the gateway's streaming collector, so+ /// a one-shot `WorkResult` would not unblock the client. Use the same chunk+ /// envelope Python's `StreamingProcessor` emits for terminal pre-execution+ /// errors.+ async fn publish_generate_terminal_error(+ &self,+ wi: &WorkItem,+ code: &str,+ message: &str,+ ) -> Result<bool, crate::publisher::PublishError> {+ if wi.reply_subject.is_empty() {+ debug!(+ work_item_id = %wi.work_item_id,+ "skipping generate terminal error publish — empty reply_subject"+ );+ return Ok(true);+ }+ let payload = encode_generate_terminal_error_chunk(wi, code, message)?;+ match self.publisher.publish_raw(&wi.reply_subject, payload).await {+ Ok(()) => Ok(true),+ Err(crate::publisher::PublishError::EmptyReplySubject) => {+ debug!(+ work_item_id = %wi.work_item_id,+ "skipping generate terminal error publish — empty reply_subject"+ );+ Ok(true)+ }+ Err(e) => {+ warn!(+ work_item_id = %wi.work_item_id,+ error = %e,+ "failed to publish generate terminal error chunk"+ );+ Err(e)+ }+ }+ }+// -- scheduler -------------------------------------------------------/// Return the per-model [`ProductionScheduler`] when@@ -2231,6 +2470,24 @@ fn truncate(s: &str, n: usize) -> &str {}}+fn encode_generate_terminal_error_chunk(+ wi: &WorkItem,+ code: &str,+ message: &str,+) -> Result<Vec<u8>, rmp_serde::encode::Error> {+ let chunk = GenerateTerminalErrorChunk {+ kind: "chunk",+ request_id: &wi.request_id,+ attempt_id: format!("{}:model-loading", wi.work_item_id),+ seq: 0,+ text_delta: "",+ done: true,+ finish_reason: "error",+ error: GenerateTerminalError { code, message },+ };+ rmp_serde::to_vec_named(&chunk)+}+async fn handle_generate_event(event: GenerateEvent,publisher: Arc<WorkPublisher>,@@ -2386,6 +2643,30 @@ async fn nak_one(msg: &Message, delay_ms: u64, metrics: &MetricsRegistry) {}}+async fn progress_all(items: &[(WorkItem, Message)], metrics: &MetricsRegistry) -> bool {+ let mut all_ok = true;+ for (_, m) in items {+ if !progress_one(m, metrics).await {+ all_ok = false;+ }+ }+ if all_ok {+ debug!(count = items.len(), "progress ACKed group");+ }+ all_ok+}++async fn progress_one(msg: &Message, metrics: &MetricsRegistry) -> bool {+ match msg.ack_with(async_nats::jetstream::AckKind::Progress).await {+ Ok(()) => true,+ Err(e) => {+ warn!(error = %e, "progress ack failed");+ metrics.jetstream_ack_failures_total.inc();+ false+ }+ }+}+// -----------------------------------------------------------------------------// Scheduler drain loop// -----------------------------------------------------------------------------@@ -3004,6 +3285,7 @@ mod tests {profile_id: String::new(),engine: String::new(),pool_name: "l4".into(),+ admission_pool: String::new(),machine_profile: String::new(),item: Some(text_item("x")),payload_ref: None,@@ -3028,6 +3310,43 @@ mod tests {}}+ #[test]+ fn generate_terminal_error_chunk_uses_streaming_wire_shape() {+ #[derive(serde::Deserialize)]+ struct DecodedChunk {+ kind: String,+ request_id: String,+ attempt_id: String,+ seq: u32,+ text_delta: String,+ done: bool,+ finish_reason: String,+ error: DecodedError,+ }++ #[derive(serde::Deserialize)]+ struct DecodedError {+ code: String,+ message: String,+ }++ let work = wi("req-load", 0, "Qwen/Qwen3-4B-Instruct-2507", "generate");+ let bytes =+ encode_generate_terminal_error_chunk(&work, MODEL_LOADING_ERROR_CODE, "loading")+ .expect("chunk encodes");+ let decoded: DecodedChunk = rmp_serde::from_slice(&bytes).expect("chunk decodes");++ assert_eq!(decoded.kind, "chunk");+ assert_eq!(decoded.request_id, "req-load");+ assert_eq!(decoded.attempt_id, "req-load.0:model-loading");+ assert_eq!(decoded.seq, 0);+ assert_eq!(decoded.text_delta, "");+ assert!(decoded.done);+ assert_eq!(decoded.finish_reason, "error");+ assert_eq!(decoded.error.code, MODEL_LOADING_ERROR_CODE);+ assert_eq!(decoded.error.message, "loading");+ }+#[tokio::test]async fn offloaded_generate_blob_with_base64_images_resolves_via_object_store() {use crate::payload_store::LocalPayloadStore;@@ -3311,6 +3630,40 @@ mod tests {);}+ #[test]+ fn readiness_progress_delay_only_covers_local_loading_states() {+ assert_eq!(+ readiness_progress_delay_ms(&ReadinessState::LoadingStarted, 5_000),+ Some(5_000)+ );+ assert_eq!(+ readiness_progress_delay_ms(&ReadinessState::LoadingInProgress, 5_000),+ Some(10_000)+ );+ assert_eq!(+ readiness_progress_delay_ms(&ReadinessState::Ready, 5_000),+ None+ );+ assert_eq!(+ readiness_progress_delay_ms(&ReadinessState::RetryLater, 5_000),+ None+ );+ }++ #[test]+ fn readiness_progress_delay_is_clamped_below_pool_ack_wait() {+ let max_progress_delay_ms =+ crate::nats_consumer::ACK_WAIT_SECS * 1_000 / READINESS_PROGRESS_ACK_WAIT_FRACTION;+ assert_eq!(+ readiness_progress_delay_ms(&ReadinessState::LoadingStarted, 20_000),+ Some(max_progress_delay_ms)+ );+ assert_eq!(+ readiness_progress_delay_ms(&ReadinessState::LoadingInProgress, 20_000),+ Some(max_progress_delay_ms)+ );+ }+#[test]fn resolve_outcome_indices_matches_by_wiid_in_arrival_order() {// Happy path: every outcome lines up with exactly one resolveddiff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rsindex 55cf6e33f..a7fc5cb89 100644--- a/packages/sie_server_sidecar/src/health_publisher.rs+++ b/packages/sie_server_sidecar/src/health_publisher.rs@@ -28,11 +28,10 @@//! gate on the local [`Readiness`] state so the heartbeat agrees//! with `/readyz`.//!-//! `loaded_models` and the GPU memory fields are informational; the-//! sidecar does not own a list of model IDs (the adapter does), so-//! we publish an empty list and let the gateway's per-model state-//! reflect what it observes from successful work-result publishes-//! plus its own model registry.+//! `loaded_models` and the GPU memory fields are informational. The+//! sidecar mirrors the adapter-owned loaded-model list from the IPC+//! heartbeat so gateway model/capacity views reflect the live worker+//! registry without adding a second probe path.//!//! [`WorkerStatusMessage`]: https://github.com/search?q=WorkerStatusMessage+repo%3Asie-internal//! [`resolve_queue_route`]: https://github.com/search?q=resolve_queue_route+repo%3Asie-internal@@ -51,6 +50,7 @@ use crate::readiness::Readiness;use crate::shutdown::Shutdown;pub type SharedBundleConfigHash = Arc<RwLock<String>>;+pub type SharedLoadedModels = Arc<RwLock<Vec<String>>>;/// Default subject prefix used by the gateway. Workers always/// publish to `sie.health.<worker_id>` because the gateway's@@ -98,6 +98,8 @@ pub struct HealthPublisherConfig {/// model registry epoch. Updated by the config subscriber after a/// successful Python registry apply.pub bundle_config_hash: SharedBundleConfigHash,+ /// Last loaded-model list observed from the Python IPC heartbeat.+ pub loaded_models: SharedLoadedModels,/// How often to publish. Defaults to [`DEFAULT_PUBLISH_INTERVAL`].pub interval: Duration,}@@ -132,11 +134,7 @@ struct WorkerStatusPayload<'a> {pool_name: &'a str,bundle: &'a str,bundle_config_hash: &'a str,- /// Empty — the sidecar has no authoritative list of loaded- /// models. The adapter knows; surfacing that would require a- /// new IPC round-trip per heartbeat which isn't worth the- /// cost for an informational field.- loaded_models: &'a [&'a str],+ loaded_models: &'a [String],}fn encode_payload(@@ -148,6 +146,17 @@ fn encode_payload(.bundle_config_hash.read().expect("bundle config hash lock poisoned");+ let loaded_models_guard = match config.loaded_models.read() {+ Ok(guard) => Some(guard),+ Err(_) => {+ warn!("loaded_models lock poisoned; publishing empty loaded model list");+ None+ }+ };+ let loaded_models = match &loaded_models_guard {+ Some(guard) => guard.as_slice(),+ None => &[],+ };let payload = WorkerStatusPayload {name: &config.worker_id,ready,@@ -157,7 +166,7 @@ fn encode_payload(pool_name: &config.pool_name,bundle: &config.bundle,bundle_config_hash: hash.as_str(),- loaded_models: &[],+ loaded_models,};serde_json::to_vec(&payload)}@@ -292,6 +301,7 @@ mod tests {machine_profile: "l4".into(),gpu_count: 1,bundle_config_hash: Arc::new(RwLock::new("hash-abc".into())),+ loaded_models: Arc::new(RwLock::new(Vec::new())),interval: DEFAULT_PUBLISH_INTERVAL,}}@@ -362,6 +372,20 @@ mod tests {assert_eq!(json["bundle_config_hash"], "hash-next");}+ #[test]+ fn payload_reads_updated_loaded_models() {+ let c = cfg();+ {+ let mut loaded_models = c.loaded_models.write().unwrap();+ *loaded_models = vec!["BAAI/bge-m3".into()];+ }++ let json: serde_json::Value =+ serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();++ assert_eq!(json["loaded_models"], serde_json::json!(["BAAI/bge-m3"]));+ }+#[test]fn tombstone_payload_marks_not_ready_and_terminated() {let c = cfg();diff --git a/packages/sie_server_sidecar/src/ipc_client.rs b/packages/sie_server_sidecar/src/ipc_client.rsindex 365b8853e..cffedcb73 100644--- a/packages/sie_server_sidecar/src/ipc_client.rs+++ b/packages/sie_server_sidecar/src/ipc_client.rs@@ -50,11 +50,12 @@ use crate::ipc_types::{EnsureModelReadyRequest, EnsureModelReadyResponse, GenerateEvent, PingRequest, PingResponse,ProcessEncodeBatchRequest, ProcessExtractBatchRequest, ProcessGenerateRequest,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,+ RequestEnvelope, ResponseEnvelope, RunBatchRequest, SetPinnedModelsRequest,+ SetPinnedModelsResponse, 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_SET_PINNED_MODELS,METHOD_SIGNAL_GENERATE_CANCEL, METHOD_WORKER_CAPABILITIES,};use crate::log_util::ErrChain;@@ -993,6 +994,14 @@ impl IpcClient {self.call(METHOD_REPLACE_MODEL_CONFIGS, req).await}+ pub async fn set_pinned_models(+ &self,+ models: Vec<String>,+ ) -> Result<SetPinnedModelsResponse, IpcError> {+ self.call(METHOD_SET_PINNED_MODELS, SetPinnedModelsRequest { models })+ .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/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex ac916b24d..a9da24a4c 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -21,6 +21,7 @@ pub mod metrics;pub mod nats_consumer;pub mod output;pub mod payload_store;+pub mod pinned_reconciler;pub mod pool_admission;pub mod prep;pub mod protocol;@@ -33,12 +34,12 @@ pub mod tokenize;pub mod work_types;use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::Arc;+use std::sync::{Arc, RwLock};use std::time::{Duration, Instant};use anyhow::Context;use futures_util::StreamExt;-use tokio::sync::{Mutex, Notify, Semaphore};+use tokio::sync::{Mutex, Semaphore};use tokio::task::JoinHandle;use tokio::time::{interval, sleep, timeout};use tracing::{debug, info, warn};@@ -100,11 +101,6 @@ const NATS_CONSUMER_RECONCILE_INTERVAL_ENV: &str = "SIE_NATS_CONSUMER_RECONCILE_const DEFAULT_NATS_CONSUMER_RECONCILE_INTERVAL_MS: u64 = 30_000;const MIN_NATS_CONSUMER_RECONCILE_INTERVAL_MS: u64 = 10_000;-const GENERATION_CAPABILITY_RECONCILE_INTERVAL_ENV: &str =- "SIE_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS";-const DEFAULT_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS: u64 = 30_000;-const MIN_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS: u64 = 5_000;-fn parse_nats_consumer_reconcile_interval_ms(raw: Option<&str>) -> Option<u64> {match raw.map(str::trim) {Some("0") => None,@@ -127,28 +123,6 @@ fn nats_consumer_reconcile_interval() -> Option<Duration> {.map(Duration::from_millis)}-fn parse_generation_capability_reconcile_interval_ms(raw: Option<&str>) -> Option<u64> {- match raw.map(str::trim) {- Some("0") => None,- Some(value) if !value.is_empty() => value- .parse::<u64>()- .ok()- .filter(|millis| *millis > 0)- .map(|millis| millis.max(MIN_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS))- .or(Some(DEFAULT_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS)),- _ => Some(DEFAULT_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS),- }-}--fn generation_capability_reconcile_interval() -> Option<Duration> {- parse_generation_capability_reconcile_interval_ms(- std::env::var(GENERATION_CAPABILITY_RECONCILE_INTERVAL_ENV)- .ok()- .as_deref(),- )- .map(Duration::from_millis)-}-/// Drain deadline sent to the Python IPC on shutdown.const DRAIN_DEADLINE_MS: u64 = 15_000;@@ -297,6 +271,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {config.ping_interval_ms,config.ready_stale_mult,));+ let loaded_models = Arc::new(RwLock::new(Vec::<String>::new()));info!(ping_interval_ms = config.ping_interval_ms,ready_stale_mult = config.ready_stale_mult,@@ -332,8 +307,6 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {model_ready_timeout_s = config.model_ready_timeout_s,"IPC client initialized with connection pool");- let generation_capable = detect_generation_capable(&ipc).await;-// --- NATSlet (nats_client, jetstream) = connect(&config.nats_url).await.context("connect NATS")?;info!(nats = %config.nats_url, "NATS connected");@@ -376,6 +349,13 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {})});+ // Pinned-model reconciler: polls the pool's PoolSpec.pinned_models and pushes+ // it to the Python worker over IPC. Decoupled from admission so pinned models+ // work even when the admission gate is disabled or fails open.+ let pinned_reconciler_handle =+ crate::pinned_reconciler::spawn(&config, Arc::clone(&ipc), Arc::clone(&shutdown))+ .context("spawn pinned reconciler")?;+// --- Backend router//// The sidecar talks to whichever adapter is co-deployed over IPC;@@ -440,6 +420,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {Some(Arc::clone(&scheduler_registry)),Some(shutdown.clone()),Some(Arc::clone(&config_apply_state)),+ pool_admission.clone(),));let generation_direct_dispatch = Arc::new(GenerationDirectDispatch::new(@@ -454,20 +435,10 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {Arc::clone(&ipc),Arc::clone(&nats_direct_active),));- if generation_capable {- generation_direct_dispatch- .activate("startup")- .await- .context("activate generation direct-dispatch at startup")?;- } else {- info!("generation: no generation models in this bundle; direct-dispatch stream disabled");- }- let generation_capability_reconciler_handle = spawn_generation_capability_reconciler(- Arc::clone(&ipc),- Arc::clone(&generation_direct_dispatch),- shutdown.clone(),- );- let generation_notify = Some(generation_direct_dispatch.reconcile_notifier());+ generation_direct_dispatch+ .activate("startup")+ .await+ .context("activate worker direct-dispatch at startup")?;let config_subscriber_handle = crate::config_subscriber::spawn(nats_client.clone(),@@ -478,7 +449,6 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {shutdown.clone(),crate::config_subscriber::ConfigSubscriberOptions {trusted_producers: config.nats_config_trusted_producers.clone(),- generation_reconcile: generation_notify.clone(),},);let config_reconciler_handle = crate::config_reconciler::spawn(@@ -499,7 +469,6 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {Arc::clone(&config_apply_state),Arc::clone(&metrics_registry),shutdown.clone(),- generation_notify,);// --- Background: heartbeat pings into IPC so /readyz reflects liveness@@ -508,6 +477,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {Duration::from_millis(config.ping_interval_ms),Arc::clone(&readiness),Arc::clone(&config_apply_state),+ Arc::clone(&loaded_models),shutdown.clone(),);@@ -532,6 +502,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {machine_profile: config.machine_profile.clone(),gpu_count: config.gpu_count,bundle_config_hash: config_apply_state.bundle_config_hash(),+ loaded_models: Arc::clone(&loaded_models),interval: Duration::from_millis(config.health_publish_interval_ms),})} else {@@ -609,7 +580,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {h.abort();let _ = h.await;}- if let Some(h) = generation_capability_reconciler_handle {+ if let Some(h) = pinned_reconciler_handle {h.abort();let _ = h.await;}@@ -715,12 +686,12 @@ struct GenerationDirectHandles {cancel: Option<JoinHandle<()>>,}-/// Owns the worker-specific generation stream and cancel subscription.+/// Owns the worker-specific direct-dispatch stream and generation cancel+/// subscription.///-/// Startup detection keeps encode-only workers on the single pool consumer.-/// Live config apply can add a generation model later, so this controller can-/// activate the direct-dispatch path exactly once after WorkerCapabilities-/// reports generation support.+/// The stream is always active: capped logical batch requests can target an+/// assigned worker directly, and generation uses the same worker subject for+/// cache-aware direct dispatch.struct GenerationDirectDispatch {jetstream: async_nats::jetstream::Context,nats_client: async_nats::Client,@@ -732,7 +703,6 @@ struct GenerationDirectDispatch {pool_admission: Option<Arc<PoolAdmissionGate>>,ipc: Arc<IpcClient>,active: Arc<AtomicBool>,- reconcile_notify: Arc<Notify>,handles: Mutex<GenerationDirectHandles>,}@@ -761,19 +731,10 @@ impl GenerationDirectDispatch {pool_admission,ipc,active,- reconcile_notify: Arc::new(Notify::new()),handles: Mutex::new(GenerationDirectHandles::default()),}}- fn is_active(&self) -> bool {- self.active.load(Ordering::Acquire)- }-- fn reconcile_notifier(&self) -> Arc<Notify> {- Arc::clone(&self.reconcile_notify)- }-async fn activate(&self, reason: &str) -> anyhow::Result<bool> {if self.active@@ -785,7 +746,7 @@ impl GenerationDirectDispatch {let worker_consumer = match ensure_worker_stream_and_consumer(&self.jetstream, &self.config).await- .context("ensure generation direct-dispatch stream/consumer")+ .context("ensure worker direct-dispatch stream/consumer"){Ok(consumer) => consumer,Err(e) => {@@ -820,7 +781,7 @@ impl GenerationDirectDispatch {let mut handles = self.handles.lock().await;handles.pull = Some(pull);handles.cancel = Some(cancel);- info!(reason, "generation: direct-dispatch activated");+ info!(reason, "worker direct-dispatch activated");Ok(true)}@@ -877,7 +838,7 @@ fn spawn_nats_consumer_reconciler(Ok(()) => {}Err(e) => warn!(error = %e,- "nats-consumer: generation direct-dispatch reconcile failed"+ "nats-consumer: worker direct-dispatch reconcile failed"),}}@@ -885,128 +846,6 @@ fn spawn_nats_consumer_reconciler(}))}-fn spawn_generation_capability_reconciler(- ipc: Arc<IpcClient>,- direct_dispatch: Arc<GenerationDirectDispatch>,- shutdown: Arc<Shutdown>,-) -> Option<JoinHandle<()>> {- if direct_dispatch.is_active() {- return None;- }- let every = generation_capability_reconcile_interval()?;- Some(tokio::spawn(async move {- info!(- interval_ms = every.as_millis() as u64,- minimum_interval_ms = MIN_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS,- "generation: capability reconciler enabled"- );- loop {- tokio::select! {- biased;- _ = shutdown.wait() => return,- _ = direct_dispatch.reconcile_notify.notified() => {},- _ = sleep(every) => {},- }-- if direct_dispatch.is_active() {- return;- }-- match probe_generation_capable(&ipc).await {- Some(true) => match direct_dispatch.activate("capability_reconcile").await {- Ok(true) => return,- Ok(false) => return,- Err(e) => warn!(- error = %ErrChain(e.as_ref()),- "generation: direct-dispatch activation failed; will retry"- ),- },- Some(false) => {- debug!("generation: WorkerCapabilities still reports no generation models");- }- None => {- debug!("generation: WorkerCapabilities probe unavailable; will retry");- }- }- }- }))-}--async fn detect_generation_capable(ipc: &Arc<IpcClient>) -> bool {- let attempts = worker_capabilities_attempts();- let timeout_ms = worker_capabilities_timeout_ms();- let mut last_error = String::new();- for attempt in 1..=attempts {- match timeout(Duration::from_millis(timeout_ms), ipc.worker_capabilities()).await {- Ok(Ok(capabilities)) => {- info!(- has_generation_models = capabilities.has_generation_models,- generation_models = ?capabilities.generation_models,- "worker capabilities loaded from Python IPC"- );- return capabilities.has_generation_models;- }- Ok(Err(e)) => {- last_error = e.to_string();- }- Err(_) => {- last_error = format!("timeout after {timeout_ms}ms");- }- }- if attempt < attempts {- sleep(Duration::from_millis(200)).await;- }- }- warn!(- attempts,- timeout_ms,- error = %last_error,- "worker capabilities unavailable; enabling generation direct-dispatch conservatively"- );- true-}--async fn probe_generation_capable(ipc: &Arc<IpcClient>) -> Option<bool> {- let timeout_ms = worker_capabilities_timeout_ms();- match timeout(Duration::from_millis(timeout_ms), ipc.worker_capabilities()).await {- Ok(Ok(capabilities)) => {- info!(- has_generation_models = capabilities.has_generation_models,- generation_models = ?capabilities.generation_models,- "generation: WorkerCapabilities reconcile probe complete"- );- Some(capabilities.has_generation_models)- }- Ok(Err(e)) => {- debug!(error = %e, "generation: WorkerCapabilities reconcile probe failed");- None- }- Err(_) => {- debug!(- timeout_ms,- "generation: WorkerCapabilities reconcile probe timed out"- );- None- }- }-}--fn worker_capabilities_attempts() -> usize {- std::env::var("SIE_WORKER_CAPABILITIES_ATTEMPTS")- .ok()- .and_then(|s| s.parse::<usize>().ok())- .filter(|&n| n > 0)- .unwrap_or(30)-}--fn worker_capabilities_timeout_ms() -> u64 {- std::env::var("SIE_WORKER_CAPABILITIES_TIMEOUT_MS")- .ok()- .and_then(|s| s.parse::<u64>().ok())- .filter(|&n| n > 0)- .unwrap_or(1_000)-}-fn spawn_generation_cancel_subscriber(nats_client: async_nats::Client,ipc: Arc<IpcClient>,@@ -1075,6 +914,7 @@ fn spawn_heartbeat(every: Duration,readiness: Arc<Readiness>,config_apply_state: Arc<ConfigApplyState>,+ loaded_models: crate::health_publisher::SharedLoadedModels,shutdown: Arc<Shutdown>,) -> tokio::task::JoinHandle<()> {tokio::spawn(async move {@@ -1099,7 +939,15 @@ fn spawn_heartbeat(if config_apply_state.current_bundle_config_hash().is_empty()&& !resp.bundle_config_hash.is_empty(){- config_apply_state.set_bundle_hash(resp.bundle_config_hash);+ config_apply_state.set_bundle_hash(resp.bundle_config_hash.clone());+ }+ match loaded_models.write() {+ Ok(mut guard) => {+ *guard = resp.loaded_models;+ }+ Err(_) => {+ warn!("loaded_models lock poisoned; NATS health will keep the previous model list");+ }}readiness.record_ping_success();if consecutive_failures > 0 {@@ -1249,11 +1097,12 @@ async fn run_pull_loop('outer: loop {if let Some(gate) = pool_admission.as_ref() {- if !gate.admitted() {+ if !gate.pull_admitted() {// Drop the long-lived pull stream while not admitted. Keeping// it open would leave server-side pull credits active and let// JetStream deliver messages into this client even though this- // worker is outside the pool assignment.+ // worker is outside the physical queue or every assigned+ // logical pool backed by that queue.stream = None;tokio::select! {biased;diff --git a/packages/sie_server_sidecar/src/metrics.rs b/packages/sie_server_sidecar/src/metrics.rsindex 4922e2d64..ac0659951 100644--- a/packages/sie_server_sidecar/src/metrics.rs+++ b/packages/sie_server_sidecar/src/metrics.rs@@ -79,6 +79,7 @@ pub struct MetricsRegistry {pub messages_received_total: IntCounter,pub messages_acked_total: IntCounter,pub messages_naked_total: IntCounter,+ pub pool_admission_naks_total: IntCounterVec,pub ipc_requests_total: IntCounter,pub ipc_failures_total: IntCounter,pub inflight_batches: IntGauge,@@ -87,6 +88,7 @@ pub struct MetricsRegistry {pub pull_batch_process_seconds: HistogramVec,pub pull_nak_unloaded_total: IntCounterVec,pub pull_model_loads_total: IntCounterVec,+ pub generate_model_loading_responses_total: IntCounterVec,// Per-backend visibility. These measure what actually landed in// each backend after routing, so operators can compare native and@@ -193,6 +195,13 @@ impl MetricsRegistry {IntCounter::new("sie_worker_messages_acked_total", "NATS msgs ACKed")?;let messages_naked_total =IntCounter::new("sie_worker_messages_naked_total", "NATS msgs NAKed")?;+ let pool_admission_naks_total = IntCounterVec::new(+ Opts::new(+ "sie_worker_pool_admission_naks_total",+ "Work items NAKed before IPC because this worker is not assigned to the logical admission pool",+ ),+ &["reason"],+ )?;let ipc_requests_total = IntCounter::new("sie_worker_ipc_requests_total", "IPC RPCs sent")?;let ipc_failures_total = IntCounter::new("sie_worker_ipc_failures_total",@@ -233,6 +242,13 @@ impl MetricsRegistry {),&["model"],)?;+ let generate_model_loading_responses_total = IntCounterVec::new(+ Opts::new(+ "sie_worker_generate_model_loading_responses_total",+ "Terminal MODEL_LOADING generation responses emitted by the sidecar before execution",+ ),+ &["model", "state", "result"],+ )?;let backend_process_seconds = HistogramVec::new(HistogramOpts::new(@@ -442,6 +458,7 @@ impl MetricsRegistry {registry.register(Box::new(messages_received_total.clone()))?;registry.register(Box::new(messages_acked_total.clone()))?;registry.register(Box::new(messages_naked_total.clone()))?;+ registry.register(Box::new(pool_admission_naks_total.clone()))?;registry.register(Box::new(ipc_requests_total.clone()))?;registry.register(Box::new(ipc_failures_total.clone()))?;registry.register(Box::new(inflight_batches.clone()))?;@@ -449,6 +466,7 @@ impl MetricsRegistry {registry.register(Box::new(pull_batch_process_seconds.clone()))?;registry.register(Box::new(pull_nak_unloaded_total.clone()))?;registry.register(Box::new(pull_model_loads_total.clone()))?;+ registry.register(Box::new(generate_model_loading_responses_total.clone()))?;registry.register(Box::new(backend_process_seconds.clone()))?;registry.register(Box::new(backend_batch_items.clone()))?;registry.register(Box::new(backend_process_errors_total.clone()))?;@@ -502,6 +520,7 @@ impl MetricsRegistry {messages_received_total,messages_acked_total,messages_naked_total,+ pool_admission_naks_total,ipc_requests_total,ipc_failures_total,inflight_batches,@@ -509,6 +528,7 @@ impl MetricsRegistry {pull_batch_process_seconds,pull_nak_unloaded_total,pull_model_loads_total,+ generate_model_loading_responses_total,backend_process_seconds,backend_batch_items,backend_process_errors_total,@@ -722,6 +742,9 @@ mod tests {.with_label_values(&["m1"]).inc_by(3);m.pull_model_loads_total.with_label_values(&["m1"]).inc();+ m.generate_model_loading_responses_total+ .with_label_values(&["m1", "loading_started", "published_acked"])+ .inc();let families = m.registry.gather();let names: Vec<&str> = families.iter().map(|f| f.name()).collect();@@ -731,6 +754,7 @@ mod tests {"sie_pull_loop_batch_process_seconds","sie_pull_loop_nak_unloaded_total","sie_pull_loop_model_loads_total",+ "sie_worker_generate_model_loading_responses_total",] {assert!(names.contains(&expected), "missing metric {expected}");}diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rsindex 628f25c32..bfcc5dac8 100644--- a/packages/sie_server_sidecar/src/nats_consumer.rs+++ b/packages/sie_server_sidecar/src/nats_consumer.rs@@ -25,7 +25,7 @@ use crate::subject::subjects_overlap;/// and any other worker in the pool — when multiple creators share a/// durable consumer by name, the first to create it wins, and subsequent/// callers silently inherit whatever was there.-const ACK_WAIT_SECS: u64 = 30;+pub(crate) const ACK_WAIT_SECS: u64 = 30;const GENERATION_ACK_WAIT_SECS: u64 = 300;const DEFAULT_MAX_DELIVER: i64 = 20;const DEFAULT_MAX_ACK_PENDING: i64 = 1000;@@ -393,14 +393,13 @@ pub async fn reconcile_stream_and_consumer(.map(|_| ())}-/// Ensure the worker-specific stream used by generation direct-dispatch.+/// Ensure the worker-specific stream used by direct-dispatch.///-/// The gateway publishes direct generation work to+/// The gateway publishes worker-directed work to/// `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`. That/// subject intentionally does not match the pool stream/// (`sie.work.{pool}.*.*.*`), so the sidecar must-/// bind this second stream for generation to avoid relying solely on-/// first-chunk fallback republish to the pool.+/// bind this second stream for generation and capped logical batch dispatch.pub async fn ensure_worker_stream_and_consumer(js: &JsContext,config: &WorkerConfig,@@ -474,7 +473,7 @@ pub async fn ensure_worker_stream_and_consumer(consumer = %consumer_name,subject = %subject,ack_wait_s = GENERATION_ACK_WAIT_SECS,- "ensured generation direct-dispatch stream and pull consumer"+ "ensured worker direct-dispatch stream and pull consumer");Ok(consumer)}diff --git a/packages/sie_server_sidecar/src/pinned_reconciler.rs b/packages/sie_server_sidecar/src/pinned_reconciler.rsnew file mode 100644index 000000000..b6231daf6--- /dev/null+++ b/packages/sie_server_sidecar/src/pinned_reconciler.rs@@ -0,0 +1,407 @@+//! Worker-side pinned-model reconciler.+//!+//! The gateway owns the pinned-model set per logical pool (`PoolSpec.pinned_models`,+//! set via the `/v1/pools` API or `SIE_GATEWAY_STATIC_QUEUE_POOLS`). This+//! module polls that source of truth on a timer, computes the union of pins for+//! logical pools that currently assign this worker, and pushes it to the Python+//! worker over IPC on change, so the worker eager-loads pinned models and+//! excludes them from eviction.+//!+//! It is deliberately decoupled from the pool admission gate: a deployment may+//! run with `SIE_POOL_ADMISSION_ENABLED=false` (or use the default,+//! fail-open pool) and still want pinned models, so this reconciler runs+//! whenever a gateway URL is configured, independent of admission.+//!+//! There is no gateway push channel for pool changes, so delivery is poll-based+//! (mirroring `config_reconciler`). The Python `set_pinned_models` mutator is+//! idempotent, so a redundant push is harmless; we still suppress no-op pushes+//! via change detection.++use std::sync::Arc;+use std::time::Duration;++use serde_json::Value;+use tokio::task::JoinHandle;+use tokio::time::{interval, MissedTickBehavior};+use tracing::{debug, info, warn};++use crate::config::WorkerConfig;+use crate::ipc_client::IpcClient;+use crate::shutdown::Shutdown;++const HTTP_TIMEOUT: Duration = Duration::from_secs(5);++struct PinnedReconciler {+ pool_name: String,+ worker_id: String,+ gateway_url: String,+ api_key: Option<String>,+ poll_interval: Duration,+ http: reqwest::Client,+ ipc: Arc<IpcClient>,+ /// Last set pushed to the worker (sorted), or `None` before the first+ /// successful push. Starts `None` so the first authoritative fetch always+ /// pushes — even an empty set — replacing any deploy-time `SIE_PINNED_MODELS`+ /// bootstrap baseline.+ last_pushed: Option<Vec<String>>,+ /// Whether the previous fetch failed, so we warn once on the transition into+ /// a failing state (a wedged gateway URL / api key) instead of only emitting+ /// debug logs that hide a never-converging reconciler.+ last_fetch_failed: bool,+}++impl PinnedReconciler {+ fn from_worker_config(+ config: &WorkerConfig,+ ipc: Arc<IpcClient>,+ ) -> anyhow::Result<Option<Self>> {+ let Some(gateway_url) = config.gateway_url.as_deref().map(str::trim) else {+ debug!("pinned-reconciler: disabled because SIE_GATEWAY_URL is unset");+ return Ok(None);+ };+ if gateway_url.is_empty() {+ debug!("pinned-reconciler: disabled because SIE_GATEWAY_URL is empty");+ return Ok(None);+ }+ let http = reqwest::Client::builder().timeout(HTTP_TIMEOUT).build()?;+ Ok(Some(Self {+ pool_name: config.pool.clone(),+ worker_id: config.worker_id.clone(),+ gateway_url: gateway_url.trim_end_matches('/').to_string(),+ api_key: config.gateway_api_key.clone(),+ // Reuse the admission poll cadence. Decoupled from admission+ // otherwise (runs even when the gate is disabled); split into its+ // own field only if the cadences ever need to diverge.+ poll_interval: Duration::from_millis(config.pool_admission_check_interval_ms),+ http,+ ipc,+ last_pushed: None,+ last_fetch_failed: false,+ }))+ }++ async fn run(mut self, shutdown: Arc<Shutdown>) {+ info!(+ pool = %self.pool_name,+ worker_id = %self.worker_id,+ gateway = %self.gateway_url,+ poll_interval_ms = self.poll_interval.as_millis() as u64,+ "pinned-reconciler: started"+ );+ let mut ticker = interval(self.poll_interval);+ ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);+ loop {+ tokio::select! {+ biased;+ _ = shutdown.wait() => return,+ _ = ticker.tick() => self.refresh().await,+ }+ }+ }++ async fn refresh(&mut self) {+ let pools = match self.fetch_pools().await {+ // HTTP call succeeded. The pool list is authoritative, even when+ // empty: an empty assigned pin union clears any deploy-time+ // `SIE_PINNED_MODELS` bootstrap baseline.+ Ok(pools) => {+ self.last_fetch_failed = false;+ pools+ }+ // Network / auth / 5xx: keep the last set rather than wiping pins on+ // a glitch. Warn on the first failure so a wedged gateway URL or api+ // key (which would never converge) is visible, then drop to debug.+ Err(error) => {+ if self.last_fetch_failed {+ debug!(pool = %self.pool_name, worker_id = %self.worker_id, error = %error, "pinned-reconciler: fetch still failing; keeping current pinned set");+ } else {+ warn!(pool = %self.pool_name, worker_id = %self.worker_id, error = %error, "pinned-reconciler: pool fetch failed; keeping current pinned set, will retry");+ }+ self.last_fetch_failed = true;+ return;+ }+ };++ let current = parse_assigned_pinned_models(&pools, &self.worker_id, &self.pool_name);+ if current.is_empty() {+ let candidate_count = pinned_pool_count_for_home_queue(&pools, &self.pool_name);+ if candidate_count > 0 {+ debug!(+ pool = %self.pool_name,+ worker_id = %self.worker_id,+ candidate_count,+ "pinned-reconciler: pinned pools exist on this queue but none assign this worker"+ );+ }+ }+ if self.last_pushed.as_ref() == Some(¤t) {+ return;+ }++ match self.ipc.set_pinned_models(current.clone()).await {+ Ok(resp) => {+ info!(+ pool = %self.pool_name,+ worker_id = %self.worker_id,+ count = current.len(),+ applied = resp.applied,+ "pinned-reconciler: pushed pinned set to worker"+ );+ self.last_pushed = Some(current);+ }+ Err(error) => {+ // Leave `last_pushed` unchanged so the next tick retries.+ warn!(pool = %self.pool_name, worker_id = %self.worker_id, error = %error, "pinned-reconciler: failed to push pinned set; will retry");+ }+ }+ }++ async fn fetch_pools(&self) -> Result<Vec<Value>, String> {+ let url = format!("{}/v1/pools", self.gateway_url);+ let mut req = self.http.get(&url).header("accept", "application/json");+ if let Some(token) = self.api_key.as_deref().filter(|token| !token.is_empty()) {+ req = req.bearer_auth(token);+ }+ let resp = req.send().await.map_err(|e| e.to_string())?;+ let status = resp.status();+ if !status.is_success() {+ let body = resp.text().await.unwrap_or_default();+ return Err(format!(+ "status {} from pool list endpoint: {}",+ status.as_u16(),+ body.chars().take(120).collect::<String>()+ ));+ }+ let body = resp.json::<Value>().await.map_err(|e| e.to_string())?;+ parse_pool_list(&body).ok_or_else(|| "pool list response missing 'pools' array".to_string())+ }+}++fn parse_pool_list(body: &Value) -> Option<Vec<Value>> {+ body.get("pools")+ .and_then(Value::as_array)+ .cloned()+ .or_else(|| body.as_array().cloned())+}++fn normalize_pool_name(name: &str) -> String {+ name.trim().to_ascii_lowercase()+}++fn pool_queue_matches(pool: &Value, home_pool: &str) -> bool {+ let spec = pool.get("spec");+ let queue_pool = spec+ .and_then(|spec| spec.get("queue_pool"))+ .and_then(Value::as_str)+ .or_else(|| {+ spec.and_then(|spec| spec.get("name"))+ .and_then(Value::as_str)+ })+ .unwrap_or("default");+ normalize_pool_name(queue_pool) == normalize_pool_name(home_pool)+}++fn pool_assigns_worker(pool: &Value, worker_id: &str) -> bool {+ pool.get("status")+ .and_then(|status| status.get("assigned_workers"))+ .and_then(Value::as_array)+ .is_some_and(|workers| {+ workers.iter().any(|worker| {+ worker+ .get("name")+ .and_then(Value::as_str)+ .is_some_and(|name| name == worker_id)+ })+ })+}++fn parse_assigned_pinned_models(pools: &[Value], worker_id: &str, home_pool: &str) -> Vec<String> {+ let mut out: Vec<String> = pools+ .iter()+ .filter(|pool| pool_queue_matches(pool, home_pool))+ .filter(|pool| pool_assigns_worker(pool, worker_id))+ .flat_map(parse_pinned_models)+ .collect();+ out.sort();+ out.dedup();+ out+}++fn pinned_pool_count_for_home_queue(pools: &[Value], home_pool: &str) -> usize {+ pools+ .iter()+ .filter(|pool| pool_queue_matches(pool, home_pool))+ .filter(|pool| !parse_pinned_models(pool).is_empty())+ .count()+}++/// Extract `spec.pinned_models` from a pool JSON body as a sorted, deduped,+/// non-empty-trimmed list. Missing spec / field / non-array all yield an empty+/// set (the worker un-pins everything). Sorting makes change detection stable.+///+/// Ids are shipped gateway-canonical (bare or `model:profile`); normalization+/// (strip `:profile`, lowercase) is the worker's job, so the dedup here is on+/// the canonical form. Distinct canonical ids that collapse to the same bare id+/// on the worker are pushed as a "change" and the worker no-ops them — harmless,+/// but it means the logged count is canonical, not effective.+fn parse_pinned_models(pool: &Value) -> Vec<String> {+ let mut out: Vec<String> = pool+ .get("spec")+ .and_then(|spec| spec.get("pinned_models"))+ .and_then(Value::as_array)+ .map(|arr| {+ arr.iter()+ .filter_map(Value::as_str)+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .collect()+ })+ .unwrap_or_default();+ out.sort();+ out.dedup();+ out+}++/// Spawn the pinned-model reconciler. Returns `None` (no task) when no gateway+/// URL is configured, matching the standalone / no-gateway deployment shape+/// where pinned models come only from the `SIE_PINNED_MODELS` env baseline.+pub fn spawn(+ config: &WorkerConfig,+ ipc: Arc<IpcClient>,+ shutdown: Arc<Shutdown>,+) -> anyhow::Result<Option<JoinHandle<()>>> {+ let Some(reconciler) = PinnedReconciler::from_worker_config(config, ipc)? else {+ return Ok(None);+ };+ Ok(Some(tokio::spawn(async move {+ reconciler.run(shutdown).await;+ })))+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn parses_sorted_deduped_set() {+ let pool = json!({"spec": {"pinned_models": ["b/model", "a/model", "b/model"]}});+ assert_eq!(parse_pinned_models(&pool), vec!["a/model", "b/model"]);+ }++ #[test]+ fn missing_spec_or_field_is_empty() {+ assert_eq!(parse_pinned_models(&json!({})), Vec::<String>::new());+ assert_eq!(+ parse_pinned_models(&json!({"spec": {}})),+ Vec::<String>::new()+ );+ assert_eq!(+ parse_pinned_models(&json!({"spec": {"pinned_models": []}})),+ Vec::<String>::new()+ );+ }++ #[test]+ fn filters_non_strings_and_blanks() {+ let pool = json!({"spec": {"pinned_models": ["org/a", 7, "", " ", "org/b:fast"]}});+ assert_eq!(parse_pinned_models(&pool), vec!["org/a", "org/b:fast"]);+ }++ #[test]+ fn profile_qualified_ids_pass_through_unchanged() {+ // Normalization (strip :profile, lowercase) is the worker's job; the+ // reconciler ships gateway-canonical ids verbatim.+ let pool = json!({"spec": {"pinned_models": ["Org/Model:Fast"]}});+ assert_eq!(parse_pinned_models(&pool), vec!["Org/Model:Fast"]);+ }++ #[test]+ fn assigned_pool_union_uses_worker_and_home_queue() {+ let pools = vec![+ json!({+ "spec": {+ "name": "tenant-a",+ "queue_pool": "default",+ "pinned_models": ["BAAI/bge-m3", "intfloat/e5"]+ },+ "status": {+ "assigned_workers": [{"name": "worker-1"}]+ }+ }),+ json!({+ "spec": {+ "name": "tenant-b",+ "queue_pool": "default",+ "pinned_models": ["BAAI/bge-m3", "Qwen/Qwen3"]+ },+ "status": {+ "assigned_workers": [{"name": "worker-1"}]+ }+ }),+ json!({+ "spec": {+ "name": "tenant-c",+ "queue_pool": "other",+ "pinned_models": ["other/model"]+ },+ "status": {+ "assigned_workers": [{"name": "worker-1"}]+ }+ }),+ json!({+ "spec": {+ "name": "tenant-d",+ "queue_pool": "default",+ "pinned_models": ["unassigned/model"]+ },+ "status": {+ "assigned_workers": [{"name": "worker-2"}]+ }+ }),+ ];++ assert_eq!(+ parse_assigned_pinned_models(&pools, "worker-1", "default"),+ vec!["BAAI/bge-m3", "Qwen/Qwen3", "intfloat/e5"]+ );+ }++ #[test]+ fn assigned_pool_union_normalizes_home_queue() {+ let pools = vec![json!({+ "spec": {+ "name": "tenant-a",+ "queue_pool": "default",+ "pinned_models": ["BAAI/bge-m3"]+ },+ "status": {+ "assigned_workers": [{"name": "worker-1"}]+ }+ })];++ assert_eq!(+ parse_assigned_pinned_models(&pools, "worker-1", " DEFAULT "),+ vec!["BAAI/bge-m3"]+ );+ }++ #[test]+ fn missing_queue_pool_falls_back_to_pool_name_for_legacy_static_pools() {+ let pools = vec![json!({+ "spec": {+ "name": "l4",+ "pinned_models": ["BAAI/bge-m3"]+ },+ "status": {+ "assigned_workers": [{"name": "worker-1"}]+ }+ })];++ assert_eq!(+ parse_assigned_pinned_models(&pools, "worker-1", "l4"),+ vec!["BAAI/bge-m3"]+ );+ }+}diff --git a/packages/sie_server_sidecar/src/pool_admission.rs b/packages/sie_server_sidecar/src/pool_admission.rsindex 3756670c7..11d22f7aa 100644--- a/packages/sie_server_sidecar/src/pool_admission.rs+++ b/packages/sie_server_sidecar/src/pool_admission.rs@@ -1,12 +1,14 @@//! Worker-side pool admission gate.//!-//! The gateway owns pool assignment. Capped pools publish their assigned-//! workers in `/v1/pools/{name}`; a worker that is not assigned must not pull-//! from that pool's JetStream consumer, otherwise direct NATS publishes can-//! bypass the gateway's admission decision.+//! The gateway owns pool assignment. The sidecar polls `/v1/pools`, opens its+//! physical JetStream consumer only when the physical pool or at least one+//! backed logical pool assigns this worker, then checks every work item's+//! `admission_pool` before Python IPC so direct NATS publishes cannot bypass+//! the gateway's admission decision.+use std::collections::HashSet;use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::Arc;+use std::sync::{Arc, RwLock};use std::time::{Duration, Instant};use serde_json::{Map, Value};@@ -41,6 +43,7 @@ pub struct PoolAdmissionGate {stale_after: Duration,http: reqwest::Client,admitted: AtomicBool,+ assigned_logical_pools: RwLock<HashSet<String>>,state: Mutex<GateState>,}@@ -72,6 +75,7 @@ impl PoolAdmissionGate {stale_after: Duration::from_millis(config.pool_admission_stale_after_ms),http,admitted: AtomicBool::new(initially_admitted),+ assigned_logical_pools: RwLock::new(HashSet::new()),state: Mutex::new(GateState {last_check_at: None,last_success_at: None,@@ -111,6 +115,24 @@ impl PoolAdmissionGate {self.admitted.load(Ordering::Acquire)}+ pub fn pull_admitted(&self) -> bool {+ self.admitted()+ || self+ .assigned_logical_pools+ .read()+ .is_ok_and(|pools| !pools.is_empty())+ }++ pub fn admits_work_item_pool(&self, admission_pool: &str) -> bool {+ let requested = normalize_pool_name(admission_pool);+ if requested.is_empty() || requested == normalize_pool_name(&self.pool_name) {+ return self.admitted();+ }+ self.assigned_logical_pools+ .read()+ .is_ok_and(|pools| pools.contains(&requested))+ }+async fn refresh(&self) {let now = Instant::now();{@@ -118,13 +140,19 @@ impl PoolAdmissionGate {state.last_check_at = Some(now);}- let fetched = self.fetch_pool().await;+ let fetched = self.fetch_pools().await;let mut state = self.state.lock().await;match fetched {- Ok(pool) => {+ Ok(pools) => {state.last_success_at = Some(Instant::now());+ self.set_assigned_logical_pools(assigned_logical_pools_for_worker(+ &pools,+ &self.worker_id,+ &self.pool_name,+ ));+ let pool = pool_by_name(&pools, &self.pool_name);let (admitted, reason) = decide_pool_admission(- pool.as_ref(),+ pool,&self.pool_name,&self.worker_id,&self.machine_profile,@@ -132,37 +160,34 @@ impl PoolAdmissionGate {self.set_admitted(&mut state, admitted, reason);}Err(error) => {- self.handle_error(&mut state, Instant::now(), error);+ if !self.handle_error(&mut state, Instant::now(), error) {+ self.set_assigned_logical_pools(HashSet::new());+ }}}}- async fn fetch_pool(&self) -> Result<Option<Value>, String> {- let url = format!("{}/v1/pools/{}", self.gateway_url, self.pool_name);+ async fn fetch_pools(&self) -> Result<Vec<Value>, String> {+ let url = format!("{}/v1/pools", self.gateway_url);let mut req = self.http.get(&url).header("accept", "application/json");if let Some(token) = self.api_key.as_deref().filter(|token| !token.is_empty()) {req = req.bearer_auth(token);}let resp = req.send().await.map_err(|e| e.to_string())?;let status = resp.status();- if status.as_u16() == 404 {- return Ok(None);- }if !status.is_success() {let body = resp.text().await.unwrap_or_default();return Err(format!(- "status {} from pool status endpoint: {}",+ "status {} from pool list endpoint: {}",status.as_u16(),body.chars().take(120).collect::<String>()));}- resp.json::<Value>()- .await- .map(Some)- .map_err(|e| e.to_string())+ let body = resp.json::<Value>().await.map_err(|e| e.to_string())?;+ parse_pool_list(&body).ok_or_else(|| "pool list response missing 'pools' array".to_string())}- fn handle_error(&self, state: &mut GateState, now: Instant, error: String) {+ fn handle_error(&self, state: &mut GateState, now: Instant, error: String) -> bool {if state.last_success_at.is_some_and(|last| now.duration_since(last) <= self.stale_after)@@ -173,13 +198,14 @@ impl PoolAdmissionGate {error = %error,"pool-admission: keeping cached decision during stale window");- return;+ return true;}// Keep the default pool available during gateway/status glitches.// Named pools fail closed because their caps are isolation contracts.let fail_open = normalize_pool_name(&self.pool_name) == "default";self.set_admitted(state, fail_open, format!("status_error:{error}"));+ false}fn set_admitted(&self, state: &mut GateState, admitted: bool, reason: String) {@@ -198,12 +224,80 @@ impl PoolAdmissionGate {if admitted { "granted" } else { "paused" });}++ fn set_assigned_logical_pools(&self, pools: HashSet<String>) {+ if let Ok(mut assigned) = self.assigned_logical_pools.write() {+ *assigned = pools;+ }+ }}fn normalize_pool_name(name: &str) -> String {name.trim().to_ascii_lowercase()}+fn parse_pool_list(body: &Value) -> Option<Vec<Value>> {+ body.get("pools")+ .and_then(Value::as_array)+ .cloned()+ .or_else(|| body.as_array().cloned())+}++fn pool_by_name<'a>(pools: &'a [Value], pool_name: &str) -> Option<&'a Value> {+ let pool_name = normalize_pool_name(pool_name);+ pools.iter().find(|pool| {+ pool.get("spec")+ .and_then(|spec| spec.get("name"))+ .and_then(Value::as_str)+ .is_some_and(|name| normalize_pool_name(name) == pool_name)+ })+}++fn pool_queue_matches(pool: &Value, home_pool: &str) -> bool {+ let spec = pool.get("spec");+ let queue_pool = spec+ .and_then(|spec| spec.get("queue_pool"))+ .and_then(Value::as_str)+ .or_else(|| {+ spec.and_then(|spec| spec.get("name"))+ .and_then(Value::as_str)+ })+ .unwrap_or("default");+ normalize_pool_name(queue_pool) == normalize_pool_name(home_pool)+}++fn pool_assigns_worker(pool: &Value, worker_id: &str) -> bool {+ pool.get("status")+ .and_then(|status| status.get("assigned_workers"))+ .and_then(Value::as_array)+ .is_some_and(|workers| {+ workers.iter().any(|worker| {+ worker+ .get("name")+ .and_then(Value::as_str)+ .is_some_and(|name| name == worker_id)+ })+ })+}++fn assigned_logical_pools_for_worker(+ pools: &[Value],+ worker_id: &str,+ home_pool: &str,+) -> HashSet<String> {+ pools+ .iter()+ .filter(|pool| pool_queue_matches(pool, home_pool))+ .filter(|pool| pool_assigns_worker(pool, worker_id))+ .filter_map(|pool| {+ pool.get("spec")+ .and_then(|spec| spec.get("name"))+ .and_then(Value::as_str)+ .map(normalize_pool_name)+ })+ .collect()+}+fn object_field<'a>(value: &'a Value, key: &str) -> Option<&'a Map<String, Value>> {value.get(key).and_then(Value::as_object)}@@ -366,4 +460,84 @@ mod tests {(false, "malformed_assigned_workers".to_string()));}++ #[test]+ fn logical_pool_assignments_follow_home_queue_and_worker() {+ let pools = vec![+ json!({+ "spec": {"name": "tenant-a", "queue_pool": "default"},+ "status": {"assigned_workers": [{"name": "worker-1"}]}+ }),+ json!({+ "spec": {"name": "tenant-b", "queue_pool": "default"},+ "status": {"assigned_workers": [{"name": "worker-2"}]}+ }),+ json!({+ "spec": {"name": "dedicated", "queue_pool": "customer-a"},+ "status": {"assigned_workers": [{"name": "worker-1"}]}+ }),+ ];++ let assigned = assigned_logical_pools_for_worker(&pools, "worker-1", "default");+ assert!(assigned.contains("tenant-a"));+ assert!(!assigned.contains("tenant-b"));+ assert!(!assigned.contains("dedicated"));+ }++ #[test]+ fn gate_admits_same_physical_pool_or_assigned_logical_pool() {+ let gate = PoolAdmissionGate {+ pool_name: "default".to_string(),+ worker_id: "worker-1".to_string(),+ machine_profile: "l4".to_string(),+ gateway_url: "http://gateway".to_string(),+ api_key: None,+ check_interval: Duration::from_secs(1),+ pause: Duration::from_millis(10),+ stale_after: Duration::from_secs(30),+ http: reqwest::Client::new(),+ admitted: AtomicBool::new(true),+ assigned_logical_pools: RwLock::new(HashSet::from(["tenant-a".to_string()])),+ state: Mutex::new(GateState {+ last_check_at: None,+ last_success_at: None,+ admitted: true,+ last_reason: "test".to_string(),+ }),+ };++ assert!(gate.admits_work_item_pool(""));+ assert!(gate.admits_work_item_pool("default"));+ assert!(gate.admits_work_item_pool("TENANT-A"));+ assert!(!gate.admits_work_item_pool("tenant-b"));+ }++ #[test]+ fn gate_can_pull_for_assigned_logical_pool_without_physical_admission() {+ let gate = PoolAdmissionGate {+ pool_name: "customer-queue".to_string(),+ worker_id: "worker-1".to_string(),+ machine_profile: "l4".to_string(),+ gateway_url: "http://gateway".to_string(),+ api_key: None,+ check_interval: Duration::from_secs(1),+ pause: Duration::from_millis(10),+ stale_after: Duration::from_secs(30),+ http: reqwest::Client::new(),+ admitted: AtomicBool::new(false),+ assigned_logical_pools: RwLock::new(HashSet::from(["tenant-a".to_string()])),+ state: Mutex::new(GateState {+ last_check_at: None,+ last_success_at: None,+ admitted: false,+ last_reason: "test".to_string(),+ }),+ };++ assert!(gate.pull_admitted());+ assert!(gate.admits_work_item_pool("tenant-a"));+ assert!(!gate.admits_work_item_pool(""));+ assert!(!gate.admits_work_item_pool("customer-queue"));+ assert!(!gate.admits_work_item_pool("tenant-b"));+ }}diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex 713cf5f3b..34a12f537 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -41,6 +41,7 @@ pub const METHOD_SIGNAL_GENERATE_CANCEL: &str = "SignalGenerateCancel";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_SET_PINNED_MODELS: &str = "SetPinnedModels";pub const METHOD_DRAIN: &str = "Drain";// -----------------------------------------------------------------------------@@ -150,6 +151,8 @@ pub struct PingResponse {pub worker_id: String,#[serde(default)]pub bundle_config_hash: String,+ #[serde(default)]+ pub loaded_models: Vec<String>,}// -----------------------------------------------------------------------------@@ -309,6 +312,29 @@ pub struct ReplaceModelConfigsResponse {pub applied_models: Vec<String>,}+// -----------------------------------------------------------------------------+// SetPinnedModels+// -----------------------------------------------------------------------------++/// Runtime delivery of a pool's pinned-model set from the gateway to the+/// worker. The sidecar polls the pool's `PoolSpec.pinned_models` (the single+/// source of truth, set via the `/v1/pools` API or+/// `SIE_GATEWAY_STATIC_QUEUE_POOLS`) and pushes it here on change. `models`+/// carries gateway-canonical ids (bare `sie_id` or `sie_id:profile`); Python+/// normalizes them. The set is authoritative and REPLACES the worker's current+/// pinned set.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SetPinnedModelsRequest {+ pub models: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SetPinnedModelsResponse {+ pub applied: bool,+ #[serde(default)]+ pub pinned_count: u32,+}+// -----------------------------------------------------------------------------// ProcessGenerate: streaming generation over IPC// -----------------------------------------------------------------------------@@ -1136,6 +1162,7 @@ mod tests {assert_eq!(back.worker_id, "w-1");assert_eq!(back.timestamp_ms, 123.0);assert_eq!(back.bundle_config_hash, "");+ assert!(back.loaded_models.is_empty());}#[test]diff --git a/packages/sie_server_sidecar/src/work_types.rs b/packages/sie_server_sidecar/src/work_types.rsindex 6fefbb9dc..640696b98 100644--- a/packages/sie_server_sidecar/src/work_types.rs+++ b/packages/sie_server_sidecar/src/work_types.rs@@ -35,6 +35,8 @@ pub struct WorkItem {#[serde(default)]pub engine: String,pub pool_name: String,+ #[serde(default)]+ pub admission_pool: String,pub machine_profile: String,#[serde(default)]pub item: Option<WireValue>,@@ -129,6 +131,7 @@ mod tests {profile_id: String::new(),engine: String::new(),pool_name: "l4".into(),+ admission_pool: "l4".into(),machine_profile: "l4-spot".into(),item: Some(msg_value(serde_json::json!({"text": "hello"}))),payload_ref: None,diff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rsindex c2b032d56..84003ed55 100644--- a/packages/sie_server_sidecar/tests/integration_smoke.rs+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs@@ -266,6 +266,15 @@ impl GatewayPoolHarness {pool: &'static str,worker_id: &'static str,machine_profile: &'static str,+ ) -> Self {+ Self::start_with_queue_pool(pool, pool, worker_id, machine_profile).await+ }++ async fn start_with_queue_pool(+ pool: &'static str,+ queue_pool: &'static str,+ worker_id: &'static str,+ machine_profile: &'static str,) -> Self {let listener = TcpListener::bind(("127.0.0.1", 0)).await@@ -285,9 +294,12 @@ impl GatewayPoolHarness {return;};let request = String::from_utf8_lossy(&buf[..n]);- let expected_path = format!("/v1/pools/{pool}");let ok_path = request.lines().next().is_some_and(|line| {- line.starts_with("GET ") && line.contains(&expected_path)+ let mut parts = line.split_whitespace();+ matches!(parts.next(), Some("GET"))+ && parts.next().is_some_and(|target| {+ target == "/v1/pools" || target.starts_with("/v1/pools?")+ })});let (status, body) = if ok_path {let assigned_workers = if assigned.load(Ordering::Acquire) {@@ -300,7 +312,7 @@ impl GatewayPoolHarness {("200 OK",format!(- r#"{{"spec":{{"gpu_caps":{{"{machine_profile}":1}}}},"status":{{"state":"active","assigned_workers":{assigned_workers}}}}}"#+ r#"{{"pools":[{{"spec":{{"name":"{pool}","queue_pool":"{queue_pool}","gpu_caps":{{"{machine_profile}":1}}}},"status":{{"state":"active","assigned_workers":{assigned_workers}}}}}]}}"#),)} else {@@ -675,6 +687,7 @@ async fn smoke_encode_request_round_trips_through_rust_worker() {profile_id: String::new(),engine: String::new(),pool_name: pool.into(),+ admission_pool: String::new(),machine_profile: pool.into(),item: Some(text_item("hello rust worker")),payload_ref: None,@@ -788,6 +801,73 @@ async fn smoke_encode_request_round_trips_through_rust_worker() {let _ = Arc::new(());}+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn smoke_encode_direct_dispatch_round_trips_through_worker_stream() {+ if skip_unless_tools_available() {+ return;+ }+ let _guard = smoke_test_guard().await;++ let nats = NatsHarness::start().await;+ eprintln!("nats: {} (port {})", nats.url, nats.port);++ let sock = ShortSocket::new("ipc.sock");+ let python = PythonHarness::start(sock.path.clone()).await;+ eprintln!("python harness: socket={}", python.socket_path.display());++ let pool = "smoke-direct";+ let bundle = "default";+ let metrics_port = find_free_tcp_port();+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, metrics_port, None);+ wait_for_tcp(metrics_port, Duration::from_secs(30))+ .await+ .expect("worker metrics port");+ sleep(Duration::from_millis(500)).await;++ let client = async_nats::connect(&nats.url)+ .await+ .expect("client connect");+ let js = async_nats::jetstream::new(client.clone());++ let reply_subject = format!("_INBOX.smoke-direct.{}", uuid::Uuid::new_v4());+ let mut sub = client+ .subscribe(reply_subject.clone())+ .await+ .expect("subscribe reply");++ let model_id = "BAAI/bge-m3";+ let subject = worker_work_subject(pool, pool, bundle, model_id, "smoke-worker");+ publish_work_item(+ &js,+ &subject,+ "smoke-direct-encode-1",+ model_id,+ "BAAI__bge-m3",+ pool,+ &reply_subject,+ )+ .await;++ let reply = timeout(Duration::from_secs(30), sub.next())+ .await+ .expect("timed out waiting for direct-dispatch WorkResult")+ .expect("reply stream closed");+ let result: WorkResult = rmp_serde::from_slice(&reply.payload).expect("decode WorkResult");+ assert!(+ result.success,+ "expected direct-dispatch success, got error={:?}",+ result.error+ );+ assert_eq!(result.request_id, "smoke-direct-encode-1");+ assert_eq!(result.worker_id.as_deref(), Some("smoke-worker"));++ drop(_worker);+ drop(python);+ drop(nats);+ let _ = sock;+ sleep(Duration::from_millis(200)).await;+}+/// End-to-end smoke test for generation direct-dispatch through the/// sidecar. The Python harness exposes one fake generation model and/// answers `ProcessGenerate` with the same event sequence a real@@ -846,6 +926,7 @@ async fn smoke_generate_direct_dispatch_round_trips_through_rust_worker() {profile_id: String::new(),engine: String::new(),pool_name: pool.into(),+ admission_pool: String::new(),machine_profile: pool.into(),item: None,payload_ref: None,@@ -917,13 +998,11 @@ async fn smoke_generate_direct_dispatch_round_trips_through_rust_worker() {sleep(Duration::from_millis(200)).await;}-/// Generation direct-dispatch must also come up after a live config change.-/// The harness hides its generation capability from the startup-/// WorkerCapabilities probe, then exposes it on the next probe. This exercises-/// the sidecar's capability reconciler without needing a full sie-config-/// process in the smoke test.+/// Worker direct-dispatch is not gated by WorkerCapabilities. The harness hides+/// generation capability from the first probe, but the worker-specific stream+/// must still be available for direct generation work immediately.#[tokio::test(flavor = "multi_thread", worker_threads = 4)]-async fn smoke_generation_direct_dispatch_activates_after_capability_reconcile() {+async fn smoke_generation_direct_dispatch_is_active_before_capability_reconcile() {if skip_unless_tools_available() {return;}@@ -945,22 +1024,12 @@ async fn smoke_generation_direct_dispatch_activates_after_capability_reconcile()let pool = "smoke-gen-hot-add";let bundle = "default";let metrics_port = find_free_tcp_port();- let _worker = WorkerHarness::spawn_with_env(- &nats.url,- &sock.path,- pool,- bundle,- metrics_port,- None,- &[("SIE_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS", "1000")],- );+ let _worker =+ WorkerHarness::spawn_with_env(&nats.url, &sock.path, pool, bundle, metrics_port, None, &[]);wait_for_tcp(metrics_port, Duration::from_secs(30)).await.expect("worker metrics port");-- // The binary clamps the reconcile interval to 5s so production cannot- // accidentally create a tight IPC polling loop.- sleep(Duration::from_millis(6_500)).await;+ sleep(Duration::from_millis(500)).await;let client = async_nats::connect(&nats.url).await@@ -987,6 +1056,7 @@ async fn smoke_generation_direct_dispatch_activates_after_capability_reconcile()profile_id: String::new(),engine: String::new(),pool_name: pool.into(),+ admission_pool: String::new(),machine_profile: pool.into(),item: None,payload_ref: None,@@ -1140,6 +1210,7 @@ async fn smoke_payload_ref_request_round_trips_through_rust_worker() {profile_id: String::new(),engine: String::new(),pool_name: pool.into(),+ admission_pool: String::new(),machine_profile: pool.into(),item: None,payload_ref: Some(payload_ref.clone()),@@ -1297,6 +1368,7 @@ async fn smoke_extract_payload_ref_preserves_document_bytes_through_ipc() {profile_id: String::new(),engine: String::new(),pool_name: pool.into(),+ admission_pool: String::new(),machine_profile: pool.into(),item: None,payload_ref: Some(payload_ref.clone()),@@ -1463,6 +1535,30 @@ async fn publish_work_item(normalized: &str,pool: &str,reply_subject: &str,+) {+ publish_work_item_with_admission_pool(+ js,+ subject,+ request_id,+ model_id,+ normalized,+ pool,+ "",+ reply_subject,+ )+ .await;+}++#[allow(clippy::too_many_arguments)]+async fn publish_work_item_with_admission_pool(+ js: &async_nats::jetstream::Context,+ subject: &str,+ request_id: &str,+ model_id: &str,+ normalized: &str,+ pool: &str,+ admission_pool: &str,+ reply_subject: &str,) {let _ = normalized; // subject is pre-built by callerlet now_s = std::time::SystemTime::now()@@ -1479,6 +1575,7 @@ async fn publish_work_item(profile_id: String::new(),engine: String::new(),pool_name: pool.into(),+ admission_pool: admission_pool.into(),machine_profile: pool.into(),item: Some(text_item(format!("concurrent-{request_id}"))),payload_ref: None,@@ -1534,6 +1631,7 @@ async fn pool_admission_pauses_until_gateway_assigns_worker() {("SIE_POOL_ADMISSION_CHECK_INTERVAL_S", "1"),("SIE_POOL_ADMISSION_PAUSE_S", "0.1"),("SIE_POOL_ADMISSION_STALE_AFTER_S", "0"),+ ("SIE_NAK_DELAY_S", "0.1"),],);wait_for_tcp(metrics_port, Duration::from_secs(30))@@ -1589,6 +1687,98 @@ async fn pool_admission_pauses_until_gateway_assigns_worker() {assert_eq!(result.request_id, "gated-req-1");}+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn logical_pool_admission_naks_until_assigned_worker_serves_item() {+ if skip_unless_tools_available() {+ return;+ }+ let _guard = smoke_test_guard().await;++ let physical_pool = "default";+ let logical_pool = "tenant-a";+ let worker_id = "smoke-worker";+ let gateway = GatewayPoolHarness::start_with_queue_pool(+ logical_pool,+ physical_pool,+ worker_id,+ physical_pool,+ )+ .await;++ let nats = NatsHarness::start().await;+ let sock = ShortSocket::new("ipc.sock");+ let _python = PythonHarness::start(sock.path.clone()).await;++ let bundle = "default";+ let metrics_port = find_free_tcp_port();+ let _worker = WorkerHarness::spawn_with_env(+ &nats.url,+ &sock.path,+ physical_pool,+ bundle,+ metrics_port,+ None,+ &[+ ("SIE_GATEWAY_URL", gateway.url.as_str()),+ ("SIE_POOL_ADMISSION_CHECK_INTERVAL_S", "1"),+ ("SIE_POOL_ADMISSION_PAUSE_S", "0.1"),+ ("SIE_POOL_ADMISSION_STALE_AFTER_S", "0"),+ ("SIE_NAK_DELAY_S", "0.1"),+ ],+ );+ wait_for_tcp(metrics_port, Duration::from_secs(30))+ .await+ .expect("worker metrics port");+ sleep(Duration::from_millis(500)).await;++ let client = async_nats::connect(&nats.url)+ .await+ .expect("client connect");+ let js = async_nats::jetstream::new(client.clone());+ let reply_subject = format!("_INBOX.logical.{}", uuid::Uuid::new_v4());+ let mut sub = client+ .subscribe(reply_subject.clone())+ .await+ .expect("subscribe reply");++ let model_id = "BAAI/bge-m3";+ let normalized = "BAAI__bge-m3";+ let subject = pool_work_subject(physical_pool, physical_pool, bundle, model_id);+ publish_work_item_with_admission_pool(+ &js,+ &subject,+ "logical-req-1",+ model_id,+ normalized,+ physical_pool,+ logical_pool,+ &reply_subject,+ )+ .await;++ match timeout(Duration::from_millis(700), sub.next()).await {+ Err(_) => {}+ Ok(Some(msg)) => panic!(+ "worker served logical pool before assignment; payload bytes={}",+ msg.payload.len()+ ),+ Ok(None) => panic!("reply subscription closed before logical assignment"),+ }++ gateway.set_assigned(true);+ let reply = timeout(Duration::from_secs(5), sub.next())+ .await+ .expect("timed out waiting for WorkResult after logical assignment")+ .expect("reply stream closed after logical assignment");+ let result: WorkResult = rmp_serde::from_slice(&reply.payload).expect("decode WorkResult");+ assert!(+ result.success,+ "expected success after logical assignment, got error={:?}",+ result.error+ );+ assert_eq!(result.request_id, "logical-req-1");+}+/// Fire N concurrent publishes on distinct reply subjects and assert that/// **every one** gets a reply within a budget well short of `ack_wait`.///@@ -2179,6 +2369,7 @@ async fn smoke_prepared_tokens_round_trip_through_rust_worker() {profile_id: String::new(),engine: String::new(),pool_name: pool.into(),+ admission_pool: String::new(),machine_profile: pool.into(),item: Some(text_item("hello world")),payload_ref: None,@@ -2355,6 +2546,7 @@ async fn publish_score_work_item(profile_id: String::new(),engine: String::new(),pool_name: pool.into(),+ admission_pool: String::new(),machine_profile: pool.into(),item: None,payload_ref: None,@@ -2405,6 +2597,7 @@ async fn publish_extract_work_item(profile_id: String::new(),engine: String::new(),pool_name: pool.into(),+ admission_pool: String::new(),machine_profile: pool.into(),item: Some(text_item("Barack Obama was born in Hawaii.")),payload_ref: None,diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex 01fd4bc73..706f1addb 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.10",+ "version": "0.6.11","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 daa03037d..3c18131df 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -88,6 +88,7 @@ import type {Item,ModelInfo,PoolInfo,+ PoolSpec,SIEClientOptions,ScoreOptions,ScoreResult,@@ -180,7 +181,7 @@ function extractGenerateChunkError(chunk: GenerateChunk): SIEStreamError | null* ```typescript* const client = new SIEClient("http://gateway:8080");*- * // Create a dedicated pool+ * // Create a logical pool backed by the cluster's default worker queue* await client.createPool("eval-bench", { l4: 2 });** // Use pool for requests@@ -1159,12 +1160,15 @@ export class SIEClient {/*** Create or update a resource pool for isolated capacity.*- * Pools provide dedicated worker capacity, isolated from other clients.- * Workers are assigned to pools and only serve requests from that pool.+ * Pools provide logical capacity isolation. By default they draw from the+ * cluster's `default` Helm/NATS queue; pass `queuePool` only when the cluster+ * has a dedicated physical worker queue declared under+ * `queueRouting.staticQueuePools` for this workload.** @param name - Pool name (used in GPU param as "poolName/machineProfile")* @param gpus - Optional machine profile requirements for pool readiness, e.g., { "l4": 2, "l4-spot": 1 }* @param gpuCaps - Optional maximum assigned workers per machine profile+ * @param queuePool - Optional Helm/NATS queue namespace backing this logical pool. Defaults to "default".** @example* ```typescript@@ -1182,6 +1186,7 @@ export class SIEClient {name: string,gpus?: Record<string, number>,gpuCaps?: Record<string, number>,+ queuePool?: string,): Promise<void> {const alreadyTracking = this.pools.has(name);@@ -1190,6 +1195,7 @@ export class SIEClient {name: string;gpus?: Record<string, number>;gpu_caps?: Record<string, number>;+ queue_pool?: string;} = {name,};@@ -1199,6 +1205,9 @@ export class SIEClient {if (gpuCaps) {requestBody.gpu_caps = gpuCaps;}+ if (queuePool) {+ requestBody.queue_pool = queuePool;+ }const url = `${this.baseUrl}/v1/pools`;const headers: Record<string, string> = {@@ -1342,7 +1351,7 @@ export class SIEClient {const response = await this.requestJson(`/v1/pools/${encodeURIComponent(name)}`);const data = (await response.json()) as {name: string;- spec: { gpus?: Record<string, number>; gpu_caps?: Record<string, number> };+ spec: PoolSpec;status: {state: string;assigned_workers: Array<{ name: string; url: string; gpu: string }>;diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex a55f2a44e..a4f1a05b3 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -302,15 +302,37 @@ export interface CapacityInfo {/*** Pool specification for creating resource pools.*/-export interface PoolSpec {+export interface PoolCreateSpec {/** Pool name (used in GPU param as "poolName/machineProfile") */name: string;+ /** Optional Helm/NATS queue namespace backing this logical pool. Defaults to "default"; non-default values must be declared under queueRouting.staticQueuePools. */+ queuePool?: string;/** Machine profile requirements for pool readiness, e.g., { l4: 2, "a100-40gb": 1 } */gpus?: Record<string, number>;/** Optional maximum assigned workers per machine profile */gpuCaps?: Record<string, number>;+}++/**+ * Pool specification returned by the gateway.+ */+export interface PoolSpec {+ /** Pool name (used in GPU param as "poolName/machineProfile") */+ name: string;+ /** Helm/NATS queue namespace backing this logical pool */+ queue_pool?: string;+ /** Optional bundle constraint for this pool */+ bundle?: string | null;+ /** Machine profile requirements for pool readiness, e.g., { l4: 2, "a100-40gb": 1 } */+ gpus?: Record<string, number>;/** Optional maximum assigned workers per machine profile, as returned by the gateway */gpu_caps?: Record<string, number>;+ /** Optional TTL for dynamic pool leases */+ ttl_seconds?: number | null;+ /** Minimum workers kept warm for this pool */+ minimum_worker_count?: number;+ /** Models pinned for this pool */+ pinned_models?: string[];}/**@@ -334,7 +356,7 @@ export interface PoolInfo {/** Pool name */name: string;/** Pool specification */- spec: { gpus?: Record<string, number>; gpu_caps?: Record<string, number> };+ spec: PoolSpec;/** Pool status */status: PoolStatus;}diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 43e4c99a4..ed483dd62 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.10"; // x-release-please-version+export const SDK_VERSION = "0.6.11"; // x-release-please-versiondiff --git a/pyproject.toml b/pyproject.tomlindex 2498bf103..842667975 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -234,6 +234,9 @@ ignore = ["tools/sie_dashboard/scripts/*.py" = ["INP001", # JS project subdir; not a Python package]+"tools/loadtest/*.py" = [+ "INP001", # Standalone loadtest CI scripts, not a package+]"**/tests/**/*" = ["ANN", # Type annotations (tests don't need full typing)"ARG", # Unused function arguments (fixtures)diff --git a/uv.lock b/uv.lockindex aa20e1202..6b34e8d7f 100644--- a/uv.lock+++ b/uv.lock@@ -5719,7 +5719,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.6.10"+version = "0.6.11"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5752,7 +5752,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.6.10"+version = "0.6.11"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5837,7 +5837,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.6.10"+version = "0.6.11"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5909,7 +5909,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.10"+version = "0.6.11"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5934,7 +5934,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.10"+version = "0.6.11"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5959,7 +5959,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.10"+version = "0.6.11"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5986,7 +5986,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.10"+version = "0.6.11"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -6013,7 +6013,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.10"+version = "0.6.11"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -6040,7 +6040,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.10"+version = "0.6.11"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -6106,7 +6106,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.6.10"+version = "0.6.11"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -6129,7 +6129,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.10"+version = "0.6.11"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -6182,7 +6182,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.10"+version = "0.6.11"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -6312,7 +6312,7 @@ requires-dist = [[[package]]name = "sie-weaviate"-version = "0.6.10"+version = "0.6.11"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },