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.5.0
github-actions[bot]5959dab91125
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6e96f565b..2af769877 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,40 @@# Changelog+## v0.5.0++- chore(main): release 0.5.0+- docs(helm): clarify README pool example is illustrative, not tester-specific+- fix(helm): fail-fast on missing/invalid bundle replica bounds+- chore(helm): address PR #1205 review feedback+- fix(helm): preserve gateway metrics scrape labels+- feat(helm)!: split worker pools into pool × bundles schema+- fix(gateway): expose unauthenticated metrics scrape port+- chore(openapi): regenerate spec for code/sql/guard capability fields+- fix(models): drop unsupported ebnf advertisement + restore guardian a100 guard threshold+- feat(models): surface code/sql/guard capabilities; resolve job aliases in configs/resolve+- fix(guard): robust verdict thresholding, logprob hygiene, decoded-token logprobs+- feat(tester-cluster): add sglang worker pool for generative models+- fix(sie_server): honor params.instruction in Florence-2 extract (#1053)+- fix(helm): use sidecar binary for image pre-pull+- chore: remove agent-jobs runbook, ADR 0001, and m5-planning docs+- fix(guard): reject multi-candidate sampling + keep logprobs consistent on rewrite+- feat(guard): P(unsafe) logprob threshold for CHECK POLICY precision (#1187)+- docs(ops): agent-jobs prod-readiness runbook + opt-in model-alias deploy config+- fix(review): address #1184 review comments + restore dropped A/B fix+- bench(sql): grammar A/B + SQLCoder native-template measured on Spider+- test(gateway): end-to-end precision routing through resolve_model_and_bundle+- test(gateway): prove a model routes across two precision bundles+- feat(gateway): job aliases can carry a precision bundle (SQL->BF16 routing)+- docs(27b): flag FP8 SQL regression on sql cap + clarify targets are documentary+- feat(27b): measure Qwen3.6-27B on code/SQL/tools; advertise code+sql+- feat(guard): CHECK POLICY content-moderation model + ToxicChat F1 eval+- bench(sql): measured Spider execution accuracy + anchored floor; SQLCoder serve-validated+- feat(code): point model="code" at the measured model; xgrammar-validate SQL grammar+- feat(sql): onboard SQLCoder (Defog) config + starter SQL grammar artifact+- feat(bench): add Spider text-to-SQL execution-accuracy eval + model="sql" alias+- fix(review): address PR feedback on the code-eval+- feat(server,gateway): advertise code capability + model="code" alias+## v0.4.2- chore(main): release 0.4.2diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex 67a43d45f..e1e29b383 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.4.2 # x-release-please-version-appVersion: v0.4.2 # x-release-please-version+version: 0.5.0 # x-release-please-version+appVersion: v0.5.0 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 78d9bb44b..2918de67a 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -132,15 +132,33 @@ See `values.yaml` for all options. Key settings:**Important**: All worker pools are disabled by default. You must explicitly enablethe pools you need in your values override.+The values below are an illustrative shape; concrete per-cluster sizes+live in each cluster's own values file (e.g. the tester cluster's+rtx6000 default bundle scales 3–10 — see+`deploy/terraform/aws/internal-examples/tester-cluster/DEPLOY.md`).+```yaml# Worker pool configuration (must explicitly enable pools)# Pool naming: <machineProfile> (e.g. l4, a100-40gb, cpu)+# Each pool can serve multiple bundles. Each (pool, bundle) renders its+# own StatefulSet + ScaledObject named worker-<pool>-<bundle>.workers:pools:l4:- enabled: true # Enable this pool (disabled by default)- minReplicas: 0 # Scale to zero- maxReplicas: 10+ enabled: true # Enable this pool (disabled by default)+ bundles:+ default:+ minReplicas: 0 # Scale to zero+ maxReplicas: 10+ rtx6000:+ enabled: true+ bundles:+ default: # embedding/rerank baseline+ minReplicas: 1+ maxReplicas: 5+ sglang: # generation, scale-from-zero on same GPUs+ minReplicas: 0+ maxReplicas: 5# Gateway configurationgateway:@@ -152,6 +170,41 @@ autoscaling:cooldownPeriod: 600 # 10 min before scale-down```+### Upgrading from the legacy single-bundle pool schema++Releases up to and including 0.4.x used a flat schema where each pool+declared a single `bundle:` plus `minReplicas:`/`maxReplicas:` at the+pool level. That shape is no longer accepted — `bundles:` is required+(see schema docs in `values.yaml`).++The rename also changes resource names from `worker-<pool>` to+`worker-<pool>-<bundle>` for StatefulSets, KEDA ScaledObjects, PDBs, and+the image-prepull DaemonSet. `helm upgrade` creates the new resources+but does not delete the old ones. The legacy resources are+distinguishable from the new ones by the absence of the+`sie.superlinked.com/bundle` label:++```bash+NS=sie # release namespace++# Pre-refactor worker family (no bundle label) — delete before/after upgrade+kubectl -n "$NS" delete statefulset,pdb,daemonset \+ -l 'app.kubernetes.io/component=worker,!sie.superlinked.com/bundle'++# Pre-refactor image-prepull DaemonSets+kubectl -n "$NS" delete daemonset \+ -l 'app.kubernetes.io/component=image-prepull,!sie.superlinked.com/bundle'++# Pre-refactor KEDA ScaledObjects (the chart's apply Job only creates;+# it never deletes obsolete entries)+kubectl -n "$NS" delete scaledobject \+ -l 'app.kubernetes.io/component=worker,!sie.superlinked.com/bundle'+```++Run these once per cluster after the upgrade settles. Leftover+ScaledObjects will keep trying to scale deleted StatefulSets and spam+KEDA logs; leftover PDBs will block node drains.+## IngressEnable the Ingress with `ingress.enabled=true` and route traffic to the gateway bydiff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex d0c48d61c..bd5592d76 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -176,6 +176,14 @@ Gateway service name (used for worker discovery){{- printf "%s-gateway" $fullname }}{{- end }}+{{/*+Gateway metrics service name (ClusterIP-only ServiceMonitor scrape target)+Budget: prefix (≤47) + "-gateway-metrics" (16) = 63 (DNS-1123 label max).+*/}}+{{- define "sie-cluster.gateway.metricsServiceName" -}}+{{- printf "%s-gateway-metrics" (include "sie-cluster.fullname" . | trunc 47 | trimSuffix "-") }}+{{- end }}+{{/*In-cluster URL used by workers to ask the gateway whether they are admittedto pull from their configured queue pool.diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex b50102250..1039c55c7 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -118,6 +118,11 @@ spec:- name: httpcontainerPort: 8080protocol: TCP+ {{- if .Values.serviceMonitor.enabled }}+ - name: gateway-metrics+ containerPort: 9090+ protocol: TCP+ {{- end }}env:# Kubernetes-based worker discovery- name: SIE_GATEWAY_KUBERNETES@@ -148,6 +153,14 @@ spec:configMapKeyRef:name: {{ include "sie-cluster.fullname" . }}-gpu-configkey: gpu-aliases+ {{- with .Values.gateway.modelAliases }}+ # Job/friendly model aliases (e.g. {"sql":"bf16-27b:/Qwen/Qwen3.6-27B"}).+ # A bundle-qualified target routes that job to a precision/profile+ # bundle (e.g. route SQL to a BF16 27B variant). Opt-in: only+ # rendered when gateway.modelAliases is set.+ - name: SIE_GATEWAY_MODEL_ALIASES+ value: {{ toJson . | quote }}+ {{- end }}# Machine profiles (JSON format for pool validation and routing)- name: SIE_GATEWAY_MACHINE_PROFILESvalueFrom:@@ -171,6 +184,12 @@ spec:name: {{ .Values.gateway.auth.tokenSecretName }}key: {{ .Values.gateway.auth.tokenSecretKey }}{{- end }}+ {{- if .Values.serviceMonitor.enabled }}+ # Dedicated metrics listener. Keeps the public 8080 Service auth-gated+ # while Prometheus scrapes a ClusterIP-only Service without a bearer token.+ - name: SIE_METRICS_PORT+ value: "9090"+ {{- end }}{{- if .Values.nats.enabled }}- name: SIE_NATS_URLvalue: {{ .Values.nats.url | default (printf "nats://%s-nats:4222" .Release.Name) | quote }}diff --git a/deploy/helm/sie-cluster/templates/gateway-service.yaml b/deploy/helm/sie-cluster/templates/gateway-service.yamlindex c2fd095d4..3bf440d5a 100644--- a/deploy/helm/sie-cluster/templates/gateway-service.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-service.yaml@@ -18,3 +18,24 @@ spec:protocol: TCPselector:{{- include "sie-cluster.gateway.selectorLabels" . | nindent 4 }}+{{- if .Values.serviceMonitor.enabled }}+---+apiVersion: v1+kind: Service+metadata:+ name: {{ include "sie-cluster.gateway.metricsServiceName" . }}+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.labels" . | nindent 4 }}+ app.kubernetes.io/component: gateway-metrics+ sie.superlinked.com/prometheus-job: sie-gateway+spec:+ type: ClusterIP+ ports:+ - name: gateway-metrics+ port: 9090+ targetPort: gateway-metrics+ protocol: TCP+ selector:+ {{- include "sie-cluster.gateway.selectorLabels" . | nindent 4 }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml b/deploy/helm/sie-cluster/templates/keda-scaledobject.yamlindex 26d290f0e..a361df4f4 100644--- a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml+++ b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml@@ -76,16 +76,18 @@ metadata:helm.sh/hook-delete-policy: before-hook-creationhelm.sh/hook-weight: "1"data:- # Worker pool ScaledObjects (one per enabled pool)+ # Worker pool ScaledObjects (one per enabled (pool, bundle)){{- range $poolName, $pool := .Values.workers.pools }}{{- if $pool.enabled }}-{{- $bundle := default $root.Values.workers.common.bundle $pool.bundle }}{{- $machineProfile := default $pool.gpuType $pool.machineProfile }}- scaledobject-worker-{{ $poolName }}.yaml: |+{{- range $bundleName, $bundleCfg := $pool.bundles }}+{{- if dig "enabled" true $bundleCfg }}+{{- $bundle := $bundleName }}+ scaledobject-worker-{{ $poolName }}-{{ $bundleName }}.yaml: |apiVersion: keda.sh/v1alpha1kind: ScaledObjectmetadata:- name: {{ include "sie-cluster.fullname" $root }}-worker-{{ $poolName }}-scaler+ name: {{ include "sie-cluster.fullname" $root }}-worker-{{ $poolName }}-{{ $bundleName }}-scalernamespace: {{ include "sie-cluster.namespace" $root }}labels:{{- include "sie-cluster.worker.labels" $root | nindent 8 }}@@ -94,9 +96,9 @@ data:spec:scaleTargetRef:kind: StatefulSet- name: {{ include "sie-cluster.fullname" $root }}-worker-{{ $poolName }}- minReplicaCount: {{ $pool.minReplicas }}- maxReplicaCount: {{ $pool.maxReplicas }}+ name: {{ include "sie-cluster.fullname" $root }}-worker-{{ $poolName }}-{{ $bundleName }}+ minReplicaCount: {{ $bundleCfg.minReplicas }}+ maxReplicaCount: {{ $bundleCfg.maxReplicas }}pollingInterval: {{ $root.Values.autoscaling.pollingInterval }}cooldownPeriod: {{ $root.Values.autoscaling.cooldownPeriod }}fallback:@@ -129,21 +131,21 @@ data:- type: prometheusmetadata:serverAddress: {{ $promAddr }}- metricName: sie_gateway_pending_demand_{{ $poolName }}+ metricName: sie_gateway_pending_demand_{{ $poolName }}_{{ $bundleName }}query: sum(sie_gateway_pending_demand{machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)threshold: "1"activationThreshold: "0"- type: prometheusmetadata:serverAddress: {{ $promAddr }}- metricName: sie_gateway_queue_depth_{{ $poolName }}+ metricName: sie_gateway_queue_depth_{{ $poolName }}_{{ $bundleName }}query: sum(sie_gateway_worker_queue_depth{machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)threshold: {{ $root.Values.autoscaling.queueDepthThreshold | quote }}activationThreshold: {{ $root.Values.autoscaling.queueDepthActivation | quote }}- type: prometheusmetadata:serverAddress: {{ $promAddr }}- metricName: sie_gateway_active_lease_gpus_{{ $poolName }}+ metricName: sie_gateway_active_lease_gpus_{{ $poolName }}_{{ $bundleName }}query: sum(sie_gateway_active_lease_gpus{machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)threshold: "1"activationThreshold: "0"@@ -184,6 +186,8 @@ data:threshold: "1"activationThreshold: "0"{{- end }}+{{- end }}+{{- end }}{{- end }}# Gateway ScaledObjectscaledobject-gateway.yaml: |diff --git a/deploy/helm/sie-cluster/templates/servicemonitor.yaml b/deploy/helm/sie-cluster/templates/servicemonitor.yamlindex d5943e8ee..1f44c44d2 100644--- a/deploy/helm/sie-cluster/templates/servicemonitor.yaml+++ b/deploy/helm/sie-cluster/templates/servicemonitor.yaml@@ -19,14 +19,16 @@ metadata:{{- toYaml . | nindent 4 }}{{- end }}spec:+ jobLabel: sie.superlinked.com/prometheus-jobselector:matchLabels:- {{- include "sie-cluster.gateway.selectorLabels" . | nindent 6 }}+ {{- include "sie-cluster.selectorLabels" . | nindent 6 }}+ app.kubernetes.io/component: gateway-metricsnamespaceSelector:matchNames:- {{ include "sie-cluster.namespace" . }}endpoints:- - port: http+ - port: gateway-metricsinterval: {{ .Values.serviceMonitor.interval }}scrapeTimeout: {{ .Values.serviceMonitor.scrapeTimeout }}path: /metricsdiff --git a/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml b/deploy/helm/sie-cluster/templates/worker-image-prepull.yamlindex 38abaa398..d33a7412d 100644--- a/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml+++ b/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml@@ -2,37 +2,42 @@{{- if $root.Values.workers.common.imagePrepull.enabled }}{{- range $poolName, $pool := .Values.workers.pools }}{{- if $pool.enabled }}-{{- $bundle := default $root.Values.workers.common.bundle $pool.bundle }}-{{- /* See worker-statefulset.yaml for the imageBundle rationale. */ -}}-{{- $imageBundle := default $bundle (default $root.Values.workers.common.imageBundle $pool.imageBundle) }}{{- $platform := default $root.Values.workers.common.platform $pool.platform }}-{{- $imageTag := default $root.Chart.AppVersion $root.Values.workers.common.image.tag }}-{{- $workerImage := printf "%s:%s-%s-%s" $root.Values.workers.common.image.repository $imageTag $platform $imageBundle }}{{- $rs := $root.Values.workers.common.workerSidecar }}{{- $rsTag := default $root.Chart.AppVersion $rs.image.tag }}{{- $rsImage := printf "%s:%s" $rs.image.repository $rsTag }}+{{- range $bundleName, $bundleCfg := $pool.bundles }}+{{- if dig "enabled" true $bundleCfg }}+{{- $bundle := $bundleName }}+{{- /* See worker-statefulset.yaml for the imageBundle rationale. */ -}}+{{- $imageBundle := default $bundle $bundleCfg.imageBundle }}+{{- $imageTag := default $root.Chart.AppVersion $root.Values.workers.common.image.tag }}+{{- $workerImage := printf "%s:%s-%s-%s" $root.Values.workers.common.image.repository $imageTag $platform $imageBundle }}---apiVersion: apps/v1kind: DaemonSetmetadata:- name: {{ include "sie-cluster.fullname" $root }}-image-prepull-{{ $poolName }}+ name: {{ include "sie-cluster.fullname" $root }}-image-prepull-{{ $poolName }}-{{ $bundleName }}namespace: {{ include "sie-cluster.namespace" $root }}labels:{{- include "sie-cluster.labels" $root | nindent 4 }}app.kubernetes.io/component: image-prepullsie.superlinked.com/pool: {{ $poolName | quote }}+ sie.superlinked.com/bundle: {{ $bundleName | quote }}spec:selector:matchLabels:{{- include "sie-cluster.selectorLabels" $root | nindent 6 }}app.kubernetes.io/component: image-prepullsie.superlinked.com/pool: {{ $poolName | quote }}+ sie.superlinked.com/bundle: {{ $bundleName | quote }}template:metadata:labels:{{- include "sie-cluster.selectorLabels" $root | nindent 8 }}app.kubernetes.io/component: image-prepullsie.superlinked.com/pool: {{ $poolName | quote }}+ sie.superlinked.com/bundle: {{ $bundleName | quote }}spec:{{- include "sie-cluster.imagePullSecrets" $root | nindent 6 }}automountServiceAccountToken: false@@ -53,7 +58,7 @@ spec:- name: pull-sie-worker-sidecar-imageimage: {{ $rsImage }}imagePullPolicy: {{ $rs.image.pullPolicy }}- command: ["true"]+ command: ["/sie-server-sidecar", "--version"]resources:requests:cpu: "1m"@@ -98,3 +103,5 @@ spec:{{- end }}{{- end }}{{- end }}+{{- end }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/worker-pdb.yaml b/deploy/helm/sie-cluster/templates/worker-pdb.yamlindex 0f0dd3361..e1e5297f5 100644--- a/deploy/helm/sie-cluster/templates/worker-pdb.yaml+++ b/deploy/helm/sie-cluster/templates/worker-pdb.yaml@@ -1,20 +1,26 @@{{- $root := . -}}{{- range $poolName, $pool := .Values.workers.pools }}{{- if $pool.enabled }}+{{- range $bundleName, $bundleCfg := $pool.bundles }}+{{- if dig "enabled" true $bundleCfg }}---apiVersion: policy/v1kind: PodDisruptionBudgetmetadata:- name: {{ include "sie-cluster.fullname" $root }}-worker-{{ $poolName }}+ name: {{ include "sie-cluster.fullname" $root }}-worker-{{ $poolName }}-{{ $bundleName }}namespace: {{ include "sie-cluster.namespace" $root }}labels:{{- include "sie-cluster.worker.labels" $root | nindent 4 }}sie.superlinked.com/pool: {{ $poolName | quote }}+ sie.superlinked.com/bundle: {{ $bundleName | quote }}spec:maxUnavailable: 1selector:matchLabels:{{- include "sie-cluster.worker.selectorLabels" $root | nindent 6 }}sie.superlinked.com/pool: {{ $poolName | quote }}+ sie.superlinked.com/bundle: {{ $bundleName | quote }}+{{- end }}+{{- end }}{{- end }}{{- end }}diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex cfd5f9ebb..a0a5ad713 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -18,21 +18,35 @@ fast at render time.{{- end }}{{- range $poolName, $pool := .Values.workers.pools }}{{- if $pool.enabled }}-{{- $bundle := default $root.Values.workers.common.bundle $pool.bundle }}+{{- if not $pool.bundles }}+{{- fail (printf "workers.pools.%s: missing required `bundles:` map. Define at least one bundle under the pool (e.g. `bundles: { default: { minReplicas: 0, maxReplicas: 1 } }`)." $poolName) }}+{{- end }}+{{- $platform := default $root.Values.workers.common.platform $pool.platform }}+{{- $machineProfile := default $pool.gpuType $pool.machineProfile }}+{{- $queuePool := default (default "default" $root.Values.workers.common.queuePool) $pool.queuePool }}+{{- range $bundleName, $bundleCfg := $pool.bundles }}+{{- if dig "enabled" true $bundleCfg }}+{{- if not (hasKey $bundleCfg "minReplicas") }}+{{- fail (printf "workers.pools.%s.bundles.%s: missing required `minReplicas`." $poolName $bundleName) }}+{{- end }}+{{- if not (hasKey $bundleCfg "maxReplicas") }}+{{- fail (printf "workers.pools.%s.bundles.%s: missing required `maxReplicas`." $poolName $bundleName) }}+{{- end }}+{{- if lt (int $bundleCfg.maxReplicas) (int $bundleCfg.minReplicas) }}+{{- fail (printf "workers.pools.%s.bundles.%s: `maxReplicas` (%d) must be >= `minReplicas` (%d)." $poolName $bundleName (int $bundleCfg.maxReplicas) (int $bundleCfg.minReplicas)) }}+{{- end }}+{{- $bundle := $bundleName }}{{- /* imageBundle decouples the image-tag suffix from the logical bundle name.- Defaults to $bundle, but pools whose logical bundle has no dedicated+ Defaults to $bundle, but bundles whose logical name has no dedicatedDocker image (e.g. `sglang-embedding`, which shares deps and image with`sglang`) set this to the bundle whose image they reuse. Labels, envvars, --bundle flag, and metrics still use $bundle. */ -}}-{{- $imageBundle := default $bundle (default $root.Values.workers.common.imageBundle $pool.imageBundle) }}-{{- $platform := default $root.Values.workers.common.platform $pool.platform }}-{{- $machineProfile := default $pool.gpuType $pool.machineProfile }}-{{- $queuePool := default (default "default" $root.Values.workers.common.queuePool) $pool.queuePool }}+{{- $imageBundle := default $bundle $bundleCfg.imageBundle }}---apiVersion: apps/v1kind: StatefulSetmetadata:- name: {{ include "sie-cluster.fullname" $root }}-worker-{{ $poolName }}+ name: {{ include "sie-cluster.fullname" $root }}-worker-{{ $poolName }}-{{ $bundleName }}namespace: {{ include "sie-cluster.namespace" $root }}labels:{{- include "sie-cluster.worker.labels" $root | nindent 4 }}@@ -42,12 +56,13 @@ metadata:sie.superlinked.com/pool: {{ $poolName | quote }}spec:serviceName: {{ include "sie-cluster.worker.serviceName" $root }}- replicas: {{ $pool.minReplicas }}+ replicas: {{ $bundleCfg.minReplicas }}podManagementPolicy: Parallelselector:matchLabels:{{- include "sie-cluster.worker.selectorLabels" $root | nindent 6 }}sie.superlinked.com/pool: {{ $poolName | quote }}+ sie.superlinked.com/bundle: {{ $bundle | quote }}template:metadata:labels:@@ -186,6 +201,9 @@ spec:{{- with $root.Values.workers.common.extraEnv }}{{- toYaml . | nindent 12 }}{{- end }}+ {{- with $bundleCfg.extraEnv }}+ {{- toYaml . | nindent 12 }}+ {{- end }}lifecycle:preStop:exec:@@ -459,7 +477,7 @@ spec:{{- toYaml . | nindent 8 }}{{- end }}affinity:- # Prefer spreading across nodes+ # Prefer spreading same-bundle workers across nodespodAntiAffinity:preferredDuringSchedulingIgnoredDuringExecution:- weight: 100@@ -468,6 +486,7 @@ spec:matchLabels:{{- include "sie-cluster.worker.selectorLabels" $root | nindent 20 }}sie.superlinked.com/pool: {{ $poolName | quote }}+ sie.superlinked.com/bundle: {{ $bundle | quote }}topologyKey: kubernetes.io/hostnamevolumes:# Shared memory for PyTorch DataLoader@@ -489,3 +508,5 @@ spec:{{- end }}{{- end }}{{- end }}+{{- end }}+{{- end }}diff --git a/deploy/helm/sie-cluster/values-aws.yaml b/deploy/helm/sie-cluster/values-aws.yamlindex 9df32e259..603d7df2e 100644--- a/deploy/helm/sie-cluster/values-aws.yaml+++ b/deploy/helm/sie-cluster/values-aws.yaml@@ -115,11 +115,8 @@ workers:# AWS g6.xlarge pool (NVIDIA L4)l4:enabled: true- minReplicas: 0- maxReplicas: 10machineProfile: l4gpuType: nvidia-l4- bundle: default# No GCP-specific node selectornodeSelector: {}gpu:@@ -136,6 +133,10 @@ workers:- key: nvidia.com/gpuoperator: Existseffect: NoSchedule+ bundles:+ default:+ minReplicas: 0+ maxReplicas: 10# ServiceAccount — Helm manages creation; IRSA annotation must be injected at deploy time.# NAMING CONTRACT: name must match module.sie_irsa_role namespace_service_accountsdiff --git a/deploy/helm/sie-cluster/values-gke.yaml b/deploy/helm/sie-cluster/values-gke.yamlindex 1f12ce21e..ced220100 100644--- a/deploy/helm/sie-cluster/values-gke.yaml+++ b/deploy/helm/sie-cluster/values-gke.yaml@@ -125,11 +125,8 @@ workers:# GKE L4 pool (spot) — enable default bundlel4:enabled: true- minReplicas: 0- maxReplicas: 10machineProfile: l4gpuType: l4- bundle: defaultnodeSelector:cloud.google.com/gke-accelerator: nvidia-l4gpu:@@ -146,6 +143,10 @@ workers:- key: nvidia.com/gpuoperator: Existseffect: NoSchedule+ bundles:+ default:+ minReplicas: 0+ maxReplicas: 10# ServiceAccount — Helm manages creation; Workload Identity annotation injected at deploy time.# NAMING CONTRACT: name must match Terraform's Workload Identity bindingdiff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 4bc51deda..4844f3794 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -129,6 +129,15 @@ config:# config deltas. It does not own config persistence or writes;# POST /v1/configs/models is not registered on the gateway (axum returns 405).gateway:+ # -- Job/friendly model aliases → canonical model id, optionally bundle-+ # qualified. Maps a request like `model: "sql"` to a real model, and a+ # `bundle:/org/model` target pins a precision/profile bundle (e.g. route SQL+ # to a BF16 27B variant that avoids the FP8 SQL-accuracy regression). Empty by+ # default (the gateway's built-in code/sql/guard aliases still apply). Example:+ # modelAliases:+ # sql: "bf16-27b:/Qwen/Qwen3.6-27B"+ modelAliases: {}+# -- Number of gateway replicas (default 1; bump to 2+ for HA).# Also used as KEDA's `minReplicaCount` floor (see# templates/keda-scaledobject.yaml). The gateway is stateless on the@@ -318,18 +327,6 @@ workers:# -- Models to preload on startup (empty = lazy loading)preloadModels: []- # -- Bundle to use (default)- bundle: default-- # -- Image-tag bundle suffix override. Set this only when the logical- # `bundle` has no dedicated Docker image and reuses another bundle's- # image. Example: `sglang-embedding` shares deps and image with- # `sglang` (lockstep deps enforced by tests/test_bundles.py), so pools- # whose logical bundle is `sglang-embedding` set `imageBundle: sglang`- # to pull the built image. When unset, falls back to `bundle`. Labels,- # env vars, `--bundle` flag, and metrics still reflect `bundle`.- imageBundle: ""-# -- Python ModelWorker passthrough mode. When `true` (and the Rust# sidecar is enabled), the Python adapter process bypasses its internal# BatchFormer / FCFS / adaptive controller; every IPC frame from@@ -579,47 +576,51 @@ workers:# WorkerGroup naming convention: <machineProfile> (e.g. l4, a100-40gb, cpu).# All pools scale to zero by default; enable the ones you need.#- # Per-pool keys (alphabetical, with defaults):- # bundle: string. Overrides workers.common.bundle. Required to- # match a real bundle in sie_config; otherwise the- # sidecar refuses to start.- # enabled: bool. Skip rendering when false.+ # Schema (pool = GPU/node class, bundles = workloads served on it):+ #+ # Pool-level keys (shared across bundles on this hardware):+ # enabled: bool. Skip rendering the whole pool when false.# gpu.count: int. 0 disables nvidia.com/gpu request on the pod.# gpu.product: string. nvidia.com/gpu.product node-label match.# gpuType: short label (l4, a100-40gb, cpu, …) used by the- # gateway for routing/metrics. Doubles as the- # statefulset suffix.+ # gateway for routing/metrics.# machineProfile: long label used by KEDA scalers + Prometheus.- # maxReplicas: KEDA upper bound.- # minReplicas: baseline replicas (0 = scale-to-zero).# nodeSelector: map. Merged with workers.common.nodeSelector.# platform: Optional override (e.g. "cpu"). Used as the# image-tag suffix for the worker image# (e.g. `<repo>:<tag>-cpu-<bundle>`),# NOT propagated to a pod env var.+ # queuePool: string. Optional override of common.queuePool.# resources: requests/limits for the Python ``worker``# container (the GPU-bound forward-pass server).+ # runtimeClassName: Optional override of common.runtimeClassName.# tolerations: extra tolerations on top of the chart defaults.#- # NOTE: a stray ``engine`` key on a pool is silently ignored by- # this chart (only ``pytorch``-style pods are rendered).+ # bundles: map keyed by bundle name (matches a bundle in sie_config;+ # otherwise the sidecar refuses to start). Per-bundle keys:+ # enabled: bool, default true. Skip this bundle on this pool.+ # imageBundle: string. Optional image-tag bundle suffix override.+ # Set only when the logical bundle reuses another+ # bundle's image (e.g. `sglang-embedding` -> `sglang`).+ # extraEnv: list. Extra env vars on the ``worker`` container.+ # Rendered after workers.common.extraEnv so a+ # bundle-level entry wins on duplicate names.+ # maxReplicas: KEDA upper bound.+ # minReplicas: baseline replicas (0 = scale-to-zero).+ #+ # Each (pool, bundle) renders one StatefulSet + KEDA ScaledObject ++ # PDB + image-prepull DaemonSet, named worker-{pool}-{bundle}.pools:# L4 GPUl4:enabled: false- # -- Minimum replicas (0 for scale-to-zero)- minReplicas: 0- # -- Maximum replicas- maxReplicas: 10# -- Machine profile name (key from machineProfiles section)# Used for routing, metrics, and KEDA scalingmachineProfile: l4# -- GPU type label for routing (short form used by gateway)gpuType: l4- # -- Bundle to use (overrides common.bundle if set)- bundle: default# -- Optional runtime class override for this pool# runtimeClassName: "nvidia"# -- Node selector for GPU nodes (override per cloud in values-gke/aws.yaml)@@ -642,16 +643,20 @@ workers:- key: nvidia.com/gpuoperator: Existseffect: NoSchedule+ # -- Workloads running on this pool. Each key is a bundle name.+ bundles:+ default:+ # -- Minimum replicas (0 for scale-to-zero)+ minReplicas: 0+ # -- Maximum replicas+ maxReplicas: 10# A100 40GBa100-40gb:enabled: false- minReplicas: 0- maxReplicas: 5machineProfile: a100-40gbgpuType: a100-40gb- bundle: defaultnodeSelector: {}gpu:count: 1@@ -667,16 +672,17 @@ workers:- key: nvidia.com/gpuoperator: Existseffect: NoSchedule+ bundles:+ default:+ minReplicas: 0+ maxReplicas: 5# A100 80GBa100-80gb:enabled: false- minReplicas: 0- maxReplicas: 3machineProfile: a100-80gbgpuType: a100-80gb- bundle: defaultnodeSelector: {}gpu:count: 1@@ -692,16 +698,17 @@ workers:- key: nvidia.com/gpuoperator: Existseffect: NoSchedule+ bundles:+ default:+ minReplicas: 0+ maxReplicas: 3# CPU (local testing with kind, no GPU)cpu:enabled: false- minReplicas: 1- maxReplicas: 3machineProfile: cpugpuType: cpu- bundle: default# -- Platform override for CPU poolplatform: cpu# No node selector - runs on any node@@ -717,6 +724,10 @@ workers:cpu: "4"memory: "12Gi"tolerations: []+ bundles:+ default:+ minReplicas: 1+ maxReplicas: 3# -- Autoscaling configuration using KEDA ScaledObjects.# -- Requires KEDA operator. Set keda.install=true to install KEDA as a sub-chart,diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex 16e2e011a..0f5ba0c3b 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.4.2"+version = "0.5.0"description = "SIE integration for ChromaDB"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.tomlindex a94365f54..60961a860 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.4.2"+version = "0.5.0"description = "SIE integration for CrewAI"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.tomlindex feac429cc..bd9016837 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.4.2"+version = "0.5.0"description = "SIE integration for DSPy"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.tomlindex 3df165405..50a9fa5fe 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.4.2"+version = "0.5.0"description = "SIE integration for Haystack"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.tomlindex c58227c89..6dff59a04 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.4.2"+version = "0.5.0"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 4daec7de1..2b0ffc87e 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.4.2"+version = "0.5.0"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex d672ac5a3..bafbf05f5 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.4.2"+version = "0.5.0"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex bf022ce5c..46cf9bb2a 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.4.2"+version = "0.5.0"description = "SIE integration for Qdrant"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.jsonindex c64773d2d..8f258fedf 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.4.2",+ "version": "0.5.0","description": "SIE embedding function for ChromaDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.jsonindex 06cc0e27f..24118256f 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.4.2",+ "version": "0.5.0","description": "SIE embedding function and reranker for LanceDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.jsonindex f0bdf1e5d..815b0851e 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.4.2",+ "version": "0.5.0","description": "SIE embeddings integration for LangChain.js","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.jsonindex 5a09c5e7e..2572af2a1 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.4.2",+ "version": "0.5.0","description": "SIE embeddings integration for LlamaIndex.TS","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.tomlindex f61c596a7..b68534ccb 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.4.2"+version = "0.5.0"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 ba7d518e7..12d59d432 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -2959,7 +2959,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-gateway"-version = "0.4.2"+version = "0.5.0"dependencies = ["arc-swap","async-nats",diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 0288274b2..b9c124284 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.4.2"+version = "0.5.0"edition = "2021"publish = falsediff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 1e6a76327..fa920393f 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -484,6 +484,14 @@ Config reads (read auth unless noted):Both services expose Prometheus metrics on `GET /metrics`. The gateway uses the `prometheus` Rust crate; `sie-config` uses `prometheus-client` (matches `sie-server`'s library choice). All metric names use the `sie_gateway_` or `sie_config_` prefix to make cross-service dashboards unambiguous.+When `SIE_METRICS_PORT` is set, the gateway also binds a metrics-only listener+on that port with a single unauthenticated `GET /metrics` route. The Helm chart+enables this for `serviceMonitor.enabled=true`: Prometheus scrapes a+ClusterIP-only gateway metrics Service on port 9090, while the normal gateway+Service on port 8080 keeps the public request surface behind the configured+auth mode. The 8080 `/metrics` route still exists and follows the main app's+auth rules.+### 15.1 Request and latency — gatewayEmitted from a Tower middleware (`MetricsLayer` in `middleware/metrics.rs`) that wraps the proxy routes. Putting it in middleware rather than inline in handlers ensures these counters cover every response including early rejections (validation, auth, capacity, timeout).diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 9dc5dcae6..7547c86b0 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -1733,8 +1733,12 @@"type": "object"},"ModelCapabilitiesWire": {- "description": "Capability summary surfaced on each entry of ``GET /v1/models``.\n\nMirrors the JSON shape constructed in\n``types/model.rs::to_model_info_value``. All fields are optional —\ntheir presence depends on what the model config declares.",+ "description": "Capability summary surfaced on each entry of ``GET /v1/models``.\n\nMirrors the JSON shape constructed in\n``types/model.rs::to_model_info_value``. All fields are optional —\ntheir presence depends on what the model config declares.\n\nThese flags indicate that a model *supports* a task — they are NOT a\nprecision-independent quality SLA. A flag is true at the model level even\nwhen quality is profile/precision-dependent (e.g. ``sql`` quality regresses\nunder FP8; route SQL-critical traffic to a BF16 bundle via the ``sql``\nalias). Treat them as \"can do this\", not \"guaranteed to score X\".","properties": {+ "code": {+ "description": "Whether the model is validated for code generation — backs the\n``model=\"code\"`` alias. Informational only; never request-gated.",+ "type": "boolean"+ },"grammar": {"description": "Grammar kinds the model's active backend supports\n(``json_schema`` | ``regex`` | ``ebnf``). EBNF presence depends\non the backend: SGLang's Outlines backend does not implement\nEBNF, so a profile with ``grammar_backend: outlines`` advertises\nonly ``[\"json_schema\", \"regex\"]``; xgrammar/llguidance profiles\nadvertise all three.","items": {@@ -1745,6 +1749,10 @@"null"]},+ "guard": {+ "description": "Whether the model is a content-moderation / policy-check guard —\nbacks the ``model=\"guard\"`` alias. Informational only; never\nrequest-gated.",+ "type": "boolean"+ },"lora_adapters": {"description": "Union of LoRA served-names across profiles. Back-compat summary\nfor consumers that don't care about profile scope; validation\nMUST go through ``profile_lora_adapters``.","items": {@@ -1771,6 +1779,10 @@"null"]},+ "sql": {+ "description": "Whether the model targets the SQL path — backs the ``model=\"sql\"``\nalias. Informational only; never request-gated. Precision-sensitive:\nSQL quality can regress sharply under FP8, so this model-level flag is a\nsupport signal, not a per-profile quality guarantee.",+ "type": "boolean"+ },"tools": {"description": "Whether the model supports tool / function calling.","type": [@@ -1779,6 +1791,11 @@]}},+ "required": [+ "code",+ "sql",+ "guard"+ ],"type": "object"},"ModelConfigStatusResponse": {@@ -2870,7 +2887,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.4.2"+ "version": "0.5.0"},"openapi": "3.1.0","paths": {diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex 14463a091..90ff6ae30 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -6,6 +6,7 @@ pub struct Config {// Serverpub host: String,pub port: u16,+ pub metrics_port: Option<u16>,// Discoverypub worker_urls: Vec<String>,@@ -60,6 +61,13 @@ pub struct Config {// Pre-computed lowercase→original map for GPU profile resolution (avoids HashMap rebuild per request)pub gpu_profile_map: HashMap<String, String>,+ // Job/friendly model aliases: lowercase alias → canonical model id. Lets a+ // caller request `model: "code"` and have it resolve to the recommended+ // model before the registry lookup. Ships with built-in defaults (see+ // `build_model_aliases`); extend/override via `SIE_GATEWAY_MODEL_ALIASES`+ // (JSON map). Mirrors the `SIE_GATEWAY_GPU_ALIASES` mechanism.+ pub model_aliases: HashMap<String, String>,+// Model registry paths (filesystem seed; same volume mounted into sie-config// for consistency, but the gateway never writes to them).pub bundles_dir: String,@@ -95,6 +103,10 @@ fn env_int(key: &str, fallback: u16) -> u16 {.unwrap_or(fallback)}+fn env_optional_int(key: &str) -> Option<u16> {+ env::var(key).ok().and_then(|s| s.parse().ok())+}+fn env_float(key: &str, fallback: f64) -> f64 {env::var(key).ok()@@ -129,6 +141,52 @@ fn env_json_string_map(key: &str) -> HashMap<String, String> {}}+/// Job/friendly model aliases: lowercase alias → model id (or `bundle:/model`).+///+/// Ships with built-in defaults so `model="code"` works without operator+/// config (and makes "each agent job routes to the right model" true by+/// default). `SIE_GATEWAY_MODEL_ALIASES` (a JSON map) extends or overrides+/// them. Empty alias/target pairs are skipped; aliases are stored lowercased+/// because resolution lowercases the lookup.+///+/// A target may be a bare model id (`Org/Model`) or a bundle-qualified spec+/// (`bundle:/Org/Model`). The bundle form lets an operator pin a precision /+/// profile bundle for a job — e.g. map `sql` to a BF16 bundle that avoids the+/// FP8 SQL-accuracy regression (ADR 0001), since the `:profile` variant suffix+/// is stripped before worker dispatch and so cannot itself route by precision.+/// `resolve_model_spec_with_aliases` (proxy.rs) applies the bundle.+fn build_model_aliases(overrides: HashMap<String, String>) -> HashMap<String, String> {+ let mut map: HashMap<String, String> = HashMap::new();+ // Built-in: the code-generation job → the model with a MEASURED+ // HumanEval/MBPP pass@1 baseline that also serves reliably+ // (Qwen3-4B-Instruct-2507: 0.866 / 0.74). Qwen3.5-4B is stronger on paper+ // but its NEXTN/hybrid serving path does not come up reliably yet, so it is+ // not the default until measured + its serving init is fixed.+ map.insert(+ "code".to_string(),+ "Qwen/Qwen3-4B-Instruct-2507".to_string(),+ );+ // Text-to-SQL job → an ebnf-grammar-capable LLM for the "any LLM + SQL+ // grammar" path. Repoint to SQLCoder once that model is onboarded.+ map.insert("sql".to_string(), "Qwen/Qwen3-4B-Instruct-2507".to_string());+ // CHECK POLICY job → a generative guard model that emits a safe/unsafe+ // verdict. Granite Guardian 3.0 2B (Apache-2.0, ungated) measured on+ // ToxicChat via the generation gate; serves on the same SGLang path.+ map.insert(+ "guard".to_string(),+ "ibm-granite/granite-guardian-3.0-2b".to_string(),+ );+ for (alias, target) in overrides {+ let alias = alias.trim().to_lowercase();+ let target = target.trim().to_string();+ if alias.is_empty() || target.is_empty() {+ continue;+ }+ map.insert(alias, target);+ }+ map+}+fn build_gpu_profile_map(configured_gpus: &[String],aliases: HashMap<String, String>,@@ -169,10 +227,12 @@ impl Config {&configured_gpus,env_json_string_map("SIE_GATEWAY_GPU_ALIASES"),);+ let model_aliases = build_model_aliases(env_json_string_map("SIE_GATEWAY_MODEL_ALIASES"));Self {host: "0.0.0.0".to_string(),port: 8080,+ metrics_port: env_optional_int("SIE_METRICS_PORT"),worker_urls: env_csv("SIE_GATEWAY_WORKERS"),use_kubernetes: env_bool("SIE_GATEWAY_KUBERNETES"),@@ -217,6 +277,7 @@ impl Config {configured_gpus,gpu_profile_map,+ model_aliases,bundles_dir: env_default("SIE_BUNDLES_DIR", "bundles"),models_dir: env_default("SIE_MODELS_DIR", "models"),@@ -507,6 +568,37 @@ mod tests {assert_eq!(result.get("l4"), Some(&"l4-spot".to_string()));}+ #[test]+ fn test_build_model_aliases_has_builtin_code_default() {+ let result = build_model_aliases(HashMap::new());+ assert_eq!(+ result.get("code"),+ Some(&"Qwen/Qwen3-4B-Instruct-2507".to_string())+ );+ assert_eq!(+ result.get("sql"),+ Some(&"Qwen/Qwen3-4B-Instruct-2507".to_string())+ );+ assert_eq!(+ result.get("guard"),+ Some(&"ibm-granite/granite-guardian-3.0-2b".to_string())+ );+ }++ #[test]+ fn test_build_model_aliases_env_overrides_and_extends() {+ let mut overrides = HashMap::new();+ overrides.insert("code".to_string(), "Org/Coder".to_string()); // override default+ overrides.insert("SQL".to_string(), "Org/SQLModel".to_string()); // extend + lowercased+ overrides.insert("blank".to_string(), "".to_string()); // skipped (empty target)++ let result = build_model_aliases(overrides);++ assert_eq!(result.get("code"), Some(&"Org/Coder".to_string()));+ assert_eq!(result.get("sql"), Some(&"Org/SQLModel".to_string()));+ assert!(!result.contains_key("blank"));+ }+#[test]fn test_build_gpu_profile_map_does_not_override_canonical_profile() {let mut aliases = HashMap::new();@@ -618,6 +710,38 @@ mod tests {);}+ #[test]+ fn test_metrics_port_from_env() {+ with_env(&[("SIE_METRICS_PORT", "9090")], || {+ let cfg = Config::load();+ assert_eq!(cfg.metrics_port, Some(9090));+ });+ }++ #[test]+ fn test_metrics_port_unset_is_none() {+ without_env(&["SIE_METRICS_PORT"], || {+ let cfg = Config::load();+ assert_eq!(cfg.metrics_port, None);+ });+ }++ #[test]+ fn test_metrics_port_invalid_is_none() {+ with_env(&[("SIE_METRICS_PORT", "not-a-number")], || {+ let cfg = Config::load();+ assert_eq!(cfg.metrics_port, None);+ });+ }++ #[test]+ fn test_metrics_port_out_of_range_is_none() {+ with_env(&[("SIE_METRICS_PORT", "70000")], || {+ let cfg = Config::load();+ assert_eq!(cfg.metrics_port, None);+ });+ }+#[test]fn test_stream_max_age_default_matches_worker_contract() {without_env(&["SIE_STREAM_MAX_AGE_S"], || {@@ -663,6 +787,7 @@ mod tests {let mut cfg = Config {host: String::new(),port: 0,+ metrics_port: None,worker_urls: Vec::new(),use_kubernetes: false,k8s_namespace: String::new(),@@ -686,6 +811,7 @@ mod tests {stream_max_age_s: 0,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),+ model_aliases: HashMap::new(),bundles_dir: String::new(),models_dir: String::new(),config_service_url: None,diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex d2fde5ed2..f8ebbf18a 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -32,14 +32,6 @@ use crate::http_error::{code as err_code, json_detail, json_detail_merge};use crate::server::AppState;use crate::state::model_registry::ResolveError;-fn parse_model_spec(spec: &str) -> (String, String) {- if let Some(idx) = spec.find(":/") {- (spec[..idx].to_string(), spec[idx + 2..].to_string())- } else {- (String::new(), spec.to_string())- }-}-fn yaml_response<T: Serialize>(status: StatusCode, value: &T) -> Response {let body = match serde_yaml::to_string(value) {Ok(body) => body,@@ -345,7 +337,17 @@ pub async fn resolve_config(State(state): State<Arc<AppState>>,Json(req): Json<ResolveRequest>,) -> impl IntoResponse {- let (parsed_bundle_override, model_name) = parse_model_spec(&req.model);+ // Apply the same job/friendly-alias expansion the inference path uses+ // (proxy.rs ``resolve_model_spec_with_aliases``) so a dry-run with+ // ``model="sql"`` / ``"code"`` / ``"guard"`` resolves to the alias+ // target — and its bundle — exactly like a real chat request, instead+ // of failing a literal model lookup.+ let (parsed_bundle_override, model_name) =+ crate::handlers::proxy::resolve_model_spec_with_aliases(+ &state.config.model_aliases,+ &req.model,+ |m| state.model_registry.resolve_canonical_model_name(m),+ );let bundle_override = if parsed_bundle_override.is_empty() {req.bundle.as_deref()} else {@@ -433,6 +435,7 @@ mod tests {Config {host: "127.0.0.1".to_string(),port: 0,+ metrics_port: None,worker_urls: Vec::new(),use_kubernetes: false,k8s_namespace: "default".to_string(),@@ -456,6 +459,7 @@ mod tests {stream_max_age_s: 120,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),+ model_aliases: HashMap::new(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),payload_store_url: String::new(),@@ -697,20 +701,6 @@ mod tests {assert_eq!(response.status(), StatusCode::NOT_FOUND);}- #[test]- fn test_parse_model_spec_with_bundle_prefix() {- let (bundle, model) = parse_model_spec("embedding:/BAAI/bge-m3");- assert_eq!(bundle, "embedding");- assert_eq!(model, "BAAI/bge-m3");- }-- #[test]- fn test_parse_model_spec_without_prefix() {- let (bundle, model) = parse_model_spec("BAAI/bge-m3");- assert_eq!(bundle, "");- assert_eq!(model, "BAAI/bge-m3");- }-/// Helper: seed a model into the registry so status tests have a target.fn seed_model(state: &AppState, model_id: &str) {use crate::types::model::{ModelConfig, ProfileConfig};@@ -1040,6 +1030,68 @@ mod tests {assert!(body.contains("foo/status"), "body was: {}", body);}+ #[tokio::test]+ async fn test_resolve_config_expands_builtin_alias_to_target() {+ // L6 regression: `POST /v1/configs/resolve` must dry-run gateway+ // job aliases the same way inference does. With `sql` aliased to a+ // real model, resolving `model="sql"` must yield the alias TARGET+ // (`BAAI/bge-m3`), not a literal lookup of "sql" (which would 404).+ let bundles_dir = tempfile::TempDir::new().unwrap();+ let models_dir = tempfile::TempDir::new().unwrap();+ std::fs::write(+ bundles_dir.path().join("default.yaml"),+ "name: default\nadapters:\n - module\ndefault: true\n",+ )+ .unwrap();++ let mut cfg = test_config(+ bundles_dir.path().to_str().unwrap(),+ models_dir.path().to_str().unwrap(),+ None,+ );+ cfg.model_aliases+ .insert("sql".to_string(), "BAAI/bge-m3".to_string());+ let config = Arc::new(cfg);+ let model_registry = Arc::new(ModelRegistry::new(+ bundles_dir.path(),+ models_dir.path(),+ true,+ ));+ let state = Arc::new(AppState {+ registry: Arc::new(WorkerRegistry::new(Duration::from_secs(30), None)),+ config: Arc::clone(&config),+ model_registry,+ pool_manager: Arc::new(PoolManager::new(Vec::new())),+ work_publisher: None,+ demand_tracker: Arc::new(DemandTracker::new()),+ config_epoch: crate::state::config_epoch::ConfigEpoch::new(),+ });+ seed_model(&state, "BAAI/bge-m3");+ let app = create_router(Arc::clone(&state), config);++ let response = app+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/v1/configs/resolve")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::to_vec(&serde_json::json!({"model": "sql"})).unwrap(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let parsed: serde_json::Value =+ serde_json::from_slice(&body_bytes(response).await).unwrap();+ assert_eq!(+ parsed["model"], "BAAI/bge-m3",+ "alias `sql` must resolve to its target, not a literal `sql` lookup"+ );+ }+#[tokio::test]async fn test_model_status_reports_config_epoch() {let bundles_dir = tempfile::TempDir::new().unwrap();diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex b95a160ee..4155e49b8 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -175,6 +175,9 @@ fn worker_only_model_info(name: &str, loaded: bool) -> Value {max_output_tokens: None,grammar_capabilities: None,tools_supported: None,+ code: false,+ sql: false,+ guard: false,lora_adapters: None,profile_lora_adapters: None,},@@ -321,6 +324,7 @@ mod route_tests {Config {host: "127.0.0.1".to_string(),port: 0,+ metrics_port: None,worker_urls: Vec::new(),use_kubernetes: false,k8s_namespace: "default".to_string(),@@ -344,6 +348,7 @@ mod route_tests {stream_max_age_s: 120,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),+ model_aliases: HashMap::new(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),payload_store_url: String::new(),@@ -411,6 +416,71 @@ mod route_tests {.unwrap();}+ // End-to-end through the routing entry point (proxy::resolve_model_and_bundle),+ // not just the pure resolver: a `sql` job alias whose target carries a BF16+ // bundle routes model="sql" to that bundle, a `code` alias to the FP8 bundle+ // of the SAME base model, an explicit caller bundle overrides the alias, and+ // an alias pointing at a bundle the model isn't registered under is a hard+ // error (not a silent FP8 fallback). Validates the #1184 precision-routing+ // mechanism against a real AppState + ModelRegistry.+ #[test]+ fn test_resolve_model_and_bundle_alias_carries_precision_bundle() {+ let bundles_dir = tempfile::TempDir::new().unwrap();+ let models_dir = tempfile::TempDir::new().unwrap();+ // Two bundles sharing the seeded model's adapter → the model lives in both.+ for name in ["fp8-pytorch", "bf16-pytorch"] {+ std::fs::write(+ bundles_dir.path().join(format!("{name}.yaml")),+ format!("name: {name}\nadapters:\n - module\n"),+ )+ .unwrap();+ }++ let mut config = test_config(+ bundles_dir.path().to_str().unwrap(),+ models_dir.path().to_str().unwrap(),+ );+ config.model_aliases = HashMap::from([+ ("sql".to_string(), "bf16-pytorch:/test/model".to_string()),+ ("code".to_string(), "fp8-pytorch:/test/model".to_string()),+ ("broken".to_string(), "ghost-bundle:/test/model".to_string()),+ ]);+ let config = Arc::new(config);+ let model_registry = Arc::new(ModelRegistry::new(+ bundles_dir.path(),+ models_dir.path(),+ true,+ ));+ let state = AppState {+ registry: Arc::new(WorkerRegistry::new(Duration::from_secs(30), None)),+ config: Arc::clone(&config),+ model_registry,+ pool_manager: Arc::new(PoolManager::new(Vec::new())),+ work_publisher: None,+ demand_tracker: Arc::new(DemandTracker::new()),+ config_epoch: crate::state::config_epoch::ConfigEpoch::new(),+ };+ seed_model(&state, "test/model");++ use crate::handlers::proxy::resolve_model_and_bundle;+ // sql -> BF16 bundle; code -> FP8 bundle (same base model, different precision).+ assert_eq!(+ resolve_model_and_bundle(&state, "sql").unwrap(),+ ("test/model".to_string(), "bf16-pytorch".to_string()),+ );+ assert_eq!(+ resolve_model_and_bundle(&state, "code").unwrap(),+ ("test/model".to_string(), "fp8-pytorch".to_string()),+ );+ // An explicit caller bundle overrides the alias's bundle.+ assert_eq!(+ resolve_model_and_bundle(&state, "fp8-pytorch:/sql").unwrap(),+ ("test/model".to_string(), "fp8-pytorch".to_string()),+ );+ // Alias -> a bundle the model isn't registered under: hard 409, no fallback.+ assert!(resolve_model_and_bundle(&state, "broken").is_err());+ }+/// Seed a multi-profile model whose profiles declare disjoint LoRA/// adapter sets. Used to exercise the per-profile lora_adapter/// scoping behavior introduced for M10.diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 8b7ed6749..325021d15 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -604,11 +604,13 @@ async fn proxy_request();}- // Parse model spec: [bundle:/]org/model- let (bundle_override, model_name_from_path) = parse_model_spec(&model);- let model_name = resolve_path_model_id(&model_name_from_path, |id| {- state.model_registry.resolve_canonical_model_name(id)- });+ // Parse model spec: [bundle:/]org/model, expanding a job/friendly alias+ // whose target may carry a precision/profile bundle (see+ // resolve_model_spec_with_aliases).+ let (bundle_override, model_name) =+ resolve_model_spec_with_aliases(&state.config.model_aliases, &model, |m| {+ state.model_registry.resolve_canonical_model_name(m)+ });let bundle_override_ref = if bundle_override.is_empty() {None} else {@@ -4059,14 +4061,14 @@ fn map_chat_finish_reason(sie: &str) -> &'static str {// resolution helpers return it for the caller to `return` directly, mirroring// the handlers' own pattern.#[allow(clippy::result_large_err)]-fn resolve_model_and_bundle(+pub(crate) fn resolve_model_and_bundle(state: &AppState,model_spec: &str,) -> Result<(String, String), Response> {- let (bundle_override, model_name_from_body) = parse_model_spec(model_spec);- let model_name = resolve_path_model_id(&model_name_from_body, |id| {- state.model_registry.resolve_canonical_model_name(id)- });+ let (bundle_override, model_name) =+ resolve_model_spec_with_aliases(&state.config.model_aliases, model_spec, |m| {+ state.model_registry.resolve_canonical_model_name(m)+ });let bundle_override_ref = if bundle_override.is_empty() {None} else {@@ -6190,6 +6192,87 @@ fn resolve_path_model_id(path_id: &str, canonicalize: impl Fn(&str) -> Option<Stpath_id.to_string()}+/// Canonicalise `id`, falling back to a configured job/friendly alias.+///+/// A real model id resolves through `canonicalize` directly. Otherwise, if+/// `id` (case-insensitive) is a configured alias (e.g. `"code"`), its target+/// is substituted and canonicalised; when the target itself is not in the+/// registry the target string is returned verbatim (so the downstream+/// model-not-found path references the resolved model, not the alias).+/// Mirrors the GPU-alias mechanism (`SIE_GATEWAY_GPU_ALIASES`).+fn canonicalize_with_aliases(+ aliases: &std::collections::HashMap<String, String>,+ id: &str,+ canonicalize: impl Fn(&str) -> Option<String>,+) -> Option<String> {+ if let Some(canonical) = canonicalize(id) {+ return Some(canonical);+ }+ lookup_alias(aliases, id).map(|target| {+ // The alias target may be `bundle:/model`; the bundle is routed+ // separately (resolve_model_spec_with_aliases), so resolve only the+ // model portion here. A bare target leaves the model unchanged.+ // Resolve it like any path id: handles the SIE-safe "__"->"/" form and+ // canonical case-folding, falling back to the target model verbatim (so+ // model-not-found references the resolved model).+ let (_bundle, model) = parse_model_spec(target);+ resolve_path_model_id(&model, &canonicalize)+ })+}++/// Look up a job/friendly alias by its name, tolerating a `:profile` variant+/// suffix on the request.+///+/// Tries the full (lowercased) id first, then the base before the first `:`, so+/// `sql:rtx-pro-6000` still resolves the `sql` alias. The `:profile` suffix+/// can't route by precision anyway (it's stripped before worker dispatch), so+/// dropping it for alias resolution is safe; the alias's own bundle is what+/// routes. (A real model id with a `:` resolves through `canonicalize` before+/// this is reached, so this never shadows one.)+fn lookup_alias<'a>(+ aliases: &'a std::collections::HashMap<String, String>,+ id: &str,+) -> Option<&'a String> {+ let key = id.to_ascii_lowercase();+ aliases+ .get(&key)+ .or_else(|| key.split_once(':').and_then(|(base, _)| aliases.get(base)))+}++/// Resolve a request's model spec to `(bundle_override, canonical_model_name)`,+/// expanding a job/friendly alias whose target may itself carry a bundle.+///+/// Replaces the `parse_model_spec` + `canonicalize_with_aliases` pair at the+/// routing sites. The model-name resolution is unchanged (real id, else alias+/// target, else the `__`->`/` form, else verbatim). The addition: an alias+/// *target* may be a full `bundle:/org/model` spec, so an operator can pin a+/// precision/profile bundle for a job alias — e.g. map `sql` to a BF16 bundle+/// that avoids the FP8 SQL-accuracy regression (ADR 0001), since the `:profile`+/// variant suffix is stripped before worker dispatch and cannot itself route by+/// precision. An explicit caller bundle (`somebundle:/sql`) always wins over the+/// alias's bundle.+pub(crate) fn resolve_model_spec_with_aliases(+ aliases: &std::collections::HashMap<String, String>,+ spec: &str,+ canonicalize: impl Fn(&str) -> Option<String>,+) -> (String, String) {+ let (req_bundle, req_model) = parse_model_spec(spec);+ let model_name = resolve_path_model_id(&req_model, |id| {+ canonicalize_with_aliases(aliases, id, &canonicalize)+ });+ // Adopt the alias target's bundle only when the caller pinned none AND the+ // bare model resolved through an alias (not a real model id). Uses the same+ // `:profile`-tolerant lookup as the model-name resolution above, so a+ // `sql:profile` request adopts the `sql` alias bundle too.+ if req_bundle.is_empty() && canonicalize(&req_model).is_none() {+ if let Some(target) = lookup_alias(aliases, &req_model) {+ let (alias_bundle, _) = parse_model_spec(target);+ return (alias_bundle, model_name);+ }+ }+ (req_bundle, model_name)+}+fn decode_model_path(raw: &str) -> Result<String, String> {percent_decode_str(raw).decode_utf8()@@ -8847,6 +8930,167 @@ mod tests {);}+ #[test]+ fn test_canonicalize_with_aliases_passes_through_real_model() {+ // A real model id resolves directly; aliases are not consulted.+ let aliases = std::collections::HashMap::new();+ let out =+ canonicalize_with_aliases(&aliases, "Qwen/Qwen3.5-4B", canon_of("Qwen/Qwen3.5-4B"));+ assert_eq!(out.as_deref(), Some("Qwen/Qwen3.5-4B"));+ }++ #[test]+ fn test_canonicalize_with_aliases_resolves_alias_to_target() {+ // "code" → target, case-insensitive on the alias key; the target is+ // then canonicalised through the registry.+ let mut aliases = std::collections::HashMap::new();+ aliases.insert("code".to_string(), "Qwen/Qwen3.5-4B".to_string());+ let canon = canon_of("Qwen/Qwen3.5-4B");+ assert_eq!(+ canonicalize_with_aliases(&aliases, "code", &canon).as_deref(),+ Some("Qwen/Qwen3.5-4B")+ );+ assert_eq!(+ canonicalize_with_aliases(&aliases, "CODE", &canon).as_deref(),+ Some("Qwen/Qwen3.5-4B")+ );+ }++ #[test]+ fn test_canonicalize_with_aliases_target_verbatim_when_registry_empty() {+ // Alias target not in the registry → return the target verbatim so the+ // 404 references the resolved model, not the alias.+ let mut aliases = std::collections::HashMap::new();+ aliases.insert("code".to_string(), "Qwen/Qwen3.5-4B".to_string());+ assert_eq!(+ canonicalize_with_aliases(&aliases, "code", |_| None).as_deref(),+ Some("Qwen/Qwen3.5-4B")+ );+ }++ #[test]+ fn test_canonicalize_with_aliases_resolves_sie_safe_target() {+ // An alias target stored in the SIE-safe "__" form resolves to the+ // slash form via resolve_path_model_id, not just bare canonicalize.+ let mut aliases = std::collections::HashMap::new();+ aliases.insert("code".to_string(), "Qwen__Qwen3.5-4B".to_string());+ assert_eq!(+ canonicalize_with_aliases(&aliases, "code", canon_of("Qwen/Qwen3.5-4B")).as_deref(),+ Some("Qwen/Qwen3.5-4B")+ );+ }++ #[test]+ fn test_canonicalize_with_aliases_unknown_falls_through() {+ // Neither a real model nor a configured alias → None (normal 404 path).+ let aliases = std::collections::HashMap::new();+ assert_eq!(canonicalize_with_aliases(&aliases, "nope", |_| None), None);+ }++ #[test]+ fn test_resolve_model_spec_real_model_no_bundle() {+ // A real model id resolves directly; aliases not consulted, no bundle.+ let aliases = std::collections::HashMap::new();+ let (bundle, model) = resolve_model_spec_with_aliases(+ &aliases,+ "Qwen/Qwen3.5-4B",+ canon_of("Qwen/Qwen3.5-4B"),+ );+ assert_eq!(bundle, "");+ assert_eq!(model, "Qwen/Qwen3.5-4B");+ }++ #[test]+ fn test_resolve_model_spec_caller_bundle_preserved() {+ // An explicit `bundle:/model` request keeps its bundle.+ let aliases = std::collections::HashMap::new();+ let (bundle, model) = resolve_model_spec_with_aliases(+ &aliases,+ "bf16:/Qwen/Qwen3.5-4B",+ canon_of("Qwen/Qwen3.5-4B"),+ );+ assert_eq!(bundle, "bf16");+ assert_eq!(model, "Qwen/Qwen3.5-4B");+ }++ #[test]+ fn test_resolve_model_spec_alias_carries_bundle() {+ // The headline feature: a `sql` alias whose target carries a bundle+ // routes to that (BF16) bundle while resolving the base model.+ let mut aliases = std::collections::HashMap::new();+ aliases.insert("sql".to_string(), "bf16:/Qwen/Qwen3.6-27B".to_string());+ let (bundle, model) =+ resolve_model_spec_with_aliases(&aliases, "sql", canon_of("Qwen/Qwen3.6-27B"));+ assert_eq!(bundle, "bf16");+ assert_eq!(model, "Qwen/Qwen3.6-27B");+ }++ #[test]+ fn test_resolve_model_spec_alias_with_profile_suffix_still_routes() {+ // A profile-suffixed alias request (`sql:rtx-pro-6000`) must still hit+ // the `sql` alias and adopt its BF16 bundle; the (precision-inert)+ // profile suffix is dropped for alias resolution.+ let mut aliases = std::collections::HashMap::new();+ aliases.insert("sql".to_string(), "bf16:/Qwen/Qwen3.6-27B".to_string());+ let (bundle, model) = resolve_model_spec_with_aliases(+ &aliases,+ "sql:rtx-pro-6000",+ canon_of("Qwen/Qwen3.6-27B"),+ );+ assert_eq!(bundle, "bf16");+ assert_eq!(model, "Qwen/Qwen3.6-27B");+ }++ #[test]+ fn test_resolve_model_spec_alias_bare_target_has_no_bundle() {+ // An alias with a plain (bundle-less) target resolves the model and+ // leaves the bundle empty — unchanged from the pre-feature behavior.+ let mut aliases = std::collections::HashMap::new();+ aliases.insert(+ "code".to_string(),+ "Qwen/Qwen3-4B-Instruct-2507".to_string(),+ );+ let (bundle, model) = resolve_model_spec_with_aliases(+ &aliases,+ "CODE",+ canon_of("Qwen/Qwen3-4B-Instruct-2507"),+ );+ assert_eq!(bundle, "");+ assert_eq!(model, "Qwen/Qwen3-4B-Instruct-2507");+ }++ #[test]+ fn test_resolve_model_spec_caller_bundle_wins_over_alias_bundle() {+ // An explicit caller bundle on an aliased request overrides the alias's+ // bundle (the model still resolves through the alias).+ let mut aliases = std::collections::HashMap::new();+ aliases.insert("sql".to_string(), "bf16:/Qwen/Qwen3.6-27B".to_string());+ let (bundle, model) =+ resolve_model_spec_with_aliases(&aliases, "fp8:/sql", canon_of("Qwen/Qwen3.6-27B"));+ assert_eq!(bundle, "fp8");+ assert_eq!(model, "Qwen/Qwen3.6-27B");+ }++ #[test]+ fn test_resolve_model_spec_alias_bundle_with_sie_safe_target() {+ // The alias target's model portion may use the SIE-safe `__` form.+ let mut aliases = std::collections::HashMap::new();+ aliases.insert("sql".to_string(), "bf16:/Qwen__Qwen3.6-27B".to_string());+ let (bundle, model) =+ resolve_model_spec_with_aliases(&aliases, "sql", canon_of("Qwen/Qwen3.6-27B"));+ assert_eq!(bundle, "bf16");+ assert_eq!(model, "Qwen/Qwen3.6-27B");+ }++ #[test]+ fn test_resolve_model_spec_unknown_passthrough_no_bundle() {+ // Neither a real model nor an alias → verbatim model, no bundle (404 path).+ let aliases = std::collections::HashMap::new();+ let (bundle, model) = resolve_model_spec_with_aliases(&aliases, "nope", |_| None);+ assert_eq!(bundle, "");+ assert_eq!(model, "nope");+ }+#[test]fn test_resolve_path_model_id_returns_original_when_unknown() {// Neither the path id nor the `/`-substituted variant is in the@@ -13692,6 +13936,9 @@ mod tests {max_output_tokens: None,grammar_capabilities: None,tools_supported: None,+ code: false,+ sql: false,+ guard: false,// Union summary (back-compat). The gate must NOT consult this.lora_adapters: Some(vec!["a1".to_string(), "a2".to_string(), "b1".to_string()]),profile_lora_adapters: Some(per_profile),diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rsindex 9b13f67a9..6cf889d09 100644--- a/packages/sie_gateway/src/main.rs+++ b/packages/sie_gateway/src/main.rs@@ -23,6 +23,7 @@ use std::time::Duration;use clap::{Parser, Subcommand};use tokio::net::TcpListener;use tokio::signal;+use tokio::sync::watch;use tracing::info;use config::Config;@@ -635,7 +636,10 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {config_epoch: config_epoch.clone(),});- let app = server::create_router(state, Arc::clone(&config));+ let app = server::create_router(Arc::clone(&state), Arc::clone(&config));+ let metrics_app = config+ .metrics_port+ .map(|_| server::create_metrics_router(Arc::clone(&state)));info!(addr = %addr,@@ -644,11 +648,39 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {"starting SIE Gateway");+ let (shutdown_tx, shutdown_rx) = watch::channel(false);let listener = TcpListener::bind(&addr).await?;- axum::serve(listener, app)- .with_graceful_shutdown(shutdown_signal())- .await?;+ let metrics_handle = match (config.metrics_port, metrics_app) {+ (Some(metrics_port), Some(metrics_app)) => {+ let metrics_addr = format!("{}:{}", config.host, metrics_port);+ let metrics_listener = TcpListener::bind(&metrics_addr).await?;+ let metrics_shutdown = shutdown_rx.clone();+ info!(+ addr = %metrics_addr,+ "starting SIE Gateway metrics listener"+ );+ Some(tokio::spawn(async move {+ axum::serve(metrics_listener, metrics_app)+ .with_graceful_shutdown(wait_for_shutdown(metrics_shutdown))+ .await+ }))+ }+ _ => None,+ };++ let shutdown_tx_for_signal = shutdown_tx.clone();+ let serve_result = axum::serve(listener, app)+ .with_graceful_shutdown(async move {+ shutdown_signal().await;+ let _ = shutdown_tx_for_signal.send(true);+ })+ .await;+ let _ = shutdown_tx.send(true);+ if let Some(handle) = metrics_handle {+ handle.await??;+ }+ serve_result?;info!("server stopped");@@ -696,3 +728,11 @@ async fn shutdown_signal() {}}}++async fn wait_for_shutdown(mut rx: watch::Receiver<bool>) {+ while !*rx.borrow() {+ if rx.changed().await.is_err() {+ break;+ }+ }+}diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rsindex da0669dca..ba01f470e 100644--- a/packages/sie_gateway/src/middleware/auth.rs+++ b/packages/sie_gateway/src/middleware/auth.rs@@ -323,6 +323,7 @@ mod tests {Arc::new(Config {host: String::new(),port: 0,+ metrics_port: None,worker_urls: Vec::new(),use_kubernetes: false,k8s_namespace: String::new(),@@ -346,6 +347,7 @@ mod tests {stream_max_age_s: 0,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),+ model_aliases: HashMap::new(),bundles_dir: String::new(),models_dir: String::new(),config_service_url: None,diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex efa0cac1e..acf571a71 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -1944,6 +1944,12 @@ pub struct ModelInfoWire {/// Mirrors the JSON shape constructed in/// ``types/model.rs::to_model_info_value``. All fields are optional —/// their presence depends on what the model config declares.+///+/// These flags indicate that a model *supports* a task — they are NOT a+/// precision-independent quality SLA. A flag is true at the model level even+/// when quality is profile/precision-dependent (e.g. ``sql`` quality regresses+/// under FP8; route SQL-critical traffic to a BF16 bundle via the ``sql``+/// alias). Treat them as "can do this", not "guaranteed to score X".#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct ModelCapabilitiesWire {/// Union of LoRA served-names across profiles. Back-compat summary@@ -1968,6 +1974,18 @@ pub struct ModelCapabilitiesWire {/// Whether the model supports tool / function calling.#[serde(skip_serializing_if = "Option::is_none")]pub tools: Option<bool>,+ /// Whether the model is validated for code generation — backs the+ /// ``model="code"`` alias. Informational only; never request-gated.+ pub code: bool,+ /// Whether the model targets the SQL path — backs the ``model="sql"``+ /// alias. Informational only; never request-gated. Precision-sensitive:+ /// SQL quality can regress sharply under FP8, so this model-level flag is a+ /// support signal, not a per-profile quality guarantee.+ pub sql: bool,+ /// Whether the model is a content-moderation / policy-check guard —+ /// backs the ``model="guard"`` alias. Informational only; never+ /// request-gated.+ pub guard: bool,}/// One OpenAI-shaped model object in the `data` array ofdiff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex 7c73338d9..711b27026 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -102,6 +102,12 @@ pub fn create_router(state: Arc<AppState>, config: Arc<Config>) -> Router {.with_state(state)}+pub fn create_metrics_router(state: Arc<AppState>) -> Router {+ Router::new()+ .route("/metrics", get(metrics_handler))+ .with_state(state)+}+#[utoipa::path(get,path = "/metrics",diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 39b0f3216..d561f7f3e 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -1903,6 +1903,68 @@ profiles:assert!(matches!(result, Err(ResolveError::BundleConflict(_))));}+ #[test]+ fn test_precision_bundle_override_routes_or_conflicts() {+ // Validates the premise behind bundle-carrying job aliases (proxy.rs+ // resolve_model_spec_with_aliases): one base model can be registered+ // under TWO precision-labeled bundles that share the same generation+ // adapter, so a `<bundle>:/model` override (what a `sql` alias expands+ // to) actually routes to the chosen precision — and an unregistered+ // bundle 409s rather than silently falling back to the FP8 default.+ let (_dir, bundles_dir, models_dir) = create_test_dirs();++ // Two bundles, same generation adapter → both match the model.+ for name in ["fp8-pytorch", "bf16-pytorch"] {+ fs::write(+ bundles_dir.join(format!("{name}.yaml")),+ format!(+ r#"+name: {name}+priority: 10+adapters:+ - sie_server.adapters.sglang.generation+"#+ ),+ )+ .unwrap();+ }++ fs::write(+ models_dir.join("qwen3-27b.yaml"),+ r#"+name: Qwen/Qwen3.6-27B+profiles:+ default:+ adapter_path: "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"+"#,+ )+ .unwrap();++ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);++ // The model lives in BOTH bundles → an operator can deploy a BF16+ // variant under its own bundle (the deployment story the ADR describes).+ assert_eq!(+ registry+ .resolve_bundle("Qwen/Qwen3.6-27B", Some("bf16-pytorch"))+ .unwrap(),+ "bf16-pytorch",+ );+ assert_eq!(+ registry+ .resolve_bundle("Qwen/Qwen3.6-27B", Some("fp8-pytorch"))+ .unwrap(),+ "fp8-pytorch",+ );+ // An alias pointing at a bundle the model is NOT registered under is a+ // hard BundleConflict (409), not a silent fallback — the failure mode+ // an operator must avoid when wiring SIE_GATEWAY_MODEL_ALIASES.+ assert!(matches!(+ registry.resolve_bundle("Qwen/Qwen3.6-27B", Some("no-such-bundle")),+ Err(ResolveError::BundleConflict(_)),+ ));+ }+#[test]fn test_bundle_priority_ordering() {let (_dir, bundles_dir, models_dir) = create_test_dirs();diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex 9e9beff24..5ed23b2c6 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -31,6 +31,23 @@ pub struct ModelInfoExtras {/// has no ``generate`` task). Defaults to ``false`` per/// :class:`sie_server.config.model.GenerateCapabilities`.pub tools_supported: Option<bool>,+ /// ``tasks.generate.capabilities.code`` from the model YAML — a+ /// boolean advertising whether the model is validated for code+ /// generation (backs the ``model="code"`` alias). Informational+ /// only; never request-gated. Defaults to ``false`` when the+ /// ``capabilities`` block or the key is absent.+ pub code: bool,+ /// ``tasks.generate.capabilities.sql`` from the model YAML — a+ /// boolean advertising whether the model targets the SQL path+ /// (backs the ``model="sql"`` alias). Informational only; never+ /// request-gated. Defaults to ``false`` when absent.+ pub sql: bool,+ /// ``tasks.generate.capabilities.guard`` from the model YAML — a+ /// boolean advertising whether the model is a content-moderation /+ /// policy-check guard (backs the ``model="guard"`` alias).+ /// Informational only; never request-gated. Defaults to ``false``+ /// when absent.+ pub guard: bool,/// Multi-LoRA served-names advertised on ``/v1/models`` under/// ``capabilities.lora_adapters``. Union of the public served-names across/// the model's profiles (``profiles.<p>.adapter_options.loadtime.lora_paths``@@ -163,6 +180,23 @@ impl ModelInfoExtras {.and_then(|v| v.as_bool()).unwrap_or(false);extras.tools_supported = Some(tools);+ // ``capabilities.{code,sql,guard}: bool`` — informational+ // job-capability flags that back the ``model="code"`` /+ // ``"sql"`` / ``"guard"`` aliases. Each defaults to+ // ``false`` when the ``capabilities`` block or the key is+ // absent (mirrors :class:`GenerateCapabilities`).+ extras.code = capabilities+ .and_then(|m| m.get("code"))+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ extras.sql = capabilities+ .and_then(|m| m.get("sql"))+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ extras.guard = capabilities+ .and_then(|m| m.get("guard"))+ .and_then(|v| v.as_bool())+ .unwrap_or(false);}}@@ -231,6 +265,9 @@ impl ModelInfoExtras {max_output_tokens: None,grammar_capabilities: None,tools_supported: None,+ code: false,+ sql: false,+ guard: false,lora_adapters: None,profile_lora_adapters: None,},@@ -313,6 +350,9 @@ impl ModelEntry {"profile_lora_adapters": self.info_extras.profile_lora_adapters,"grammar": self.info_extras.grammar_capabilities,"tools": self.info_extras.tools_supported,+ "code": self.info_extras.code,+ "sql": self.info_extras.sql,+ "guard": self.info_extras.guard,},})}@@ -744,6 +784,142 @@ tasks:assert_eq!(extras.tools_supported, Some(true));}+ #[test]+ fn test_model_info_extras_code_sql_guard_capabilities_parsed() {+ // Qwen3-4B-Instruct-2507 advertises code + sql (and tools); it is+ // not a guard model. Mirrors+ // ``packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml``.+ let raw: serde_yaml::Value = serde_yaml::from_str(+ r#"+name: Qwen/Qwen3-4B-Instruct-2507+inputs:+ text: true+tasks:+ generate:+ context_length: 32768+ max_output_tokens: 4096+ capabilities:+ grammar: ["json_schema", "regex", "ebnf"]+ tools: true+ code: true+ sql: true+"#,+ )+ .unwrap();+ let extras = ModelInfoExtras::from_yaml_raw(&raw);+ assert!(extras.code);+ assert!(extras.sql);+ assert!(!extras.guard);++ // Qwen3.6-27B also advertises code + sql. Mirrors+ // ``packages/sie_server/models/Qwen__Qwen3.6-27B.yaml``.+ let raw: serde_yaml::Value = serde_yaml::from_str(+ r#"+name: Qwen/Qwen3.6-27B+inputs:+ text: true+tasks:+ generate:+ context_length: 32768+ max_output_tokens: 4096+ capabilities:+ grammar: ["json_schema", "regex"]+ tools: true+ code: true+ sql: true+"#,+ )+ .unwrap();+ let extras = ModelInfoExtras::from_yaml_raw(&raw);+ assert!(extras.code);+ assert!(extras.sql);+ assert!(!extras.guard);++ // Granite Guardian 3.0-2b advertises guard only. Mirrors+ // ``packages/sie_server/models/ibm-granite__granite-guardian-3.0-2b.yaml``.+ let raw: serde_yaml::Value = serde_yaml::from_str(+ r#"+name: ibm-granite/granite-guardian-3.0-2b+inputs:+ text: true+tasks:+ generate:+ context_length: 8192+ max_output_tokens: 512+ capabilities:+ grammar: []+ tools: false+ guard: true+"#,+ )+ .unwrap();+ let extras = ModelInfoExtras::from_yaml_raw(&raw);+ assert!(extras.guard);+ assert!(!extras.code);+ assert!(!extras.sql);+ }++ #[test]+ fn test_model_info_extras_code_sql_guard_default_false_when_absent() {+ // No ``capabilities`` block at all — all three default to false.+ let raw: serde_yaml::Value = serde_yaml::from_str(+ r#"+name: m+inputs:+ text: true+tasks:+ generate:+ context_length: 1024+ max_output_tokens: 512+"#,+ )+ .unwrap();+ let extras = ModelInfoExtras::from_yaml_raw(&raw);+ assert!(!extras.code);+ assert!(!extras.sql);+ assert!(!extras.guard);+ }++ #[test]+ fn test_to_model_info_value_surfaces_code_sql_guard_flags() {+ // The three flags must surface inside the same ``capabilities``+ // JSON object as ``grammar``/``tools``, using snake_case wire keys.+ let raw: serde_yaml::Value = serde_yaml::from_str(+ r#"+name: Qwen/Qwen3-4B-Instruct-2507+inputs:+ text: true+tasks:+ generate:+ context_length: 32768+ max_output_tokens: 4096+ capabilities:+ grammar: ["json_schema"]+ tools: true+ code: true+ sql: true+"#,+ )+ .unwrap();+ let info_extras = ModelInfoExtras::from_yaml_raw(&raw);+ let entry = ModelEntry {+ name: "Qwen/Qwen3-4B-Instruct-2507".to_string(),+ bundles: Vec::new(),+ adapter_modules: HashSet::new(),+ profile_names: HashSet::new(),+ profile_configs: HashMap::new(),+ info_extras,+ };+ let body = entry.to_model_info_value(false);+ let caps = body+ .get("capabilities")+ .and_then(|c| c.as_object())+ .expect("capabilities block");+ assert_eq!(caps.get("code"), Some(&json!(true)));+ assert_eq!(caps.get("sql"), Some(&json!(true)));+ assert_eq!(caps.get("guard"), Some(&json!(false)));+ }+#[test]fn test_model_info_extras_tools_capability_defaults_to_false() {let raw: serde_yaml::Value = serde_yaml::from_str(diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex 8e003ace9..edc337ae7 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.4.2"+version = "0.5.0"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex f19d4005b..cf7adbe68 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -169,6 +169,33 @@ class ModelDims(TypedDict, total=False):multivector: int+class ModelCapabilities(TypedDict, total=False):+ """Advertised model capabilities.++ Mirrors the gateway ``capabilities`` object on each ``/v1/models``+ entry (``ModelCapabilitiesWire``). All keys are optional; their+ presence depends on what the model config declares. ``grammar`` is+ the list of supported grammar kinds (``json_schema`` | ``regex`` |+ ``ebnf``). ``code``/``sql``/``guard`` are informational flags that+ advertise validated generation jobs and back the ``model="code"`` /+ ``model="sql"`` / ``model="guard"`` aliases.++ These flags mean the model *supports* a task — they are NOT a+ precision-independent quality SLA. A flag is true at the model level even+ when quality is profile/precision-dependent (e.g. ``sql`` quality regresses+ under FP8; route SQL-critical traffic to a BF16 bundle via the ``sql``+ alias). Treat them as "can do this", not "guaranteed to score X".+ """++ grammar: list[str]+ tools: bool+ lora_adapters: list[str]+ profile_lora_adapters: dict[str, list[str]]+ code: bool+ sql: bool+ guard: bool++class ModelInfo(TypedDict, total=False):"""Information about a model returned by list_models().@@ -181,6 +208,7 @@ class ModelInfo(TypedDict, total=False):outputs: list[str] # ["dense"], ["dense", "sparse"], etc.dims: ModelDimsmax_sequence_length: int+ capabilities: ModelCapabilitiesclass ScoreEntry(TypedDict):diff --git a/packages/sie_sdk/tests/client/test_sync.py b/packages/sie_sdk/tests/client/test_sync.pyindex 052dc59e3..4aca5bdda 100644--- a/packages/sie_sdk/tests/client/test_sync.py+++ b/packages/sie_sdk/tests/client/test_sync.py@@ -5,6 +5,7 @@ import msgpackimport numpy as npimport pytestfrom sie_sdk import RequestError, ServerError, SIEClient, SIEConnectionError+from sie_sdk.types import ModelCapabilitiesclass TestSIEClientInit:@@ -418,6 +419,43 @@ class TestListModels:assert "dense" in models[0]["outputs"]client.close()+ def test_list_models_surfaces_capabilities(self) -> None:+ """Generation models surface the typed ``capabilities`` field."""+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.json.return_value = {+ "models": [+ {+ "name": "qwen3-4b",+ "loaded": True,+ "inputs": ["text"],+ "outputs": ["text"],+ "dims": {},+ "max_sequence_length": 32768,+ "capabilities": {+ "grammar": ["json_schema", "regex"],+ "tools": True,+ "code": True,+ "sql": True,+ "guard": False,+ },+ }+ ]+ }++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.get.return_value = mock_response+ client = SIEClient("http://localhost:8080")+ models = client.list_models()++ caps: ModelCapabilities = models[0]["capabilities"]+ assert caps["grammar"] == ["json_schema", "regex"]+ assert caps["tools"] is True+ assert caps["code"] is True+ assert caps["sql"] is True+ assert caps["guard"] is False+ client.close()+def test_get_model_returns_info(self) -> None:"""get_model returns ModelInfo for a specific model."""mock_response = MagicMock()diff --git a/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml b/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yamlindex 3ded160c9..72e865ab2 100644--- a/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml+++ b/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml@@ -14,12 +14,18 @@ tasks:context_length: 32768max_output_tokens: 4096capabilities:- # Outlines-backed JSON Schema, regex, and EBNF grammars are- # all supported by the SGLang adapter (Outlines and XGrammar- # both accept EBNF natively). The gateway gates requests on- # this exact list — adding a new ``grammar.kind`` variant- # requires both the gateway parser and this list to be updated.- grammar: ["json_schema", "regex", "ebnf"]+ # Same constraint as Qwen3.5-4B / Qwen3.6-27B: this profile runs the+ # default ``grammar_backend: outlines``, and SGLang's outlines_backend+ # does NOT implement ebnf (it logs ``Skip unsupported key_type='ebnf'``+ # then fails the compile — confirmed on A100 smoke 2026-05-26). Only+ # advertise ``"ebnf"`` here once a profile pins an EBNF-capable backend+ # (``grammar_backend: xgrammar``) AND a via-SIE EBNF smoke passes; the+ # gateway gates requests on this exact list, so advertising ebnf without+ # an ebnf-capable backend admits requests the worker then fails to serve.+ # The ``test_advertised_ebnf_requires_capable_backend`` consistency test+ # guards this invariant. Adding a new ``grammar.kind`` variant requires+ # both the gateway parser and this list to be updated.+ grammar: ["json_schema", "regex"]streaming: true# Qwen3-4B-Instruct's chat template emits OpenAI-compatible# ``<tool_call>{...}</tool_call>`` blocks when ``tools`` is@@ -28,6 +34,16 @@ tasks:# them on ``delta.tool_calls`` for SSE and on# ``message.tool_calls`` for non-streaming requests.tools: true+ # Validated for code generation — MEASURED HumanEval 0.866 / MBPP 0.74 on+ # Modal A100 (see benchmarks/generation/.../code/measured_baseline.json).+ # Backs the model="code" alias. Informational (not request-gated).+ code: true+ # Backs the model="sql" alias. NOTE: this profile runs the outlines+ # backend (no ebnf), so SQL output here relies on the model's native+ # text-to-SQL ability, NOT an EBNF grammar constraint. Re-add ``"ebnf"``+ # to ``grammar`` above (behind an xgrammar profile + via-SIE EBNF smoke)+ # to enable grammar-constrained SQL. Informational (not request-gated).+ sql: true# Forwarded verbatim to ``tokenizer.apply_chat_template(**kwargs)`` when# the worker renders an OpenAI-shaped ``messages`` request.# Qwen3's chat template emits a ``<think>``/``</think>`` reasoning blockdiff --git a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml b/packages/sie_server/models/Qwen__Qwen3.5-4B.yamlindex 63a196ebc..593b63241 100644--- a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml@@ -29,6 +29,11 @@ tasks:grammar: ["json_schema", "regex"]streaming: truetools: true+ # NOTE: not advertising code:true here yet — Qwen3.5-4B is the strongest+ # model on paper but its NEXTN/hybrid serving path does not come up+ # reliably on the current eval image, so it has no measured HumanEval/MBPP+ # baseline. The ``model="code"`` alias points to the measured+ # Qwen3-4B-Instruct-2507; promote this once 3.5-4B is measured.# Grammar backend: ``outlines`` (set per-profile under# ``adapter_options.loadtime``). Earlier revisions forced ``xgrammar``# here because the worker-side Outlines preflight (``compile_outlines``)diff --git a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml b/packages/sie_server/models/Qwen__Qwen3.6-27B.yamlindex e66535a06..02e4b9469 100644--- a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml@@ -34,6 +34,23 @@ tasks:grammar: ["json_schema", "regex"]streaming: truetools: true+ # Validated on code + text-to-SQL — MEASURED on Modal H100 (bf16 no-spec,+ # greedy+min_tokens=10; accuracy is GPU-invariant + FP8≈BF16 per ADR+ # 0001): HumanEval 0.933, MBPP 0.81 (beats the 4B code default 0.866/0.74),+ # Spider exec-acc 0.693. See code_sql_tools/measured_baseline.json.+ # Informational (not request-gated); surfaces the high-end code/SQL option.+ code: true+ # CAVEAT: this flag is precision-agnostic, but FP8 weight quant regresses+ # SQL ~13pts (Spider 0.71 BF16 -> 0.58 FP8, same-subset control; see the+ # ADR + baseline). Code/tools/MC are FP8-safe. The default rtx-pro-6000+ # profile is FP8, so route SQL-critical traffic to the BF16+NEXTN variant+ # (the 96GB card fits it). The `:profile` variant suffix can't route by+ # precision (it's stripped before worker dispatch), so deploy the BF16+ # variant under a distinct bundle and point the `sql` job alias at it via+ # a bundle-qualified target, e.g.+ # SIE_GATEWAY_MODEL_ALIASES={"sql":"<bf16-bundle>:/Qwen/Qwen3.6-27B"}+ # (gateway resolve_model_spec_with_aliases; see ADR 0001).+ sql: true# Qwen3.6 emits ``<think>...</think>`` reasoning by default. We# disable it for the OpenAI-compat path so visible output is the# answer only. Operators wanting CoT can flip this profile-side.diff --git a/packages/sie_server/models/defog__sqlcoder-7b-2.yaml b/packages/sie_server/models/defog__sqlcoder-7b-2.yamlnew file mode 100644index 000000000..adb7f0c41--- /dev/null+++ b/packages/sie_server/models/defog__sqlcoder-7b-2.yaml@@ -0,0 +1,70 @@+sie_id: defog/sqlcoder-7b-2+hf_id: defog/sqlcoder-7b-2+# SQLCoder-7B-2 (Defog) — a CodeLlama-7B base fine-tuned for text-to-SQL.+# Served via the existing SGLang generation adapter (LlamaForCausalLM is native+# to SGLang); onboarding is config-only.+#+# CAVEATS (read before pointing model="sql" at this):+# * COMPLETION model, not chat-tuned. It expects its verbatim template+# (``### Task ... ### Database Schema ... ### Answer ...[SQL]``) via the+# completions path — a chat-completions wrapper will underperform. The+# model="sql" alias currently targets Qwen3-4B-Instruct (chat + grammar+# path); repoint here only once the SQLCoder prompt template + completions+# rendering are wired and measured on Spider.+# * dtype float16 (CodeLlama base; the card pins fp16).+# * License CC-BY-SA-4.0 (share-alike copyleft) — clear distribution/bundle+# use before shipping.+# * Card recommends num_beams=4 (beam search); SGLang serves greedy, so+# expect a small delta vs the published SQL-Eval numbers.+# * MEASURED in SIE (Modal A100): serves via the sglang.generation adapter.+# The native ### Task...[SQL] completions template is ESSENTIAL — generic+# chat prompt scored 0.025, the native template (spider_sqlcoder task,+# --mode completions) scored 0.467 (140/300, greedy) on 2026-06-03. But that+# still LOSES to general Qwen3-4B-Instruct at 0.70 on Spider exec-acc, so the+# model="sql" alias STAYS on Qwen3-4B-Instruct. (The card recommends+# num_beams=4; SGLang serves greedy, so 0.467 is a lower bound, but beam+# search is a serving change and would still likely trail.) See+# benchmarks/generation/Qwen__Qwen3-4B-Instruct-2507/sql/measured_baseline.json.+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ generate:+ # Base model supports 16384; 8192 comfortably fits a Spider schema + question.+ context_length: 8192+ max_output_tokens: 512+ capabilities:+ # Grammar-constrained SQL (the "any LLM + grammar" path) is plausible via+ # the SGLang outlines/xgrammar backend but unverified for this model, so+ # nothing is advertised here yet.+ grammar: []+ streaming: true+ tools: false+ # NOT advertising sql:true. The capability flag would expose this model as+ # SQL-ready to capability-based SDK/UI selection, but the currently-wired+ # served path (generic chat) scores only 0.025 on Spider, and even with its+ # native completions template (0.467) it loses to Qwen3-4B-Instruct (0.70 —+ # the actual model="sql" target). Flip on only once SQLCoder beats the+ # incumbent on a wired, measured path.+profiles:+ default:+ # Generation does not batch at the SIE layer (SGLang batches internally) but+ # the validator requires the field.+ max_batch_tokens: 16384+ compute_precision: float16+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter+ kv_budget_tokens: 32768+ adapter_options:+ loadtime:+ mem_fraction_static: 0.85+ served_model_name: defog/sqlcoder-7b-2+ runtime:+ first_chunk_timeout_s: 30+ inter_chunk_timeout_s: 10+ overall_timeout_s: 300+ # Deterministic decode for text-to-SQL (the card uses do_sample=False).+ default_sampling:+ temperature: 0.0+ top_p: 1.0diff --git a/packages/sie_server/models/ibm-granite__granite-guardian-3.0-2b.yaml b/packages/sie_server/models/ibm-granite__granite-guardian-3.0-2b.yamlnew file mode 100644index 000000000..fc161c3bc--- /dev/null+++ b/packages/sie_server/models/ibm-granite__granite-guardian-3.0-2b.yaml@@ -0,0 +1,93 @@+sie_id: ibm-granite/granite-guardian-3.0-2b+hf_id: ibm-granite/granite-guardian-3.0-2b+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ # CHECK POLICY job: a generative guard model. It takes a conversation (or a+ # single user message) and *generates* a one-token verdict — "Yes" (unsafe)+ # or "No" (safe) — under a risk taxonomy. Its chat template defaults to the+ # ``harm`` risk when no ``guardian_config`` is supplied, so the standard+ # OpenAI ``/v1/chat/completions`` path elicits a moderation verdict with no+ # special kwargs. Served on the same SGLang generation adapter as the other+ # decoder-only LLMs (architecture: GraniteForCausalLM).+ generate:+ context_length: 8192+ # Moderation needs only a couple of tokens ("Yes"/"No"); the cap is a+ # generous ceiling, not a target.+ max_output_tokens: 512+ capabilities:+ # Guard verdicts are free-form single tokens — no grammar/tools needed.+ grammar: []+ streaming: true+ tools: false+ # Content-moderation / policy-check job — MEASURED on ToxicChat via the+ # generation gate (see safety/measured_baseline.json): high-recall (0.97)+ # / low-precision (0.16) under the default 'harm' risk. Backs the+ # model="guard" alias. Informational (not request-gated).+ guard: true+max_sequence_length: 8192+profiles:+ default:+ # max_batch_tokens is a generic engine knob; generation does not batch at+ # the SIE layer (SGLang batches internally) but the validator requires it.+ max_batch_tokens: 16384+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter+ # Conservative L4 baseline; moderation prompts are short so a small KV+ # budget is ample. Re-calibrate with a concurrency/OOM sweep if promoted.+ kv_budget_tokens: 8192+ adapter_options:+ loadtime:+ mem_fraction_static: 0.85+ served_model_name: ibm-granite/granite-guardian-3.0-2b+ # CHECK POLICY precision dial. The adapter reads the verdict-token+ # logprobs, computes P(unsafe) over Yes/No, and returns "Yes" iff+ # P(unsafe) >= threshold. threshold=0.5 == the model's argmax (the+ # current high-recall default: recall 0.97 / precision 0.16). Measured+ # ToxicChat trade-off (guard baseline logprob_threshold_sweep):+ # 0.5 -> F1 0.26 recall 0.97 precision 0.15 (catch-everything)+ # 0.8 -> F1 0.38 recall 0.54 precision 0.29 (best F1)+ # 0.95 -> F1 0.31 recall 0.20 precision 0.70 (precision-critical)+ # Raising it trades recall for precision — a PRODUCT/safety decision per+ # deployment (a moderation guard usually favours recall), so the shipped+ # default stays at argmax. Operators raise it to taste.+ guard:+ threshold: 0.5+ runtime:+ first_chunk_timeout_s: 30+ inter_chunk_timeout_s: 10+ overall_timeout_s: 300+ # Greedy: a guard verdict must be deterministic.+ default_sampling:+ temperature: 0.0+ stop_tokens:+ - "<|end_of_text|>"+ a100-40gb:+ max_batch_tokens: 32768+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter+ # ~2.5B weights leave most of a 40 GB card for KV; moderation traffic is+ # short-context so this budget is set for many concurrent admissions.+ kv_budget_tokens: 65536+ adapter_options:+ loadtime:+ mem_fraction_static: 0.85+ served_model_name: ibm-granite/granite-guardian-3.0-2b+ # Duplicated from ``default`` — this is a NON-extending profile, and+ # loadtime blocks are whole-dict replaced (not deep-merged), so the+ # CHECK POLICY precision dial would otherwise be dropped here and the+ # A100 variant would silently fall back to raw argmax (self._guard={}).+ # Keep in sync with the ``default`` profile's guard.threshold.+ guard:+ threshold: 0.5+ runtime:+ first_chunk_timeout_s: 30+ inter_chunk_timeout_s: 10+ overall_timeout_s: 300+ default_sampling:+ temperature: 0.0+ stop_tokens:+ - "<|end_of_text|>"diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 25abf8fed..afd9dbe11 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.4.2"+ "version": "0.5.0"},"paths": {"/": {@@ -848,6 +848,41 @@"type": "object","title": "HTTPValidationError"},+ "ModelCapabilities": {+ "properties": {+ "grammar": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Grammar",+ "default": []+ },+ "tools": {+ "type": "boolean",+ "title": "Tools",+ "default": false+ },+ "code": {+ "type": "boolean",+ "title": "Code",+ "default": false+ },+ "sql": {+ "type": "boolean",+ "title": "Sql",+ "default": false+ },+ "guard": {+ "type": "boolean",+ "title": "Guard",+ "default": false+ }+ },+ "type": "object",+ "title": "ModelCapabilities",+ "description": "Advertised generation capabilities for a model.\n\nMirrors the gateway ``capabilities`` wire shape\n(``ModelCapabilitiesWire``) for the keys derivable from the loaded\nmodel config's :class:`~sie_server.config.model.GenerateCapabilities`.\n``code``/``sql``/``guard`` are informational flags advertising\nvalidated generation jobs that back the ``model=\"code\"`` /\n``model=\"sql\"`` / ``model=\"guard\"`` aliases. Populated only for\nmodels that declare ``tasks.generate``; ``None`` otherwise.\n\nThese flags mean the model *supports* a task \u2014 they are NOT a\nprecision-independent quality SLA. A flag is true at the model level even\nwhen quality is profile/precision-dependent (e.g. ``sql`` quality regresses\nunder FP8; route SQL-critical traffic to a BF16 bundle via the ``sql``\nalias)."+ },"ModelInfo": {"properties": {"name": {@@ -919,6 +954,16 @@"type": "object","title": "Profiles","default": {}+ },+ "capabilities": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ModelCapabilities"+ },+ {+ "type": "null"+ }+ ]}},"type": "object",diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex 53ff56ffa..ebd7a161a 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.4.2"+version = "0.5.0"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py b/packages/sie_server/src/sie_server/adapters/florence2/__init__.pyindex abbf59e26..8e4c47d44 100644--- a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/florence2/__init__.py@@ -29,6 +29,7 @@ from sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.core.inference_output import EncodeOutput, ExtractOutput+from sie_server.core.preprocessor.vision import resolve_florence2_promptfrom sie_server.types.inputs import media_bytesfrom sie_server.types.responses import DetectedObject, Entity@@ -247,15 +248,18 @@ class Florence2Adapter(BaseAdapter):max_new_tokens = options.get("max_new_tokens", self._max_new_tokens)num_beams = options.get("num_beams", self._num_beams)- # Build task prompt- prompt = self._build_prompt(task, labels, instruction)+ # Resolve the prompt and the effective task token. A free-text instruction+ # is answered via DocVQA, so the effective task may differ from the+ # configured one — post-processing must use the effective task to match+ # what the prompt asked the model to do.+ prompt, effective_task = resolve_florence2_prompt(task, labels, instruction)# Use preprocessed items if availableif prepared_items is not None and len(prepared_items) > 0:return self._extract_preprocessed(items=items,prepared_items=prepared_items,- task=task,+ task=effective_task,max_new_tokens=max_new_tokens,num_beams=num_beams,)@@ -267,7 +271,7 @@ class Florence2Adapter(BaseAdapter):entities, objects = self._extract_single(item,prompt=prompt,- task=task,+ task=effective_task,max_new_tokens=max_new_tokens,num_beams=num_beams,)@@ -388,16 +392,8 @@ class Florence2Adapter(BaseAdapter):Returns:Complete prompt string."""- # Use instruction as custom prompt if provided- if instruction:- return f"{task}{instruction}"-- # For phrase grounding, append labels- if task == TASK_CAPTION_TO_PHRASE_GROUNDING and labels:- label_text = ", ".join(labels)- return f"{task}{label_text}"-- return task+ prompt, _ = resolve_florence2_prompt(task, labels, instruction)+ return promptdef _extract_single(self,diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 46902d6d0..4a4711aa9 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -20,8 +20,10 @@ from __future__ import annotationsimport asyncioimport contextlib+import dataclassesimport jsonimport logging+import mathimport osimport shleximport subprocess@@ -65,6 +67,15 @@ _GENERATE_POOL_TIMEOUT_S = float(os.environ.get("SIE_SGLANG_GENERATE_POOL_TIMEOU# wait_for. Override via ``SIE_SGLANG_ABORT_REQUEST_TIMEOUT_S``._ABORT_REQUEST_TIMEOUT_S = float(os.environ.get("SIE_SGLANG_ABORT_REQUEST_TIMEOUT_S", "1.5"))+# How many leading token POSITIONS to scan for the guard's Yes/No verdict+# distribution. A guard's verdict usually sits at position 0, but a leading+# whitespace/punctuation/preamble token can push it back a slot — so we scan+# the first few positions for the first one that carries a Yes/No top_logprobs+# distribution. Mirrors the eval runner's ``content[:3]`` scan+# (``sie_bench.eval.generation_runner._p_unsafe_from_logprobs``) so serving and+# eval agree on which position the verdict is read from.+_GUARD_VERDICT_SCAN_POSITIONS = 3+def _resolve_read_timeout() -> float | None:raw = os.environ.get("SIE_SGLANG_GENERATE_READ_TIMEOUT_S")@@ -127,6 +138,14 @@ class SGLangGenerationAdapter(GenerationAdapter):grammar_backend: str | None = "outlines",reasoning_parser: str | None = None,tool_call_parser: str | None = None,+ # Generative guard models (CHECK POLICY) emit a one-token Yes/No verdict.+ # When set (``{"threshold": 0.8, "positive": "Yes"}``) the adapter reads+ # the verdict-token logprobs, computes P(unsafe) over the Yes/No tokens,+ # and returns "Yes" iff P(unsafe) >= threshold — a precision/recall dial+ # that lifts the argmax 0.16 precision (measured: F1 0.27->0.38, prec+ # 0.16->0.29 at 0.8; see the guard baseline). Only guard model YAMLs set+ # this, so it is inert for every other model.+ guard: dict[str, Any] | None = None,speculative: dict[str, Any] | None = None,extra_launch_args: list[str] | None = None,extra_env: dict[str, str] | None = None,@@ -173,6 +192,10 @@ class SGLangGenerationAdapter(GenerationAdapter):# ``--tool-call-parser`` (e.g. ``qwen3_coder`` for Qwen3.5).# Set ``None`` to omit the flag.self._tool_call_parser = tool_call_parser+ # Guard verdict thresholding (see the kwarg docstring). Empty for every+ # non-guard model, which makes the verdict rewrite in ``generate`` a+ # no-op for them.+ self._guard = guard or {}# Generic speculative-decoding surface accepts# ``{enabled, algorithm, num_steps?, eagle_topk?,# num_draft_tokens?, draft_model?}``; translated by@@ -744,6 +767,25 @@ class SGLangGenerationAdapter(GenerationAdapter):) -> AsyncIterator[GenerationChunk]:self._check_loaded()+ # Guard verdict thresholding only runs on the single-candidate (n=1)+ # path, so reject multi-candidate sampling up front — otherwise a guard+ # request with n>1 / best_of>1 would silently return an UN-thresholded+ # verdict from the multi-candidate path. Inert for non-guard models.+ if self._guard and ((n is not None and n > 1) or (best_of is not None and best_of > 1)):+ raise ValueError("guard models support single-candidate generation only (n=1, best_of<=1)")+ # Whether the CLIENT asked for logprobs, captured before the guard+ # forcing below. Guard models force logprobs on internally to compute+ # the verdict threshold; those forced logprobs are an implementation+ # detail and MUST NOT leak to a client that did not request them+ # (GenerationChunk.logprobs contract). The streaming guard intercept+ # uses this to decide whether to strip the forced logprobs.+ client_requested_logprobs = logprobs+ # Thresholding needs the verdict-token distribution — force logprobs on+ # even if the caller didn't ask. Only affects the n=1 path below.+ if self._guard:+ logprobs = True+ top_logprobs = max(top_logprobs or 0, 20)+sampling_params: dict[str, Any] = {"max_new_tokens": max_new_tokens,"temperature": temperature,@@ -810,10 +852,14 @@ class SGLangGenerationAdapter(GenerationAdapter):elif grammar.kind == "regex":sampling_params["regex"] = grammar.valueelif grammar.kind == "ebnf":- # SGLang accepts EBNF on both Outlines and XGrammar- # backends. The gateway has size-capped the source via- # ``MAX_EBNF_LEN``; further compile-time validation- # happens inside the backend.+ # SGLang accepts EBNF only on EBNF-capable backends+ # (``xgrammar``/``llguidance``) — the default ``outlines``+ # backend skips/fails it. Models must therefore only+ # advertise ``"ebnf"`` in their grammar capabilities when+ # their profile pins such a backend (gated by the gateway+ # capability check + the profile-backend consistency test).+ # The gateway has size-capped the source via ``MAX_EBNF_LEN``;+ # further compile-time validation happens inside the backend.sampling_params["ebnf"] = grammar.value# Multi-candidate (``n > 1`` and/or ``best_of``): ask SGLang for all@@ -848,6 +894,11 @@ class SGLangGenerationAdapter(GenerationAdapter):sbody["lora_path"] = lora_pathif logprobs:sbody["return_logprob"] = True+ # Without this SGLang omits the decoded token TEXT from+ # output_(top_)logprobs (entries are [logprob, token_id, None]),+ # so the OpenAI ``token`` field comes back empty and the guard+ # verdict thresholding cannot match ``yes``/``no``.+ sbody["return_text_in_logprobs"] = Trueif top_logprobs is not None and top_logprobs > 0:sbody["top_logprobs_num"] = top_logprobssclient = await self._get_or_create_http_client()@@ -974,6 +1025,9 @@ class SGLangGenerationAdapter(GenerationAdapter):nbody["lora_path"] = lora_pathif logprobs or rank:nbody["return_logprob"] = True+ # Surface decoded token text (see streaming body below) so the+ # OpenAI ``token`` field is populated and guard thresholding works.+ nbody["return_text_in_logprobs"] = Trueif top_logprobs is not None and top_logprobs > 0:nbody["top_logprobs_num"] = top_logprobsnclient = await self._get_or_create_http_client()@@ -1080,6 +1134,11 @@ class SGLangGenerationAdapter(GenerationAdapter):# .logprobs.content`` shape.if logprobs:body["return_logprob"] = True+ # SGLang only includes the decoded token TEXT in+ # output_(top_)logprobs when this is set; without it the entries are+ # [logprob, token_id, None] and the OpenAI ``token`` field (and the+ # guard ``yes``/``no`` verdict match) sees only empty strings.+ body["return_text_in_logprobs"] = Trueif top_logprobs is not None and top_logprobs > 0:body["top_logprobs_num"] = top_logprobs@@ -1122,6 +1181,20 @@ class SGLangGenerationAdapter(GenerationAdapter):# so we slice off the tail-since-last-event each# round to build per-chunk OpenAI-shape logprobs.logprobs_surfaced = 0+ # Guard verdict buffering (CHECK POLICY) — inert for non-guard+ # models. A guard's Yes/No verdict can sit a few token positions+ # in, behind a leading whitespace/punctuation/preamble token that+ # SGLang spreads across streaming chunks. We accumulate the+ # leading chunks' per-token logprob entries (``guard_lp_buffer``)+ # and SUPPRESS their text (the guard consumer wants just the+ # verdict, not the preamble) until a verdict resolves within the+ # first ``_GUARD_VERDICT_SCAN_POSITIONS`` positions — or the+ # stream terminates first, in which case we flush the raw buffered+ # chunks unchanged (fallback, never drop output).+ guard_active = bool(self._guard)+ guard_resolved = False+ guard_lp_buffer: list[dict[str, Any]] = []+ guard_pending: list[GenerationChunk] = []async for raw_line in response.aiter_lines():line = raw_line.strip()@@ -1166,10 +1239,69 @@ class SGLangGenerationAdapter(GenerationAdapter):cumulative_lp = event_meta.get("output_token_logprobs")if isinstance(cumulative_lp, list):logprobs_surfaced = max(logprobs_surfaced, len(cumulative_lp))- stream_timer.mark_yield(has_text=bool(chunk.text_delta))- yield chunk- if chunk.done:- break+ # Guard verdict thresholding (CHECK POLICY): resolve the+ # P(unsafe)>=threshold verdict from the first parseable+ # position within ``_GUARD_VERDICT_SCAN_POSITIONS`` and emit a+ # single verdict chunk. Inert for non-guard models, which take+ # the byte-for-byte unchanged ``else`` path below.+ if guard_active and not guard_resolved:+ # Accumulate this chunk's forced logprob entries so a+ # verdict that lands on a later token position is visible.+ if chunk.logprobs:+ guard_lp_buffer.extend(chunk.logprobs)+ guard_pending.append(chunk)+ verdict = _thresholded_verdict(tuple(guard_lp_buffer), self._guard)+ if verdict is not None:+ guard_resolved = True+ # Carry through terminal state if the verdict resolved+ # on (or only by) the terminal chunk, so done /+ # finish_reason / completion_tokens are preserved.+ last = guard_pending[-1]+ # Strip the internally-forced logprobs when the client+ # did not ask for them (implementation detail). When+ # the client did ask, drop the single verdict entry+ # that was consumed/rewritten (it described the raw+ # sampled token, not the served threshold verdict) and+ # keep the rest of the buffered token metadata.+ if client_requested_logprobs:+ v_idx = _verdict_position(tuple(guard_lp_buffer))+ kept = [e for i, e in enumerate(guard_lp_buffer) if i != v_idx]+ remaining = tuple(kept) or None+ else:+ remaining = None+ verdict_chunk = dataclasses.replace(+ last,+ text_delta=verdict,+ is_first=True,+ logprobs=remaining,+ )+ stream_timer.mark_yield(has_text=True)+ yield verdict_chunk+ if verdict_chunk.done:+ break+ elif chunk.done:+ # Terminal reached without a parseable verdict in the+ # first N positions: flush the raw buffered chunks+ # unchanged so the response is never dropped. Strip the+ # forced logprobs only when the client didn't ask.+ guard_resolved = True+ for buffered in guard_pending:+ if not client_requested_logprobs:+ buffered = dataclasses.replace(buffered, logprobs=None)+ stream_timer.mark_yield(has_text=bool(buffered.text_delta))+ yield buffered+ break+ # else: keep buffering (suppress this leading chunk's text).+ else:+ # Guard tail chunks (after the verdict resolved) must still+ # honour the M4 logprobs contract: strip the internally+ # forced logprobs when the client didn't request them.+ if guard_active and not client_requested_logprobs and chunk.logprobs is not None:+ chunk = dataclasses.replace(chunk, logprobs=None)+ stream_timer.mark_yield(has_text=bool(chunk.text_delta))+ yield chunk+ if chunk.done:+ breakif not terminal_yielded:raise RuntimeError("SGLang stream terminated without terminal event")@@ -1209,6 +1341,94 @@ class SGLangGenerationAdapter(GenerationAdapter):stream_timer.finalize(completion_tokens=terminal_completion_tokens)+def _p_unsafe_from_entry(entry: Any) -> float | None:+ """``P(unsafe)`` from one OpenAI-shape content token's ``top_logprobs``.++ Renormalises ``exp(lp_yes)/(exp(lp_yes)+exp(lp_no))`` over the ``yes``/``no``+ verdict tokens in this single position. ``None`` when neither appears.+ """+ if not isinstance(entry, dict):+ return None+ lp_yes: float | None = None+ lp_no: float | None = None+ for top in entry.get("top_logprobs") or []:+ if not isinstance(top, dict):+ continue+ tok = str(top.get("token") or "").strip().lower()+ val = top.get("logprob")+ if not isinstance(val, (int, float)) or isinstance(val, bool):+ continue+ if tok == "yes":+ lp_yes = val if lp_yes is None else max(lp_yes, val)+ elif tok == "no":+ lp_no = val if lp_no is None else max(lp_no, val)+ if lp_yes is None and lp_no is None:+ return None+ ey = math.exp(lp_yes) if lp_yes is not None else 0.0+ en = math.exp(lp_no) if lp_no is not None else 0.0+ return ey / (ey + en) if (ey + en) > 0 else None+++def _verdict_position(chunk_logprobs: Any, scan_positions: int = _GUARD_VERDICT_SCAN_POSITIONS) -> int | None:+ """Index of the first position (within ``scan_positions``) carrying a verdict+ distribution, or ``None``. The consumed/rewritten verdict entry the streaming+ intercept drops from client-requested logprobs.+ """+ if not chunk_logprobs:+ return None+ for idx, entry in enumerate(chunk_logprobs[:scan_positions]):+ if _p_unsafe_from_entry(entry) is not None:+ return idx+ return None+++def _p_unsafe_from_verdict_logprobs(+ chunk_logprobs: Any, scan_positions: int = _GUARD_VERDICT_SCAN_POSITIONS+) -> float | None:+ """``P(unsafe)`` from a guard verdict chunk's logprobs, or ``None``.++ ``chunk_logprobs`` is the OpenAI ``content`` shape this adapter builds —+ ``({"token", "logprob", "top_logprobs": [{"token", "logprob"}, ...]}, ...)``.+ Scans the first up-to ``scan_positions`` content tokens for the first whose+ ``top_logprobs`` carries a ``yes``/``no`` verdict distribution, then+ renormalises ``exp(lp_yes)/(exp(lp_yes)+exp(lp_no))`` over those two tokens.+ Scanning past position 0 keeps a leading whitespace/punctuation/preamble+ token from hiding the verdict, matching the eval runner's ``content[:3]``+ scan. ``None`` when no verdict token appears in range (caller keeps raw).+ """+ if not chunk_logprobs:+ return None+ for entry in chunk_logprobs[:scan_positions]:+ p_unsafe = _p_unsafe_from_entry(entry)+ if p_unsafe is not None:+ return p_unsafe+ return None+++def _thresholded_verdict(+ chunk_logprobs: Any,+ guard: dict[str, Any],+ scan_positions: int = _GUARD_VERDICT_SCAN_POSITIONS,+) -> str | None:+ """The guard's thresholded verdict token, or ``None`` to leave output as-is.++ ``guard`` is ``{"threshold": float, "positive": "Yes", "negative": "No"}``+ (positive/negative default to Yes/No). Returns the ``positive`` label iff+ ``P(unsafe) >= threshold``, else ``negative``; ``None`` when P(unsafe) can't+ be computed (no verdict logprobs within ``scan_positions``) so the raw model+ token is preserved.+ """+ p_unsafe = _p_unsafe_from_verdict_logprobs(chunk_logprobs, scan_positions)+ if p_unsafe is None:+ return None+ threshold = guard.get("threshold")+ if not isinstance(threshold, (int, float)) or isinstance(threshold, bool):+ return None+ positive = str(guard.get("positive") or "Yes")+ negative = str(guard.get("negative") or "No")+ return positive if p_unsafe >= float(threshold) else negative++def _cumulative_logprob(result: Any) -> float:"""Sum a candidate's per-token output logprobs (for ``best_of`` ranking).diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.pyindex 55f02fd69..f909f0909 100644--- a/packages/sie_server/src/sie_server/api/models.py+++ b/packages/sie_server/src/sie_server/api/models.py@@ -43,6 +43,31 @@ class ModelLoadError(BaseModel):"""True when the failure will not auto-retry; operator must intervene."""+class ModelCapabilities(BaseModel):+ """Advertised generation capabilities for a model.++ Mirrors the gateway ``capabilities`` wire shape+ (``ModelCapabilitiesWire``) for the keys derivable from the loaded+ model config's :class:`~sie_server.config.model.GenerateCapabilities`.+ ``code``/``sql``/``guard`` are informational flags advertising+ validated generation jobs that back the ``model="code"`` /+ ``model="sql"`` / ``model="guard"`` aliases. Populated only for+ models that declare ``tasks.generate``; ``None`` otherwise.++ These flags mean the model *supports* a task — they are NOT a+ precision-independent quality SLA. A flag is true at the model level even+ when quality is profile/precision-dependent (e.g. ``sql`` quality regresses+ under FP8; route SQL-critical traffic to a BF16 bundle via the ``sql``+ alias).+ """++ grammar: list[str] = []+ tools: bool = False+ code: bool = False+ sql: bool = False+ guard: bool = False++class ModelInfo(BaseModel):"""Information about a model."""@@ -62,6 +87,9 @@ class ModelInfo(BaseModel):max_sequence_length: int | None = Noneprofiles: dict[str, ProfileInfo] = {}+ capabilities: ModelCapabilities | None = None+ """Advertised generation capabilities, ``None`` for non-generate models."""+def _resolve_state_and_error(registry: "ModelRegistry | Any",@@ -104,6 +132,28 @@ def _resolve_state_and_error(return state, last_error+def _resolve_capabilities(config: Any) -> ModelCapabilities | None:+ """Build :class:`ModelCapabilities` from a loaded model config.++ Reads ``config.tasks.generate.capabilities`` (a+ :class:`~sie_server.config.model.GenerateCapabilities`) when the+ model declares a generate task; returns ``None`` for+ embedding/score/extract-only models that have no generate+ capabilities to advertise.+ """+ generate = config.tasks.generate+ if generate is None:+ return None+ caps = generate.capabilities+ return ModelCapabilities(+ grammar=list(caps.grammar),+ tools=caps.tools,+ code=caps.code,+ sql=caps.sql,+ guard=caps.guard,+ )++class ModelsListResponse(BaseModel):"""Response for listing models."""@@ -143,6 +193,7 @@ async def list_models(http_request: Request) -> ModelsListResponse:last_error=last_error,max_sequence_length=config.max_sequence_length,profiles=profiles,+ capabilities=_resolve_capabilities(config),))@@ -195,4 +246,5 @@ async def get_model(model: str, http_request: Request) -> ModelInfo:last_error=last_error,max_sequence_length=config.max_sequence_length,profiles=profiles,+ capabilities=_resolve_capabilities(config),)diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.pyindex c3c2aca66..8ea5c9bcb 100644--- a/packages/sie_server/src/sie_server/config/model.py+++ b/packages/sie_server/src/sie_server/config/model.py@@ -67,6 +67,17 @@ class GenerateCapabilities(BaseModel):grammar: list[Literal["json_schema", "regex", "ebnf"]] = []streaming: bool = Truetools: bool = False+ # Advertises that the model is validated for code generation (HumanEval /+ # MBPP pass@1 in the generation quality gate). Informational only — unlike+ # ``grammar``, the gateway does not reject requests on this flag; it lets+ # the SDK/UI surface the capability and backs the ``model="code"`` alias.+ code: bool = False+ # Same, for text-to-SQL (Spider execution accuracy); backs ``model="sql"``.+ sql: bool = False+ # Same, for the content-moderation / policy-check job (CHECK POLICY): a+ # generative guard model that emits a safe/unsafe verdict (e.g. Granite+ # Guardian, measured on ToxicChat). Backs the ``model="guard"`` alias.+ guard: bool = False# Kinds permitted in ``prewarm_grammars`` entries. Mirrors thediff --git a/packages/sie_server/src/sie_server/core/preprocessor/vision.py b/packages/sie_server/src/sie_server/core/preprocessor/vision.pyindex ac5d25915..eea85cd77 100644--- a/packages/sie_server/src/sie_server/core/preprocessor/vision.py+++ b/packages/sie_server/src/sie_server/core/preprocessor/vision.py@@ -387,6 +387,83 @@ class NemoColEmbedPreprocessor:}+# Florence-2 dispatches behaviour on a single leading task token. The processor+# asserts that region/OCR task tokens (e.g. <OCR_WITH_REGION>) stand alone, so an+# instruction must never be appended to them — a free-text instruction is a+# question and is answered through DocVQA instead.+_FLORENCE2_DOCVQA = "<DocVQA>"+_FLORENCE2_PHRASE_GROUNDING = "<CAPTION_TO_PHRASE_GROUNDING>"+_FLORENCE2_TASK_TOKENS = frozenset(+ {+ "<OCR>",+ "<OCR_WITH_REGION>",+ "<OD>",+ "<CAPTION>",+ "<DETAILED_CAPTION>",+ "<MORE_DETAILED_CAPTION>",+ "<DENSE_REGION_CAPTION>",+ "<REGION_PROPOSAL>",+ "<CAPTION_TO_PHRASE_GROUNDING>",+ "<DocVQA>",+ "<REFERRING_EXPRESSION_SEGMENTATION>",+ "<REGION_TO_SEGMENTATION>",+ "<OPEN_VOCABULARY_DETECTION>",+ "<REGION_TO_CATEGORY>",+ "<REGION_TO_DESCRIPTION>",+ "<REGION_TO_OCR>",+ }+)+++def _leading_florence2_task_token(text: str) -> str | None:+ """Return the leading Florence-2 ``<TASK>`` token of ``text``, or None."""+ if not text.startswith("<"):+ return None+ end = text.find(">")+ if end == -1:+ return None+ token = text[: end + 1]+ return token if token in _FLORENCE2_TASK_TOKENS else None+++def resolve_florence2_prompt(+ task: str,+ labels: list[str] | None,+ instruction: str | None,+) -> tuple[str, str]:+ """Resolve the Florence-2 prompt and its effective task token.++ Florence-2 selects its task from a single leading token. A free-text+ ``instruction`` is a question, so it is answered via DocVQA unless it already+ carries an explicit task token (which is then used verbatim). The configured+ ``task`` is used only when no instruction is supplied; appending an+ instruction to a region/OCR task is invalid (the processor asserts that such+ tokens must stand alone) and so is never done.++ Args:+ task: Configured task token (e.g. ``<OCR_WITH_REGION>``).+ labels: Optional labels, appended for phrase grounding.+ instruction: Optional free-text instruction or explicit ``<TASK>`` prompt.++ Returns:+ Tuple of (prompt, effective_task): the prompt string fed to the processor+ and the task token to use when post-processing the generated text.+ """+ if instruction:+ instr = instruction.strip()+ token = _leading_florence2_task_token(instr)+ if token is not None:+ body = instr[len(token) :].strip()+ return (f"{token}{body}" if body else token), token+ return f"{_FLORENCE2_DOCVQA}{instr}", _FLORENCE2_DOCVQA++ if task == _FLORENCE2_PHRASE_GROUNDING and labels:+ label_text = ", ".join(labels)+ return f"{task}{label_text}", task++ return task, task++class Florence2Preprocessor:"""Preprocessor for Florence-2 document understanding model.@@ -496,10 +573,9 @@ class Florence2Preprocessor:Returns:PreparedBatch with Florence2Payload items."""- # Build prompt- prompt = task or self._default_task- if instruction:- prompt = f"{prompt}{instruction}"+ # Build prompt. A free-text instruction is answered via DocVQA; it is+ # never appended to a region/OCR task token (see resolve_florence2_prompt).+ prompt, _ = resolve_florence2_prompt(task or self._default_task, None, instruction)# Single item: process directly (no thread pool overhead)if len(items) == 1:diff --git a/packages/sie_server/tests/adapters/test_florence2.py b/packages/sie_server/tests/adapters/test_florence2.pyindex 0a5ca30bd..a40ea9c2b 100644--- a/packages/sie_server/tests/adapters/test_florence2.py+++ b/packages/sie_server/tests/adapters/test_florence2.py@@ -109,10 +109,19 @@ class TestFlorence2Adapter:prompt = adapter._build_prompt("<OCR>", labels=None, instruction=None)assert prompt == "<OCR>"- def test_build_prompt_with_instruction(self, adapter: Florence2Adapter) -> None:- """Build prompt appends instruction."""- prompt = adapter._build_prompt("<OCR>", labels=None, instruction="Extract all text")- assert prompt == "<OCR>Extract all text"+ def test_build_prompt_free_text_instruction_uses_docvqa(self, adapter: Florence2Adapter) -> None:+ """A free-text instruction is answered via DocVQA, not appended to the task.++ Regression for #1053: appending an instruction to a region/OCR task token+ makes Florence-2's processor raise ("task token should be the only token").+ """+ prompt = adapter._build_prompt("<OCR_WITH_REGION>", labels=None, instruction="What is the title?")+ assert prompt == "<DocVQA>What is the title?"++ def test_build_prompt_instruction_with_task_token_used_verbatim(self, adapter: Florence2Adapter) -> None:+ """An instruction that already carries a task token is used verbatim (no double token)."""+ prompt = adapter._build_prompt("<DocVQA>", labels=None, instruction="<DocVQA> What is the title?")+ assert prompt == "<DocVQA>What is the title?"def test_build_prompt_phrase_grounding_with_labels(self, adapter: Florence2Adapter) -> None:"""Build prompt appends labels for phrase grounding."""@@ -159,3 +168,75 @@ class TestFlorence2Adapter:assert objects[0]["label"] == "car"assert objects[0]["score"] == 1.0assert objects[0]["bbox"] is not None++ def test_extract_threads_docvqa_task_into_postprocessing(+ self,+ adapter: Florence2Adapter,+ mock_florence2_model: MagicMock,+ mock_florence2_processor: MagicMock,+ ) -> None:+ """A free-text instruction makes extract() post-process as DocVQA, not OCR.++ Regression for #1053: the configured task is <OCR_WITH_REGION>, but an+ instruction must switch both the prompt and the post-processing to DocVQA.+ """+ import io++ from PIL import Image as PILImage+ from sie_server.types.inputs import ImageInput++ mock_florence2_processor.batch_decode.return_value = ["<s><DocVQA>1.8 to 5.5 V</s>"]+ mock_florence2_processor.post_process_generation.return_value = {"<DocVQA>": "1.8 to 5.5 V"}+ adapter._model = mock_florence2_model+ adapter._processor = mock_florence2_processor+ adapter._device = "cpu"++ buf = io.BytesIO()+ PILImage.new("RGB", (8, 8), "white").save(buf, format="JPEG")+ items = [Item(images=[ImageInput(data=buf.getvalue(), format="jpeg")])]+ out = adapter.extract(items, instruction="What is the operating voltage range?")++ # Post-processing must be asked for the DocVQA task, not the configured OCR task.+ _, kwargs = mock_florence2_processor.post_process_generation.call_args+ assert kwargs["task"] == "<DocVQA>"+ assert out.entities[0][0]["text"] == "1.8 to 5.5 V"+ assert out.entities[0][0]["label"] == "answer"+++class TestResolveFlorence2Prompt:+ """Tests for the shared Florence-2 prompt/task resolver."""++ def test_no_instruction_keeps_configured_task(self) -> None:+ from sie_server.core.preprocessor.vision import resolve_florence2_prompt++ assert resolve_florence2_prompt("<OCR_WITH_REGION>", None, None) == (+ "<OCR_WITH_REGION>",+ "<OCR_WITH_REGION>",+ )++ def test_free_text_instruction_becomes_docvqa(self) -> None:+ from sie_server.core.preprocessor.vision import resolve_florence2_prompt++ # Even though the configured task is OCR, a free-text question is DocVQA.+ assert resolve_florence2_prompt("<OCR_WITH_REGION>", None, "What is the title?") == (+ "<DocVQA>What is the title?",+ "<DocVQA>",+ )++ def test_instruction_with_task_token_is_verbatim(self) -> None:+ from sie_server.core.preprocessor.vision import resolve_florence2_prompt++ # No double task token, leading/inner whitespace normalised.+ assert resolve_florence2_prompt("<DocVQA>", None, "<DocVQA> What is the title?") == (+ "<DocVQA>What is the title?",+ "<DocVQA>",+ )+ assert resolve_florence2_prompt("<OCR_WITH_REGION>", None, "<CAPTION>") == ("<CAPTION>", "<CAPTION>")++ def test_phrase_grounding_appends_labels(self) -> None:+ from sie_server.core.preprocessor.vision import resolve_florence2_prompt++ assert resolve_florence2_prompt("<CAPTION_TO_PHRASE_GROUNDING>", ["person", "car"], None) == (+ "<CAPTION_TO_PHRASE_GROUNDING>person, car",+ "<CAPTION_TO_PHRASE_GROUNDING>",+ )diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex c29e4b01a..4e09a8dfd 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -20,7 +20,9 @@ from sie_server.adapters._generation_base import GenerationChunk, collect_generafrom sie_server.adapters.sglang.generation import (SGLangGenerationAdapter,_chunk_from_sglang_event,+ _p_unsafe_from_verdict_logprobs,_parse_sglang_generate_response,+ _thresholded_verdict,)@@ -442,6 +444,34 @@ def test_generate_request_body_uses_stream_true(mock_async_client: MagicMock, adassert "rid" in body # cancellation handle+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_logprobs_request_sets_return_text_in_logprobs(mock_async_client: MagicMock, adapter) -> None:+ """A logprobs request must ask SGLang for decoded token TEXT.++ Without ``return_text_in_logprobs`` SGLang returns+ ``[logprob, token_id, None]`` and the OpenAI ``token`` field (and the guard+ ``yes``/``no`` verdict match) sees only empty strings — confirmed on a real+ Granite Guardian L4 run.+ """+ sse_lines = [+ 'data: {"text": "x", "meta_info": {"prompt_tokens": 1, "completion_tokens": 1, "finish_reason": {"type": "stop"}}}',+ ]+ client_instance = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ mock_async_client.return_value = client_instance+ adapter._server_url = "http://localhost:30005"++ async def _drain() -> None:+ async for _ in adapter.generate(prompt="Hi", max_new_tokens=8, logprobs=True, top_logprobs=20):+ pass++ asyncio.run(_drain())++ body = client_instance.stream.call_args.kwargs["json"]+ assert body["return_logprob"] is True+ assert body["return_text_in_logprobs"] is True+ assert body["top_logprobs_num"] == 20++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")def test_generate_forwards_top_k_and_repetition_penalty(mock_async_client: MagicMock, adapter) -> None:"""``top_k`` / ``repetition_penalty`` reach SGLang's sampling_params@@ -1079,3 +1109,375 @@ def test_generate_n_gt_one_non_streaming_omits_logprobs_when_not_requested(# Ranking is enabled (best_of>n triggers return_logprob), but the# candidate's surfaced logprobs field must remain None.assert term.candidates[0]["logprobs"] is None+++def _lp(token: str, logprob: float) -> dict[str, Any]:+ return {"token": token, "logprob": logprob}+++class TestGuardVerdictThreshold:+ """P(unsafe) threshold applied to a guard model's verdict (CHECK POLICY)."""++ def _chunk_logprobs(self, lp_yes: float, lp_no: float) -> tuple[dict[str, Any], ...]:+ # One content token with a top_logprobs distribution over Yes/No.+ return ({"token": "Yes", "logprob": lp_yes, "top_logprobs": [_lp("Yes", lp_yes), _lp("No", lp_no)]},)++ def test_p_unsafe_renormalises_over_yes_no(self) -> None:+ # Equal logprobs -> 0.5; Yes dominant -> >0.5.+ assert _p_unsafe_from_verdict_logprobs(self._chunk_logprobs(-0.5, -0.5)) == pytest.approx(0.5)+ assert _p_unsafe_from_verdict_logprobs(self._chunk_logprobs(-0.1, -2.3)) > 0.8++ def test_p_unsafe_none_without_verdict_tokens(self) -> None:+ lp = ({"token": "Maybe", "logprob": -0.1, "top_logprobs": [_lp("Maybe", -0.1), _lp("Perhaps", -1.0)]},)+ assert _p_unsafe_from_verdict_logprobs(lp) is None+ assert _p_unsafe_from_verdict_logprobs(()) is None++ def test_threshold_dial(self) -> None:+ # P(unsafe)=~0.5 (equal logprobs). threshold 0.5 -> Yes; 0.8 -> No.+ lp = self._chunk_logprobs(-0.5, -0.5)+ assert _thresholded_verdict(lp, {"threshold": 0.5}) == "Yes"+ assert _thresholded_verdict(lp, {"threshold": 0.8}) == "No"++ def test_threshold_high_recall_vs_precision(self) -> None:+ # A borderline-unsafe row (P(unsafe)=0.6): caught at 0.5, missed at 0.8.+ lp = self._chunk_logprobs(-0.51, -0.92) # exp ratio ~0.6+ assert _thresholded_verdict(lp, {"threshold": 0.5}) == "Yes"+ assert _thresholded_verdict(lp, {"threshold": 0.8}) == "No"++ def test_no_threshold_or_no_logprobs_leaves_output(self) -> None:+ # Missing/invalid threshold or absent verdict logprobs -> None (raw kept).+ assert _thresholded_verdict(self._chunk_logprobs(-0.1, -2.0), {}) is None+ assert _thresholded_verdict((), {"threshold": 0.8}) is None++ def test_custom_labels(self) -> None:+ lp = self._chunk_logprobs(-0.1, -3.0) # P(unsafe) high+ assert _thresholded_verdict(lp, {"threshold": 0.5, "positive": "UNSAFE", "negative": "SAFE"}) == "UNSAFE"+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_applies_guard_threshold_in_serving_path(mock_async_client: MagicMock) -> None:+ """End-to-end: the served verdict is the thresholded one, not the raw argmax.++ The model argmax-emits "Yes" (top_logprobs Yes -0.1 / No -2.0 → P(unsafe)≈0.87),+ but a high-precision guard threshold (0.95) flips the served verdict to "No".+ Proves the SGLang adapter applies the threshold in the real streaming path.+ """+ import json as _json++ guard_adapter = SGLangGenerationAdapter(+ model_name_or_path="ibm-granite/granite-guardian-3.0-2b",+ served_model_name="ibm-granite/granite-guardian-3.0-2b",+ guard={"threshold": 0.95},+ )+ lp = {+ "output_token_logprobs": [[-0.1, 100, "Yes"]],+ "output_top_logprobs": [[[-0.1, 100, "Yes"], [-2.0, 200, "No"]]],+ }+ sse_lines = [+ "data: " + _json.dumps({"text": "Yes", "meta_info": {"prompt_tokens": 5, **lp}}),+ "data: "+ + _json.dumps(+ {+ "text": "Yes",+ "meta_info": {"prompt_tokens": 5, "completion_tokens": 1, "finish_reason": {"type": "stop"}, **lp},+ }+ ),+ "data: [DONE]",+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ guard_adapter._server_url = "http://localhost:30005"++ async def _collect() -> list[GenerationChunk]:+ out: list[GenerationChunk] = []+ async for chunk in guard_adapter.generate(prompt="is this unsafe?", max_new_tokens=8):+ out.append(chunk)+ return out++ chunks = asyncio.run(_collect())+ # The raw model token was "Yes"; the 0.95 threshold rewrites it to "No".+ assert chunks[0].text_delta == "No"+ assert chunks[0].is_first is True+ # The stale leading logprob entry (described the original "Yes") is dropped+ # so callers aren't handed token metadata inconsistent with the served verdict.+ assert chunks[0].logprobs is None+++def test_generate_rejects_multi_candidate_for_guard_models() -> None:+ """A guard request with n>1 / best_of>1 must fail fast, not silently skip the+ threshold via the multi-candidate path.+ """+ guard_adapter = SGLangGenerationAdapter(+ model_name_or_path="ibm-granite/granite-guardian-3.0-2b",+ served_model_name="ibm-granite/granite-guardian-3.0-2b",+ guard={"threshold": 0.5},+ )+ guard_adapter._server_url = "http://localhost:30005"++ async def _drive(**kw: Any) -> None:+ await guard_adapter.generate(prompt="x", max_new_tokens=8, **kw).__anext__()++ for kw in ({"n": 2}, {"best_of": 2}):+ with pytest.raises(ValueError, match="single-candidate"):+ asyncio.run(_drive(**kw))+++# -- Guard streaming: verdict-position scan + logprobs leakage (M4/H2) -------+++def _sglang_token(token: str, logprob: float, tid: int = 0) -> list[Any]:+ """One SGLang flat token-logprob entry: ``[logprob, token_id, token_text]``."""+ return [logprob, tid, token]+++def _guard_top(yes: float | None = None, no: float | None = None, *, filler: str = "x") -> list[list[Any]]:+ """Top-logprobs distribution for one position. With ``yes``/``no`` it carries+ a verdict; otherwise just a non-verdict filler token (no Yes/No).+ """+ if yes is None and no is None:+ return [_sglang_token(filler, -0.1, 1)]+ out: list[list[Any]] = []+ if yes is not None:+ out.append(_sglang_token("Yes", yes, 100))+ if no is not None:+ out.append(_sglang_token("No", no, 200))+ return out+++def _guard_event(+ text: str,+ token_lp: list[list[Any]],+ top_lp: list[list[list[Any]]],+ *,+ terminal: bool = False,+) -> str:+ """A cumulative SGLang SSE event line carrying flat + top logprobs."""+ import json as _json++ meta: dict[str, Any] = {+ "prompt_tokens": 5,+ "output_token_logprobs": token_lp,+ "output_top_logprobs": top_lp,+ }+ if terminal:+ meta["completion_tokens"] = len(token_lp)+ meta["finish_reason"] = {"type": "stop"}+ return "data: " + _json.dumps({"text": text, "meta_info": meta})+++def _guard_adapter(**guard_overrides: Any) -> SGLangGenerationAdapter:+ guard = {"threshold": 0.5, **guard_overrides}+ a = SGLangGenerationAdapter(+ model_name_or_path="ibm-granite/granite-guardian-3.0-2b",+ served_model_name="ibm-granite/granite-guardian-3.0-2b",+ guard=guard,+ )+ a._server_url = "http://localhost:30005"+ return a+++def _drive_guard(adapter: SGLangGenerationAdapter, sse_lines: list[str], **gen_kwargs: Any) -> list[GenerationChunk]:+ async def _collect() -> list[GenerationChunk]:+ out: list[GenerationChunk] = []+ async for chunk in adapter.generate(prompt="is this unsafe?", max_new_tokens=8, **gen_kwargs):+ out.append(chunk)+ return out++ return asyncio.run(_collect())+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_guard_leading_whitespace_then_verdict_applies_threshold(mock_async_client: MagicMock) -> None:+ """H2: a leading WHITESPACE token (no Yes/No at position 0) must not skip the+ threshold — the scan finds the verdict at position 1 and applies it.+ """+ # Position 0: whitespace, no verdict. Position 1: "Yes" with P(unsafe)≈0.5+ # over Yes/No (equal logprobs) → 0.5 threshold yields "Yes".+ sse_lines = [+ _guard_event(" ", [_sglang_token(" ", -0.2)], [_guard_top(filler=" ")]),+ _guard_event(+ " Yes",+ [_sglang_token(" ", -0.2), _sglang_token("Yes", -0.3, 100)],+ [_guard_top(filler=" "), _guard_top(yes=-0.5, no=-0.5)],+ terminal=True,+ ),+ "data: [DONE]",+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ chunks = _drive_guard(_guard_adapter(), sse_lines)+ verdicts = [c for c in chunks if c.text_delta]+ assert verdicts, "expected at least one verdict chunk"+ assert verdicts[0].text_delta == "Yes"+ assert verdicts[0].is_first is True+ # No leading whitespace chunk leaked.+ assert all(c.text_delta in ("Yes", "") for c in chunks)+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_guard_leading_punctuation_then_verdict_applies_threshold(mock_async_client: MagicMock) -> None:+ """H2: a leading PUNCTUATION/preamble token before the verdict is suppressed,+ and the threshold is applied to the verdict at the next position.+ """+ sse_lines = [+ _guard_event(":", [_sglang_token(":", -0.2)], [_guard_top(filler=":")]),+ _guard_event(+ ": Yes",+ [_sglang_token(":", -0.2), _sglang_token("Yes", -0.1, 100)],+ # P(unsafe) high (Yes -0.1 / No -2.0 ≈ 0.87). 0.95 threshold → "No".+ [_guard_top(filler=":"), _guard_top(yes=-0.1, no=-2.0)],+ terminal=True,+ ),+ "data: [DONE]",+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ chunks = _drive_guard(_guard_adapter(threshold=0.95), sse_lines)+ verdicts = [c for c in chunks if c.text_delta]+ assert verdicts[0].text_delta == "No" # threshold flips argmax "Yes" → "No"+ assert verdicts[0].is_first is True+ assert all(c.text_delta in ("No", "") for c in chunks)+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_guard_verdict_in_second_position_applies_threshold(mock_async_client: MagicMock) -> None:+ """H2: verdict logprobs accumulated across chunks resolve from the SECOND+ position even when both leading tokens arrive in separate stream events.+ """+ sse_lines = [+ _guard_event("Pre", [_sglang_token("Pre", -0.2)], [_guard_top(filler="Pre")]),+ _guard_event(+ "PreYes",+ [_sglang_token("Pre", -0.2), _sglang_token("Yes", -0.3, 100)],+ [_guard_top(filler="Pre"), _guard_top(yes=-0.5, no=-0.5)],+ terminal=True,+ ),+ "data: [DONE]",+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ chunks = _drive_guard(_guard_adapter(), sse_lines)+ verdicts = [c for c in chunks if c.text_delta]+ assert verdicts[0].text_delta == "Yes"+ assert verdicts[0].is_first is True+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_guard_no_verdict_in_scan_window_falls_back_to_raw(mock_async_client: MagicMock) -> None:+ """H2 fallback: no Yes/No anywhere in the first N positions → the raw buffered+ output is preserved (never dropped or hung).+ """+ sse_lines = [+ _guard_event("a", [_sglang_token("a", -0.1)], [_guard_top(filler="a")]),+ _guard_event(+ "ab",+ [_sglang_token("a", -0.1), _sglang_token("b", -0.1, 2)],+ [_guard_top(filler="a"), _guard_top(filler="b")],+ ),+ _guard_event(+ "abc",+ [_sglang_token("a", -0.1), _sglang_token("b", -0.1, 2), _sglang_token("c", -0.1, 3)],+ [_guard_top(filler="a"), _guard_top(filler="b"), _guard_top(filler="c")],+ terminal=True,+ ),+ "data: [DONE]",+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ chunks = _drive_guard(_guard_adapter(), sse_lines)+ # Raw output preserved: the concatenated deltas reproduce the model output.+ assert "".join(c.text_delta for c in chunks) == "abc"+ assert any(c.done for c in chunks)+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_guard_no_client_logprobs_strips_forced_logprobs_on_success(mock_async_client: MagicMock) -> None:+ """M4: client did NOT request logprobs → every yielded chunk has+ logprobs=None even though the guard forced logprobs internally.+ """+ sse_lines = [+ _guard_event(" ", [_sglang_token(" ", -0.2)], [_guard_top(filler=" ")]),+ _guard_event(+ " Yes",+ [_sglang_token(" ", -0.2), _sglang_token("Yes", -0.3, 100)],+ [_guard_top(filler=" "), _guard_top(yes=-0.5, no=-0.5)],+ terminal=True,+ ),+ "data: [DONE]",+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ chunks = _drive_guard(_guard_adapter(), sse_lines) # logprobs not requested+ assert all(c.logprobs is None for c in chunks)+ assert next(c for c in chunks if c.text_delta).text_delta == "Yes"+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_guard_no_client_logprobs_strips_forced_logprobs_on_fallback(mock_async_client: MagicMock) -> None:+ """M4: on the fallback path (no verdict parsed) the forced logprobs are still+ stripped when the client did not request them.+ """+ sse_lines = [+ _guard_event("a", [_sglang_token("a", -0.1)], [_guard_top(filler="a")]),+ _guard_event(+ "ab",+ [_sglang_token("a", -0.1), _sglang_token("b", -0.1, 2)],+ [_guard_top(filler="a"), _guard_top(filler="b")],+ terminal=True,+ ),+ "data: [DONE]",+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ chunks = _drive_guard(_guard_adapter(), sse_lines)+ assert all(c.logprobs is None for c in chunks)+ assert "".join(c.text_delta for c in chunks) == "ab"+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_guard_client_logprobs_preserved_minus_verdict_entry(mock_async_client: MagicMock) -> None:+ """M4: client DID request logprobs → logprobs preserved, minus the consumed+ verdict entry (the position that produced the verdict).+ """+ # Position 0: leading whitespace (no verdict). Position 1: the "Yes" verdict.+ # Both arrive in one event so the buffer holds two entries at resolution; the+ # consumed verdict entry (position 1) is dropped, the whitespace entry kept.+ sse_lines = [+ _guard_event(+ " Yes",+ [_sglang_token(" ", -0.2), _sglang_token("Yes", -0.3, 100)],+ [_guard_top(filler=" "), _guard_top(yes=-0.5, no=-0.5)],+ terminal=True,+ ),+ "data: [DONE]",+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ chunks = _drive_guard(_guard_adapter(), sse_lines, logprobs=True, top_logprobs=20)+ verdict_chunk = next(c for c in chunks if c.text_delta)+ assert verdict_chunk.text_delta == "Yes"+ # The consumed verdict entry (position 1) is dropped; the leading whitespace+ # entry remains so callers still get the surrounding token metadata.+ assert verdict_chunk.logprobs is not None+ assert [e["token"] for e in verdict_chunk.logprobs] == [" "]+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_non_guard_model_streaming_unaffected(mock_async_client: MagicMock, adapter) -> None:+ """A non-guard model takes the byte-for-byte unchanged path: no suppression,+ no stripping, logprobs only present when the client asked.+ """+ sse_lines = [+ 'data: {"text": "Hello", "meta_info": {"prompt_tokens": 5}}',+ 'data: {"text": "Hello!", "meta_info": {"prompt_tokens": 5, "completion_tokens": 2, "finish_reason": {"type": "stop"}}}',+ "data: [DONE]",+ ]+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ adapter._server_url = "http://localhost:30005"++ async def _collect() -> list[GenerationChunk]:+ out: list[GenerationChunk] = []+ async for chunk in adapter.generate(prompt="hi", max_new_tokens=8):+ out.append(chunk)+ return out++ chunks = asyncio.run(_collect())+ # Leading "Hello" chunk is NOT suppressed; deltas reproduce the output.+ assert "".join(c.text_delta for c in chunks) == "Hello!"+ assert chunks[0].text_delta == "Hello"+ assert chunks[0].is_first is True+ # Client didn't request logprobs and the model isn't a guard → all None.+ assert all(c.logprobs is None for c in chunks)+ assert any(c.done for c in chunks)diff --git a/packages/sie_server/tests/api/test_models.py b/packages/sie_server/tests/api/test_models.pyindex 4a750266d..c127a5caa 100644--- a/packages/sie_server/tests/api/test_models.py+++ b/packages/sie_server/tests/api/test_models.py@@ -8,6 +8,8 @@ from sie_server.api.models import router as models_routerfrom sie_server.config.model import (EmbeddingDim,EncodeTask,+ GenerateCapabilities,+ GenerateTask,ModelConfig,ProfileConfig,Tasks,@@ -41,6 +43,32 @@ def _make_config()+def _make_generate_config(+ sie_id: str,+ hf_id: str,+ *,+ capabilities: GenerateCapabilities,+) -> ModelConfig:+ return ModelConfig(+ sie_id=sie_id,+ hf_id=hf_id,+ tasks=Tasks(+ generate=GenerateTask(+ context_length=32768,+ max_output_tokens=4096,+ capabilities=capabilities,+ ),+ ),+ profiles={+ "default": ProfileConfig(+ adapter_path="sie_server.adapters.sglang:SGLangGenerationAdapter",+ max_batch_tokens=16384,+ kv_budget_tokens=8192,+ ),+ },+ )++@pytest.fixturedef mock_registry() -> MagicMock:"""Create a mock registry with test models."""@@ -240,3 +268,71 @@ class TestModelStateField:# a failed sibling — guard against accidental cross-talk in the# list serializer.assert by_name["model-b"].get("last_error") is None+++class TestModelCapabilitiesField:+ """Coverage for the ``capabilities`` field on ``ModelInfo``."""++ @pytest.fixture+ def caps_client(self) -> TestClient:+ """Client exposing a generate model and an encode-only model."""+ registry = MagicMock(spec=ModelRegistry)+ registry.model_names = ["gen-model", "enc-model"]++ configs = {+ "gen-model": _make_generate_config(+ "gen-model",+ "org/gen-model",+ capabilities=GenerateCapabilities(+ grammar=["json_schema", "regex"],+ tools=True,+ code=True,+ sql=True,+ guard=False,+ ),+ ),+ "enc-model": _make_config(+ "enc-model",+ "org/enc-model",+ dense_dim=768,+ ),+ }++ registry.get_config = lambda name: configs[name]+ registry.has_model = lambda name: name in configs+ registry.is_loaded = lambda _name: False+ registry.is_loading = lambda _name: False+ registry.is_unloading = lambda _name: False+ registry.is_failed = lambda _name: False+ registry.get_failure = lambda _name: None++ app = FastAPI()+ app.include_router(models_router)+ app.state.registry = registry+ return TestClient(app)++ def test_generate_model_surfaces_capabilities(self, caps_client: TestClient) -> None:+ """``code``/``sql``/``guard`` (and grammar/tools) surface for a generate model."""+ response = caps_client.get("/v1/models/gen-model")+ assert response.status_code == 200+ caps = response.json()["capabilities"]+ assert caps is not None+ assert caps["grammar"] == ["json_schema", "regex"]+ assert caps["tools"] is True+ assert caps["code"] is True+ assert caps["sql"] is True+ assert caps["guard"] is False++ def test_encode_model_has_no_capabilities(self, caps_client: TestClient) -> None:+ """Non-generate models omit generation capabilities (``None``)."""+ response = caps_client.get("/v1/models/enc-model")+ assert response.status_code == 200+ assert response.json()["capabilities"] is None++ def test_list_models_includes_capabilities(self, caps_client: TestClient) -> None:+ """``GET /v1/models`` carries per-model capabilities."""+ response = caps_client.get("/v1/models")+ assert response.status_code == 200+ by_name = {m["name"]: m for m in response.json()["models"]}+ assert by_name["gen-model"]["capabilities"]["code"] is True+ assert by_name["enc-model"]["capabilities"] is Nonediff --git a/packages/sie_server/tests/config/test_profile_backend_consistency.py b/packages/sie_server/tests/config/test_profile_backend_consistency.pyindex aa14bdd08..583a4fb34 100644--- a/packages/sie_server/tests/config/test_profile_backend_consistency.py+++ b/packages/sie_server/tests/config/test_profile_backend_consistency.py@@ -93,3 +93,75 @@ def test_status_doc_names_outlines_as_backend_of_record() -> None:f"reconciled: {hits}. Production profiles ship grammar_backend: "f"outlines; the doc must match the code.")+++MODELS_DIR = SIE_SERVER_ROOT / "models"+GUARDIAN_PROFILE = MODELS_DIR / "ibm-granite__granite-guardian-3.0-2b.yaml"++# The SGLang generation adapter defaults ``grammar_backend`` to "outlines"+# (see adapters/sglang/generation.py). Only these backends actually compile+# EBNF; outlines skips/fails it.+DEFAULT_GRAMMAR_BACKEND = "outlines"+EBNF_CAPABLE_BACKENDS = {"xgrammar", "llguidance"}+++def _grammar_capabilities(data: dict) -> list[str]:+ caps = ((data.get("tasks") or {}).get("generate") or {}).get("capabilities") or {}+ grammar = caps.get("grammar") or []+ return [str(k) for k in grammar] if isinstance(grammar, list) else []+++def test_advertised_ebnf_requires_capable_backend() -> None:+ """A model may advertise ``ebnf`` only if every profile pins an EBNF-capable backend.++ The gateway admits grammar requests purely on the advertised+ ``capabilities.grammar`` list. If a profile advertises ``ebnf`` but runs the+ default ``outlines`` backend (which cannot compile EBNF), the gateway admits+ a request the worker then fails to serve. This guards that advertise-vs-serve+ invariant across every shipped model YAML.+ """+ offenders: list[str] = []+ for path in sorted(MODELS_DIR.glob("*.yaml")):+ data = yaml.safe_load(path.read_text()) or {}+ if not isinstance(data, dict) or "ebnf" not in _grammar_capabilities(data):+ continue+ profiles = data.get("profiles") or {}+ for name, entry in profiles.items():+ if not isinstance(entry, dict):+ continue+ loadtime = (entry.get("adapter_options") or {}).get("loadtime") or {}+ backend = str(loadtime.get("grammar_backend") or DEFAULT_GRAMMAR_BACKEND)+ if backend not in EBNF_CAPABLE_BACKENDS:+ offenders.append(f"{path.name}:{name} advertises ebnf but runs grammar_backend={backend!r}")+ assert not offenders, (+ "Model(s) advertise 'ebnf' without an EBNF-capable grammar_backend "+ f"({sorted(EBNF_CAPABLE_BACKENDS)}); the gateway would admit EBNF requests "+ f"the worker cannot serve: {offenders}"+ )+++def test_guardian_profiles_carry_guard_threshold() -> None:+ """Every Granite Guardian profile must carry the guard threshold load-time dial.++ Loadtime blocks are whole-dict replaced (not deep-merged) across profiles, so+ a non-extending variant that omits ``guard`` constructs with ``self._guard={}``+ and silently skips CHECK POLICY thresholding (falls back to raw argmax).+ """+ if not GUARDIAN_PROFILE.exists():+ pytest.skip(f"Guardian profile not present at {GUARDIAN_PROFILE}")+ data = yaml.safe_load(GUARDIAN_PROFILE.read_text()) or {}+ profiles = data.get("profiles") or {}+ assert profiles, f"No profiles found in {GUARDIAN_PROFILE.name}"+ missing: list[str] = []+ for name, entry in profiles.items():+ if not isinstance(entry, dict):+ continue+ loadtime = (entry.get("adapter_options") or {}).get("loadtime") or {}+ threshold = (loadtime.get("guard") or {}).get("threshold")+ if not isinstance(threshold, (int, float)) or isinstance(threshold, bool):+ missing.append(name)+ assert not missing, (+ f"Granite Guardian profile(s) missing guard.threshold load-time config: "+ f"{missing}. Non-extending profiles do not inherit it, so the variant would "+ f"skip thresholding. Duplicate the guard block into each profile's loadtime."+ )diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lockindex 56a0b3dbc..327ee005c 100644--- a/packages/sie_server_sidecar/Cargo.lock+++ b/packages/sie_server_sidecar/Cargo.lock@@ -2216,7 +2216,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-server-sidecar"-version = "0.4.2"+version = "0.5.0"dependencies = ["anyhow","async-nats",diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex 897ac7d6b..4573f46a6 100644--- a/packages/sie_server_sidecar/Cargo.toml+++ b/packages/sie_server_sidecar/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-server-sidecar"-version = "0.4.2"+version = "0.5.0"edition = "2021"description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex f8960c79d..082cbc917 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.4.2",+ "version": "0.5.0","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.tsindex 4366cd5f8..47e325938 100644--- a/packages/sie_ts_sdk/src/index.ts+++ b/packages/sie_ts_sdk/src/index.ts@@ -40,6 +40,7 @@ export type {DetectedObject,ExtractResult,// Model and cluster info+ ModelCapabilities,ModelDims,ModelInfo,ModelState,diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex f6ee99d3a..a5e6883e0 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -115,6 +115,38 @@ export interface ModelDims {multivector?: number;}+/**+ * Advertised model capabilities.+ *+ * Mirrors the gateway `capabilities` object on each `/v1/models` entry+ * (`ModelCapabilitiesWire`). All fields are optional; their presence+ * depends on what the model config declares. `grammar` lists the+ * supported grammar kinds ("json_schema" | "regex" | "ebnf").+ * `code`/`sql`/`guard` are informational flags advertising validated+ * generation jobs that back the model="code"/"sql"/"guard" aliases.+ *+ * These flags mean the model *supports* a task — they are NOT a+ * precision-independent quality SLA. A flag is true at the model level even+ * when quality is profile/precision-dependent (e.g. `sql` quality regresses+ * under FP8; route SQL-critical traffic to a BF16 bundle via the `sql` alias).+ */+export interface ModelCapabilities {+ /** Supported grammar kinds: ["json_schema", "regex", "ebnf"] */+ grammar?: string[];+ /** Whether the model supports tool / function calling */+ tools?: boolean;+ /** Union of LoRA served-names across profiles (display summary) */+ lora_adapters?: string[];+ /** Per-profile LoRA served-names, keyed by profile name */+ profile_lora_adapters?: Record<string, string[]>;+ /** Validated for code generation; backs model="code" */+ code?: boolean;+ /** Supports text-to-SQL; backs model="sql". Precision-sensitive (FP8 regresses SQL) — a support flag, not a per-profile quality guarantee. */+ sql?: boolean;+ /** Generative guard model; backs model="guard" */+ guard?: boolean;+}+/*** Information about a model returned by listModels().*/@@ -131,6 +163,8 @@ export interface ModelInfo {dims?: ModelDims;/** Maximum sequence length the model supports */maxSequenceLength?: number;+ /** Advertised model capabilities (grammar, tools, code/sql/guard, LoRA adapters) */+ capabilities?: ModelCapabilities;}/**diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex aefb2ecd6..bd3bd8599 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.4.2"; // x-release-please-version+export const SDK_VERSION = "0.5.0"; // x-release-please-versiondiff --git a/packages/sie_ts_sdk/tests/types.test.ts b/packages/sie_ts_sdk/tests/types.test.tsindex 05b21acd3..ee1ca9c16 100644--- a/packages/sie_ts_sdk/tests/types.test.ts+++ b/packages/sie_ts_sdk/tests/types.test.ts@@ -16,6 +16,7 @@ import type {Entity,ExtractResult,Item,+ ModelCapabilities,ModelInfo,ScoreEntry,ScoreResult,@@ -394,6 +395,33 @@ describe("ModelInfo - model discovery", () => {expect(canRequestSparse(model)).toBe(true);expect(canProcessImage(model)).toBe(false);});++ it("surfaces generation capabilities for code/sql/guard discovery", () => {+ // User scenario: "Show generation models that support text-to-SQL"+ const capabilities: ModelCapabilities = {+ grammar: ["json_schema", "regex"],+ tools: true,+ lora_adapters: ["sql-lora"],+ profile_lora_adapters: { default: ["sql-lora"] },+ code: true,+ sql: true,+ guard: false,+ };++ const model: ModelInfo = {+ name: "qwen3-4b",+ loaded: true,+ inputs: ["text"],+ outputs: ["text"],+ capabilities,+ };++ expect(model.capabilities?.code).toBe(true);+ expect(model.capabilities?.sql).toBe(true);+ expect(model.capabilities?.guard).toBe(false);+ expect(model.capabilities?.grammar).toEqual(["json_schema", "regex"]);+ expect(model.capabilities?.profile_lora_adapters?.default).toEqual(["sql-lora"]);+ });});describe("Batch processing patterns", () => {diff --git a/uv.lock b/uv.lockindex cd4540930..04c1648ec 100644--- a/uv.lock+++ b/uv.lock@@ -5635,7 +5635,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.4.2"+version = "0.5.0"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5668,7 +5668,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.4.2"+version = "0.5.0"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5753,7 +5753,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.4.2"+version = "0.5.0"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5825,7 +5825,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.4.2"+version = "0.5.0"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5850,7 +5850,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.4.2"+version = "0.5.0"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5875,7 +5875,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.4.2"+version = "0.5.0"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5902,7 +5902,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.4.2"+version = "0.5.0"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -5929,7 +5929,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.4.2"+version = "0.5.0"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -5956,7 +5956,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.4.2"+version = "0.5.0"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -5983,7 +5983,7 @@ requires-dist = [[[package]]name = "sie-qdrant"-version = "0.4.2"+version = "0.5.0"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -6006,7 +6006,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.4.2"+version = "0.5.0"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -6055,7 +6055,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.4.2"+version = "0.5.0"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -6170,7 +6170,7 @@ dev = [][[package]]name = "sie-weaviate"-version = "0.4.2"+version = "0.5.0"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },