Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
release: v0.3.2
github-actions[bot]a86f9433544c
diff --git a/.gitignore b/.gitignoreindex c37d66bef..5a2d93fd4 100644--- a/.gitignore+++ b/.gitignore@@ -16,6 +16,9 @@ eggs/.eggs/lib/lib64/+# JS/TS projects under tools/ legitimately use a `lib/` directory.+!tools/*/lib/+!tools/*/lib/**parts/sdist/var/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex baaffa1cb..f81ff2219 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,50 @@# Changelog+## v0.3.2++- chore(main): release 0.3.2+- test(fixtures): configure deployment environment for test containers and clusters+- ci(telemetry): add deployment environment tagging across internal infrastructure+- docs(gateway): document embeddings partial-success contract+- fix(docker): stub bundles/ and models/ in deps stage+- docs(gateway): clarify OpenAPI contracts+- fix(sie-server): include model and bundle directories in wheel distribution+- feat(sie_server): per-stage timing markers in lifespan for engine_boot attribution+- feat(sie_server): split adapter.warmup() out of load() with cold-start log markers+- feat(helm): wire probe templates to values trees+- feat(helm): expose probes value trees for worker/gateway/config+- fix(gateway): preserve scale-from-zero request path+- fix(gateway): preserve embeddings timing headers+- fix(gateway): address latest coderabbit contract notes+- docs(gateway): document service unavailable variants+- fix(gateway): close remaining review contract gaps+- docs(gateway): align embeddings encoding docs+- fix(gateway): reject unsupported embeddings token arrays+- fix(paddleocr_vl): pass use_cache=True to generate to enable KV-cache+- fix(gateway): address probe and SDK review findings+- feat(gateway): unify API errors and align probe contracts+- fix(docling): mark adapter unloaded in unload()+- fix(docling): cache DocumentConverter per (device, ocr_enabled)+- fix(chart): pass --cluster-cache to sie-server and correct populate command in docs+- docs(infra): drop mise wrappers from public-facing model-cache docs (#791)+- feat(infra): opt-in S3 cluster model cache (#791)+- docs(helm): correct Let's Encrypt rate-limit wording in README+- fix(helm): validate ACME server and privateKeySecretRef in validateTls+- docs(helm): address local reviewer suggestions on TLS work+- feat(helm): TLS termination via cert-manager + BYO matrix docs+- fix(gateway): address PR review for NATS health mode+- fix(gateway): align CreatePoolRequest OpenAPI with runtime validation+- fix(gateway): clarify experimental NATS health mode+- feat(gateway): expose OpenAPI contract+- feat(docling): add ocr profile defaulting do_ocr=true+- fix(docling): thread device through PdfPipelineOptions accelerator_options+- fix(review): tighten score_pairs options handling and query text validation+- refactor(eval): consolidate colbert model lists and improve query validation+- feat(adapters): default score_pairs() in BaseAdapter + baseline reranking targets+- refactor(colbert): hoist score-pair grouping helper to _utils+- feat(server): emit INFO log on invalid SIE_TORCH_NUM_THREADS fallback+- feat(server): cap torch CPU threads at worker startup+## v0.3.1- chore(main): release 0.3.1diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex f22b1852c..a159400c9 100644--- a/deploy/helm/sie-cluster/Chart.yaml+++ b/deploy/helm/sie-cluster/Chart.yaml@@ -4,8 +4,8 @@ description: >-SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,and observabilitytype: application-version: 0.3.1 # x-release-please-version-appVersion: v0.3.1 # x-release-please-version+version: 0.3.2 # x-release-please-version+appVersion: v0.3.2 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 8a02628d8..a1d4486cb 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -57,6 +57,31 @@ When a pool is scaling from zero, the gateway returns:The SDK handles this automatically with configurable retries.+## Cluster model cache (S3/GCS)++Pre-populate a shared bucket with model weights so worker pods don't re-download from HuggingFace on every cold start. The Python SDK pulls from the bucket first and falls back to HF on miss.++**AWS (Terraform-managed bucket):**++```bash+# 1. Provision the bucket via the AWS Terraform module (opt-in via create_model_cache=true)+cd deploy/terraform/aws/examples/dev-g6-spot+terraform apply++# 2. One-time populate from your laptop+sie-admin cache weights sync --bundle default \+ --dest $(terraform output -raw model_cache_bucket_url)/++# 3. Wire into Helm+helm upgrade --install sie-cluster . \+ --set workers.common.clusterCache.enabled=true \+ --set workers.common.clusterCache.url=$(terraform output -raw model_cache_bucket_url)+```++The Terraform output already includes the `/models` prefix, so the same URL is used for both `sie-admin --target` and `clusterCache.url`.++**Other clouds / BYO bucket:** point `workers.common.clusterCache.url` at any `s3://...` or `gs://...` URL the workload Service Account can read; populate it with the same `sie-admin cache weights sync --dest ...` command.+## AutoscalingKEDA-based autoscaling with scale-to-zero support:@@ -111,6 +136,88 @@ autoscaling:cooldownPeriod: 600 # 10 min before scale-down```+## TLS / HTTPS++The chart supports two TLS modes for the Ingress (set via `ingress.tls.mode`):++- `byo` — bring your own `kubernetes.io/tls` Secret (default, backward compatible).+- `cert-manager` — chart annotates the Ingress; [cert-manager](https://cert-manager.io/) provisions and renews the certificate via ACME (HTTP-01 challenge to Let's Encrypt by default).++Only HTTP-01 ACME challenges are supported by the chart. DNS-01 / wildcard certs (which require cloud-provider IRSA / Workload Identity for Route53 / Cloud DNS) are out of scope — set them up manually outside the chart and reference the resulting Secret via `mode: byo`.++### BYO certificate++Create the TLS Secret yourself (e.g. from a corporate CA, ACM cert exported to a Secret, or an existing wildcard cert), then point the chart at it:++```bash+kubectl -n sie create secret tls sie-tls --cert=path/to/tls.crt --key=path/to/tls.key+```++```yaml+ingress:+ enabled: true+ className: nginx+ host: sie.example.com+ tls:+ enabled: true+ mode: byo # default+ secretName: sie-tls # default+```++### cert-manager + Let's Encrypt++Prerequisite: install cert-manager once in the cluster (its CRDs are cluster-scoped and must exist exactly once — that's why it is **not** bundled as a subchart):++```bash+helm repo add jetstack https://charts.jetstack.io && helm repo update+helm install cert-manager jetstack/cert-manager \+ --set crds.enabled=true -n cert-manager --create-namespace+```++Then enable cert-manager mode in your SIE values:++```yaml+ingress:+ enabled: true+ className: nginx+ host: sie.example.com+ tls:+ enabled: true+ mode: cert-manager+ certManager:+ email: [email protected]+ # Use Let's Encrypt staging while iterating to avoid the 50 new-cert/registered-domain/week prod limit (duplicate-cert limit is 5/week):+ # server: https://acme-staging-v02.api.letsencrypt.org/directory+ kind: ClusterIssuer # cluster-scoped; share across namespaces. Use "Issuer" for namespace-scoped.+ create: true # chart renders the Issuer/ClusterIssuer+```++The chart renders a `{kind}` named `{release-fullname}-letsencrypt-prod` (release-scoped to avoid collisions when multiple SIE releases share a cluster) and adds the appropriate `cert-manager.io/cluster-issuer` (or `/issuer`) annotation to the main Ingress. cert-manager populates `ingress.tls.secretName` (default `sie-tls`); the same Secret is referenced by the oauth2-proxy Ingress when auth is enabled.++Note: Helm's standard `fullname` collapses when the release name already contains the chart name, so `helm install sie-cluster …` produces `sie-cluster-letsencrypt-prod` (not `sie-cluster-sie-cluster-letsencrypt-prod`). If you override `certManager.name`, set the full intended name explicitly rather than expecting a particular default.++Issuer kind tradeoff:++- `ClusterIssuer` — single ACME account / private key shared across all namespaces. Best for shared clusters.+- `Issuer` — namespace-scoped. Use for hard tenant isolation, or when you don't have permission to create cluster-scoped resources.++### Reusing an existing ClusterIssuer/Issuer++In multi-tenant clusters where a platform team already manages a shared `ClusterIssuer`, set `create: false` and reference it by name:++```yaml+ingress:+ tls:+ enabled: true+ mode: cert-manager+ certManager:+ kind: ClusterIssuer+ create: false+ name: platform-letsencrypt-prod+```++The chart only adds the annotation — it does not render any Issuer resource.+## Gated ModelsSome HuggingFace models require authentication to download (gated models). Examples:@@ -197,6 +304,14 @@ telemetry:deploymentEnv: staging # production (default) | staging | development | ci```+> **Internal Superlinked clusters:** any cluster owned by Superlinked that is+> not a customer-facing production install MUST set `telemetry.deploymentEnv`+> to one of `staging | development | ci`. The chart default is `production`+> so that customer Helm installs are correctly tagged out of the box; internal+> stacks must opt out explicitly to keep them out of the production telemetry+> dashboards. See `deploy/terraform/{aws,gcp}/internal-examples/` for the+> per-cluster mapping.+## ObservabilityObservability components (Prometheus, Grafana, Loki, DCGM Exporter, Alloy, Event Exporter) are included as optional sub-chart dependencies. Enable them in your values overlay (e.g. `kube-prometheus-stack.install: true`).diff --git a/deploy/helm/sie-cluster/templates/NOTES.txt b/deploy/helm/sie-cluster/templates/NOTES.txtindex 42a59d043..e409a4ed3 100644--- a/deploy/helm/sie-cluster/templates/NOTES.txt+++ b/deploy/helm/sie-cluster/templates/NOTES.txt@@ -1,4 +1,5 @@{{- include "sie-cluster.validateNats" . -}}+{{- include "sie-cluster.validateTls" . -}}SIE Cluster {{ .Chart.Version }} deployed to namespace {{ include "sie-cluster.namespace" . }}.Gateway: http://{{ include "sie-cluster.gateway.serviceName" . }}.{{ include "sie-cluster.namespace" . }}.svc:{{ .Values.gateway.service.port }}@@ -11,3 +12,10 @@ Grafana password: kubectl get secret -n {{ include "sie-cluster.namespace" . }}{{- if .Values.keda.install }}KEDA: enabled{{- end }}+{{- if and .Values.ingress.tls.enabled (eq .Values.ingress.tls.mode "cert-manager") }}++TLS via cert-manager: certificate is being issued via ACME HTTP-01 challenge.+This typically takes 30–120s on first install. Track progress with:+ kubectl -n {{ include "sie-cluster.namespace" . }} get certificate -w+The gateway will return TLS errors briefly until the certificate is Ready.+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex 34766c817..63fe1575f 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -238,6 +238,43 @@ Fails if nats.install=true but nats.enabled=false (NATS deploys but nothing conn{{- end }}{{- end }}+{{/*+Validation: TLS configuration consistency.+Runs from NOTES.txt so every install/upgrade is checked, regardless of which (or no) Issuer template renders.+*/}}+{{- define "sie-cluster.validateTls" -}}+{{- if .Values.ingress.tls.enabled }}+{{- $mode := .Values.ingress.tls.mode }}+{{- if not (or (eq $mode "byo") (eq $mode "cert-manager")) }}+{{- fail (printf "Invalid configuration: ingress.tls.mode=%q. Must be one of: \"byo\", \"cert-manager\"." $mode) }}+{{- end }}+{{- if eq $mode "cert-manager" }}+{{- if not .Values.ingress.host }}+{{- fail "Invalid configuration: ingress.tls.mode=cert-manager requires ingress.host to be set (cert-manager has nothing to issue a certificate against without a hostname)." }}+{{- end }}+{{- $kind := .Values.ingress.tls.certManager.kind }}+{{- if not (or (eq $kind "ClusterIssuer") (eq $kind "Issuer")) }}+{{- fail (printf "Invalid configuration: ingress.tls.certManager.kind=%q. Must be either \"ClusterIssuer\" or \"Issuer\" (case-sensitive)." $kind) }}+{{- end }}+{{- if .Values.ingress.tls.certManager.create }}+{{- if not .Values.ingress.tls.certManager.server }}+{{- fail "Invalid configuration: ingress.tls.certManager.create=true requires ingress.tls.certManager.server to be set (ACME directory URL is required)." }}+{{- end }}+{{- if not .Values.ingress.tls.certManager.privateKeySecretRef }}+{{- fail "Invalid configuration: ingress.tls.certManager.create=true requires ingress.tls.certManager.privateKeySecretRef to be set (ACME account key Secret name is required)." }}+{{- end }}+{{- if not .Values.ingress.tls.certManager.email }}+{{- fail "Invalid configuration: ingress.tls.certManager.create=true requires ingress.tls.certManager.email to be set (ACME account registration needs an email)." }}+{{- end }}+{{- else }}+{{- if not .Values.ingress.tls.certManager.name }}+{{- fail "Invalid configuration: ingress.tls.certManager.create=false requires ingress.tls.certManager.name to be set (without a name there is no existing Issuer/ClusterIssuer to annotate against)." }}+{{- end }}+{{- end }}+{{- end }}+{{- end }}+{{- end }}+{{/*KEDA apply hook: ServiceAccount name*/}}diff --git a/deploy/helm/sie-cluster/templates/cluster-issuer.yaml b/deploy/helm/sie-cluster/templates/cluster-issuer.yamlnew file mode 100644index 000000000..c4e1f515a--- /dev/null+++ b/deploy/helm/sie-cluster/templates/cluster-issuer.yaml@@ -0,0 +1,23 @@+{{- if and .Values.ingress.tls.enabled (eq .Values.ingress.tls.mode "cert-manager") .Values.ingress.tls.certManager.create }}+{{- $issuerName := .Values.ingress.tls.certManager.name }}+{{- if not $issuerName }}{{ $issuerName = printf "%s-letsencrypt-prod" (include "sie-cluster.fullname" .) }}{{ end }}+apiVersion: cert-manager.io/v1+kind: {{ .Values.ingress.tls.certManager.kind }}+metadata:+ name: {{ $issuerName }}+ {{- if eq .Values.ingress.tls.certManager.kind "Issuer" }}+ namespace: {{ include "sie-cluster.namespace" . }}+ {{- end }}+ labels:+ {{- include "sie-cluster.labels" . | nindent 4 }}+spec:+ acme:+ server: {{ .Values.ingress.tls.certManager.server | quote }}+ email: {{ .Values.ingress.tls.certManager.email | quote }}+ privateKeySecretRef:+ name: {{ .Values.ingress.tls.certManager.privateKeySecretRef | quote }}+ solvers:+ - http01:+ ingress:+ ingressClassName: {{ default .Values.ingress.className .Values.ingress.tls.certManager.ingressClassName }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/config-deployment.yaml b/deploy/helm/sie-cluster/templates/config-deployment.yamlindex 8a875116f..501191661 100644--- a/deploy/helm/sie-cluster/templates/config-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/config-deployment.yaml@@ -94,23 +94,17 @@ spec:httpGet:path: /healthzport: http- initialDelaySeconds: 5- periodSeconds: 5- failureThreshold: 12+ {{- toYaml .Values.config.probes.startup | nindent 12 }}livenessProbe:httpGet:path: /healthzport: http- periodSeconds: 10- timeoutSeconds: 5- failureThreshold: 3+ {{- toYaml .Values.config.probes.liveness | nindent 12 }}readinessProbe:httpGet:path: /readyzport: http- periodSeconds: 5- timeoutSeconds: 3- failureThreshold: 3+ {{- toYaml .Values.config.probes.readiness | nindent 12 }}resources:{{- toYaml .Values.config.resources | nindent 12 }}{{- if .Values.config.configStore.enabled }}diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex 10c4aad3a..a5b5e7f1d 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -162,23 +162,17 @@ spec:httpGet:path: /healthzport: http- initialDelaySeconds: 5- periodSeconds: 5- failureThreshold: 12+ {{- toYaml .Values.gateway.probes.startup | nindent 12 }}livenessProbe:httpGet:path: /healthzport: http- periodSeconds: 10- timeoutSeconds: 5- failureThreshold: 3+ {{- toYaml .Values.gateway.probes.liveness | nindent 12 }}readinessProbe:httpGet:path: /readyzport: http- periodSeconds: 5- timeoutSeconds: 3- failureThreshold: 3+ {{- toYaml .Values.gateway.probes.readiness | nindent 12 }}resources:{{- toYaml .Values.gateway.resources | nindent 12 }}{{- if or .Values.gateway.embeddedConfigs.enabled .Values.gateway.configMap.enabled }}diff --git a/deploy/helm/sie-cluster/templates/ingress.yaml b/deploy/helm/sie-cluster/templates/ingress.yamlindex 4ff0ff2b7..1f2c73621 100644--- a/deploy/helm/sie-cluster/templates/ingress.yaml+++ b/deploy/helm/sie-cluster/templates/ingress.yaml@@ -29,6 +29,13 @@ metadata:}}{{- $annotations = merge $annotations $authDefaults }}{{- end }}+ {{- if and .Values.ingress.tls.enabled (eq .Values.ingress.tls.mode "cert-manager") }}+ {{- $issuerAnnotation := ternary "cert-manager.io/cluster-issuer" "cert-manager.io/issuer" (eq .Values.ingress.tls.certManager.kind "ClusterIssuer") }}+ {{- $issuerName := .Values.ingress.tls.certManager.name }}+ {{- if not $issuerName }}{{ $issuerName = printf "%s-letsencrypt-prod" (include "sie-cluster.fullname" .) }}{{ end }}+ {{- $cmDefaults := dict $issuerAnnotation $issuerName }}+ {{- $annotations = merge $annotations $cmDefaults }}+ {{- end }}{{- if $annotations }}annotations:{{- toYaml $annotations | nindent 4 }}diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex 73472fe91..4275b846e 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -61,6 +61,9 @@ spec:- --host=0.0.0.0- --port={{ $root.Values.workers.common.port }}- --bundle={{ $bundle }}+ {{- if $root.Values.workers.common.clusterCache.enabled }}+ - --cluster-cache=$(SIE_CLUSTER_CACHE)+ {{- end }}ports:- name: httpcontainerPort: {{ $root.Values.workers.common.port }}@@ -156,25 +159,17 @@ spec:httpGet:path: /healthzport: http- periodSeconds: 10- failureThreshold: 60- # Total: 600s (10 min) for model downloads + GPU loading+ {{- toYaml $root.Values.workers.common.probes.startup | nindent 12 }}livenessProbe:httpGet:path: /healthzport: http- initialDelaySeconds: 10- periodSeconds: 30- timeoutSeconds: 10- failureThreshold: 3+ {{- toYaml $root.Values.workers.common.probes.liveness | nindent 12 }}readinessProbe:httpGet:path: /readyzport: http- initialDelaySeconds: 5- periodSeconds: 10- timeoutSeconds: 10- failureThreshold: 3+ {{- toYaml $root.Values.workers.common.probes.readiness | nindent 12 }}resources:requests:{{- toYaml $pool.resources.requests | nindent 14 }}diff --git a/deploy/helm/sie-cluster/values-aws.yaml b/deploy/helm/sie-cluster/values-aws.yamlindex 69a0e865e..a1cf33e49 100644--- a/deploy/helm/sie-cluster/values-aws.yaml+++ b/deploy/helm/sie-cluster/values-aws.yaml@@ -45,6 +45,16 @@ machineProfiles:ingress:enabled: trueclassName: nginx+ # TLS defaults to BYO (user-supplied kubernetes.io/tls Secret).+ # To enable automated HTTPS via cert-manager + Let's Encrypt, install cert-manager+ # in the cluster (one-time prerequisite) and uncomment:+ #+ # host: sie.example.com # required when tls.mode=cert-manager+ # tls:+ # enabled: true+ # mode: cert-manager+ # certManager:+ # email: [email protected]gateway:# HA configuration to match GCPdiff --git a/deploy/helm/sie-cluster/values-gke.yaml b/deploy/helm/sie-cluster/values-gke.yamlindex f8703ec3e..1e6a8f15f 100644--- a/deploy/helm/sie-cluster/values-gke.yaml+++ b/deploy/helm/sie-cluster/values-gke.yaml@@ -67,6 +67,16 @@ healthGates:ingress:enabled: trueclassName: nginx+ # TLS defaults to BYO (user-supplied kubernetes.io/tls Secret).+ # To enable automated HTTPS via cert-manager + Let's Encrypt, install cert-manager+ # in the cluster (one-time prerequisite) and uncomment:+ #+ # host: sie.example.com # required when tls.mode=cert-manager+ # tls:+ # enabled: true+ # mode: cert-manager+ # certManager:+ # email: [email protected]gateway:replicas: 2diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 6083d0f99..769821b33 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -91,6 +91,23 @@ config:adminTokenSecretName: ""adminTokenSecretKey: "SIE_ADMIN_TOKEN"+ # -- Liveness/readiness/startup probe timing. The httpGet path/port are+ # contracts owned by the template (sie-config exposes /healthz and /readyz);+ # only the timing fields below are overridable. Defaults match the previous+ # hardcoded values (modulo the dropped startupProbe.initialDelaySeconds).+ probes:+ startup:+ periodSeconds: 5+ failureThreshold: 12+ liveness:+ periodSeconds: 10+ timeoutSeconds: 5+ failureThreshold: 3+ readiness:+ periodSeconds: 5+ timeoutSeconds: 3+ failureThreshold: 3+# -- Persistent config store for sie-config. Owned by sie-config only (the# gateway no longer persists config). Keep enabled=false in test clusters where# the pod can drop state on restart.@@ -171,8 +188,28 @@ gateway:# Example — bump log verbosity for one pod without touching the chart:# - name: SIE_LOG_LEVEL# value: "debug"+ #+ # Do not use extraEnv to set SIE_GATEWAY_HEALTH_MODE=nats unless you also run+ # a worker-side publisher for sie.health.>. The chart intentionally does not+ # expose gateway.healthMode until NATS worker health is wired end to end.extraEnv: []+ # -- Liveness/readiness/startup probe timing. Mirrors config.probes; httpGet+ # path/port are owned by the template. Defaults match the previous hardcoded+ # values (modulo the dropped startupProbe.initialDelaySeconds).+ probes:+ startup:+ periodSeconds: 5+ failureThreshold: 12+ liveness:+ periodSeconds: 10+ timeoutSeconds: 5+ failureThreshold: 3+ readiness:+ periodSeconds: 5+ timeoutSeconds: 3+ failureThreshold: 3+# -- Embedded configs: auto-generate ConfigMaps from files/ in chart and# mount them at /configs/{bundles,models} on the gateway. Disabled by# default: the gateway pulls bundles+models live from sie-config at startup@@ -275,7 +312,9 @@ workers:# -- Cluster cache (S3/GCS) configurationclusterCache:enabled: false- # -- S3/GCS bucket URL (e.g., s3://my-bucket/models or gs://my-bucket/models)+ # -- S3/GCS bucket URL with the /models prefix (e.g., s3://my-bucket/models or gs://my-bucket/models).+ # AWS users: get this from `terraform output -raw model_cache_bucket_url`.+ # Pre-populate the bucket once with `sie-admin cache weights sync --bundle default --dest <url>/`.url: ""# -- HuggingFace cache configuration@@ -316,6 +355,31 @@ workers:# value: "5"extraEnv: []+ # -- Liveness/readiness/startup probe timing for worker pods. The httpGet+ # path/port are contracts owned by the template (workers expose /healthz+ # and /readyz). Only the timing fields below are overridable.+ #+ # Defaults are tightened to reduce kubelet probe-poll latency on the+ # cold-start path (issue #814):+ # - startupProbe.periodSeconds 10 → 3, failureThreshold 60 → 200+ # (preserves the ≥600s budget: 200 × 3s = 600s for model downloads+ # and GPU loading)+ # - readinessProbe.initialDelaySeconds dropped, periodSeconds 10 → 2+ # so kubelet flips the pod to Ready within ~2s of mark_ready()+ probes:+ startup:+ periodSeconds: 3+ failureThreshold: 200+ liveness:+ initialDelaySeconds: 10+ periodSeconds: 30+ timeoutSeconds: 10+ failureThreshold: 3+ readiness:+ periodSeconds: 2+ timeoutSeconds: 10+ failureThreshold: 3+# -- Worker pools (one StatefulSet per pool)# Each pool creates a WorkerGroup: one StatefulSet + one pre-pull DaemonSet.# Pool naming convention: <machineProfile> (e.g. l4, a100-40gb, cpu).@@ -479,7 +543,33 @@ ingress:# -- TLS configurationtls:enabled: false+ # Mode: byo | cert-manager+ # byo: user supplies a kubernetes.io/tls Secret named `secretName`. (default — backward compatible)+ # cert-manager: chart adds a cert-manager annotation to the main Ingress; cert-manager populates `secretName`.+ # Requires cert-manager to be installed in the cluster (one-time prerequisite).+ mode: byo+ # Name of the kubernetes.io/tls Secret. In cert-manager mode this is where cert-manager writes the cert.secretName: sie-tls+ # cert-manager-specific knobs (only used when mode=cert-manager)+ certManager:+ # Issuer kind: ClusterIssuer (cluster-scoped) | Issuer (namespace-scoped). Case-sensitive.+ kind: ClusterIssuer+ # When true, chart renders the Issuer/ClusterIssuer using settings below.+ # When false, chart only annotates the Ingress, referencing an existing Issuer/ClusterIssuer by `name`.+ create: true+ # Name of the Issuer/ClusterIssuer. Empty string => default "{fullname}-letsencrypt-prod" (release-scoped,+ # avoids collisions when two SIE releases share a cluster). Override to a static name only when there is+ # known to be no other SIE release on this cluster.+ name: ""+ # ACME settings (used only when create=true). Flat (no nested `acme:` block) — ACME is the only supported issuer path.+ server: https://acme-v02.api.letsencrypt.org/directory+ # Email for ACME account registration. REQUIRED when create=true. Empty value triggers a helm install/upgrade fail.+ email: ""+ # Secret name where cert-manager stores the ACME account private key. Cluster-scoped if kind=ClusterIssuer.+ privateKeySecretRef: letsencrypt-account-key+ # HTTP-01 solver ingress class. Empty => defaults to .Values.ingress.className. Override only if your+ # cert-manager solver needs a different class than your data-plane ingress (rare).+ ingressClassName: ""# -- Auth configuration (ingress-nginx + oauth2-proxy)auth:diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex 9a24291f6..ffb59e6be 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.3.1"+version = "0.3.2"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 505c444f7..250fed6e1 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.3.1"+version = "0.3.2"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 468945d7c..76d07b7c2 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.3.1"+version = "0.3.2"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 5adab0d9f..b3963d1ab 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.3.1"+version = "0.3.2"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 0792f2383..41501851b 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.3.1"+version = "0.3.2"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 6cea93269..fbcf99d08 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.3.1"+version = "0.3.2"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex ea8fcc4c5..5c24ae6a3 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.3.1"+version = "0.3.2"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 789064ddf..d07d936ca 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.3.1"+version = "0.3.2"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 be97d8394..035a0ae66 100644--- a/integrations/sie_ts_chroma/package.json+++ b/integrations/sie_ts_chroma/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-chroma",- "version": "0.3.1",+ "version": "0.3.2","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 74ec47172..c3cc956f8 100644--- a/integrations/sie_ts_lancedb/package.json+++ b/integrations/sie_ts_lancedb/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-lancedb",- "version": "0.3.1",+ "version": "0.3.2","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 f6a0266f1..9843f9ec1 100644--- a/integrations/sie_ts_langchain/package.json+++ b/integrations/sie_ts_langchain/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-langchain",- "version": "0.3.1",+ "version": "0.3.2","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 a1cf3999a..3bab62ab4 100644--- a/integrations/sie_ts_llamaindex/package.json+++ b/integrations/sie_ts_llamaindex/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-llamaindex",- "version": "0.3.1",+ "version": "0.3.2","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 60ec3d4f1..9868ddd3b 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.3.1"+version = "0.3.2"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 d84a525bd..65fa8fdbf 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -2774,12 +2774,13 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"[[package]]name = "sie-gateway"-version = "0.3.1"+version = "0.3.2"dependencies = ["arc-swap","async-nats","async-trait","axum",+ "base64","bytes","chrono","clap",@@ -2816,6 +2817,7 @@ dependencies = ["tracing","tracing-subscriber","url",+ "utoipa","uuid","wiremock",]@@ -3410,6 +3412,29 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"+[[package]]+name = "utoipa"+version = "5.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2fcc29c80c21c31608227e0912b2d7fddba57ad76b606890627ba8ee7964e993"+dependencies = [+ "indexmap",+ "serde",+ "serde_json",+ "utoipa-gen",+]++[[package]]+name = "utoipa-gen"+version = "5.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d79d08d92ab8af4c5e8a6da20c47ae3f61a0f1dabc1997cdf2d082b757ca08b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "uuid"version = "1.23.0"diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex b14c342fa..173f45881 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.3.1"+version = "0.3.2"edition = "2021"publish = false@@ -10,6 +10,7 @@ path = "src/main.rs"[dependencies]axum = { version = "0.8", features = ["ws"] }+base64 = "0.22"tokio = { version = "1", features = ["full"] }hyper = { version = "1", features = ["full"] }hyper-util = { version = "0.1", features = ["tokio"] }@@ -66,6 +67,7 @@ percent-encoding = "2"# Cloud config store backends (opt-in)object_store = { version = "0.11", optional = true, features = ["aws", "gcp"] }url = { version = "2", optional = true }+utoipa = "5.4.0"[features]default = []diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.mdindex 8317892df..2ef41f648 100644--- a/packages/sie_gateway/README.md+++ b/packages/sie_gateway/README.md@@ -64,11 +64,12 @@ Key options:--k8s-port <PORT> K8s worker port (default: 8080)-l, --log-level <LEVEL> Log level (default: info)--json-logs Enable structured JSON logging- --health-mode <MODE> Health mode: ws|nats (default: ws)+ --health-mode <MODE> Worker health transport (supported: ws; default: ws)--bundles-dir <PATH> Bundles directory--models-dir <PATH> Models directorysie-gateway version+sie-gateway openapi --output packages/sie_gateway/openapi.json```Each `--flag` above has a matching `SIE_*` environment variable (see next section); CLI flags override env vars.@@ -84,7 +85,7 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio| `SIE_GATEWAY_K8S_NAMESPACE` | `default` | K8s namespace || `SIE_GATEWAY_K8S_SERVICE` | `sie-worker` | K8s service name || `SIE_GATEWAY_K8S_PORT` | `8080` | K8s worker port |-| `SIE_GATEWAY_HEALTH_MODE` | `ws` | Health mode: `ws` or `nats` |+| `SIE_GATEWAY_HEALTH_MODE` | `ws` | Worker health transport. Supported value: `ws`. `nats` is experimental/internal and requires a worker-side `sie.health.>` publisher, which is not wired by default || `SIE_NATS_URL` | | NATS server URL. The process can start without it, but inference requests will return `503` until a usable client exists || `SIE_AUTH_MODE` | `none` | Auth mode for inbound requests: `none` disables, `token` (alias `static`) enforces. Unknown values fail-open-to-bypass; `main` logs a startup error naming the bad value || `SIE_AUTH_TOKENS` | | CSV of valid bearer tokens for inference and pool/config read endpoints. If unset, the singular `SIE_AUTH_TOKEN` is used as a fallback. When auth is enabled and this list is empty, non-probe requests return `500` |@@ -114,10 +115,11 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio| Method | Path | Description ||--------|------|-------------|| GET | `/` | HTML status page |-| GET | `/healthz` | Liveness probe |-| GET | `/readyz` | Readiness probe |+| GET | `/healthz` | Liveness — **`200`**, **`text/plain`** body **`ok`** |+| GET | `/readyz` | Readiness — **`200`** + **`ok`** once the gateway process is serving (**`text/plain`**); worker availability is exposed by `/health` || GET | `/health` | Cluster health JSON || GET | `/metrics` | Prometheus metrics |+| GET | `/openapi.json` | OpenAPI 3 contract for gateway-owned HTTP routes || GET | `/ws/cluster-status` | WebSocket cluster status feed || GET | `/v1/models` | List available models |@@ -143,6 +145,8 @@ Common behaviors:- `503` + `X-SIE-Error-Code: MODEL_LOADING` + `Retry-After: 5` for queue result timeouts (typically a worker cold-loading the target model). SDK clients with `wait_for_capacity=True` retry under the existing `provision_timeout_s` budget.- `503` + `X-SIE-Error-Code: RESOURCE_EXHAUSTED` + `Retry-After: 5` when every item in a batch fails with the same retryable code (`RESOURCE_EXHAUSTED` from worker-side OOM recovery exhaustion, `MODEL_LOADING` from a worker still warming up). The SDK auto-retries with bounded exponential backoff. Mixed batches keep returning `500 all_items_failed` with per-item `code` fields in the response body so callers can see which items hit which failure mode.+The same gateway-owned OpenAPI contract is available at runtime via `GET /openapi.json` and as a committed static artifact at `packages/sie_gateway/openapi.json`. Regenerate it with `mise run openapi` before committing API-surface changes.+### Pool Management| Method | Path | Description |diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 66cdb7be7..fe600607c 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -44,6 +44,7 @@ Key terms used throughout this document:- `POST /v1/encode/{*model}`- `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.{model}.{pool}`.4. A matching worker consumes the work item and executes inference.@@ -60,9 +61,14 @@ Rules enforced on the inference path:- On no-consumer conditions for the JetStream publish the gateway returns `503` with `Retry-After: 120`. On backpressure conditions the gateway returns `503` with `Retry-After: 5`.- On queue result timeouts the gateway returns `503` with `X-SIE-Error-Code: MODEL_LOADING` and `Retry-After: 5`. The most common trigger is a worker cold-loading the target model on demand (worker NAKs the JetStream message and redelivers after load); the SDK retries this under the same `provision_timeout_s` budget used for worker-emitted `MODEL_LOADING` responses.- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED` (worker-side OOM recovery exhausted — `Retry-After: 5`), `MODEL_LOADING`, and `LORA_LOADING`. **Mixed batches** (different codes per item) keep going through the legacy `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.+- When **every** failed item carries **`MODEL_LOAD_FAILED`**, the gateway returns **`502 Bad Gateway`** with the SDK-style **`error`** object (`code`, `message`, `error_class`, `attempts`, `permanent`) — matching the terminal model-load contract consumed by SDK retry logic (no `Retry-After`; the SDK must not burn the `MODEL_LOADING` retry budget). The gateway synthesises conservative `attempts` / `permanent` fields on this queue path when the worker payload does not carry registry-shaped failure metadata.++Encode / extract tuning fields (`output_types`, `instruction`, `options`, `labels`, `output_schema`, `is_query`) are read **only** from the nested JSON **`params`** object (and the msgpack analogue: a top-level **`params`** map). The score path continues to read `query` / `instruction` / `options` at the top level of the request body, matching `sie_server`.Work-item and result payloads on the wire are **msgpack** (`rmp_serde`). JSON is used only for the HTTP request/response envelope when the client negotiates it (via `Content-Type` / `Accept`); the gateway transcodes msgpack ↔ JSON at the edge so the hot path between gateway and workers is always binary.+Gateway-generated **JSON error** bodies (validation, routing, auth, config read, pools) use a FastAPI-like envelope **`{"detail":{"code":"<STABLE_CODE>","message":"…", …}}`**. Extra diagnostic keys (e.g. `compatible_bundles`, `gpu`, `model`) live **inside** `detail` when present. This is intentionally **not** the same shape as SDK retry contracts, which remain **`{"error":{"code","message"}}`** for **503** retryable worker signals and **`502`** **`MODEL_LOAD_FAILED`**. **202 provisioning** and **200** success payloads keep their existing top-level shapes.+## 3. Configuration Write PathAll config mutations go to `sie-config`. The gateway has no write handler.@@ -113,9 +119,11 @@ The gateway does not block startup on `sie-config`. Startup is:1. Construct `ModelRegistry`. In default Helm deploys, `SIE_BUNDLES_DIR` and `SIE_MODELS_DIR` are unset and the registry's filesystem reload is a no-op (warns once that the dirs are missing, then proceeds with empty bundle and model maps). The optional `gateway.embeddedConfigs` / `gateway.configMap` overlays mount a ConfigMap at `/configs/{bundles,models}` and set those env vars; in that mode the registry loads the seed before bootstrap runs.2. Initialize the other runtime subsystems that do not depend on `sie-config`: NATS manager (with config-delta subscription), worker health manager, optional filesystem config watcher, pool manager / K8s backend, and worker discovery.3. Spawn two independent background tasks: `state::config_bootstrap::spawn_bootstrap_retry` and `state::config_poller::spawn`. They share the same `ModelRegistry`, `ConfigEpoch` (monotonic model-write counter), and `BundlesHash` (sha256 fingerprint of `sie-config`'s loaded bundle set). The poller skips its first tick (one `DEFAULT_POLL_INTERVAL` grace) so the initial bootstrap attempt can run first, and then reconciles on every subsequent tick regardless of whether the bootstrap task has completed yet.-4. Bind the HTTP listener. `/readyz` returns `200` unconditionally — it does not gate on `sie-config` reachability.+4. Bind the HTTP listener. Kubernetes probes use plain-text endpoints implemented in `handlers/health.rs`:+ - **`GET /healthz`** — liveness. Always **`200 OK`** with body **`ok`** and **`Content-Type: text/plain; charset=utf-8`** (same wire shape as `sie_server`'s `/healthz`).+ - **`GET /readyz`** — readiness for **routing traffic to this gateway process**. Returns **`200 OK`** + **`ok`** once the gateway listener is serving. It is intentionally independent of worker health and `sie-config` reachability: a gateway with zero healthy workers must still receive the first inference request so it can return `202 + Retry-After` and emit `sie_gateway_pending_demand` for scale-from-zero. Worker availability is exposed on **`GET /health`** and by the inference response path itself.-The bootstrap/poller tasks are spawned **before** the HTTP listener binds, so requests hitting a freshly-bound replica can observe either filesystem-seed-only state or a partially-applied snapshot depending on timing. That is by design; `/readyz` does not gate on control-plane sync (see §11 caveat 3).+The bootstrap/poller tasks are spawned **before** the HTTP listener binds, so requests hitting a freshly-bound replica can observe either filesystem-seed-only state or a partially-applied snapshot depending on timing. That is by design. **`/readyz` does not wait for control-plane sync** (see §11 caveat 3); bootstrap completeness is tracked via **`GET /v1/configs/models/{id}/status`**, **`sie_gateway_config_bootstrap_degraded`**, and **`sie_gateway_config_epoch`** — not by `/readyz` alone.### 4.1 Bootstrap retry@@ -148,7 +156,7 @@ On failure (DNS, 5xx, timeout, decode error, partial apply):During the bootstrap-retry window (before the first successful fetch):-- `/readyz` returns `200` unconditionally. The gateway serves filesystem-seed traffic.+- **`GET /readyz`** follows the **process-readiness** rule above — it is **not** tied to export success or worker health. The gateway still serves whatever models exist in the in-memory registry (typically filesystem-seed-only during this window), and workerless inference requests can still reach the gateway to trigger scale-from-zero.- `GET /v1/configs/models/{id}` returns only filesystem-seeded models.- `POST /v1/configs/resolve` for API-only models returns `404`. Admin tooling retries with backoff.- `ConfigEpoch.get()` typically returns `0` and `GET /v1/configs/models/{id}/status` surfaces `config_epoch: 0`, which admin tooling uses to detect a pre-bootstrap replica. The epoch is not strictly pinned to `0`, however: if the NATS delta subscriber (§4.3) receives a valid `ConfigNotification` with a non-zero `epoch` before the first export succeeds, `ConfigEpoch::set_max` will advance the counter. The `config_bootstrap_degraded` gauge is the more reliable "has export ever succeeded?" signal.@@ -357,11 +365,11 @@ The gateway has no persistent config store. `SIE_CONFIG_STORE_DIR` and `SIE_CONF## 11. Known Operational Caveats-1. **`sie-config` is a single point of failure for the control plane.** While the pod is down, config writes, authoritative config reads, and gateway catch-up fetches all fail. **The inference hot path is unaffected** — it never touches `sie-config`. New gateway pods enter the soft-degraded bootstrap-retry state (§4.1) and serve filesystem-seed traffic until `sie-config` is reachable. The SPOF is rooted in `_IdempotencyState` (in-memory, per-process). Multi-replica requires moving idempotency state to a shared backend (Redis, JetStream KV, a DB row per key). Until then, `replicas: 1` is a deliberate trade of availability for a correct idempotency contract.+1. **`sie-config` is a single point of failure for the control plane.** While the pod is down, config writes, authoritative config reads, and gateway catch-up fetches all fail. **The inference hot path is unaffected** — it never touches `sie-config`. New gateway pods enter the soft-degraded bootstrap-retry state (§4.1), serve filesystem-seed traffic until `sie-config` is reachable, and return **`200 ok`** from **`GET /readyz`** once the process is serving. The SPOF is rooted in `_IdempotencyState` (in-memory, per-process). Multi-replica requires moving idempotency state to a shared backend (Redis, JetStream KV, a DB row per key). Until then, `replicas: 1` is a deliberate trade of availability for a correct idempotency contract.2. **Config deltas use NATS Core pub/sub; deltas published during a gateway-NATS disconnect are lost.** Recovery is automatic via the epoch poller (§4.2). The worst-case staleness window is `DEFAULT_POLL_INTERVAL` plus one export round-trip. No pod restart is required. Shortening `DEFAULT_POLL_INTERVAL` trades load on `sie-config` for recovery time.-3. **Bootstrap is background-retried, not blocking.** A gateway started while `sie-config` is unreachable will serve filesystem-seed traffic immediately. API-added models are missing until the first successful export. `ConfigEpoch` typically stays at `0` during this window — but a NATS delta that arrives before the first export can move it above `0`, so admin tooling should use the `sie_gateway_config_bootstrap_degraded` gauge (set after 10 failed attempts or 5 minutes of sustained failure, cleared on first success) as the authoritative "has this replica ever reconciled with `sie-config`?" signal rather than `config_epoch == 0`.+3. **Bootstrap is background-retried, not blocking.** A gateway started while `sie-config` is unreachable will serve filesystem-seed traffic immediately. API-added models are missing until the first successful export. `ConfigEpoch` typically stays at `0` during this window — but a NATS delta that arrives before the first export can move it above `0`, so admin tooling should use the `sie_gateway_config_bootstrap_degraded` gauge (set after 10 failed attempts or 5 minutes of sustained failure, cleared on first success) as the authoritative "has this replica ever reconciled with `sie-config`?" signal rather than `config_epoch == 0`. **`GET /readyz` does not encode bootstrap completion or worker health**; it is process readiness (§4).4. **Partial NATS publish on `sie-config`.** If a write succeeds on disk and in the registry but the NATS publish fails for a subset of affected bundles, `sie-config` still returns `201` (or `200` for no-op replays) with a structured `warnings` entry naming the failed bundles. Workers on those bundles stay on the previous epoch until the gateway poller triggers a re-export.@@ -380,7 +388,7 @@ The gateway has no persistent config store. `SIE_CONFIG_STORE_DIR` and `SIE_CONFThe `gateway.embeddedConfigs` / `gateway.configMap` Helm overlays remain available as an escape hatch that statically seeds the registry and eliminates the cold-start dependency, at the cost of losing live bundle resync.-8. **`registry_unavailable` (503) on `sie-config`.** If the `ModelRegistry` failed to initialize (e.g. malformed bundle YAML), `sie-config`'s `/readyz` returns 503 and every registry-dependent endpoint (`/v1/configs/models`, `/v1/configs/models/{id}`, `/v1/configs/bundles`, `/v1/configs/bundles/{id}`, `/v1/configs/resolve`, `POST /v1/configs/models`, `/v1/configs/export`) returns 503 with a structured `registry_unavailable` error body. `/epoch` is intentionally independent of the registry (it reads the epoch file directly), so the gateway's poller can still discover that `sie-config` is up but not serving — admin tooling should treat `/readyz=503` plus `/epoch=200` as "control plane is alive but wedged; inspect logs".+8. **`registry_unavailable` (503) on `sie-config`.** (This is **`sie-config`'s** `/readyz`, not the gateway's — same path string, different process.) If the `ModelRegistry` failed to initialize (e.g. malformed bundle YAML), `sie-config`'s `/readyz` returns 503 and every registry-dependent endpoint (`/v1/configs/models`, `/v1/configs/models/{id}`, `/v1/configs/bundles`, `/v1/configs/bundles/{id}`, `/v1/configs/resolve`, `POST /v1/configs/models`, `/v1/configs/export`) returns 503 with a structured `registry_unavailable` error body. `/epoch` is intentionally independent of the registry (it reads the epoch file directly), so the gateway's poller can still discover that `sie-config` is up but not serving — admin tooling should treat **`sie-config` `/readyz=503`** plus **`/epoch=200`** as "control plane is alive but wedged; inspect logs".## 12. Interaction Rules (Invariants)@@ -403,7 +411,7 @@ Gateway (`sie-gateway`):- `SIE_ADMIN_TOKEN` — (1) bearer token the gateway-as-client presents on `GET /v1/configs/export` and `GET /v1/configs/epoch`; (2) the token that `AuthLayer` requires for admin-gated mutations on the gateway itself (`POST/PUT/DELETE` on `/v1/configs/*`, `/v1/admin/*`, `/v1/pools/*`). If empty and the matching inbound request targets an admin path, the middleware fails closed with `403`. On outbound calls, if empty, no `Authorization` header is sent (so `sie-config` must either be unauthenticated or the gateway will fail with `401`/`403`).- `SIE_AUTH_TOKEN` / `SIE_AUTH_TOKENS` — tokens accepted by the gateway's own inference API (`/v1/encode`, `/v1/score`, `/v1/extract`) and for read-side pool/config routes. Not used for outbound calls to `sie-config`. When `SIE_AUTH_MODE` enables auth but this list is empty, every non-probe request returns `500`.- `SIE_AUTH_MODE` — `token` (alias: `static`) enforces auth; `none` (default) disables it. Typos are fail-open-to-bypass by design; `audit_auth` logs a startup error naming the bad value so operators see it in `kubectl logs`.-- `SIE_AUTH_EXEMPT_OPERATIONAL` — when `true`, `/`, `/health`, `/metrics`, and `/ws/*` are exempt from auth (they expose worker URLs, bundle assignments, queue depth, GPU inventory — treat as sensitive). Default `false`. `/healthz` and `/readyz` are **always** exempt because Kubernetes probes carry no credentials; a misconfiguration must not take the pod out of rotation.+- `SIE_AUTH_EXEMPT_OPERATIONAL` — when `true`, `/`, `/health`, `/metrics`, and `/ws/*` are exempt from auth (they expose worker URLs, bundle assignments, queue depth, GPU inventory — treat as sensitive). Default `false`. **`/healthz` and `/readyz` are always exempt from auth** so kubelet probes never fail with **`401`/`403`** because of a missing bearer token. `/readyz` reports process readiness only; worker health remains visible through `/health` and inference responses.- `SIE_NATS_CONFIG_TRUSTED_PRODUCERS` — comma-separated producer allowlist for `sie.config.models._all`. Default `sie-config`. Matching is exact OR K8s pod-name prefix (see §4.3). Untrusted notifications are dropped; the `config_poller` still closes the gap.- `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` — `true` disables producer validation entirely. Intended for local/dev. `main.rs` emits a startup audit warning when on.- NATS connection variables per the existing gateway configuration.@@ -426,6 +434,7 @@ Inference (queue-only):- `POST /v1/encode/{*model}`- `POST /v1/score/{*model}`- `POST /v1/extract/{*model}`+- `POST /v1/embeddings` — OpenAI JSON compatibility layer over encode (string or list of strings); see §2.Config (read-side only):@@ -438,7 +447,7 @@ Config (read-side only):Pools and operator:- `GET /v1/pools`, `POST /v1/pools`, `GET /v1/pools/{name}`, `POST /v1/pools/{name}/renew`, `DELETE /v1/pools/{name}`-- `GET /v1/models`+- `GET /v1/models`, `GET /v1/models/{*model}` — model catalogue. JSON objects mirror `sie_server` **`ModelInfo`** shape (including `inputs`, `outputs`, `dims`, `profiles`, worker-derived `loaded` / `state`, optional `last_error`, …). An unknown `model` id returns **`404`** with **`{"detail":{"code":"MODEL_NOT_FOUND",...}}`** (same envelope style as FastAPI validation errors on `sie_server`).- `GET /healthz`, `GET /readyz`, `GET /health`- `GET /metrics`- `GET /ws/cluster-status`diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonnew file mode 100644index 000000000..d8e6fae2c--- /dev/null+++ b/packages/sie_gateway/openapi.json@@ -0,0 +1,4193 @@+{+ "components": {+ "schemas": {+ "AllItemsFailedResponse": {+ "properties": {+ "details": {+ "items": {+ "$ref": "#/components/schemas/InferenceErrorDetail"+ },+ "type": "array"+ },+ "error": {+ "type": "string"+ }+ },+ "required": [+ "error",+ "details"+ ],+ "type": "object"+ },+ "AssignedWorker": {+ "properties": {+ "gpu": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ },+ "required": [+ "name",+ "url",+ "gpu"+ ],+ "type": "object"+ },+ "BundleConfigDocument": {+ "properties": {+ "adapters": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "name": {+ "type": "string"+ },+ "priority": {+ "format": "int32",+ "type": "integer"+ },+ "source": {+ "type": "string"+ }+ },+ "required": [+ "name",+ "priority",+ "source",+ "adapters"+ ],+ "type": "object"+ },+ "BundleConfigSummary": {+ "properties": {+ "adapter_count": {+ "minimum": 0,+ "type": "integer"+ },+ "bundle_id": {+ "type": "string"+ },+ "connected_workers": {+ "minimum": 0,+ "type": "integer"+ },+ "priority": {+ "format": "int32",+ "type": "integer"+ },+ "source": {+ "type": "string"+ }+ },+ "required": [+ "bundle_id",+ "priority",+ "adapter_count",+ "source",+ "connected_workers"+ ],+ "type": "object"+ },+ "BundleConfigsResponse": {+ "properties": {+ "bundles": {+ "items": {+ "$ref": "#/components/schemas/BundleConfigSummary"+ },+ "type": "array"+ }+ },+ "required": [+ "bundles"+ ],+ "type": "object"+ },+ "BundleConflictResponse": {+ "properties": {+ "detail": {+ "$ref": "#/components/schemas/BundleRoutingConflictDetail"+ }+ },+ "required": [+ "detail"+ ],+ "type": "object"+ },+ "BundleRoutingConflictDetail": {+ "properties": {+ "code": {+ "type": "string"+ },+ "compatible_bundles": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message",+ "compatible_bundles"+ ],+ "type": "object"+ },+ "ClusterSummary": {+ "properties": {+ "gpu_count": {+ "format": "int32",+ "type": "integer"+ },+ "models_loaded": {+ "format": "int32",+ "type": "integer"+ },+ "total_qps": {+ "format": "double",+ "type": "number"+ },+ "worker_count": {+ "format": "int32",+ "type": "integer"+ }+ },+ "required": [+ "worker_count",+ "gpu_count",+ "models_loaded",+ "total_qps"+ ],+ "type": "object"+ },+ "ConfigModelDocument": {+ "properties": {+ "bundles": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "sie_id": {+ "type": "string"+ },+ "source": {+ "type": "string"+ }+ },+ "required": [+ "sie_id",+ "source",+ "bundles"+ ],+ "type": "object"+ },+ "ConfigModelSummary": {+ "properties": {+ "model_id": {+ "type": "string"+ },+ "profiles": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "source": {+ "type": "string"+ }+ },+ "required": [+ "model_id",+ "profiles",+ "source"+ ],+ "type": "object"+ },+ "ConfigModelsResponse": {+ "properties": {+ "models": {+ "items": {+ "$ref": "#/components/schemas/ConfigModelSummary"+ },+ "type": "array"+ }+ },+ "required": [+ "models"+ ],+ "type": "object"+ },+ "CreatePoolRequest": {+ "properties": {+ "bundle": {+ "type": [+ "string",+ "null"+ ]+ },+ "gpus": {+ "additionalProperties": {+ "format": "int32",+ "minimum": 0,+ "type": "integer"+ },+ "minProperties": 1,+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "minimum_worker_count": {+ "format": "int32",+ "minimum": 0,+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "ttl_seconds": {+ "format": "int64",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ }+ },+ "required": [+ "name",+ "gpus"+ ],+ "type": "object"+ },+ "DenseVector": {+ "properties": {+ "dims": {+ "minimum": 0,+ "type": "integer"+ },+ "dtype": {+ "$ref": "#/components/schemas/OutputDtype"+ },+ "values": {+ "items": {+ "format": "float",+ "type": "number"+ },+ "type": "array"+ }+ },+ "required": [+ "dims",+ "dtype",+ "values"+ ],+ "type": "object"+ },+ "DocumentInput": {+ "properties": {+ "data": {+ "items": {+ "format": "int32",+ "minimum": 0,+ "type": "integer"+ },+ "type": "array"+ },+ "format": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },+ "EncodeParams": {+ "properties": {+ "instruction": {+ "type": [+ "string",+ "null"+ ]+ },+ "options": {},+ "output_dtype": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/OutputDtype"+ }+ ]+ },+ "output_types": {+ "items": {+ "$ref": "#/components/schemas/OutputType"+ },+ "type": [+ "array",+ "null"+ ]+ }+ },+ "type": "object"+ },+ "EncodeRequest": {+ "properties": {+ "items": {+ "items": {+ "$ref": "#/components/schemas/ItemInput"+ },+ "minItems": 1,+ "type": "array"+ },+ "params": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EncodeParams"+ }+ ]+ }+ },+ "required": [+ "items"+ ],+ "type": "object"+ },+ "EncodeResponse": {+ "properties": {+ "items": {+ "items": {+ "$ref": "#/components/schemas/EncodeResult"+ },+ "type": "array"+ },+ "model": {+ "type": "string"+ },+ "timing": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/TimingInfo"+ }+ ]+ }+ },+ "required": [+ "model",+ "items"+ ],+ "type": "object"+ },+ "EncodeResult": {+ "properties": {+ "dense": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/DenseVector"+ }+ ]+ },+ "id": {+ "type": [+ "string",+ "null"+ ]+ },+ "multivector": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MultiVector"+ }+ ]+ },+ "sparse": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/SparseVector"+ }+ ]+ }+ },+ "type": "object"+ },+ "Entity": {+ "properties": {+ "bbox": {+ "items": {+ "format": "double",+ "type": "number"+ },+ "type": [+ "array",+ "null"+ ]+ },+ "end": {+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "label": {+ "type": "string"+ },+ "score": {+ "format": "double",+ "type": "number"+ },+ "start": {+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "text": {+ "type": "string"+ }+ },+ "required": [+ "text",+ "label",+ "score"+ ],+ "type": "object"+ },+ "ErrorDetailCore": {+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message"+ ],+ "type": "object"+ },+ "ExtractParams": {+ "properties": {+ "instruction": {+ "type": [+ "string",+ "null"+ ]+ },+ "labels": {+ "items": {+ "type": "string"+ },+ "type": [+ "array",+ "null"+ ]+ },+ "options": {},+ "output_schema": {}+ },+ "type": "object"+ },+ "ExtractRequest": {+ "properties": {+ "items": {+ "items": {+ "$ref": "#/components/schemas/ItemInput"+ },+ "minItems": 1,+ "type": "array"+ },+ "params": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ExtractParams"+ }+ ]+ }+ },+ "required": [+ "items"+ ],+ "type": "object"+ },+ "ExtractResponse": {+ "properties": {+ "items": {+ "items": {+ "$ref": "#/components/schemas/ExtractResult"+ },+ "type": "array"+ },+ "model": {+ "type": "string"+ }+ },+ "required": [+ "model",+ "items"+ ],+ "type": "object"+ },+ "ExtractResult": {+ "properties": {+ "classifications": {+ "items": {},+ "type": "array"+ },+ "data": {},+ "entities": {+ "items": {+ "$ref": "#/components/schemas/Entity"+ },+ "type": "array"+ },+ "id": {+ "type": "string"+ },+ "relations": {+ "items": {+ "$ref": "#/components/schemas/Relation"+ },+ "type": "array"+ }+ },+ "required": [+ "id"+ ],+ "type": "object"+ },+ "GatewayErrorResponse": {+ "properties": {+ "configured_gpu_types": {+ "items": {+ "type": "string"+ },+ "type": [+ "array",+ "null"+ ]+ },+ "details": {+ "items": {+ "$ref": "#/components/schemas/InferenceErrorDetail"+ },+ "type": [+ "array",+ "null"+ ]+ },+ "error": {},+ "gpu": {+ "type": [+ "string",+ "null"+ ]+ },+ "message": {+ "type": [+ "string",+ "null"+ ]+ },+ "status": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "type": "object"+ },+ "GatewayModelLoadFailedDetail": {+ "description": "SDK-style ``502`` body for ``MODEL_LOAD_FAILED`` (SDK short-circuit).",+ "properties": {+ "attempts": {+ "format": "int32",+ "type": "integer"+ },+ "code": {+ "type": "string"+ },+ "error_class": {+ "type": [+ "string",+ "null"+ ]+ },+ "message": {+ "type": "string"+ },+ "permanent": {+ "type": "boolean"+ }+ },+ "required": [+ "code",+ "message",+ "attempts",+ "permanent"+ ],+ "type": "object"+ },+ "GatewayModelLoadFailedResponse": {+ "properties": {+ "error": {+ "$ref": "#/components/schemas/GatewayModelLoadFailedDetail"+ }+ },+ "required": [+ "error"+ ],+ "type": "object"+ },+ "GpuNotConfiguredDetail": {+ "description": "``detail`` when the caller's ``X-SIE-MACHINE-PROFILE`` GPU is not in the gateway allow-list.",+ "properties": {+ "code": {+ "type": "string"+ },+ "configured_gpu_types": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "gpu": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message",+ "gpu",+ "configured_gpu_types"+ ],+ "type": "object"+ },+ "GpuNotConfiguredError": {+ "properties": {+ "detail": {+ "$ref": "#/components/schemas/GpuNotConfiguredDetail"+ }+ },+ "required": [+ "detail"+ ],+ "type": "object"+ },+ "HealthResponse": {+ "properties": {+ "cluster": {+ "$ref": "#/components/schemas/ClusterSummary"+ },+ "configured_gpu_types": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "live_gpu_types": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "models": {+ "items": {+ "$ref": "#/components/schemas/ModelInfo"+ },+ "type": "array"+ },+ "status": {+ "type": "string"+ },+ "type": {+ "type": "string"+ },+ "workers": {+ "items": {+ "$ref": "#/components/schemas/WorkerInfo"+ },+ "type": "array"+ }+ },+ "required": [+ "status",+ "type",+ "configured_gpu_types",+ "live_gpu_types",+ "cluster",+ "workers",+ "models"+ ],+ "type": "object"+ },+ "ImageInput": {+ "properties": {+ "data": {+ "items": {+ "format": "int32",+ "minimum": 0,+ "type": "integer"+ },+ "type": "array"+ },+ "format": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },+ "InferenceErrorDetail": {+ "properties": {+ "code": {+ "type": [+ "string",+ "null"+ ]+ },+ "error": {+ "type": [+ "string",+ "null"+ ]+ },+ "item_index": {+ "format": "int32",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "item_index"+ ],+ "type": "object"+ },+ "InferenceInternalServerErrorResponse": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/AllItemsFailedResponse"+ },+ {+ "$ref": "#/components/schemas/StandardApiError"+ }+ ]+ },+ "InferenceServiceUnavailableResponse": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/GatewayErrorResponse"+ },+ {+ "$ref": "#/components/schemas/StandardApiError"+ },+ {+ "$ref": "#/components/schemas/GpuNotConfiguredError"+ }+ ]+ },+ "ItemInput": {+ "properties": {+ "document": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/DocumentInput"+ }+ ]+ },+ "id": {+ "type": [+ "string",+ "null"+ ]+ },+ "images": {+ "items": {+ "$ref": "#/components/schemas/ImageInput"+ },+ "type": [+ "array",+ "null"+ ]+ },+ "metadata": {},+ "text": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "type": "object"+ },+ "MessageResponse": {+ "properties": {+ "message": {+ "type": "string"+ }+ },+ "required": [+ "message"+ ],+ "type": "object"+ },+ "ModelAckBundleStatus": {+ "properties": {+ "acked": {+ "type": "boolean"+ },+ "acked_workers": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "bundle_id": {+ "type": "string"+ },+ "expected_bundle_config_hash": {+ "type": "string"+ },+ "pending_workers": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "total_eligible_workers": {+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "bundle_id",+ "expected_bundle_config_hash",+ "total_eligible_workers",+ "acked_workers",+ "pending_workers",+ "acked"+ ],+ "type": "object"+ },+ "ModelConfigStatusResponse": {+ "properties": {+ "all_bundles_acked": {+ "type": "boolean"+ },+ "bundles": {+ "items": {+ "$ref": "#/components/schemas/ModelAckBundleStatus"+ },+ "type": "array"+ },+ "config_epoch": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "model_id": {+ "type": "string"+ },+ "no_bundles": {+ "type": "boolean"+ },+ "source": {+ "type": "string"+ }+ },+ "required": [+ "model_id",+ "config_epoch",+ "all_bundles_acked",+ "no_bundles",+ "bundles",+ "source"+ ],+ "type": "object"+ },+ "ModelInfo": {+ "properties": {+ "gpu_types": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "name": {+ "type": "string"+ },+ "state": {+ "type": "string"+ },+ "total_queue_depth": {+ "format": "int32",+ "type": "integer"+ },+ "worker_count": {+ "format": "int32",+ "type": "integer"+ }+ },+ "required": [+ "name",+ "state",+ "worker_count",+ "gpu_types",+ "total_queue_depth"+ ],+ "type": "object"+ },+ "ModelInfoWire": {+ "description": "Wire shape aligned with ``sie_server`` ``ModelInfo`` for ``GET /v1/models``.",+ "properties": {+ "dims": {+ "additionalProperties": {+ "format": "int64",+ "type": "integer"+ },+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "inputs": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "last_error": {},+ "loaded": {+ "type": "boolean"+ },+ "max_sequence_length": {+ "format": "int64",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "name": {+ "type": "string"+ },+ "outputs": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "profiles": {+ "additionalProperties": {+ "$ref": "#/components/schemas/ProfileInfoWire"+ },+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "state": {+ "type": "string"+ }+ },+ "required": [+ "name",+ "inputs",+ "outputs",+ "dims",+ "loaded",+ "state",+ "profiles"+ ],+ "type": "object"+ },+ "ModelNotFoundDetail": {+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message"+ ],+ "type": "object"+ },+ "ModelNotFoundResponse": {+ "properties": {+ "detail": {+ "$ref": "#/components/schemas/ModelNotFoundDetail"+ }+ },+ "required": [+ "detail"+ ],+ "type": "object"+ },+ "ModelsResponse": {+ "properties": {+ "models": {+ "items": {+ "$ref": "#/components/schemas/ModelInfoWire"+ },+ "type": "array"+ }+ },+ "required": [+ "models"+ ],+ "type": "object"+ },+ "MultiVector": {+ "properties": {+ "dtype": {+ "$ref": "#/components/schemas/OutputDtype"+ },+ "num_tokens": {+ "minimum": 0,+ "type": "integer"+ },+ "token_dims": {+ "minimum": 0,+ "type": "integer"+ },+ "values": {+ "items": {+ "items": {+ "format": "float",+ "type": "number"+ },+ "type": "array"+ },+ "type": "array"+ }+ },+ "required": [+ "token_dims",+ "num_tokens",+ "dtype",+ "values"+ ],+ "type": "object"+ },+ "OpenAIEmbeddingDataEntry": {+ "properties": {+ "embedding": {+ "$ref": "#/components/schemas/OpenAIEmbeddingVector"+ },+ "index": {+ "minimum": 0,+ "type": "integer"+ },+ "object": {+ "type": "string"+ }+ },+ "required": [+ "object",+ "embedding",+ "index"+ ],+ "type": "object"+ },+ "OpenAIEmbeddingEncodingFormat": {+ "enum": [+ "float",+ "base64"+ ],+ "type": "string"+ },+ "OpenAIEmbeddingInput": {+ "oneOf": [+ {+ "type": "string"+ },+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ ]+ },+ "OpenAIEmbeddingRequest": {+ "description": "OpenAI-compatible ``POST /v1/embeddings`` request (subset supported on gateway).",+ "properties": {+ "dimensions": {+ "description": "Accepted but ignored; the gateway returns the model's native dimension.",+ "format": "int32",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "encoding_format": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/OpenAIEmbeddingEncodingFormat"+ }+ ]+ },+ "input": {+ "$ref": "#/components/schemas/OpenAIEmbeddingInput"+ },+ "model": {+ "type": "string"+ },+ "user": {+ "description": "Accepted but ignored; kept for OpenAI SDK compatibility.",+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "model",+ "input"+ ],+ "type": "object"+ },+ "OpenAIEmbeddingUsage": {+ "properties": {+ "prompt_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "total_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "prompt_tokens",+ "total_tokens"+ ],+ "type": "object"+ },+ "OpenAIEmbeddingVector": {+ "oneOf": [+ {+ "items": {+ "format": "double",+ "type": "number"+ },+ "type": "array"+ },+ {+ "type": "string"+ }+ ]+ },+ "OpenAIEmbeddingsListResponse": {+ "properties": {+ "data": {+ "items": {+ "$ref": "#/components/schemas/OpenAIEmbeddingDataEntry"+ },+ "type": "array"+ },+ "model": {+ "type": "string"+ },+ "object": {+ "type": "string"+ },+ "usage": {+ "$ref": "#/components/schemas/OpenAIEmbeddingUsage"+ }+ },+ "required": [+ "object",+ "data",+ "model",+ "usage"+ ],+ "type": "object"+ },+ "OutputDtype": {+ "enum": [+ "float32",+ "float16",+ "int8",+ "uint8",+ "binary"+ ],+ "type": "string"+ },+ "OutputType": {+ "enum": [+ "dense",+ "sparse",+ "multivector"+ ],+ "type": "string"+ },+ "Pool": {+ "properties": {+ "spec": {+ "$ref": "#/components/schemas/PoolSpec"+ },+ "status": {+ "$ref": "#/components/schemas/PoolStatus"+ }+ },+ "required": [+ "spec",+ "status"+ ],+ "type": "object"+ },+ "PoolListResponse": {+ "properties": {+ "pools": {+ "items": {+ "$ref": "#/components/schemas/Pool"+ },+ "type": "array"+ }+ },+ "required": [+ "pools"+ ],+ "type": "object"+ },+ "PoolSpec": {+ "properties": {+ "bundle": {+ "type": [+ "string",+ "null"+ ]+ },+ "gpus": {+ "additionalProperties": {+ "format": "int32",+ "minimum": 0,+ "type": "integer"+ },+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "minimum_worker_count": {+ "format": "int32",+ "minimum": 0,+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "ttl_seconds": {+ "format": "int64",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ }+ },+ "required": [+ "name"+ ],+ "type": "object"+ },+ "PoolState": {+ "enum": [+ "pending",+ "active",+ "expired"+ ],+ "type": "string"+ },+ "PoolStatus": {+ "properties": {+ "assigned_workers": {+ "items": {+ "$ref": "#/components/schemas/AssignedWorker"+ },+ "type": "array"+ },+ "created_at": {+ "format": "double",+ "type": "number"+ },+ "last_renewed": {+ "format": "double",+ "type": "number"+ },+ "state": {+ "$ref": "#/components/schemas/PoolState"+ }+ },+ "required": [+ "state"+ ],+ "type": "object"+ },+ "ProfileInfoWire": {+ "properties": {+ "is_default": {+ "type": "boolean"+ }+ },+ "type": "object"+ },+ "ProvisioningResponse": {+ "properties": {+ "bundle": {+ "type": "string"+ },+ "estimated_wait_s": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "gpu": {+ "type": "string"+ },+ "message": {+ "type": "string"+ },+ "status": {+ "type": "string"+ }+ },+ "required": [+ "status",+ "estimated_wait_s"+ ],+ "type": "object"+ },+ "Relation": {+ "properties": {+ "head": {+ "type": "string"+ },+ "relation": {+ "type": "string"+ },+ "score": {+ "format": "double",+ "type": "number"+ },+ "tail": {+ "type": "string"+ }+ },+ "required": [+ "head",+ "tail",+ "relation",+ "score"+ ],+ "type": "object"+ },+ "ResolveBundleConflictDetail": {+ "properties": {+ "bundle": {+ "type": "string"+ },+ "code": {+ "type": "string"+ },+ "compatible_bundles": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "message": {+ "type": "string"+ },+ "model": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message",+ "model",+ "bundle",+ "compatible_bundles"+ ],+ "type": "object"+ },+ "ResolveBundleConflictResponse": {+ "properties": {+ "detail": {+ "$ref": "#/components/schemas/ResolveBundleConflictDetail"+ }+ },+ "required": [+ "detail"+ ],+ "type": "object"+ },+ "ResolveConfigResponse": {+ "properties": {+ "compatible_bundles": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "model": {+ "type": "string"+ },+ "profiles": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "resolved_bundle": {+ "type": "string"+ }+ },+ "required": [+ "model",+ "resolved_bundle",+ "compatible_bundles",+ "profiles"+ ],+ "type": "object"+ },+ "ResolveModelNotFoundDetail": {+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ },+ "model": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message",+ "model"+ ],+ "type": "object"+ },+ "ResolveModelNotFoundResponse": {+ "properties": {+ "detail": {+ "$ref": "#/components/schemas/ResolveModelNotFoundDetail"+ }+ },+ "required": [+ "detail"+ ],+ "type": "object"+ },+ "ResolveRequest": {+ "description": "POST /v1/configs/resolve - Resolve bundle for a model.",+ "properties": {+ "bundle": {+ "type": [+ "string",+ "null"+ ]+ },+ "model": {+ "type": "string"+ }+ },+ "required": [+ "model"+ ],+ "type": "object"+ },+ "ScoreEntry": {+ "properties": {+ "item_id": {+ "type": "string"+ },+ "rank": {+ "minimum": 0,+ "type": "integer"+ },+ "score": {+ "format": "double",+ "type": "number"+ }+ },+ "required": [+ "item_id",+ "score",+ "rank"+ ],+ "type": "object"+ },+ "ScoreRequest": {+ "properties": {+ "instruction": {+ "type": [+ "string",+ "null"+ ]+ },+ "items": {+ "items": {+ "$ref": "#/components/schemas/ItemInput"+ },+ "minItems": 1,+ "type": "array"+ },+ "options": {},+ "query": {+ "$ref": "#/components/schemas/ItemInput"+ }+ },+ "required": [+ "query",+ "items"+ ],+ "type": "object"+ },+ "ScoreResponse": {+ "properties": {+ "model": {+ "type": "string"+ },+ "query_id": {+ "type": [+ "string",+ "null"+ ]+ },+ "scores": {+ "items": {+ "$ref": "#/components/schemas/ScoreEntry"+ },+ "type": "array"+ }+ },+ "required": [+ "model",+ "scores"+ ],+ "type": "object"+ },+ "SparseVector": {+ "properties": {+ "dims": {+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "dtype": {+ "$ref": "#/components/schemas/OutputDtype"+ },+ "indices": {+ "items": {+ "minimum": 0,+ "type": "integer"+ },+ "type": "array"+ },+ "values": {+ "items": {+ "format": "float",+ "type": "number"+ },+ "type": "array"+ }+ },+ "required": [+ "dtype",+ "indices",+ "values"+ ],+ "type": "object"+ },+ "StandardApiError": {+ "description": "FastAPI-style error envelope for most gateway JSON errors.",+ "properties": {+ "detail": {+ "$ref": "#/components/schemas/ErrorDetailCore"+ }+ },+ "required": [+ "detail"+ ],+ "type": "object"+ },+ "TimingInfo": {+ "properties": {+ "inference_ms": {+ "format": "double",+ "type": "number"+ },+ "postprocessing_ms": {+ "format": "double",+ "type": [+ "number",+ "null"+ ]+ },+ "queue_ms": {+ "format": "double",+ "type": "number"+ },+ "tokenization_ms": {+ "format": "double",+ "type": "number"+ },+ "total_ms": {+ "format": "double",+ "type": "number"+ }+ },+ "required": [+ "total_ms",+ "queue_ms",+ "tokenization_ms",+ "inference_ms"+ ],+ "type": "object"+ },+ "WorkerInfo": {+ "properties": {+ "bundle": {+ "type": "string"+ },+ "bundle_config_hash": {+ "type": "string"+ },+ "gpu": {+ "type": "string"+ },+ "gpu_count": {+ "format": "int32",+ "type": "integer"+ },+ "healthy": {+ "type": "boolean"+ },+ "loaded_models": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "memory_total_bytes": {+ "format": "int64",+ "type": "integer"+ },+ "memory_used_bytes": {+ "format": "int64",+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "queue_depth": {+ "format": "int32",+ "type": "integer"+ },+ "url": {+ "type": "string"+ }+ },+ "required": [+ "name",+ "url",+ "gpu",+ "gpu_count",+ "loaded_models",+ "queue_depth",+ "memory_used_bytes",+ "memory_total_bytes",+ "healthy",+ "bundle",+ "bundle_config_hash"+ ],+ "type": "object"+ }+ },+ "securitySchemes": {+ "bearerAuth": {+ "bearerFormat": "opaque",+ "description": "SIE bearer token. Mutating pool/config/admin routes require the configured admin token; other protected routes accept a normal gateway token.",+ "scheme": "bearer",+ "type": "http"+ }+ }+ },+ "info": {+ "description": "Rust gateway API for SIE inference, pool coordination, and read-only runtime config.",+ "license": {+ "name": "Apache-2.0",+ "url": "https://www.apache.org/licenses/LICENSE-2.0.html"+ },+ "title": "SIE Gateway",+ "version": "0.3.2"+ },+ "openapi": "3.1.0",+ "paths": {+ "/": {+ "get": {+ "operationId": "status_page",+ "responses": {+ "200": {+ "content": {+ "text/html": {+ "schema": {+ "type": "string"+ }+ }+ },+ "description": "HTML gateway status page"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "summary": "Static HTML status page",+ "tags": [+ "health"+ ]+ }+ },+ "/health": {+ "get": {+ "operationId": "health",+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HealthResponse"+ }+ }+ },+ "description": "Gateway cluster health"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "health"+ ]+ }+ },+ "/healthz": {+ "get": {+ "operationId": "healthz",+ "responses": {+ "200": {+ "content": {+ "text/plain; charset=utf-8": {+ "schema": {+ "type": "string"+ }+ }+ },+ "description": "Liveness probe (plain text, matches sie_server)"+ }+ },+ "security": [],+ "tags": [+ "health"+ ]+ }+ },+ "/metrics": {+ "get": {+ "operationId": "metrics_handler",+ "responses": {+ "200": {+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ },+ "description": "Prometheus metrics"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "observability"+ ]+ }+ },+ "/openapi.json": {+ "get": {+ "operationId": "openapi_json",+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "type": "object"+ }+ }+ },+ "description": "OpenAPI document"+ }+ },+ "security": [],+ "tags": [+ "docs"+ ]+ }+ },+ "/readyz": {+ "get": {+ "description": "Process readiness only. Always returns 200 once the gateway is serving requests; never returns 503. Worker readiness is reported by GET /health and by inference responses (202 + Retry-After from a workerless gateway). This contract supports KEDA scale-from-zero.",+ "operationId": "readyz",+ "responses": {+ "200": {+ "content": {+ "text/plain; charset=utf-8": {+ "schema": {+ "type": "string"+ }+ }+ },+ "description": "Gateway process is ready"+ }+ },+ "security": [],+ "tags": [+ "health"+ ]+ }+ },+ "/v1/configs/bundles": {+ "get": {+ "operationId": "get_bundle_configs",+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BundleConfigsResponse"+ }+ }+ },+ "description": "Bundle configs visible to this gateway replica"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "summary": "GET /v1/configs/bundles - List all bundle configs.",+ "tags": [+ "config"+ ]+ }+ },+ "/v1/configs/bundles/{id}": {+ "get": {+ "operationId": "get_bundle_config",+ "parameters": [+ {+ "description": "Bundle id",+ "in": "path",+ "name": "id",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/x-yaml": {+ "schema": {+ "$ref": "#/components/schemas/BundleConfigDocument"+ }+ }+ },+ "description": "Bundle config YAML"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Bundle not found"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Failed to serialize YAML; gateway auth enabled but no tokens configured"+ }+ },+ "summary": "GET /v1/configs/bundles/{id} - Get specific bundle config.",+ "tags": [+ "config"+ ]+ }+ },+ "/v1/configs/models": {+ "get": {+ "operationId": "get_model_configs",+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConfigModelsResponse"+ }+ }+ },+ "description": "Model configs visible to this gateway replica"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "summary": "GET /v1/configs/models - List all model configs visible to this gateway.",+ "tags": [+ "config"+ ]+ }+ },+ "/v1/configs/models/{id}": {+ "get": {+ "description": "Handles two endpoints sharing the same wildcard route:\n\n- `GET /v1/configs/models/{id}` — YAML view of the gateway's model.\n- `GET /v1/configs/models/{id}/status` — JSON worker-ack readiness for\n that model on this specific gateway replica.\n\nThe `{*id}` wildcard is necessary because model IDs routinely contain\nforward slashes (`BAAI/bge-m3`), so we strip an optional trailing\n`/status` segment here rather than maintain two overlapping axum routes\n(axum's `matchit` panics on overlapping catch-all routes).\n\nDisambiguation when a model literally named `something/status` exists:\nwe prefer the status interpretation only when the `/status`-stripped\nid resolves to a real model. That keeps an accidental model whose ID\nends with `/status` addressable under `GET\n/v1/configs/models/foo/status` as a config read, and matches what\nadmin tooling expects (status requests are only meaningful against\nmodels that actually exist). `sie-config` additionally refuses to\nregister model IDs ending in `/status` so the pathological case where\n**both** `foo` and `foo/status` are models cannot arise, but we\nstill degrade gracefully if it ever does.",+ "operationId": "get_model_config_or_status",+ "parameters": [+ {+ "description": "Model id. Runtime route is Axum catch-all `/v1/configs/models/{*id}`; clients using this OpenAPI path template should percent-encode slashes in model ids, for example `BAAI%2Fbge-m3`.",+ "in": "path",+ "name": "id",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/x-yaml": {+ "schema": {+ "$ref": "#/components/schemas/ConfigModelDocument"+ }+ }+ },+ "description": "Model config YAML"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Model not found"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Failed to serialize YAML; gateway auth enabled but no tokens configured"+ }+ },+ "summary": "GET /v1/configs/models/{*id} — dual-purpose dispatcher.",+ "tags": [+ "config"+ ],+ "x-sie-axum-catch-all": "/v1/configs/models/{*id}"+ }+ },+ "/v1/configs/models/{id}/status": {+ "get": {+ "operationId": "get_model_config_status",+ "parameters": [+ {+ "description": "Model id. Runtime route is Axum catch-all `/v1/configs/models/{*id}`; clients using this OpenAPI path template should percent-encode slashes in model ids, for example `BAAI%2Fbge-m3`.",+ "in": "path",+ "name": "id",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelConfigStatusResponse"+ }+ }+ },+ "description": "Per-replica worker acknowledgement status"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Model not found"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "config"+ ],+ "x-sie-axum-catch-all": "/v1/configs/models/{*id}"+ }+ },+ "/v1/configs/resolve": {+ "post": {+ "operationId": "resolve_config",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ResolveRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ResolveConfigResponse"+ }+ }+ },+ "description": "Resolved runtime bundle"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "403": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Valid bearer token but admin token required for this mutation (or admin token not configured)"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ResolveModelNotFoundResponse"+ }+ }+ },+ "description": "Model not found"+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ResolveBundleConflictResponse"+ }+ }+ },+ "description": "Bundle override conflict"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "config"+ ]+ }+ },+ "/v1/embeddings": {+ "post": {+ "description": "OpenAI-compatible embeddings proxy. A 200 response contains one embedding per input; partial or truncated internal encode success is treated as a 500 INTERNAL_ERROR instead of returning a partial 200.",+ "operationId": "proxy_openai_embeddings",+ "parameters": [+ {+ "description": "Preferred GPU or machine profile",+ "in": "header",+ "name": "X-SIE-MACHINE-PROFILE",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Explicit pool routing override",+ "in": "header",+ "name": "X-SIE-Pool",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Client SDK version for skew warnings",+ "in": "header",+ "name": "X-SIE-SDK-Version",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIEmbeddingRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIEmbeddingsListResponse"+ }+ }+ },+ "description": "OpenAI-compatible embeddings response",+ "headers": {+ "X-Inference-Time": {+ "description": "Worker-reported inference time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Payload-Fetch-Time": {+ "description": "Worker-reported offloaded payload fetch time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Postprocessing-Time": {+ "description": "Worker-reported postprocessing time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Publish-Time": {+ "description": "Milliseconds spent publishing work to the queue",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Time": {+ "description": "Worker-reported queue time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Wait-Time": {+ "description": "Milliseconds spent waiting for worker results",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Request-Id": {+ "description": "Gateway request id for queue-backed inference",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Worker": {+ "description": "Logical queue worker tag that produced the response",+ "schema": {+ "type": "string"+ }+ },+ "X-Tokenization-Time": {+ "description": "Worker-reported tokenization time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "202": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ProvisioningResponse"+ }+ }+ },+ "description": "Worker provisioning in progress",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Invalid request"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Model not found"+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BundleConflictResponse"+ }+ }+ },+ "description": "Bundle override conflicts with model routing"+ },+ "413": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Request body too large"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/InferenceInternalServerErrorResponse"+ },+ {+ "$ref": "#/components/schemas/StandardApiError"+ }+ ]+ }+ }+ },+ "description": "All batch items failed or gateway internal error; gateway auth enabled but no tokens configured"+ },+ "502": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GatewayModelLoadFailedResponse"+ }+ }+ },+ "description": "MODEL_LOAD_FAILED",+ "headers": {+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Version": {+ "description": "Gateway package version associated with the error envelope",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "503": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/InferenceServiceUnavailableResponse"+ }+ }+ },+ "description": "Model loading, capacity, queue unavailable, or GPU not configured",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds, when retryable",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "504": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Result channel closed"+ }+ },+ "tags": [+ "inference"+ ]+ }+ },+ "/v1/encode/{model}": {+ "post": {+ "description": "Mixed-success batches return 200 with only successful items; the response carries no per-item error envelope. For per-item error visibility, send single-item batches.",+ "operationId": "proxy_encode",+ "parameters": [+ {+ "description": "Model id. Runtime route is Axum catch-all `/v1/encode/{*model}`; clients using this OpenAPI path template should percent-encode slashes in model ids, for example `BAAI%2Fbge-m3`.",+ "in": "path",+ "name": "model",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "description": "Preferred GPU or machine profile",+ "in": "header",+ "name": "X-SIE-MACHINE-PROFILE",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Explicit pool routing override",+ "in": "header",+ "name": "X-SIE-Pool",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Client SDK version for skew warnings",+ "in": "header",+ "name": "X-SIE-SDK-Version",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EncodeRequest"+ }+ },+ "application/msgpack": {+ "schema": {+ "$ref": "#/components/schemas/EncodeRequest"+ }+ },+ "application/vnd.msgpack": {+ "schema": {+ "$ref": "#/components/schemas/EncodeRequest"+ }+ },+ "application/x-msgpack": {+ "schema": {+ "$ref": "#/components/schemas/EncodeRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EncodeResponse"+ }+ },+ "application/msgpack": {+ "schema": {+ "$ref": "#/components/schemas/EncodeResponse"+ }+ },+ "application/vnd.msgpack": {+ "schema": {+ "$ref": "#/components/schemas/EncodeResponse"+ }+ },+ "application/x-msgpack": {+ "schema": {+ "$ref": "#/components/schemas/EncodeResponse"+ }+ }+ },+ "description": "Encode response",+ "headers": {+ "X-Inference-Time": {+ "description": "Worker-reported inference time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Payload-Fetch-Time": {+ "description": "Worker-reported offloaded payload fetch time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Postprocessing-Time": {+ "description": "Worker-reported postprocessing time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Publish-Time": {+ "description": "Milliseconds spent publishing work to the queue",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Time": {+ "description": "Worker-reported queue time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Wait-Time": {+ "description": "Milliseconds spent waiting for worker results",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Request-Id": {+ "description": "Gateway request id for queue-backed inference",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Worker": {+ "description": "Logical queue worker tag that produced the response",+ "schema": {+ "type": "string"+ }+ },+ "X-Tokenization-Time": {+ "description": "Worker-reported tokenization time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "202": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ProvisioningResponse"+ }+ }+ },+ "description": "Worker provisioning in progress",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Invalid request"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Model not found"+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BundleConflictResponse"+ }+ }+ },+ "description": "Bundle override conflicts with model routing"+ },+ "413": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Request body too large"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/InferenceInternalServerErrorResponse"+ },+ {+ "$ref": "#/components/schemas/StandardApiError"+ }+ ]+ }+ }+ },+ "description": "All batch items failed or gateway internal error; gateway auth enabled but no tokens configured"+ },+ "502": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GatewayModelLoadFailedResponse"+ }+ }+ },+ "description": "Terminal model load failure (MODEL_LOAD_FAILED)",+ "headers": {+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Version": {+ "description": "Gateway package version associated with the error envelope",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "503": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/InferenceServiceUnavailableResponse"+ }+ }+ },+ "description": "Queue unavailable, GPU not configured, model loading, or capacity exhausted",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds, when retryable",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "504": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Result channel closed"+ }+ },+ "tags": [+ "inference"+ ],+ "x-sie-axum-catch-all": "/v1/encode/{*model}"+ }+ },+ "/v1/extract/{model}": {+ "post": {+ "description": "Mixed-success batches return 200 with only successful items; the response carries no per-item error envelope. For per-item error visibility, send single-item batches.",+ "operationId": "proxy_extract",+ "parameters": [+ {+ "description": "Model id. Runtime route is Axum catch-all `/v1/extract/{*model}`; clients using this OpenAPI path template should percent-encode slashes in model ids, for example `BAAI%2Fbge-m3`.",+ "in": "path",+ "name": "model",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "description": "Preferred GPU or machine profile",+ "in": "header",+ "name": "X-SIE-MACHINE-PROFILE",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Explicit pool routing override",+ "in": "header",+ "name": "X-SIE-Pool",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Client SDK version for skew warnings",+ "in": "header",+ "name": "X-SIE-SDK-Version",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ExtractRequest"+ }+ },+ "application/msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ExtractRequest"+ }+ },+ "application/vnd.msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ExtractRequest"+ }+ },+ "application/x-msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ExtractRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ExtractResponse"+ }+ },+ "application/msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ExtractResponse"+ }+ },+ "application/vnd.msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ExtractResponse"+ }+ },+ "application/x-msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ExtractResponse"+ }+ }+ },+ "description": "Extract response",+ "headers": {+ "X-Inference-Time": {+ "description": "Worker-reported inference time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Payload-Fetch-Time": {+ "description": "Worker-reported offloaded payload fetch time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Postprocessing-Time": {+ "description": "Worker-reported postprocessing time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Publish-Time": {+ "description": "Milliseconds spent publishing work to the queue",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Time": {+ "description": "Worker-reported queue time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Wait-Time": {+ "description": "Milliseconds spent waiting for worker results",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Request-Id": {+ "description": "Gateway request id for queue-backed inference",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Worker": {+ "description": "Logical queue worker tag that produced the response",+ "schema": {+ "type": "string"+ }+ },+ "X-Tokenization-Time": {+ "description": "Worker-reported tokenization time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "202": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ProvisioningResponse"+ }+ }+ },+ "description": "Worker provisioning in progress",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Invalid request"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Model not found"+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BundleConflictResponse"+ }+ }+ },+ "description": "Bundle override conflicts with model routing"+ },+ "413": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Request body too large"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/InferenceInternalServerErrorResponse"+ },+ {+ "$ref": "#/components/schemas/StandardApiError"+ }+ ]+ }+ }+ },+ "description": "All batch items failed or gateway internal error; gateway auth enabled but no tokens configured"+ },+ "502": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GatewayModelLoadFailedResponse"+ }+ }+ },+ "description": "Terminal model load failure (MODEL_LOAD_FAILED)",+ "headers": {+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Version": {+ "description": "Gateway package version associated with the error envelope",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "503": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/InferenceServiceUnavailableResponse"+ }+ }+ },+ "description": "Queue unavailable, GPU not configured, model loading, or capacity exhausted",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds, when retryable",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "504": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Result channel closed"+ }+ },+ "tags": [+ "inference"+ ],+ "x-sie-axum-catch-all": "/v1/extract/{*model}"+ }+ },+ "/v1/models": {+ "get": {+ "operationId": "get_models",+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelsResponse"+ }+ }+ },+ "description": "Models visible to this gateway replica"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "models"+ ]+ }+ },+ "/v1/models/{model}": {+ "get": {+ "operationId": "get_model",+ "parameters": [+ {+ "description": "Model id. Runtime route is Axum catch-all `/v1/models/{*model}`; clients using this OpenAPI path template should percent-encode slashes in model ids, for example `BAAI%2Fbge-m3`.",+ "in": "path",+ "name": "model",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelInfoWire"+ }+ }+ },+ "description": "Model detail"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ModelNotFoundResponse"+ }+ }+ },+ "description": "Model not found"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "summary": "Detail counterpart to `get_models`.",+ "tags": [+ "models"+ ],+ "x-sie-axum-catch-all": "/v1/models/{*model}"+ }+ },+ "/v1/pools": {+ "get": {+ "operationId": "list_pools",+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PoolListResponse"+ }+ }+ },+ "description": "Pools visible to this gateway replica"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "pools"+ ]+ },+ "post": {+ "operationId": "create_pool",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreatePoolRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Pool"+ }+ }+ },+ "description": "Pool created"+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Invalid pool request"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "403": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Valid bearer token but admin token required for this mutation (or admin token not configured)"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "pools"+ ]+ }+ },+ "/v1/pools/{name}": {+ "delete": {+ "operationId": "delete_pool",+ "parameters": [+ {+ "description": "Pool name",+ "in": "path",+ "name": "name",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MessageResponse"+ }+ }+ },+ "description": "Pool deleted"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "403": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Pool cannot be deleted"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Pool not found"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "pools"+ ]+ },+ "get": {+ "operationId": "get_pool",+ "parameters": [+ {+ "description": "Pool name",+ "in": "path",+ "name": "name",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Pool"+ }+ }+ },+ "description": "Pool detail"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Pool not found"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "pools"+ ]+ }+ },+ "/v1/pools/{name}/renew": {+ "post": {+ "operationId": "renew_pool",+ "parameters": [+ {+ "description": "Pool name",+ "in": "path",+ "name": "name",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MessageResponse"+ }+ }+ },+ "description": "Pool renewed"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "403": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Valid bearer token but admin token required for this mutation (or admin token not configured)"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Pool not found"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "pools"+ ]+ }+ },+ "/v1/score/{model}": {+ "post": {+ "description": "Mixed-success batches return 200 with only successful items; the response carries no per-item error envelope. For per-item error visibility, send single-item batches.",+ "operationId": "proxy_score",+ "parameters": [+ {+ "description": "Model id. Runtime route is Axum catch-all `/v1/score/{*model}`; clients using this OpenAPI path template should percent-encode slashes in model ids, for example `BAAI%2Fbge-m3`.",+ "in": "path",+ "name": "model",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "description": "Preferred GPU or machine profile",+ "in": "header",+ "name": "X-SIE-MACHINE-PROFILE",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Explicit pool routing override",+ "in": "header",+ "name": "X-SIE-Pool",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Client SDK version for skew warnings",+ "in": "header",+ "name": "X-SIE-SDK-Version",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ScoreRequest"+ }+ },+ "application/msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ScoreRequest"+ }+ },+ "application/vnd.msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ScoreRequest"+ }+ },+ "application/x-msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ScoreRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ScoreResponse"+ }+ },+ "application/msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ScoreResponse"+ }+ },+ "application/vnd.msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ScoreResponse"+ }+ },+ "application/x-msgpack": {+ "schema": {+ "$ref": "#/components/schemas/ScoreResponse"+ }+ }+ },+ "description": "Score response",+ "headers": {+ "X-Inference-Time": {+ "description": "Worker-reported inference time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Payload-Fetch-Time": {+ "description": "Worker-reported offloaded payload fetch time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Postprocessing-Time": {+ "description": "Worker-reported postprocessing time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Publish-Time": {+ "description": "Milliseconds spent publishing work to the queue",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Time": {+ "description": "Worker-reported queue time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Wait-Time": {+ "description": "Milliseconds spent waiting for worker results",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Request-Id": {+ "description": "Gateway request id for queue-backed inference",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Worker": {+ "description": "Logical queue worker tag that produced the response",+ "schema": {+ "type": "string"+ }+ },+ "X-Tokenization-Time": {+ "description": "Worker-reported tokenization time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "202": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ProvisioningResponse"+ }+ }+ },+ "description": "Worker provisioning in progress",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Invalid request"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Model not found"+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BundleConflictResponse"+ }+ }+ },+ "description": "Bundle override conflicts with model routing"+ },+ "413": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Request body too large"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/InferenceInternalServerErrorResponse"+ },+ {+ "$ref": "#/components/schemas/StandardApiError"+ }+ ]+ }+ }+ },+ "description": "All batch items failed or gateway internal error; gateway auth enabled but no tokens configured"+ },+ "502": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GatewayModelLoadFailedResponse"+ }+ }+ },+ "description": "Terminal model load failure (MODEL_LOAD_FAILED)",+ "headers": {+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Version": {+ "description": "Gateway package version associated with the error envelope",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "503": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/InferenceServiceUnavailableResponse"+ }+ }+ },+ "description": "Queue unavailable, GPU not configured, model loading, or capacity exhausted",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds, when retryable",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "504": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Result channel closed"+ }+ },+ "tags": [+ "inference"+ ],+ "x-sie-axum-catch-all": "/v1/score/{*model}"+ }+ },+ "/ws/cluster-status": {+ "get": {+ "operationId": "ws_cluster_status",+ "responses": {+ "101": {+ "description": "WebSocket cluster status stream"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Missing or invalid bearer token (inference token)"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StandardApiError"+ }+ }+ },+ "description": "Gateway auth enabled but no tokens configured"+ }+ },+ "tags": [+ "observability"+ ]+ }+ }+ },+ "security": [+ {+ "bearerAuth": []+ }+ ],+ "tags": [+ {+ "description": "Gateway health, readiness, and status surfaces",+ "name": "health"+ },+ {+ "description": "Queue-backed inference entrypoints",+ "name": "inference"+ },+ {+ "description": "Models visible to this gateway replica",+ "name": "models"+ },+ {+ "description": "Runtime pool coordination",+ "name": "pools"+ },+ {+ "description": "Read-only gateway view of model and bundle config",+ "name": "config"+ },+ {+ "description": "Metrics and streaming status",+ "name": "observability"+ },+ {+ "description": "API description",+ "name": "docs"+ }+ ]+}diff --git a/packages/sie_gateway/src/error.rs b/packages/sie_gateway/src/error.rsindex 10600ab71..128a7fdbd 100644--- a/packages/sie_gateway/src/error.rs+++ b/packages/sie_gateway/src/error.rs@@ -1,6 +1,8 @@use axum::http::StatusCode;use axum::response::{IntoResponse, Response};+use crate::http_error::{code as err_code, json_detail};+#[allow(dead_code)]#[derive(Debug, thiserror::Error)]pub enum AppError {@@ -19,14 +21,30 @@ pub enum AppError {impl IntoResponse for AppError {fn into_response(self) -> Response {- let (status, message) = match &self {- AppError::NoWorkerAvailable => (StatusCode::SERVICE_UNAVAILABLE, self.to_string()),- AppError::GpuProvisioning(_) => (StatusCode::ACCEPTED, self.to_string()),- AppError::UpstreamConnection(_) => (StatusCode::BAD_GATEWAY, self.to_string()),- AppError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),+ let (status, code, message) = match &self {+ AppError::NoWorkerAvailable => (+ StatusCode::SERVICE_UNAVAILABLE,+ err_code::QUEUE_UNAVAILABLE,+ self.to_string(),+ ),+ AppError::GpuProvisioning(_) => (+ StatusCode::ACCEPTED,+ err_code::PROVISIONING,+ self.to_string(),+ ),+ AppError::UpstreamConnection(_) => (+ StatusCode::BAD_GATEWAY,+ err_code::INTERNAL_ERROR,+ self.to_string(),+ ),+ AppError::Internal(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ err_code::INTERNAL_ERROR,+ self.to_string(),+ ),};- let body = serde_json::json!({ "message": message });+ let body = json_detail(code, message);(status, axum::Json(body)).into_response()}}diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex 2461c2234..d12333079 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -25,8 +25,10 @@ use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::Json;use serde::{Deserialize, Serialize};-use serde_json::json;+use serde_json::{json, Map};+use utoipa::ToSchema;+use crate::http_error::{code as err_code, json_detail, json_detail_merge};use crate::server::AppState;use crate::state::model_registry::ResolveError;@@ -44,9 +46,12 @@ fn yaml_response<T: Serialize>(status: StatusCode, value: &T) -> Response {Err(e) => {return (StatusCode::INTERNAL_SERVER_ERROR,- Json(json!({"message": format!("Failed to serialize YAML: {}", e)})),+ Json(json_detail(+ err_code::SERIALIZATION_ERROR,+ format!("Failed to serialize YAML: {}", e),+ )),)- .into_response()+ .into_response();}};@@ -58,6 +63,12 @@ fn yaml_response<T: Serialize>(status: StatusCode, value: &T) -> Response {}/// GET /v1/configs/models - List all model configs visible to this gateway.+#[utoipa::path(+ get,+ path = "/v1/configs/models",+ tag = "config",+ responses((status = 200, description = "Model configs visible to this gateway replica", body = crate::openapi::ConfigModelsResponse))+)]pub async fn get_model_configs(State(state): State<Arc<AppState>>) -> impl IntoResponse {let models: Vec<serde_json::Value> = state.model_registry@@ -99,6 +110,17 @@ pub async fn get_model_configs(State(state): State<Arc<AppState>>) -> impl IntoR/// register model IDs ending in `/status` so the pathological case where/// **both** `foo` and `foo/status` are models cannot arise, but we/// still degrade gracefully if it ever does.+#[utoipa::path(+ get,+ path = "/v1/configs/models/{id}",+ tag = "config",+ params(("id" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients")),+ responses(+ (status = 200, description = "Model config YAML", body = crate::openapi::ConfigModelDocument, content_type = "application/x-yaml"),+ (status = 404, description = "Model not found", body = crate::openapi::StandardApiError),+ (status = 500, description = "Failed to serialize YAML", body = crate::openapi::StandardApiError)+ )+)]pub async fn get_model_config_or_status(State(state): State<Arc<AppState>>,Path(raw): Path<String>,@@ -117,7 +139,10 @@ fn model_config_response(state: &AppState, id: &str) -> Response {let Some(model_info) = state.model_registry.get_model_info(id) else {return (StatusCode::NOT_FOUND,- Json(json!({"message": format!("Model '{}' not found", id)})),+ Json(json_detail(+ err_code::MODEL_NOT_FOUND,+ format!("Model '{}' not found", id),+ )),).into_response();};@@ -147,7 +172,10 @@ async fn model_status_response(state: &AppState, id: &str) -> Response {let Some(model_info) = state.model_registry.get_model_info(id) else {return (StatusCode::NOT_FOUND,- Json(json!({"message": format!("Model '{}' not found", id)})),+ Json(json_detail(+ err_code::MODEL_NOT_FOUND,+ format!("Model '{}' not found", id),+ )),).into_response();};@@ -225,6 +253,12 @@ async fn compute_model_status(}/// GET /v1/configs/bundles - List all bundle configs.+#[utoipa::path(+ get,+ path = "/v1/configs/bundles",+ tag = "config",+ responses((status = 200, description = "Bundle configs visible to this gateway replica", body = crate::openapi::BundleConfigsResponse))+)]pub async fn get_bundle_configs(State(state): State<Arc<AppState>>) -> impl IntoResponse {let workers = state.registry.workers().await;@@ -253,6 +287,17 @@ pub async fn get_bundle_configs(State(state): State<Arc<AppState>>) -> impl Into}/// GET /v1/configs/bundles/{id} - Get specific bundle config.+#[utoipa::path(+ get,+ path = "/v1/configs/bundles/{id}",+ tag = "config",+ params(("id" = String, Path, description = "Bundle id")),+ responses(+ (status = 200, description = "Bundle config YAML", body = crate::openapi::BundleConfigDocument, content_type = "application/x-yaml"),+ (status = 404, description = "Bundle not found", body = crate::openapi::StandardApiError),+ (status = 500, description = "Failed to serialize YAML", body = crate::openapi::StandardApiError)+ )+)]pub async fn get_bundle_config(State(state): State<Arc<AppState>>,Path(id): Path<String>,@@ -260,7 +305,10 @@ pub async fn get_bundle_config(let Some(info) = state.model_registry.get_bundle_info(&id) else {return (StatusCode::NOT_FOUND,- Json(json!({"message": format!("Bundle '{}' not found", id)})),+ Json(json_detail(+ err_code::BUNDLE_NOT_FOUND,+ format!("Bundle '{}' not found", id),+ )),).into_response();};@@ -275,13 +323,24 @@ pub async fn get_bundle_config(}/// POST /v1/configs/resolve - Resolve bundle for a model.-#[derive(Debug, Deserialize)]+#[derive(Debug, Deserialize, ToSchema)]pub struct ResolveRequest {pub model: String,#[serde(default)]pub bundle: Option<String>,}+#[utoipa::path(+ post,+ path = "/v1/configs/resolve",+ tag = "config",+ request_body = ResolveRequest,+ responses(+ (status = 200, description = "Resolved runtime bundle", body = crate::openapi::ResolveConfigResponse),+ (status = 404, description = "Model not found", body = crate::openapi::ResolveModelNotFoundResponse),+ (status = 409, description = "Bundle override conflict", body = crate::openapi::ResolveBundleConflictResponse)+ )+)]pub async fn resolve_config(State(state): State<Arc<AppState>>,Json(req): Json<ResolveRequest>,@@ -312,21 +371,37 @@ pub async fn resolve_config().into_response()}- Err(ResolveError::ModelNotFound(e)) => (- StatusCode::NOT_FOUND,- Json(json!({"message": e.to_string(), "model": model_name})),- )- .into_response(),- Err(ResolveError::BundleConflict(e)) => (- StatusCode::CONFLICT,- Json(json!({- "message": e.to_string(),- "model": model_name,- "bundle": e.bundle,- "compatible_bundles": e.compatible_bundles,- })),- )- .into_response(),+ Err(ResolveError::ModelNotFound(e)) => {+ let mut m = Map::new();+ m.insert("model".to_string(), json!(model_name));+ (+ StatusCode::NOT_FOUND,+ Json(json_detail_merge(+ err_code::MODEL_NOT_FOUND,+ e.to_string(),+ m,+ )),+ )+ .into_response()+ }+ Err(ResolveError::BundleConflict(e)) => {+ let mut m = Map::new();+ m.insert("model".to_string(), json!(model_name));+ m.insert("bundle".to_string(), json!(e.bundle));+ m.insert(+ "compatible_bundles".to_string(),+ json!(e.compatible_bundles),+ );+ (+ StatusCode::CONFLICT,+ Json(json_detail_merge(+ err_code::CONFIG_RESOLVE_BUNDLE_CONFLICT,+ e.to_string(),+ m,+ )),+ )+ .into_response()+ }}}@@ -657,6 +732,9 @@ mod tests {adapter_module: None,default_bundle: None,profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: None,}).unwrap();}@@ -846,6 +924,9 @@ mod tests {adapter_module: None,default_bundle: None,profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: None,});// The add above will error because 'nonexistent.module' isn't in// any bundle — which is actually the intended real-world path:@@ -864,6 +945,7 @@ mod tests {adapter_modules: Default::default(),profile_names: Default::default(),profile_configs: Default::default(),+ info_extras: Default::default(),};let status = compute_model_status(state.as_ref(), &entry).await;assert_eq!(status["all_bundles_acked"], false);diff --git a/packages/sie_gateway/src/handlers/health.rs b/packages/sie_gateway/src/handlers/health.rsindex 795045166..2c11fa6a5 100644--- a/packages/sie_gateway/src/handlers/health.rs+++ b/packages/sie_gateway/src/handlers/health.rs@@ -1,5 +1,6 @@use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};use axum::extract::State;+use axum::http::header;use axum::http::StatusCode;use axum::response::{Html, IntoResponse};use axum::Json;@@ -10,6 +11,12 @@ use std::time::Duration;use crate::server::AppState;/// Static HTML status page+#[utoipa::path(+ get,+ path = "/",+ tag = "health",+ responses((status = 200, description = "HTML gateway status page", body = String, content_type = "text/html"))+)]pub async fn status_page(State(state): State<Arc<AppState>>) -> impl IntoResponse {let cluster = state.registry.get_cluster_status().await;let status_str = if cluster.worker_count > 0 {@@ -68,21 +75,48 @@ pub async fn status_page(State(state): State<Arc<AppState>>) -> impl IntoResponsHtml(html)}+#[utoipa::path(+ get,+ path = "/healthz",+ tag = "health",+ responses((+ status = 200,+ description = "Liveness probe (plain text, matches sie_server)",+ body = String,+ content_type = "text/plain; charset=utf-8"+ ))+)]pub async fn healthz() -> impl IntoResponse {- (StatusCode::OK, Json(json!({"status": "ok"})))+ (+ StatusCode::OK,+ [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],+ "ok",+ )}-pub async fn readyz(State(state): State<Arc<AppState>>) -> impl IntoResponse {- let healthy = state.registry.healthy_workers().await.len();+#[utoipa::path(+ get,+ path = "/readyz",+ tag = "health",+ description = "Process readiness only. Always returns 200 once the gateway is serving requests; never returns 503. Worker readiness is reported by GET /health and by inference responses (202 + Retry-After from a workerless gateway). This contract supports KEDA scale-from-zero.",+ responses(+ (status = 200, description = "Gateway process is ready", body = String, content_type = "text/plain; charset=utf-8")+ )+)]+pub async fn readyz() -> impl IntoResponse {(StatusCode::OK,- Json(json!({- "status": "ready",- "healthy_workers": healthy,- })),+ [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],+ "ok",)}+#[utoipa::path(+ get,+ path = "/health",+ tag = "health",+ responses((status = 200, description = "Gateway cluster health", body = crate::openapi::HealthResponse))+)]pub async fn health(State(state): State<Arc<AppState>>) -> impl IntoResponse {let cluster = state.registry.get_cluster_status().await;let status_str = if cluster.worker_count > 0 {@@ -112,6 +146,12 @@ pub async fn health(State(state): State<Arc<AppState>>) -> impl IntoResponse {)}+#[utoipa::path(+ get,+ path = "/ws/cluster-status",+ tag = "observability",+ responses((status = 101, description = "WebSocket cluster status stream"))+)]pub async fn ws_cluster_status(ws: WebSocketUpgrade,State(state): State<Arc<AppState>>,diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 047976a2a..c3cb1284f 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -3,63 +3,124 @@ use axum::http::{HeaderMap, StatusCode};use axum::response::{IntoResponse, Response};use axum::Json;use serde_json::{json, Value};+use std::collections::{BTreeSet, HashMap, HashSet};use std::sync::Arc;use crate::server::AppState;-+use crate::state::model_registry::ModelRegistry;+use crate::types::model::{ModelEntry, ModelInfoExtras};++#[utoipa::path(+ get,+ path = "/v1/models",+ tag = "models",+ responses((status = 200, description = "Models visible to this gateway replica", body = crate::openapi::ModelsResponse))+)]pub async fn get_models(State(state): State<Arc<AppState>>) -> impl IntoResponse {- let model_workers = state.registry.get_models().await;-- let all_model_names = state.model_registry.list_models();- let models: Vec<serde_json::Value> = if !all_model_names.is_empty() {- all_model_names- .iter()- .map(|name| {- let worker_urls = model_workers.get(name).cloned().unwrap_or_default();- let bundles = state.model_registry.get_model_bundles(name);- build_model_payload(name, &bundles, &worker_urls)- })- .collect()- } else {- model_workers- .into_iter()- .map(|(name, urls)| build_model_payload(&name, &[], &urls))- .collect()- };+ let model_workers =+ canonical_worker_models(state.registry.get_models().await, &state.model_registry);++ let model_names: BTreeSet<String> = state+ .model_registry+ .list_models()+ .into_iter()+ .chain(model_workers.keys().cloned())+ .collect();+ let models: Vec<serde_json::Value> = model_names+ .iter()+ .map(|name| {+ let worker_urls = model_workers.get(name).cloned().unwrap_or_default();+ let loaded = !worker_urls.is_empty();+ match state.model_registry.get_model_info(name) {+ Some(entry) => entry.to_model_info_value(loaded),+ None => worker_only_model_info(name, loaded),+ }+ })+ .collect();(StatusCode::OK, Json(json!({"models": models}))).into_response()}/// Detail counterpart to `get_models`.+#[utoipa::path(+ get,+ path = "/v1/models/{model}",+ tag = "models",+ params(("model" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients")),+ responses(+ (status = 200, description = "Model detail", body = crate::openapi::ModelInfoWire),+ (status = 404, description = "Model not found", body = crate::openapi::ModelNotFoundResponse)+ )+)]pub async fn get_model(Path(model): Path<String>, State(state): State<Arc<AppState>>) -> Response {- let known_in_registry = state.model_registry.get_model_info(&model).is_some();+ let model_entry = state.model_registry.get_model_info(&model);+ let known_in_registry = model_entry.is_some();+ let canonical_model = model_entry+ .as_ref()+ .map(|entry| entry.name.as_str())+ .unwrap_or(model.as_str());let bundles = state.model_registry.get_model_bundles(&model);- let model_workers = state.registry.get_models().await;- let worker_urls = model_workers.get(&model).cloned().unwrap_or_default();+ let model_workers =+ canonical_worker_models(state.registry.get_models().await, &state.model_registry);+ let worker_urls = model_workers+ .get(canonical_model)+ .cloned()+ .unwrap_or_default();if !known_in_registry && bundles.is_empty() && worker_urls.is_empty() {return (StatusCode::NOT_FOUND,- Json(json!({"message": format!("Model '{}' not found", model)})),+ Json(json!({+ "detail": {+ "code": "MODEL_NOT_FOUND",+ "message": format!("Model '{}' not found", model),+ }+ })),).into_response();}- (- StatusCode::OK,- Json(build_model_payload(&model, &bundles, &worker_urls)),- )- .into_response()+ let loaded = !worker_urls.is_empty();+ let body = match model_entry {+ Some(entry) => entry.to_model_info_value(loaded),+ None => worker_only_model_info(&model, loaded),+ };++ (StatusCode::OK, Json(body)).into_response()+}++fn canonical_worker_models(+ model_workers: HashMap<String, Vec<String>>,+ model_registry: &ModelRegistry,+) -> HashMap<String, Vec<String>> {+ let mut normalized: HashMap<String, Vec<String>> = HashMap::new();+ for (model, urls) in model_workers {+ let canonical = model_registry+ .get_model_info(&model)+ .map(|entry| entry.name)+ .unwrap_or(model);+ normalized.entry(canonical).or_default().extend(urls);+ }+ normalized}-fn build_model_payload(name: &str, bundles: &[String], worker_urls: &[String]) -> Value {- json!({- "name": name,- "bundles": bundles,- "worker_count": worker_urls.len(),- "workers": worker_urls,- "loaded": !worker_urls.is_empty(),- })+/// ``ModelInfo``-shaped JSON when workers advertise a model id that is not+/// present in the local registry snapshot (bootstrap / race window).+fn worker_only_model_info(name: &str, loaded: bool) -> Value {+ ModelEntry {+ name: name.to_string(),+ bundles: Vec::new(),+ adapter_modules: HashSet::new(),+ profile_names: HashSet::new(),+ profile_configs: HashMap::new(),+ info_extras: ModelInfoExtras {+ inputs: Vec::new(),+ outputs: Vec::new(),+ dims: HashMap::new(),+ max_sequence_length: None,+ },+ }+ .to_model_info_value(loaded)}pub fn extract_bearer_token(headers: &HeaderMap) -> Option<String> {@@ -283,6 +344,9 @@ mod route_tests {adapter_module: None,default_bundle: None,profiles,+ inputs: None,+ tasks: None,+ max_sequence_length: None,}).unwrap();}@@ -333,6 +397,80 @@ mod route_tests {assert_eq!(models[0]["loaded"], false);}+ #[tokio::test]+ async fn test_list_models_includes_registry_and_worker_only_models() {+ let (app, state, _bundles_dir, _models_dir) = build_router_with_state().await;+ seed_model(&state, "BAAI/bge-m3");+ state+ .registry+ .update_worker(+ "http://worker-1:8080",+ worker_msg("worker-1", vec!["worker/only".to_string()]),+ )+ .await;++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let body = body_json(response).await;+ let models = body["models"].as_array().unwrap();+ assert_eq!(models.len(), 2);++ let by_name: HashMap<_, _> = models+ .iter()+ .map(|model| (model["name"].as_str().unwrap(), model))+ .collect();+ assert_eq!(by_name["BAAI/bge-m3"]["loaded"], false);+ assert_eq!(by_name["worker/only"]["loaded"], true);+ assert!(by_name["worker/only"]["inputs"]+ .as_array()+ .unwrap()+ .is_empty());+ assert!(by_name["worker/only"]["outputs"]+ .as_array()+ .unwrap()+ .is_empty());+ }++ #[tokio::test]+ async fn test_list_models_canonicalizes_worker_model_names() {+ let (app, state, _bundles_dir, _models_dir) = build_router_with_state().await;+ seed_model(&state, "BAAI/bge-m3");+ state+ .registry+ .update_worker(+ "http://worker-1:8080",+ worker_msg("worker-1", vec!["baai/BGE-M3".to_string()]),+ )+ .await;++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let body = body_json(response).await;+ let models = body["models"].as_array().unwrap();+ assert_eq!(models.len(), 1);+ assert_eq!(models[0]["name"], "BAAI/bge-m3");+ assert_eq!(models[0]["loaded"], true);+ assert_eq!(models[0]["state"], "loaded");+ }+#[tokio::test]async fn test_get_model_detail_known_model_no_workers() {let (app, state, _bundles_dir, _models_dir) = build_router_with_state().await;@@ -352,9 +490,9 @@ mod route_tests {let body = body_json(response).await;assert_eq!(body["name"], "BAAI/bge-m3");assert_eq!(body["loaded"], false);- assert_eq!(body["worker_count"], 0);- assert!(body["workers"].as_array().unwrap().is_empty());- assert!(!body["bundles"].as_array().unwrap().is_empty());+ assert_eq!(body["state"], "available");+ assert!(!body["inputs"].as_array().unwrap().is_empty());+ assert!(body["profiles"].is_object());}#[tokio::test]@@ -383,11 +521,36 @@ mod route_tests {let body = body_json(response).await;assert_eq!(body["name"], "BAAI/bge-m3");assert_eq!(body["loaded"], true);- assert_eq!(body["worker_count"], 1);- assert_eq!(- body["workers"].as_array().unwrap()[0],- "http://worker-1:8080"- );+ assert_eq!(body["state"], "loaded");+ }++ #[tokio::test]+ async fn test_get_model_detail_canonicalizes_worker_model_names() {+ let (app, state, _bundles_dir, _models_dir) = build_router_with_state().await;+ seed_model(&state, "BAAI/bge-m3");+ state+ .registry+ .update_worker(+ "http://worker-1:8080",+ worker_msg("worker-1", vec!["baai/BGE-M3".to_string()]),+ )+ .await;++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models/baai/bge-m3")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let body = body_json(response).await;+ assert_eq!(body["name"], "BAAI/bge-m3");+ assert_eq!(body["loaded"], true);+ assert_eq!(body["state"], "loaded");}#[tokio::test]@@ -407,7 +570,11 @@ mod route_tests {assert_eq!(response.status(), StatusCode::NOT_FOUND);let body = body_json(response).await;- assert!(body["message"].as_str().unwrap().contains("does/not/exist"));+ assert_eq!(body["detail"]["code"], "MODEL_NOT_FOUND");+ assert!(body["detail"]["message"]+ .as_str()+ .unwrap()+ .contains("does/not/exist"));}#[tokio::test]@@ -426,6 +593,10 @@ mod route_tests {assert_eq!(response.status(), StatusCode::NOT_FOUND);let body = body_json(response).await;- assert!(body["message"].as_str().unwrap().contains("anything"));+ assert_eq!(body["detail"]["code"], "MODEL_NOT_FOUND");+ assert!(body["detail"]["message"]+ .as_str()+ .unwrap()+ .contains("anything"));}}diff --git a/packages/sie_gateway/src/handlers/pools.rs b/packages/sie_gateway/src/handlers/pools.rsindex 41163a23d..38db9fdbd 100644--- a/packages/sie_gateway/src/handlers/pools.rs+++ b/packages/sie_gateway/src/handlers/pools.rs@@ -7,11 +7,13 @@ use serde_json::json;use std::collections::HashMap;use std::sync::Arc;use tracing::info;+use utoipa::ToSchema;+use crate::http_error::{code as err_code, json_detail};use crate::server::AppState;use crate::state::pool_manager::DEFAULT_POOL_NAME;-#[derive(Debug, Deserialize)]+#[derive(Debug, Deserialize, ToSchema)]pub struct CreatePoolRequest {pub name: String,#[serde(default)]@@ -24,6 +26,16 @@ pub struct CreatePoolRequest {pub minimum_worker_count: u32,}+#[utoipa::path(+ post,+ path = "/v1/pools",+ tag = "pools",+ request_body = CreatePoolRequest,+ responses(+ (status = 201, description = "Pool created", body = crate::types::pool::Pool),+ (status = 400, description = "Invalid pool request", body = crate::openapi::StandardApiError)+ )+)]pub async fn create_pool(State(state): State<Arc<AppState>>,Json(req): Json<CreatePoolRequest>,@@ -31,7 +43,10 @@ pub async fn create_pool(if req.name.is_empty() {return (StatusCode::BAD_REQUEST,- Json(json!({"message": "Pool name is required"})),+ Json(json_detail(+ err_code::INVALID_REQUEST,+ "Pool name is required",+ )),).into_response();}@@ -39,7 +54,10 @@ pub async fn create_pool(if req.gpus.is_empty() {return (StatusCode::BAD_REQUEST,- Json(json!({"message": "GPU requirements are required"})),+ Json(json_detail(+ err_code::INVALID_REQUEST,+ "GPU requirements are required",+ )),).into_response();}@@ -61,17 +79,33 @@ pub async fn create_pool(}Err(e) => (StatusCode::BAD_REQUEST,- Json(json!({"message": e.to_string()})),+ Json(json_detail(err_code::INVALID_REQUEST, e.to_string())),).into_response(),}}+#[utoipa::path(+ get,+ path = "/v1/pools",+ tag = "pools",+ responses((status = 200, description = "Pools visible to this gateway replica", body = crate::openapi::PoolListResponse))+)]pub async fn list_pools(State(state): State<Arc<AppState>>) -> impl IntoResponse {let pools = state.pool_manager.list_pools().await;(StatusCode::OK, Json(json!({"pools": pools})))}+#[utoipa::path(+ get,+ path = "/v1/pools/{name}",+ tag = "pools",+ params(("name" = String, Path, description = "Pool name")),+ responses(+ (status = 200, description = "Pool detail", body = crate::types::pool::Pool),+ (status = 404, description = "Pool not found", body = crate::openapi::StandardApiError)+ )+)]pub async fn get_pool(State(state): State<Arc<AppState>>,Path(name): Path<String>,@@ -80,12 +114,26 @@ pub async fn get_pool(Some(pool) => (StatusCode::OK, Json(json!(pool))).into_response(),None => (StatusCode::NOT_FOUND,- Json(json!({"message": format!("Pool '{}' not found", name)})),+ Json(json_detail(+ err_code::POOL_NOT_FOUND,+ format!("Pool '{}' not found", name),+ )),).into_response(),}}+#[utoipa::path(+ delete,+ path = "/v1/pools/{name}",+ tag = "pools",+ params(("name" = String, Path, description = "Pool name")),+ responses(+ (status = 200, description = "Pool deleted", body = crate::openapi::MessageResponse),+ (status = 403, description = "Pool cannot be deleted", body = crate::openapi::StandardApiError),+ (status = 404, description = "Pool not found", body = crate::openapi::StandardApiError)+ )+)]pub async fn delete_pool(State(state): State<Arc<AppState>>,Path(name): Path<String>,@@ -93,7 +141,10 @@ pub async fn delete_pool(if name == DEFAULT_POOL_NAME {return (StatusCode::FORBIDDEN,- Json(json!({"message": "Cannot delete the default pool"})),+ Json(json_detail(+ err_code::DEFAULT_POOL_DELETE_FORBIDDEN,+ "Cannot delete the default pool",+ )),).into_response();}@@ -105,17 +156,33 @@ pub async fn delete_pool(}Ok(false) => (StatusCode::NOT_FOUND,- Json(json!({"message": format!("Pool '{}' not found", name)})),+ Json(json_detail(+ err_code::POOL_NOT_FOUND,+ format!("Pool '{}' not found", name),+ )),).into_response(),Err(e) => (StatusCode::FORBIDDEN,- Json(json!({"message": e.to_string()})),+ Json(json_detail(+ err_code::POOL_OPERATION_FORBIDDEN,+ e.to_string(),+ )),).into_response(),}}+#[utoipa::path(+ post,+ path = "/v1/pools/{name}/renew",+ tag = "pools",+ params(("name" = String, Path, description = "Pool name")),+ responses(+ (status = 200, description = "Pool renewed", body = crate::openapi::MessageResponse),+ (status = 404, description = "Pool not found", body = crate::openapi::StandardApiError)+ )+)]pub async fn renew_pool(State(state): State<Arc<AppState>>,Path(name): Path<String>,@@ -126,7 +193,10 @@ pub async fn renew_pool(} else {(StatusCode::NOT_FOUND,- Json(json!({"message": format!("Pool '{}' not found", name)})),+ Json(json_detail(+ err_code::POOL_NOT_FOUND,+ format!("Pool '{}' not found", name),+ )),)}}diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex a79f30247..e2f353f68 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -1,15 +1,18 @@-use axum::body::Body;+use axum::body::{to_bytes, Body};use axum::extract::{Request, State};-use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};+use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};use axum::response::{IntoResponse, Response};use axum::Json;+use base64::Engine;use dashmap::DashMap;+use percent_encoding::percent_decode_str;use rmp_serde;-use serde_json::json;+use serde_json::{json, Map, Value};use std::sync::Arc;use std::time::{Duration, Instant};use tracing::{debug, error, info, warn};+use crate::http_error::{code as err_code, json_detail, json_detail_merge};use crate::metrics;use crate::queue::publisher;@@ -41,6 +44,10 @@ const RESOURCE_EXHAUSTED_RETRY_AFTER: &str = "5";const LORA_LOADING_ERROR_CODE: &str = "LORA_LOADING";const LORA_LOADING_RETRY_AFTER: &str = "5";const ESTIMATED_WAIT_S: u64 = 180;+/// Terminal model load failure (non-retryable). Matches ``sie_server`` HTTP 502+/// contract so ``sie_sdk`` can short-circuit before the ``MODEL_LOADING`` retry+/// budget (see ``raise_if_model_load_failed``).+const MODEL_LOAD_FAILED_ERROR_CODE: &str = "MODEL_LOAD_FAILED";/// Track which SDK minor versions we've already warned about (to warn once per minor).static SDK_WARNED_MINORS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<u32>>> =@@ -170,14 +177,92 @@ async fn resolve_effective_pool(}}+#[utoipa::path(+ post,+ path = "/v1/encode/{model}",+ tag = "inference",+ description = "Mixed-success batches return 200 with only successful items; the response carries no per-item error envelope. For per-item error visibility, send single-item batches.",+ params(+ ("model" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients"),+ ("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),+ ("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override"),+ ("X-SIE-SDK-Version" = Option<String>, Header, description = "Client SDK version for skew warnings")+ ),+ request_body = crate::openapi::EncodeRequest,+ responses(+ (status = 200, description = "Encode response", body = crate::openapi::EncodeResponse),+ (status = 202, description = "Worker provisioning in progress", body = crate::openapi::ProvisioningResponse),+ (status = 400, description = "Invalid request", body = crate::openapi::StandardApiError),+ (status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),+ (status = 404, description = "Model not found", body = crate::openapi::StandardApiError),+ (status = 409, description = "Bundle override conflicts with model routing", body = crate::openapi::BundleConflictResponse),+ (status = 413, description = "Request body too large", body = crate::openapi::StandardApiError),+ (status = 500, description = "All batch items failed or gateway internal error", body = crate::openapi::InferenceInternalServerErrorResponse),+ (status = 502, description = "Terminal model load failure (MODEL_LOAD_FAILED)", body = crate::openapi::GatewayModelLoadFailedResponse),+ (status = 503, description = "Queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::InferenceServiceUnavailableResponse),+ (status = 504, description = "Result channel closed", body = crate::openapi::StandardApiError)+ )+)]pub async fn proxy_encode(state: State<Arc<AppState>>, req: Request) -> impl IntoResponse {proxy_request(state, req, "encode").await}+#[utoipa::path(+ post,+ path = "/v1/score/{model}",+ tag = "inference",+ description = "Mixed-success batches return 200 with only successful items; the response carries no per-item error envelope. For per-item error visibility, send single-item batches.",+ params(+ ("model" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients"),+ ("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),+ ("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override"),+ ("X-SIE-SDK-Version" = Option<String>, Header, description = "Client SDK version for skew warnings")+ ),+ request_body = crate::openapi::ScoreRequest,+ responses(+ (status = 200, description = "Score response", body = crate::openapi::ScoreResponse),+ (status = 202, description = "Worker provisioning in progress", body = crate::openapi::ProvisioningResponse),+ (status = 400, description = "Invalid request", body = crate::openapi::StandardApiError),+ (status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),+ (status = 404, description = "Model not found", body = crate::openapi::StandardApiError),+ (status = 409, description = "Bundle override conflicts with model routing", body = crate::openapi::BundleConflictResponse),+ (status = 413, description = "Request body too large", body = crate::openapi::StandardApiError),+ (status = 500, description = "All batch items failed or gateway internal error", body = crate::openapi::InferenceInternalServerErrorResponse),+ (status = 502, description = "Terminal model load failure (MODEL_LOAD_FAILED)", body = crate::openapi::GatewayModelLoadFailedResponse),+ (status = 503, description = "Queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::InferenceServiceUnavailableResponse),+ (status = 504, description = "Result channel closed", body = crate::openapi::StandardApiError)+ )+)]pub async fn proxy_score(state: State<Arc<AppState>>, req: Request) -> impl IntoResponse {proxy_request(state, req, "score").await}+#[utoipa::path(+ post,+ path = "/v1/extract/{model}",+ tag = "inference",+ description = "Mixed-success batches return 200 with only successful items; the response carries no per-item error envelope. For per-item error visibility, send single-item batches.",+ params(+ ("model" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients"),+ ("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),+ ("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override"),+ ("X-SIE-SDK-Version" = Option<String>, Header, description = "Client SDK version for skew warnings")+ ),+ request_body = crate::openapi::ExtractRequest,+ responses(+ (status = 200, description = "Extract response", body = crate::openapi::ExtractResponse),+ (status = 202, description = "Worker provisioning in progress", body = crate::openapi::ProvisioningResponse),+ (status = 400, description = "Invalid request", body = crate::openapi::StandardApiError),+ (status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),+ (status = 404, description = "Model not found", body = crate::openapi::StandardApiError),+ (status = 409, description = "Bundle override conflicts with model routing", body = crate::openapi::BundleConflictResponse),+ (status = 413, description = "Request body too large", body = crate::openapi::StandardApiError),+ (status = 500, description = "All batch items failed or gateway internal error", body = crate::openapi::InferenceInternalServerErrorResponse),+ (status = 502, description = "Terminal model load failure (MODEL_LOAD_FAILED)", body = crate::openapi::GatewayModelLoadFailedResponse),+ (status = 503, description = "Queue unavailable, GPU not configured, model loading, or capacity exhausted", body = crate::openapi::InferenceServiceUnavailableResponse),+ (status = 504, description = "Result channel closed", body = crate::openapi::StandardApiError)+ )+)]pub async fn proxy_extract(state: State<Arc<AppState>>, req: Request) -> impl IntoResponse {proxy_request(state, req, "extract").await}@@ -193,7 +278,17 @@ async fn proxy_request(// Extract model from path: /v1/{endpoint}/{model...}let prefix = format!("/v1/{}/", endpoint);let path = req.uri().path().to_string();- let model = path.strip_prefix(&prefix).unwrap_or("").to_string();+ let raw_model = path.strip_prefix(&prefix).unwrap_or("");+ let model = match decode_model_path(raw_model) {+ Ok(model) => model,+ Err(message) => {+ return (+ StatusCode::BAD_REQUEST,+ Json(json_detail(err_code::INVALID_REQUEST, message)),+ )+ .into_response();+ }+ };if model.is_empty() {// Early exit, headers haven't been parsed yet — pass through@@ -203,7 +298,7 @@ async fn proxy_request(metrics::record_rejected_request("", "unknown", "model_required");return (StatusCode::BAD_REQUEST,- Json(json!({"message": "model is required"})),+ Json(json_detail(err_code::INVALID_REQUEST, "model is required")),).into_response();}@@ -232,17 +327,23 @@ async fn proxy_request(Err(ResolveError::ModelNotFound(e)) => {return (StatusCode::NOT_FOUND,- Json(json!({"message": e.to_string()})),+ Json(json_detail(err_code::MODEL_NOT_FOUND, e.to_string())),).into_response();}Err(ResolveError::BundleConflict(e)) => {+ let mut m = Map::new();+ m.insert(+ "compatible_bundles".to_string(),+ json!(e.compatible_bundles),+ );return (StatusCode::CONFLICT,- Json(json!({- "message": e.to_string(),- "compatible_bundles": e.compatible_bundles,- })),+ Json(json_detail_merge(+ err_code::BUNDLE_ROUTING_CONFLICT,+ e.to_string(),+ m,+ )),).into_response();}@@ -250,9 +351,10 @@ async fn proxy_request(} else if state.model_registry.has_any_models() {return (StatusCode::NOT_FOUND,- Json(json!({- "message": format!("Unknown model '{}'", model_name),- })),+ Json(json_detail(+ err_code::MODEL_NOT_FOUND,+ format!("Model '{}' not found", model_name),+ )),).into_response();} else if bundle_override.is_empty() {@@ -317,14 +419,19 @@ async fn proxy_request(if !found {metrics::record_rejected_request(&gpu, &bundle, "gpu_not_configured");+ let mut m = Map::new();+ m.insert("gpu".to_string(), json!(&gpu));+ m.insert(+ "configured_gpu_types".to_string(),+ json!(&state.config.configured_gpus),+ );return (StatusCode::SERVICE_UNAVAILABLE,- Json(json!({- "status": "gpu_not_configured",- "gpu": gpu,- "configured_gpu_types": state.config.configured_gpus,- "message": format!("GPU type '{}' is not configured in this cluster.", gpu),- })),+ Json(json_detail_merge(+ err_code::GPU_NOT_CONFIGURED,+ format!("GPU type '{}' is not configured in this cluster.", gpu),+ m,+ )),).into_response();}@@ -334,9 +441,10 @@ async fn proxy_request(metrics::record_rejected_request(&gpu, &bundle, "queue_unavailable");return (StatusCode::SERVICE_UNAVAILABLE,- Json(json!({- "message": "Rust gateway is queue-only, but NATS JetStream is unavailable"- })),+ Json(json_detail(+ err_code::QUEUE_UNAVAILABLE,+ "Rust gateway is queue-only, but NATS JetStream is unavailable",+ )),).into_response();};@@ -400,6 +508,14 @@ async fn proxy_request(HeaderName::from_static("retry-after"),HeaderValue::from_static(DEFAULT_RETRY_AFTER),);+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-version"),+ HeaderValue::from_static(GATEWAY_VERSION),+ );+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-server-version"),+ HeaderValue::from_static(GATEWAY_VERSION),+ );return resp;}};@@ -434,7 +550,10 @@ async fn proxy_request(metrics::record_rejected_request(&gpu, &bundle, "body_too_large");return (StatusCode::PAYLOAD_TOO_LARGE,- Json(json!({"message": format!("Request body too large (max {} bytes)", MAX_PROXY_BODY)})),+ Json(json_detail(+ err_code::PAYLOAD_TOO_LARGE,+ format!("Request body too large (max {} bytes)", MAX_PROXY_BODY),+ )),).into_response();}@@ -491,7 +610,10 @@ async fn queue_mode_proxy(metrics::record_rejected_request(gpu, bundle, "body_parse_error");return (StatusCode::BAD_REQUEST,- Json(json!({"message": format!("Failed to parse request body: {}", e)})),+ Json(json_detail(+ err_code::INVALID_REQUEST,+ format!("Failed to parse request body: {}", e),+ )),).into_response();}@@ -501,7 +623,10 @@ async fn queue_mode_proxy(metrics::record_rejected_request(gpu, bundle, "empty_items");return (StatusCode::BAD_REQUEST,- Json(json!({"message": "No items found in request body"})),+ Json(json_detail(+ err_code::INVALID_REQUEST,+ "No items found in request body",+ )),).into_response();}@@ -529,12 +654,19 @@ async fn queue_mode_proxy(let lower = e.to_lowercase();if lower.contains("score request missing query item") {metrics::record_rejected_request(gpu, bundle, "score_missing_query");- return (StatusCode::BAD_REQUEST, Json(json!({"message": e}))).into_response();+ return (+ StatusCode::BAD_REQUEST,+ Json(json_detail(err_code::INVALID_REQUEST, e)),+ )+ .into_response();}let mut response = (StatusCode::SERVICE_UNAVAILABLE,- Json(json!({"message": format!("Queue publish failed: {}", e)})),+ Json(json_detail(+ err_code::QUEUE_UNAVAILABLE,+ format!("Queue publish failed: {}", e),+ )),).into_response();@@ -576,7 +708,10 @@ async fn queue_mode_proxy(metrics::record_rejected_request(gpu, bundle, "result_channel_closed");return (StatusCode::GATEWAY_TIMEOUT,- Json(json!({"message": "Result channel closed"})),+ Json(json_detail(+ err_code::GATEWAY_TIMEOUT,+ "Result channel closed",+ )),).into_response();}@@ -609,6 +744,17 @@ async fn queue_mode_proxy(let errors: Vec<&publisher::WorkResult> = results.iter().filter(|r| !r.success).collect();if successful.is_empty() && !errors.is_empty() {+ if errors+ .iter()+ .all(|r| r.error_code.as_deref() == Some(MODEL_LOAD_FAILED_ERROR_CODE))+ {+ let first_msg = errors+ .first()+ .and_then(|r| r.error.as_deref())+ .unwrap_or("Model load failed");+ metrics::record_rejected_request(gpu, bundle, "model_load_failed_terminal");+ return build_model_load_failed_response(model, first_msg);+ }// Translate retryable worker error codes into the SDK-expected 503// contract. Without this every per-item failure surfaced as 500// ``all_items_failed`` and the SDK retry path never engaged. We@@ -645,83 +791,9 @@ async fn queue_mode_proxy(.into_response();}- let content_key = if endpoint == "score" {- "scores"- } else {- "items"- };let status: u16 = 200;- let resp_body = if use_msgpack {- // Msgpack: build {"model": ..., "items"|"scores": [raw_blobs...]} at byte level- let result_blobs: Vec<&[u8]> = successful- .iter()- .map(|r| r.result_msgpack.as_slice())- .collect();- let mut packer = rmp::encode::buffer::ByteBuf::new();- let n_keys = if errors.is_empty() { 2u32 } else { 3 };- rmp::encode::write_map_len(&mut packer, n_keys).unwrap();- rmp::encode::write_str(&mut packer, "model").unwrap();- rmp::encode::write_str(&mut packer, model).unwrap();- rmp::encode::write_str(&mut packer, content_key).unwrap();- if endpoint == "score" && result_blobs.len() == 1 {- // Score: single blob is the complete list, embed directly- let mut parts = packer.into_vec();- parts.extend_from_slice(result_blobs[0]);- parts- } else {- rmp::encode::write_array_len(&mut packer, result_blobs.len() as u32).unwrap();- let mut parts = packer.into_vec();- for blob in result_blobs {- parts.extend_from_slice(blob);- }- parts- }- } else {- // JSON: decode each blob, convert numpy arrays, wrap in envelope.- //- // The result blobs typically carry msgpack_numpy-encoded- // arrays — `{"nd": true, "type": "<f4", "shape": [...],- // "data": <binary>}`. `rmpv_to_response_json` detects the- // sentinel while walking the `rmpv::Value` tree and decodes- // `Binary` / `Ext` blobs directly from their byte slice, so- // we never materialise the `data` buffer as a- // `Vec<serde_json::Value::Number>` (one Number per byte)- // just to re-collect it back into bytes for dtype decoding.- let mut result_items: Vec<serde_json::Value> = successful- .iter()- .filter_map(|r| {- let rmpv_val: rmpv::Value = rmp_serde::from_slice(&r.result_msgpack).ok()?;- Some(rmpv_to_response_json(rmpv_val))- })- .collect();- // Score: the single blob *is* the candidate-list already, so- // we unwrap it and hand the inner array straight to the- // envelope. Use `into_iter().next()` to move the item out- // instead of cloning — score payloads can be thousands of- // entries long and this used to clone the whole vec.- let items_val = if endpoint == "score" && result_items.len() == 1 {- match result_items.pop() {- Some(serde_json::Value::Array(arr)) => serde_json::Value::Array(arr),- Some(other) => serde_json::Value::Array(vec![other]),- None => serde_json::Value::Array(Vec::new()),- }- } else {- serde_json::Value::Array(result_items)- };- let mut response_data = json!({- "model": model,- content_key: items_val,- });- if !errors.is_empty() {- let error_details: Vec<serde_json::Value> = errors- .iter()- .map(|r| json!({"item_index": r.item_index, "error": r.error}))- .collect();- response_data["errors"] = json!(error_details);- }- serde_json::to_vec(&response_data).unwrap_or_default()- };+ let resp_body = build_queue_success_body(endpoint, model, &successful, use_msgpack);debug!(request_id = %request_id,@@ -796,6 +868,41 @@ async fn queue_mode_proxy(response}+fn build_model_load_failed_response(model: &str, message: &str) -> Response {+ let mut resp = (+ StatusCode::BAD_GATEWAY,+ Json(json!({+ "error": {+ "code": MODEL_LOAD_FAILED_ERROR_CODE,+ "message": format!(+ "Model '{model}' failed to load ({MODEL_LOAD_FAILED_ERROR_CODE}, attempts=1): {message}"+ ),+ "error_class": MODEL_LOAD_FAILED_ERROR_CODE,+ "attempts": 1,+ "permanent": true,+ }+ })),+ )+ .into_response();+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(MODEL_LOAD_FAILED_ERROR_CODE),+ );+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-error-version"),+ HeaderValue::from_static(GATEWAY_VERSION),+ );+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-version"),+ HeaderValue::from_static(GATEWAY_VERSION),+ );+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-server-version"),+ HeaderValue::from_static(GATEWAY_VERSION),+ );+ resp+}+/// Return the retryable error code shared by every failed item, or/// ``None`` if the batch is mixed / non-retryable.///@@ -944,6 +1051,13 @@ fn parse_model_spec(spec: &str) -> (String, String) {}}+fn decode_model_path(raw: &str) -> Result<String, String> {+ percent_decode_str(raw)+ .decode_utf8()+ .map(|decoded| decoded.into_owned())+ .map_err(|_| "model path is not valid UTF-8 after percent decoding".to_string())+}+fn resolve_machine_profile(gpu: &str,gpu_profile_map: &std::collections::HashMap<String, String>,@@ -1040,6 +1154,126 @@ fn insert_queue_worker_timing_headers();}+fn is_openai_embeddings_forwarded_header(name: &str) -> bool {+ [+ "x-sie-request-id",+ "x-sie-version",+ "x-sie-server-version",+ "x-sie-worker",+ "x-queue-publish-time",+ "x-queue-wait-time",+ "x-queue-time",+ "x-inference-time",+ "x-tokenization-time",+ "x-postprocessing-time",+ "x-payload-fetch-time",+ ]+ .iter()+ .any(|allowed| name.eq_ignore_ascii_case(allowed))+}++fn result_decode_error_value(r: &publisher::WorkResult, message: String) -> serde_json::Value {+ json!({+ "item_index": r.item_index,+ "work_item_id": r.work_item_id,+ "error": {+ "code": "RESULT_DECODE_FAILED",+ "message": message,+ },+ })+}++fn validated_msgpack_result_blob(r: &publisher::WorkResult) -> Vec<u8> {+ match rmp_serde::from_slice::<rmpv::Value>(&r.result_msgpack) {+ Ok(_) => r.result_msgpack.clone(),+ Err(err) => {+ let placeholder =+ result_decode_error_value(r, format!("failed to decode result_msgpack: {err}"));+ rmp_serde::to_vec(&placeholder).unwrap_or_else(|_| {+ rmp_serde::to_vec(&json!({+ "item_index": r.item_index,+ "error": {+ "code": "RESULT_DECODE_FAILED",+ "message": "failed to encode result decode error",+ },+ }))+ .unwrap_or_default()+ })+ }+ }+}++fn build_queue_success_body(+ endpoint: &str,+ model: &str,+ successful: &[&publisher::WorkResult],+ use_msgpack: bool,+) -> Vec<u8> {+ let content_key = if endpoint == "score" {+ "scores"+ } else {+ "items"+ };++ if use_msgpack {+ // Msgpack: build {"model": ..., "items"|"scores": [raw_blobs...]}+ // at byte level. Partial per-item failures are deliberately omitted+ // from 200 bodies to keep parity with the Python server envelope.+ let result_blobs: Vec<Vec<u8>> = successful+ .iter()+ .map(|r| validated_msgpack_result_blob(r))+ .collect();+ let mut packer = rmp::encode::buffer::ByteBuf::new();+ rmp::encode::write_map_len(&mut packer, 2).unwrap();+ rmp::encode::write_str(&mut packer, "model").unwrap();+ rmp::encode::write_str(&mut packer, model).unwrap();+ rmp::encode::write_str(&mut packer, content_key).unwrap();+ if endpoint == "score" && result_blobs.len() == 1 {+ let mut parts = packer.into_vec();+ parts.extend_from_slice(&result_blobs[0]);+ parts+ } else {+ rmp::encode::write_array_len(&mut packer, result_blobs.len() as u32).unwrap();+ let mut parts = packer.into_vec();+ for blob in &result_blobs {+ parts.extend_from_slice(blob);+ }+ parts+ }+ } else {+ // JSON: decode each blob, convert numpy arrays, wrap in the server+ // envelope. The result blobs typically carry msgpack_numpy-encoded+ // arrays; `rmpv_to_response_json` decodes those without bouncing large+ // binary buffers through serde_json byte arrays.+ let mut result_items: Vec<serde_json::Value> = successful+ .iter()+ .map(+ |r| match rmp_serde::from_slice::<rmpv::Value>(&r.result_msgpack) {+ Ok(rmpv_val) => rmpv_to_response_json(rmpv_val),+ Err(err) => result_decode_error_value(+ r,+ format!("failed to decode result_msgpack: {err}"),+ ),+ },+ )+ .collect();+ let items_val = if endpoint == "score" && result_items.len() == 1 {+ match result_items.pop() {+ Some(serde_json::Value::Array(arr)) => serde_json::Value::Array(arr),+ Some(other) => serde_json::Value::Array(vec![other]),+ None => serde_json::Value::Array(Vec::new()),+ }+ } else {+ serde_json::Value::Array(result_items)+ };+ serde_json::to_vec(&json!({+ "model": model,+ content_key: items_val,+ }))+ .unwrap_or_default()+ }+}+/// Check client SDK version skew./// Warns once per minor version if client SDK differs by >1 minor version.fn check_sdk_version(headers: &HeaderMap) {@@ -1305,25 +1539,19 @@ fn work_params_from_json(parsed: &serde_json::Value, endpoint: &str) -> publishe}let nested_params = parsed.get("params");- let shared_field = |key: &str| {- nested_params- .and_then(|params| params.get(key))- .or_else(|| parsed.get(key))- };- let options = shared_field("options").cloned();+ let field = |key: &str| nested_params.and_then(|params| params.get(key));+ let options = field("options").cloned();publisher::WorkParams {- output_types: shared_field("output_types")- .and_then(|v| v.as_array())- .map(|arr| {- arr.iter()- .filter_map(|v| v.as_str().map(String::from))- .collect()- }),- instruction: shared_field("instruction")+ output_types: field("output_types").and_then(|v| v.as_array()).map(|arr| {+ arr.iter()+ .filter_map(|v| v.as_str().map(String::from))+ .collect()+ }),+ instruction: field("instruction").and_then(|v| v.as_str()).map(String::from),- is_query: shared_field("is_query")+ is_query: field("is_query").and_then(|v| v.as_bool()).or_else(|| {options@@ -1333,14 +1561,12 @@ fn work_params_from_json(parsed: &serde_json::Value, endpoint: &str) -> publishe}).unwrap_or(false),options,- labels: shared_field("labels")- .and_then(|v| v.as_array())- .map(|arr| {- arr.iter()- .filter_map(|v| v.as_str().map(String::from))- .collect()- }),- output_schema: shared_field("output_schema").cloned(),+ labels: field("labels").and_then(|v| v.as_array()).map(|arr| {+ arr.iter()+ .filter_map(|v| v.as_str().map(String::from))+ .collect()+ }),+ output_schema: field("output_schema").cloned(),query_item: None,}}@@ -1367,21 +1593,16 @@ fn work_params_from_rmpv(};}- // For `encode`/`extract`, callers may nest the param block under- // `"params"`; fall through to the top-level if the nested copy- // doesn't carry the field.+ // For `encode`/`extract`, match ``sie_server`` / msgspec: tuning fields live+ // only under the ``params`` object (no top-level merge).let nested = rmpv_map_get(parsed, "params").and_then(|v| match v {rmpv::Value::Map(m) => Some(m.as_slice()),_ => None,});- let shared_field = |key: &str| -> Option<&rmpv::Value> {- nested- .and_then(|m| rmpv_map_get(m, key))- .or_else(|| rmpv_map_get(parsed, key))- };- let options_rmpv = shared_field("options");+ let field = |key: &str| -> Option<&rmpv::Value> { nested.and_then(|m| rmpv_map_get(m, key)) };+ let options_rmpv = field("options");let options = options_rmpv.map(rmpv_to_json_owned);- let is_query = shared_field("is_query")+ let is_query = field("is_query").and_then(rmpv_as_bool).or_else(|| {options_rmpv@@ -1394,14 +1615,12 @@ fn work_params_from_rmpv(.unwrap_or(false);publisher::WorkParams {- output_types: shared_field("output_types").and_then(rmpv_string_array),- instruction: shared_field("instruction")- .and_then(rmpv_as_str)- .map(String::from),+ output_types: field("output_types").and_then(rmpv_string_array),+ instruction: field("instruction").and_then(rmpv_as_str).map(String::from),is_query,options,- labels: shared_field("labels").and_then(rmpv_string_array),- output_schema: shared_field("output_schema").map(rmpv_to_json_owned),+ labels: field("labels").and_then(rmpv_string_array),+ output_schema: field("output_schema").map(rmpv_to_json_owned),query_item: None,}}@@ -1826,6 +2045,339 @@ fn reshape_recursive((serde_json::Value::Array(result), offset)}+#[derive(Debug, PartialEq, Eq)]+struct OpenAiEmbeddingInput {+ texts: Vec<String>,+ token_count: u64,+}++fn estimate_embedding_tokens(texts: &[String]) -> u64 {+ let total: usize = texts.iter().map(|s| s.len()).sum();+ u64::max(1, (total / 4) as u64)+}++fn openai_embedding_input_to_texts(input: &Value) -> Result<OpenAiEmbeddingInput, String> {+ match input {+ Value::String(s) => {+ let texts = vec![s.clone()];+ Ok(OpenAiEmbeddingInput {+ token_count: estimate_embedding_tokens(&texts),+ texts,+ })+ }+ Value::Array(a) if a.is_empty() => Err("input array is empty".to_string()),+ Value::Array(a) if a.iter().all(|x| x.is_string()) => {+ let texts: Vec<String> = a+ .iter()+ .filter_map(|x| x.as_str().map(String::from))+ .collect();+ Ok(OpenAiEmbeddingInput {+ token_count: estimate_embedding_tokens(&texts),+ texts,+ })+ }+ Value::Array(a)+ if a.iter().all(|x| x.as_i64().is_some())+ || a.iter().all(|x| {+ x.as_array()+ .map(|arr| arr.iter().all(|inner| inner.as_i64().is_some()))+ .unwrap_or(false)+ }) =>+ {+ Err(+ "token-array embeddings input is not supported by the gateway; use text input"+ .to_string(),+ )+ }+ _ => Err("input must be a string or array of strings".to_string()),+ }+}++fn extract_dense_embedding_vector(item: &Value) -> Option<Vec<f64>> {+ let dense = item.get("dense")?;+ if let Some(arr) = dense.as_array() {+ return arr.iter().map(Value::as_f64).collect();+ }+ dense+ .get("values")+ .and_then(|v| v.as_array())+ .and_then(|vals| vals.iter().map(Value::as_f64).collect())+}++fn openai_embedding_value(vector: Vec<f64>, encoding_format: &str) -> Value {+ if encoding_format == "base64" {+ let mut bytes = Vec::with_capacity(vector.len() * std::mem::size_of::<f32>());+ for value in vector {+ bytes.extend_from_slice(&(value as f32).to_le_bytes());+ }+ Value::String(base64::engine::general_purpose::STANDARD.encode(bytes))+ } else {+ json!(vector)+ }+}++fn openai_embedding_items_to_data(+ items: &[Value],+ expected_len: usize,+ encoding_format: &str,+) -> Result<Vec<Value>, String> {+ if items.len() != expected_len {+ return Err(format!(+ "encode response item count mismatch: expected {}, got {}",+ expected_len,+ items.len()+ ));+ }++ let mut data = Vec::with_capacity(items.len());+ for (idx, item) in items.iter().enumerate() {+ let Some(vec) = extract_dense_embedding_vector(item) else {+ return Err(format!("item {idx} missing dense embedding"));+ };+ data.push(json!({+ "object": "embedding",+ "embedding": openai_embedding_value(vec, encoding_format),+ "index": idx,+ }));+ }+ Ok(data)+}++#[utoipa::path(+ post,+ path = "/v1/embeddings",+ tag = "inference",+ description = "OpenAI-compatible embeddings proxy. A 200 response contains one embedding per input; partial or truncated internal encode success is treated as a 500 INTERNAL_ERROR instead of returning a partial 200.",+ request_body = crate::openapi::OpenAIEmbeddingRequest,+ params(+ ("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),+ ("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override"),+ ("X-SIE-SDK-Version" = Option<String>, Header, description = "Client SDK version for skew warnings")+ ),+ responses(+ (status = 200, description = "OpenAI-compatible embeddings response", body = crate::openapi::OpenAIEmbeddingsListResponse),+ (status = 202, description = "Worker provisioning in progress", body = crate::openapi::ProvisioningResponse),+ (status = 400, description = "Invalid request", body = crate::openapi::StandardApiError),+ (status = 401, description = "Missing or invalid bearer token", body = crate::openapi::StandardApiError),+ (status = 404, description = "Model not found", body = crate::openapi::StandardApiError),+ (status = 409, description = "Bundle override conflicts with model routing", body = crate::openapi::BundleConflictResponse),+ (status = 413, description = "Request body too large", body = crate::openapi::StandardApiError),+ (status = 500, description = "All batch items failed or gateway internal error", body = crate::openapi::InferenceInternalServerErrorResponse),+ (status = 502, description = "MODEL_LOAD_FAILED", body = crate::openapi::GatewayModelLoadFailedResponse),+ (status = 503, description = "Model loading, capacity, queue unavailable, or GPU not configured", body = crate::openapi::InferenceServiceUnavailableResponse),+ (status = 504, description = "Result channel closed", body = crate::openapi::StandardApiError)+ )+)]+pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Request) -> Response {+ check_sdk_version(req.headers());+ const MAX: usize = 256 * 1024 * 1024;+ let hdr = req.headers().clone();+ let (parts, body) = req.into_parts();+ let body_bytes = match to_bytes(body, MAX).await {+ Ok(b) => b,+ Err(e) => {+ return (+ StatusCode::PAYLOAD_TOO_LARGE,+ Json(json_detail(+ err_code::PAYLOAD_TOO_LARGE,+ format!("request body: {}", e),+ )),+ )+ .into_response();+ }+ };+ let parsed: Value = match serde_json::from_slice(&body_bytes) {+ Ok(v) => v,+ Err(e) => {+ return (+ StatusCode::BAD_REQUEST,+ Json(json_detail(+ err_code::INVALID_REQUEST,+ format!("invalid JSON: {}", e),+ )),+ )+ .into_response();+ }+ };+ let model_str = match parsed.get("model").and_then(|v| v.as_str()) {+ Some(s) if !s.is_empty() => s.to_string(),+ _ => {+ return (+ StatusCode::BAD_REQUEST,+ Json(json_detail(+ err_code::INVALID_REQUEST,+ "field \"model\" is required",+ )),+ )+ .into_response();+ }+ };+ let enc_fmt = parsed+ .get("encoding_format")+ .and_then(|v| v.as_str())+ .unwrap_or("float");+ if enc_fmt != "float" && enc_fmt != "base64" {+ return (+ StatusCode::BAD_REQUEST,+ Json(json_detail(+ err_code::INVALID_REQUEST,+ "encoding_format must be either 'float' or 'base64'",+ )),+ )+ .into_response();+ }+ let input = parsed.get("input").cloned().unwrap_or(Value::Null);+ let normalized_input = match openai_embedding_input_to_texts(&input) {+ Ok(input) => input,+ Err(msg) => {+ return (+ StatusCode::BAD_REQUEST,+ Json(json_detail(err_code::INVALID_REQUEST, msg)),+ )+ .into_response();+ }+ };+ let OpenAiEmbeddingInput { texts, token_count } = normalized_input;+ let encode_body = json!({+ "items": texts.iter().map(|t| json!({"text": t})).collect::<Vec<_>>(),+ "params": {"output_types": ["dense"]},+ });+ let encode_uri = format!("/v1/encode/{}", model_str.trim_start_matches('/'));+ let encode_bytes = match serde_json::to_vec(&encode_body) {+ Ok(b) => b,+ Err(e) => {+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json_detail(+ err_code::INTERNAL_ERROR,+ format!("encode body: {}", e),+ )),+ )+ .into_response();+ }+ };+ let version = parts.version;+ let extensions = parts.extensions;+ let mut inner_headers = HeaderMap::new();+ for (name, val) in hdr.iter() {+ let n = name.as_str();+ if n.eq_ignore_ascii_case("authorization")+ || n.eq_ignore_ascii_case("x-sie-machine-profile")+ || n.eq_ignore_ascii_case("x-sie-pool")+ || n.eq_ignore_ascii_case("x-sie-sdk-version")+ {+ inner_headers.insert(name.clone(), val.clone());+ }+ }+ inner_headers.insert(+ axum::http::header::CONTENT_TYPE,+ HeaderValue::from_static("application/json"),+ );+ inner_headers.insert(+ axum::http::header::ACCEPT,+ HeaderValue::from_static("application/json"),+ );+ let uri: axum::http::Uri = match encode_uri.parse() {+ Ok(u) => u,+ Err(_) => {+ return (+ StatusCode::BAD_REQUEST,+ Json(json_detail(+ err_code::INVALID_REQUEST,+ "invalid model id for path",+ )),+ )+ .into_response();+ }+ };+ let mut builder = Request::builder()+ .method(Method::POST)+ .uri(uri)+ .version(version);+ for (k, v) in inner_headers.iter() {+ builder = builder.header(k, v);+ }+ let mut inner_req = match builder.body(Body::from(encode_bytes)) {+ Ok(r) => r,+ Err(_) => {+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json_detail(+ err_code::INTERNAL_ERROR,+ "failed to build internal encode request",+ )),+ )+ .into_response();+ }+ };+ *inner_req.extensions_mut() = extensions;+ let resp = proxy_request(State(state.clone()), inner_req, "encode").await;+ if resp.status() != StatusCode::OK {+ return resp;+ }+ let enc_headers = resp.headers().clone();+ let rb = match to_bytes(resp.into_body(), MAX).await {+ Ok(b) => b,+ Err(_) => {+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json_detail(+ err_code::INTERNAL_ERROR,+ "failed to read encode response body",+ )),+ )+ .into_response();+ }+ };+ let enc: Value = match serde_json::from_slice(&rb) {+ Ok(v) => v,+ Err(e) => {+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json_detail(+ err_code::INTERNAL_ERROR,+ format!("encode JSON: {}", e),+ )),+ )+ .into_response();+ }+ };+ let Some(items) = enc.get("items").and_then(|i| i.as_array()) else {+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json_detail(+ err_code::INTERNAL_ERROR,+ "encode response missing items",+ )),+ )+ .into_response();+ };+ let data = match openai_embedding_items_to_data(items, texts.len(), enc_fmt) {+ Ok(data) => data,+ Err(msg) => {+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json_detail(err_code::INTERNAL_ERROR, msg)),+ )+ .into_response();+ }+ };+ let token_est = token_count;+ let out = json!({+ "object": "list",+ "data": data,+ "model": model_str,+ "usage": {"prompt_tokens": token_est, "total_tokens": token_est},+ });+ let mut out_resp = (StatusCode::OK, Json(out)).into_response();+ for (k, v) in enc_headers.iter() {+ if is_openai_embeddings_forwarded_header(k.as_str()) {+ out_resp.headers_mut().insert(k.clone(), v.clone());+ }+ }+ out_resp+}+#[cfg(test)]mod tests {use super::*;@@ -1839,6 +2391,18 @@ mod tests {assert_eq!(model, "BAAI/bge-m3");}+ #[test]+ fn test_decode_model_path_decodes_percent_encoded_slashes() {+ let model = decode_model_path("premium:%2FBAAI%2Fbge-m3").unwrap();+ assert_eq!(model, "premium:/BAAI/bge-m3");+ }++ #[test]+ fn test_decode_model_path_rejects_invalid_utf8() {+ let err = decode_model_path("BAAI%2Fbad%FFmodel").unwrap_err();+ assert!(err.contains("not valid UTF-8"));+ }+// ── build_model_loading_timeout_response ──────────────────────//// The queue proxy used to return 504 Gateway Timeout whenever the@@ -1905,6 +2469,25 @@ mod tests {);}+ #[tokio::test]+ async fn test_build_model_load_failed_response_uses_legacy_error_envelope_and_headers() {+ let resp = build_model_load_failed_response("BAAI/bge-m3", "repository is gated");+ assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);+ assert_eq!(+ resp.headers().get("x-sie-error-code").unwrap(),+ MODEL_LOAD_FAILED_ERROR_CODE+ );+ assert!(resp.headers().get("x-sie-error-version").is_some());++ let body_bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)+ .await+ .expect("read body");+ let body: serde_json::Value =+ serde_json::from_slice(&body_bytes).expect("response body is valid JSON");+ assert_eq!(body["error"]["code"], MODEL_LOAD_FAILED_ERROR_CODE);+ assert!(body.get("detail").is_none());+ }+// ── retryable error code translation ───────────────────────────//// When every item in a batch fails with the *same* retryable code@@ -1933,6 +2516,25 @@ mod tests {}}+ fn _ok_result(item_index: u32, result_msgpack: Vec<u8>) -> publisher::WorkResult {+ publisher::WorkResult {+ work_item_id: format!("req.{item_index}"),+ request_id: "req".to_string(),+ item_index,+ success: true,+ result_msgpack,+ 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,+ }+ }+#[test]fn test_unanimous_retryable_error_code_resource_exhausted() {let r1 = _err_result(Some("RESOURCE_EXHAUSTED"), "oom 1");@@ -2017,6 +2619,153 @@ mod tests {assert_eq!(unanimous_retryable_error_code(&errors), None);}+ #[test]+ fn test_queue_success_body_json_omits_partial_error_envelope() {+ let payload = rmp_serde::to_vec(&json!({"result": "ok"})).unwrap();+ let ok = _ok_result(0, payload);+ let body = build_queue_success_body("encode", "model-a", &[&ok], false);+ let parsed: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert_eq!(parsed["model"], "model-a");+ assert_eq!(parsed["items"][0]["result"], "ok");+ assert!(parsed.get("errors").is_none());+ }++ #[test]+ fn test_queue_success_body_json_preserves_decode_failure_item() {+ let bad = _ok_result(0, vec![0xc1]);+ let body = build_queue_success_body("encode", "model-a", &[&bad], false);+ let parsed: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert_eq!(parsed["model"], "model-a");+ let items = parsed["items"].as_array().unwrap();+ assert_eq!(items.len(), 1);+ assert_eq!(items[0]["item_index"], 0);+ assert_eq!(items[0]["work_item_id"], "req.0");+ assert_eq!(items[0]["error"]["code"], "RESULT_DECODE_FAILED");+ assert!(items[0]["error"]["message"]+ .as_str()+ .unwrap()+ .contains("failed to decode result_msgpack"));+ }++ #[test]+ fn test_queue_success_body_msgpack_has_server_envelope_only() {+ let payload = rmp_serde::to_vec(&json!({"result": "ok"})).unwrap();+ let ok = _ok_result(0, payload);+ let body = build_queue_success_body("encode", "model-a", &[&ok], true);+ let parsed: serde_json::Value = rmp_serde::from_slice(&body).unwrap();++ assert_eq!(parsed["model"], "model-a");+ assert_eq!(parsed["items"][0]["result"], "ok");+ assert_eq!(parsed.as_object().unwrap().len(), 2);+ }++ #[test]+ fn test_queue_success_body_msgpack_preserves_decode_failure_item() {+ let bad = _ok_result(0, vec![0xc1]);+ let body = build_queue_success_body("encode", "model-a", &[&bad], true);+ let parsed: serde_json::Value = rmp_serde::from_slice(&body).unwrap();++ assert_eq!(parsed["model"], "model-a");+ let items = parsed["items"].as_array().unwrap();+ assert_eq!(items.len(), 1);+ assert_eq!(items[0]["item_index"], 0);+ assert_eq!(items[0]["work_item_id"], "req.0");+ assert_eq!(items[0]["error"]["code"], "RESULT_DECODE_FAILED");+ }++ #[test]+ fn test_queue_success_body_score_msgpack_replaces_bad_single_payload() {+ let bad = _ok_result(0, vec![0xc1]);+ let body = build_queue_success_body("score", "model-a", &[&bad], true);+ let parsed: serde_json::Value = rmp_serde::from_slice(&body).unwrap();++ assert_eq!(parsed["model"], "model-a");+ assert_eq!(parsed["scores"]["item_index"], 0);+ assert_eq!(parsed["scores"]["error"]["code"], "RESULT_DECODE_FAILED");+ }++ #[test]+ fn test_openai_embeddings_reject_token_id_array() {+ let err = openai_embedding_input_to_texts(&json!([10, 20, 30])).unwrap_err();++ assert!(err.contains("token-array embeddings input is not supported"));+ }++ #[test]+ fn test_openai_embeddings_reject_nested_token_arrays() {+ let err = openai_embedding_input_to_texts(&json!([[10, 20, 30], [40, 50]])).unwrap_err();++ assert!(err.contains("token-array embeddings input is not supported"));+ }++ #[test]+ fn test_openai_embeddings_forwarded_headers_include_encode_timings() {+ for name in [+ "x-sie-request-id",+ "x-sie-version",+ "x-sie-server-version",+ "x-sie-worker",+ "x-queue-publish-time",+ "x-queue-wait-time",+ "x-queue-time",+ "x-inference-time",+ "x-tokenization-time",+ "x-postprocessing-time",+ "x-payload-fetch-time",+ ] {+ assert!(+ is_openai_embeddings_forwarded_header(name),+ "{name} should be forwarded from /v1/encode to /v1/embeddings"+ );+ }+ assert!(is_openai_embeddings_forwarded_header("X-SIE-WORKER"));+ assert!(!is_openai_embeddings_forwarded_header("content-type"));+ assert!(!is_openai_embeddings_forwarded_header("x-sie-error-code"));+ }++ #[test]+ fn test_openai_embedding_value_base64_is_little_endian_f32() {+ let encoded = openai_embedding_value(vec![1.0, -2.0], "base64");+ let Value::String(encoded) = encoded else {+ panic!("expected base64 string");+ };++ let bytes = base64::engine::general_purpose::STANDARD+ .decode(encoded)+ .unwrap();+ assert_eq!(bytes, vec![0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0xc0]);+ }++ #[test]+ fn test_openai_embedding_items_to_data_rejects_partial_encode_response() {+ let items = vec![json!({"dense": [1.0, 2.0]})];+ let err = openai_embedding_items_to_data(&items, 2, "float").unwrap_err();+ assert!(err.contains("expected 2, got 1"));+ }++ #[test]+ fn test_openai_embedding_items_to_data_rejects_missing_dense_vector() {+ let items = vec![json!({"sparse": {"indices": [1], "values": [0.5]}})];+ let err = openai_embedding_items_to_data(&items, 1, "float").unwrap_err();+ assert_eq!(err, "item 0 missing dense embedding");+ }++ #[test]+ fn test_openai_embedding_items_to_data_rejects_non_numeric_dense_array() {+ let items = vec![json!({"dense": [1.0, "bad", 3.0]})];+ let err = openai_embedding_items_to_data(&items, 1, "float").unwrap_err();+ assert_eq!(err, "item 0 missing dense embedding");+ }++ #[test]+ fn test_openai_embedding_items_to_data_rejects_non_numeric_dense_values() {+ let items = vec![json!({"dense": {"values": [1.0, false, 3.0]}})];+ let err = openai_embedding_items_to_data(&items, 1, "float").unwrap_err();+ assert_eq!(err, "item 0 missing dense embedding");+ }+#[test]fn test_build_retryable_error_response_resource_exhausted_status_and_headers() {let resp = build_retryable_error_response(@@ -2240,10 +2989,8 @@ mod tests {assert_eq!(params.query_item, Some(rmpv::Value::from("hello")));}- /// Msgpack-in encode request: the whole body is a msgpack map,- /// `items` is an array of maps, and `work_params_from_rmpv`- /// should read `output_types` / `instruction` / `options` the- /// same way the JSON path does.+ /// Msgpack-in encode request: tuning fields are read only from the nested+ /// ``params`` map (parity with ``sie_server`` / msgspec).#[test]fn test_parse_queue_request_msgpack_encode_reads_params() {let body_value = rmpv::Value::Map(vec![@@ -2255,19 +3002,24 @@ mod tests {)])]),),(- rmpv::Value::from("output_types"),- rmpv::Value::Array(vec![rmpv::Value::from("dense")]),- ),- (- rmpv::Value::from("instruction"),- rmpv::Value::from("search"),- ),- (- rmpv::Value::from("options"),- rmpv::Value::Map(vec![(- rmpv::Value::from("is_query"),- rmpv::Value::Boolean(true),- )]),+ rmpv::Value::from("params"),+ rmpv::Value::Map(vec![+ (+ rmpv::Value::from("output_types"),+ rmpv::Value::Array(vec![rmpv::Value::from("dense")]),+ ),+ (+ rmpv::Value::from("instruction"),+ rmpv::Value::from("search"),+ ),+ (+ rmpv::Value::from("options"),+ rmpv::Value::Map(vec![(+ rmpv::Value::from("is_query"),+ rmpv::Value::Boolean(true),+ )]),+ ),+ ]),),]);let body = rmp_serde::to_vec(&body_value).unwrap();@@ -2613,7 +3365,7 @@ mod tests {];let items: Vec<serde_json::Value> = results.iter()- .filter_map(|r| rmp_serde::from_slice(&r.result_msgpack).ok())+ .map(|r| rmp_serde::from_slice(&r.result_msgpack).unwrap()).collect();assert_eq!(items.len(), 2);assert_eq!(items[0]["result"], "a");diff --git a/packages/sie_gateway/src/health_mode.rs b/packages/sie_gateway/src/health_mode.rsnew file mode 100644index 000000000..e4474ff42--- /dev/null+++ b/packages/sie_gateway/src/health_mode.rs@@ -0,0 +1,81 @@+//! Pure classification for `SIE_GATEWAY_HEALTH_MODE` vs NATS connectivity.+//! Side effects and manager startup live in `main.rs`.++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum HealthModeDisposition {+ /// Default supported path: WebSocket worker health.+ WebSocketDefault,+ /// Experimental path: subscribe to `sie.health.>` when URL + client exist.+ TryNatsExperimental,+ /// `nats` requested but `SIE_NATS_URL` is unset or empty.+ FallbackWebSocketMissingNatsUrl,+ /// `nats` requested but no usable NATS client is available yet.+ FallbackWebSocketNoNatsClient,+ /// Unknown mode string; fall back to WebSocket like `main` has always done.+ FallbackWebSocketUnsupported,+}++/// Classify how the gateway should initialize worker health transport before any+/// subscription side effects.+pub fn health_mode_disposition(+ mode: &str,+ nats_url_nonempty: bool,+ nats_client_available: bool,+) -> HealthModeDisposition {+ match mode {+ "ws" => HealthModeDisposition::WebSocketDefault,+ "nats" if !nats_url_nonempty => HealthModeDisposition::FallbackWebSocketMissingNatsUrl,+ "nats" if !nats_client_available => HealthModeDisposition::FallbackWebSocketNoNatsClient,+ "nats" => HealthModeDisposition::TryNatsExperimental,+ _ => HealthModeDisposition::FallbackWebSocketUnsupported,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ws_always_default() {+ assert_eq!(+ health_mode_disposition("ws", false, false),+ HealthModeDisposition::WebSocketDefault+ );+ assert_eq!(+ health_mode_disposition("ws", true, true),+ HealthModeDisposition::WebSocketDefault+ );+ }++ #[test]+ fn nats_requires_url() {+ assert_eq!(+ health_mode_disposition("nats", false, true),+ HealthModeDisposition::FallbackWebSocketMissingNatsUrl+ );+ }++ #[test]+ fn nats_requires_client_when_url_present() {+ assert_eq!(+ health_mode_disposition("nats", true, false),+ HealthModeDisposition::FallbackWebSocketNoNatsClient+ );+ }++ #[test]+ fn nats_with_url_and_client_is_experimental_path() {+ assert_eq!(+ health_mode_disposition("nats", true, true),+ HealthModeDisposition::TryNatsExperimental+ );+ }++ #[test]+ fn unknown_mode_falls_back() {+ assert_eq!(+ health_mode_disposition("grpc", true, true),+ HealthModeDisposition::FallbackWebSocketUnsupported+ );+ }+}diff --git a/packages/sie_gateway/src/http_error.rs b/packages/sie_gateway/src/http_error.rsnew file mode 100644index 000000000..290c09add--- /dev/null+++ b/packages/sie_gateway/src/http_error.rs@@ -0,0 +1,50 @@+//! Canonical JSON error bodies (FastAPI-style ``{"detail": {"code", "message", ...}}``).+//! SDK-stable responses (``502 MODEL_LOAD_FAILED``, ``503`` retryable ``{"error":{...}}``)+//! intentionally stay on their existing shapes.++use serde_json::{json, Map, Value};++/// Stable ``detail.code`` values for gateway-generated errors.+pub mod code {+ pub const MODEL_NOT_FOUND: &str = "MODEL_NOT_FOUND";+ pub const BUNDLE_NOT_FOUND: &str = "BUNDLE_NOT_FOUND";+ pub const POOL_NOT_FOUND: &str = "POOL_NOT_FOUND";+ pub const INVALID_REQUEST: &str = "INVALID_REQUEST";+ pub const PAYLOAD_TOO_LARGE: &str = "PAYLOAD_TOO_LARGE";+ pub const QUEUE_UNAVAILABLE: &str = "QUEUE_UNAVAILABLE";+ pub const GPU_NOT_CONFIGURED: &str = "GPU_NOT_CONFIGURED";+ pub const BUNDLE_ROUTING_CONFLICT: &str = "BUNDLE_ROUTING_CONFLICT";+ pub const CONFIG_RESOLVE_BUNDLE_CONFLICT: &str = "BUNDLE_ROUTING_CONFLICT";+ pub const INTERNAL_ERROR: &str = "INTERNAL_SERVER_ERROR";+ pub const GATEWAY_TIMEOUT: &str = "GATEWAY_TIMEOUT";+ pub const SERIALIZATION_ERROR: &str = "SERIALIZATION_ERROR";+ pub const UNAUTHORIZED: &str = "UNAUTHORIZED";+ pub const FORBIDDEN: &str = "FORBIDDEN";+ pub const GATEWAY_AUTH_MISCONFIGURED: &str = "GATEWAY_AUTH_MISCONFIGURED";+ pub const DEFAULT_POOL_DELETE_FORBIDDEN: &str = "DEFAULT_POOL_DELETE_FORBIDDEN";+ pub const POOL_OPERATION_FORBIDDEN: &str = "POOL_OPERATION_FORBIDDEN";+ pub const PROVISIONING: &str = "PROVISIONING";+}++/// ``{"detail": {"code", "message"}}``+pub fn json_detail(code: &str, message: impl Into<String>) -> Value {+ json!({+ "detail": {+ "code": code,+ "message": message.into(),+ }+ })+}++/// ``{"detail": { "code", "message", ...extra }}`` — merge extra keys into ``detail``.+pub fn json_detail_merge(+ code: &str,+ message: impl Into<String>,+ extra: Map<String, Value>,+) -> Value {+ let mut d = Map::new();+ d.insert("code".to_string(), json!(code));+ d.insert("message".to_string(), json!(message.into()));+ d.extend(extra);+ json!({ "detail": Value::Object(d) })+}diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rsindex f3dc81a30..d957bdd6a 100644--- a/packages/sie_gateway/src/main.rs+++ b/packages/sie_gateway/src/main.rs@@ -2,14 +2,18 @@ mod config;mod discovery;mod error;mod handlers;+mod health_mode;+mod http_error;mod metrics;mod middleware;mod nats;+mod openapi;mod queue;mod server;mod state;mod types;+use std::path::PathBuf;use std::sync::Arc;use std::time::Duration;@@ -22,6 +26,7 @@ use config::Config;use discovery::nats_health::NatsHealthManager;use discovery::static_discovery::StaticDiscovery;use discovery::ws_health::WsHealthManager;+use health_mode::{health_mode_disposition, HealthModeDisposition};use nats::manager::NatsManager;use queue::payload_store::create_payload_store;use server::AppState;@@ -86,6 +91,10 @@ enum Commands {#[arg(long)]models_dir: Option<String>,},+ Openapi {+ #[arg(short = 'o', long)]+ output: Option<PathBuf>,+ },Version,}@@ -97,6 +106,12 @@ async fn main() {Commands::Version => {println!("sie-gateway {} (rust)", VERSION);}+ Commands::Openapi { output } => {+ if let Err(e) = openapi::write_openapi_json(output.as_deref()) {+ eprintln!("failed to export OpenAPI spec: {e}");+ std::process::exit(1);+ }+ }Commands::Serve {port,host,@@ -289,48 +304,62 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {}}- // Set up health manager based on mode+ // Set up health manager based on mode. WebSocket health is the supported+ // product path; NATS health is an internal/experimental consumer until+ // workers publish `sie.health.>` by default.+ //+ // Core NATS subscriptions are resumed by the client on reconnect; do not spawn+ // duplicate `NatsHealthManager::start` loops on `reconnect_notify` (see PR review).let mut ws_manager: Option<Arc<WsHealthManager>> = None;let mut nats_health_manager: Option<Arc<NatsHealthManager>> = None;let mut use_ws = true;- if config.health_mode == "nats" && !config.nats_url.is_empty() {- if let Some(client) = nats_manager.get_client().await {- info!("using NATS health mode (shared connection)");- let nats_mgr = Arc::new(NatsHealthManager::new(Arc::clone(®istry)));- match nats_mgr.start(&client).await {- Ok(()) => {- nats_mgr.start_heartbeat_loop().await;-- // Reconnect listener: re-subscribe health on NATS reconnect- let nats_mgr_for_reconnect = Arc::clone(&nats_mgr);- let reconnect = nats_manager.reconnect_notify();- let nats_mgr_client_source = Arc::clone(&nats_manager);- tokio::spawn(async move {- loop {- reconnect.notified().await;- info!("NATS reconnected — re-subscribing health");- if let Some(client) = nats_mgr_client_source.get_client().await {- if let Err(e) = nats_mgr_for_reconnect.start(&client).await {- tracing::warn!(error = %e, "failed to re-subscribe health on reconnect");- }- }- }- });-- nats_health_manager = Some(nats_mgr);- use_ws = false;- info!("NATS health manager started");- }- Err(e) => {- tracing::warn!(error = %e, "failed to start NATS health manager, falling back to WS");- }- }- } else {+ let nats_url_nonempty = !config.nats_url.is_empty();+ let nats_client_available = nats_manager.get_client().await.is_some();+ let disposition = health_mode_disposition(+ config.health_mode.as_str(),+ nats_url_nonempty,+ nats_client_available,+ );++ match disposition {+ HealthModeDisposition::WebSocketDefault => {}+ HealthModeDisposition::FallbackWebSocketMissingNatsUrl => {+ tracing::warn!(+ "NATS health mode requested but SIE_NATS_URL is not configured; falling back to WS"+ );+ }+ HealthModeDisposition::FallbackWebSocketNoNatsClient => {tracing::warn!("NATS health mode requested but client not available, falling back to WS");}+ HealthModeDisposition::FallbackWebSocketUnsupported => {+ tracing::warn!(+ mode = %config.health_mode,+ "unsupported gateway health mode requested; falling back to WS"+ );+ }+ HealthModeDisposition::TryNatsExperimental => {+ tracing::warn!(+ "NATS health mode is experimental/internal and requires workers to publish sie.health.>; if no publisher exists, the worker registry can remain empty"+ );+ if let Some(client) = nats_manager.get_client().await {+ info!("using NATS health mode (shared connection)");+ let nats_mgr = Arc::new(NatsHealthManager::new(Arc::clone(®istry)));+ match nats_mgr.start(&client).await {+ Ok(()) => {+ nats_mgr.start_heartbeat_loop().await;+ nats_health_manager = Some(nats_mgr);+ use_ws = false;+ info!("NATS health manager started");+ }+ Err(e) => {+ tracing::warn!(error = %e, "failed to start NATS health manager, falling back to WS");+ }+ }+ }+ }}if use_ws {diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rsindex 604e7b904..da9677636 100644--- a/packages/sie_gateway/src/middleware/auth.rs+++ b/packages/sie_gateway/src/middleware/auth.rs@@ -8,6 +8,8 @@ use std::task::{Context, Poll};use subtle::ConstantTimeEq;use tower::{Layer, Service};+use crate::http_error::code as err_code;+use crate::config::Config;/// Paths that are always exempt from auth. Kubernetes liveness/readiness@@ -17,6 +19,10 @@ use crate::config::Config;/// intentionally NOT in this list — see `EXEMPT_OPERATIONAL_PATHS`.const EXEMPT_PROBE_PATHS: &[&str] = &["/healthz", "/readyz"];+/// Public API description. Keep client-codegen and discovery usable even+/// when request auth is enabled.+const EXEMPT_DOC_PATHS: &[&str] = &["/openapi.json"];+/// Paths that expose operational data (status page, rich `/health`,/// `/metrics`, `/ws/*`). Exempt from auth only when/// `SIE_AUTH_EXEMPT_OPERATIONAL=true`; default is fail-closed.@@ -74,7 +80,7 @@ wherelet path = req.uri().path();- if EXEMPT_PROBE_PATHS.contains(&path) {+ if EXEMPT_PROBE_PATHS.contains(&path) || EXEMPT_DOC_PATHS.contains(&path) {return inner.call(req).await;}@@ -87,6 +93,7 @@ whereif config.auth_tokens.is_empty() {return Ok(error_response(StatusCode::INTERNAL_SERVER_ERROR,+ err_code::GATEWAY_AUTH_MISCONFIGURED,"Gateway auth enabled but no tokens configured",));}@@ -96,6 +103,7 @@ whereNone => {return Ok(error_response(StatusCode::UNAUTHORIZED,+ err_code::UNAUTHORIZED,"Missing Authorization header",));}@@ -107,6 +115,7 @@ whereif config.admin_token.is_empty() {return Ok(error_response(StatusCode::FORBIDDEN,+ err_code::FORBIDDEN,"Admin token not configured",));}@@ -114,6 +123,7 @@ whereif !constant_time_eq_str(&token, &config.admin_token) {return Ok(error_response(StatusCode::FORBIDDEN,+ err_code::FORBIDDEN,"Admin token required",));}@@ -127,7 +137,11 @@ where.any(|valid_token| constant_time_eq_str(&token, valid_token));if !valid {- return Ok(error_response(StatusCode::UNAUTHORIZED, "Invalid token"));+ return Ok(error_response(+ StatusCode::UNAUTHORIZED,+ err_code::UNAUTHORIZED,+ "Invalid token",+ ));}inner.call(req).await@@ -186,8 +200,13 @@ fn constant_time_eq_str(a: &str, b: &str) -> bool {a.as_bytes().ct_eq(b.as_bytes()).into()}-fn error_response(status: StatusCode, message: &str) -> Response {- let body = serde_json::json!({"message": message});+fn error_response(status: StatusCode, code: &'static str, message: &str) -> Response {+ let body = serde_json::json!({+ "detail": {+ "code": code,+ "message": message,+ }+ });(status, axum::Json(body)).into_response()}@@ -267,6 +286,7 @@ mod tests {// Probe paths are always exempt; operational paths are not.assert!(EXEMPT_PROBE_PATHS.contains(&"/healthz"));assert!(EXEMPT_PROBE_PATHS.contains(&"/readyz"));+ assert!(EXEMPT_DOC_PATHS.contains(&"/openapi.json"));assert!(!EXEMPT_PROBE_PATHS.contains(&"/health"));assert!(!EXEMPT_PROBE_PATHS.contains(&"/metrics"));assert!(EXEMPT_OPERATIONAL_PATHS.contains(&"/"));@@ -339,6 +359,7 @@ mod tests {.route("/", get(|| async { "index" })).route("/health", get(|| async { "rich-health" })).route("/metrics", get(|| async { "metrics" }))+ .route("/openapi.json", get(|| async { "{}" })).route("/ws/cluster-status", get(|| async { "ws" })).route("/v1/encode/{*model}", post(|| async { "encoded" })).route("/v1/pools", post(|| async { "created" }))@@ -376,6 +397,16 @@ mod tests {assert_eq!(send(r, Method::GET, "/readyz", None).await, StatusCode::OK);}+ #[tokio::test]+ async fn middleware_openapi_is_always_exempt() {+ let cfg = cfg_for_middleware("token", vec!["user"], "admin", false);+ let r = test_router(cfg);+ assert_eq!(+ send(r, Method::GET, "/openapi.json", None).await,+ StatusCode::OK+ );+ }+#[tokio::test]async fn middleware_operational_paths_fail_closed_by_default() {let cfg = cfg_for_middleware("token", vec!["user"], "admin", false);diff --git a/packages/sie_gateway/src/middleware/metrics.rs b/packages/sie_gateway/src/middleware/metrics.rsindex 18742c6a0..c4a7957f3 100644--- a/packages/sie_gateway/src/middleware/metrics.rs+++ b/packages/sie_gateway/src/middleware/metrics.rs@@ -7,8 +7,8 @@//! `handlers::proxy::queue_mode_proxy` has been removed in favour of//! this layer.//!-//! Only the three inference endpoints (`/v1/encode/*`, `/v1/score/*`,-//! `/v1/extract/*`) populate `sie_gateway_requests_total` ++//! Only inference endpoints (`/v1/encode/*`, `/v1/score/*`,+//! `/v1/extract/*`, `/v1/embeddings`) populate `sie_gateway_requests_total` +//! `sie_gateway_request_latency_seconds`. Infrastructure paths//! (`/health*`, `/metrics`, `/ws/*`, `/v1/configs/*`, `/v1/pools`,//! `/v1/models`) are intentionally skipped: they are not traffic, and@@ -42,7 +42,7 @@//! `/metrics` scrapes, config plane calls) pay **zero heap allocations//! and no clock reads** from this layer — the classifier runs on a//! borrowed `&str` and exits early when the path isn't one of the-//! three inference prefixes.+//! inference prefixes.//!//! For inference requests the added overhead is bounded://! - One `Instant::now()` / `elapsed()` pair (vDSO, ~20 ns).@@ -164,7 +164,7 @@ where}}-/// Return the endpoint label (`encode`, `score`, `extract`) when the+/// Return the endpoint label (`encode`, `score`, `extract`, `embeddings`) when the/// path matches an inference route, otherwise `None`. Non-inference/// paths are intentionally excluded — see module-level docs.///@@ -178,6 +178,8 @@ fn classify_endpoint(path: &str) -> Option<&'static str> {Some("score")} else if path.starts_with("/v1/extract/") {Some("extract")+ } else if path == "/v1/embeddings" {+ Some("embeddings")} else {None}@@ -286,6 +288,10 @@ mod tests {))}),)+ .route(+ "/v1/embeddings",+ post(|req: Request<Body>| async move { set_profile(req, "l4-spot").await }),+ ).route("/health", axum::routing::get(|| async { "health" })).route("/metrics", axum::routing::get(|| async { "metrics" })).layer(MetricsLayer::new())@@ -391,6 +397,19 @@ mod tests {assert_eq!(counter_value("extract", "504", "a100") - before, 1.0);}+ #[tokio::test]+ #[allow(clippy::await_holding_lock)] // see COUNTER_TEST_LOCK doc+ async fn records_200_on_openai_embeddings_from_handler_slot() {+ let _guard = COUNTER_TEST_LOCK.lock().unwrap();+ let _ = &*metrics::REGISTRY;+ let before = counter_value("embeddings", "200", "l4-spot");++ let status = fire(test_router(), Method::POST, "/v1/embeddings", None).await;+ assert_eq!(status, StatusCode::OK);++ assert_eq!(counter_value("embeddings", "200", "l4-spot") - before, 1.0);+ }+#[tokio::test]#[allow(clippy::await_holding_lock)] // see COUNTER_TEST_LOCK docasync fn skips_infrastructure_paths() {@@ -435,6 +454,7 @@ mod tests {assert_eq!(classify_endpoint("/v1/encode/org/model"), Some("encode"));assert_eq!(classify_endpoint("/v1/score/org/model"), Some("score"));assert_eq!(classify_endpoint("/v1/extract/org/model"), Some("extract"));+ assert_eq!(classify_endpoint("/v1/embeddings"), Some("embeddings"));assert_eq!(classify_endpoint("/health"), None);assert_eq!(classify_endpoint("/healthz"), None);assert_eq!(classify_endpoint("/readyz"), None);diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rsindex 3428c5aa6..e8b3db775 100644--- a/packages/sie_gateway/src/nats/manager.rs+++ b/packages/sie_gateway/src/nats/manager.rs@@ -605,6 +605,9 @@ adapters:);profiles},+ inputs: None,+ max_sequence_length: None,+ tasks: None,};registry.add_model_config(seed).unwrap();diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsnew file mode 100644index 000000000..009ddbb3f--- /dev/null+++ b/packages/sie_gateway/src/openapi.rs@@ -0,0 +1,1467 @@+use axum::http::header;+use axum::response::IntoResponse;+use serde::{Deserialize, Serialize};+use serde_json::json;+use serde_json::Value;+use std::path::Path;+use std::sync::LazyLock;+use utoipa::{OpenApi, ToSchema};++static OPENAPI_DOC: LazyLock<utoipa::openapi::OpenApi> = LazyLock::new(|| {+ let mut doc = ApiDoc::openapi();+ doc.info.version = env!("CARGO_PKG_VERSION").to_string();+ doc+});++static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {+ let mut value = serde_json::to_value(&*OPENAPI_DOC).expect("OpenAPI document should serialize");+ apply_gateway_openapi_overrides(&mut value);+ serde_json::to_string_pretty(&value).expect("OpenAPI document should serialize") + "\n"+});++#[derive(OpenApi)]+#[openapi(+ info(+ title = "SIE Gateway",+ description = "Rust gateway API for SIE inference, pool coordination, and read-only runtime config.",+ version = "0.0.0"+ ),+ paths(+ crate::handlers::health::status_page,+ openapi_json,+ crate::handlers::health::healthz,+ crate::handlers::health::readyz,+ crate::handlers::health::health,+ crate::handlers::health::ws_cluster_status,+ crate::handlers::models::get_models,+ crate::handlers::models::get_model,+ crate::handlers::pools::create_pool,+ crate::handlers::pools::list_pools,+ crate::handlers::pools::get_pool,+ crate::handlers::pools::delete_pool,+ crate::handlers::pools::renew_pool,+ crate::handlers::config_api::get_model_configs,+ crate::handlers::config_api::get_model_config_or_status,+ get_model_config_status_doc,+ crate::handlers::config_api::get_bundle_configs,+ crate::handlers::config_api::get_bundle_config,+ crate::handlers::config_api::resolve_config,+ crate::handlers::proxy::proxy_encode,+ crate::handlers::proxy::proxy_openai_embeddings,+ crate::handlers::proxy::proxy_score,+ crate::handlers::proxy::proxy_extract,+ crate::server::metrics_handler+ ),+ components(schemas(+ BundleConfigDocument,+ BundleConfigSummary,+ BundleConfigsResponse,+ ClusterSummary,+ ConfigModelDocument,+ ConfigModelSummary,+ ConfigModelsResponse,+ crate::handlers::pools::CreatePoolRequest,+ ErrorDetailCore,+ StandardApiError,+ GpuNotConfiguredDetail,+ GpuNotConfiguredError,+ GatewayModelLoadFailedDetail,+ GatewayModelLoadFailedResponse,+ GatewayErrorResponse,+ InferenceInternalServerErrorResponse,+ InferenceServiceUnavailableResponse,+ AllItemsFailedResponse,+ BundleRoutingConflictDetail,+ BundleConflictResponse,+ DocumentInput,+ DenseVector,+ EncodeParams,+ EncodeRequest,+ EncodeResponse,+ EncodeResult,+ Entity,+ ExtractParams,+ ExtractRequest,+ ExtractResponse,+ ExtractResult,+ ImageInput,+ HealthResponse,+ ItemInput,+ InferenceErrorDetail,+ MessageResponse,+ ModelAckBundleStatus,+ ModelConfigStatusResponse,+ ModelInfoWire,+ ModelNotFoundDetail,+ ModelNotFoundResponse,+ ProfileInfoWire,+ crate::types::worker::ModelInfo,+ MultiVector,+ OpenAIEmbeddingDataEntry,+ OpenAIEmbeddingEncodingFormat,+ OpenAIEmbeddingInput,+ OpenAIEmbeddingRequest,+ OpenAIEmbeddingUsage,+ OpenAIEmbeddingVector,+ OpenAIEmbeddingsListResponse,+ PoolListResponse,+ crate::types::pool::PoolSpec,+ crate::types::pool::PoolStatus,+ crate::types::pool::PoolState,+ ProvisioningResponse,+ Relation,+ ResolveBundleConflictDetail,+ ResolveBundleConflictResponse,+ ResolveModelNotFoundDetail,+ ResolveModelNotFoundResponse,+ ResolveConfigResponse,+ ScoreEntry,+ crate::handlers::config_api::ResolveRequest,+ ScoreRequest,+ ScoreResponse,+ SparseVector,+ TimingInfo,+ crate::types::pool::AssignedWorker,+ crate::types::worker::WorkerInfo+ )),+ tags(+ (name = "health", description = "Gateway health, readiness, and status surfaces"),+ (name = "inference", description = "Queue-backed inference entrypoints"),+ (name = "models", description = "Models visible to this gateway replica"),+ (name = "pools", description = "Runtime pool coordination"),+ (name = "config", description = "Read-only gateway view of model and bundle config"),+ (name = "observability", description = "Metrics and streaming status"),+ (name = "docs", description = "API description")+ )+)]+pub struct ApiDoc;++#[utoipa::path(+ get,+ path = "/openapi.json",+ tag = "docs",+ responses((status = 200, description = "OpenAPI document"))+)]+pub async fn openapi_json() -> impl IntoResponse {+ (+ [(header::CONTENT_TYPE, "application/json")],+ OPENAPI_JSON.as_str(),+ )+}++#[cfg(test)]+fn openapi_document() -> utoipa::openapi::OpenApi {+ OPENAPI_DOC.clone()+}++fn apply_gateway_openapi_overrides(value: &mut Value) {+ value["info"]["license"] = json!({+ "name": "Apache-2.0",+ "url": "https://www.apache.org/licenses/LICENSE-2.0.html"+ });+ value["security"] = json!([{ "bearerAuth": [] }]);++ let components = value+ .as_object_mut()+ .expect("OpenAPI root should be an object")+ .entry("components")+ .or_insert_with(|| json!({}));+ components["securitySchemes"] = json!({+ "bearerAuth": {+ "type": "http",+ "scheme": "bearer",+ "bearerFormat": "opaque",+ "description": "SIE bearer token. Mutating pool/config/admin routes require the configured admin token; other protected routes accept a normal gateway token."+ }+ });++ if let Some(create_pool) = value+ .get_mut("components")+ .and_then(|components| components.get_mut("schemas"))+ .and_then(|schemas| schemas.get_mut("CreatePoolRequest"))+ {+ create_pool["required"] = json!(["name", "gpus"]);+ if let Some(gpus) = create_pool+ .get_mut("properties")+ .and_then(|properties| properties.get_mut("gpus"))+ {+ gpus["minProperties"] = json!(1);+ }+ }++ let paths = value["paths"]+ .as_object_mut()+ .expect("OpenAPI paths should be an object");++ for path in ["/healthz", "/readyz", "/openapi.json"] {+ if let Some(operation) = paths+ .get_mut(path)+ .and_then(|path_item| path_item.get_mut("get"))+ {+ operation["security"] = json!([]);+ }+ }++ if let Some(response) = paths+ .get_mut("/openapi.json")+ .and_then(|path_item| path_item.get_mut("get"))+ .and_then(|operation| operation.get_mut("responses"))+ .and_then(|responses| responses.get_mut("200"))+ {+ response["content"] = json!({+ "application/json": {+ "schema": {+ "type": "object"+ }+ }+ });+ }++ inject_inference_msgpack_content(paths);+ inject_inference_response_headers(paths);+ inject_bearer_auth_error_responses(paths);+ annotate_slash_bearing_path_parameters(paths);+}++/// Duplicate ``application/json`` schemas to the msgpack media types accepted by queue inference.+fn inject_inference_msgpack_content(paths: &mut serde_json::Map<String, Value>) {+ for path in [+ "/v1/encode/{model}",+ "/v1/score/{model}",+ "/v1/extract/{model}",+ ] {+ let Some(path_item) = paths.get_mut(path) else {+ continue;+ };+ let Some(post) = path_item.get_mut("post").and_then(|p| p.as_object_mut()) else {+ continue;+ };+ if let Some(rb) = post.get_mut("requestBody").and_then(|r| r.as_object_mut()) {+ if let Some(content) = rb.get_mut("content").and_then(|c| c.as_object_mut()) {+ if let Some(json_entry) = content.get("application/json").cloned() {+ for media_type in [+ "application/msgpack",+ "application/x-msgpack",+ "application/vnd.msgpack",+ ] {+ content.insert(media_type.to_string(), json_entry.clone());+ }+ }+ }+ }+ let Some(responses) = post.get_mut("responses").and_then(|r| r.as_object_mut()) else {+ continue;+ };+ let Some(ok) = responses.get_mut("200").and_then(|x| x.as_object_mut()) else {+ continue;+ };+ let Some(content) = ok.get_mut("content").and_then(|c| c.as_object_mut()) else {+ continue;+ };+ if let Some(json_entry) = content.get("application/json").cloned() {+ for media_type in [+ "application/msgpack",+ "application/x-msgpack",+ "application/vnd.msgpack",+ ] {+ content.insert(media_type.to_string(), json_entry.clone());+ }+ }+ }+}++fn header(description: &str) -> Value {+ json!({+ "description": description,+ "schema": { "type": "string" }+ })+}++fn merge_headers(response: &mut Value, headers: &Value) {+ let Some(response) = response.as_object_mut() else {+ return;+ };+ let Some(header_map) = headers.as_object() else {+ return;+ };+ let headers = response+ .entry("headers")+ .or_insert_with(|| json!({}))+ .as_object_mut()+ .expect("OpenAPI response headers should be an object");+ for (name, value) in header_map {+ headers.entry(name.clone()).or_insert(value.clone());+ }+}++fn inject_inference_response_headers(paths: &mut serde_json::Map<String, Value>) {+ let queue_success_headers = json!({+ "X-SIE-Version": header("Gateway package version that handled the request"),+ "X-SIE-Server-Version": header("Gateway-compatible server version advertised by this gateway"),+ "X-SIE-Request-Id": header("Gateway request id for queue-backed inference"),+ "X-SIE-Worker": header("Logical queue worker tag that produced the response"),+ "X-Queue-Publish-Time": header("Milliseconds spent publishing work to the queue"),+ "X-Queue-Wait-Time": header("Milliseconds spent waiting for worker results"),+ "X-Queue-Time": header("Worker-reported queue time in milliseconds"),+ "X-Inference-Time": header("Worker-reported inference time in milliseconds"),+ "X-Tokenization-Time": header("Worker-reported tokenization time in milliseconds, when available"),+ "X-Postprocessing-Time": header("Worker-reported postprocessing time in milliseconds, when available"),+ "X-Payload-Fetch-Time": header("Worker-reported offloaded payload fetch time in milliseconds, when available")+ });+ let provisioning_headers = json!({+ "Retry-After": header("Suggested retry delay in seconds"),+ "X-SIE-Version": header("Gateway package version that handled the request"),+ "X-SIE-Server-Version": header("Gateway-compatible server version advertised by this gateway")+ });+ let retryable_error_headers = json!({+ "Retry-After": header("Suggested retry delay in seconds, when retryable"),+ "X-SIE-Error-Code": header("SDK-stable gateway or worker error code"),+ "X-SIE-Version": header("Gateway package version that handled the request"),+ "X-SIE-Server-Version": header("Gateway-compatible server version advertised by this gateway")+ });+ let terminal_error_headers = json!({+ "X-SIE-Error-Code": header("SDK-stable gateway or worker error code"),+ "X-SIE-Error-Version": header("Gateway package version associated with the error envelope"),+ "X-SIE-Version": header("Gateway package version that handled the request"),+ "X-SIE-Server-Version": header("Gateway-compatible server version advertised by this gateway")+ });++ for path in [+ "/v1/encode/{model}",+ "/v1/score/{model}",+ "/v1/extract/{model}",+ ] {+ let Some(responses) = paths+ .get_mut(path)+ .and_then(|path_item| path_item.get_mut("post"))+ .and_then(|post| post.get_mut("responses"))+ .and_then(|responses| responses.as_object_mut())+ else {+ continue;+ };+ if let Some(response) = responses.get_mut("200") {+ merge_headers(response, &queue_success_headers);+ }+ if let Some(response) = responses.get_mut("202") {+ merge_headers(response, &provisioning_headers);+ }+ if let Some(response) = responses.get_mut("502") {+ merge_headers(response, &terminal_error_headers);+ }+ if let Some(response) = responses.get_mut("503") {+ merge_headers(response, &retryable_error_headers);+ }+ }++ if let Some(responses) = paths+ .get_mut("/v1/embeddings")+ .and_then(|path_item| path_item.get_mut("post"))+ .and_then(|post| post.get_mut("responses"))+ .and_then(|responses| responses.as_object_mut())+ {+ if let Some(response) = responses.get_mut("200") {+ merge_headers(response, &queue_success_headers);+ }+ if let Some(response) = responses.get_mut("202") {+ merge_headers(response, &provisioning_headers);+ }+ if let Some(response) = responses.get_mut("502") {+ merge_headers(response, &terminal_error_headers);+ }+ if let Some(response) = responses.get_mut("503") {+ merge_headers(response, &retryable_error_headers);+ }+ }+}++/// Add documented auth responses for bearer-protected operations (spec completeness).+fn inject_bearer_auth_error_responses(paths: &mut serde_json::Map<String, Value>) {+ let unauthorized = json!({+ "description": "Missing or invalid bearer token (inference token)",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/StandardApiError" }+ }+ }+ });+ let forbidden = json!({+ "description": "Valid bearer token but admin token required for this mutation (or admin token not configured)",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/StandardApiError" }+ }+ }+ });+ let auth_misconfigured = json!({+ "description": "Gateway auth enabled but no tokens configured",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/StandardApiError" }+ }+ }+ });++ for (path, path_item) in paths.iter_mut() {+ let Some(path_item) = path_item.as_object_mut() else {+ continue;+ };+ for (method, op) in path_item.iter_mut() {+ if !matches!(method.as_str(), "get" | "post" | "put" | "delete" | "patch") {+ continue;+ }+ let Some(op_ob) = op.as_object_mut() else {+ continue;+ };+ let secured = op_ob+ .get("security")+ .and_then(|s| s.as_array())+ .map(|a| !a.is_empty())+ .unwrap_or(true);+ if !secured {+ continue;+ }+ let Some(responses) = op_ob.get_mut("responses").and_then(|r| r.as_object_mut()) else {+ continue;+ };+ responses+ .entry("401".to_string())+ .or_insert(unauthorized.clone());+ merge_auth_misconfigured_response(responses, &auth_misconfigured);++ if admin_mutation(method.as_str(), path) {+ responses+ .entry("403".to_string())+ .or_insert(forbidden.clone());+ }+ }+ }+}++fn standard_api_error_schema() -> Value {+ json!({ "$ref": "#/components/schemas/StandardApiError" })+}++fn schema_allows_standard_api_error(schema: &Value) -> bool {+ if schema == &standard_api_error_schema() {+ return true;+ }+ schema+ .get("oneOf")+ .and_then(|one_of| one_of.as_array())+ .map(|schemas| schemas.iter().any(schema_allows_standard_api_error))+ .unwrap_or(false)+}++fn merge_auth_misconfigured_response(+ responses: &mut serde_json::Map<String, Value>,+ auth_misconfigured: &Value,+) {+ let Some(existing) = responses.get_mut("500") else {+ responses.insert("500".to_string(), auth_misconfigured.clone());+ return;+ };++ let Some(existing) = existing.as_object_mut() else {+ return;+ };+ let description = existing+ .entry("description")+ .or_insert_with(|| json!("Internal server error"));+ if let Some(description_text) = description.as_str() {+ if !description_text.contains("auth enabled but no tokens configured") {+ *description = json!(format!(+ "{description_text}; gateway auth enabled but no tokens configured"+ ));+ }+ }++ let content = existing+ .entry("content")+ .or_insert_with(|| json!({}))+ .as_object_mut()+ .expect("OpenAPI response content should be an object");+ let json_content = content+ .entry("application/json")+ .or_insert_with(|| json!({}))+ .as_object_mut()+ .expect("OpenAPI application/json response should be an object");+ let schema = json_content.entry("schema").or_insert_with(|| json!(null));+ if schema.is_null() {+ *schema = standard_api_error_schema();+ } else if !schema_allows_standard_api_error(schema) {+ let old_schema = schema.clone();+ *schema = json!({+ "oneOf": [+ old_schema,+ standard_api_error_schema()+ ]+ });+ }+}++fn admin_mutation(method: &str, path: &str) -> bool {+ if !matches!(method, "post" | "put" | "delete") {+ return false;+ }+ path.starts_with("/v1/config") || path.starts_with("/v1/admin") || path.starts_with("/v1/pools")+}++fn annotate_slash_bearing_path_parameters(paths: &mut serde_json::Map<String, Value>) {+ for (path, param_name, runtime_path) in [+ ("/v1/models/{model}", "model", "/v1/models/{*model}"),+ ("/v1/encode/{model}", "model", "/v1/encode/{*model}"),+ ("/v1/score/{model}", "model", "/v1/score/{*model}"),+ ("/v1/extract/{model}", "model", "/v1/extract/{*model}"),+ ("/v1/configs/models/{id}", "id", "/v1/configs/models/{*id}"),+ (+ "/v1/configs/models/{id}/status",+ "id",+ "/v1/configs/models/{*id}",+ ),+ ] {+ let Some(path_item) = paths.get_mut(path).and_then(|item| item.as_object_mut()) else {+ continue;+ };+ for operation in path_item.values_mut() {+ let Some(operation) = operation.as_object_mut() else {+ continue;+ };+ operation.insert("x-sie-axum-catch-all".to_string(), json!(runtime_path));+ let Some(parameters) = operation+ .get_mut("parameters")+ .and_then(|parameters| parameters.as_array_mut())+ else {+ continue;+ };+ for parameter in parameters {+ if parameter.get("name").and_then(|name| name.as_str()) != Some(param_name) {+ continue;+ }+ parameter["description"] = json!(format!(+ "Model id. Runtime route is Axum catch-all `{runtime_path}`; clients using this OpenAPI path template should percent-encode slashes in model ids, for example `BAAI%2Fbge-m3`."+ ));+ }+ }+ }+}++pub fn write_openapi_json(path: Option<&Path>) -> Result<(), Box<dyn std::error::Error>> {+ match path {+ Some(path) => std::fs::write(path, OPENAPI_JSON.as_bytes())?,+ None => print!("{}", OPENAPI_JSON.as_str()),+ }+ Ok(())+}++#[utoipa::path(+ get,+ path = "/v1/configs/models/{id}/status",+ operation_id = "get_model_config_status",+ tag = "config",+ params(("id" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients")),+ responses(+ (status = 200, description = "Per-replica worker acknowledgement status", body = ModelConfigStatusResponse),+ (status = 404, description = "Model not found", body = StandardApiError)+ )+)]+#[allow(dead_code)]+pub fn get_model_config_status_doc() {}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ErrorDetailCore {+ pub code: String,+ pub message: String,+}++/// FastAPI-style error envelope for most gateway JSON errors.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct StandardApiError {+ pub detail: ErrorDetailCore,+}++/// ``detail`` when the caller's ``X-SIE-MACHINE-PROFILE`` GPU is not in the gateway allow-list.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct GpuNotConfiguredDetail {+ pub code: String,+ pub message: String,+ pub gpu: String,+ pub configured_gpu_types: Vec<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct GpuNotConfiguredError {+ pub detail: GpuNotConfiguredDetail,+}++/// SDK-style ``502`` body for ``MODEL_LOAD_FAILED`` (SDK short-circuit).+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct GatewayModelLoadFailedDetail {+ pub code: String,+ pub message: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub error_class: Option<String>,+ pub attempts: i32,+ pub permanent: bool,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct GatewayModelLoadFailedResponse {+ pub error: GatewayModelLoadFailedDetail,+}++/// OpenAI-compatible ``POST /v1/embeddings`` request (subset supported on gateway).+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct OpenAIEmbeddingRequest {+ pub model: String,+ pub input: OpenAIEmbeddingInput,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub encoding_format: Option<OpenAIEmbeddingEncodingFormat>,+ /// Accepted but ignored; the gateway returns the model's native dimension.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub dimensions: Option<u32>,+ /// Accepted but ignored; kept for OpenAI SDK compatibility.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub user: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(untagged)]+pub enum OpenAIEmbeddingInput {+ String(String),+ Strings(Vec<String>),+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "lowercase")]+pub enum OpenAIEmbeddingEncodingFormat {+ Float,+ Base64,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(untagged)]+pub enum OpenAIEmbeddingVector {+ Float(Vec<f64>),+ Base64(String),+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct OpenAIEmbeddingDataEntry {+ pub object: String,+ pub embedding: OpenAIEmbeddingVector,+ pub index: usize,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct OpenAIEmbeddingUsage {+ pub prompt_tokens: u64,+ pub total_tokens: u64,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct OpenAIEmbeddingsListResponse {+ pub object: String,+ pub data: Vec<OpenAIEmbeddingDataEntry>,+ pub model: String,+ pub usage: OpenAIEmbeddingUsage,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct GatewayErrorResponse {+ #[serde(default)]+ pub message: Option<String>,+ #[serde(default)]+ pub error: Option<Value>,+ #[serde(default)]+ pub details: Option<Vec<InferenceErrorDetail>>,+ #[serde(default)]+ pub status: Option<String>,+ #[serde(default)]+ pub gpu: Option<String>,+ #[serde(default)]+ pub configured_gpu_types: Option<Vec<String>>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(untagged)]+pub enum InferenceInternalServerErrorResponse {+ AllItemsFailed(AllItemsFailedResponse),+ Standard(StandardApiError),+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(untagged)]+pub enum InferenceServiceUnavailableResponse {+ Gateway(GatewayErrorResponse),+ Standard(StandardApiError),+ GpuNotConfigured(GpuNotConfiguredError),+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct BundleRoutingConflictDetail {+ pub code: String,+ pub message: String,+ pub compatible_bundles: Vec<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct BundleConflictResponse {+ pub detail: BundleRoutingConflictDetail,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ResolveModelNotFoundDetail {+ pub code: String,+ pub message: String,+ pub model: String,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ResolveModelNotFoundResponse {+ pub detail: ResolveModelNotFoundDetail,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ResolveBundleConflictDetail {+ pub code: String,+ pub message: String,+ pub model: String,+ pub bundle: String,+ pub compatible_bundles: Vec<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ResolveBundleConflictResponse {+ pub detail: ResolveBundleConflictDetail,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct AllItemsFailedResponse {+ pub error: String,+ pub details: Vec<InferenceErrorDetail>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct MessageResponse {+ pub message: String,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct HealthResponse {+ pub status: String,+ #[serde(rename = "type")]+ #[schema(rename = "type")]+ pub service_type: String,+ pub configured_gpu_types: Vec<String>,+ pub live_gpu_types: Vec<String>,+ pub cluster: ClusterSummary,+ pub workers: Vec<crate::types::worker::WorkerInfo>,+ pub models: Vec<crate::types::worker::ModelInfo>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ClusterSummary {+ pub worker_count: i32,+ pub gpu_count: i32,+ pub models_loaded: i32,+ pub total_qps: f64,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ProfileInfoWire {+ #[serde(default)]+ pub is_default: bool,+}++/// Wire shape aligned with ``sie_server`` ``ModelInfo`` for ``GET /v1/models``.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ModelInfoWire {+ pub name: String,+ pub inputs: Vec<String>,+ pub outputs: Vec<String>,+ pub dims: std::collections::HashMap<String, i64>,+ pub loaded: bool,+ pub state: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub last_error: Option<serde_json::Value>,+ pub max_sequence_length: Option<u64>,+ pub profiles: std::collections::HashMap<String, ProfileInfoWire>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ModelsResponse {+ pub models: Vec<ModelInfoWire>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ModelNotFoundResponse {+ pub detail: ModelNotFoundDetail,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ModelNotFoundDetail {+ pub code: String,+ pub message: String,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct PoolListResponse {+ pub pools: Vec<crate::types::pool::Pool>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ConfigModelsResponse {+ pub models: Vec<ConfigModelSummary>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ConfigModelSummary {+ pub model_id: String,+ pub profiles: Vec<String>,+ pub source: String,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ConfigModelDocument {+ pub sie_id: String,+ pub source: String,+ pub bundles: Vec<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ModelConfigStatusResponse {+ pub model_id: String,+ pub config_epoch: u64,+ pub all_bundles_acked: bool,+ pub no_bundles: bool,+ pub bundles: Vec<ModelAckBundleStatus>,+ pub source: String,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ModelAckBundleStatus {+ pub bundle_id: String,+ pub expected_bundle_config_hash: String,+ pub total_eligible_workers: usize,+ pub acked_workers: Vec<String>,+ pub pending_workers: Vec<String>,+ pub acked: bool,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct BundleConfigsResponse {+ pub bundles: Vec<BundleConfigSummary>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct BundleConfigSummary {+ pub bundle_id: String,+ pub priority: i32,+ pub adapter_count: usize,+ pub source: String,+ pub connected_workers: usize,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct BundleConfigDocument {+ pub name: String,+ pub priority: i32,+ pub source: String,+ pub adapters: Vec<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ResolveConfigResponse {+ pub model: String,+ pub resolved_bundle: String,+ pub compatible_bundles: Vec<String>,+ pub profiles: Vec<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ImageInput {+ pub data: Vec<u8>,+ #[serde(default)]+ pub format: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct DocumentInput {+ pub data: Vec<u8>,+ #[serde(default)]+ pub format: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ItemInput {+ #[serde(default)]+ pub id: Option<String>,+ #[serde(default)]+ pub text: Option<String>,+ #[serde(default)]+ pub images: Option<Vec<ImageInput>>,+ #[serde(default)]+ pub document: Option<DocumentInput>,+ #[serde(default)]+ pub metadata: Option<Value>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct EncodeParams {+ #[serde(default)]+ pub output_types: Option<Vec<OutputType>>,+ #[serde(default)]+ pub instruction: Option<String>,+ #[serde(default)]+ pub output_dtype: Option<OutputDtype>,+ #[serde(default)]+ pub options: Option<Value>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "lowercase")]+pub enum OutputType {+ Dense,+ Sparse,+ Multivector,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "lowercase")]+pub enum OutputDtype {+ Float32,+ Float16,+ Int8,+ Uint8,+ Binary,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct EncodeRequest {+ #[schema(min_items = 1)]+ pub items: Vec<ItemInput>,+ #[serde(default)]+ pub params: Option<EncodeParams>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ExtractParams {+ #[serde(default)]+ pub labels: Option<Vec<String>>,+ #[serde(default)]+ pub output_schema: Option<Value>,+ #[serde(default)]+ pub instruction: Option<String>,+ #[serde(default)]+ pub options: Option<Value>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ExtractRequest {+ #[schema(min_items = 1)]+ pub items: Vec<ItemInput>,+ #[serde(default)]+ pub params: Option<ExtractParams>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ScoreRequest {+ pub query: ItemInput,+ #[schema(min_items = 1)]+ pub items: Vec<ItemInput>,+ #[serde(default)]+ pub instruction: Option<String>,+ #[serde(default)]+ pub options: Option<Value>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct DenseVector {+ pub dims: usize,+ pub dtype: OutputDtype,+ pub values: Vec<f32>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct SparseVector {+ #[serde(default)]+ pub dims: Option<usize>,+ pub dtype: OutputDtype,+ pub indices: Vec<usize>,+ pub values: Vec<f32>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct MultiVector {+ pub token_dims: usize,+ pub num_tokens: usize,+ pub dtype: OutputDtype,+ pub values: Vec<Vec<f32>>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct EncodeResult {+ #[serde(default)]+ pub id: Option<String>,+ #[serde(default)]+ pub dense: Option<DenseVector>,+ #[serde(default)]+ pub sparse: Option<SparseVector>,+ #[serde(default)]+ pub multivector: Option<MultiVector>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct TimingInfo {+ pub total_ms: f64,+ pub queue_ms: f64,+ pub tokenization_ms: f64,+ pub inference_ms: f64,+ #[serde(default)]+ pub postprocessing_ms: Option<f64>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct EncodeResponse {+ pub model: String,+ pub items: Vec<EncodeResult>,+ #[serde(default)]+ pub timing: Option<TimingInfo>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct Entity {+ pub text: String,+ pub label: String,+ pub score: f64,+ #[serde(default)]+ pub start: Option<usize>,+ #[serde(default)]+ pub end: Option<usize>,+ #[serde(default)]+ pub bbox: Option<Vec<f64>>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct Relation {+ pub head: String,+ pub tail: String,+ pub relation: String,+ pub score: f64,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ExtractResult {+ pub id: String,+ #[serde(default)]+ pub entities: Vec<Entity>,+ #[serde(default)]+ pub relations: Vec<Relation>,+ #[serde(default)]+ pub classifications: Vec<Value>,+ #[serde(default)]+ pub data: Value,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ExtractResponse {+ pub model: String,+ pub items: Vec<ExtractResult>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ScoreEntry {+ pub item_id: String,+ pub score: f64,+ pub rank: usize,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ScoreResponse {+ pub model: String,+ #[serde(default)]+ pub query_id: Option<String>,+ pub scores: Vec<ScoreEntry>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct InferenceErrorDetail {+ pub item_index: u32,+ pub error: Option<String>,+ #[serde(default)]+ pub code: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ProvisioningResponse {+ pub status: String,+ #[serde(default)]+ pub gpu: String,+ #[serde(default)]+ pub bundle: String,+ pub estimated_wait_s: u64,+ #[serde(default)]+ pub message: String,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn openapi_document_has_gateway_metadata() {+ let doc = ApiDoc::openapi();+ assert_eq!(doc.info.title, "SIE Gateway");+ }++ #[tokio::test]+ async fn openapi_handler_sets_gateway_version() {+ let doc: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ assert_eq!(doc["info"]["version"], env!("CARGO_PKG_VERSION"));+ assert_eq!(doc["info"]["license"]["name"], "Apache-2.0");+ }++ #[test]+ fn openapi_json_documents_auth_and_exempt_routes() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ assert_eq!(spec["security"], json!([{ "bearerAuth": [] }]));+ assert_eq!(spec["paths"]["/healthz"]["get"]["security"], json!([]));+ assert_eq!(spec["paths"]["/readyz"]["get"]["security"], json!([]));+ assert!(spec["paths"]["/readyz"]["get"]["description"]+ .as_str()+ .unwrap()+ .contains("never returns 503"));+ assert_eq!(spec["paths"]["/openapi.json"]["get"]["security"], json!([]));+ assert_eq!(+ spec["components"]["securitySchemes"]["bearerAuth"]["scheme"],+ "bearer"+ );+ }++ #[test]+ fn openapi_json_documents_its_response_content() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ assert_eq!(+ spec["paths"]["/openapi.json"]["get"]["responses"]["200"]["content"]+ ["application/json"]["schema"]["type"],+ "object"+ );+ }++ #[test]+ fn openapi_json_documents_create_pool_runtime_validation() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ let create_pool = &spec["components"]["schemas"]["CreatePoolRequest"];+ assert_eq!(create_pool["required"], json!(["name", "gpus"]));+ assert_eq!(create_pool["properties"]["gpus"]["minProperties"], 1);+ }++ #[test]+ fn openapi_document_includes_gateway_paths() {+ let doc = ApiDoc::openapi();+ let paths = doc.paths.paths;+ for path in [+ "/",+ "/openapi.json",+ "/healthz",+ "/v1/models",+ "/v1/pools",+ "/v1/configs/models",+ "/v1/configs/models/{id}/status",+ "/v1/embeddings",+ "/v1/encode/{model}",+ "/v1/score/{model}",+ "/v1/extract/{model}",+ ] {+ assert!(paths.contains_key(path), "{path} missing from OpenAPI doc");+ }+ }++ #[test]+ fn openapi_document_covers_all_gateway_route_methods() {+ let spec = serde_json::to_value(openapi_document()).unwrap();+ let paths = spec["paths"].as_object().unwrap();+ let expected = [+ ("/", &["get"][..]),+ ("/healthz", &["get"][..]),+ ("/readyz", &["get"][..]),+ ("/health", &["get"][..]),+ ("/metrics", &["get"][..]),+ ("/openapi.json", &["get"][..]),+ ("/v1/models", &["get"][..]),+ ("/v1/models/{model}", &["get"][..]),+ ("/v1/pools", &["get", "post"][..]),+ ("/v1/pools/{name}", &["delete", "get"][..]),+ ("/v1/pools/{name}/renew", &["post"][..]),+ ("/v1/configs/models", &["get"][..]),+ ("/v1/configs/models/{id}", &["get"][..]),+ ("/v1/configs/models/{id}/status", &["get"][..]),+ ("/v1/configs/bundles", &["get"][..]),+ ("/v1/configs/bundles/{id}", &["get"][..]),+ ("/v1/configs/resolve", &["post"][..]),+ ("/v1/embeddings", &["post"][..]),+ ("/ws/cluster-status", &["get"][..]),+ ("/v1/encode/{model}", &["post"][..]),+ ("/v1/score/{model}", &["post"][..]),+ ("/v1/extract/{model}", &["post"][..]),+ ];++ let actual_paths: std::collections::BTreeSet<_> =+ paths.keys().map(String::as_str).collect();+ let expected_paths: std::collections::BTreeSet<_> =+ expected.iter().map(|(path, _)| *path).collect();+ assert_eq!(actual_paths, expected_paths);++ for (path, methods) in expected {+ let path_item = paths[path].as_object().unwrap();+ let actual_methods: std::collections::BTreeSet<_> =+ path_item.keys().map(String::as_str).collect();+ let expected_methods: std::collections::BTreeSet<_> = methods.iter().copied().collect();+ assert_eq!(actual_methods, expected_methods, "{path} methods differ");+ }+ }++ #[test]+ fn openapi_document_does_not_advertise_internal_engine_header() {+ let spec = serde_json::to_value(openapi_document()).unwrap();+ for path_item in spec["paths"].as_object().unwrap().values() {+ for operation in path_item.as_object().unwrap().values() {+ let Some(parameters) = operation.get("parameters").and_then(|p| p.as_array())+ else {+ continue;+ };+ for parameter in parameters {+ let name = parameter["name"].as_str().unwrap_or_default();+ assert_ne!(name.to_ascii_lowercase(), "x-sie-engine");+ }+ }+ }+ }++ #[test]+ fn openapi_document_covers_inference_error_statuses() {+ let spec = serde_json::to_value(openapi_document()).unwrap();+ for path in [+ "/v1/encode/{model}",+ "/v1/score/{model}",+ "/v1/extract/{model}",+ ] {+ let responses = spec["paths"][path]["post"]["responses"]+ .as_object()+ .unwrap();+ for status in [+ "200", "202", "400", "404", "409", "413", "500", "502", "503", "504",+ ] {+ assert!(responses.contains_key(status), "{path} missing {status}");+ }+ }++ let emb = &spec["paths"]["/v1/embeddings"]["post"]["responses"]+ .as_object()+ .unwrap();+ for status in [+ "200", "202", "400", "401", "404", "409", "413", "500", "502", "503", "504",+ ] {+ assert!(emb.contains_key(status), "/v1/embeddings missing {status}");+ }+ }++ #[test]+ fn openapi_document_documents_inference_error_unions() {+ let spec = serde_json::to_value(openapi_document()).unwrap();+ let internal_error =+ &spec["components"]["schemas"]["InferenceInternalServerErrorResponse"]["oneOf"];+ assert_eq!(+ internal_error,+ &json!([+ {"$ref": "#/components/schemas/AllItemsFailedResponse"},+ {"$ref": "#/components/schemas/StandardApiError"},+ ])+ );++ let service_unavailable =+ &spec["components"]["schemas"]["InferenceServiceUnavailableResponse"]["oneOf"];+ assert_eq!(+ service_unavailable,+ &json!([+ {"$ref": "#/components/schemas/GatewayErrorResponse"},+ {"$ref": "#/components/schemas/StandardApiError"},+ {"$ref": "#/components/schemas/GpuNotConfiguredError"},+ ])+ );++ for path in [+ "/v1/encode/{model}",+ "/v1/score/{model}",+ "/v1/extract/{model}",+ "/v1/embeddings",+ ] {+ assert_eq!(+ spec["paths"][path]["post"]["responses"]["500"]["content"]["application/json"]+ ["schema"]["$ref"],+ "#/components/schemas/InferenceInternalServerErrorResponse"+ );+ assert_eq!(+ spec["paths"][path]["post"]["responses"]["503"]["content"]["application/json"]+ ["schema"]["$ref"],+ "#/components/schemas/InferenceServiceUnavailableResponse"+ );+ }+ }++ #[test]+ fn openapi_export_adds_msgpack_content_and_unauthorized_responses() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ for path in [+ "/v1/encode/{model}",+ "/v1/score/{model}",+ "/v1/extract/{model}",+ ] {+ let post = &spec["paths"][path]["post"];+ let content = &post["responses"]["200"]["content"];+ assert!(+ content.get("application/json").is_some(),+ "{path} missing application/json 200"+ );+ assert!(+ content.get("application/x-msgpack").is_some(),+ "{path} missing application/x-msgpack 200"+ );+ assert!(+ content.get("application/msgpack").is_some(),+ "{path} missing application/msgpack 200"+ );+ assert!(+ content.get("application/vnd.msgpack").is_some(),+ "{path} missing application/vnd.msgpack 200"+ );+ let req_content = &post["requestBody"]["content"];+ assert!(req_content.get("application/x-msgpack").is_some());+ assert!(req_content.get("application/msgpack").is_some());+ assert!(req_content.get("application/vnd.msgpack").is_some());++ let responses = post["responses"].as_object().unwrap();+ assert!(responses.contains_key("401"), "{path} missing injected 401");+ assert!(+ responses.contains_key("500"),+ "{path} missing auth-misconfigured 500"+ );+ assert!(+ responses["200"]["headers"]+ .get("X-SIE-Request-Id")+ .is_some(),+ "{path} missing documented request id header"+ );+ assert!(+ responses["200"]["headers"].get("X-Queue-Time").is_some(),+ "{path} missing documented queue timing header"+ );+ }++ let pool_post = &spec["paths"]["/v1/pools"]["post"]["responses"];+ assert!(pool_post.as_object().unwrap().contains_key("401"));+ assert!(pool_post.as_object().unwrap().contains_key("403"));+ assert!(pool_post.as_object().unwrap().contains_key("500"));++ let config_resolve = &spec["paths"]["/v1/configs/resolve"]["post"]["responses"];+ assert!(config_resolve.as_object().unwrap().contains_key("401"));+ assert!(config_resolve.as_object().unwrap().contains_key("403"));+ assert!(config_resolve.as_object().unwrap().contains_key("500"));++ let embeddings_202_headers =+ &spec["paths"]["/v1/embeddings"]["post"]["responses"]["202"]["headers"];+ assert!(embeddings_202_headers.get("Retry-After").is_some());+ assert!(embeddings_202_headers.get("X-SIE-Version").is_some());+ assert!(embeddings_202_headers.get("X-SIE-Server-Version").is_some());++ let embeddings_200_headers =+ &spec["paths"]["/v1/embeddings"]["post"]["responses"]["200"]["headers"];+ for name in [+ "X-SIE-Request-Id",+ "X-SIE-Worker",+ "X-Queue-Publish-Time",+ "X-Queue-Wait-Time",+ "X-Queue-Time",+ "X-Inference-Time",+ "X-Tokenization-Time",+ "X-Postprocessing-Time",+ "X-Payload-Fetch-Time",+ ] {+ assert!(+ embeddings_200_headers.get(name).is_some(),+ "/v1/embeddings 200 missing documented {name} header"+ );+ }+ }++ #[test]+ fn openapi_export_documents_server_parity_cleanup() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();++ for schema in ["EncodeResponse", "ExtractResponse", "ScoreResponse"] {+ assert!(+ spec["components"]["schemas"][schema]["properties"]+ .get("errors")+ .is_none(),+ "{schema} must not document gateway-only partial error envelope"+ );+ }++ let model_param = &spec["paths"]["/v1/encode/{model}"]["post"]["parameters"][0];+ assert!(model_param.get("allowReserved").is_none());+ assert!(model_param["description"]+ .as_str()+ .unwrap()+ .contains("percent-encode slashes"));+ assert_eq!(+ spec["paths"]["/v1/encode/{model}"]["post"]["x-sie-axum-catch-all"],+ "/v1/encode/{*model}"+ );++ let model_load_failed = &spec["components"]["schemas"]["GatewayModelLoadFailedResponse"];+ assert!(model_load_failed["properties"].get("error").is_some());+ assert!(model_load_failed["properties"].get("detail").is_none());++ let embeddings_request = &spec["components"]["schemas"]["OpenAIEmbeddingRequest"];+ assert_eq!(+ embeddings_request["properties"]["input"]["$ref"],+ "#/components/schemas/OpenAIEmbeddingInput"+ );+ assert!(embeddings_request["properties"]["encoding_format"]["oneOf"]+ .as_array()+ .unwrap()+ .iter()+ .any(|schema| schema["$ref"] == "#/components/schemas/OpenAIEmbeddingEncodingFormat"));+ assert_eq!(+ embeddings_request["properties"]["dimensions"]["type"],+ json!(["integer", "null"])+ );+ assert_eq!(+ embeddings_request["properties"]["user"]["type"],+ json!(["string", "null"])+ );+ assert_eq!(+ spec["components"]["schemas"]["OpenAIEmbeddingEncodingFormat"]["enum"],+ json!(["float", "base64"])+ );++ for path in [+ "/v1/encode/{model}",+ "/v1/score/{model}",+ "/v1/extract/{model}",+ ] {+ assert!(spec["paths"][path]["post"]["description"]+ .as_str()+ .unwrap()+ .contains("Mixed-success batches return 200"));+ }+ assert!(spec["paths"]["/v1/embeddings"]["post"]["description"]+ .as_str()+ .unwrap()+ .contains("partial or truncated internal encode success"));++ let headers = &spec["paths"]["/v1/embeddings"]["post"]["responses"]["502"]["headers"];+ assert!(headers.get("X-SIE-Error-Code").is_some());+ assert!(headers.get("X-SIE-Error-Version").is_some());+ }+}diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex 6019d97df..189ee1e7e 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -8,6 +8,7 @@ use crate::metrics;use crate::middleware::audit::AuditLayer;use crate::middleware::auth::AuthLayer;use crate::middleware::metrics::MetricsLayer;+use crate::openapi;use crate::queue::publisher::WorkPublisher;use crate::state::config_epoch::ConfigEpoch;use crate::state::demand_tracker::DemandTracker;@@ -24,7 +25,7 @@ pub struct AppState {pub demand_tracker: Arc<DemandTracker>,/// Monotonic view of the furthest-known control-plane epoch. Written by/// bootstrap, the NATS delta handler, and the epoch poller; read by- /// `/v1/configs/models/{id}/status` and `/health`.+ /// `GET /v1/configs/models/{id}/status` and metrics (`sie_gateway_config_epoch`).pub config_epoch: ConfigEpoch,}@@ -38,6 +39,8 @@ pub fn create_router(state: Arc<AppState>, config: Arc<Config>) -> Router {.route("/health", get(health::health))// Metrics endpoint.route("/metrics", get(metrics_handler))+ // API description+ .route("/openapi.json", get(openapi::openapi_json))// Models endpoints. `{*model}` accepts slash-bearing IDs..route("/v1/models", get(models::get_models)).route("/v1/models/{*model}", get(models::get_model))@@ -70,6 +73,7 @@ pub fn create_router(state: Arc<AppState>, config: Arc<Config>) -> Router {.route("/v1/configs/resolve", post(config_api::resolve_config))// WebSocket cluster status.route("/ws/cluster-status", get(health::ws_cluster_status))+ .route("/v1/embeddings", post(proxy::proxy_openai_embeddings))// Proxy endpoints - use wildcard for model path.route("/v1/encode/{*model}", post(proxy::proxy_encode)).route("/v1/score/{*model}", post(proxy::proxy_score))@@ -86,7 +90,13 @@ pub fn create_router(state: Arc<AppState>, config: Arc<Config>) -> Router {.with_state(state)}-async fn metrics_handler(+#[utoipa::path(+ get,+ path = "/metrics",+ tag = "observability",+ responses((status = 200, description = "Prometheus metrics", body = String, content_type = "text/plain"))+)]+pub(crate) async fn metrics_handler(axum::extract::State(state): axum::extract::State<Arc<AppState>>,) -> impl axum::response::IntoResponse {// Update worker gauges before servingdiff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex ccbe04c74..ce7a65066 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -28,9 +28,14 @@//! backoff (capped) until it succeeds. Every successful fetch is applied//! into the shared `ModelRegistry` and stored as the current `ConfigEpoch`.//! - While bootstrap has not yet succeeded, API-added models from-//! `sie-config` are missing. `/readyz` still reports ready (soft-degraded,-//! not an outage), and `/health` exposes `config_epoch` so operators can-//! see catch-up progress.+//! `sie-config` are missing. `GET /readyz` is process readiness only: once+//! the gateway listener is serving it returns **200** + plain text `ok`, even+//! with zero workers, so the first inference request can reach the gateway and+//! trigger scale-from-zero via `202 + Retry-After`. Bootstrap catch-up is+//! visible separately via `GET /v1/configs/models/{id}/status` (`config_epoch`+//! on that payload), the `sie_gateway_config_epoch` /+//! `sie_gateway_config_bootstrap_degraded` metrics, and gateway logs — not+//! via `/readyz` flipping on export completion.//! - `state::config_poller` runs in parallel, periodically reconciling//! against `GET /v1/configs/epoch` so any missed NATS deltas after the//! initial bootstrap are caught within one poll interval.diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 9f35cfe3b..5b59ca7f3 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -7,7 +7,7 @@ use sha2::{Digest, Sha256};use tracing::{debug, error, info, warn};use crate::types::bundle::BundleInfo;-use crate::types::model::{CanonicalProfile, ModelConfig, ModelEntry};+use crate::types::model::{CanonicalProfile, ModelConfig, ModelEntry, ModelInfoExtras};#[derive(Debug)]pub struct ModelNotFoundError {@@ -297,6 +297,7 @@ impl ModelRegistry {let content = std::fs::read_to_string(path)?;let config: ModelConfig = serde_yaml::from_str(&content)?;+ let info_extras = crate::types::model::ModelInfoExtras::from_model_config(&config);let model_name = config.name;let mut adapter_modules: HashSet<String> = HashSet::new();let mut profile_names: HashSet<String> = HashSet::new();@@ -322,6 +323,7 @@ impl ModelRegistry {adapter_modules,profile_names,profile_configs,+ info_extras,})}@@ -684,6 +686,7 @@ impl ModelRegistry {.insert(pname.clone(), CanonicalProfile::from_profile(profile));}}+ Self::merge_model_info_extras(&mut existing.info_extras, &config);} else {// New modellet mut profile_names: HashSet<String> = HashSet::new();@@ -696,6 +699,7 @@ impl ModelRegistry {created_profiles = config.profiles.keys().cloned().collect();+ let info_extras = ModelInfoExtras::from_model_config(&config);snap.models.insert(sie_id.clone(),ModelEntry {@@ -704,6 +708,7 @@ impl ModelRegistry {adapter_modules: new_adapter_modules,profile_names,profile_configs,+ info_extras,},);snap.model_names_lower@@ -761,6 +766,25 @@ impl ModelRegistry {Ok((created_profiles, skipped_profiles, affected_bundles))}++ fn merge_model_info_extras(existing: &mut ModelInfoExtras, config: &ModelConfig) {+ if config.inputs.is_none() && config.tasks.is_none() && config.max_sequence_length.is_none()+ {+ return;+ }++ let refreshed = ModelInfoExtras::from_model_config(config);+ if config.inputs.is_some() {+ existing.inputs = refreshed.inputs;+ }+ if config.tasks.is_some() {+ existing.outputs = refreshed.outputs;+ existing.dims = refreshed.dims;+ }+ if config.max_sequence_length.is_some() {+ existing.max_sequence_length = refreshed.max_sequence_length;+ }+ }}#[cfg(test)]@@ -821,6 +845,9 @@ mod tests {adapter_module: None,default_bundle: None,profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: None,}).unwrap();assert!(registry.has_any_models(), "must report populated after add");@@ -871,6 +898,9 @@ mod tests {adapter_module: None,default_bundle: None,profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: None,};registry.add_model_config(cfg).expect("add must succeed");}@@ -1072,6 +1102,9 @@ adapters:);m},+ inputs: None,+ max_sequence_length: None,+ tasks: None,};let (created, skipped, bundles) = registry.add_model_config(config).unwrap();@@ -1084,6 +1117,198 @@ adapters:assert_eq!(resolved, "default");}+ #[test]+ fn test_add_model_config_refreshes_existing_model_info_extras() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();++ fs::write(+ bundles_dir.join("default.yaml"),+ r#"+name: default+priority: 10+adapters:+ - module+"#,+ )+ .unwrap();++ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let mut profiles = HashMap::new();+ profiles.insert(+ "default".to_string(),+ crate::types::model::ProfileConfig {+ adapter_path: Some("module:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ registry+ .add_model_config(ModelConfig {+ name: "test/model".to_string(),+ adapter_module: None,+ default_bundle: None,+ profiles,+ inputs: None,+ max_sequence_length: Some(512),+ tasks: Some(+ serde_yaml::from_str(+ r#"+encode:+ dense:+ dim: 384+"#,+ )+ .unwrap(),+ ),+ })+ .unwrap();++ let first = registry.get_model_info("test/model").unwrap();+ assert_eq!(first.info_extras.outputs, vec!["dense"]);+ assert_eq!(first.info_extras.dims["dense"], 384);+ assert_eq!(first.info_extras.max_sequence_length, Some(512));++ let mut profiles = HashMap::new();+ profiles.insert(+ "default".to_string(),+ crate::types::model::ProfileConfig {+ adapter_path: Some("module:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ profiles.insert(+ "alt".to_string(),+ crate::types::model::ProfileConfig {+ adapter_path: Some("module:Adapter".to_string()),+ max_batch_tokens: Some(2048),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );++ registry+ .add_model_config(ModelConfig {+ name: "test/model".to_string(),+ adapter_module: None,+ default_bundle: None,+ profiles,+ inputs: None,+ max_sequence_length: Some(1024),+ tasks: Some(+ serde_yaml::from_str(+ r#"+encode:+ sparse:+ dim: 30000+"#,+ )+ .unwrap(),+ ),+ })+ .unwrap();++ let refreshed = registry.get_model_info("test/model").unwrap();+ assert!(refreshed.profile_names.contains("alt"));+ assert_eq!(refreshed.info_extras.outputs, vec!["sparse"]);+ assert_eq!(refreshed.info_extras.dims["sparse"], 30000);+ assert_eq!(refreshed.info_extras.max_sequence_length, Some(1024));+ }++ #[test]+ fn test_add_model_config_preserves_info_extras_for_profile_only_update() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();++ fs::write(+ bundles_dir.join("default.yaml"),+ r#"+name: default+priority: 10+adapters:+ - module+"#,+ )+ .unwrap();++ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let mut profiles = HashMap::new();+ profiles.insert(+ "default".to_string(),+ crate::types::model::ProfileConfig {+ adapter_path: Some("module:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ registry+ .add_model_config(ModelConfig {+ name: "test/model".to_string(),+ adapter_module: None,+ default_bundle: None,+ profiles,+ inputs: None,+ max_sequence_length: Some(512),+ tasks: Some(+ serde_yaml::from_str(+ r#"+encode:+ dense:+ dim: 384+"#,+ )+ .unwrap(),+ ),+ })+ .unwrap();++ let mut profiles = HashMap::new();+ profiles.insert(+ "default".to_string(),+ crate::types::model::ProfileConfig {+ adapter_path: Some("module:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ profiles.insert(+ "alt".to_string(),+ crate::types::model::ProfileConfig {+ adapter_path: Some("module:Adapter".to_string()),+ max_batch_tokens: Some(2048),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );++ registry+ .add_model_config(ModelConfig {+ name: "test/model".to_string(),+ adapter_module: None,+ default_bundle: None,+ profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: None,+ })+ .unwrap();++ let refreshed = registry.get_model_info("test/model").unwrap();+ assert!(refreshed.profile_names.contains("alt"));+ assert_eq!(refreshed.info_extras.outputs, vec!["dense"]);+ assert_eq!(refreshed.info_extras.dims["dense"], 384);+ assert_eq!(refreshed.info_extras.max_sequence_length, Some(512));+ }+#[test]fn test_compute_bundle_config_hash() {let (_dir, bundles_dir, models_dir) = create_test_dirs();@@ -1174,6 +1399,9 @@ adapters:);m},+ inputs: None,+ max_sequence_length: None,+ tasks: None,};reg.add_model_config(config).expect("add_model_config");}));diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex 0fc719950..fbb237149 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -1,6 +1,97 @@use serde::{Deserialize, Serialize};+use serde_json::{json, Map, Value};use std::collections::{HashMap, HashSet};+/// Fields mirrored from model YAML for ``/v1/models`` wire parity with+/// ``sie_server`` ``ModelInfo`` (inputs, outputs, dims, profiles, …).+#[derive(Debug, Clone, Default)]+pub struct ModelInfoExtras {+ pub inputs: Vec<String>,+ pub outputs: Vec<String>,+ pub dims: HashMap<String, i64>,+ pub max_sequence_length: Option<u64>,+}++impl ModelInfoExtras {+ /// Best-effort extraction from a raw model YAML document (same files as+ /// ``sie_server`` / ``sie-config``). Missing sections fall back to+ /// conservative defaults so the JSON shape stays valid.+ pub fn from_yaml_raw(raw: &serde_yaml::Value) -> Self {+ let mut extras = Self::default();++ if let serde_yaml::Value::Mapping(m) = raw.get("inputs").unwrap_or(&serde_yaml::Value::Null)+ {+ for (k, v) in m {+ let Some(ks) = k.as_str() else {+ continue;+ };+ if matches!(v, serde_yaml::Value::Bool(true)) {+ extras.inputs.push(ks.to_string());+ }+ }+ }+ if extras.inputs.is_empty() {+ extras.inputs.push("text".to_string());+ }++ extras.max_sequence_length = raw.get("max_sequence_length").and_then(|v| v.as_u64());++ let tasks = raw.get("tasks");+ if let Some(enc) = tasks.and_then(|t| match t.get("encode")? {+ serde_yaml::Value::Mapping(m) => Some(m),+ _ => None,+ }) {+ for (k, v) in enc {+ let Some(key) = k.as_str() else {+ continue;+ };+ if key.is_empty() {+ continue;+ }+ match v {+ serde_yaml::Value::Mapping(vm) => {+ if let Some(dim) = vm.get("dim").and_then(|d| {+ d.as_u64().or_else(|| d.as_i64().map(|i| i.max(0) as u64))+ }) {+ extras.dims.insert(key.to_string(), dim as i64);+ extras.outputs.push(key.to_string());+ } else if !vm.is_empty() {+ extras.outputs.push(key.to_string());+ }+ }+ serde_yaml::Value::Null => {}+ _ => {+ extras.outputs.push(key.to_string());+ }+ }+ }+ }++ let tasks_absent_or_empty = match tasks {+ None | Some(serde_yaml::Value::Null) => true,+ Some(serde_yaml::Value::Mapping(m)) => m.is_empty(),+ _ => false,+ };+ if extras.outputs.is_empty() && tasks_absent_or_empty {+ extras.outputs.push("dense".to_string());+ }++ extras+ }++ pub fn from_model_config(config: &ModelConfig) -> Self {+ match serde_yaml::to_value(config) {+ Ok(v) => Self::from_yaml_raw(&v),+ Err(_) => Self {+ inputs: vec!["text".to_string()],+ outputs: vec!["dense".to_string()],+ dims: HashMap::new(),+ max_sequence_length: config.max_sequence_length,+ },+ }+ }+}+#[derive(Debug, Clone, Deserialize, Serialize)]pub struct ModelConfig {#[serde(alias = "sie_id")]@@ -11,6 +102,14 @@ pub struct ModelConfig {pub default_bundle: Option<String>,#[serde(default)]pub profiles: HashMap<String, ProfileConfig>,+ /// Model YAML ``inputs:`` map (e.g. ``text: true``).+ #[serde(default)]+ pub inputs: Option<HashMap<String, bool>>,+ #[serde(default)]+ pub max_sequence_length: Option<u64>,+ /// Full ``tasks:`` tree from YAML (encode outputs / dims).+ #[serde(default)]+ pub tasks: Option<serde_yaml::Value>,}#[derive(Debug, Clone, Deserialize, Serialize)]@@ -34,6 +133,29 @@ pub struct ModelEntry {pub adapter_modules: HashSet<String>,pub profile_names: HashSet<String>,pub profile_configs: HashMap<String, CanonicalProfile>,+ pub info_extras: ModelInfoExtras,+}++impl ModelEntry {+ /// JSON shaped like ``sie_server.api.models.ModelInfo`` for HTTP clients.+ pub fn to_model_info_value(&self, loaded: bool) -> Value {+ let state = if loaded { "loaded" } else { "available" };+ let mut profiles = Map::new();+ for pname in &self.profile_names {+ profiles.insert(pname.clone(), json!({ "is_default": pname == "default" }));+ }+ json!({+ "name": self.name,+ "inputs": self.info_extras.inputs,+ "outputs": self.info_extras.outputs,+ "dims": self.info_extras.dims,+ "loaded": loaded,+ "state": state,+ "last_error": Value::Null,+ "max_sequence_length": self.info_extras.max_sequence_length,+ "profiles": Value::Object(profiles),+ })+ }}#[derive(Debug, Clone, PartialEq)]@@ -254,10 +376,48 @@ profiles: {}adapter_module: Some("mod".into()),default_bundle: None,profiles: HashMap::new(),+ inputs: None,+ max_sequence_length: None,+ tasks: None,};let json = serde_json::to_string(&config).unwrap();let back: ModelConfig = serde_json::from_str(&json).unwrap();assert_eq!(back.name, "test/model");assert_eq!(back.adapter_module, Some("mod".into()));}++ #[test]+ fn test_model_info_extras_defaults_dense_when_tasks_absent() {+ let raw: serde_yaml::Value = serde_yaml::from_str(+ r#"+name: example/model+inputs:+ text: true+"#,+ )+ .unwrap();++ let extras = ModelInfoExtras::from_yaml_raw(&raw);+ assert_eq!(extras.outputs, vec!["dense"]);+ }++ #[test]+ fn test_model_info_extras_does_not_invent_dense_for_non_encode_tasks() {+ let raw: serde_yaml::Value = serde_yaml::from_str(+ r#"+name: example/reranker+inputs:+ text: true+tasks:+ score:+ relevance:+ dim: 1+"#,+ )+ .unwrap();++ let extras = ModelInfoExtras::from_yaml_raw(&raw);+ assert!(extras.outputs.is_empty());+ assert!(extras.dims.is_empty());+ }}diff --git a/packages/sie_gateway/src/types/pool.rs b/packages/sie_gateway/src/types/pool.rsindex 94bebcffa..e7c8f90bf 100644--- a/packages/sie_gateway/src/types/pool.rs+++ b/packages/sie_gateway/src/types/pool.rs@@ -1,7 +1,8 @@use serde::{Deserialize, Serialize};use std::collections::HashMap;+use utoipa::ToSchema;-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]#[serde(rename_all = "lowercase")]pub enum PoolState {Pending,@@ -19,7 +20,7 @@ impl std::fmt::Display for PoolState {}}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct PoolSpec {pub name: String,#[serde(default)]@@ -32,14 +33,14 @@ pub struct PoolSpec {pub minimum_worker_count: u32,}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct AssignedWorker {pub name: String,pub url: String,pub gpu: String,}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct PoolStatus {pub state: PoolState,#[serde(default)]@@ -61,7 +62,7 @@ impl Default for PoolStatus {}}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct Pool {pub spec: PoolSpec,pub status: PoolStatus,diff --git a/packages/sie_gateway/src/types/worker.rs b/packages/sie_gateway/src/types/worker.rsindex dae99ac5f..b4daa94a9 100644--- a/packages/sie_gateway/src/types/worker.rs+++ b/packages/sie_gateway/src/types/worker.rs@@ -1,5 +1,6 @@use serde::{Deserialize, Serialize};use std::time::Instant;+use utoipa::ToSchema;#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum WorkerHealth {@@ -49,7 +50,7 @@ impl WorkerState {}}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct ClusterStatus {pub timestamp: f64,pub worker_count: i32,@@ -60,7 +61,7 @@ pub struct ClusterStatus {pub models: Vec<ModelInfo>,}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct WorkerInfo {pub name: String,pub url: String,@@ -75,7 +76,7 @@ pub struct WorkerInfo {pub bundle_config_hash: String,}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct ModelInfo {pub name: String,pub state: String,diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex 1fb04e126..8e3102932 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.3.1"+version = "0.3.2"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/Dockerfile.cpu b/packages/sie_server/Dockerfile.cpuindex 5f4962f0e..1533efa97 100644--- a/packages/sie_server/Dockerfile.cpu+++ b/packages/sie_server/Dockerfile.cpu@@ -39,7 +39,10 @@ COPY packages/sie_sdk/pyproject.toml /tmp/sie_sdk/pyproject.tomlCOPY packages/sie_server/pyproject.toml ./pyproject.toml# Stub source trees so pip accepts the editable installs during dep resolution.-RUN mkdir -p /tmp/sie_sdk/src/sie_sdk src/sie_server \+# Also create empty bundles/ and models/ — referenced by force-include in+# pyproject.toml; hatchling resolves them at editable-metadata time even though+# real contents only land 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__.pydiff --git a/packages/sie_server/Dockerfile.cuda11 b/packages/sie_server/Dockerfile.cuda11index 12daa6f63..3d4accf74 100644--- a/packages/sie_server/Dockerfile.cuda11+++ b/packages/sie_server/Dockerfile.cuda11@@ -41,7 +41,10 @@ WORKDIR /appCOPY packages/sie_sdk/pyproject.toml /tmp/sie_sdk/pyproject.tomlCOPY packages/sie_server/pyproject.toml ./pyproject.toml-RUN mkdir -p /tmp/sie_sdk/src/sie_sdk src/sie_server \+# 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__.pydiff --git a/packages/sie_server/Dockerfile.cuda12 b/packages/sie_server/Dockerfile.cuda12index dd272abde..6ee4e83c5 100644--- a/packages/sie_server/Dockerfile.cuda12+++ b/packages/sie_server/Dockerfile.cuda12@@ -44,7 +44,10 @@ WORKDIR /appCOPY packages/sie_sdk/pyproject.toml /tmp/sie_sdk/pyproject.tomlCOPY packages/sie_server/pyproject.toml ./pyproject.toml-RUN mkdir -p /tmp/sie_sdk/src/sie_sdk src/sie_server \+# 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__.pydiff --git a/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml b/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yamlindex 6106edb43..9aac172ce 100644--- a/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml+++ b/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml@@ -11,7 +11,7 @@ tasks:sparse: nullmultivector:dim: 96- score: null+ score: {}extract: nullmax_sequence_length: 512profiles:diff --git a/packages/sie_server/models/colbert-ir__colbertv2.0.yaml b/packages/sie_server/models/colbert-ir__colbertv2.0.yamlindex 8287ede99..35ed494ee 100644--- a/packages/sie_server/models/colbert-ir__colbertv2.0.yaml+++ b/packages/sie_server/models/colbert-ir__colbertv2.0.yaml@@ -11,7 +11,7 @@ tasks:sparse: nullmultivector:dim: 128- score: null+ score: {}extract: nullmax_sequence_length: 512profiles:diff --git a/packages/sie_server/models/docling.yaml b/packages/sie_server/models/docling.yamlindex cbe55afdb..93cea9b87 100644--- a/packages/sie_server/models/docling.yaml+++ b/packages/sie_server/models/docling.yaml@@ -18,3 +18,11 @@ profiles:adapter_options:loadtime: {}runtime: {}+ ocr:+ max_batch_tokens: 1+ compute_precision: null+ adapter_path: sie_server.adapters.docling:DoclingAdapter+ adapter_options:+ loadtime: {}+ runtime:+ ocr: truediff --git a/packages/sie_server/models/jinaai__jina-colbert-v2.yaml b/packages/sie_server/models/jinaai__jina-colbert-v2.yamlindex 6a3536dda..911e298d3 100644--- a/packages/sie_server/models/jinaai__jina-colbert-v2.yaml+++ b/packages/sie_server/models/jinaai__jina-colbert-v2.yaml@@ -11,7 +11,7 @@ tasks:sparse: nullmultivector:dim: 128- score: null+ score: {}extract: nullmax_sequence_length: 8192profiles:diff --git a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yamlindex c23a86b76..e51b375b5 100644--- a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml+++ b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml@@ -11,7 +11,7 @@ tasks:sparse: nullmultivector:dim: 128- score: null+ score: {}extract: nullmax_sequence_length: 8192profiles:diff --git a/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml b/packages/sie_server/models/lightonai__Reason-ModernColBERT.yamlindex d90f98383..b1404a971 100644--- a/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml+++ b/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml@@ -11,7 +11,7 @@ tasks:sparse: nullmultivector:dim: 128- score: null+ score: {}extract: nullmax_sequence_length: 8192profiles:diff --git a/packages/sie_server/models/mixedbread-ai__mxbai-colbert-large-v1.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-colbert-large-v1.yamlindex 217668a6d..de40017d8 100644--- a/packages/sie_server/models/mixedbread-ai__mxbai-colbert-large-v1.yaml+++ b/packages/sie_server/models/mixedbread-ai__mxbai-colbert-large-v1.yaml@@ -11,7 +11,7 @@ tasks:sparse: nullmultivector:dim: 128- score: null+ score: {}extract: nullmax_sequence_length: 512profiles:diff --git a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yamlindex 1e93edd49..2789262dc 100644--- a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml+++ b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml@@ -11,7 +11,7 @@ tasks:sparse: nullmultivector:dim: 64- score: null+ score: {}extract: nullmax_sequence_length: 8192profiles:diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 8e5a78131..a59f5b11a 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -3,7 +3,7 @@"info": {"title": "SIE Server","description": "Search Inference Engine - GPU inference server for search workloads",- "version": "0.3.1"+ "version": "0.3.2"},"paths": {"/": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex 21a6f11f8..b0a395f3c 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.3.1"+version = "0.3.2"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }@@ -80,6 +80,10 @@ build-backend = "hatchling.build"[tool.hatch.build.targets.wheel]packages = ["src/sie_server"]+[tool.hatch.build.targets.wheel.force-include]+"models" = "sie_server/models"+"bundles" = "sie_server/bundles"+[tool.uv.sources]# Prebuilt flash-attn wheel for torch 2.9 + cu128 (official wheels only go up to torch 2.8)# Platform-specific: Linux x86_64 only. Non-Linux users should not install the flash-attn extra.diff --git a/packages/sie_server/src/sie_server/adapters/_base_adapter.py b/packages/sie_server/src/sie_server/adapters/_base_adapter.pyindex 3b8c95e52..b3f1b6e82 100644--- a/packages/sie_server/src/sie_server/adapters/_base_adapter.py+++ b/packages/sie_server/src/sie_server/adapters/_base_adapter.py@@ -6,11 +6,15 @@ from typing import TYPE_CHECKING, Any, ClassVar, castfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED+from sie_server.adapters._utils import grouped_score_pairsfrom sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDimsif TYPE_CHECKING:import torch+ from sie_server.core.inference_output import ScoreOutput+ from sie_server.types.inputs import Item+logger = logging.getLogger(__name__)@@ -57,7 +61,16 @@ class BaseAdapter(ModelAdapter):raise TypeError(msg)if "score" in spec.outputs:- if cls.score is ModelAdapter.score and cls.score_pairs is ModelAdapter.score_pairs:+ # BaseAdapter ships a default score_pairs() that delegates to score().+ # Treat that default as "not implemented" for validation purposes:+ # subclasses must override either score() or score_pairs() so the+ # default delegate doesn't bottom out in ModelAdapter.score().+ score_overridden = cls.score is not ModelAdapter.score+ score_pairs_overridden = cls.score_pairs not in (+ ModelAdapter.score_pairs,+ BaseAdapter.score_pairs,+ )+ if not score_overridden and not score_pairs_overridden:msg = f"{cls.__name__} declares 'score' in outputs but does not implement score() or score_pairs()"raise TypeError(msg)@@ -117,6 +130,41 @@ class BaseAdapter(ModelAdapter):model_name=getattr(self, "_model_name_or_path", ""),)+ # -- Default batched scoring ---------------------------------------------++ def score_pairs(+ self,+ queries: list[Item],+ docs: list[Item],+ *,+ instruction: str | None = None,+ options: dict[str, Any] | None = None,+ ) -> ScoreOutput:+ """Default ``score_pairs()`` that batches via per-query grouping.++ Groups parallel ``(query, doc)`` pairs by ``(text, id, instruction)``+ so each unique query is encoded once and its docs are scored as a+ single ``score()`` call. Subclasses with a more efficient native+ cross-batch path (e.g. cross-encoders that pack queries and docs+ into one transformer pass) should override this.++ Per-call ``options`` are not supported by this default delegate+ (it dispatches per-query and cannot route options into ``score()``+ without subclass-specific knowledge). If ``options`` is a non-empty+ mapping, this raises ``NotImplementedError`` to surface the+ unsupported configuration; pass ``options=None`` (or ``{}``) or+ override ``score_pairs()`` with an options-aware implementation.+ """+ if options:+ msg = (+ f"{type(self).__name__}.score_pairs(): per-call options are "+ f"not supported by the default batching path "+ f"(got options={options!r}). Override score_pairs() with an "+ f"options-aware implementation."+ )+ raise NotImplementedError(msg)+ return grouped_score_pairs(self.score, queries, docs, instruction=instruction)+# -- Shared helpers ------------------------------------------------------def _check_loaded(self) -> None:diff --git a/packages/sie_server/src/sie_server/adapters/_utils.py b/packages/sie_server/src/sie_server/adapters/_utils.pyindex ced09080e..b9488f8af 100644--- a/packages/sie_server/src/sie_server/adapters/_utils.py+++ b/packages/sie_server/src/sie_server/adapters/_utils.py@@ -1,6 +1,10 @@from __future__ import annotations-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Protocol++import numpy as np++from sie_server.core.inference_output import ScoreOutputif TYPE_CHECKING:import torch@@ -8,6 +12,16 @@ if TYPE_CHECKING:from sie_server.types.inputs import Item+class _ScoreFn(Protocol):+ def __call__(+ self,+ query: Item,+ items: list[Item],+ *,+ instruction: str | None = ...,+ ) -> list[float]: ...++# ---------------------------------------------------------------------------# RoPE utilities (eliminates 7 identical copies)# ---------------------------------------------------------------------------@@ -140,3 +154,67 @@ def resolve_embedding_options(opts.get("query_template", default_query_template),opts.get("doc_template", default_doc_template),)+++# ---------------------------------------------------------------------------+# Score-pair grouping (shared by ColBERT-family adapters)+# ---------------------------------------------------------------------------+++def grouped_score_pairs(+ score_fn: _ScoreFn,+ queries: list[Item],+ docs: list[Item],+ *,+ instruction: str | None = None,+) -> ScoreOutput:+ """Run a per-query ``score()`` callable over parallel (query, doc) pairs.++ Groups pairs by ``(query.text, query.id, instruction)`` so each unique+ query is encoded once and its docs are scored as one batch. Used by+ ColBERT-family adapters to satisfy the worker's ``score_pairs()``+ contract while reusing the optimized batched ``score()``.++ Queries with ``text is None`` are not supported and raise ``ValueError``+ (ColBERT scoring requires text). The grouping key is+ ``(query.text, query.id or "", instruction or "")`` — two distinct+ ``Item`` objects with identical text/id/instruction collapse to one+ encoding pass.++ Args:+ score_fn: Bound ``adapter.score(query, items, *, instruction=None)``.+ queries: Query items (parallel to docs).+ docs: Document items to score.+ instruction: Optional instruction passed through to ``score_fn``.++ Returns:+ ``ScoreOutput`` with one float per pair, in the original input order.++ Raises:+ ValueError: If ``queries`` and ``docs`` lengths differ, or any query+ lacks text.+ """+ if len(queries) != len(docs):+ msg = f"queries and docs must be parallel; got {len(queries)} vs {len(docs)}"+ raise ValueError(msg)++ if not docs:+ return ScoreOutput(scores=np.zeros(0, dtype=np.float32), batch_size=0)++ groups: dict[tuple[str, str, str], list[int]] = {}+ for i, q in enumerate(queries):+ if q.text is None:+ msg = f"grouped_score_pairs requires queries[{i}].text; got None"+ raise ValueError(msg)+ key = (q.text, q.id or "", instruction or "")+ groups.setdefault(key, []).append(i)++ scores = np.zeros(len(docs), dtype=np.float32)+ for indices in groups.values():+ q = queries[indices[0]]+ group_docs = [docs[i] for i in indices]+ group_scores = score_fn(q, group_docs, instruction=instruction)+ for idx, s in zip(indices, group_scores, strict=True):+ scores[idx] = float(s)++ return ScoreOutput(scores=scores, batch_size=len(docs))diff --git a/packages/sie_server/src/sie_server/adapters/base.py b/packages/sie_server/src/sie_server/adapters/base.pyindex c739061f4..c7c93481c 100644--- a/packages/sie_server/src/sie_server/adapters/base.py+++ b/packages/sie_server/src/sie_server/adapters/base.py@@ -127,6 +127,20 @@ class ModelAdapter(ABC):device: Device string (e.g., "cuda:0", "cpu")."""+ def warmup(self) -> None:+ """Run a warmup forward pass on the loaded model.++ Called by the model loader after ``load()`` has completed. The default+ implementation is a no-op for adapters that do not need warmup. Adapters+ that compile kernels on first call (e.g. flash-attention) or otherwise+ benefit from a priming pass should override this and run a single+ inference pass against a tiny synthetic input.++ Splitting this from ``load()`` lets the cold-start instrumentation+ attribute deserialize and warmup time separately.+ """+ return+@abstractmethoddef unload(self) -> None:"""Unload the model and free resources.diff --git a/packages/sie_server/src/sie_server/adapters/bert_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/bert_flash/__init__.pyindex 0e26be8e3..06601cb64 100644--- a/packages/sie_server/src/sie_server/adapters/bert_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/bert_flash/__init__.py@@ -172,6 +172,7 @@ class BertFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):self._max_seq_length,)+ def warmup(self) -> None:# Warmup flash attention kernelslogger.info("Warming up CUDA kernels...")warmup_items = [Item(text="warmup")]diff --git a/packages/sie_server/src/sie_server/adapters/docling/__init__.py b/packages/sie_server/src/sie_server/adapters/docling/__init__.pyindex c169f7ca3..22815d3d1 100644--- a/packages/sie_server/src/sie_server/adapters/docling/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/docling/__init__.py@@ -2,7 +2,6 @@ from __future__ import annotationsimport ioimport logging-from concurrent.futures import ThreadPoolExecutorfrom typing import TYPE_CHECKING, Any, ClassVarfrom sie_server.adapters._base_adapter import BaseAdapter@@ -52,11 +51,17 @@ class DoclingAdapter(BaseAdapter):OCR is disabled by default for speed and predictability. Pass``options={"ocr": True}`` per request to enable it.- Concurrency: a fresh ``DocumentConverter`` is built per item rather than- sharing one across threads. Construction is ~10 ms once Docling's- layout/table models have been pre-warmed (they cache globally), and this- sidesteps thread-safety concerns reported upstream- (https://github.com/docling-project/docling/issues/115).+ Concurrency: one ``DocumentConverter`` is cached per ``ocr_enabled`` value+ on the adapter instance. ``self._device`` is set once in ``load()`` and is+ stable for the adapter's lifetime, so the effective cache key is+ ``(self._device, ocr_enabled)`` and at most two converters ever exist per+ adapter instance. Cross-request serialization is provided by+ ``ModelWorker._inference_executor`` (max_workers=1), so the cache itself+ does not need a lock. Items within one batch are processed serially+ (rather than via a per-item thread pool) to sidestep the converter's known+ thread-safety issue (https://github.com/docling-project/docling/issues/115);+ at GPU-bound concurrency the upstream worker is already saturating the+ device, so intra-batch parallelism does not buy real throughput."""spec: ClassVar[AdapterSpec] = AdapterSpec(@@ -69,12 +74,13 @@ class DoclingAdapter(BaseAdapter):self,model_name_or_path: str | None = None, # unused; Docling is package-backed*,- compute_precision: str | None = None, # unused; Docling runs on CPU+ compute_precision: str | None = None, # unused; device is threaded via load()**kwargs: Any,) -> None:_ = (model_name_or_path, compute_precision, kwargs)self._loaded = Falseself._device: str | None = None+ self._converters: dict[bool, Any] = {}def load(self, device: str) -> None:self._device = device@@ -82,12 +88,20 @@ class DoclingAdapter(BaseAdapter):# the first real request doesn't block on a multi-hundred-MB pull.# Models cache globally, so subsequent per-task converters are cheap.try:- warm_converter = self._make_converter(ocr_enabled=False)+ warm_converter = self._get_converter(ocr_enabled=False)self._convert_bytes(warm_converter, _TINY_PDF_BYTES, format_hint="pdf")+ # Also build the OCR-enabled converter so the first ocr-profile+ # request doesn't pay layout+OCR model-init latency.+ self._get_converter(ocr_enabled=True)except Exception:logger.exception("Docling pre-warm failed; first real request may be slow")self._loaded = True+ def unload(self) -> None:+ self._converters.clear()+ self._loaded = False+ super().unload()+def extract(self,items: list[Item],@@ -113,28 +127,35 @@ class DoclingAdapter(BaseAdapter):)def _run_extract(self, items: list[Item], *, ocr_enabled: bool) -> list[dict[str, Any]]:- """Run extract per-item, parallelized across the batch.+ """Run extract per-item, serially.- Each task gets its own DocumentConverter (see class docstring).+ Items are processed one at a time so we can share a single cached+ DocumentConverter (see class docstring). At GPU-bound concurrency the+ worker-level inference executor is already saturating the device, so+ intra-batch parallelism does not buy real throughput."""- if len(items) <= 1:- return [self._extract_one(item, ocr_enabled=ocr_enabled) for item in items]-- with ThreadPoolExecutor(max_workers=min(len(items), 4)) as pool:- futures = [pool.submit(self._extract_one, item, ocr_enabled=ocr_enabled) for item in items]- return [f.result() for f in futures]+ return [self._extract_one(item, ocr_enabled=ocr_enabled) for item in items]def _extract_one(self, item: Item, *, ocr_enabled: bool) -> dict[str, Any]:document = item.documentif not is_document_input(document):return {"error": _ERR_REQUIRES_DOCUMENT}try:- converter = self._make_converter(ocr_enabled=ocr_enabled)+ converter = self._get_converter(ocr_enabled=ocr_enabled)return self._convert_bytes(converter, document["data"], format_hint=document.get("format"))except Exception as e: # noqa: BLE001 - per-item failure must not poison the batchlogger.warning("Docling extract failed for item id=%s: %s", item.id, e)return {"error": str(e)}+ def _get_converter(self, *, ocr_enabled: bool) -> Any:+ """Return the cached DocumentConverter for this ocr_enabled value, building lazily on first use."""+ cached = self._converters.get(ocr_enabled)+ if cached is not None:+ return cached+ converter = self._make_converter(ocr_enabled=ocr_enabled)+ self._converters[ocr_enabled] = converter+ return converter+def _convert_bytes(self, converter: Any, data: bytes, *, format_hint: str | None) -> dict[str, Any]:from docling.datamodel.base_models import DocumentStream # ty: ignore[unresolved-import]@@ -151,15 +172,45 @@ class DoclingAdapter(BaseAdapter):}def _make_converter(self, *, ocr_enabled: bool) -> Any:- """Build a fresh DocumentConverter. One per task — see class docstring."""+ """Build a fresh DocumentConverter. Callers should usually go through _get_converter() for caching.++ Threads self._device through Docling's AcceleratorOptions so layout, table,+ and OCR models actually run on the configured device. Without this, Docling+ silently defaults to CPU regardless of how SIE was launched.+ """from docling.document_converter import DocumentConverter # ty: ignore[unresolved-import]- if not ocr_enabled:- return DocumentConverter()+ accelerator_options = self._build_accelerator_options()from docling.datamodel.base_models import InputFormat # ty: ignore[unresolved-import]from docling.datamodel.pipeline_options import PdfPipelineOptions # ty: ignore[unresolved-import]from docling.document_converter import PdfFormatOption # ty: ignore[unresolved-import]- pdf_opts = PdfPipelineOptions(do_ocr=True)+ # Pass do_ocr explicitly on both paths. Docling's PdfPipelineOptions defaults+ # do_ocr=True, so an unset default would silently OCR every PDF and make the+ # `ocr` profile a no-op vs. the default profile.+ pdf_kwargs: dict[str, Any] = {"do_ocr": ocr_enabled}+ if accelerator_options is not None:+ pdf_kwargs["accelerator_options"] = accelerator_options+ pdf_opts = PdfPipelineOptions(**pdf_kwargs)return DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pdf_opts)})++ def _build_accelerator_options(self) -> Any:+ """Translate self._device into a Docling AcceleratorOptions, or None."""+ if not self._device:+ return None+ from docling.datamodel.accelerator_options import AcceleratorOptions # ty: ignore[unresolved-import]++ try:+ return AcceleratorOptions(device=str(self._device))+ except Exception as e: # noqa: BLE001 - pydantic validation; fall back to auto+ logger.warning(+ "Docling: invalid device %r, falling back to 'auto' (%s)",+ self._device,+ e,+ )+ try:+ return AcceleratorOptions(device="auto")+ except Exception:+ logger.exception("Docling: failed to build AcceleratorOptions even with 'auto'")+ return Nonediff --git a/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.pyindex a9b6066d3..69986248e 100644--- a/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py@@ -142,6 +142,7 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):self._max_seq_length,)+ def warmup(self) -> None:# Warmup flash attention kernelslogger.info("Warming up CUDA kernels...")warmup_items = [Item(text="warmup")]diff --git a/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py b/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.pyindex 56ac51670..0333ffcfb 100644--- a/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py@@ -293,6 +293,7 @@ class PaddleOCRVLAdapter(BaseAdapter):max_new_tokens=max_new_tokens,do_sample=False,num_beams=num_beams,+ use_cache=True,)generated_ids = output_ids[0, prompt_len:]@@ -344,6 +345,7 @@ class PaddleOCRVLAdapter(BaseAdapter):max_new_tokens=max_new_tokens,do_sample=False,num_beams=num_beams,+ use_cache=True,)generated_ids = output_ids[0, prompt_len:]diff --git a/packages/sie_server/src/sie_server/adapters/sentence_transformer/__init__.py b/packages/sie_server/src/sie_server/adapters/sentence_transformer/__init__.pyindex 0efb61bec..47e73e2eb 100644--- a/packages/sie_server/src/sie_server/adapters/sentence_transformer/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/sentence_transformer/__init__.py@@ -82,13 +82,17 @@ class SentenceTransformerDenseAdapter(BaseAdapter):trust_remote_code=self._trust_remote_code,config_kwargs=self._config_kwargs,)- _ = self._model.encode(["warmup"], convert_to_numpy=True, show_progress_bar=False)if self._max_seq_length is not None:self._model.max_seq_length = self._max_seq_lengthself._dense_dim = self._model.get_embedding_dimension()+ def warmup(self) -> None:+ if self._model is None:+ return+ _ = self._model.encode(["warmup"], convert_to_numpy=True, show_progress_bar=False)+def encode(self,items: list[Item],diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.pyindex ae79ca9ce..6928a2962 100644--- a/packages/sie_server/src/sie_server/app/app_factory.py+++ b/packages/sie_server/src/sie_server/app/app_factory.py@@ -1,5 +1,6 @@import loggingimport os+import timefrom collections.abc import AsyncGenerator, Callablefrom contextlib import asynccontextmanagerfrom typing import Any@@ -35,6 +36,27 @@ from sie_server.observability.tracing import setup_tracinglogger = logging.getLogger(__name__)+@asynccontextmanager+async def _timed_stage(name: str, cm: Any) -> AsyncGenerator[Any, None]:+ """Wrap an async context manager to log its entry-phase elapsed time.++ Emits one structured line per stage on entry — `lifespan.stage <name>+ elapsed_s=<x>` — so cold-start tooling (issue #816) can attribute the ~5s+ `engine_boot_s` consistently seen across LTFR runs to specific lifespan+ stages (NVML init, NATS connect, telemetry handshake, etc).++ The exit-phase teardown is intentionally not timed — only the setup phase+ contributes to `engine_boot_s`. ``cm`` is typed as ``Any`` because the+ contextlib ``@asynccontextmanager`` wrapper produces a context manager+ type that ty struggles to bind through a TypeVar parameter.+ """+ t0 = time.perf_counter()+ async with cm as value:+ elapsed = time.perf_counter() - t0+ logger.info("lifespan.stage %s elapsed_s=%.3f", name, elapsed)+ yield value++class AppFactory:@classmethoddef create_app(cls, config: AppStateConfig) -> FastAPI:@@ -80,15 +102,16 @@ class AppFactory:- Then proceeds with normal shutdown (unload models, cleanup)"""init_server_start_time()+ cls._configure_torch_threads()cls._configure_cuda_defaults()async with (- cls._nvml(),- telemetry_sender(),- cls._model_registry(config) as registry,- cls._nats_subscriber(registry) as nats_sub,- cls._nats_pull_loop(registry, nats_sub) as pull_loop,- cls._graceful_shutdown(shutdown_state),- cls._readiness_handling(),+ _timed_stage("nvml", cls._nvml()),+ _timed_stage("telemetry", telemetry_sender()),+ _timed_stage("model_registry", cls._model_registry(config)) as registry,+ _timed_stage("nats_subscriber", cls._nats_subscriber(registry)) as nats_sub,+ _timed_stage("nats_pull_loop", cls._nats_pull_loop(registry, nats_sub)) as pull_loop,+ _timed_stage("graceful_shutdown", cls._graceful_shutdown(shutdown_state)),+ _timed_stage("readiness", cls._readiness_handling()),):app.state.registry = registryapp.state.nats_subscriber = nats_sub@@ -293,8 +316,10 @@ class AppFactory:in the async-with stack, so the pod stays NotReady during preload."""if not config.preload_models:+ logger.info("lifespan.stage preload_models elapsed_s=0.000")return+ t0 = time.perf_counter()logger.info("Preloading %d model(s): %s", len(config.preload_models), ", ".join(config.preload_models))# Sequential loading is intentional: parallel loads risk OOM on GPU workers@@ -313,7 +338,9 @@ class AppFactory:name,)+ elapsed = time.perf_counter() - t0logger.info("Preload complete: %d/%d models loaded", succeeded, len(config.preload_models))+ logger.info("lifespan.stage preload_models elapsed_s=%.3f", elapsed)@staticmethoddef _configure_cuda_defaults() -> None:@@ -329,3 +356,34 @@ class AppFactory:torch.backends.cudnn.allow_tf32 = Truetorch.backends.cudnn.benchmark = Truelogger.info("CUDA defaults: TF32 enabled, cudnn.benchmark enabled")++ @staticmethod+ def _configure_torch_threads() -> None:+ # Cap torch BLAS threads so concurrent CPU consumers (Docling per-batch+ # pool, image preprocessor pool) don't oversubscribe cores. Override+ # via SIE_TORCH_NUM_THREADS; default = half the logical cores.+ override = os.environ.get("SIE_TORCH_NUM_THREADS")+ if override is not None:+ try:+ n = int(override)+ if n < 1:+ raise ValueError+ except ValueError:+ logger.warning(+ "SIE_TORCH_NUM_THREADS=%r is not a positive integer; using default",+ override,+ )+ n = max(1, (os.cpu_count() or 4) // 2)+ logger.info("torch threads: %d (default after invalid override; cpu_count=%s)", n, os.cpu_count())+ else:+ logger.info("torch threads: %d (from SIE_TORCH_NUM_THREADS)", n)+ else:+ n = max(1, (os.cpu_count() or 4) // 2)+ logger.info("torch threads: %d (default; cpu_count=%s)", n, os.cpu_count())++ torch.set_num_threads(n)+ try:+ torch.set_num_interop_threads(1)+ except RuntimeError:+ # Already initialised; safe to ignore — only the first call has effect.+ logger.warning("torch.set_num_interop_threads(1) ignored: parallel runtime already started")diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.pyindex 296dcd432..f9fee3c60 100644--- a/packages/sie_server/src/sie_server/cli.py+++ b/packages/sie_server/src/sie_server/cli.py@@ -14,9 +14,20 @@ from sie_server.main import run_serverlogger = logging.getLogger(__name__)-# Default bundles directory relative to sie_server package-_DEFAULT_BUNDLES_DIR = Path(__file__).parent.parent.parent / "bundles"-DEFAULT_MODELS_DIR = str(Path(str(sie_server.__file__)).parent.parent.parent / "models")++# Prefer the package-internal location so a fresh `pip install sie-server`+# followed by `sie-server serve` works out of the box (issue #820).+def _resolve_default_dir(name: str) -> Path:+ pkg_dir = Path(sie_server.__file__).parent+ bundled = pkg_dir / name+ if bundled.is_dir():+ return bundled+ # Fallback: source/dev layout (packages/sie_server/<name>)+ return pkg_dir.parent.parent / name+++_DEFAULT_BUNDLES_DIR = _resolve_default_dir("bundles")+DEFAULT_MODELS_DIR = str(_resolve_default_dir("models"))def detect_device() -> str:diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.pyindex 15c9424aa..301618449 100644--- a/packages/sie_server/src/sie_server/core/model_loader.py+++ b/packages/sie_server/src/sie_server/core/model_loader.py@@ -272,7 +272,7 @@ class ModelLoader:LoadedModel containing the loaded state."""logger.info("Loading model '%s' onto %s", name, device)- adapter.load(device)+ _run_load_with_markers(name, device, adapter)return self._finish_load(name, device, adapter, config)async def load_and_register_async(@@ -326,7 +326,7 @@ class ModelLoader:def _load_sync() -> LoadedModel:logger.info("Loading model '%s' onto %s", name, device)- adapter.load(device)+ _run_load_with_markers(name, device, adapter)return self._finish_load(name, device, adapter, config)return await loop.run_in_executor(self._load_executor, _load_sync)@@ -353,7 +353,7 @@ class ModelLoader:LoadedModel containing the loaded state."""logger.info("Loading model '%s' onto %s (main thread)", name, device)- adapter.load(device)+ _run_load_with_markers(name, device, adapter)return self._finish_load(name, device, adapter, config)def _finish_load(@@ -524,6 +524,23 @@ class ModelLoader:self._load_executor.shutdown(wait=False)+def _run_load_with_markers(name: str, device: str, adapter: ModelAdapter) -> None:+ """Drive ``adapter.load()`` then ``adapter.warmup()`` with cold-start log markers.++ The four markers (``Model deserialize start/end`` and ``Model warmup start/end``)+ let the multipod cold-start bench (schema v6) attribute deserialize and warmup+ time separately. They are emitted unconditionally — adapters whose ``warmup()``+ is a no-op still produce both warmup markers so the parser can attribute+ consistently across adapters (the resulting ``warmup_s`` is just ~0).+ """+ logger.info("Model deserialize start: '%s' on %s", name, device)+ adapter.load(device)+ logger.info("Model deserialize end: '%s' on %s", name, device)+ logger.info("Model warmup start: '%s' on %s", name, device)+ adapter.warmup()+ logger.info("Model warmup end: '%s' on %s", name, device)++def _merge_adaptive_params(engine: AdaptiveBatchingParams,profile: ProfileAdaptiveBatching | None,diff --git a/packages/sie_server/tests/adapters/test_docling.py b/packages/sie_server/tests/adapters/test_docling.pyindex de21160b0..263461813 100644--- a/packages/sie_server/tests/adapters/test_docling.py+++ b/packages/sie_server/tests/adapters/test_docling.py@@ -12,8 +12,9 @@ def _make_adapter(*, ocr_factory: Any = None) -> tuple[DoclingAdapter, MagicMock"""Build a loaded adapter whose `_make_converter` returns mocks.Returns the adapter and the patched factory so tests can inspect calls.- Each invocation of the factory yields a *new* MagicMock-backed converter- (mirroring the per-task instantiation contract documented on the adapter).+ Each invocation of the factory yields a *new* MagicMock-backed converter;+ the adapter caches them via `_get_converter` so within a single+ `ocr_enabled` value only the first extract triggers a build."""adapter = DoclingAdapter()adapter._loaded = True@@ -90,36 +91,39 @@ class TestDoclingExtract:adapter = DoclingAdapter()adapter._loaded = True- good_converter = MagicMock(name="DocumentConverter[good]")+ converter = MagicMock(name="DocumentConverter[shared]")- def _good_convert(stream: Any) -> MagicMock:+ def _good_result(name: str, stream_name: str) -> MagicMock:r = MagicMock()- r.document.export_to_text.return_value = "text:good"- r.document.export_to_markdown.return_value = "# md:good"- r.document.export_to_dict.return_value = {"name": stream.name}+ r.document.export_to_text.return_value = f"text:{name}"+ r.document.export_to_markdown.return_value = f"# md:{name}"+ r.document.export_to_dict.return_value = {"name": stream_name}return r- good_converter.convert.side_effect = _good_convert+ calls = {"n": 0}- bad_converter = MagicMock(name="DocumentConverter[bad]")- bad_converter.convert.side_effect = ValueError("corrupt PDF")+ def _convert_side_effect(stream: Any, **_kwargs: Any) -> MagicMock:+ calls["n"] += 1+ if calls["n"] == 2:+ raise RuntimeError("boom")+ return _good_result(f"doc{calls['n']}", stream.name)- # First call returns the good converter, second call returns the bad one.- produced: list[MagicMock] = [good_converter, bad_converter]- adapter._make_converter = MagicMock(side_effect=lambda **_: produced.pop(0)) # type: ignore[method-assign]+ converter.convert.side_effect = _convert_side_effect+ factory = MagicMock(name="_make_converter", return_value=converter)+ adapter._make_converter = factory # type: ignore[method-assign]out = adapter.extract([Item(document={"data": b"a", "format": "pdf"}),Item(document={"data": b"b", "format": "pdf"}),+ Item(document={"data": b"c", "format": "pdf"}),])assert out.data is not None- # Either order is valid because of the thread pool — assert both slots- # individually.- statuses = sorted(d.get("error", "ok") for d in out.data)- assert statuses == ["corrupt PDF", "ok"]+ statuses = [d.get("error", "ok") for d in out.data]+ assert statuses == ["ok", "boom", "ok"]+ assert factory.call_count == 1 # converter built once, not three timesdef test_extract_before_load_raises(self) -> None:adapter = DoclingAdapter()@@ -132,10 +136,9 @@ class TestDoclingExtract:adapter.extract([Item(document={"data": b"x", "format": "pdf"})], options={"ocr": True})adapter.extract([Item(document={"data": b"x", "format": "pdf"})], options={"ocr": True})- assert factory.call_args_list == [- ({"ocr_enabled": True},),- ({"ocr_enabled": True},),- ] or all(call.kwargs == {"ocr_enabled": True} for call in factory.call_args_list)+ # Cache means we built once even though we extracted twice.+ assert factory.call_count == 1+ assert factory.call_args.kwargs == {"ocr_enabled": True}def test_ocr_default_off_passes_false(self) -> None:adapter, factory = _make_adapter()@@ -145,15 +148,30 @@ class TestDoclingExtract:assert factory.call_count == 1assert factory.call_args.kwargs == {"ocr_enabled": False}- def test_batch_constructs_converter_per_item(self) -> None:+ def test_batch_reuses_cached_converter(self) -> None:adapter, factory = _make_adapter()items = [Item(document={"data": b"x", "format": "pdf"}) for _ in range(3)]out = adapter.extract(items)assert out.batch_size == 3- # One fresh converter per item — no sharing across the batch.- assert factory.call_count == 3+ # One cached converter shared across the whole batch.+ assert factory.call_count == 1+ assert factory.call_args.kwargs == {"ocr_enabled": False}++ def test_extract_caches_converter_across_calls(self) -> None:+ adapter, factory = _make_adapter()+ adapter.extract([Item(document={"data": b"x", "format": "pdf"})])+ adapter.extract([Item(document={"data": b"y", "format": "pdf"})])+ assert factory.call_count == 1++ def test_extract_caches_per_ocr_key(self) -> None:+ adapter, factory = _make_adapter()+ adapter.extract([Item(document={"data": b"x", "format": "pdf"})]) # ocr=False+ adapter.extract([Item(document={"data": b"y", "format": "pdf"})], options={"ocr": True}) # ocr=True+ assert factory.call_count == 2+ adapter.extract([Item(document={"data": b"z", "format": "pdf"})]) # ocr=False (cached)+ assert factory.call_count == 2class TestDoclingSpec:@@ -162,21 +180,39 @@ class TestDoclingSpec:assert adapter.capabilities.inputs == ["document"]assert adapter.capabilities.outputs == ["json"]- def test_unload_is_no_op(self) -> None:- # No converter state to clear — package-backed adapter holds no weights.- adapter = DoclingAdapter()+ def test_unload_clears_converter_cache(self) -> None:+ adapter, _factory = _make_adapter()+ adapter.extract([Item(document={"data": b"x", "format": "pdf"})])+ assert adapter._converters # populated+ assert adapter._loaded+adapter.unload() # must not raise+ assert adapter._converters == {}+ assert not adapter._loaded++ with pytest.raises(RuntimeError, match=r"load.* before extract"):+ adapter.extract([Item(document={"data": b"x", "format": "pdf"})])class TestDoclingMakeConverter:- def test_make_converter_no_ocr_returns_default(self) -> None:+ def test_make_converter_no_ocr_passes_do_ocr_false(self) -> None:+ # Docling's PdfPipelineOptions defaults do_ocr=True, so we must pass+ # do_ocr=False explicitly on the default path — otherwise the `ocr`+ # profile is a no-op vs the default profile.adapter = DoclingAdapter()+ assert adapter._device is None- with patch("docling.document_converter.DocumentConverter") as mock_cls:+ with (+ patch("docling.document_converter.DocumentConverter") as mock_cls,+ patch("docling.datamodel.pipeline_options.PdfPipelineOptions") as mock_opts,+ patch("docling.document_converter.PdfFormatOption") as mock_fmt_opt,+ ):adapter._make_converter(ocr_enabled=False)- # No format_options when OCR is off- mock_cls.assert_called_once_with()+ mock_opts.assert_called_once_with(do_ocr=False)+ mock_fmt_opt.assert_called_once()+ mock_cls.assert_called_once()+ assert "format_options" in mock_cls.call_args.kwargsdef test_make_converter_ocr_passes_pdf_pipeline_options(self) -> None:adapter = DoclingAdapter()@@ -192,3 +228,129 @@ class TestDoclingMakeConverter:mock_fmt_opt.assert_called_once()mock_cls.assert_called_once()assert "format_options" in mock_cls.call_args.kwargs++ def test_make_converter_no_ocr_uses_accelerator_options_when_device_set(self) -> None:+ adapter = DoclingAdapter()+ adapter._device = "cuda"++ with (+ patch("docling.document_converter.DocumentConverter") as mock_cls,+ patch("docling.datamodel.pipeline_options.PdfPipelineOptions") as mock_opts,+ patch("docling.datamodel.accelerator_options.AcceleratorOptions") as mock_accel,+ patch("docling.document_converter.PdfFormatOption") as mock_fmt_opt,+ ):+ adapter._make_converter(ocr_enabled=False)++ mock_accel.assert_called_once_with(device="cuda")+ kwargs = mock_opts.call_args.kwargs+ assert kwargs["accelerator_options"] is mock_accel.return_value+ assert kwargs["do_ocr"] is False+ mock_fmt_opt.assert_called_once()+ mock_cls.assert_called_once()+ assert "format_options" in mock_cls.call_args.kwargs++ def test_make_converter_ocr_threads_accelerator_options(self) -> None:+ adapter = DoclingAdapter()+ adapter._device = "cuda:0"++ with (+ patch("docling.document_converter.DocumentConverter") as mock_cls,+ patch("docling.datamodel.pipeline_options.PdfPipelineOptions") as mock_opts,+ patch("docling.datamodel.accelerator_options.AcceleratorOptions") as mock_accel,+ patch("docling.document_converter.PdfFormatOption"),+ ):+ adapter._make_converter(ocr_enabled=True)++ mock_accel.assert_called_once_with(device="cuda:0")+ kwargs = mock_opts.call_args.kwargs+ assert kwargs.get("do_ocr") is True+ assert kwargs.get("accelerator_options") is mock_accel.return_value+ mock_cls.assert_called_once()++ @pytest.mark.parametrize("device", ["cuda", "cuda:0", "mps", "cpu", "auto"])+ def test_make_converter_passes_known_device_strings_through(self, device: str) -> None:+ adapter = DoclingAdapter()+ adapter._device = device++ with (+ patch("docling.document_converter.DocumentConverter"),+ patch("docling.datamodel.pipeline_options.PdfPipelineOptions"),+ patch("docling.datamodel.accelerator_options.AcceleratorOptions") as mock_accel,+ patch("docling.document_converter.PdfFormatOption"),+ ):+ adapter._make_converter(ocr_enabled=True)++ mock_accel.assert_called_once_with(device=device)++ def test_make_converter_invalid_device_falls_back_to_auto(self) -> None:+ adapter = DoclingAdapter()+ adapter._device = "definitely-not-a-device"++ with (+ patch("docling.document_converter.DocumentConverter"),+ patch("docling.datamodel.pipeline_options.PdfPipelineOptions"),+ patch("docling.datamodel.accelerator_options.AcceleratorOptions") as mock_accel,+ patch("docling.document_converter.PdfFormatOption"),+ ):+ mock_accel.side_effect = [ValueError("invalid device"), MagicMock()]+ adapter._make_converter(ocr_enabled=True)++ actual = [c.kwargs for c in mock_accel.call_args_list]+ assert actual == [+ {"device": "definitely-not-a-device"},+ {"device": "auto"},+ ]+++class TestDoclingOcrPrecedence:+ """The DoclingAdapter only sees the merged ``options`` dict produced by+ ``resolve_runtime_options`` (api/options.py); it does not know about+ profiles. These tests pin down the contract that the merged dict drives+ ``ocr_enabled`` regardless of where the value came from.+ """++ def test_profile_runtime_ocr_true_makes_extract_ocr_default(self) -> None:+ """When profile resolution sets options={'ocr': True}, the adapter+ builds an OCR-enabled converter even with no per-request overrides.+ """+ adapter, factory = _make_adapter()++ # Simulates what the worker passes through after the 'ocr' profile is+ # resolved server-side: profile.runtime.ocr=true becomes options.ocr=true+ # before reaching the adapter.+ adapter.extract(+ [Item(document={"data": b"x", "format": "pdf"})],+ options={"ocr": True},+ )++ assert factory.call_count == 1+ assert factory.call_args.kwargs == {"ocr_enabled": True}++ def test_request_ocr_false_overrides_profile_ocr_true(self) -> None:+ """Per-request override wins. ``resolve_runtime_options`` emits the+ already-merged dict, so the adapter sees options={'ocr': False}+ even if the profile would have defaulted ocr=True.+ """+ adapter, factory = _make_adapter()++ adapter.extract(+ [Item(document={"data": b"x", "format": "pdf"})],+ options={"ocr": False},+ )++ assert factory.call_count == 1+ assert factory.call_args.kwargs == {"ocr_enabled": False}++ def test_request_ocr_true_works_without_profile_default(self) -> None:+ """Regression: per-request ocr=true keeps working when no profile+ default is set (i.e., the historical 'default' profile path).+ """+ adapter, factory = _make_adapter()++ adapter.extract(+ [Item(document={"data": b"x", "format": "pdf"})],+ options={"ocr": True},+ )++ assert factory.call_count == 1+ assert factory.call_args.kwargs == {"ocr_enabled": True}diff --git a/packages/sie_server/tests/adapters/test_paddleocr_vl.py b/packages/sie_server/tests/adapters/test_paddleocr_vl.pyindex 2500755d5..a440d4a37 100644--- a/packages/sie_server/tests/adapters/test_paddleocr_vl.py+++ b/packages/sie_server/tests/adapters/test_paddleocr_vl.py@@ -237,6 +237,51 @@ class TestPaddleOCRVLAdapter:finally:masking_utils.create_causal_mask = original+ def test_extract_single_passes_use_cache_true(self) -> None:+ """``_extract_single`` must pass ``use_cache=True`` to ``model.generate``.++ Upstream's generation_config.json ships ``use_cache=false``; without an+ explicit override KV-cache stays off and decode degrades to O(N^2).+ """+ import io++ import torch+ from PIL import Image as PILImage+ from sie_server.adapters.paddleocr_vl import PaddleOCRVLAdapter++ adapter = PaddleOCRVLAdapter("PaddlePaddle/PaddleOCR-VL-1.5")+ adapter._device = "cpu"++ mock_model = MagicMock()+ mock_model.dtype = torch.float32+ mock_model.generate.return_value = torch.zeros((1, 4), dtype=torch.long)+ adapter._model = mock_model++ mock_processor = MagicMock()+ mock_processor.apply_chat_template.return_value = ""+ mock_processor.decode.return_value = ""+ mock_processor.return_value = {+ "input_ids": torch.zeros((1, 1), dtype=torch.long),+ "attention_mask": torch.zeros((1, 1), dtype=torch.long),+ "pixel_values": torch.zeros((1, 1), dtype=torch.long),+ "image_grid_thw": torch.zeros((1, 1), dtype=torch.long),+ }+ adapter._processor = mock_processor++ buf = io.BytesIO()+ PILImage.new("RGB", (4, 4)).save(buf, format="JPEG")+ item = Item(images=[ImageInput(data=buf.getvalue(), format="jpeg")])++ adapter._extract_single(+ item,+ task="ocr",+ instruction=None,+ max_new_tokens=8,+ num_beams=1,+ )++ assert mock_model.generate.call_args.kwargs["use_cache"] is True+def test_yaml_config_loads(self) -> None:"""The shipped model YAML parses and resolves an adapter path."""import yamldiff --git a/packages/sie_server/tests/adapters/test_sentence_transformer.py b/packages/sie_server/tests/adapters/test_sentence_transformer.pyindex faf84bba7..b17b2c023 100644--- a/packages/sie_server/tests/adapters/test_sentence_transformer.py+++ b/packages/sie_server/tests/adapters/test_sentence_transformer.py@@ -80,6 +80,7 @@ class TestSentenceTransformerDenseAdapter:"""Encode returns dense embeddings."""mock_st_class.return_value = mock_st_modeladapter.load("cpu")+ adapter.warmup()items = [Item(text="hello"), Item(text="world")]output = adapter.encode(items, output_types=["dense"])@@ -88,7 +89,7 @@ class TestSentenceTransformerDenseAdapter:assert output.dense is not Noneassert output.dense[0].shape == (384,)- # First call is warmup during load, second is actual encode+ # First call is warmup, second is actual encodeassert mock_st_model.encode.call_count == 2call_args = mock_st_model.encode.call_argsassert call_args[0][0] == ["hello", "world"]diff --git a/packages/sie_server/tests/app/test_app_factory.py b/packages/sie_server/tests/app/test_app_factory.pyindex 5d59f5820..5af187e53 100644--- a/packages/sie_server/tests/app/test_app_factory.py+++ b/packages/sie_server/tests/app/test_app_factory.py@@ -1,5 +1,6 @@"""Tests for the FastAPI app factory."""+import loggingfrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -132,3 +133,67 @@ class TestPreloadModelsEnvRoundTrip:config.save_to_env_vars()restored = AppStateConfig.from_env_vars()assert restored.preload_models is None+++class TestConfigureTorchThreads:+ def test_default_uses_half_cpu_count(self, monkeypatch) -> None:+ monkeypatch.delenv("SIE_TORCH_NUM_THREADS", raising=False)+ monkeypatch.setattr("sie_server.app.app_factory.os.cpu_count", lambda: 8)+ set_n = MagicMock()+ set_interop = MagicMock()+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_threads", set_n)+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_interop_threads", set_interop)+ AppFactory._configure_torch_threads()+ set_n.assert_called_once_with(4)+ set_interop.assert_called_once_with(1)++ def test_default_floor_when_cpu_count_is_none(self, monkeypatch) -> None:+ monkeypatch.delenv("SIE_TORCH_NUM_THREADS", raising=False)+ monkeypatch.setattr("sie_server.app.app_factory.os.cpu_count", lambda: None)+ set_n = MagicMock()+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_threads", set_n)+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_interop_threads", MagicMock())+ AppFactory._configure_torch_threads()+ set_n.assert_called_once_with(2)++ def test_env_override_honored(self, monkeypatch) -> None:+ monkeypatch.setenv("SIE_TORCH_NUM_THREADS", "3")+ set_n = MagicMock()+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_threads", set_n)+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_interop_threads", MagicMock())+ AppFactory._configure_torch_threads()+ set_n.assert_called_once_with(3)++ def test_invalid_env_override_falls_back(self, monkeypatch, caplog) -> None:+ monkeypatch.setenv("SIE_TORCH_NUM_THREADS", "abc")+ monkeypatch.setattr("sie_server.app.app_factory.os.cpu_count", lambda: 8)+ set_n = MagicMock()+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_threads", set_n)+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_interop_threads", MagicMock())+ with caplog.at_level(logging.WARNING, logger="sie_server.app.app_factory"):+ AppFactory._configure_torch_threads()+ set_n.assert_called_once_with(4)+ assert any("not a positive integer" in r.message for r in caplog.records)++ def test_zero_env_override_falls_back(self, monkeypatch, caplog) -> None:+ monkeypatch.setenv("SIE_TORCH_NUM_THREADS", "0")+ monkeypatch.setattr("sie_server.app.app_factory.os.cpu_count", lambda: 8)+ set_n = MagicMock()+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_threads", set_n)+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_interop_threads", MagicMock())+ with caplog.at_level(logging.WARNING, logger="sie_server.app.app_factory"):+ AppFactory._configure_torch_threads()+ set_n.assert_called_once_with(4)+ assert any("not a positive integer" in r.message for r in caplog.records)++ def test_interop_runtime_error_is_swallowed(self, monkeypatch, caplog) -> None:+ monkeypatch.delenv("SIE_TORCH_NUM_THREADS", raising=False)+ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_threads", MagicMock())++ def _raise(_n: int) -> None:+ raise RuntimeError("parallel runtime already started")++ monkeypatch.setattr("sie_server.app.app_factory.torch.set_num_interop_threads", _raise)+ with caplog.at_level(logging.WARNING, logger="sie_server.app.app_factory"):+ AppFactory._configure_torch_threads() # must not raise+ assert any("set_num_interop_threads" in r.message for r in caplog.records)diff --git a/packages/sie_server/tests/conftest.py b/packages/sie_server/tests/conftest.pyindex 63d38127c..b52b3c789 100644--- a/packages/sie_server/tests/conftest.py+++ b/packages/sie_server/tests/conftest.py@@ -310,6 +310,11 @@ def sie_docker_server() -> Generator[str]:},"environment": {"HF_HOME": "/app/.cache/huggingface",+ # Propagate the deployment-env tag from the host (set to "ci" by+ # the GH workflow, "development" by `mise run serve`) into the+ # container so heartbeats from the dockerised sie-server don't+ # land in the "unknown" telemetry bucket.+ "SIE_DEPLOYMENT_ENV": os.environ.get("SIE_DEPLOYMENT_ENV", "development"),},}diff --git a/packages/sie_server/tests/test_all_models.py b/packages/sie_server/tests/test_all_models.pyindex 0320ff50d..6170af1f8 100644--- a/packages/sie_server/tests/test_all_models.py+++ b/packages/sie_server/tests/test_all_models.py@@ -844,6 +844,45 @@ def test_qwen_qwen3_reranker_4b_score() -> None:_assert_score("Qwen/Qwen3-Reranker-4B", [0.288818359375])+# =============================================================================+# Score (ColBERT / late-interaction MaxSim rerankers)+# -----------------------------------------------------------------------------+# Expected scores below are compared after casting both sides to float16+# (see _assert_score), so the literal values are fp16 golden values — not+# bit-exact bf16 outputs even when the adapter computes in bfloat16. A+# precision/device/CUDA-version change can shift every value at once;+# update them as a batch and bisect against a single trusted run.+# =============================================================================+++def test_answerdotai_answerai_colbert_small_v1_score() -> None:+ _assert_score("answerdotai/answerai-colbert-small-v1", [6.9140625])+++def test_colbert_ir_colbertv2_0_score() -> None:+ _assert_score("colbert-ir/colbertv2.0", [29.890625])+++def test_jinaai_jina_colbert_v2_score() -> None:+ _assert_score("jinaai/jina-colbert-v2", [27.953125])+++def test_lightonai_gte_moderncolbert_v1_score() -> None:+ _assert_score("lightonai/GTE-ModernColBERT-v1", [30.296875])+++def test_lightonai_reason_moderncolbert_score() -> None:+ _assert_score("lightonai/Reason-ModernColBERT", [29.578125])+++def test_mixedbread_ai_mxbai_colbert_large_v1_score() -> None:+ _assert_score("mixedbread-ai/mxbai-colbert-large-v1", [6.19140625])+++def test_mixedbread_ai_mxbai_edge_colbert_v0_32m_score() -> None:+ _assert_score("mixedbread-ai/mxbai-edge-colbert-v0-32m", [14.359375])++# =============================================================================# Extract models (text input - GLiNER / NLI classification)# =============================================================================diff --git a/packages/sie_server/tests/test_docker_integration.py b/packages/sie_server/tests/test_docker_integration.pyindex 6461c5023..89a179508 100644--- a/packages/sie_server/tests/test_docker_integration.py+++ b/packages/sie_server/tests/test_docker_integration.py@@ -146,8 +146,8 @@ class TestDockerGateway:assert response.status_code == 200def test_readiness_endpoint(self, sie_docker_gateway: str) -> None:- """Gateway Docker container responds to readiness probe."""+ """Workerless gateway is ready so scale-from-zero requests can reach it."""response = httpx.get(f"{sie_docker_gateway}/readyz", timeout=10.0)assert response.status_code == 200- data = response.json()- assert data["status"] == "ready"+ assert response.headers.get("content-type", "").startswith("text/plain")+ assert response.text == "ok"diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex 679f8fb99..4bfeafa75 100644--- a/packages/sie_ts_sdk/package.json+++ b/packages/sie_ts_sdk/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-sdk",- "version": "0.3.1",+ "version": "0.3.2","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.tsindex 79ddb092a..19da1e17e 100644--- a/packages/sie_ts_sdk/src/internal/parsing.ts+++ b/packages/sie_ts_sdk/src/internal/parsing.ts@@ -140,23 +140,41 @@ export async function throwIfModelLoadFailed(response: Response, model?: string)export async function handleError(response: Response, gpu?: string): Promise<never> {const { status } = response;- let errorBody: { code?: string; detail?: string } = {};- try {- errorBody = (await response.json()) as { code?: string; detail?: string };- } catch {- // Ignore JSON parsing errors- }+ // Prefer nested ``error`` / ``detail`` objects (gateway + FastAPI dict detail),+ // same as Python ``handle_error``. Legacy: string ``detail``, or top-level+ // ``message`` (e.g. gateway 202 provisioning body).+ const detail = await getErrorDetail(response.clone());- const code = errorBody.code ?? "UNKNOWN";- const message = errorBody.detail ?? response.statusText;+ let code: string | undefined;+ let message: string;++ if (detail) {+ const c = detail.code;+ code = typeof c === "string" ? c : undefined;+ const m = detail.message;+ message = typeof m === "string" ? m : JSON.stringify(detail);+ } else {+ try {+ const data = (await response.json()) as Record<string, unknown>;+ if (typeof data.detail === "string") {+ code = typeof data.code === "string" ? data.code : undefined;+ message = data.detail;+ } else if (typeof data.message === "string") {+ code = typeof data.code === "string" ? data.code : undefined;+ message = data.message;+ } else {+ code = typeof data.code === "string" ? data.code : undefined;+ message = response.statusText;+ }+ } catch {+ code = undefined;+ message = response.statusText;+ }+ }if (status === HTTP_ACCEPTED) {- const retryAfter = response.headers.get("Retry-After");- throw new ProvisioningError(- message,- gpu,- retryAfter ? Number.parseInt(retryAfter, 10) * 1000 : undefined,- );+ const retryAfter = getRetryAfter(response);+ throw new ProvisioningError(message, gpu, retryAfter);}if (status >= HTTP_CLIENT_ERROR_MIN && status <= HTTP_CLIENT_ERROR_MAX) {diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 403c3f419..5ae24e888 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.3.1"; // x-release-please-version+export const SDK_VERSION = "0.3.2"; // x-release-please-versiondiff --git a/packages/sie_ts_sdk/tests/internal.test.ts b/packages/sie_ts_sdk/tests/internal.test.tsindex fdeb40937..4bfe7f0da 100644--- a/packages/sie_ts_sdk/tests/internal.test.ts+++ b/packages/sie_ts_sdk/tests/internal.test.ts@@ -9,7 +9,7 @@*/import { describe, expect, it } from "vitest";-import { parseCapacityInfo, parseGpuParam } from "../src/internal/parsing.js";+import { handleError, parseCapacityInfo, parseGpuParam } from "../src/internal/parsing.js";import { computeBackoffWithJitter, getRetryAfter } from "../src/internal/retry.js";describe("Retry logic - exponential backoff with jitter", () => {@@ -225,6 +225,99 @@ describe("Real-world retry scenarios", () => {});});+describe("handleError (gateway / FastAPI bodies)", () => {+ it("reads nested FastAPI-style detail (gateway 4xx/5xx)", async () => {+ const res = new Response(+ JSON.stringify({+ detail: { code: "MODEL_NOT_FOUND", message: "Model 'x' not found" },+ }),+ { status: 404, headers: { "Content-Type": "application/json" } },+ );+ await expect(handleError(res)).rejects.toMatchObject({+ name: "RequestError",+ message: "Model 'x' not found",+ code: "MODEL_NOT_FOUND",+ statusCode: 404,+ });+ });++ it("reads top-level message for 202 provisioning (no detail object)", async () => {+ const res = new Response(+ JSON.stringify({+ status: "provisioning",+ gpu: "l4",+ bundle: "default",+ estimated_wait_s: 30,+ message: "No worker available for GPU type 'l4'. Provisioning in progress.",+ }),+ {+ status: 202,+ headers: { "Content-Type": "application/json", "Retry-After": "5" },+ },+ );+ await expect(handleError(res, "l4")).rejects.toMatchObject({+ name: "ProvisioningError",+ message: "No worker available for GPU type 'l4'. Provisioning in progress.",+ gpu: "l4",+ retryAfter: 5000,+ });+ });++ it("parses HTTP-date Retry-After for 202 provisioning", async () => {+ const retryAt = new Date(Date.now() + 60_000).toUTCString();+ const res = new Response(+ JSON.stringify({+ status: "provisioning",+ message: "Provisioning in progress.",+ }),+ {+ status: 202,+ headers: { "Content-Type": "application/json", "Retry-After": retryAt },+ },+ );++ try {+ await handleError(res, "l4");+ throw new Error("expected handleError to throw");+ } catch (err) {+ expect(err).toMatchObject({+ name: "ProvisioningError",+ message: "Provisioning in progress.",+ gpu: "l4",+ });+ expect((err as { retryAfter?: number }).retryAfter).toBeGreaterThan(0);+ expect((err as { retryAfter?: number }).retryAfter).toBeLessThanOrEqual(60_000);+ }+ });++ it("reads SDK-style error object (503)", async () => {+ const res = new Response(+ JSON.stringify({+ error: { code: "MODEL_LOADING", message: "Model is loading" },+ }),+ { status: 503, headers: { "Content-Type": "application/json" } },+ );+ await expect(handleError(res)).rejects.toMatchObject({+ name: "ServerError",+ message: "Model is loading",+ code: "MODEL_LOADING",+ statusCode: 503,+ });+ });++ it("supports legacy string detail", async () => {+ const res = new Response(JSON.stringify({ detail: "Not allowed" }), {+ status: 403,+ headers: { "Content-Type": "application/json" },+ });+ await expect(handleError(res)).rejects.toMatchObject({+ name: "RequestError",+ message: "Not allowed",+ statusCode: 403,+ });+ });+});+describe("Capacity info parsing", () => {it("should parse gateway health response", () => {const wireData = {diff --git a/pyproject.toml b/pyproject.tomlindex efc095944..ca01f033b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -48,10 +48,11 @@ dev = ["ipykernel>=7.1.0","python-hcl2>=7.3.1","pandas>=2.0",- "plotly>=5.0",+ "plotly>=6.1.1","statsmodels>=0.14","marimo>=0.20.4","modal>=0.73",+ "kaleido>=1.3.0",]benchview = ["datasets>=2.19,<4.0", # trust_remote_code support was removed in 4.0@@ -215,6 +216,9 @@ ignore = [][tool.ruff.lint.per-file-ignores]+"tools/loadtest_dashboard/scripts/*.py" = [+ "INP001", # JS project subdir; not a Python package+]"**/tests/**/*" = ["ANN", # Type annotations (tests don't need full typing)"ARG", # Unused function arguments (fixtures)diff --git a/uv.lock b/uv.lockindex 2dccf57ee..7ed19556a 100644--- a/uv.lock+++ b/uv.lock@@ -476,6 +476,20 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/db/8f/61959034484a4a7c527811f4721e75d02d653a35afb0b6054474d8185d4c/charset_normalizer-3.4.7-py3-none-any.whl", hash = "sha256:3dce51d0f5e7951f8bb4900c257dad282f49190fdbebecd4ba99bcc41fef404d", size = 61958 },]+[[package]]+name = "choreographer"+version = "1.3.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "logistro" },+ { name = "platformdirs" },+ { name = "simplejson" },+]+sdist = { url = "https://files.pythonhosted.org/packages/17/69/3058cd4f16d6b75c80e8f95e5b713d930526353ce294df9a7887453ba215/choreographer-1.3.0.tar.gz", hash = "sha256:6c44a0e48e9b37977344d40bfa5a9ed88575fe4bc0fd836771bf702bc24d6884", size = 48291 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/ba/6c/ff8bf52315064dbeb55cb5067e191120a5b2e58bb648d0d34cf7969dc2c2/choreographer-1.3.0-py3-none-any.whl", hash = "sha256:cea4cb739e4f61625e4b53888a8d3fa1d3bf73948b56753e460ab44da7d8d44f", size = 52622 },+]+[[package]]name = "chroma-haystack"version = "4.1.1"@@ -2232,6 +2246,21 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/e7/e7/80988e32bf6f73919a113473a604f5a8f09094de312b9d52b79c2df7612b/jupyter_core-5.9.1-py3-none-any.whl", hash = "sha256:ebf87fdc6073d142e114c72c9e29a9d7ca03fad818c5d300ce2adc1fb0743407", size = 29032 },]+[[package]]+name = "kaleido"+version = "1.3.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "choreographer" },+ { name = "logistro" },+ { name = "orjson" },+ { name = "packaging" },+]+sdist = { url = "https://files.pythonhosted.org/packages/e0/64/53eac73d31dbfc3310ee2e87bcac1ae7417427f0fbe3dd800eaf676db324/kaleido-1.3.0.tar.gz", hash = "sha256:5e0378a7475e98852773deeb6483dee91f8aa7b364dde7b5f2b3622cb468a3e6", size = 68938 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/9e/b9/a6d8bb7d228940f01885bd9f327ab7f9d366a9be775c4bf366bf9d9477ae/kaleido-1.3.0-py3-none-any.whl", hash = "sha256:52714dfd38e8f2a114831826200c40bb10d0ca0c11d4272f3f48ad499cd8f8ea", size = 55580 },+]+[[package]]name = "kiwisolver"version = "1.5.0"@@ -2530,6 +2559,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/2f/f5/d281ae0f79378a5a91f308ea9fdb9f9cc068fddd09629edc0725a5a8fde1/llvmlite-0.47.0-cp312-cp312-win_amd64.whl", hash = "sha256:f3079f25bdc24cd9d27c4b2b5e68f5f60c4fdb7e8ad5ee2b9b006007558f9df7", size = 38138692 },]+[[package]]+name = "logistro"+version = "2.0.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/08/90/bfd7a6fab22bdfafe48ed3c4831713cb77b4779d18ade5e248d5dbc0ca22/logistro-2.0.1.tar.gz", hash = "sha256:8446affc82bab2577eb02bfcbcae196ae03129287557287b6a070f70c1985047", size = 8398 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl", hash = "sha256:06ffa127b9fb4ac8b1972ae6b2a9d7fde57598bf5939cd708f43ec5bba2d31eb", size = 8555 },+]+[[package]]name = "loguru"version = "0.7.3"@@ -5113,6 +5151,7 @@ dev = [{ name = "docker" },{ name = "httpx" },{ name = "ipykernel" },+ { name = "kaleido" },{ name = "marimo" },{ name = "modal" },{ name = "pandas" },@@ -5158,10 +5197,11 @@ dev = [{ name = "docker", specifier = ">=7.1.0" },{ name = "httpx", specifier = ">=0.27" },{ name = "ipykernel", specifier = ">=7.1.0" },+ { name = "kaleido", specifier = ">=1.3.0" },{ name = "marimo", specifier = ">=0.20.4" },{ name = "modal", specifier = ">=0.73" },{ name = "pandas", specifier = ">=2.0" },- { name = "plotly", specifier = ">=5.0" },+ { name = "plotly", specifier = ">=6.1.1" },{ name = "pre-commit", specifier = "~=4.0" },{ name = "pydantic", specifier = ">=2.0" },{ name = "pytest", specifier = "~=8.0" },@@ -5179,7 +5219,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.3.1"+version = "0.3.2"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5212,7 +5252,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.3.1"+version = "0.3.2"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5289,7 +5329,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.3.1"+version = "0.3.2"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5361,7 +5401,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.3.1"+version = "0.3.2"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5386,7 +5426,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.3.1"+version = "0.3.2"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5411,7 +5451,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.3.1"+version = "0.3.2"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5438,7 +5478,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.3.1"+version = "0.3.2"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -5465,7 +5505,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.3.1"+version = "0.3.2"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -5492,7 +5532,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.3.1"+version = "0.3.2"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -5519,7 +5559,7 @@ requires-dist = [[[package]]name = "sie-qdrant"-version = "0.3.1"+version = "0.3.2"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -5542,7 +5582,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.3.1"+version = "0.3.2"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -5591,7 +5631,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.3.1"+version = "0.3.2"source = { editable = "packages/sie_server" }dependencies = [{ name = "docling" },@@ -5704,7 +5744,7 @@ dev = [][[package]]name = "sie-weaviate"-version = "0.3.1"+version = "0.3.2"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },@@ -5725,6 +5765,26 @@ requires-dist = [{ name = "weaviate-client", specifier = ">=4.16" },]+[[package]]+name = "simplejson"+version = "4.1.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/0e/2a/54837395a3487c725669428d513293612a48d82b95a0642c936932e5d898/simplejson-4.1.1.tar.gz", hash = "sha256:c08eb9f7a90f77ae470e19a07472e9a79ebc0d1c2315d86a72767665bd5ba79f", size = 118860 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/60/25/e90998fe8e480eb43b966c09e835379887d427567ebd496563d3b1e16b19/simplejson-4.1.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:19040a17154dc03d289bab68d73ce0a6a0be01de30c584bbdd93490bead14b22", size = 112414 },+ { url = "https://files.pythonhosted.org/packages/9c/a0/abd4785f36c3400f1fbb21f517be39295a750a714f04b7ee175adf6ef580/simplejson-4.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a94ebaecdbaa80d9551a3ec6bf0c9302fc8b53ab6c1b2bfd498a1df4cb28158d", size = 91120 },+ { url = "https://files.pythonhosted.org/packages/b8/78/fc060d2e3b13c6ec59288574b8efac64075e316b2afba4396a56b2422f78/simplejson-4.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:67341c95c0a168ab4a6d1e807e50463f1c8da932c3286d81e201266c427061fa", size = 91055 },+ { url = "https://files.pythonhosted.org/packages/0c/b6/156a8de1e1b47694f0e7de6675866936608d45dc68388fd017d36f8693be/simplejson-4.1.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:45ec18e337fec538b7e902d489505c450b2454653d1290f3f50385e6fd8aa607", size = 190297 },+ { url = "https://files.pythonhosted.org/packages/86/1c/e4d0eab695be3eb21d0f46bce820752031f03e7113f9c80a9b3c73ee7157/simplejson-4.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:820c69a4710400e9b248d5670647d60be58824369282d3925e516b3ff1a7cd82", size = 187002 },+ { url = "https://files.pythonhosted.org/packages/76/0e/7f5a59d29426b062d5928fb88b403c3f797129d53be7102f955dbe51aa44/simplejson-4.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2e708d373a10e4378ef2d59f8361850c7150fd907ed49efe49bc5492160476d1", size = 195146 },+ { url = "https://files.pythonhosted.org/packages/78/18/9943db224dd4d5fa3c090c3e56a94c37b254338c83995ec5680285111c40/simplejson-4.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:980fc33353f81fd12d8c49d44f8c2760d1dc8192285e627c5180d141035b228a", size = 183931 },+ { url = "https://files.pythonhosted.org/packages/c2/08/9a690da9a766161c06c627d805362cf159f1abe480969372b2897649b955/simplejson-4.1.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:de2ed102fff88dacf543699f53ee3a533cc11539a39baa176b7e09dd783069d6", size = 192228 },+ { url = "https://files.pythonhosted.org/packages/05/88/bd8aad36b451ffb0e0a3f721d695a88befa6d1ac7d1e02ae788ca7ff4029/simplejson-4.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2785ff8edc0e28bf773a32543a6bbed46351453c997b3f6709c744e3c2f7eabb", size = 187808 },+ { url = "https://files.pythonhosted.org/packages/04/ee/14f91db0d1f481533b651dafbf8cd0da088d9817f7af30c68f7f19f9c847/simplejson-4.1.1-cp312-cp312-win32.whl", hash = "sha256:2e0d5ead6d14610467ec356ec1f6b5d8a56aa216abaad8d41c8b873b16cf313f", size = 88512 },+ { url = "https://files.pythonhosted.org/packages/b9/c4/90de06b2d8737c68c05ff9274113f854dbf6a5f28b7a955212111672cb57/simplejson-4.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:63a5451f557d6be48a231bae932458655c620902b868170b2f1c8afed496f6b4", size = 90748 },+ { url = "https://files.pythonhosted.org/packages/ce/6a/8b74c52ffd33dbbde00fe7251fee6a0acdc8cea33f7a43805aed258fb79b/simplejson-4.1.1-py3-none-any.whl", hash = "sha256:2ce92b3748f02423e26d2bfb636fb9d7a8f67c8f5854dcae69d350d123b2eee2", size = 69195 },+]+[[package]]name = "six"version = "1.17.0"