Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

release: v0.6.0

github-actions[bot]96c44d026e05
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2af769877..e8f0c6adb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,17 @@
# Changelog
+## v0.6.0
+
+- chore(main): release 0.6.0
+- fix(helm): preserve worker-group queue defaults
+- test(gateway): assert capped lane pending demand
+- docs: align queue lane naming
+- fix(helm): align lane defaults and tilt e2e
+- fix(gateway): harden queue lane admission
+- feat(gateway)!: route work by queue pool lanes
+- feat(helm)!: default SIE_POOL to pool name (not "default")
+- fix(deps): bump vitest 2.1.9 -> 4.1.0 (CVE-2026-47429)
+
## v0.5.0
- chore(main): release 0.5.0
diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yaml
index e1e29b383..2eedfe597 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 observability
type: application
-version: 0.5.0 # x-release-please-version
-appVersion: v0.5.0 # x-release-please-version
+version: 0.6.0 # x-release-please-version
+appVersion: v0.6.0 # x-release-please-version
keywords:
- inference
- embedding
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.md
index 2918de67a..7f1d1b10d 100644
--- a/deploy/helm/sie-cluster/README.md
+++ b/deploy/helm/sie-cluster/README.md
@@ -27,7 +27,7 @@ helm install sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \
- **Gateway**: Stateless request proxy that routes to workers based on GPU type and model affinity. Consumes config via GET/NATS from `sie-config`.
- **sie-config**: Authoritative control plane for model/bundle configuration. Serves `/v1/configs/*` writes and publishes NATS deltas to the gateway and workers. Deployed as a singleton (`replicas: 1`, `strategy: Recreate`).
-- **Worker Pools**: StatefulSets per GPU type, each with KEDA autoscaling.
+- **Worker Pools**: StatefulSets per enabled worker group, each with KEDA autoscaling. Routing, metrics, and KEDA scale on the full `(queuePool, machineProfile, bundle)` lane.
## Cold Start Expectations
@@ -95,17 +95,21 @@ autoscaling:
### Scale-from-Zero Trigger
-The gateway exposes `sie_gateway_pending_demand{gpu="..."}` metric when requests
-arrive for GPU types with no available workers. KEDA uses this to trigger scale-up
-even when there are 0 workers (and thus no worker metrics).
+The gateway exposes `sie_gateway_pending_demand{pool="...",machine_profile="...",bundle="..."}`
+when requests arrive for queue lanes with no available workers. KEDA uses this
+to trigger scale-up even when there are 0 workers (and thus no worker metrics).
+For `X-SIE-Pool` requests that omit `X-SIE-MACHINE-PROFILE`, the gateway can
+emit a lane-specific signal only when the registered pool spec contains exactly
+one machine profile. Multi-profile tenant pools should send both headers.
### Scaling Metrics
| Metric | Source | Purpose |
|--------|--------|---------|
| `sie_gateway_pending_demand` | Gateway | Trigger scale from 0 |
-| `sie_request_queue_depth` | Workers | Scale up on load |
-| `sie_active_requests` | Workers | Scale up on concurrent requests |
+| `sie_gateway_worker_queue_depth` | Gateway worker registry | Scale up on queued work in the exact pool/profile/bundle lane |
+| `sie_gateway_active_lease_gpus` | Gateway pool manager | Hold capacity for active pool leases in the exact pool/profile/bundle lane |
+| `sie_gateway_rejected_requests_total` | Gateway | Scale up on sustained capacity/no-worker rejections after retryable cold-load reasons are excluded |
### Worker-sidecar Metrics
@@ -139,9 +143,13 @@ rtx6000 default bundle scales 3–10 — see
```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>.
+# The map key is the Kubernetes capacity family/resource name. When
+# machineProfile is omitted, it defaults to that map key. machineProfile is the
+# runtime lane label used by routing and metrics. queuePool is the logical queue
+# namespace / tenant boundary; when omitted it inherits workers.common.queuePool,
+# then falls back to the worker group key.
+# Each worker group renders its own StatefulSet + ScaledObject named
+# worker-<pool>-<bundle>.
workers:
pools:
l4:
diff --git a/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml b/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml
index 97414f39e..9688b5ac5 100644
--- a/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml
+++ b/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml
@@ -21,13 +21,13 @@ groups:
description: "All SIE worker pods are down. Requests will fail."
- alert: SIEWorkerHighQueueDepth
- expr: sie_request_queue_depth > 50
+ expr: sie_gateway_worker_queue_depth > 50
for: 5m
labels:
severity: warning
annotations:
- summary: "High queue depth on {{ $labels.pod }}"
- description: "Worker {{ $labels.pod }} has queue depth {{ $value }} for 5 minutes. Consider scaling up."
+ summary: "High queue depth on {{ $labels.worker }}"
+ description: "Worker {{ $labels.worker }} in {{ $labels.pool }}/{{ $labels.machine_profile }}/{{ $labels.bundle }} has queue depth {{ $value }} for 5 minutes. Consider scaling up."
# GPU alerts
- name: sie-gpu-health
@@ -114,7 +114,7 @@ groups:
description: "{{ $value | humanizePercentage }} of requests are failing with non-retryable errors (excludes RESOURCE_EXHAUSTED, MODEL_LOADING, and upstream_lora_loading which the SDK auto-retries)."
- alert: SIEHighLatency
- expr: histogram_quantile(0.95, sum by (le) (rate(sie_request_duration_seconds_bucket[5m]))) > 5
+ expr: histogram_quantile(0.95, sum by (le) (rate(sie_gateway_request_latency_seconds_bucket[5m]))) > 5
for: 5m
labels:
severity: warning
diff --git a/deploy/helm/sie-cluster/files/dashboards/cluster-overview.json b/deploy/helm/sie-cluster/files/dashboards/cluster-overview.json
index 58629162f..c307ffb32 100644
--- a/deploy/helm/sie-cluster/files/dashboards/cluster-overview.json
+++ b/deploy/helm/sie-cluster/files/dashboards/cluster-overview.json
@@ -44,7 +44,7 @@
"pluginVersion": "10.0.0",
"targets": [
{
- "expr": "histogram_quantile(0.95, sum(rate(sie_request_duration_seconds_bucket{namespace=\"$namespace\"}[5m])) by (le)) * 1000",
+ "expr": "histogram_quantile(0.95, sum(rate(sie_gateway_request_latency_seconds_bucket{namespace=\"$namespace\"}[5m])) by (le)) * 1000",
"legendFormat": "p95 Latency (ms)",
"refId": "A"
}
@@ -106,12 +106,12 @@
"pluginVersion": "10.0.0",
"targets": [
{
- "expr": "sum(rate(sie_requests_total{namespace=\"$namespace\"}[5m])) by (gpu_type)",
- "legendFormat": "{{gpu_type}}",
+ "expr": "sum(rate(sie_gateway_requests_total{namespace=\"$namespace\", machine_profile=~\".+\"}[5m])) by (machine_profile)",
+ "legendFormat": "{{machine_profile}}",
"refId": "A"
}
],
- "title": "QPS by GPU Type",
+ "title": "QPS by Machine Profile",
"type": "timeseries"
},
{
@@ -124,22 +124,22 @@
"pluginVersion": "10.0.0",
"targets": [
{
- "expr": "histogram_quantile(0.50, sum(rate(sie_request_duration_seconds_bucket{namespace=\"$namespace\"}[5m])) by (le, gpu_type)) * 1000",
- "legendFormat": "{{gpu_type}} p50",
+ "expr": "histogram_quantile(0.50, sum(rate(sie_gateway_request_latency_seconds_bucket{namespace=\"$namespace\", machine_profile=~\".+\"}[5m])) by (le, machine_profile)) * 1000",
+ "legendFormat": "{{machine_profile}} p50",
"refId": "A"
},
{
- "expr": "histogram_quantile(0.95, sum(rate(sie_request_duration_seconds_bucket{namespace=\"$namespace\"}[5m])) by (le, gpu_type)) * 1000",
- "legendFormat": "{{gpu_type}} p95",
+ "expr": "histogram_quantile(0.95, sum(rate(sie_gateway_request_latency_seconds_bucket{namespace=\"$namespace\", machine_profile=~\".+\"}[5m])) by (le, machine_profile)) * 1000",
+ "legendFormat": "{{machine_profile}} p95",
"refId": "B"
},
{
- "expr": "histogram_quantile(0.99, sum(rate(sie_request_duration_seconds_bucket{namespace=\"$namespace\"}[5m])) by (le, gpu_type)) * 1000",
- "legendFormat": "{{gpu_type}} p99",
+ "expr": "histogram_quantile(0.99, sum(rate(sie_gateway_request_latency_seconds_bucket{namespace=\"$namespace\", machine_profile=~\".+\"}[5m])) by (le, machine_profile)) * 1000",
+ "legendFormat": "{{machine_profile}} p99",
"refId": "C"
}
],
- "title": "Latency by GPU Type",
+ "title": "Latency by Machine Profile",
"type": "timeseries"
},
{
@@ -152,12 +152,12 @@
"pluginVersion": "10.0.0",
"targets": [
{
- "expr": "sum(sie_request_queue_depth{namespace=\"$namespace\"}) by (gpu_type)",
- "legendFormat": "{{gpu_type}}",
+ "expr": "sum(sie_gateway_worker_queue_depth{namespace=\"$namespace\"}) by (pool, machine_profile, bundle)",
+ "legendFormat": "{{pool}}/{{machine_profile}}/{{bundle}}",
"refId": "A"
}
],
- "title": "Queue Depth by GPU Type",
+ "title": "Queue Depth by Lane",
"type": "timeseries"
},
{
diff --git a/deploy/helm/sie-cluster/files/dashboards/model-performance.json b/deploy/helm/sie-cluster/files/dashboards/model-performance.json
index f4e44e9eb..d83ea4702 100644
--- a/deploy/helm/sie-cluster/files/dashboards/model-performance.json
+++ b/deploy/helm/sie-cluster/files/dashboards/model-performance.json
@@ -84,12 +84,12 @@
"pluginVersion": "10.0.0",
"targets": [
{
- "expr": "sum(sie_request_queue_depth{namespace=\"$namespace\", model=\"$model\"}) by (pod)",
- "legendFormat": "{{pod}}",
+ "expr": "sum(sie_gateway_worker_queue_depth{namespace=\"$namespace\"}) by (worker, pool, machine_profile, bundle)",
+ "legendFormat": "{{worker}} {{pool}}/{{machine_profile}}/{{bundle}}",
"refId": "A"
}
],
- "title": "Queue Depth by Pod",
+ "title": "Queue Depth by Worker Lane",
"type": "timeseries"
},
{
diff --git a/deploy/helm/sie-cluster/templates/NOTES.txt b/deploy/helm/sie-cluster/templates/NOTES.txt
index 5a30dad51..da8a582f6 100644
--- a/deploy/helm/sie-cluster/templates/NOTES.txt
+++ b/deploy/helm/sie-cluster/templates/NOTES.txt
@@ -6,7 +6,7 @@ SIE Cluster {{ .Chart.Version }} deployed to namespace {{ include "sie-cluster.n
Gateway: http://{{ include "sie-cluster.gateway.serviceName" . }}.{{ include "sie-cluster.namespace" . }}.svc:{{ .Values.gateway.service.port }}
{{- if index .Values "kube-prometheus-stack" "install" }}
-Prometheus: enabled - kubectl port-forward -n {{ include "sie-cluster.namespace" . }} svc/prometheus-operated 9090
+Prometheus: enabled - kubectl port-forward -n {{ include "sie-cluster.namespace" . }} svc/{{ include "sie-cluster.kubePrometheusStack.prometheusServiceName" . }} 9090
Grafana: enabled - kubectl port-forward -n {{ include "sie-cluster.namespace" . }} svc/{{ .Release.Name }}-grafana 3000:80
Grafana password: kubectl get secret -n {{ include "sie-cluster.namespace" . }} {{ .Release.Name }}-grafana -o jsonpath="{.data.admin-password}" | base64 -d
{{- end }}
diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tpl
index bd5592d76..a66f43634 100644
--- a/deploy/helm/sie-cluster/templates/_helpers.tpl
+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl
@@ -115,6 +115,32 @@ Namespace to use
{{- default .Release.Namespace .Values.global.namespace }}
{{- end }}
+{{/*
+Prometheus service generated by the kube-prometheus-stack sub-chart.
+Mirrors kube-prometheus-stack's fullname helper truncation and service suffix.
+*/}}
+{{- define "sie-cluster.kubePrometheusStack.fullname" -}}
+{{- $values := (index .Values "kube-prometheus-stack") | default dict -}}
+{{- if $values.fullnameOverride -}}
+{{- $values.fullnameOverride | trunc 26 | trimSuffix "-" -}}
+{{- else -}}
+{{- $name := default "kube-prometheus-stack" $values.nameOverride -}}
+{{- if contains $name .Release.Name -}}
+{{- .Release.Name | trunc 26 | trimSuffix "-" -}}
+{{- else -}}
+{{- printf "%s-%s" .Release.Name $name | trunc 26 | trimSuffix "-" -}}
+{{- end -}}
+{{- end -}}
+{{- end }}
+
+{{- define "sie-cluster.kubePrometheusStack.prometheusServiceName" -}}
+{{- printf "%s-prometheus" (include "sie-cluster.kubePrometheusStack.fullname" .) -}}
+{{- end }}
+
+{{- define "sie-cluster.kubePrometheusStack.prometheusAddress" -}}
+{{- printf "http://%s.%s.svc.cluster.local:9090" (include "sie-cluster.kubePrometheusStack.prometheusServiceName" .) (include "sie-cluster.namespace" .) -}}
+{{- end }}
+
{{/*
Gateway image
*/}}
diff --git a/deploy/helm/sie-cluster/templates/gpu-config.yaml b/deploy/helm/sie-cluster/templates/gpu-config.yaml
index a808d95fd..e2199bd3d 100644
--- a/deploy/helm/sie-cluster/templates/gpu-config.yaml
+++ b/deploy/helm/sie-cluster/templates/gpu-config.yaml
@@ -15,7 +15,7 @@ data:
{{- $gpuAliases := dict }}
{{- range $poolName, $pool := .Values.workers.pools }}
{{- if $pool.enabled }}
- {{- $machineProfile := default $pool.gpuType $pool.machineProfile }}
+ {{- $machineProfile := default $poolName $pool.machineProfile }}
{{- $gpuTypes = append $gpuTypes $machineProfile }}
{{- $_ := set $gpuAliases $machineProfile $machineProfile }}
{{- if and $pool.gpuType (ne $pool.gpuType $machineProfile) (not (hasKey $gpuAliases $pool.gpuType)) }}
diff --git a/deploy/helm/sie-cluster/templates/hooks/prometheus-ready-test.yaml b/deploy/helm/sie-cluster/templates/hooks/prometheus-ready-test.yaml
index 691b1c405..93e882341 100644
--- a/deploy/helm/sie-cluster/templates/hooks/prometheus-ready-test.yaml
+++ b/deploy/helm/sie-cluster/templates/hooks/prometheus-ready-test.yaml
@@ -8,7 +8,7 @@
{{- $promAddr := .Values.autoscaling.prometheusAddress }}
{{- if index .Values "kube-prometheus-stack" "install" }}
{{- $promNs = include "sie-cluster.namespace" . }}
-{{- $promAddr = printf "http://prometheus-operated.%s.svc.cluster.local:9090" (include "sie-cluster.namespace" .) }}
+{{- $promAddr = include "sie-cluster.kubePrometheusStack.prometheusAddress" . }}
{{- end }}
apiVersion: v1
kind: ServiceAccount
diff --git a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml
index a361df4f4..92b7af47f 100644
--- a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml
+++ b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml
@@ -6,7 +6,7 @@
*/ -}}
{{- $promAddr := .Values.autoscaling.prometheusAddress }}
{{- if index .Values "kube-prometheus-stack" "install" }}
-{{- $promAddr = printf "http://prometheus-operated.%s.svc.cluster.local:9090" (include "sie-cluster.namespace" .) }}
+{{- $promAddr = include "sie-cluster.kubePrometheusStack.prometheusAddress" . }}
{{- end }}
{{- /*
ScaledObjects are rendered into a ConfigMap and applied by a post-install/post-upgrade
@@ -76,10 +76,11 @@ metadata:
helm.sh/hook-delete-policy: before-hook-creation
helm.sh/hook-weight: "1"
data:
- # Worker pool ScaledObjects (one per enabled (pool, bundle))
+ # Worker pool ScaledObjects (one per enabled queuePool/machineProfile/bundle lane)
{{- range $poolName, $pool := .Values.workers.pools }}
{{- if $pool.enabled }}
-{{- $machineProfile := default $pool.gpuType $pool.machineProfile }}
+{{- $machineProfile := default $poolName $pool.machineProfile }}
+{{- $queuePool := default (default $poolName $root.Values.workers.common.queuePool) $pool.queuePool }}
{{- range $bundleName, $bundleCfg := $pool.bundles }}
{{- if dig "enabled" true $bundleCfg }}
{{- $bundle := $bundleName }}
@@ -95,6 +96,7 @@ data:
sie.superlinked.com/bundle: {{ $bundle | quote }}
spec:
scaleTargetRef:
+ apiVersion: apps/v1
kind: StatefulSet
name: {{ include "sie-cluster.fullname" $root }}-worker-{{ $poolName }}-{{ $bundleName }}
minReplicaCount: {{ $bundleCfg.minReplicas }}
@@ -132,27 +134,27 @@ data:
metadata:
serverAddress: {{ $promAddr }}
metricName: sie_gateway_pending_demand_{{ $poolName }}_{{ $bundleName }}
- query: sum(sie_gateway_pending_demand{machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)
+ query: sum(sie_gateway_pending_demand{pool="{{ $queuePool }}", machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)
threshold: "1"
activationThreshold: "0"
- type: prometheus
metadata:
serverAddress: {{ $promAddr }}
metricName: sie_gateway_queue_depth_{{ $poolName }}_{{ $bundleName }}
- query: sum(sie_gateway_worker_queue_depth{machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)
+ query: sum(sie_gateway_worker_queue_depth{pool="{{ $queuePool }}", machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)
threshold: {{ $root.Values.autoscaling.queueDepthThreshold | quote }}
activationThreshold: {{ $root.Values.autoscaling.queueDepthActivation | quote }}
- type: prometheus
metadata:
serverAddress: {{ $promAddr }}
metricName: sie_gateway_active_lease_gpus_{{ $poolName }}_{{ $bundleName }}
- query: sum(sie_gateway_active_lease_gpus{machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)
+ query: sum(sie_gateway_active_lease_gpus{pool="{{ $queuePool }}", machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)
threshold: "1"
activationThreshold: "0"
- type: prometheus
metadata:
serverAddress: {{ $promAddr }}
- metricName: sie_gateway_rejected_rate_{{ $poolName }}
+ metricName: sie_gateway_rejected_rate_{{ $poolName }}_{{ $bundleName }}
# Filter out reasons the SDK already retries against the same
# worker pool; they are per-request transient signals, not
# "we need more workers" signals:
@@ -182,7 +184,7 @@ data:
# ``resource_exhausted_extended`` would NOT be excluded and
# would drive scale-up. If new retryable reasons are added in
# ``proxy.rs::record_rejected_request``, append them here.
- query: sum(rate(sie_gateway_rejected_requests_total{machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}", reason!~"resource_exhausted|upstream_model_loading|upstream_timeout_model_loading|upstream_lora_loading"}[2m])) or vector(0)
+ query: sum(rate(sie_gateway_rejected_requests_total{pool="{{ $queuePool }}", machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}", reason!~"resource_exhausted|upstream_model_loading|upstream_timeout_model_loading|upstream_lora_loading"}[2m])) or vector(0)
threshold: "1"
activationThreshold: "0"
{{- end }}
@@ -200,6 +202,7 @@ data:
{{- include "sie-cluster.gateway.labels" . | nindent 8 }}
spec:
scaleTargetRef:
+ apiVersion: apps/v1
kind: Deployment
name: {{ include "sie-cluster.gateway.serviceName" . }}
minReplicaCount: {{ .Values.gateway.replicas }}
diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
index a0a5ad713..763ffe4f7 100644
--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
@@ -22,8 +22,8 @@ fast at render time.
{{- 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 }}
+{{- $machineProfile := default $poolName $pool.machineProfile }}
+{{- $queuePool := default (default $poolName $root.Values.workers.common.queuePool) $pool.queuePool }}
{{- range $bundleName, $bundleCfg := $pool.bundles }}
{{- if dig "enabled" true $bundleCfg }}
{{- if not (hasKey $bundleCfg "minReplicas") }}
diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yaml
index 4844f3794..3c20dff2e 100644
--- a/deploy/helm/sie-cluster/values.yaml
+++ b/deploy/helm/sie-cluster/values.yaml
@@ -300,7 +300,7 @@ machineProfiles:
machineType: ""
spot: false
-# -- Worker pools configuration (one StatefulSet per pool)
+# -- Worker pools configuration (one StatefulSet per enabled queuePool/machineProfile/bundle lane)
workers:
# -- Common worker settings
common:
@@ -340,10 +340,16 @@ workers:
passthroughMode: true
# -- Logical queue pool consumed by workers in queue-routing mode.
- # Defaults to "default" so Helm WorkerGroups serve unpinned SDK traffic.
- # Override per worker pool with workers.pools.<name>.queuePool only for
- # explicit isolation pools targeted via X-SIE-Pool or gpu="pool/profile".
- queuePool: default
+ # When unset (the default), each pool uses its own name as the queue
+ # pool, so a worker in `workers.pools.rtx6000` subscribes to
+ # `sie.work.rtx6000.rtx6000.default.*` for the default bundle,
+ # preventing the cross-pool durable-consumer collision that happens
+ # when every pool shares one queue. Set this
+ # to a fixed string (e.g. `"default"`) only to deliberately share a
+ # queue across multiple pools (e.g. `l4` + `l4-spot` competing for
+ # the same work). Per-pool overrides via `workers.pools.<name>.queuePool`
+ # take precedence over both.
+ queuePool: ""
# -- Runtime class for workers (e.g., "nvidia" to enable GPU runtime)
runtimeClassName: ""
@@ -570,8 +576,9 @@ workers:
cpu: "2"
memory: "2Gi"
- # -- Worker pools (one StatefulSet per pool)
- # Each map entry creates a WorkerGroup: one StatefulSet + one pre-pull DaemonSet.
+ # -- Worker pools (one StatefulSet per enabled queuePool/machineProfile/bundle lane)
+ # Each map entry creates a WorkerGroup family: one StatefulSet + one
+ # pre-pull DaemonSet per enabled bundle.
# The map key names the Kubernetes WorkerGroup, not the SDK logical pool.
# WorkerGroup naming convention: <machineProfile> (e.g. l4, a100-40gb, cpu).
# All pools scale to zero by default; enable the ones you need.
@@ -582,15 +589,17 @@ workers:
# 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.
- # machineProfile: long label used by KEDA scalers + Prometheus.
+ # gpuType: GPU/node label used for node selection and display.
+ # machineProfile: Optional queue-lane label used by KEDA scalers,
+ # Prometheus, gateway routing, and worker subjects.
+ # Defaults to the worker group key.
# 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.
+ # If both are unset, defaults to the worker group key.
# resources: requests/limits for the Python ``worker``
# container (the GPU-bound forward-pass server).
# runtimeClassName: Optional override of common.runtimeClassName.
@@ -608,8 +617,8 @@ workers:
# 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}.
+ # Each queuePool/machineProfile/bundle lane renders one StatefulSet +
+ # KEDA ScaledObject + PDB + image-prepull DaemonSet, named worker-{pool}-{bundle}.
pools:
# L4 GPU
diff --git a/deploy/k8s/keda-scaledobject.yaml b/deploy/k8s/keda-scaledobject.yaml
index 1035d1a65..61142ca34 100644
--- a/deploy/k8s/keda-scaledobject.yaml
+++ b/deploy/k8s/keda-scaledobject.yaml
@@ -7,7 +7,12 @@
# - Prometheus available for metrics
# - SIE deployment created
#
-# Apply: kubectl apply -f keda-scaledobject.yaml
+# Apply after replacing the example lane values:
+# kubectl apply -f keda-scaledobject.yaml
+#
+# NOTE: This standalone manifest is a single-lane example. The Helm chart is
+# the production path and renders one ScaledObject per
+# (queuePool, machineProfile, bundle) lane.
---
# =============================================================================
@@ -22,14 +27,19 @@
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
- name: sie-worker-scaler
+ name: sie-worker-default-l4-default-scaler
namespace: sie
labels:
app.kubernetes.io/name: sie
app.kubernetes.io/component: worker
+ sie.superlinked.com/pool: default
+ sie.superlinked.com/machine-profile: l4
+ sie.superlinked.com/bundle: default
spec:
scaleTargetRef:
- name: sie-worker # Target deployment name
+ apiVersion: apps/v1
+ kind: StatefulSet
+ name: sie-worker-l4-default # Target worker StatefulSet for this one lane
# Replica counts
minReplicaCount: 0 # Scale to zero when idle (cost optimization)
@@ -74,25 +84,25 @@ spec:
# Triggers for scaling decisions
triggers:
- # Primary: Queue depth (most responsive)
+ # Primary: Gateway pending demand (scale-from-zero signal)
- type: prometheus
metadata:
serverAddress: http://prometheus-operated.monitoring.svc:9090
- metricName: sie_request_queue_depth
- query: sum(sie_request_queue_depth{namespace="sie"})
- threshold: '10' # Target: 10 queued requests per pod
- activationThreshold: '2' # Wake from 0 when >2 requests queued
- authenticationRef:
- name: prometheus-auth # Optional: if Prometheus requires auth
-
- # Secondary: Active requests (complementary signal)
+ metricName: sie_gateway_pending_demand_default_l4_default
+ query: sum(sie_gateway_pending_demand{namespace="sie",pool="default",machine_profile="l4",bundle="default"}) or vector(0)
+ threshold: '1'
+ activationThreshold: '0'
+ # authenticationRef: # Optional: uncomment if Prometheus requires auth
+ # name: prometheus-auth
+
+ # Secondary: Worker queue depth (steady-state backlog signal)
- type: prometheus
metadata:
serverAddress: http://prometheus-operated.monitoring.svc:9090
- metricName: sie_active_requests
- query: sum(sie_active_requests{namespace="sie"})
- threshold: '5' # Target: 5 concurrent requests per pod
- activationThreshold: '1' # Wake from 0 when >1 active request
+ metricName: sie_gateway_worker_queue_depth_default_l4_default
+ query: sum(sie_gateway_worker_queue_depth{namespace="sie",pool="default",machine_profile="l4",bundle="default"}) or vector(0)
+ threshold: '10' # Target: 10 queued requests per pod
+ activationThreshold: '2' # Wake from 0 when >2 requests queued
---
# =============================================================================
@@ -112,6 +122,8 @@ metadata:
app.kubernetes.io/component: gateway
spec:
scaleTargetRef:
+ apiVersion: apps/v1
+ kind: Deployment
name: sie-gateway
minReplicaCount: 2 # Always keep 2 for HA
diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.toml
index 0f5ba0c3b..9083912e3 100644
--- a/integrations/sie_chroma/pyproject.toml
+++ b/integrations/sie_chroma/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-chroma"
-version = "0.5.0"
+version = "0.6.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.toml
index 60961a860..8b6490f78 100644
--- a/integrations/sie_crewai/pyproject.toml
+++ b/integrations/sie_crewai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-crewai"
-version = "0.5.0"
+version = "0.6.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.toml
index bd9016837..d83133cb7 100644
--- a/integrations/sie_dspy/pyproject.toml
+++ b/integrations/sie_dspy/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-dspy"
-version = "0.5.0"
+version = "0.6.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.toml
index 50a9fa5fe..e55bdc12a 100644
--- a/integrations/sie_haystack/pyproject.toml
+++ b/integrations/sie_haystack/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-haystack"
-version = "0.5.0"
+version = "0.6.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.toml
index 6dff59a04..ddc1b2a58 100644
--- a/integrations/sie_lancedb/pyproject.toml
+++ b/integrations/sie_lancedb/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-lancedb"
-version = "0.5.0"
+version = "0.6.0"
description = "SIE integration for LanceDB"
requires-python = ">=3.12"
dependencies = [
diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.toml
index 2b0ffc87e..27e9c7f63 100644
--- a/integrations/sie_langchain/pyproject.toml
+++ b/integrations/sie_langchain/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-langchain"
-version = "0.5.0"
+version = "0.6.0"
description = "SIE integration for LangChain"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.toml
index bafbf05f5..d9bc28b53 100644
--- a/integrations/sie_llamaindex/pyproject.toml
+++ b/integrations/sie_llamaindex/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-llamaindex"
-version = "0.5.0"
+version = "0.6.0"
description = "SIE integration for LlamaIndex"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.toml
index 46cf9bb2a..67a69bf08 100644
--- a/integrations/sie_qdrant/pyproject.toml
+++ b/integrations/sie_qdrant/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-qdrant"
-version = "0.5.0"
+version = "0.6.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.json
index 8f258fedf..788099cb1 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.5.0",
+ "version": "0.6.0",
"description": "SIE embedding function for ChromaDB",
"type": "module",
"main": "./dist/index.cjs",
@@ -38,7 +38,7 @@
"chromadb": "^1.10.5",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
- "vitest": "^2.1.9"
+ "vitest": "^4.1.0"
},
"engines": {
"node": ">=22.0.0"
diff --git a/integrations/sie_ts_chroma/tests/embedding.test.ts b/integrations/sie_ts_chroma/tests/embedding.test.ts
index 64a93a0f6..a167931ea 100644
--- a/integrations/sie_ts_chroma/tests/embedding.test.ts
+++ b/integrations/sie_ts_chroma/tests/embedding.test.ts
@@ -19,7 +19,9 @@ vi.mock("@superlinked/sie-sdk", async (importOriginal) => {
return {
...actual,
- SIEClient: vi.fn().mockImplementation(() => mockClient),
+ SIEClient: vi.fn().mockImplementation(function () {
+ return mockClient;
+ }),
};
});
@@ -58,9 +60,11 @@ describe("SIEEmbeddingFunction", () => {
{ dense: new Float32Array([0.5, 0.25, 0.75]) },
{ dense: new Float32Array([1.0, 0.5, 0.25]) },
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
- }));
+ };
+ });
const ef = new SIEEmbeddingFunction({
baseUrl: "http://localhost:8080",
@@ -78,9 +82,11 @@ describe("SIEEmbeddingFunction", () => {
it("calls encode with correct parameters", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue([{ dense: new Float32Array([0.5, 0.25, 0.75]) }]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
- }));
+ };
+ });
const ef = new SIEEmbeddingFunction({
baseUrl: "http://localhost:8080",
@@ -101,9 +107,11 @@ describe("SIEEmbeddingFunction", () => {
.mockResolvedValue([
{ sparse: { indices: new Int32Array([]), values: new Float32Array([]) } },
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
- }));
+ };
+ });
const ef = new SIEEmbeddingFunction();
@@ -154,9 +162,11 @@ describe("SIESparseEmbeddingFunction", () => {
},
},
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
- }));
+ };
+ });
const ef = new SIESparseEmbeddingFunction({
baseUrl: "http://localhost:8080",
@@ -187,9 +197,11 @@ describe("SIESparseEmbeddingFunction", () => {
},
},
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
- }));
+ };
+ });
const ef = new SIESparseEmbeddingFunction({
baseUrl: "http://localhost:8080",
@@ -206,9 +218,11 @@ describe("SIESparseEmbeddingFunction", () => {
it("returns empty indices/values when sparse is missing", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue([{ dense: new Float32Array([0.5]) }]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
- }));
+ };
+ });
const ef = new SIESparseEmbeddingFunction();
const result = await ef.generate(["test"]);
@@ -226,9 +240,11 @@ describe("SIESparseEmbeddingFunction", () => {
},
},
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
- }));
+ };
+ });
const ef = new SIESparseEmbeddingFunction({
baseUrl: "http://localhost:8080",
@@ -262,9 +278,11 @@ describe("SIESparseEmbeddingFunction", () => {
},
},
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
- }));
+ };
+ });
const ef = new SIESparseEmbeddingFunction();
diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.json
index 24118256f..14b76f5d7 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.5.0",
+ "version": "0.6.0",
"description": "SIE embedding function and reranker for LanceDB",
"type": "module",
"main": "./dist/index.cjs",
@@ -39,7 +39,7 @@
"apache-arrow": "^18.1.0",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
- "vitest": "^2.1.9"
+ "vitest": "^4.1.0"
},
"engines": {
"node": ">=22.0.0"
diff --git a/integrations/sie_ts_lancedb/tests/embedding.test.ts b/integrations/sie_ts_lancedb/tests/embedding.test.ts
index 33bbc43c2..f2b3750ed 100644
--- a/integrations/sie_ts_lancedb/tests/embedding.test.ts
+++ b/integrations/sie_ts_lancedb/tests/embedding.test.ts
@@ -20,7 +20,9 @@ vi.mock("@superlinked/sie-sdk", () => {
};
return {
- SIEClient: vi.fn().mockImplementation(() => mockClient),
+ SIEClient: vi.fn().mockImplementation(function () {
+ return mockClient;
+ }),
toNumberArray: (arr: Float32Array | Int32Array | number[]) => Array.from(arr),
};
});
@@ -62,11 +64,13 @@ describe("SIEEmbeddingFunction", () => {
{ dense: new Float32Array([0.5, 0.25, 0.75]) },
{ dense: new Float32Array([1.0, 0.5, 0.25]) },
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
getModel: vi.fn(),
close: vi.fn(),
- }));
+ };
+ });
const func = new SIEEmbeddingFunction({ model: "BAAI/bge-m3" });
const embeddings = await func.generateEmbeddings(["Hello world", "Goodbye world"]);
@@ -79,11 +83,13 @@ describe("SIEEmbeddingFunction", () => {
it("calls encode with correct parameters", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue([{ dense: new Float32Array([0.5]) }]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
getModel: vi.fn(),
close: vi.fn(),
- }));
+ };
+ });
const func = new SIEEmbeddingFunction({
model: "test-model",
@@ -103,11 +109,13 @@ describe("SIEEmbeddingFunction", () => {
it("embedQuery passes isQuery: true", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue([{ dense: new Float32Array([0.5, 0.25]) }]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
getModel: vi.fn(),
close: vi.fn(),
- }));
+ };
+ });
const func = new SIEEmbeddingFunction({ model: "test-model" });
const result = await func.embedQuery("search text");
@@ -123,11 +131,13 @@ describe("SIEEmbeddingFunction", () => {
it("embedDocuments does not pass isQuery", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue([{ dense: new Float32Array([0.5]) }]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
getModel: vi.fn(),
close: vi.fn(),
- }));
+ };
+ });
const func = new SIEEmbeddingFunction({ model: "test-model" });
await func.embedDocuments(["doc text"]);
@@ -139,11 +149,13 @@ describe("SIEEmbeddingFunction", () => {
it("throws error when dense embedding is missing", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue([{ sparse: {} }]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
getModel: vi.fn(),
close: vi.fn(),
- }));
+ };
+ });
const func = new SIEEmbeddingFunction();
await expect(func.generateEmbeddings(["test"])).rejects.toThrow(
@@ -156,11 +168,13 @@ describe("SIEEmbeddingFunction", () => {
const mockGetModel = vi.fn().mockResolvedValue(
{ name: "BAAI/bge-m3", dims: { dense: 1024 }, loaded: true, inputs: ["text"], outputs: ["dense"] },
);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: vi.fn(),
getModel: mockGetModel,
close: vi.fn(),
- }));
+ };
+ });
const func = new SIEEmbeddingFunction({ model: "BAAI/bge-m3" });
const dims = await func.ndims();
@@ -174,11 +188,13 @@ describe("SIEEmbeddingFunction", () => {
const mockGetModel = vi.fn().mockResolvedValue(
{ name: "test-model", dims: { dense: 384 }, loaded: true, inputs: ["text"], outputs: ["dense"] },
);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: vi.fn(),
getModel: mockGetModel,
close: vi.fn(),
- }));
+ };
+ });
const func = new SIEEmbeddingFunction({ model: "test-model" });
await func.ndims();
@@ -192,11 +208,13 @@ describe("SIEEmbeddingFunction", () => {
const mockGetModel = vi.fn().mockResolvedValue(
{ name: "multivec-only", dims: { multivector: 128 }, loaded: true, inputs: ["text"], outputs: ["multivector"] },
);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: vi.fn(),
getModel: mockGetModel,
close: vi.fn(),
- }));
+ };
+ });
const func = new SIEEmbeddingFunction({ model: "multivec-only" });
await expect(func.ndims()).rejects.toThrow("does not support dense");
diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.json
index 815b0851e..9b438caf6 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.5.0",
+ "version": "0.6.0",
"description": "SIE embeddings integration for LangChain.js",
"type": "module",
"main": "./dist/index.cjs",
@@ -38,7 +38,7 @@
"@langchain/core": "^0.3.80",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
- "vitest": "^2.1.9"
+ "vitest": "^4.1.0"
},
"engines": {
"node": ">=22.0.0"
diff --git a/integrations/sie_ts_langchain/tests/embeddings.test.ts b/integrations/sie_ts_langchain/tests/embeddings.test.ts
index d4a2391ff..9809ac0de 100644
--- a/integrations/sie_ts_langchain/tests/embeddings.test.ts
+++ b/integrations/sie_ts_langchain/tests/embeddings.test.ts
@@ -15,7 +15,9 @@ vi.mock("@superlinked/sie-sdk", async (importOriginal) => {
return {
...actual,
- SIEClient: vi.fn().mockImplementation(() => mockClient),
+ SIEClient: vi.fn().mockImplementation(function () {
+ return mockClient;
+ }),
};
});
@@ -56,10 +58,12 @@ describe("SIEEmbeddings", () => {
{ dense: new Float32Array([0.5, 0.25, 0.75]) },
{ dense: new Float32Array([1.0, 2.0, 3.0]) },
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const embeddings = new SIEEmbeddings({ model: "test-model" });
const result = await embeddings.embedDocuments(["Hello", "World"]);
@@ -83,10 +87,12 @@ describe("SIEEmbeddings", () => {
const mockEncode = vi.fn().mockResolvedValue({
dense: new Float32Array([0.5, 0.25, 0.125]),
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const embeddings = new SIEEmbeddings({ model: "test-model" });
const result = await embeddings.embedQuery("What is this?");
@@ -106,10 +112,12 @@ describe("SIEEmbeddings", () => {
it("embedQuery throws if dense is missing", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue({});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const embeddings = new SIEEmbeddings();
await expect(embeddings.embedQuery("test")).rejects.toThrow("missing dense embedding");
@@ -120,10 +128,12 @@ describe("SIEEmbeddings", () => {
const mockEncode = vi.fn().mockResolvedValue({
dense: new Float32Array([0.5, 0.25]),
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const embeddings = new SIEEmbeddings({
instruction: "Represent this for retrieval:",
@@ -168,10 +178,12 @@ describe("SIESparseEncoder", () => {
},
},
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const encoder = new SIESparseEncoder({ model: "test-model" });
const result = await encoder.encodeQueries(["test query"]);
@@ -197,10 +209,12 @@ describe("SIESparseEncoder", () => {
.mockResolvedValue([
{ sparse: { indices: new Int32Array([2, 4]), values: new Float32Array([0.5, 0.75]) } },
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const encoder = new SIESparseEncoder();
const result = await encoder.encodeDocuments(["test doc"]);
@@ -223,10 +237,12 @@ describe("SIESparseEncoder", () => {
it("returns empty arrays when sparse is missing", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue([{}]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const encoder = new SIESparseEncoder();
const result = await encoder.encodeDocuments(["test"]);
diff --git a/integrations/sie_ts_langchain/tests/extractors.test.ts b/integrations/sie_ts_langchain/tests/extractors.test.ts
index 173b6a20f..3aa8ecf76 100644
--- a/integrations/sie_ts_langchain/tests/extractors.test.ts
+++ b/integrations/sie_ts_langchain/tests/extractors.test.ts
@@ -18,7 +18,9 @@ vi.mock("@superlinked/sie-sdk", async (importOriginal) => {
return {
...actual,
- SIEClient: vi.fn().mockImplementation(() => mockClient),
+ SIEClient: vi.fn().mockImplementation(function () {
+ return mockClient;
+ }),
};
});
@@ -58,10 +60,12 @@ describe("SIEExtractor", () => {
classifications: [],
objects: [],
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
extract: mockExtract,
close: vi.fn(),
- }));
+ };
+ });
const extractor = new SIEExtractor({ model: "test-ner" });
const result = await extractor._call("John Smith works at Acme Corp");
@@ -89,10 +93,12 @@ describe("SIEExtractor", () => {
it("passes custom labels to extract", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockExtract = vi.fn().mockResolvedValue(emptyExtractResult);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
extract: mockExtract,
close: vi.fn(),
- }));
+ };
+ });
const extractor = new SIEExtractor({
labels: ["product", "date"],
@@ -107,10 +113,12 @@ describe("SIEExtractor", () => {
it("passes threshold when specified", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockExtract = vi.fn().mockResolvedValue(emptyExtractResult);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
extract: mockExtract,
close: vi.fn(),
- }));
+ };
+ });
const extractor = new SIEExtractor({
threshold: 0.5,
@@ -126,10 +134,12 @@ describe("SIEExtractor", () => {
it("returns empty result for no extractions", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockExtract = vi.fn().mockResolvedValue(emptyExtractResult);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
extract: mockExtract,
close: vi.fn(),
- }));
+ };
+ });
const extractor = new SIEExtractor();
const result = await extractor._call("no entities here");
@@ -149,10 +159,12 @@ describe("SIEExtractor", () => {
classifications: [],
objects: [],
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
extract: mockExtract,
close: vi.fn(),
- }));
+ };
+ });
const extractor = new SIEExtractor();
const result = await extractor._call("test");
diff --git a/integrations/sie_ts_langchain/tests/rerankers.test.ts b/integrations/sie_ts_langchain/tests/rerankers.test.ts
index b585b60af..8bce62002 100644
--- a/integrations/sie_ts_langchain/tests/rerankers.test.ts
+++ b/integrations/sie_ts_langchain/tests/rerankers.test.ts
@@ -15,7 +15,9 @@ vi.mock("@superlinked/sie-sdk", async (importOriginal) => {
return {
...actual,
- SIEClient: vi.fn().mockImplementation(() => mockClient),
+ SIEClient: vi.fn().mockImplementation(function () {
+ return mockClient;
+ }),
};
});
@@ -55,10 +57,12 @@ describe("SIEReranker", () => {
{ itemId: "2", score: 0.31, rank: 2 },
],
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
score: mockScore,
close: vi.fn(),
- }));
+ };
+ });
const documents = [
{ pageContent: "First document", metadata: { source: "a" } },
@@ -97,10 +101,12 @@ describe("SIEReranker", () => {
{ itemId: "2", score: 0.31, rank: 2 },
],
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
score: mockScore,
close: vi.fn(),
- }));
+ };
+ });
const documents = [
{ pageContent: "Doc A", metadata: {} },
@@ -121,10 +127,12 @@ describe("SIEReranker", () => {
const mockScore = vi.fn().mockResolvedValue({
scores: [{ itemId: "0", score: 0.9, rank: 0 }],
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
score: mockScore,
close: vi.fn(),
- }));
+ };
+ });
const documents = [{ pageContent: "Doc", metadata: {}, id: "doc-123" }];
diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.json
index 2572af2a1..33ded824b 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.5.0",
+ "version": "0.6.0",
"description": "SIE embeddings integration for LlamaIndex.TS",
"type": "module",
"main": "./dist/index.cjs",
@@ -38,7 +38,7 @@
"llamaindex": "^0.8.37",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
- "vitest": "^2.1.9"
+ "vitest": "^4.1.0"
},
"engines": {
"node": ">=22.0.0"
diff --git a/integrations/sie_ts_llamaindex/tests/embedding.test.ts b/integrations/sie_ts_llamaindex/tests/embedding.test.ts
index 0ec01f73e..b13c670d5 100644
--- a/integrations/sie_ts_llamaindex/tests/embedding.test.ts
+++ b/integrations/sie_ts_llamaindex/tests/embedding.test.ts
@@ -15,7 +15,9 @@ vi.mock("@superlinked/sie-sdk", async (importOriginal) => {
return {
...actual,
- SIEClient: vi.fn().mockImplementation(() => mockClient),
+ SIEClient: vi.fn().mockImplementation(function () {
+ return mockClient;
+ }),
};
});
@@ -59,10 +61,12 @@ describe("SIEEmbedding", () => {
const mockEncode = vi.fn().mockResolvedValue({
dense: new Float32Array([0.5, 0.25, 0.75]),
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const embedding = new SIEEmbedding();
const result = await embedding.getTextEmbedding("Document text");
@@ -93,10 +97,12 @@ describe("SIEEmbedding", () => {
{ dense: new Float32Array([0.5, 0.25]) },
{ dense: new Float32Array([0.75, 0.125]) },
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const embedding = new SIEEmbedding();
const result = await embedding.getTextEmbeddings(["Hello", "World"]);
@@ -118,10 +124,12 @@ describe("SIEEmbedding", () => {
it("throws if dense is missing", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue({});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const embedding = new SIEEmbedding();
await expect(embedding.getTextEmbedding("test")).rejects.toThrow("missing dense embedding");
@@ -132,10 +140,12 @@ describe("SIEEmbedding", () => {
const mockEncode = vi.fn().mockResolvedValue({
dense: new Float32Array([0.5, 0.25]),
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const embedding = new SIEEmbedding({
instruction: "Represent this for retrieval:",
@@ -177,10 +187,12 @@ describe("SIESparseEmbeddingFunction", () => {
.mockResolvedValue([
{ sparse: { indices: new Int32Array([1, 5]), values: new Float32Array([0.5, 0.25]) } },
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const fn = new SIESparseEmbeddingFunction({ modelName: "test-model" });
const [indices, values] = await fn.encodeQueries(["test query"]);
@@ -205,10 +217,12 @@ describe("SIESparseEmbeddingFunction", () => {
.mockResolvedValue([
{ sparse: { indices: new Int32Array([2, 4]), values: new Float32Array([0.5, 0.75]) } },
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const fn = new SIESparseEmbeddingFunction();
const [indices, values] = await fn.encodeDocuments(["test doc"]);
@@ -229,10 +243,12 @@ describe("SIESparseEmbeddingFunction", () => {
it("returns empty arrays when sparse is missing", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockEncode = vi.fn().mockResolvedValue([{}]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const fn = new SIESparseEmbeddingFunction();
const [indices, values] = await fn.encodeDocuments(["test"]);
@@ -249,10 +265,12 @@ describe("SIESparseEmbeddingFunction", () => {
{ sparse: { indices: new Int32Array([1]), values: new Float32Array([0.5]) } },
{ sparse: { indices: new Int32Array([2, 3]), values: new Float32Array([0.25, 0.75]) } },
]);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
encode: mockEncode,
close: vi.fn(),
- }));
+ };
+ });
const fn = new SIESparseEmbeddingFunction();
const [indices, values] = await fn.encodeDocuments(["text1", "text2"]);
diff --git a/integrations/sie_ts_llamaindex/tests/extractors.test.ts b/integrations/sie_ts_llamaindex/tests/extractors.test.ts
index bbbe49254..7e739c8f6 100644
--- a/integrations/sie_ts_llamaindex/tests/extractors.test.ts
+++ b/integrations/sie_ts_llamaindex/tests/extractors.test.ts
@@ -18,7 +18,9 @@ vi.mock("@superlinked/sie-sdk", async (importOriginal) => {
return {
...actual,
- SIEClient: vi.fn().mockImplementation(() => mockClient),
+ SIEClient: vi.fn().mockImplementation(function () {
+ return mockClient;
+ }),
};
});
@@ -55,10 +57,12 @@ describe("createSIEExtractorTool", () => {
classifications: [],
objects: [],
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
extract: mockExtract,
close: vi.fn(),
- }));
+ };
+ });
const tool = createSIEExtractorTool({ modelName: "test-ner" });
const result = await tool.call({ text: "John Smith works at Acme Corp" });
@@ -86,10 +90,12 @@ describe("createSIEExtractorTool", () => {
it("passes custom labels to extract", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockExtract = vi.fn().mockResolvedValue(emptyExtractResult);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
extract: mockExtract,
close: vi.fn(),
- }));
+ };
+ });
const tool = createSIEExtractorTool({
labels: ["product", "date"],
@@ -104,10 +110,12 @@ describe("createSIEExtractorTool", () => {
it("returns empty result for no extractions", async () => {
const { SIEClient } = await import("@superlinked/sie-sdk");
const mockExtract = vi.fn().mockResolvedValue(emptyExtractResult);
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
extract: mockExtract,
close: vi.fn(),
- }));
+ };
+ });
const tool = createSIEExtractorTool();
const result = await tool.call({ text: "no entities here" });
diff --git a/integrations/sie_ts_llamaindex/tests/rerankers.test.ts b/integrations/sie_ts_llamaindex/tests/rerankers.test.ts
index 24b9ab2b2..1bafff8dc 100644
--- a/integrations/sie_ts_llamaindex/tests/rerankers.test.ts
+++ b/integrations/sie_ts_llamaindex/tests/rerankers.test.ts
@@ -16,7 +16,9 @@ vi.mock("@superlinked/sie-sdk", async (importOriginal) => {
return {
...actual,
- SIEClient: vi.fn().mockImplementation(() => mockClient),
+ SIEClient: vi.fn().mockImplementation(function () {
+ return mockClient;
+ }),
};
});
@@ -78,10 +80,12 @@ describe("SIENodePostprocessor", () => {
{ itemId: "2", score: 0.31, rank: 2 },
],
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
score: mockScore,
close: vi.fn(),
- }));
+ };
+ });
const nodes = [
mockNodeWithScore("First doc", 0.5),
@@ -121,10 +125,12 @@ describe("SIENodePostprocessor", () => {
{ itemId: "0", score: 0.72, rank: 1 },
],
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
score: mockScore,
close: vi.fn(),
- }));
+ };
+ });
const nodes = [mockNodeWithScore("doc1"), mockNodeWithScore("doc2")];
@@ -144,10 +150,12 @@ describe("SIENodePostprocessor", () => {
const mockScore = vi.fn().mockResolvedValue({
scores: [{ itemId: "0", score: 0.9, rank: 0 }],
});
- (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ (SIEClient as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {
+ return {
score: mockScore,
close: vi.fn(),
- }));
+ };
+ });
const nodes = [mockNodeWithScore("doc1")];
diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.toml
index b68534ccb..ad3367e12 100644
--- a/integrations/sie_weaviate/pyproject.toml
+++ b/integrations/sie_weaviate/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-weaviate"
-version = "0.5.0"
+version = "0.6.0"
description = "SIE integration for Weaviate"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/package.json b/package.json
index f0bb68e5e..58cfc2a0d 100644
--- a/package.json
+++ b/package.json
@@ -28,6 +28,7 @@
"tar": ">=7.5.11",
"uuid": ">=11.1.1",
"vite": "^6.4.2",
+ "vitest": "^4.1.0",
"ws": ">=8.20.1"
}
}
diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lock
index 12d59d432..ac685854f 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.5.0"
+version = "0.6.0"
dependencies = [
"arc-swap",
"async-nats",
diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.toml
index b9c124284..e00068cb1 100644
--- a/packages/sie_gateway/Cargo.toml
+++ b/packages/sie_gateway/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-gateway"
-version = "0.5.0"
+version = "0.6.0"
edition = "2021"
publish = false
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index fa920393f..8337d70a3 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -46,7 +46,7 @@ Key terms used throughout this document:
- `POST /v1/extract/{*model}`
- `POST /v1/embeddings` — OpenAI-compatible JSON surface; the gateway accepts **string** or **list of strings** for `input`, supports `encoding_format=float` (default) or `base64`, translates to an internal **`POST /v1/encode/{model}`** with `items[].text` and `params.output_types=["dense"]`, then maps encode `items[].dense` vectors into OpenAI `data[].embedding` plus a rough `usage` estimate. Token-id / nested-array inputs are rejected with **`400`**.
2. Gateway resolves the request to a model, a bundle, a machine profile, and a queue pool using its in-memory registry.
-3. Gateway publishes work to JetStream on `sie.work.{model}.{pool}`.
+3. Gateway publishes work to JetStream on `sie.work.{pool}.{machine_profile}.{bundle}.{model}`.
4. A matching worker consumes the work item and executes inference.
5. Worker publishes the result on `_INBOX.{router_id}.{request_id}` (NATS Core).
6. Gateway collects the result and returns the HTTP response.
@@ -280,8 +280,8 @@ Per-subject transport:
| Path | Subject pattern | Transport | Notes |
|---|---|---|---|
-| Inference work (`encode` / `score` / `extract`) | `sie.work.{model}.{pool}` | JetStream | Durability and max-delivery semantics required. Work-item payload is msgpack. One stream per pool (`WORK_POOL_{pool}`) captures all non-generation work for the pool; see §8.2. |
-| Generation direct-dispatch | `sie.work.{model}.{pool}.{worker_id}` | JetStream | Worker-specific stream used only by pools that host generation-capable models. Non-generation workers must not create or poll this stream; keeping them pool-only preserves queue batching for `encode` / `score` / `extract`. |
+| Inference work (`encode` / `score` / `extract`) | `sie.work.{pool}.{machine_profile}.{bundle}.{model}` | JetStream | Durability and max-delivery semantics required. Work-item payload is msgpack. One stream per pool (`WORK_POOL_{pool}`) captures all non-generation work for the pool, while worker consumers filter one concrete machine-profile/bundle lane; see §8.2. |
+| Generation direct-dispatch | `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}` | JetStream | Worker-specific stream used only by pools that host generation-capable models. Non-generation workers must not create or poll this stream; keeping them pool-only preserves queue batching for `encode` / `score` / `extract`. |
| Inference results | `_INBOX.{router_id}.{request_id}` | NATS Core | Gateway is waiting synchronously; a brief blip after publish but before delivery means the result is lost and the client retries (the gateway returns `503` with `X-SIE-Error-Code: MODEL_LOADING` and `Retry-After: 5` — see §2). Result payload is msgpack. |
| Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (§4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through Python IPC. |
| Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`). Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply; the **default `health_mode=ws`** still uses the Python WebSocket path. |
@@ -294,7 +294,7 @@ The gateway's `ensure_stream` (per pool, called lazily on first publish) creates
```
name: WORK_POOL_{pool}
-subjects: ["sie.work.*.{pool}"]
+subjects: ["sie.work.{pool}.*.*.*"]
retention: WorkQueue
storage: Memory
max_age: 60s (gateway-side)
@@ -303,11 +303,18 @@ max_msgs: 100_000
The worker-sidecar (`packages/sie_server_sidecar`, binary `sie-server-sidecar`) also calls `add_stream` with the **same** name but a default `max_age` of 120 s (`SIE_STREAM_MAX_AGE_S`). `get_or_create_stream` / `add_stream` does not update an existing stream's config, so whichever side races to the broker first wins. To avoid drift, pick one owner (either the gateway or the worker); the Helm values should set `SIE_STREAM_MAX_AGE_S` on workers to match the gateway's constant, or the gateway should read the same env.
-The stream's subject filter `sie.work.*.{pool}` matches **exactly one token** in the model position. NATS subject tokens legally contain `/`, so `BAAI/bge-m3` works directly. They cannot contain `.`, `*`, `>`, or whitespace, so any model whose `sie_id` contains one of those characters would — without normalization — expand into multiple tokens, not match the stream filter, and get rejected at the broker.
+When a gateway or sidecar observes an existing `WORK_POOL_{pool}` stream, it
+reconciles the stream subjects to exactly `sie.work.{pool}.*.*.*`. Legacy
+subjects such as `sie.work.*.{pool}` are intentionally removed from the stream
+configuration. This release is a cutover to the lane-aware subject shape, not a
+mixed-version bridge: all gateways and workers in the cluster must use the new
+shape, and any old queued work should be drained or purged before rollout.
-To prevent that, the Rust gateway's `work_subject(model, pool)` in `packages/sie_gateway/src/queue/publisher.rs` calls a private `normalize_model_id` helper that mirrors the Python SDK (`sie_sdk.queue_types.normalize_model_id`): `/` → `__`, `.` → `_dot_`, and `*`/`>`/space → `_`. So `vidore/colqwen2.5-v0.2` publishes on `sie.work.vidore__colqwen2_dot_5-v0_dot_2.default` — exactly four tokens, matches the consumer filter. The DLQ token extractor in `queue/dlq.rs` splits the advisory subject on `.` and takes `parts[2]`, which with the normalization in place is already a single safe token.
+The stream's subject filter `sie.work.{pool}.*.*.*` matches exactly one token each for machine profile, bundle, and model. Workers attach durable consumers with the narrower `sie.work.{pool}.{machine_profile}.{bundle}.*` filter, so multiple bundles can share a pool stream without stealing each other's work. NATS subject tokens legally contain `/`, so `BAAI/bge-m3` works directly. They cannot contain `.`, `*`, `>`, or whitespace, so any model whose `sie_id` contains one of those characters would — without normalization — expand into multiple tokens, not match the stream or consumer filters, and get rejected at the broker.
-Generation adds a worker-specific subject, `sie.work.{model}.{pool}.{worker_id}`, which has one additional token after the pool. That subject intentionally does not match the pool stream's `sie.work.*.{pool}` filter. The worker runtime binds the worker-specific stream only when the local pool hosts a generation model; encode-only pools keep the pre-generation queue runtime: exactly one hot JetStream consumer, the pool pull loop, the existing adaptive fetch timeout, and the existing dispatch path. This is a batching invariant, not just a resource optimization: generation-only machinery, including the streaming processor, cancel subscription, grammar prewarm, and direct-dispatch pull loop, must not start on encode-only workers because it can perturb shared NATS intake and collapse queue-side batch size. If live config reconciliation adds a generation model to a previously encode-only sidecar, the sidecar rechecks `WorkerCapabilities` and activates this worker-specific stream exactly once.
+To prevent that, the Rust gateway's `work_subject(pool, machine_profile, bundle, model)` in `packages/sie_gateway/src/queue/publisher.rs` calls a private `normalize_model_id` helper that mirrors the Python SDK (`sie_sdk.queue_types.normalize_model_id`): `/` → `__`, `.` → `_dot_`, and `*`/`>`/space → `_`. So `vidore/colqwen2.5-v0.2` on the default RTX 6000 default-bundle lane publishes on `sie.work.default.rtx6000.default.vidore__colqwen2_dot_5-v0_dot_2` — exactly six tokens, matches the lane consumer filter. The DLQ token extractor in `queue/dlq.rs` splits the advisory subject on `.` and takes `parts[5]`, which with the normalization in place is already a single safe token.
+
+Generation adds a worker-specific subject, `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`, which has one additional token after the model. That subject intentionally does not match the pool stream's `sie.work.{pool}.*.*.*` filter. The worker runtime binds the worker-specific stream only when the local pool hosts a generation model; encode-only pools keep the pre-generation queue runtime: exactly one hot JetStream consumer, the pool pull loop, the existing adaptive fetch timeout, and the existing dispatch path. This is a batching invariant, not just a resource optimization: generation-only machinery, including the streaming processor, cancel subscription, grammar prewarm, and direct-dispatch pull loop, must not start on encode-only workers because it can perturb shared NATS intake and collapse queue-side batch size. If live config reconciliation adds a generation model to a previously encode-only sidecar, the sidecar rechecks `WorkerCapabilities` and activates this worker-specific stream exactly once.
The same isolation applies in the gateway. `encode` / `score` / `extract` and `/v1/embeddings` must not pay generation-specific proxy spans, HRW/direct-dispatch routing, per-worker subjects, or trace-context envelope injection. Their work items stay on the pool JetStream subject and keep the pre-generation queue-publish hot path. Generation endpoints may open gateway spans and inject W3C trace context only on generation direct-dispatch or generation fallback work. New gateway hot-path decisions should use the shared endpoint classifier and its regression tests, not one-off string checks.
@@ -502,14 +509,14 @@ Emitted from a Tower middleware (`MetricsLayer` in `middleware/metrics.rs`) that
### 15.2 Routing outcomes — gateway
- `sie_gateway_provisioning_responses_total{machine_profile}` — counter. `202 Accepted` returned when no ready worker exists; paired with `sie_gateway_pending_demand` for KEDA scale-up.
-- `sie_gateway_rejected_requests_total{machine_profile,bundle,reason}` — counter. In-handler emission because the `reason` label (`timeout`, `capacity`, `no_workers`, ...) is too granular for the middleware.
-- `sie_gateway_pending_demand{machine_profile,bundle}` — gauge. KEDA trigger. Cleared by `clear_fulfilled_demand` when healthy workers appear.
-- `sie_gateway_active_lease_gpus{machine_profile,bundle}` — gauge. KEDA trigger. Recomputed from the current pool list on every `update_pool_metrics`.
+- `sie_gateway_rejected_requests_total{pool,machine_profile,bundle,reason}` — counter. In-handler emission because the `reason` label (`timeout`, `capacity`, `no_workers`, ...) is too granular for the middleware.
+- `sie_gateway_pending_demand{pool,machine_profile,bundle}` — gauge. KEDA trigger. Cleared by `clear_fulfilled_demand` when healthy workers appear on the exact queue lane.
+- `sie_gateway_active_lease_gpus{pool,machine_profile,bundle}` — gauge. KEDA trigger. Recomputed from the current pool list on every `update_pool_metrics`; bundle-pinned pools use the pool spec bundle, while unfiltered pools split by the assigned workers' actual bundles.
### 15.3 Worker and model state — gateway
- `sie_gateway_workers{status}` — gauge, healthy/unhealthy counts.
-- `sie_gateway_worker_queue_depth{worker,machine_profile,bundle}` — gauge.
+- `sie_gateway_worker_queue_depth{pool,worker,machine_profile,bundle}` — gauge.
- `sie_gateway_worker_memory_used_bytes{worker,machine_profile,bundle}` — gauge.
- `sie_gateway_model_workers{model}` — gauge, worker count per model.
@@ -628,11 +635,12 @@ curl -X POST https://gateway/v1/encode/BAAI/bge-m3 \
Model: BAAI/bge-m3
Bundle: default (bge_m3_flash is in the default bundle)
Pool: default (no X-SIE-POOL header, no machine-profile override)
-Subject: sie.work.BAAI__bge-m3.default
+Machine: default (no X-SIE-MACHINE-PROFILE header)
+Subject: sie.work.default.default.default.BAAI__bge-m3
Stream: WORK_POOL_default
```
-The work subject is constructed by `work_subject(model, pool)` in `queue/publisher.rs`, which runs the model id through `normalize_model_id` (the Rust mirror of `sie_sdk.queue_types.normalize_model_id`: `/` → `__`, `.` → `_dot_`, `*`/`>`/space → `_`). The result is always exactly four dot-separated tokens so it matches the worker's `sie.work.*.{pool}` consumer filter — this is the guarantee that makes dotted ids like `vidore/colqwen2.5-v0.2` work. The DLQ path extracts the third token from the advisory subject, applies the same compatibility slash normalization, and publishes on `sie.dlq.{model_normalized}` — so `sie.work.BAAI__bge-m3.default` becomes `sie.dlq.BAAI__bge-m3` when a message hits max-deliveries.
+The work subject is constructed by `work_subject(pool, machine_profile, bundle, model)` in `queue/publisher.rs`, which runs the lane tokens and model id through `normalize_model_id` (the Rust mirror of `sie_sdk.queue_types.normalize_model_id`: `/` → `__`, `.` → `_dot_`, `*`/`>`/space → `_`). The result is always exactly six dot-separated tokens so it matches the worker's `sie.work.{pool}.{machine_profile}.{bundle}.*` consumer filter — this is the guarantee that makes dotted ids like `vidore/colqwen2.5-v0.2` work. The DLQ path extracts the sixth token from the advisory subject, applies the same compatibility slash normalization, and publishes on `sie.dlq.{model_normalized}` — so `sie.work.default.default.default.BAAI__bge-m3` becomes `sie.dlq.BAAI__bge-m3` when a message hits max-deliveries.
**Step 2 — Gateway publishes work items to JetStream** (`queue/publisher.rs`). For a 2-item request the gateway publishes two msgpack work items:
@@ -646,7 +654,7 @@ WorkItem {
model_id: "BAAI/bge-m3",
profile_id: "default",
pool_name: "default",
- machine_profile: "l4-spot",
+ machine_profile: "default",
item: { "text": "..." }, // or omitted + payload_ref if >1MB
reply_subject: "_INBOX.gw-1.abc-123",
bundle_config_hash: "a1b2c3…",
@@ -711,11 +719,11 @@ POST /v1/pools
}
```
-`gpus` is required capacity; `gpu_caps` is an optional assignment cap. The `default` pool has zero requirements and no caps. The worker-sidecar polls pool status every 10 seconds before NATS pulls when the admission gate is enabled. Capped named pools fail closed unless this pod appears in `status.assigned_workers`; the `default` pool fails open during transient gateway/status errors so baseline capacity remains available. HA gateways sort workers deterministically and persist named-pool assignment status.
+`gpus` is required capacity; `gpu_caps` is an optional assignment cap. `bundle` is an optional assignment filter: when omitted, the logical pool may span multiple worker bundles and `status.assigned_workers[]` records each worker's actual bundle so `active_lease_gpus` can stay lane-aware. The `default` pool has zero requirements and no caps. The worker-sidecar polls pool status every 10 seconds before NATS pulls when the admission gate is enabled. Capped named pools fail closed unless this pod appears in `status.assigned_workers`; the `default` pool fails open during transient gateway/status errors so baseline capacity remains available. HA gateways sort workers deterministically and persist named-pool assignment status.
Helm publishes canonical machine profiles in `SIE_GATEWAY_CONFIGURED_GPUS` and request aliases in `SIE_GATEWAY_GPU_ALIASES`.
-Each pool gets its own JetStream stream (`WORK_POOL_{name}`) with subjects `sie.work.*.{name}`. Workers are deployed with `SIE_POOL={name}` and consume only from their own pool's stream. That is the isolation boundary.
+Each pool gets its own JetStream stream (`WORK_POOL_{name}`) with subjects `sie.work.{name}.*.*.*`. Workers are deployed with `SIE_POOL={name}`, `SIE_MACHINE_PROFILE={profile}`, and `SIE_BUNDLE={bundle}`; they consume only from their concrete `sie.work.{name}.{profile}.{bundle}.*` lane. The pool is the tenant/logical-capacity boundary; machine profile and bundle are the runtime lane inside that pool. A cold `X-SIE-POOL` request without `X-SIE-MACHINE-PROFILE` can emit lane-specific `pending_demand` only when the registered pool spec contains exactly one machine profile; multi-profile pools require the caller to send the profile because the gateway must not guess which StatefulSet KEDA should scale.
Creating a usable custom pool is a two-step operation: add the pool to Helm values so a `StatefulSet` of workers actually exists with `queuePool`/`SIE_POOL` set to the logical pool name, then register the pool on the gateway via `POST /v1/pools` so it tracks fulfillment and admission. Clients then target the pool with an `X-SIE-POOL: customer-acme` header. Pools expire after their TTL unless renewed with `POST /v1/pools/{name}/renew`; the `default` pool is protected and cannot be deleted.
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json
index 7547c86b0..67a1f38c6 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -21,6 +21,9 @@
},
"AssignedWorker": {
"properties": {
+ "bundle": {
+ "type": "string"
+ },
"gpu": {
"type": "string"
},
@@ -2887,7 +2890,7 @@
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
},
"title": "SIE Gateway",
- "version": "0.5.0"
+ "version": "0.6.0"
},
"openapi": "3.1.0",
"paths": {
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 325021d15..f0142d9f3 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -22,8 +22,8 @@ use crate::queue::publisher;
use crate::server::AppState;
use crate::state::model_registry::ResolveError;
-use crate::state::pool_manager::DEFAULT_POOL_NAME;
-use crate::state::worker_registry::WorkerRegistry;
+use crate::state::pool_manager::{PoolManager, DEFAULT_POOL_NAME};
+use crate::state::worker_registry::{QueueRoute, WorkerRegistry};
use crate::types::AuditEntry;
use super::models::{extract_bearer_token, mask_token};
@@ -191,41 +191,50 @@ fn parse_engine_pin(headers: &HeaderMap) -> EnginePinParse {
#[derive(Debug, PartialEq, Eq)]
enum PoolResolution {
/// A healthy worker is registered and this is the pool to publish to.
- Pool(String),
- /// No healthy worker matches `(bundle, gpu)` and the caller did not
- /// pin a specific pool — the caller should emit `202 provisioning`
- /// and record pending demand so KEDA scales up.
+ Route(QueueRoute),
+ /// No healthy worker matches the requested `(pool, machine_profile,
+ /// bundle)` lane — the caller should emit `202 provisioning` and record
+ /// pending demand so KEDA scales up.
Provisioning,
}
/// Result of `resolve_effective_pool` — bundles the routing decision
/// with a flag telling the caller whether the registry had an exact
-/// `(bundle, gpu)` worker match *before* any bundle-only fallback.
+/// `(bundle, machine_profile)` worker match.
///
/// The gateway records pending demand (for KEDA auto-scale) whenever
-/// the caller expressed a GPU preference but the exact tuple has no
+/// the caller expressed a machine-profile preference but the exact tuple has no
/// healthy worker. By reporting `exact_gpu_match` here we can fold
/// that probe into the same registry load the routing decision already
-/// does, instead of doing a separate `resolve_queue_pool` call on the
-/// hot path.
+/// does, instead of doing a separate route lookup on the hot path.
#[derive(Debug, PartialEq, Eq)]
struct PoolLookup {
resolution: PoolResolution,
- /// `true` iff a healthy worker with a non-empty pool name existed
- /// for the exact `(bundle, gpu)` tuple at lookup time.
+ /// `true` iff a healthy worker with a non-empty pool name and
+ /// machine-profile existed for the exact `(bundle, gpu)` tuple at
+ /// lookup time.
///
/// Always `false` when `gpu.is_empty()` (no exact tuple to match).
/// Caller-pinned pools still probe the registry when a GPU is
/// present so demand tracking can avoid spurious scale-up signals.
exact_gpu_match: bool,
+ /// Concrete machine-profile label that should receive pending demand
+ /// even when the caller did not send `X-SIE-MACHINE-PROFILE`.
+ ///
+ /// This is populated only when route resolution can name a cold lane
+ /// safely (for example explicit pool+GPU, or a pool spec with exactly
+ /// one profile). KEDA queries are exact `pool/profile/bundle` matches,
+ /// so recording `machine_profile=""` does not scale a specific lane.
+ pending_demand_profile: Option<String>,
}
-/// Strict allowlist for caller-supplied pool names (`[A-Za-z0-9._-]`).
+/// Strict allowlist for caller-supplied pool names (`[A-Za-z0-9_-]`).
///
/// The pool flows verbatim into the JetStream work subject
-/// `sie.work.{model}.{pool}` (see `queue::publisher::work_subject`).
+/// `sie.work.{pool}.{machine_profile}.{bundle}.{model}` (see
+/// `queue::publisher::work_subject`).
/// `model` / `worker_id` are scrubbed via `normalize_model_id`, but the
-/// pool was not — a pool containing `*`, `>`, or whitespace would
+/// pool was not — a pool containing `.`, `*`, `>`, or whitespace would
/// produce an illegal / re-tokenised subject (subject injection). Unlike
/// the model scrub (which degrades wonky chars to deterministic
/// underscores), silently mangling the pool would mis-route the request
@@ -235,9 +244,10 @@ struct PoolLookup {
fn is_valid_pool_name(pool: &str) -> bool {
!pool.is_empty()
&& pool.len() <= 128
+ && !pool.eq_ignore_ascii_case("_default")
&& pool
.chars()
- .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))
}
/// Pure decision logic for the scale-from-zero branch of `proxy_request`.
@@ -245,16 +255,18 @@ fn is_valid_pool_name(pool: &str) -> bool {
/// an `AppState` / `WorkPublisher`.
///
/// Rules:
-/// - If the caller pinned a pool via `X-SIE-Pool`, trust them and publish
-/// there unconditionally. This preserves the "power user" path where
-/// the client knows exactly which pool it wants (including cold ones
-/// that are expected to scale up on demand). The worker-side hash guard
-/// still rejects deliveries whose expected hash is unknown locally.
+/// - If the caller pinned a pool via `X-SIE-Pool` and supplied a GPU,
+/// route only when a healthy worker exists in that exact lane. Otherwise
+/// return `Provisioning` and record pending demand for the pinned lane. If
+/// they pinned only a pool, prefer a healthy worker to infer the concrete
+/// machine-profile token; when none exists, use the pool spec only if it
+/// contains exactly one machine profile so pending demand can still target a
+/// concrete KEDA lane.
/// - Otherwise look up a healthy default-pool worker for `(bundle, gpu)`.
/// The worker must also report the gateway's expected bundle config hash.
-/// If GPU was specified and the exact tuple has no worker, fall back to
-/// any default-pool worker on `bundle` (covers single-GPU clusters where
-/// the profile-level distinction is cosmetic).
+/// If GPU was specified and the exact tuple has no worker, return
+/// provisioning for that cold lane; the gateway must not silently route to
+/// another machine profile.
/// - If nothing resolves, return `Provisioning` so the caller can emit
/// `202 + Retry-After` — regardless of whether the caller sent
/// `X-SIE-MACHINE-PROFILE`. Before the fix this branch only fired when
@@ -262,62 +274,89 @@ fn is_valid_pool_name(pool: &str) -> bool {
/// timeout for default-routing clients.
async fn resolve_effective_pool(
registry: &WorkerRegistry,
+ pool_manager: Option<&PoolManager>,
bundle: &str,
gpu: &str,
pool_name: &str,
bundle_config_hash: &str,
) -> PoolLookup {
if !pool_name.is_empty() {
- // Caller pinned a pool. We still try one registry probe inside
- // that same pool to report whether its WorkerGroup is actually
- // online. Looking at any pool here would hide demand for a
- // scaled-to-zero isolation pool when default-pool workers happen
- // to exist for the same machine profile.
- let exact_gpu_match = if gpu.is_empty() {
- false
- } else {
- registry
- .resolve_queue_pool_in_pool(bundle, gpu, pool_name, bundle_config_hash)
- .await
- .is_some()
- };
+ // Caller pinned a pool. With the new subject shape, a pool-only
+ // pin is not enough to publish cold unless we can infer a single
+ // machine-profile token from the pool spec. A pool+GPU pin names the
+ // exact cold lane KEDA is expected to scale, but we still return 202
+ // until a healthy worker is present so the gateway does not publish to
+ // a stream with no active consumer.
+ if gpu.is_empty() {
+ let route = registry
+ .resolve_queue_route_in_pool(bundle, "", pool_name, bundle_config_hash)
+ .await;
+ let pending_demand_profile = if route.is_none() {
+ infer_single_pool_profile(pool_manager, pool_name).await
+ } else {
+ None
+ };
+ return PoolLookup {
+ resolution: match route {
+ Some(route) => PoolResolution::Route(route),
+ None => PoolResolution::Provisioning,
+ },
+ exact_gpu_match: false,
+ pending_demand_profile,
+ };
+ }
+
+ let route = registry
+ .resolve_queue_route_in_pool(bundle, gpu, pool_name, bundle_config_hash)
+ .await;
+ let exact_gpu_match = route.is_some();
return PoolLookup {
- resolution: PoolResolution::Pool(pool_name.to_string()),
+ resolution: match route {
+ Some(route) => PoolResolution::Route(route),
+ None => PoolResolution::Provisioning,
+ },
exact_gpu_match,
+ pending_demand_profile: if exact_gpu_match {
+ None
+ } else {
+ Some(gpu.to_string())
+ },
};
}
// Primary lookup. Folds the "was the exact tuple routable?"
// question into the same registry load we use to pick a pool.
let primary = registry
- .resolve_queue_pool_in_pool(bundle, gpu, DEFAULT_POOL_NAME, bundle_config_hash)
+ .resolve_queue_route_in_pool(bundle, gpu, DEFAULT_POOL_NAME, bundle_config_hash)
.await;
let exact_gpu_match = !gpu.is_empty() && primary.is_some();
- // Fallback: caller expressed a GPU preference but nothing matches;
- // try any healthy default-pool worker on the bundle. This covers
- // single-GPU clusters where the profile-level distinction is cosmetic
- // without leaking traffic into caller-created isolation pools.
- let resolved = match primary {
- Some(p) => Some(p),
- None if !gpu.is_empty() => {
- registry
- .resolve_queue_pool_in_pool(bundle, "", DEFAULT_POOL_NAME, bundle_config_hash)
- .await
- }
- None => None,
- };
-
- let resolution = match resolved {
- Some(p) => PoolResolution::Pool(p),
+ let resolution = match primary {
+ Some(route) => PoolResolution::Route(route),
None => PoolResolution::Provisioning,
};
+ let pending_demand_profile = if !gpu.is_empty() && !exact_gpu_match {
+ Some(gpu.to_string())
+ } else if matches!(resolution, PoolResolution::Provisioning) {
+ infer_single_pool_profile(pool_manager, DEFAULT_POOL_NAME).await
+ } else {
+ None
+ };
PoolLookup {
resolution,
exact_gpu_match,
+ pending_demand_profile,
}
}
+async fn infer_single_pool_profile(
+ pool_manager: Option<&PoolManager>,
+ pool_name: &str,
+) -> Option<String> {
+ let manager = pool_manager?;
+ manager.single_machine_profile_for_pool(pool_name).await
+}
+
fn build_provisioning_response(gpu: &str, bundle: &str) -> Response {
let gpu_label = if gpu.is_empty() { "any" } else { gpu };
info!(
@@ -365,6 +404,48 @@ fn build_provisioning_response(gpu: &str, bundle: &str) -> Response {
resp
}
+async fn capped_lane_admission_response(
+ state: &AppState,
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+) -> Option<Response> {
+ let admission = state
+ .pool_manager
+ .capped_lane_status(pool, machine_profile, bundle)
+ .await?;
+
+ if admission.cap == 0 {
+ metrics::record_rejected_request_for_pool(pool, machine_profile, bundle, "pool_cap_zero");
+ let mut m = Map::new();
+ m.insert("pool".to_string(), json!(pool));
+ m.insert("gpu".to_string(), json!(machine_profile));
+ m.insert("bundle".to_string(), json!(bundle));
+ m.insert("cap".to_string(), json!(admission.cap));
+ return Some(
+ (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(json_detail_merge(
+ err_code::POOL_CAPACITY_UNAVAILABLE,
+ format!(
+ "Pool '{}' admits zero workers for GPU type '{}' and bundle '{}'.",
+ pool, machine_profile, bundle
+ ),
+ m,
+ )),
+ )
+ .into_response(),
+ );
+ }
+
+ if admission.assigned_count == 0 {
+ state.demand_tracker.record(pool, machine_profile, bundle);
+ return Some(build_provisioning_response(machine_profile, bundle));
+ }
+
+ None
+}
+
#[utoipa::path(
post,
path = "/v1/encode/{model}",
@@ -592,7 +673,7 @@ async fn proxy_request(
// placeholder labels. `record_rejected_request` normalizes
// empty `machine_profile` to `"unknown"` internally; `bundle`
// gets the same treatment here for cardinality discipline.
- metrics::record_rejected_request("", "unknown", "model_required");
+ metrics::record_rejected_request_for_pool("unknown", "", "unknown", "model_required");
return endpoint_error_response(
endpoint,
StatusCode::BAD_REQUEST,
@@ -743,13 +824,14 @@ async fn proxy_request(
// Validate the caller-supplied pool against a strict allowlist
// BEFORE it can flow into the JetStream work subject
- // `sie.work.{model}.{pool}`. An out-of-charset pool would otherwise
+ // `sie.work.{pool}.{machine_profile}.{bundle}.{model}`. An
+ // out-of-charset pool would otherwise
// re-tokenise the subject (subject injection) and silently mis-route
// the request, so reject with an OpenAI-shaped 400 rather than
// mangle. Empty pool means "router picks the default pool" and is
// left untouched.
if !pool_name.is_empty() && !is_valid_pool_name(&pool_name) {
- metrics::record_rejected_request(&gpu, &bundle, "invalid_pool");
+ metrics::record_rejected_request_for_pool("unknown", &gpu, &bundle, "invalid_pool");
return endpoint_error_response(
endpoint,
StatusCode::BAD_REQUEST,
@@ -757,7 +839,7 @@ async fn proxy_request(
oai_type::INVALID_REQUEST,
oai_code::INVALID_REQUEST,
Some("pool"),
- "Invalid pool name: only [A-Za-z0-9._-] are allowed (max 128 chars)",
+ "Invalid pool name: only [A-Za-z0-9_-] are allowed (max 128 chars)",
);
}
@@ -807,7 +889,17 @@ async fn proxy_request(
// Bucket the rejected GPU under a fixed sentinel for the
// metric; the actual value is still surfaced in the response
// body below for operator debugging.
- metrics::record_rejected_request("invalid", &bundle, "gpu_not_configured");
+ let metric_pool = if pool_name.is_empty() {
+ DEFAULT_POOL_NAME
+ } else {
+ pool_name.as_str()
+ };
+ metrics::record_rejected_request_for_pool(
+ metric_pool,
+ "invalid",
+ &bundle,
+ "gpu_not_configured",
+ );
let mut m = Map::new();
m.insert("gpu".to_string(), json!(&gpu));
m.insert(
@@ -826,7 +918,12 @@ async fn proxy_request(
}
let Some(work_publisher) = state.work_publisher.as_ref() else {
- metrics::record_rejected_request(&gpu, &bundle, "queue_unavailable");
+ let metric_pool = if pool_name.is_empty() {
+ DEFAULT_POOL_NAME
+ } else {
+ pool_name.as_str()
+ };
+ metrics::record_rejected_request_for_pool(metric_pool, &gpu, &bundle, "queue_unavailable");
return endpoint_error_response(
endpoint,
StatusCode::SERVICE_UNAVAILABLE,
@@ -841,28 +938,34 @@ async fn proxy_request(
let bundle_config_hash = state.model_registry.compute_bundle_config_hash(&bundle);
// Resolve the effective pool in one shot. `resolve_effective_pool`
- // folds the demand-tracking probe ("was there an exact (bundle,
- // gpu) match?") into the same registry load it uses to pick a
- // pool, so we don't make two `resolve_queue_pool` calls on the
- // hot path. The `exact_gpu_match` flag is what drives pending
- // demand for KEDA — we record whenever the caller expressed a GPU
- // preference but no exact-tuple worker was registered, regardless
- // of whether we still serve this request via bundle-fallback or a
- // pinned pool (see `test_scaling.py::test_pending_demand_*`).
+ // folds the demand-tracking probe ("was there an exact
+ // (bundle, machine_profile) match?") into the same registry load it uses to pick a
+ // route, so we don't make two registry route-resolution calls on the
+ // hot path. The `pending_demand_profile` field is what drives KEDA:
+ // it is set when the caller expressed a GPU preference but no
+ // exact-tuple worker was registered, or when a cold pool-only request
+ // can be mapped to a single machine profile from the pool spec.
let lookup = resolve_effective_pool(
&state.registry,
+ Some(&state.pool_manager),
&bundle,
&gpu,
&pool_name,
&bundle_config_hash,
)
.await;
- if !gpu.is_empty() && !lookup.exact_gpu_match {
- state.demand_tracker.record(&gpu, &bundle);
+ let demand_pool = if pool_name.is_empty() {
+ DEFAULT_POOL_NAME
+ } else {
+ pool_name.as_str()
+ };
+ let pending_demand_profile = lookup.pending_demand_profile.clone();
+ if let Some(profile) = pending_demand_profile.as_deref() {
+ state.demand_tracker.record(demand_pool, profile, &bundle);
}
- let effective_pool = match lookup.resolution {
- PoolResolution::Pool(p) => p,
+ let effective_route = match lookup.resolution {
+ PoolResolution::Route(route) => route,
PoolResolution::Provisioning => {
let gpu_label = if gpu.is_empty() { "any" } else { gpu.as_str() };
info!(
@@ -874,77 +977,24 @@ async fn proxy_request(
metrics::PROVISIONING_RESPONSES
.with_label_values(&[gpu_label])
.inc();
- // Note: if the caller expressed a GPU preference, demand
- // was already recorded above via `exact_gpu_match = false`.
- // We still record here (idempotent — see
- // `DemandTracker::record`) so the empty-GPU case also
- // gets a pending-demand entry, matching the prior
- // behavior exactly.
- state.demand_tracker.record(&gpu, &bundle);
+ // If route resolution named a concrete cold lane, demand was
+ // recorded above with that machine-profile label. Otherwise keep
+ // the legacy empty/unknown-profile series for observability even
+ // though KEDA cannot scale a lane without a profile token.
+ if pending_demand_profile.is_none() {
+ state.demand_tracker.record(demand_pool, &gpu, &bundle);
+ }
return build_provisioning_response(&gpu, &bundle);
}
};
+ let effective_pool = &effective_route.pool_name;
+ let effective_machine_profile = &effective_route.machine_profile;
- if !pool_name.is_empty() {
- if gpu.is_empty() {
- if let Some(admission) = state.pool_manager.capped_pool_status(&effective_pool).await {
- let all_capped_profiles_zero = !admission.capped_profiles.is_empty()
- && admission.capped_profiles.len() == admission.zero_cap_profiles.len();
- if !admission.has_uncapped_profiles && all_capped_profiles_zero {
- metrics::record_rejected_request(&gpu, &bundle, "pool_cap_zero");
- let mut m = Map::new();
- m.insert("pool".to_string(), json!(&effective_pool));
- m.insert("gpu".to_string(), json!(&gpu));
- m.insert("profiles".to_string(), json!(admission.zero_cap_profiles));
- return (
- StatusCode::SERVICE_UNAVAILABLE,
- Json(json_detail_merge(
- err_code::POOL_CAPACITY_UNAVAILABLE,
- format!(
- "Pool '{}' admits zero workers for all capped GPU profiles.",
- effective_pool
- ),
- m,
- )),
- )
- .into_response();
- }
-
- if admission.total_assigned_count == 0 {
- state.demand_tracker.record(&gpu, &bundle);
- return build_provisioning_response(&gpu, &bundle);
- }
- }
- } else if let Some(admission) = state
- .pool_manager
- .capped_profile_status(&effective_pool, &gpu)
+ if let Some(resp) =
+ capped_lane_admission_response(&state, effective_pool, effective_machine_profile, &bundle)
.await
- {
- if admission.cap == 0 {
- metrics::record_rejected_request(&gpu, &bundle, "pool_cap_zero");
- let mut m = Map::new();
- m.insert("pool".to_string(), json!(&effective_pool));
- m.insert("gpu".to_string(), json!(&gpu));
- m.insert("cap".to_string(), json!(admission.cap));
- return (
- StatusCode::SERVICE_UNAVAILABLE,
- Json(json_detail_merge(
- err_code::POOL_CAPACITY_UNAVAILABLE,
- format!(
- "Pool '{}' admits zero workers for GPU type '{}'.",
- effective_pool, gpu
- ),
- m,
- )),
- )
- .into_response();
- }
-
- if admission.assigned_count == 0 {
- state.demand_tracker.record(&gpu, &bundle);
- return build_provisioning_response(&gpu, &bundle);
- }
- }
+ {
+ return resp;
}
let token_id = extract_bearer_token(req.headers())
@@ -987,7 +1037,12 @@ async fn proxy_request(
Ok(b) => b,
Err(e) => {
warn!(error = %e, limit = body_limit, "request body too large or read error");
- metrics::record_rejected_request(&gpu, &bundle, "body_too_large");
+ metrics::record_rejected_request_for_pool(
+ effective_pool,
+ &gpu,
+ &bundle,
+ "body_too_large",
+ );
return endpoint_error_response(
endpoint,
StatusCode::PAYLOAD_TOO_LARGE,
@@ -1007,8 +1062,8 @@ async fn proxy_request(
&model_name,
&bundle,
&engine,
- &gpu,
- &effective_pool,
+ effective_machine_profile,
+ effective_pool,
&body_bytes,
is_msgpack_in,
use_msgpack_out,
@@ -1029,11 +1084,11 @@ fn should_trace_proxy_request(endpoint: &str) -> bool {
/// `pool` is always pre-resolved by the caller via
/// [`resolve_effective_pool`] and is guaranteed non-empty: the
/// `PoolResolution::Provisioning` branch returns `202` before we get
-/// here, and every `PoolResolution::Pool(_)` path produces a non-empty
+/// here, and every `PoolResolution::Route(_)` path produces a non-empty
/// string (either the caller-pinned `X-SIE-Pool`, or a `pool_name`
-/// harvested from the registry snapshot — `resolve_queue_pool` filters
-/// out empty pool names). We therefore don't need to re-query the
-/// registry inside this function.
+/// harvested from the registry snapshot — route resolution filters out
+/// empty pool names and machine profiles). We therefore don't need to
+/// re-query the registry inside this function.
#[allow(clippy::too_many_arguments)]
async fn queue_mode_proxy(
state: &AppState,
@@ -1056,7 +1111,7 @@ async fn queue_mode_proxy(
let (items, params) = match parse_queue_request(body_bytes, is_msgpack_in, endpoint) {
Ok(r) => r,
Err(QueueParseError::Generic(e)) => {
- metrics::record_rejected_request(gpu, bundle, "body_parse_error");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "body_parse_error");
return endpoint_error_response(
endpoint,
StatusCode::BAD_REQUEST,
@@ -1072,13 +1127,13 @@ async fn queue_mode_proxy(
// — surface a precise rejection reason so dashboards can
// separate it from generic body-parse failures. Future
// pre-built paths should pick their own reason code.
- metrics::record_rejected_request(gpu, bundle, "grammar_invalid");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "grammar_invalid");
return resp;
}
};
if items.is_empty() && endpoint != "score" && endpoint != "generate" {
- metrics::record_rejected_request(gpu, bundle, "empty_items");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "empty_items");
return endpoint_error_response(
endpoint,
StatusCode::BAD_REQUEST,
@@ -1095,7 +1150,7 @@ async fn queue_mode_proxy(
// and we translate that to a 400 with an instructive message here. This
// is the gateway-side enforcement called out in §4.5.1.1 of the POC plan.
if endpoint == "generate" && params.generate.is_none() {
- metrics::record_rejected_request(gpu, bundle, "invalid_generate_body");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "invalid_generate_body");
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -1122,7 +1177,7 @@ async fn queue_mode_proxy(
.as_ref()
.and_then(|m| m.info_extras.grammar_capabilities.clone());
if let Err(resp) = super::grammar::check_capability(g, caps.as_deref(), model) {
- metrics::record_rejected_request(gpu, bundle, "grammar_capability");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "grammar_capability");
return resp;
}
}
@@ -1150,7 +1205,12 @@ async fn queue_mode_proxy(
match validate_lora_for_profile(&info, profile_name, req_lora) {
LoraValidation::Ok => {}
LoraValidation::UnknownProfile => {
- metrics::record_rejected_request(gpu, bundle, "unknown_profile");
+ metrics::record_rejected_request_for_pool(
+ pool,
+ gpu,
+ bundle,
+ "unknown_profile",
+ );
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -1163,7 +1223,12 @@ async fn queue_mode_proxy(
.into_response();
}
LoraValidation::UnknownAdapter => {
- metrics::record_rejected_request(gpu, bundle, "unknown_lora_adapter");
+ metrics::record_rejected_request_for_pool(
+ pool,
+ gpu,
+ bundle,
+ "unknown_lora_adapter",
+ );
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -1186,7 +1251,7 @@ async fn queue_mode_proxy(
// Take an Arc clone so the cancel-on-drop guard can outlive the
// borrow checker without a 'static lifetime tangle.
let Some(work_publisher_arc) = state.work_publisher.clone() else {
- metrics::record_rejected_request(gpu, bundle, "queue_unavailable");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "queue_unavailable");
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(json_openai_error(
@@ -1265,7 +1330,7 @@ async fn queue_mode_proxy(
error!(error = %e, "failed to publish work");
let lower = e.to_lowercase();
if lower.contains("score request missing query item") {
- metrics::record_rejected_request(gpu, bundle, "score_missing_query");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "score_missing_query");
return (
StatusCode::BAD_REQUEST,
Json(json_detail(err_code::INVALID_REQUEST, e)),
@@ -1283,19 +1348,24 @@ async fn queue_mode_proxy(
.into_response();
if lower.contains("no consumers") {
- metrics::record_rejected_request(gpu, bundle, "no_consumers");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "no_consumers");
response.headers_mut().insert(
HeaderName::from_static("retry-after"),
HeaderValue::from_static(DEFAULT_RETRY_AFTER),
);
} else if lower.contains("backpressure") {
- metrics::record_rejected_request(gpu, bundle, "backpressure");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "backpressure");
response.headers_mut().insert(
HeaderName::from_static("retry-after"),
HeaderValue::from_static(BACKPRESSURE_RETRY_AFTER),
);
} else {
- metrics::record_rejected_request(gpu, bundle, "queue_publish_failed");
+ metrics::record_rejected_request_for_pool(
+ pool,
+ gpu,
+ bundle,
+ "queue_publish_failed",
+ );
}
response.headers_mut().insert(
@@ -1317,7 +1387,7 @@ async fn queue_mode_proxy(
let results = match tokio::time::timeout(Duration::from_secs(timeout_secs), rx).await {
Ok(Ok(results)) => results,
Ok(Err(_)) => {
- metrics::record_rejected_request(gpu, bundle, "result_channel_closed");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "result_channel_closed");
return (
StatusCode::GATEWAY_TIMEOUT,
Json(json_detail(
@@ -1342,7 +1412,12 @@ async fn queue_mode_proxy(
// and a generic `result_timeout` for the same event would
// double-count the timeout on the error-rate dashboards
// and break rate alerts that sum across reasons.
- metrics::record_rejected_request(gpu, bundle, "upstream_timeout_model_loading");
+ metrics::record_rejected_request_for_pool(
+ pool,
+ gpu,
+ bundle,
+ "upstream_timeout_model_loading",
+ );
return build_model_loading_timeout_response(model, timeout_secs);
}
};
@@ -1364,7 +1439,12 @@ async fn queue_mode_proxy(
.first()
.and_then(|r| r.error.as_deref())
.unwrap_or("Model load failed");
- metrics::record_rejected_request(gpu, bundle, "model_load_failed_terminal");
+ metrics::record_rejected_request_for_pool(
+ pool,
+ gpu,
+ bundle,
+ "model_load_failed_terminal",
+ );
return build_model_load_failed_response(model, first_msg);
}
// Translate retryable worker error codes into the SDK-expected 503
@@ -1378,7 +1458,12 @@ async fn queue_mode_proxy(
.first()
.and_then(|r| r.error.as_deref())
.unwrap_or("Worker reported a retryable error");
- metrics::record_rejected_request(gpu, bundle, retryable_metric_reason(code));
+ metrics::record_rejected_request_for_pool(
+ pool,
+ gpu,
+ bundle,
+ retryable_metric_reason(code),
+ );
return build_retryable_error_response(code, first_msg);
}
@@ -1395,7 +1480,7 @@ async fn queue_mode_proxy(
entry
})
.collect();
- metrics::record_rejected_request(gpu, bundle, "all_items_failed");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "all_items_failed");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "all_items_failed", "details": error_details})),
@@ -1710,19 +1795,43 @@ pub(crate) async fn run_streaming_generate(
// distinguish it from capacity/health-driven fallbacks. We also
// skip the gauge update here — the ring isn't consulted, so
// recording a size for it would be misleading.
- let target = if resolved_key.hash.is_none() {
+ let (target, pool_fallback_lane_worker_count) = if resolved_key.hash.is_none() {
metrics::ROUTING_FALLBACK_TOTAL
.with_label_values(&[&model_label, &pool_label, "no_key"])
.inc();
- publisher::PublishTarget::Pool {
- model: model.to_string(),
- pool: pool.to_string(),
- }
+ (
+ publisher::PublishTarget::Pool {
+ pool: pool.to_string(),
+ machine_profile: gpu.to_string(),
+ bundle: bundle.to_string(),
+ model: model.to_string(),
+ },
+ 0,
+ )
} else {
- let ring = state.registry.ring_snapshot_for(model, pool);
+ let admitted_worker_names = state
+ .pool_manager
+ .admitted_worker_names_for_capped_lane(pool, gpu, bundle)
+ .await;
+ let fallback_lane_worker_count = state.registry.pool_fallback_lane_worker_count(
+ pool,
+ gpu,
+ bundle,
+ bundle_config_hash,
+ admitted_worker_names.as_ref(),
+ );
+ let ring = state.registry.ring_snapshot_for_admitted(
+ model,
+ pool,
+ gpu,
+ bundle,
+ bundle_config_hash,
+ admitted_worker_names.as_ref(),
+ );
+ let ring_len = ring.len();
metrics::ROUTING_HRW_RING_SIZE
.with_label_values(&[&model_label, &pool_label])
- .set(ring.len() as f64);
+ .set(ring_len as f64);
let picked = crate::routing::pick_worker(&ring, &resolved_key);
match picked {
Some(worker_id) => {
@@ -1734,11 +1843,16 @@ pub(crate) async fn run_streaming_generate(
source = resolved_key.source.as_label(),
"HRW pick"
);
- publisher::PublishTarget::Worker {
- model: model.to_string(),
- pool: pool.to_string(),
- worker_id: worker_id.to_string(),
- }
+ (
+ publisher::PublishTarget::Worker {
+ pool: pool.to_string(),
+ machine_profile: gpu.to_string(),
+ bundle: bundle.to_string(),
+ model: model.to_string(),
+ worker_id: worker_id.to_string(),
+ },
+ fallback_lane_worker_count,
+ )
}
None => {
// We had a key but the ring is empty. The registry-side
@@ -1750,17 +1864,22 @@ pub(crate) async fn run_streaming_generate(
metrics::ROUTING_FALLBACK_TOTAL
.with_label_values(&[&model_label, &pool_label, "unhealthy_skipped"])
.inc();
- publisher::PublishTarget::Pool {
- model: model.to_string(),
- pool: pool.to_string(),
- }
+ (
+ publisher::PublishTarget::Pool {
+ pool: pool.to_string(),
+ machine_profile: gpu.to_string(),
+ bundle: bundle.to_string(),
+ model: model.to_string(),
+ },
+ fallback_lane_worker_count,
+ )
}
}
};
// Capture this before the move into `publish_generate_streaming`.
let was_direct_dispatched = matches!(target, publisher::PublishTarget::Worker { .. });
let (request_id, rx, activity) = match work_publisher
- .publish_generate_streaming(target, bundle, engine, gpu, bundle_config_hash, params)
+ .publish_generate_streaming(target, engine, bundle_config_hash, params)
.await
{
Ok(r) => r,
@@ -1768,13 +1887,18 @@ pub(crate) async fn run_streaming_generate(
error!(error = %e, "failed to publish generate work");
let lower = e.to_lowercase();
let retry_after = if lower.contains("no consumers") {
- metrics::record_rejected_request(gpu, bundle, "no_consumers");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "no_consumers");
Some(DEFAULT_RETRY_AFTER)
} else if lower.contains("backpressure") {
- metrics::record_rejected_request(gpu, bundle, "backpressure");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "backpressure");
Some(BACKPRESSURE_RETRY_AFTER)
} else {
- metrics::record_rejected_request(gpu, bundle, "queue_publish_failed");
+ metrics::record_rejected_request_for_pool(
+ pool,
+ gpu,
+ bundle,
+ "queue_publish_failed",
+ );
None
};
return Err(StreamingDriverErr::PublishFailed {
@@ -1833,20 +1957,18 @@ pub(crate) async fn run_streaming_generate(
// `republished` field on `StreamCollector`) so the two paths
// cannot double-publish.
let mut republished_for_first_chunk = false;
- // Capture the pool's consumer count at dispatch time so the H9
- // single-worker suppression below uses the topology we actually
- // dispatched against. Re-reading at timeout could see a count of 1
- // after a 2-worker pool lost its chosen worker mid-flight, and
- // suppress a republish that could have failed over to the
- // remaining worker. (We accept the inverse hazard — a worker
- // joining mid-flight in a single-worker pool keeps the suppression
- // active — because the cancel-tombstone race that motivates this
- // guard cannot fire on a worker that wasn't registered at
- // dispatch.)
- let single_consumer_pool_at_dispatch = was_direct_dispatched
- && work_publisher
- .pool_consumer_count(pool)
- .is_some_and(|n| n <= 1);
+ // Capture the exact pool-fallback lane size at dispatch time so
+ // the H9 single-worker suppression below is scoped to
+ // `(pool,machine_profile,bundle)` and still counts healthy cold
+ // workers that can lazy-load after a pool republish. The old
+ // JetStream pool-wide consumer count could be inflated by another
+ // bundle or machine profile in the same logical pool, incorrectly
+ // enabling a first-chunk fallback that had no alternate worker in
+ // this lane.
+ let single_consumer_lane_at_dispatch = crate::routing::suppress_first_chunk_republish_for_lane(
+ was_direct_dispatched,
+ pool_fallback_lane_worker_count,
+ );
// Drive the wait loop. We hold a single pinned receiver across
// iterations and re-arm the inter-chunk timer on every chunk
@@ -1891,7 +2013,7 @@ pub(crate) async fn run_streaming_generate(
// overall_timeout path will surface that.
if was_direct_dispatched
&& !republished_for_first_chunk
- && !single_consumer_pool_at_dispatch
+ && !single_consumer_lane_at_dispatch
{
republished_for_first_chunk = true;
// At-least-once-execution hazard: the original
@@ -1934,7 +2056,7 @@ pub(crate) async fn run_streaming_generate(
}
}
}
- if single_consumer_pool_at_dispatch
+ if single_consumer_lane_at_dispatch
&& was_direct_dispatched
&& !republished_for_first_chunk
{
@@ -1951,7 +2073,9 @@ pub(crate) async fn run_streaming_generate(
tracing::debug!(
request_id = %request_id,
pool = %pool,
- "first_chunk_timeout — single-worker pool, suppressing republish; continuing on overall_timeout"
+ machine_profile = %gpu,
+ bundle = %bundle,
+ "first_chunk_timeout - single-worker lane, suppressing republish; continuing on overall_timeout"
);
continue;
}
@@ -2008,7 +2132,7 @@ pub(crate) async fn run_streaming_generate(
}
Err("result_channel_closed") => {
cancel_guard.defuse();
- metrics::record_rejected_request(gpu, bundle, "result_channel_closed");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "result_channel_closed");
work_publisher.drop_pending_stream(&request_id);
return Err(StreamingDriverErr::ResultChannelClosed);
}
@@ -2022,7 +2146,8 @@ pub(crate) async fn run_streaming_generate(
metrics::GENERATION_TIMEOUTS
.with_label_values(&[&model_label, &metrics::sanitize_label(pool), kind])
.inc();
- metrics::record_rejected_request(
+ metrics::record_rejected_request_for_pool(
+ pool,
gpu,
bundle,
match kind {
@@ -2041,7 +2166,7 @@ pub(crate) async fn run_streaming_generate(
// If the worker emitted an error terminal, surface it as a typed
// failure. The caller chooses the HTTP status / wire envelope.
if let Some(err) = outcome.error.as_ref() {
- metrics::record_rejected_request(gpu, bundle, "generate_worker_error");
+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "generate_worker_error");
return Err(StreamingDriverErr::WorkerError {
code: err.code.clone(),
message: err.message.clone(),
@@ -4081,7 +4206,12 @@ pub(crate) fn resolve_model_and_bundle(
{
Ok(b) => b,
Err(ResolveError::ModelNotFound(e)) => {
- metrics::record_rejected_request("", "unknown", "model_not_found");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ "unknown",
+ "model_not_found",
+ );
return Err((
StatusCode::NOT_FOUND,
Json(json_openai_error(
@@ -4094,7 +4224,12 @@ pub(crate) fn resolve_model_and_bundle(
.into_response());
}
Err(ResolveError::BundleConflict(e)) => {
- metrics::record_rejected_request("", "unknown", "bundle_routing_conflict");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ "unknown",
+ "bundle_routing_conflict",
+ );
return Err((
StatusCode::CONFLICT,
Json(json_openai_error(
@@ -4108,7 +4243,7 @@ pub(crate) fn resolve_model_and_bundle(
}
}
} else if state.model_registry.has_any_models() {
- metrics::record_rejected_request("", "unknown", "model_not_found");
+ metrics::record_rejected_request_for_pool("unknown", "", "unknown", "model_not_found");
return Err((
StatusCode::NOT_FOUND,
Json(json_openai_error(
@@ -4128,12 +4263,13 @@ pub(crate) fn resolve_model_and_bundle(
}
/// The routing context resolved from request headers + the model's bundle:
-/// machine profile (GPU), effective pool, bundle config hash, the bound work
+/// machine profile, effective pool, bundle config hash, the bound work
/// publisher, plus audit fields. Produced by [`resolve_generation_route`].
struct ResolvedRoute {
gpu: String,
engine: String,
effective_pool: String,
+ effective_machine_profile: String,
bundle_config_hash: String,
work_publisher: Arc<publisher::WorkPublisher>,
token_id: String,
@@ -4168,11 +4304,11 @@ async fn resolve_generation_route(
}
if !pool_name.is_empty() && !is_valid_pool_name(&pool_name) {
- metrics::record_rejected_request(&gpu, bundle, "invalid_pool");
+ metrics::record_rejected_request_for_pool("unknown", &gpu, bundle, "invalid_pool");
return Err((
StatusCode::BAD_REQUEST,
Json(json_openai_error(
- "Invalid pool name: only [A-Za-z0-9._-] are allowed (max 128 chars)".to_string(),
+ "Invalid pool name: only [A-Za-z0-9_-] are allowed (max 128 chars)".to_string(),
oai_type::INVALID_REQUEST,
Some("X-SIE-Pool"),
oai_code::INVALID_REQUEST,
@@ -4192,7 +4328,17 @@ async fn resolve_generation_route(
.iter()
.any(|cg| cg.eq_ignore_ascii_case(&gpu));
if !found {
- metrics::record_rejected_request(&gpu, bundle, "gpu_not_configured");
+ let metric_pool = if pool_name.is_empty() {
+ DEFAULT_POOL_NAME
+ } else {
+ pool_name.as_str()
+ };
+ metrics::record_rejected_request_for_pool(
+ metric_pool,
+ "invalid",
+ bundle,
+ "gpu_not_configured",
+ );
return Err((
StatusCode::SERVICE_UNAVAILABLE,
Json(json_openai_error(
@@ -4207,7 +4353,12 @@ async fn resolve_generation_route(
}
let Some(work_publisher_arc) = state.work_publisher.clone() else {
- metrics::record_rejected_request(&gpu, bundle, "queue_unavailable");
+ let metric_pool = if pool_name.is_empty() {
+ DEFAULT_POOL_NAME
+ } else {
+ pool_name.as_str()
+ };
+ metrics::record_rejected_request_for_pool(metric_pool, &gpu, bundle, "queue_unavailable");
return Err((
StatusCode::SERVICE_UNAVAILABLE,
Json(json_openai_error(
@@ -4228,42 +4379,40 @@ async fn resolve_generation_route(
.unwrap_or_else(|| crate::types::bundle::DEFAULT_ENGINE.to_string());
let lookup = resolve_effective_pool(
&state.registry,
+ Some(&state.pool_manager),
bundle,
&gpu,
&pool_name,
&bundle_config_hash,
)
.await;
- if !gpu.is_empty() && !lookup.exact_gpu_match {
- state.demand_tracker.record(&gpu, bundle);
+ let demand_pool = if pool_name.is_empty() {
+ DEFAULT_POOL_NAME
+ } else {
+ pool_name.as_str()
+ };
+ let pending_demand_profile = lookup.pending_demand_profile.clone();
+ if let Some(profile) = pending_demand_profile.as_deref() {
+ state.demand_tracker.record(demand_pool, profile, bundle);
}
- let effective_pool = match lookup.resolution {
- PoolResolution::Pool(p) => p,
+ let effective_route = match lookup.resolution {
+ PoolResolution::Route(route) => route,
PoolResolution::Provisioning => {
- state.demand_tracker.record(&gpu, bundle);
- let message = if gpu.is_empty() {
- format!("No worker available for bundle '{bundle}'. Provisioning in progress.")
- } else {
- format!("No worker available for GPU type '{gpu}'. Provisioning in progress.")
- };
- let mut resp = (
- StatusCode::ACCEPTED,
- Json(json!({
- "status": "provisioning",
- "gpu": gpu,
- "bundle": bundle,
- "estimated_wait_s": ESTIMATED_WAIT_S,
- "message": message,
- })),
- )
- .into_response();
- resp.headers_mut().insert(
- HeaderName::from_static("retry-after"),
- HeaderValue::from_static(DEFAULT_RETRY_AFTER),
- );
- return Err(resp);
+ if pending_demand_profile.is_none() {
+ state.demand_tracker.record(demand_pool, &gpu, bundle);
+ }
+ return Err(build_provisioning_response(&gpu, bundle));
}
};
+ let effective_pool = effective_route.pool_name;
+ let effective_machine_profile = effective_route.machine_profile;
+
+ if let Some(resp) =
+ capped_lane_admission_response(state, &effective_pool, &effective_machine_profile, bundle)
+ .await
+ {
+ return Err(resp);
+ }
let token_id = extract_bearer_token(hdr)
.map(|t| mask_token(&t))
@@ -4278,6 +4427,7 @@ async fn resolve_generation_route(
gpu,
engine,
effective_pool,
+ effective_machine_profile,
bundle_config_hash,
work_publisher: work_publisher_arc,
token_id,
@@ -4350,7 +4500,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
// matching the ``model_required`` precedent in
// ``proxy_request``. The rejection-reasons dashboard groups
// these under the explicit reason string.
- metrics::record_rejected_request("", "unknown", "body_too_large");
+ metrics::record_rejected_request_for_pool("unknown", "", "unknown", "body_too_large");
return (
StatusCode::PAYLOAD_TOO_LARGE,
Json(json_openai_error(
@@ -4367,7 +4517,12 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
let body_json: serde_json::Value = match serde_json::from_slice(&body_bytes) {
Ok(v) => v,
Err(e) => {
- metrics::record_rejected_request("", "unknown", "chat_invalid_body");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ "unknown",
+ "chat_invalid_body",
+ );
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -4388,7 +4543,12 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
// modes (unsupported field, invalid role, missing field) to
// one bucket so the dashboards stay low-cardinality; the
// response body still carries the precise ``param``/``code``.
- metrics::record_rejected_request("", "unknown", "chat_invalid_params");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ "unknown",
+ "chat_invalid_params",
+ );
return resp;
}
};
@@ -4425,7 +4585,12 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
// rejection arms into the same ``unknown_lora_adapter``
// response that's been the chat-gate contract since A.
LoraValidation::UnknownProfile | LoraValidation::UnknownAdapter => {
- metrics::record_rejected_request("", &bundle, "unknown_lora_adapter");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ &bundle,
+ "unknown_lora_adapter",
+ );
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -4441,7 +4606,12 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
}
if let Some(cap) = info.info_extras.max_output_tokens {
if cap > 0 && params.max_new_tokens > cap {
- metrics::record_rejected_request("", &bundle, "chat_max_tokens_exceeded");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ &bundle,
+ "chat_max_tokens_exceeded",
+ );
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -4463,7 +4633,12 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
info.info_extras.grammar_capabilities.as_deref(),
&model_name,
) {
- metrics::record_rejected_request("", &bundle, "grammar_capability");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ &bundle,
+ "grammar_capability",
+ );
return resp;
}
}
@@ -4476,7 +4651,12 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
if params.tools.is_some() {
let supported = info.info_extras.tools_supported.unwrap_or(false);
if !supported {
- metrics::record_rejected_request("", &bundle, "tools_capability");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ &bundle,
+ "tools_capability",
+ );
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -4492,7 +4672,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
} else if params.grammar.is_some() {
// No model info means we cannot determine grammar capabilities;
// safer to reject than to publish work the model cannot honour.
- metrics::record_rejected_request("", &bundle, "grammar_capability");
+ metrics::record_rejected_request_for_pool("unknown", "", &bundle, "grammar_capability");
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -4507,7 +4687,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
// Same defensive rejection for ``tools`` when the model is
// unknown — safer than publishing work the model cannot
// honour.
- metrics::record_rejected_request("", &bundle, "tools_capability");
+ metrics::record_rejected_request_for_pool("unknown", "", &bundle, "tools_capability");
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -4526,6 +4706,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
gpu,
engine,
effective_pool,
+ effective_machine_profile,
bundle_config_hash,
work_publisher: work_publisher_arc,
token_id,
@@ -4591,7 +4772,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
model: model_name.clone(),
bundle: bundle.clone(),
engine: engine.clone(),
- gpu: gpu.clone(),
+ gpu: effective_machine_profile.clone(),
pool: effective_pool.clone(),
bundle_config_hash: bundle_config_hash.clone(),
work_params,
@@ -4608,7 +4789,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
&model_name,
&bundle,
&engine,
- &gpu,
+ &effective_machine_profile,
&effective_pool,
&bundle_config_hash,
&work_params,
@@ -5078,7 +5259,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
let body_bytes = match to_bytes(req.into_body(), MAX_COMPLETIONS_BODY).await {
Ok(b) => b,
Err(e) => {
- metrics::record_rejected_request("", "unknown", "body_too_large");
+ metrics::record_rejected_request_for_pool("unknown", "", "unknown", "body_too_large");
return (
StatusCode::PAYLOAD_TOO_LARGE,
Json(json_openai_error(
@@ -5094,7 +5275,12 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
let body_json: serde_json::Value = match serde_json::from_slice(&body_bytes) {
Ok(v) => v,
Err(e) => {
- metrics::record_rejected_request("", "unknown", "completions_invalid_body");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ "unknown",
+ "completions_invalid_body",
+ );
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -5111,7 +5297,12 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
let params = match completions_params_from_json(&body_json) {
CompletionsParamsResult::Ok(p) => p,
CompletionsParamsResult::Err(resp) => {
- metrics::record_rejected_request("", "unknown", "completions_invalid_params");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ "unknown",
+ "completions_invalid_params",
+ );
return resp;
}
};
@@ -5125,6 +5316,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
gpu,
engine,
effective_pool,
+ effective_machine_profile,
bundle_config_hash,
work_publisher: work_publisher_arc,
token_id,
@@ -5161,7 +5353,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
model: model_name.clone(),
bundle: bundle.clone(),
engine: engine.clone(),
- gpu: gpu.clone(),
+ gpu: effective_machine_profile.clone(),
pool: effective_pool.clone(),
bundle_config_hash: bundle_config_hash.clone(),
work_params,
@@ -5176,7 +5368,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
&model_name,
&bundle,
&engine,
- &gpu,
+ &effective_machine_profile,
&effective_pool,
&bundle_config_hash,
&work_params,
@@ -5643,7 +5835,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
let body_bytes = match to_bytes(req.into_body(), MAX_RESPONSES_BODY).await {
Ok(b) => b,
Err(e) => {
- metrics::record_rejected_request("", "unknown", "body_too_large");
+ metrics::record_rejected_request_for_pool("unknown", "", "unknown", "body_too_large");
return (
StatusCode::PAYLOAD_TOO_LARGE,
Json(json_openai_error(
@@ -5659,7 +5851,12 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
let body_json: serde_json::Value = match serde_json::from_slice(&body_bytes) {
Ok(v) => v,
Err(e) => {
- metrics::record_rejected_request("", "unknown", "responses_invalid_body");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ "unknown",
+ "responses_invalid_body",
+ );
return (
StatusCode::BAD_REQUEST,
Json(json_openai_error(
@@ -5676,7 +5873,12 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
let params = match responses_params_from_json(&body_json) {
ResponsesParamsResult::Ok(p) => p,
ResponsesParamsResult::Err(resp) => {
- metrics::record_rejected_request("", "unknown", "responses_invalid_params");
+ metrics::record_rejected_request_for_pool(
+ "unknown",
+ "",
+ "unknown",
+ "responses_invalid_params",
+ );
return resp;
}
};
@@ -5689,6 +5891,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
gpu,
engine,
effective_pool,
+ effective_machine_profile,
bundle_config_hash,
work_publisher: work_publisher_arc,
token_id,
@@ -5717,7 +5920,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
&model_name,
&bundle,
&engine,
- &gpu,
+ &effective_machine_profile,
&effective_pool,
&bundle_config_hash,
&work_params,
@@ -9138,11 +9341,118 @@ mod tests {
);
}
+ fn admission_test_state(pool_manager: Arc<PoolManager>) -> AppState {
+ 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 gpu_profile_map = std::collections::HashMap::new();
+ gpu_profile_map.insert("l4".to_string(), "l4".to_string());
+ let config = crate::config::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(),
+ k8s_service: String::new(),
+ k8s_port: 0,
+ health_mode: "http".to_string(),
+ nats_url: String::new(),
+ nats_config_trusted_producers: Vec::new(),
+ auth_mode: "none".to_string(),
+ auth_tokens: Vec::new(),
+ admin_token: String::new(),
+ auth_exempt_operational: false,
+ log_level: "info".to_string(),
+ json_logs: false,
+ enable_pools: true,
+ hot_reload: false,
+ watch_polling: false,
+ multi_router: false,
+ request_timeout: 30.0,
+ max_stream_pending: 1024,
+ stream_max_age_s: 300,
+ configured_gpus: vec!["l4".to_string()],
+ gpu_profile_map,
+ model_aliases: std::collections::HashMap::new(),
+ bundles_dir: bundles_dir.path().to_string_lossy().to_string(),
+ models_dir: models_dir.path().to_string_lossy().to_string(),
+ config_service_url: None,
+ config_service_token: None,
+ payload_store_url: String::new(),
+ };
+ AppState {
+ registry: Arc::new(WorkerRegistry::new(Duration::from_secs(30), None)),
+ config: Arc::new(config),
+ model_registry: Arc::new(crate::state::model_registry::ModelRegistry::new(
+ bundles_dir.path(),
+ models_dir.path(),
+ true,
+ )),
+ pool_manager,
+ work_publisher: None,
+ demand_tracker: Arc::new(crate::state::demand_tracker::DemandTracker::new()),
+ config_epoch: crate::state::config_epoch::ConfigEpoch::new(),
+ }
+ }
+
+ #[tokio::test]
+ async fn test_capped_lane_admission_zero_cap_returns_pool_unavailable() {
+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ let mut gpus = std::collections::HashMap::new();
+ gpus.insert("l4".to_string(), 0);
+ let mut caps = std::collections::HashMap::new();
+ caps.insert("l4".to_string(), 0);
+ pm.create_pool_with_caps("tenant", gpus, caps, None, None, 0)
+ .await
+ .unwrap();
+ let state = admission_test_state(Arc::clone(&pm));
+
+ let resp = capped_lane_admission_response(&state, "tenant", "l4", "default")
+ .await
+ .expect("zero-cap lane should fail fast");
+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
+ let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap();
+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(value["detail"]["code"], err_code::POOL_CAPACITY_UNAVAILABLE);
+ }
+
+ #[tokio::test]
+ async fn test_capped_lane_admission_zero_assigned_returns_provisioning() {
+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ let mut gpus = std::collections::HashMap::new();
+ gpus.insert("l4".to_string(), 0);
+ let mut caps = std::collections::HashMap::new();
+ caps.insert("l4".to_string(), 1);
+ pm.create_pool_with_caps("tenant", gpus, caps, None, None, 0)
+ .await
+ .unwrap();
+ let state = admission_test_state(Arc::clone(&pm));
+
+ let resp = capped_lane_admission_response(&state, "tenant", "l4", "default")
+ .await
+ .expect("capped lane with no admitted workers should provision");
+ assert_eq!(resp.status(), StatusCode::ACCEPTED);
+ let pending_demand = metrics::PENDING_DEMAND
+ .with_label_values(&["tenant", "l4", "default"])
+ .get();
+ assert!((pending_demand - 1.0).abs() < f64::EPSILON);
+ state.demand_tracker.clear("tenant", "l4", "default");
+ let cleared_demand = metrics::PENDING_DEMAND
+ .with_label_values(&["tenant", "l4", "default"])
+ .get();
+ assert!((cleared_demand - 0.0).abs() < f64::EPSILON);
+ }
+
// ── is_valid_pool_name (pool subject-injection guard) ──────────
#[test]
fn test_is_valid_pool_name_accepts_allowlisted() {
- for ok in ["default", "_default", "eval-l4", "pool.1", "A-b_C.9", "x"] {
+ for ok in ["default", "eval-l4", "A-b_C-9", "x"] {
assert!(is_valid_pool_name(ok), "{ok} should be valid");
}
}
@@ -9150,16 +9460,19 @@ mod tests {
#[test]
fn test_is_valid_pool_name_rejects_subject_injection() {
// Any of these would re-tokenise / break the
- // `sie.work.{model}.{pool}` subject or inject a wildcard.
+ // `sie.work.{pool}.{machine_profile}.{bundle}.{model}` subject
+ // or inject a wildcard.
for bad in [
"", // empty
"a b", // whitespace
"pool/evil", // slash (subject separator after normalize)
+ "pool.1", // dot (subject separator)
"pool>evil", // `>` full-wildcard
"pool*", // `*` token-wildcard
"a.>", // wildcard tail
"pool\nx", // control char
"pää", // non-ascii
+ "_default", // removed legacy sentinel spelling
] {
assert!(!is_valid_pool_name(bad), "{bad:?} should be rejected");
}
@@ -11367,6 +11680,13 @@ mod tests {
}
}
+ fn route(pool: &str, gpu: &str) -> PoolResolution {
+ PoolResolution::Route(QueueRoute {
+ pool_name: pool.to_string(),
+ machine_profile: gpu.to_string(),
+ })
+ }
+
#[tokio::test]
async fn test_resolve_effective_pool_returns_provisioning_when_empty_and_no_gpu() {
// No workers at all. Caller sends no `X-SIE-MACHINE-PROFILE`.
@@ -11375,7 +11695,7 @@ mod tests {
// `Provisioning` so the caller returns `202 + Retry-After` and
// records pending demand for KEDA.
let reg = pool_registry();
- let out = resolve_effective_pool(&reg, "default", "", "", "").await;
+ let out = resolve_effective_pool(&reg, None, "default", "", "", "").await;
assert_eq!(out.resolution, PoolResolution::Provisioning);
// No GPU expressed → exact_gpu_match is definitionally false.
assert!(!out.exact_gpu_match);
@@ -11388,7 +11708,7 @@ mod tests {
let reg = pool_registry();
reg.update_worker("http://w1:8080", worker_msg("default", "a100", "pool-a"))
.await;
- let out = resolve_effective_pool(&reg, "premium", "l4", "", "").await;
+ let out = resolve_effective_pool(&reg, None, "premium", "l4", "", "").await;
assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
}
@@ -11405,25 +11725,24 @@ mod tests {
)
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "", "").await;
+ let out = resolve_effective_pool(&reg, None, "default", "l4-spot", "", "").await;
assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
}
#[tokio::test]
- async fn test_resolve_effective_pool_bundle_only_fallback_when_gpu_mismatch() {
+ async fn test_resolve_effective_pool_provisions_when_gpu_mismatch() {
// Client pinned `l4` but the cluster only has an `a100` worker on
- // the same bundle. We still route (the profile distinction is
- // cosmetic here) rather than forcing a scale-up.
+ // the same bundle. Machine profile is now part of the queue lane, so
+ // the gateway must return provisioning for the exact cold lane rather
+ // than silently routing to a different profile.
let reg = pool_registry();
reg.update_worker("http://w1:8080", worker_msg("default", "a100", "default"))
.await;
- let out = resolve_effective_pool(&reg, "default", "l4", "", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("default".to_string()));
- // Exact tuple (default, l4) had no worker — even though we
- // still routed via the bundle-only fallback, the caller must
- // record demand so KEDA scales up the l4 pool.
+ let out = resolve_effective_pool(&reg, None, "default", "l4", "", "").await;
+ assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
+ assert_eq!(out.pending_demand_profile.as_deref(), Some("l4"));
}
#[tokio::test]
@@ -11436,8 +11755,8 @@ mod tests {
worker_msg("default", "l4-spot", "default"),
)
.await;
- let out = resolve_effective_pool(&reg, "default", "", "", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("default".to_string()));
+ let out = resolve_effective_pool(&reg, None, "default", "", "", "").await;
+ assert_eq!(out.resolution, route("default", "l4-spot"));
// No GPU preference → no demand tracking applicable.
assert!(!out.exact_gpu_match);
}
@@ -11452,34 +11771,72 @@ mod tests {
worker_msg("default", "l4-spot", "default"),
)
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("default".to_string()));
+ let out = resolve_effective_pool(&reg, None, "default", "l4-spot", "", "").await;
+ assert_eq!(out.resolution, route("default", "l4-spot"));
assert!(out.exact_gpu_match);
}
#[tokio::test]
async fn test_resolve_effective_pool_honours_explicit_pool_name() {
- // Caller pinned a pool. Trust them unconditionally — even an
- // empty registry must route there so a known cold pool can be
- // targeted (worker will scale up independently).
+ // Caller pinned only a pool. The new subject shape also needs a
+ // concrete machine-profile token, so an empty registry cannot be
+ // published to safely.
+ let reg = pool_registry();
+ let out = resolve_effective_pool(&reg, None, "default", "", "my-bench", "").await;
+ assert_eq!(out.resolution, PoolResolution::Provisioning);
+ assert!(!out.exact_gpu_match);
+ assert_eq!(out.pending_demand_profile, None);
+ }
+
+ #[tokio::test]
+ async fn test_resolve_effective_pool_infers_cold_profile_from_single_profile_pool() {
+ // A tenant pool with exactly one configured machine profile can scale
+ // from a pool-only request: the gateway still returns provisioning, but
+ // pending_demand gets the concrete profile label KEDA queries.
+ let reg = pool_registry();
+ let pm = PoolManager::new(vec!["l4".into()]);
+ let mut gpus = std::collections::HashMap::new();
+ gpus.insert("l4".to_string(), 0);
+ pm.create_pool("my-bench", gpus, None, None, 0)
+ .await
+ .unwrap();
+
+ let out = resolve_effective_pool(&reg, Some(&pm), "default", "", "my-bench", "").await;
+ assert_eq!(out.resolution, PoolResolution::Provisioning);
+ assert!(!out.exact_gpu_match);
+ assert_eq!(out.pending_demand_profile.as_deref(), Some("l4"));
+ }
+
+ #[tokio::test]
+ async fn test_resolve_effective_pool_does_not_guess_ambiguous_pool_profile() {
let reg = pool_registry();
- let out = resolve_effective_pool(&reg, "default", "", "my-bench", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
+ let pm = PoolManager::new(vec!["l4".into(), "a100".into()]);
+ let mut gpus = std::collections::HashMap::new();
+ gpus.insert("l4".to_string(), 0);
+ gpus.insert("a100".to_string(), 0);
+ pm.create_pool("my-bench", gpus, None, None, 0)
+ .await
+ .unwrap();
+
+ let out = resolve_effective_pool(&reg, Some(&pm), "default", "", "my-bench", "").await;
+ assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
+ assert_eq!(out.pending_demand_profile, None);
}
#[tokio::test]
- async fn test_resolve_effective_pool_honours_explicit_pool_even_when_worker_exists() {
- // Explicit pool overrides the registry lookup entirely, but we
- // only count an exact match inside the pinned pool. A default
- // or unrelated isolation worker cannot consume the pinned
- // pool's stream and must not hide scale-up demand.
+ async fn test_resolve_effective_pool_provisions_explicit_pool_when_only_other_pool_exists() {
+ // Explicit pool + GPU names a cold lane. A default or unrelated
+ // isolation worker cannot consume the pinned pool's stream, so the
+ // gateway must return 202 instead of publishing to a lane with no
+ // active consumer.
let reg = pool_registry();
reg.update_worker("http://w1:8080", worker_msg("default", "l4-spot", "pool-a"))
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "my-bench", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
+ let out = resolve_effective_pool(&reg, None, "default", "l4-spot", "my-bench", "").await;
+ assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
+ assert_eq!(out.pending_demand_profile.as_deref(), Some("l4-spot"));
}
#[tokio::test]
@@ -11490,23 +11847,23 @@ mod tests {
worker_msg("default", "l4-spot", "my-bench"),
)
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "my-bench", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
+ let out = resolve_effective_pool(&reg, None, "default", "l4-spot", "my-bench", "").await;
+ assert_eq!(out.resolution, route("my-bench", "l4-spot"));
assert!(out.exact_gpu_match);
}
#[tokio::test]
async fn test_resolve_effective_pool_pinned_pool_with_missing_gpu_tuple_reports_no_match() {
// Caller pinned a pool AND expressed a GPU preference, but no
- // worker matches the exact tuple. We still route to the pin,
- // and `exact_gpu_match=false` tells the caller to record
- // demand for KEDA.
+ // worker matches the exact tuple. Return provisioning and record
+ // demand for KEDA instead of publishing into a cold stream.
let reg = pool_registry();
reg.update_worker("http://w1:8080", worker_msg("default", "a100", "pool-a"))
.await;
- let out = resolve_effective_pool(&reg, "default", "l4", "my-bench", "").await;
- assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
+ let out = resolve_effective_pool(&reg, None, "default", "l4", "my-bench", "").await;
+ assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
+ assert_eq!(out.pending_demand_profile.as_deref(), Some("l4"));
}
#[tokio::test]
@@ -11517,22 +11874,24 @@ mod tests {
worker_msg("default", "l4-spot", "default"),
)
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "", "new-hash").await;
+ let out = resolve_effective_pool(&reg, None, "default", "l4-spot", "", "new-hash").await;
assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
}
#[tokio::test]
- async fn test_resolve_effective_pool_pinned_pool_still_overrides_stale_hash() {
+ async fn test_resolve_effective_pool_pinned_pool_provisions_when_hash_mismatch() {
let reg = pool_registry();
reg.update_worker(
"http://w1:8080",
worker_msg("default", "l4-spot", "default"),
)
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "my-bench", "new-hash").await;
- assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
+ let out =
+ resolve_effective_pool(&reg, None, "default", "l4-spot", "my-bench", "new-hash").await;
+ assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
+ assert_eq!(out.pending_demand_profile.as_deref(), Some("l4-spot"));
}
// ── /v1/chat/completions parsing + body composition ────────────
diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rs
index 6016a2736..ae462bcff 100644
--- a/packages/sie_gateway/src/handlers/sse.rs
+++ b/packages/sie_gateway/src/handlers/sse.rs
@@ -137,47 +137,74 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
metrics::ROUTING_KEY_SOURCE
.with_label_values(&[&model_label, &pool_label, resolved_key.source.as_label()])
.inc();
- let target = if resolved_key.hash.is_none() {
+ let (target, pool_fallback_lane_worker_count) = if resolved_key.hash.is_none() {
metrics::ROUTING_FALLBACK_TOTAL
.with_label_values(&[&model_label, &pool_label, "no_key"])
.inc();
- publisher::PublishTarget::Pool {
- model: model.clone(),
- pool: pool.clone(),
- }
+ (
+ publisher::PublishTarget::Pool {
+ pool: pool.clone(),
+ machine_profile: gpu.clone(),
+ bundle: bundle.clone(),
+ model: model.clone(),
+ },
+ 0,
+ )
} else {
- let ring = state.registry.ring_snapshot_for(&model, &pool);
+ let admitted_worker_names = state
+ .pool_manager
+ .admitted_worker_names_for_capped_lane(&pool, &gpu, &bundle)
+ .await;
+ let fallback_lane_worker_count = state.registry.pool_fallback_lane_worker_count(
+ &pool,
+ &gpu,
+ &bundle,
+ &bundle_config_hash,
+ admitted_worker_names.as_ref(),
+ );
+ let ring = state.registry.ring_snapshot_for_admitted(
+ &model,
+ &pool,
+ &gpu,
+ &bundle,
+ &bundle_config_hash,
+ admitted_worker_names.as_ref(),
+ );
+ let ring_len = ring.len();
metrics::ROUTING_HRW_RING_SIZE
.with_label_values(&[&model_label, &pool_label])
- .set(ring.len() as f64);
+ .set(ring_len as f64);
match crate::routing::pick_worker(&ring, &resolved_key) {
- Some(worker_id) => publisher::PublishTarget::Worker {
- model: model.clone(),
- pool: pool.clone(),
- worker_id: worker_id.to_string(),
- },
+ Some(worker_id) => (
+ publisher::PublishTarget::Worker {
+ pool: pool.clone(),
+ machine_profile: gpu.clone(),
+ bundle: bundle.clone(),
+ model: model.clone(),
+ worker_id: worker_id.to_string(),
+ },
+ fallback_lane_worker_count,
+ ),
None => {
metrics::ROUTING_FALLBACK_TOTAL
.with_label_values(&[&model_label, &pool_label, "unhealthy_skipped"])
.inc();
- publisher::PublishTarget::Pool {
- model: model.clone(),
- pool: pool.clone(),
- }
+ (
+ publisher::PublishTarget::Pool {
+ pool: pool.clone(),
+ machine_profile: gpu.clone(),
+ bundle: bundle.clone(),
+ model: model.clone(),
+ },
+ fallback_lane_worker_count,
+ )
}
}
};
let was_direct_dispatched = matches!(target, publisher::PublishTarget::Worker { .. });
let (request_id, outcome_rx, chunk_rx) = match work_publisher
- .publish_generate_streaming_sse(
- target,
- &bundle,
- &engine,
- &gpu,
- &bundle_config_hash,
- &work_params,
- )
+ .publish_generate_streaming_sse(target, &engine, &bundle_config_hash, &work_params)
.await
{
Ok(triple) => triple,
@@ -187,13 +214,18 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
// for the `PublishFailed` arm).
let lower = e.to_lowercase();
let retry_after = if lower.contains("no consumers") {
- metrics::record_rejected_request(&gpu, &bundle, "no_consumers");
+ metrics::record_rejected_request_for_pool(&pool, &gpu, &bundle, "no_consumers");
Some("120")
} else if lower.contains("backpressure") {
- metrics::record_rejected_request(&gpu, &bundle, "backpressure");
+ metrics::record_rejected_request_for_pool(&pool, &gpu, &bundle, "backpressure");
Some("5")
} else {
- metrics::record_rejected_request(&gpu, &bundle, "queue_publish_failed");
+ metrics::record_rejected_request_for_pool(
+ &pool,
+ &gpu,
+ &bundle,
+ "queue_publish_failed",
+ );
None
};
return crate::handlers::proxy::build_streaming_publish_failed_for_sse(&e, retry_after);
@@ -268,6 +300,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
inter_chunk_timeout: timeout_config.inter_chunk,
overall_timeout: effective_overall,
was_direct_dispatched,
+ pool_fallback_lane_worker_count,
})
.await;
});
@@ -323,6 +356,7 @@ struct SseDriverArgs {
inter_chunk_timeout: Duration,
overall_timeout: Duration,
was_direct_dispatched: bool,
+ pool_fallback_lane_worker_count: usize,
}
/// Internal SSE driver — loops on the broadcast tap, forwards
@@ -353,6 +387,7 @@ async fn run_sse_driver(args: SseDriverArgs) {
inter_chunk_timeout,
overall_timeout,
was_direct_dispatched,
+ pool_fallback_lane_worker_count,
} = args;
// Install the cancel-on-drop guard. Mirrors
@@ -384,6 +419,10 @@ async fn run_sse_driver(args: SseDriverArgs) {
// ``finish_reason``/``logprobs``.
let mut multi_candidate_stream = false;
let mut republished_for_first_chunk = false;
+ let single_consumer_lane_at_dispatch = crate::routing::suppress_first_chunk_republish_for_lane(
+ was_direct_dispatched,
+ pool_fallback_lane_worker_count,
+ );
// The terminal-outcome oneshot. The per-chunk broadcast tap drives
// the normal forwarding path, but the oneshot is the *only* carrier
@@ -437,7 +476,12 @@ async fn run_sse_driver(args: SseDriverArgs) {
"overall",
])
.inc();
- metrics::record_rejected_request(&gpu, &bundle, "generation_overall_timeout");
+ metrics::record_rejected_request_for_pool(
+ &pool,
+ &gpu,
+ &bundle,
+ "generation_overall_timeout",
+ );
cancel_guard.defuse();
publisher.publish_cancel(&request_id).await;
publisher.drop_pending_stream(&request_id);
@@ -448,7 +492,10 @@ async fn run_sse_driver(args: SseDriverArgs) {
// `run_streaming_generate`). The broadcast receiver is
// already subscribed, so chunks from the republished
// attempt flow into this same loop.
- if was_direct_dispatched && !republished_for_first_chunk {
+ if was_direct_dispatched
+ && !republished_for_first_chunk
+ && !single_consumer_lane_at_dispatch
+ {
republished_for_first_chunk = true;
// At-least-once-execution hazard (mirrors the non-SSE
// `run_streaming_generate` path): a SLOW original
@@ -483,6 +530,21 @@ async fn run_sse_driver(args: SseDriverArgs) {
}
}
}
+ if single_consumer_lane_at_dispatch
+ && was_direct_dispatched
+ && !republished_for_first_chunk
+ {
+ republished_for_first_chunk = true;
+ first_chunk_deadline = overall_deadline;
+ tracing::debug!(
+ request_id = %request_id,
+ pool = %pool,
+ machine_profile = %gpu,
+ bundle = %bundle,
+ "SSE: first_chunk_timeout - single-worker lane, suppressing republish; continuing on overall_timeout"
+ );
+ continue;
+ }
send_error_chunk(
&event_tx,
&endpoint,
@@ -502,7 +564,12 @@ async fn run_sse_driver(args: SseDriverArgs) {
"first_chunk",
])
.inc();
- metrics::record_rejected_request(&gpu, &bundle, "generation_first_chunk_timeout");
+ metrics::record_rejected_request_for_pool(
+ &pool,
+ &gpu,
+ &bundle,
+ "generation_first_chunk_timeout",
+ );
cancel_guard.defuse();
publisher.publish_cancel(&request_id).await;
publisher.drop_pending_stream(&request_id);
@@ -529,7 +596,12 @@ async fn run_sse_driver(args: SseDriverArgs) {
"inter_chunk",
])
.inc();
- metrics::record_rejected_request(&gpu, &bundle, "generation_inter_chunk_timeout");
+ metrics::record_rejected_request_for_pool(
+ &pool,
+ &gpu,
+ &bundle,
+ "generation_inter_chunk_timeout",
+ );
cancel_guard.defuse();
publisher.publish_cancel(&request_id).await;
publisher.drop_pending_stream(&request_id);
diff --git a/packages/sie_gateway/src/metrics.rs b/packages/sie_gateway/src/metrics.rs
index da3e90ca5..3d094c279 100644
--- a/packages/sie_gateway/src/metrics.rs
+++ b/packages/sie_gateway/src/metrics.rs
@@ -200,7 +200,7 @@ pub static PENDING_DEMAND: LazyLock<GaugeVec> = LazyLock::new(|| {
"sie_gateway_pending_demand",
"Pools with unmet demand (KEDA trigger)",
),
- &["machine_profile", "bundle"],
+ &["pool", "machine_profile", "bundle"],
)
.unwrap()
});
@@ -212,7 +212,7 @@ pub static ACTIVE_LEASE_GPUS: LazyLock<GaugeVec> = LazyLock::new(|| {
"sie_gateway_active_lease_gpus",
"GPUs from active leases (KEDA trigger)",
),
- &["machine_profile", "bundle"],
+ &["pool", "machine_profile", "bundle"],
)
.unwrap()
});
@@ -223,7 +223,7 @@ pub static REJECTED_REQUESTS: LazyLock<CounterVec> = LazyLock::new(|| {
"sie_gateway_rejected_requests_total",
"Requests rejected before reaching a worker",
),
- &["machine_profile", "bundle", "reason"],
+ &["pool", "machine_profile", "bundle", "reason"],
)
.unwrap()
});
@@ -241,7 +241,7 @@ pub static WORKER_COUNT: LazyLock<GaugeVec> = LazyLock::new(|| {
pub static WORKER_QUEUE_DEPTH: LazyLock<GaugeVec> = LazyLock::new(|| {
GaugeVec::new(
Opts::new("sie_gateway_worker_queue_depth", "Per-worker queue depth"),
- &["worker", "machine_profile", "bundle"],
+ &["pool", "worker", "machine_profile", "bundle"],
)
.unwrap()
});
@@ -921,10 +921,10 @@ pub fn set_nats_connected(connected: bool) {
pub fn init_metric_families() {
REQUEST_COUNT.with_label_values(&["", "", ""]).inc_by(0.0);
PROVISIONING_RESPONSES.with_label_values(&[""]).inc_by(0.0);
- PENDING_DEMAND.with_label_values(&["", ""]).set(0.0);
- ACTIVE_LEASE_GPUS.with_label_values(&["", ""]).set(0.0);
+ PENDING_DEMAND.with_label_values(&["", "", ""]).set(0.0);
+ ACTIVE_LEASE_GPUS.with_label_values(&["", "", ""]).set(0.0);
REJECTED_REQUESTS
- .with_label_values(&["", "", ""])
+ .with_label_values(&["", "", "", ""])
.inc_by(0.0);
// Seed the gauge families that other call sites write to,
// so they appear in /metrics even before the first real
@@ -980,7 +980,7 @@ pub fn update_worker_metrics(workers: &[WorkerSnapshot]) {
unhealthy_count += 1;
}
WORKER_QUEUE_DEPTH
- .with_label_values(&[&w.name, &w.machine_profile, &w.bundle])
+ .with_label_values(&[&w.pool_name, &w.name, &w.machine_profile, &w.bundle])
.set(w.queue_depth as f64);
WORKER_MEMORY_USED
.with_label_values(&[&w.name, &w.machine_profile, &w.bundle])
@@ -1017,14 +1017,20 @@ pub fn update_model_metrics(models: &std::collections::HashMap<String, usize>) {
}
}
-pub fn record_rejected_request(machine_profile: &str, bundle: &str, reason: &str) {
+pub fn record_rejected_request_for_pool(
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ reason: &str,
+) {
+ let effective_pool = if pool.is_empty() { "unknown" } else { pool };
let effective_profile = if machine_profile.is_empty() {
"unknown"
} else {
machine_profile
};
REJECTED_REQUESTS
- .with_label_values(&[effective_profile, bundle, reason])
+ .with_label_values(&[effective_pool, effective_profile, bundle, reason])
.inc();
}
@@ -1032,7 +1038,7 @@ pub fn record_rejected_request(machine_profile: &str, bundle: &str, reason: &str
/// Called when worker metrics are updated to cancel stale demand signals.
/// Uses the DemandTracker to properly cancel expiry timers when clearing.
pub fn clear_fulfilled_demand(
- healthy_worker_groups: &std::collections::HashSet<(String, String)>,
+ healthy_worker_groups: &std::collections::HashSet<(String, String, String)>,
demand_tracker: &crate::state::demand_tracker::DemandTracker,
) {
// Gather current demand label pairs from the metric
@@ -1048,12 +1054,18 @@ pub fn clear_fulfilled_demand(
.map(|l| (l.name(), l.value()))
.collect();
if let Some(&gpu) = labels.get("machine_profile") {
+ let pool = labels.get("pool").copied().unwrap_or("default");
let bundle = labels.get("bundle").copied().unwrap_or("default");
- if healthy_worker_groups.contains(&(gpu.to_lowercase(), bundle.to_lowercase())) {
- let current = PENDING_DEMAND.with_label_values(&[gpu, bundle]).get();
+ if healthy_worker_groups.contains(&(
+ pool.to_lowercase(),
+ gpu.to_lowercase(),
+ bundle.to_lowercase(),
+ )) {
+ let current = PENDING_DEMAND.with_label_values(&[pool, gpu, bundle]).get();
if current > 0.0 {
- demand_tracker.clear(gpu, bundle);
+ demand_tracker.clear(pool, gpu, bundle);
tracing::info!(
+ pool = pool,
gpu = gpu,
bundle = bundle,
"cleared pending demand — healthy workers available"
@@ -1076,15 +1088,29 @@ pub fn update_pool_metrics(pools: &[crate::types::Pool]) {
// re-seed the `init_metric_families()` sentinel is wiped on the
// very first scrape.
ACTIVE_LEASE_GPUS.reset();
- ACTIVE_LEASE_GPUS.with_label_values(&["", ""]).set(0.0);
+ ACTIVE_LEASE_GPUS.with_label_values(&["", "", ""]).set(0.0);
for pool in pools {
if pool.status.state == PoolState::Active && pool.spec.name != DEFAULT_POOL_NAME {
- let bundle = pool.spec.bundle.as_deref().unwrap_or("default");
- for (gpu_type, count) in &pool.spec.gpus {
- ACTIVE_LEASE_GPUS
- .with_label_values(&[gpu_type, bundle])
- .add(*count as f64);
+ if let Some(bundle) = pool.spec.bundle.as_deref() {
+ for (gpu_type, count) in &pool.spec.gpus {
+ ACTIVE_LEASE_GPUS
+ .with_label_values(&[&pool.spec.name, gpu_type, bundle])
+ .add(*count as f64);
+ }
+ } else {
+ let mut assigned_by_lane: std::collections::HashMap<(&str, &str), usize> =
+ std::collections::HashMap::new();
+ for worker in &pool.status.assigned_workers {
+ *assigned_by_lane
+ .entry((&worker.gpu, &worker.bundle))
+ .or_default() += 1;
+ }
+ for ((gpu_type, bundle), count) in assigned_by_lane {
+ ACTIVE_LEASE_GPUS
+ .with_label_values(&[&pool.spec.name, gpu_type, bundle])
+ .add(count as f64);
+ }
}
}
}
@@ -1093,7 +1119,7 @@ pub fn update_pool_metrics(pools: &[crate::types::Pool]) {
#[cfg(test)]
mod tests {
use super::*;
- use crate::types::pool::{Pool, PoolSpec, PoolState, PoolStatus};
+ use crate::types::pool::{AssignedWorker, Pool, PoolSpec, PoolState, PoolStatus};
use std::collections::HashMap;
use std::sync::Mutex;
@@ -1151,11 +1177,47 @@ mod tests {
update_pool_metrics(&pools);
let val = ACTIVE_LEASE_GPUS
- .with_label_values(&["l4-spot", "premium"])
+ .with_label_values(&["eval-pool", "l4-spot", "premium"])
.get();
assert!((val - 2.0).abs() < f64::EPSILON);
}
+ #[test]
+ fn test_update_pool_metrics_unfiltered_pool_uses_assigned_worker_bundles() {
+ let _guard = METRICS_TEST_LOCK.lock().unwrap();
+ let _ = &*REGISTRY;
+ reset_test_metrics();
+
+ let mut gpus = HashMap::new();
+ gpus.insert("rtx6000".to_string(), 2);
+ let mut pool = make_pool("customer-acme", PoolState::Active, gpus, None);
+ pool.status.assigned_workers = vec![
+ AssignedWorker {
+ name: "worker-default".to_string(),
+ url: "http://worker-default:8080".to_string(),
+ gpu: "rtx6000".to_string(),
+ bundle: "default".to_string(),
+ },
+ AssignedWorker {
+ name: "worker-sglang".to_string(),
+ url: "http://worker-sglang:8080".to_string(),
+ gpu: "rtx6000".to_string(),
+ bundle: "sglang".to_string(),
+ },
+ ];
+
+ update_pool_metrics(&[pool]);
+
+ let default_val = ACTIVE_LEASE_GPUS
+ .with_label_values(&["customer-acme", "rtx6000", "default"])
+ .get();
+ let sglang_val = ACTIVE_LEASE_GPUS
+ .with_label_values(&["customer-acme", "rtx6000", "sglang"])
+ .get();
+ assert!((default_val - 1.0).abs() < f64::EPSILON);
+ assert!((sglang_val - 1.0).abs() < f64::EPSILON);
+ }
+
#[test]
fn test_update_pool_metrics_skips_default_pool() {
let _guard = METRICS_TEST_LOCK.lock().unwrap();
@@ -1170,7 +1232,7 @@ mod tests {
// Default pool should not contribute to active lease GPUs
let val = ACTIVE_LEASE_GPUS
- .with_label_values(&["l4-spot", "default"])
+ .with_label_values(&["default", "l4-spot", "default"])
.get();
assert!((val - 0.0).abs() < f64::EPSILON);
}
@@ -1193,7 +1255,7 @@ mod tests {
update_pool_metrics(&pools);
let val = ACTIVE_LEASE_GPUS
- .with_label_values(&["a100", "default"])
+ .with_label_values(&["pending-pool", "a100", "default"])
.get();
assert!((val - 0.0).abs() < f64::EPSILON);
}
@@ -1205,7 +1267,7 @@ mod tests {
reset_test_metrics();
ACTIVE_LEASE_GPUS
- .with_label_values(&["stale-gpu", "stale-bundle"])
+ .with_label_values(&["stale-pool", "stale-gpu", "stale-bundle"])
.set(10.0);
update_pool_metrics(&[]);
@@ -1308,7 +1370,7 @@ mod tests {
}];
update_worker_metrics(&first);
let d = WORKER_QUEUE_DEPTH
- .with_label_values(&["ghost-worker", "l4-spot", "default"])
+ .with_label_values(&["default-pool", "ghost-worker", "l4-spot", "default"])
.get();
assert!((d - 42.0).abs() < f64::EPSILON);
@@ -1327,7 +1389,7 @@ mod tests {
// The new worker is visible.
let d2 = WORKER_QUEUE_DEPTH
- .with_label_values(&["other-worker", "a100", "premium"])
+ .with_label_values(&["premium-pool", "other-worker", "a100", "premium"])
.get();
assert!((d2 - 7.0).abs() < f64::EPSILON);
@@ -1395,17 +1457,21 @@ mod tests {
// Set demand for l4-spot
PENDING_DEMAND
- .with_label_values(&["l4-spot", "default"])
+ .with_label_values(&["default", "l4-spot", "default"])
.set(1.0);
- // Healthy workers include l4-spot/default.
+ // Healthy workers include default/l4-spot/default.
let mut worker_groups = std::collections::HashSet::new();
- worker_groups.insert(("l4-spot".to_string(), "default".to_string()));
+ worker_groups.insert((
+ "default".to_string(),
+ "l4-spot".to_string(),
+ "default".to_string(),
+ ));
clear_fulfilled_demand(&worker_groups, &tracker);
let val = PENDING_DEMAND
- .with_label_values(&["l4-spot", "default"])
+ .with_label_values(&["default", "l4-spot", "default"])
.get();
assert!((val - 0.0).abs() < f64::EPSILON);
}
@@ -1420,17 +1486,23 @@ mod tests {
// Set demand for h100 (no healthy workers)
PENDING_DEMAND
- .with_label_values(&["h100", "default"])
+ .with_label_values(&["default", "h100", "default"])
.set(1.0);
- // Only l4-spot/default is healthy.
+ // Only default/l4-spot/default is healthy.
let mut worker_groups = std::collections::HashSet::new();
- worker_groups.insert(("l4-spot".to_string(), "default".to_string()));
+ worker_groups.insert((
+ "default".to_string(),
+ "l4-spot".to_string(),
+ "default".to_string(),
+ ));
clear_fulfilled_demand(&worker_groups, &tracker);
// h100 demand should remain
- let val = PENDING_DEMAND.with_label_values(&["h100", "default"]).get();
+ let val = PENDING_DEMAND
+ .with_label_values(&["default", "h100", "default"])
+ .get();
assert!((val - 1.0).abs() < f64::EPSILON);
}
@@ -1444,26 +1516,38 @@ mod tests {
// Same machine profile has demand in two bundles.
PENDING_DEMAND
- .with_label_values(&["l4-spot", "default"])
+ .with_label_values(&["default", "l4-spot", "default"])
.set(1.0);
PENDING_DEMAND
- .with_label_values(&["l4-spot", "sglang"])
+ .with_label_values(&["default", "l4-spot", "sglang"])
+ .set(1.0);
+ PENDING_DEMAND
+ .with_label_values(&["tenant-a", "l4-spot", "default"])
.set(1.0);
- // A healthy default worker must not clear sglang demand.
+ // A healthy default-pool default-bundle worker must not clear
+ // sglang demand or another pool's default-bundle demand.
let mut worker_groups = std::collections::HashSet::new();
- worker_groups.insert(("l4-spot".to_string(), "default".to_string()));
+ worker_groups.insert((
+ "default".to_string(),
+ "l4-spot".to_string(),
+ "default".to_string(),
+ ));
clear_fulfilled_demand(&worker_groups, &tracker);
let default_val = PENDING_DEMAND
- .with_label_values(&["l4-spot", "default"])
+ .with_label_values(&["default", "l4-spot", "default"])
.get();
let sglang_val = PENDING_DEMAND
- .with_label_values(&["l4-spot", "sglang"])
+ .with_label_values(&["default", "l4-spot", "sglang"])
+ .get();
+ let tenant_val = PENDING_DEMAND
+ .with_label_values(&["tenant-a", "l4-spot", "default"])
.get();
assert!((default_val - 0.0).abs() < f64::EPSILON);
assert!((sglang_val - 1.0).abs() < f64::EPSILON);
+ assert!((tenant_val - 1.0).abs() < f64::EPSILON);
}
// ------------------------------------------------------------------
diff --git a/packages/sie_gateway/src/queue/consumer.rs b/packages/sie_gateway/src/queue/consumer.rs
deleted file mode 100644
index 6d8601ef3..000000000
--- a/packages/sie_gateway/src/queue/consumer.rs
+++ /dev/null
@@ -1,232 +0,0 @@
-use std::sync::Arc;
-use std::time::Duration;
-
-use async_nats::jetstream;
-use async_nats::jetstream::consumer::pull::Config as ConsumerConfig;
-use futures_util::StreamExt;
-use tracing::{debug, error, info, warn};
-
-use super::publisher::{WorkItem, WorkResult};
-
-#[allow(dead_code)]
-const ACK_WAIT_SECS: u64 = 30;
-#[allow(dead_code)]
-const MAX_DELIVER: i64 = 3;
-#[allow(dead_code)]
-const MAX_ACK_PENDING: i64 = 1000;
-
-/// WorkConsumer pulls work items from a JetStream stream and processes them
-/// via a callback. Results are published back to the reply inbox.
-#[allow(dead_code)]
-pub struct WorkConsumer {
- jetstream: jetstream::Context,
- client: async_nats::Client,
- pool: String,
- bundle: String,
-}
-
-#[allow(dead_code)]
-impl WorkConsumer {
- pub fn new(
- jetstream: jetstream::Context,
- client: async_nats::Client,
- pool: &str,
- bundle: &str,
- ) -> Self {
- Self {
- jetstream,
- client,
- pool: pool.to_string(),
- bundle: bundle.to_string(),
- }
- }
-
- fn consumer_name(&self) -> String {
- format!("WORK_CONSUMER_{}_{}", self.bundle, self.pool)
- }
-
- /// Create or get a durable pull consumer for the given pool.
- pub async fn ensure_consumer(&self) -> Result<(), String> {
- let stream_name = format!("WORK_POOL_{}", self.pool);
- let consumer_name = self.consumer_name();
-
- let stream = self
- .jetstream
- .get_stream(&stream_name)
- .await
- .map_err(|e| format!("get stream {}: {}", stream_name, e))?;
-
- stream
- .get_or_create_consumer(
- &consumer_name,
- ConsumerConfig {
- durable_name: Some(consumer_name.clone()),
- ack_wait: Duration::from_secs(ACK_WAIT_SECS),
- max_deliver: MAX_DELIVER,
- max_ack_pending: MAX_ACK_PENDING,
- ..Default::default()
- },
- )
- .await
- .map_err(|e| format!("create consumer {}: {}", consumer_name, e))?;
-
- info!(
- stream = %stream_name,
- consumer = %consumer_name,
- "ensured durable pull consumer"
- );
-
- Ok(())
- }
-
- /// Start consuming work items. The `handler` callback processes each item
- /// and returns a WorkResult.
- pub async fn start<F, Fut>(self: Arc<Self>, handler: F) -> Result<(), String>
- where
- F: Fn(WorkItem) -> Fut + Send + Sync + 'static,
- Fut: std::future::Future<Output = WorkResult> + Send + 'static,
- {
- let stream_name = format!("WORK_POOL_{}", self.pool);
- let consumer_name = self.consumer_name();
-
- let stream = self
- .jetstream
- .get_stream(&stream_name)
- .await
- .map_err(|e| format!("get stream {}: {}", stream_name, e))?;
-
- let consumer = stream
- .get_consumer::<ConsumerConfig>(&consumer_name)
- .await
- .map_err(|e| format!("get consumer {}: {}", consumer_name, e))?;
-
- let handler = Arc::new(handler);
- let client = self.client.clone();
-
- tokio::spawn(async move {
- info!(
- stream = %stream_name,
- consumer = %consumer_name,
- "starting work consumer loop"
- );
-
- let mut messages = match consumer.messages().await {
- Ok(m) => m,
- Err(e) => {
- error!(error = %e, "failed to get message stream");
- return;
- }
- };
-
- while let Some(msg_result) = messages.next().await {
- let msg = match msg_result {
- Ok(m) => m,
- Err(e) => {
- warn!(error = %e, "error receiving message");
- continue;
- }
- };
-
- // Decode work item
- let work_item: WorkItem = match rmp_serde::from_slice(&msg.payload) {
- Ok(item) => item,
- Err(e) => {
- warn!(error = %e, "failed to decode work item");
- if let Err(e) = msg.ack().await {
- warn!(error = %e, "failed to ack malformed message");
- }
- continue;
- }
- };
-
- let reply_inbox = work_item.reply_subject.clone();
- let request_id = work_item.request_id.clone();
- let item_index = work_item.item_index;
-
- debug!(
- request_id = %request_id,
- item_index = item_index,
- operation = %work_item.operation,
- "processing work item"
- );
-
- // Process the work item
- let result = handler(work_item).await;
-
- // Acknowledge the message (explicit ACK)
- if let Err(e) = msg.ack().await {
- warn!(
- request_id = %request_id,
- error = %e,
- "failed to ack message"
- );
- }
-
- // Publish result back to reply inbox
- let encoded = match rmp_serde::to_vec(&result) {
- Ok(bytes) => bytes,
- Err(e) => {
- error!(
- request_id = %request_id,
- error = %e,
- "failed to encode result"
- );
- continue;
- }
- };
-
- if let Err(e) = client.publish(reply_inbox.clone(), encoded.into()).await {
- error!(
- request_id = %request_id,
- reply_inbox = %reply_inbox,
- error = %e,
- "failed to publish result"
- );
- }
- }
-
- warn!("work consumer loop ended");
- });
-
- Ok(())
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_ack_wait_duration() {
- assert_eq!(ACK_WAIT_SECS, 30);
- }
-
- #[test]
- fn test_max_deliver() {
- assert_eq!(MAX_DELIVER, 3);
- }
-
- #[test]
- fn test_max_ack_pending() {
- assert_eq!(MAX_ACK_PENDING, 1000);
- }
-
- #[test]
- fn test_stream_name_format() {
- let pool = "default";
- let expected = "WORK_POOL_default";
- assert_eq!(format!("WORK_POOL_{}", pool), expected);
- }
-
- #[test]
- fn test_consumer_name_format() {
- assert_eq!(
- format!("WORK_CONSUMER_{}_{}", "default", "eval-l4"),
- "WORK_CONSUMER_default_eval-l4"
- );
- assert_eq!(
- format!("WORK_CONSUMER_{}_{}", "my-bundle", "default"),
- "WORK_CONSUMER_my-bundle_default"
- );
- }
-}
diff --git a/packages/sie_gateway/src/queue/dlq.rs b/packages/sie_gateway/src/queue/dlq.rs
index 38129cd88..143606c41 100644
--- a/packages/sie_gateway/src/queue/dlq.rs
+++ b/packages/sie_gateway/src/queue/dlq.rs
@@ -102,9 +102,10 @@ impl DlqListener {
// Extract the model token from the advisory's original subject.
//
// The publisher constructs work subjects as
- // `sie.work.{normalize_model_id(model)}.{pool}` — exactly four
- // dot-separated tokens, with the 3rd token already safe to use as
- // a single NATS token (no `.`, `*`, `>`, or whitespace). We keep
+ // `sie.work.{pool}.{machine_profile}.{bundle}.{normalize_model_id(model)}`
+ // — exactly six dot-separated tokens, with the 6th token already
+ // safe to use as a single NATS token (no `.`, `*`, `>`, or whitespace).
+ // We keep
// the `/` -> `_` belt-and-suspenders replacement as a no-op for
// correctly-normalized subjects and a fallback for any legacy
// un-normalized messages still in-flight at the time of upgrade.
@@ -112,9 +113,9 @@ impl DlqListener {
.get("subject")
.and_then(|v| v.as_str())
.and_then(|s| {
- let parts: Vec<&str> = s.splitn(4, '.').collect();
- if parts.len() >= 3 {
- Some(parts[2].replace('/', "_"))
+ let parts: Vec<&str> = s.split('.').collect();
+ if parts.len() >= 6 {
+ Some(parts[5].replace('/', "_"))
} else {
None
}
diff --git a/packages/sie_gateway/src/queue/mod.rs b/packages/sie_gateway/src/queue/mod.rs
index 1baa774ca..27411348d 100644
--- a/packages/sie_gateway/src/queue/mod.rs
+++ b/packages/sie_gateway/src/queue/mod.rs
@@ -1,4 +1,3 @@
-pub mod consumer;
pub mod dlq;
pub mod payload_store;
pub mod publisher;
diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rs
index 022cc9de5..ad5a240c0 100644
--- a/packages/sie_gateway/src/queue/publisher.rs
+++ b/packages/sie_gateway/src/queue/publisher.rs
@@ -362,102 +362,7 @@ pub struct GenerateParams {
pub lora_adapter: Option<String>,
}
-/// Work item published to JetStream for queue mode.
-/// Serialized as a msgpack **map** (named fields) to match the Python WorkItem TypedDict
-/// that the worker consumer expects (`wi.get("operation")` etc.).
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct WorkItem {
- pub work_item_id: String,
- pub request_id: String,
- pub item_index: u32,
- pub total_items: u32,
- pub operation: String,
- pub model_id: String,
- #[serde(default)]
- pub profile_id: String,
- /// Execution engine the bundle that resolved this request
- /// declares. Today only ``"pytorch"`` is recognised (see
- /// ``KNOWN_ENGINES`` in ``types::bundle``). Workers can use
- /// this as a sanity check (``assert engine == self.engine``)
- /// or as a soft dispatch hint when a single pool ever ends up
- /// multiplexing engines. Older workers default to ``""`` and
- /// ignore the field — back-compat is preserved by
- /// ``#[serde(default)]``.
- #[serde(default)]
- pub engine: String,
- pub pool_name: String,
- pub machine_profile: String,
- /// Per-item payload. Carried as `rmpv::Value` so msgpack request
- /// bodies (especially those with `bin`/`ext` fields such as
- /// encoded numpy arrays) can round-trip to the worker byte-for-
- /// byte, without the old
- /// `msgpack → rmpv::Value → serde_json::Value → msgpack` detour
- /// that used to expand every `bin` into a `Vec<Number>`.
- #[serde(default)]
- pub item: Option<rmpv::Value>,
- #[serde(default)]
- pub payload_ref: Option<String>,
- #[serde(default)]
- pub output_types: Option<Vec<String>>,
- #[serde(default)]
- pub instruction: Option<String>,
- #[serde(default)]
- pub is_query: bool,
- #[serde(default)]
- pub options: Option<serde_json::Value>,
- /// Score query. Same rationale as `item` above.
- #[serde(default)]
- pub query_item: Option<rmpv::Value>,
- #[serde(default)]
- pub query_payload_ref: Option<String>,
- /// Score items. Same rationale as `item` above.
- #[serde(default)]
- pub score_items: Option<Vec<rmpv::Value>>,
- #[serde(default)]
- pub labels: Option<Vec<String>>,
- #[serde(default)]
- pub output_schema: Option<serde_json::Value>,
- /// Generate-only params. Absent on encode/score/extract.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub generate: Option<GenerateParams>,
- /// Routing-affinity hint. Carried alongside
- /// ``generate`` so direct-dispatch logic can read it
- /// without unpacking the typed generate block.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub routing_key: Option<String>,
- /// Prompt-cache hint. Same plumbing as
- /// :attr:`routing_key`.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub prompt_cache_key: Option<String>,
- #[serde(default)]
- pub bundle_config_hash: String,
- #[serde(default)]
- pub router_id: String,
- pub reply_subject: String,
- /// Epoch seconds (f64) when the work item was created (for queue latency tracking).
- #[serde(default)]
- pub timestamp: f64,
- /// W3C Trace Context `traceparent` header value, injected at
- /// publish time when a trace is active on the gateway. Absent
- /// (skipped during msgpack encode) when no parent context was
- /// extracted from the inbound HTTP request and no gateway span
- /// is recording — keeping the envelope shape backward-compatible
- /// with pre-M5 callers.
- ///
- /// Privacy: the value is two opaque IDs (trace + span) plus
- /// flags; do not log it at info-level (debug is fine). The
- /// gateway intentionally does not propagate the inbound
- /// `traceparent` *byte-for-byte* — it injects the *gateway*
- /// span's context, which is a valid child of the inbound trace.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub traceparent: Option<String>,
- /// W3C Trace Context `tracestate` header value (vendor state).
- /// Same semantics as [`Self::traceparent`].
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub tracestate: Option<String>,
-}
-
-/// Borrowed, serialize-only view of a [`WorkItem`].
+/// Borrowed, serialize-only view of the worker work-item envelope.
///
/// Used on the publish hot path to avoid cloning per-item the fields
/// that every item in a batch shares (pool/model/gpu/router_id/
@@ -467,12 +372,11 @@ pub struct WorkItem {
/// this saves roughly `7N` small-string clones plus `4N` deep
/// `Option<Vec<_>> / Option<serde_json::Value>` clones.
///
-/// The field names, order, and serde attributes are kept identical
-/// to [`WorkItem`] so that `rmp_serde::to_vec_named(&WorkItemRef)`
-/// produces the same msgpack wire bytes as encoding the equivalent
-/// owned `WorkItem`. Deserialization is intentionally not supported
-/// — results arrive as `WorkResult`, and inbound `WorkItem`s (only
-/// in tests) still use the owned form.
+/// The field names, order, and serde attributes are guarded by tests
+/// against an owned envelope shape so `rmp_serde::to_vec_named(&WorkItemRef)`
+/// keeps producing the msgpack map the Python worker consumes.
+/// Deserialization is intentionally not supported; results arrive as
+/// `WorkResult`.
#[derive(Debug, Serialize)]
struct WorkItemRef<'a> {
pub work_item_id: &'a str,
@@ -507,8 +411,8 @@ struct WorkItemRef<'a> {
pub reply_subject: &'a str,
pub timestamp: f64,
/// W3C Trace Context. Skipped on serialisation when `None`,
- /// preserving byte-identical msgpack with the owned [`WorkItem`]
- /// view that locks the legacy (pre-M5) wire shape.
+ /// preserving the compact pre-observability wire shape when no
+ /// trace context is present.
#[serde(skip_serializing_if = "Option::is_none")]
pub traceparent: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -631,10 +535,20 @@ fn stream_name(pool: &str) -> String {
format!("WORK_POOL_{}", pool)
}
-/// Normalize a model ID for use as a single NATS subject token.
+fn canonical_stream_subjects(observed: Vec<String>, desired: &str) -> Option<Vec<String>> {
+ if observed.len() == 1 && observed.first().is_some_and(|subject| subject == desired) {
+ None
+ } else {
+ Some(vec![desired.to_string()])
+ }
+}
+
+/// Normalize a model ID or operator-provided lane id for use as a single
+/// NATS subject token.
///
-/// The workers' JetStream pull consumer filters on `sie.work.*.{pool}`, which
-/// matches **exactly one token** in the model-ID position. NATS subject tokens
+/// The workers' JetStream pull consumer filters on
+/// `sie.work.{pool}.{machine_profile}.{bundle}.*`, which matches
+/// **exactly one token** in the model-ID position. NATS subject tokens
/// legally contain `/` but MUST NOT contain `.`, `*`, `>`, or whitespace.
/// Without this normalization, a model with `.` in its id (e.g.
/// `vidore/colqwen2.5-v0.2`) would expand into multiple tokens, the publish
@@ -673,18 +587,30 @@ fn normalize_model_id(model_id: &str) -> String {
out
}
-fn work_subject(model: &str, pool: &str) -> String {
- format!("sie.work.{}.{}", normalize_model_id(model), pool)
+fn work_subject(pool: &str, machine_profile: &str, bundle: &str, model: &str) -> String {
+ format!(
+ "sie.work.{}.{}.{}.{}",
+ pool,
+ normalize_model_id(machine_profile),
+ normalize_model_id(bundle),
+ normalize_model_id(model)
+ )
}
-/// Per-worker subject `sie.work.{model}.{pool}.{worker_id}`.
+/// Per-worker subject `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`.
///
/// Matches `sie_sdk.queue_types.work_worker_subject` so workers and
/// the gateway agree on the wire-level subject. The pool stream
-/// filters on `sie.work.*.{pool}` (3 tokens after `sie.work.`) so
-/// this 4-token subject cannot be captured by it — exactly the
-/// double-delivery guarantee the design requires.
-fn work_subject_worker(model: &str, pool: &str, worker_id: &str) -> String {
+/// filters on `sie.work.{pool}.*.*.*`, so this worker-addressed subject
+/// cannot be captured by it — exactly the double-delivery guarantee
+/// the design requires.
+fn work_subject_worker(
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ model: &str,
+ worker_id: &str,
+) -> String {
// Worker ids are operator-controlled (set via `WorkerStatusMessage.name`,
// ultimately sourced from `SIE_WORKER_ID` / `HOSTNAME` / `POD_NAME` on the
// worker side) and would otherwise be interpolated verbatim into a NATS
@@ -703,9 +629,11 @@ fn work_subject_worker(model: &str, pool: &str, worker_id: &str) -> String {
// Python helper or direct-dispatch will silently miss every worker whose
// raw id contains the newly-changed character.
format!(
- "sie.work.{}.{}.{}",
- normalize_model_id(model),
+ "sie.work.{}.{}.{}.{}.{}",
pool,
+ normalize_model_id(machine_profile),
+ normalize_model_id(bundle),
+ normalize_model_id(model),
normalize_model_id(worker_id)
)
}
@@ -720,15 +648,22 @@ fn work_subject_worker(model: &str, pool: &str, worker_id: &str) -> String {
#[derive(Debug, Clone)]
pub enum PublishTarget {
/// Direct-dispatch to a specific worker. Subject:
- /// `sie.work.{model}.{pool}.{worker_id}`.
+ /// `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`.
Worker {
- model: String,
pool: String,
+ machine_profile: String,
+ bundle: String,
+ model: String,
worker_id: String,
},
/// Pool fan-out — any worker subscribed to
- /// `sie.work.*.{pool}` can pick it up.
- Pool { model: String, pool: String },
+ /// `sie.work.{pool}.{machine_profile}.{bundle}.*` can pick it up.
+ Pool {
+ pool: String,
+ machine_profile: String,
+ bundle: String,
+ model: String,
+ },
}
impl PublishTarget {
@@ -736,11 +671,18 @@ impl PublishTarget {
pub fn subject(&self) -> String {
match self {
PublishTarget::Worker {
- model,
pool,
+ machine_profile,
+ bundle,
+ model,
worker_id,
- } => work_subject_worker(model, pool, worker_id),
- PublishTarget::Pool { model, pool } => work_subject(model, pool),
+ } => work_subject_worker(pool, machine_profile, bundle, model, worker_id),
+ PublishTarget::Pool {
+ pool,
+ machine_profile,
+ bundle,
+ model,
+ } => work_subject(pool, machine_profile, bundle, model),
}
}
@@ -761,12 +703,24 @@ impl PublishTarget {
#[allow(dead_code)]
pub fn as_pool_fallback(&self) -> PublishTarget {
match self {
- PublishTarget::Worker { model, pool, .. } | PublishTarget::Pool { model, pool } => {
- PublishTarget::Pool {
- model: model.clone(),
- pool: pool.clone(),
- }
+ PublishTarget::Worker {
+ pool,
+ machine_profile,
+ bundle,
+ model,
+ ..
}
+ | PublishTarget::Pool {
+ pool,
+ machine_profile,
+ bundle,
+ model,
+ } => PublishTarget::Pool {
+ pool: pool.clone(),
+ machine_profile: machine_profile.clone(),
+ bundle: bundle.clone(),
+ model: model.clone(),
+ },
}
}
@@ -781,6 +735,17 @@ impl PublishTarget {
PublishTarget::Worker { pool, .. } | PublishTarget::Pool { pool, .. } => pool,
}
}
+
+ pub fn machine_profile(&self) -> &str {
+ match self {
+ PublishTarget::Worker {
+ machine_profile, ..
+ }
+ | PublishTarget::Pool {
+ machine_profile, ..
+ } => machine_profile,
+ }
+ }
}
/// Peek the top-level `kind` discriminator on an already-decoded
@@ -1122,25 +1087,6 @@ impl WorkPublisher {
&self.router_id
}
- /// Number of JetStream consumers registered on the pool's
- /// ``WORK_POOL_<pool>`` stream — refreshed by the stream-info
- /// monitor. ``None`` when the pool hasn't been observed yet
- /// (cold cache); ``Some(0)`` is possible briefly during worker
- /// roll-over.
- ///
- /// Callers use this to gate the H9 first-chunk-fallback path: in
- /// single-consumer pools the republish targets the same worker
- /// that's already handling the original request, which produces
- /// a self-induced cancel-tombstone race
- /// (``cancel arrived before this worker registered;
- /// pool-republished attempt is authoritative``). Skipping the
- /// fallback in that shape preserves the legitimate overall_timeout
- /// fallback for genuinely slow workers without trading it for a
- /// guaranteed 503.
- pub fn pool_consumer_count(&self, pool: &str) -> Option<usize> {
- self.stream_info_cache.get(pool).map(|v| v.num_consumers)
- }
-
/// Ensure the stream exists for the given pool (cached — admin call happens once per pool).
///
/// Returns the cached JetStream stream name as an `Arc<str>` so
@@ -1152,7 +1098,8 @@ impl WorkPublisher {
}
let name = stream_name(pool);
- let subjects = vec![format!("sie.work.*.{}", pool)];
+ let desired_subject = format!("sie.work.{}.*.*.*", pool);
+ let subjects = vec![desired_subject.clone()];
let mut stream = self
.jetstream
@@ -1167,6 +1114,28 @@ impl WorkPublisher {
})
.await
.map_err(|e| format!("create/get stream {}: {}", name, e))?;
+ let observed_subjects = stream.cached_info().config.subjects.clone();
+ if let Some(updated_subjects) =
+ canonical_stream_subjects(observed_subjects.clone(), &desired_subject)
+ {
+ let mut updated = stream.cached_info().config.clone();
+ updated.subjects = updated_subjects;
+ self.jetstream
+ .update_stream(updated)
+ .await
+ .map_err(|e| format!("update stream {} subjects: {}", name, e))?;
+ stream = self
+ .jetstream
+ .get_stream(name.clone())
+ .await
+ .map_err(|e| format!("refresh stream {} after subject update: {}", name, e))?;
+ info!(
+ stream = %name,
+ observed_subjects = ?observed_subjects,
+ desired_subject = %desired_subject,
+ "reconciled JetStream stream subjects to canonical queue lane routing"
+ );
+ }
// Prime the backpressure cache so the very first request to
// this pool sees real consumer/pending numbers instead of
@@ -1203,15 +1172,15 @@ impl WorkPublisher {
/// Check backpressure from cached stream info (lock-free DashMap read).
/// Actual NATS stream.info() calls happen in the background monitor task.
///
- /// **Direct-dispatch caveat:** this check measures the pool-subject's
+ /// **Direct-dispatch caveat:** this check measures the pool stream's
/// pending count. When HRW routes to a worker's private subject
- /// (`sie.work.{model}.{pool}.{worker_id}`) the pool count can read
- /// low while the chosen worker's inbox is saturated. The first-chunk
- /// timeout in `proxy::stream_generate_response` is the safety net: on
- /// timeout, `republish_to_pool` redrives the work item onto the pool
- /// subject so any healthy worker can pick it up. Tighter per-worker
- /// admission is M5+ work (tracked alongside the §6 mixed-pool
- /// fairness scheduler).
+ /// (`sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`)
+ /// the pool count can read low while the chosen worker's inbox is
+ /// saturated. The first-chunk timeout in `proxy::stream_generate_response`
+ /// is the safety net: on timeout, `republish_to_pool` redrives the work
+ /// item onto the lane's pool subject so any healthy matching worker can
+ /// pick it up. Tighter per-worker admission is M5+ work (tracked
+ /// alongside the §6 mixed-pool fairness scheduler).
fn check_backpressure(&self, pool: &str) -> Result<(), String> {
if let Some(info) = self.stream_info_cache.get(pool) {
if info.num_consumers == 0 {
@@ -1291,7 +1260,7 @@ impl WorkPublisher {
pool: &str,
endpoint: &str,
model: &str,
- _bundle: &str,
+ bundle: &str,
engine: &str,
gpu: &str,
bundle_config_hash: &str,
@@ -1319,7 +1288,7 @@ impl WorkPublisher {
items.len() as u32
};
- let subject = work_subject(model, pool);
+ let subject = work_subject(pool, gpu, bundle, model);
// Set up result collector (DashMap — lock-free per-key insert)
let (tx, rx) = oneshot::channel();
@@ -1560,9 +1529,7 @@ impl WorkPublisher {
pub async fn publish_generate_streaming(
&self,
target: PublishTarget,
- _bundle: &str,
engine: &str,
- gpu: &str,
bundle_config_hash: &str,
params: &WorkParams,
) -> Result<
@@ -1575,6 +1542,7 @@ impl WorkPublisher {
> {
let model = target.model().to_string();
let pool = target.pool().to_string();
+ let machine_profile = target.machine_profile().to_string();
// Reuse the same JetStream stream + backpressure plumbing as
// the batch path. The stream collector replaces ResultCollector.
self.ensure_stream(&pool).await?;
@@ -1587,7 +1555,7 @@ impl WorkPublisher {
let request_id = uuid::Uuid::now_v7().to_string();
let reply_subject = format!("_INBOX.{}.{}", self.router_id, request_id);
let subject = target.subject();
- let pool_fallback_subject = work_subject(&model, &pool);
+ let pool_fallback_subject = target.as_pool_fallback().subject();
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
@@ -1613,7 +1581,7 @@ impl WorkPublisher {
endpoint: "generate",
model: &model,
pool: &pool,
- gpu,
+ gpu: &machine_profile,
engine,
bundle_config_hash,
router_id: &self.router_id,
@@ -1671,9 +1639,7 @@ impl WorkPublisher {
pub async fn publish_generate_streaming_sse(
&self,
target: PublishTarget,
- _bundle: &str,
engine: &str,
- gpu: &str,
bundle_config_hash: &str,
params: &WorkParams,
) -> Result<
@@ -1686,6 +1652,7 @@ impl WorkPublisher {
> {
let model = target.model().to_string();
let pool = target.pool().to_string();
+ let machine_profile = target.machine_profile().to_string();
self.ensure_stream(&pool).await?;
self.check_backpressure(&pool)?;
@@ -1696,7 +1663,7 @@ impl WorkPublisher {
let request_id = uuid::Uuid::now_v7().to_string();
let reply_subject = format!("_INBOX.{}.{}", self.router_id, request_id);
let subject = target.subject();
- let pool_fallback_subject = work_subject(&model, &pool);
+ let pool_fallback_subject = target.as_pool_fallback().subject();
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
@@ -1719,7 +1686,7 @@ impl WorkPublisher {
endpoint: "generate",
model: &model,
pool: &pool,
- gpu,
+ gpu: &machine_profile,
engine,
bundle_config_hash,
router_id: &self.router_id,
@@ -2639,12 +2606,97 @@ pub fn encode_response(
mod tests {
use super::*;
+ #[derive(Debug, Clone, Serialize, Deserialize)]
+ struct WorkItem {
+ pub work_item_id: String,
+ pub request_id: String,
+ pub item_index: u32,
+ pub total_items: u32,
+ pub operation: String,
+ pub model_id: String,
+ #[serde(default)]
+ pub profile_id: String,
+ #[serde(default)]
+ pub engine: String,
+ pub pool_name: String,
+ pub machine_profile: String,
+ #[serde(default)]
+ pub item: Option<rmpv::Value>,
+ #[serde(default)]
+ pub payload_ref: Option<String>,
+ #[serde(default)]
+ pub output_types: Option<Vec<String>>,
+ #[serde(default)]
+ pub instruction: Option<String>,
+ #[serde(default)]
+ pub is_query: bool,
+ #[serde(default)]
+ pub options: Option<serde_json::Value>,
+ #[serde(default)]
+ pub query_item: Option<rmpv::Value>,
+ #[serde(default)]
+ pub query_payload_ref: Option<String>,
+ #[serde(default)]
+ pub score_items: Option<Vec<rmpv::Value>>,
+ #[serde(default)]
+ pub labels: Option<Vec<String>>,
+ #[serde(default)]
+ pub output_schema: Option<serde_json::Value>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub generate: Option<GenerateParams>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub routing_key: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub prompt_cache_key: Option<String>,
+ #[serde(default)]
+ pub bundle_config_hash: String,
+ #[serde(default)]
+ pub router_id: String,
+ pub reply_subject: String,
+ #[serde(default)]
+ pub timestamp: f64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub traceparent: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tracestate: Option<String>,
+ }
+
#[test]
fn test_stream_name() {
assert_eq!(stream_name("default"), "WORK_POOL_default");
assert_eq!(stream_name("eval-l4"), "WORK_POOL_eval-l4");
}
+ #[test]
+ fn test_canonical_stream_subjects_replaces_legacy_subject() {
+ let observed = vec!["sie.work.*.default".to_string()];
+ assert_eq!(
+ canonical_stream_subjects(observed, "sie.work.default.*.*.*"),
+ Some(vec!["sie.work.default.*.*.*".to_string()])
+ );
+ }
+
+ #[test]
+ fn test_canonical_stream_subjects_drops_extra_subjects() {
+ let observed = vec![
+ "sie.work.*.default".to_string(),
+ "sie.work.other.*.*.*".to_string(),
+ ];
+ assert_eq!(
+ canonical_stream_subjects(observed, "sie.work.default.*.*.*"),
+ Some(vec!["sie.work.default.*.*.*".to_string()])
+ );
+ }
+
+ #[test]
+ fn test_canonical_stream_subjects_noops_when_exact() {
+ let observed = vec!["sie.work.default.*.*.*".to_string()];
+ assert_eq!(
+ canonical_stream_subjects(observed, "sie.work.default.*.*.*"),
+ None
+ );
+ }
+
#[test]
fn test_normalize_model_id() {
assert_eq!(normalize_model_id("BAAI/bge-m3"), "BAAI__bge-m3");
@@ -2704,32 +2756,45 @@ mod tests {
#[test]
fn test_work_subject() {
assert_eq!(
- work_subject("BAAI/bge-m3", "default"),
- "sie.work.BAAI__bge-m3.default"
+ work_subject("default", "rtx6000", "default", "BAAI/bge-m3"),
+ "sie.work.default.rtx6000.default.BAAI__bge-m3"
);
assert_eq!(
- work_subject("my-model", "eval-l4"),
- "sie.work.my-model.eval-l4"
+ work_subject("eval-l4", "l4-spot", "sglang", "my-model"),
+ "sie.work.eval-l4.l4-spot.sglang.my-model"
+ );
+ assert_eq!(
+ work_subject_worker(
+ "default",
+ "rtx6000",
+ "sglang",
+ "Qwen/Qwen3.6-27B",
+ "worker-0.svc"
+ ),
+ "sie.work.default.rtx6000.sglang.Qwen__Qwen3_dot_6-27B.worker-0_dot_svc"
);
}
- /// Regression: model IDs containing `.` must produce exactly 4
- /// subject tokens (`sie`, `work`, `{normalized_model}`, `{pool}`) so
- /// the worker's consumer filter `sie.work.*.{pool}` matches them.
+ /// Regression: model IDs containing `.` must produce exactly 6
+ /// subject tokens (`sie`, `work`, `{pool}`, `{machine_profile}`,
+ /// `{bundle}`, `{normalized_model}`) so the worker's consumer filter
+ /// `sie.work.{pool}.{machine_profile}.{bundle}.*` matches them.
#[test]
fn test_work_subject_token_count_with_dotted_model() {
- let subj = work_subject("vidore/colqwen2.5-v0.2", "l4");
+ let subj = work_subject("default", "l4", "default", "vidore/colqwen2.5-v0.2");
let tokens: Vec<&str> = subj.split('.').collect();
assert_eq!(
tokens.len(),
- 4,
- "subject {subj} must have 4 tokens to match sie.work.*.{{pool}}"
+ 6,
+ "subject {subj} must have 6 tokens to match sie.work.{{pool}}.{{machine_profile}}.{{bundle}}.*"
);
assert_eq!(tokens[0], "sie");
assert_eq!(tokens[1], "work");
+ assert_eq!(tokens[2], "default");
assert_eq!(tokens[3], "l4");
- // Token[2] contains no '.' (it's the normalized model id).
- assert!(!tokens[2].contains('.'));
+ assert_eq!(tokens[4], "default");
+ // Token[5] contains no '.' (it's the normalized model id).
+ assert!(!tokens[5].contains('.'));
}
#[test]
diff --git a/packages/sie_gateway/src/queue/streaming.rs b/packages/sie_gateway/src/queue/streaming.rs
index ab5d86236..1ffb7f8c4 100644
--- a/packages/sie_gateway/src/queue/streaming.rs
+++ b/packages/sie_gateway/src/queue/streaming.rs
@@ -963,7 +963,7 @@ mod tests {
fn test_collector_latches_attempt_and_concatenates_text() {
let (tx, _rx) = oneshot::channel();
let mut collector =
- StreamCollector::new(tx, "test/model".to_string(), "_default".to_string());
+ StreamCollector::new(tx, "test/model".to_string(), "default".to_string());
assert_eq!(
collector.apply(_make_chunk("att-A", 0, "Hello", false)),
@@ -989,7 +989,7 @@ mod tests {
fn test_collector_drops_stale_attempt_chunks() {
let (tx, _rx) = oneshot::channel();
let mut collector =
- StreamCollector::new(tx, "test/model".to_string(), "_default".to_string());
+ StreamCollector::new(tx, "test/model".to_string(), "default".to_string());
assert_eq!(
collector.apply(_make_chunk("att-A", 0, "first", false)),
@@ -1034,7 +1034,7 @@ mod tests {
fn test_collector_without_tap_no_op() {
let (tx, _rx) = oneshot::channel();
let mut collector =
- StreamCollector::new(tx, "test/model".to_string(), "_default".to_string());
+ StreamCollector::new(tx, "test/model".to_string(), "default".to_string());
assert!(collector.chunk_tap.is_none());
// apply works exactly as before — no panic, no fan-out side
// effect (the broadcast send is gated by the `Some` arm).
@@ -1052,7 +1052,7 @@ mod tests {
async fn test_collector_tap_skips_stale_chunks() {
let (tx, _rx) = oneshot::channel();
let mut collector =
- StreamCollector::new(tx, "test/model".to_string(), "_default".to_string());
+ StreamCollector::new(tx, "test/model".to_string(), "default".to_string());
let mut tap = collector.install_chunk_tap();
collector.apply(_make_chunk("att-A", 0, "first", false));
@@ -1080,7 +1080,7 @@ mod tests {
fn test_collector_drops_duplicate_seq_redelivery() {
let (tx, _rx) = oneshot::channel();
let mut collector =
- StreamCollector::new(tx, "test/model".to_string(), "_default".to_string());
+ StreamCollector::new(tx, "test/model".to_string(), "default".to_string());
assert_eq!(
collector.apply(_make_chunk("att-A", 0, "Hello", false)),
@@ -1120,7 +1120,7 @@ mod tests {
fn test_streaming_gap_rejected_as_stream_error() {
let (tx, _rx) = oneshot::channel();
let mut collector =
- StreamCollector::new(tx, "test/model".to_string(), "_default".to_string());
+ StreamCollector::new(tx, "test/model".to_string(), "default".to_string());
assert_eq!(
collector.apply(_make_chunk("att-A", 1, "first", false)),
@@ -1154,7 +1154,7 @@ mod tests {
fn test_streaming_gap_check_does_not_apply_to_terminal() {
let (tx, _rx) = oneshot::channel();
let mut collector =
- StreamCollector::new(tx, "test/model".to_string(), "_default".to_string());
+ StreamCollector::new(tx, "test/model".to_string(), "default".to_string());
assert_eq!(
collector.apply(_make_chunk("att-A", 0, "hi", false)),
diff --git a/packages/sie_gateway/src/routing/hrw.rs b/packages/sie_gateway/src/routing/hrw.rs
index fa5ed365d..155a13da1 100644
--- a/packages/sie_gateway/src/routing/hrw.rs
+++ b/packages/sie_gateway/src/routing/hrw.rs
@@ -34,9 +34,10 @@ impl RingEntry {
}
}
-/// Immutable snapshot of the eligible workers for a single
-/// `(model, pool)`. Built by `WorkerRegistry::ring_snapshot_for` and
-/// cached on the registry's `ArcSwap` so per-request picks are lock-free.
+/// Immutable worker ring for one `(model, pool, machine_profile, bundle)` lane.
+/// `WorkerRegistry::ring_snapshot_for` rebuilds this per request from the
+/// registry snapshot; the broader worker view is what lives behind `ArcSwap`,
+/// so reads stay lock-free even though this lane ring is freshly constructed.
#[derive(Debug, Clone, Default)]
pub struct RingSnapshot {
pub entries: Vec<RingEntry>,
diff --git a/packages/sie_gateway/src/routing/mod.rs b/packages/sie_gateway/src/routing/mod.rs
index d2f071bd5..5d387800a 100644
--- a/packages/sie_gateway/src/routing/mod.rs
+++ b/packages/sie_gateway/src/routing/mod.rs
@@ -31,6 +31,16 @@ mod tests;
// remain available for code that needs the rest of the type surface.
pub use hrw::pick_worker;
+/// Whether a direct-dispatched generation request should skip the
+/// first-chunk timeout republish because the pool-fallback lane had no
+/// alternate worker at dispatch time.
+pub(crate) fn suppress_first_chunk_republish_for_lane(
+ was_direct_dispatched: bool,
+ pool_fallback_lane_worker_count: usize,
+) -> bool {
+ was_direct_dispatched && pool_fallback_lane_worker_count <= 1
+}
+
/// Environment variable that opts in to raw routing-key logging.
/// Default (unset / not "1") emits only the `xxh:` prefix.
///
diff --git a/packages/sie_gateway/src/routing/tests.rs b/packages/sie_gateway/src/routing/tests.rs
index 697209073..c4c64140e 100644
--- a/packages/sie_gateway/src/routing/tests.rs
+++ b/packages/sie_gateway/src/routing/tests.rs
@@ -14,7 +14,7 @@ use super::key::{
};
#[cfg(feature = "raw-routing-logs")]
use super::RAW_LOGGING_ENV;
-use super::{fmt_key_hash, log_raw_keys_enabled};
+use super::{fmt_key_hash, log_raw_keys_enabled, suppress_first_chunk_republish_for_lane};
fn workers(n: usize) -> RingSnapshot {
RingSnapshot::new((0..n).map(|i| format!("worker-{i}")))
@@ -123,6 +123,21 @@ fn empty_snapshot_returns_none() {
assert!(pick_worker(&snap, &key).is_none());
}
+#[test]
+fn first_chunk_republish_is_suppressed_for_single_direct_lane() {
+ assert!(suppress_first_chunk_republish_for_lane(true, 1));
+}
+
+#[test]
+fn first_chunk_republish_is_not_suppressed_when_lane_has_failover() {
+ assert!(!suppress_first_chunk_republish_for_lane(true, 2));
+}
+
+#[test]
+fn first_chunk_republish_guard_ignores_pool_fallback_dispatch() {
+ assert!(!suppress_first_chunk_republish_for_lane(false, 0));
+}
+
#[test]
fn none_keysource_returns_none_pick() {
let snap = workers(4);
diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rs
index 711b27026..30c88a668 100644
--- a/packages/sie_gateway/src/server.rs
+++ b/packages/sie_gateway/src/server.rs
@@ -133,17 +133,21 @@ pub(crate) async fn metrics_handler(
.collect();
metrics::update_worker_metrics(&snapshots);
- // Clear PENDING_DEMAND only for WorkerGroups that now have healthy workers.
- let healthy_worker_groups: std::collections::HashSet<(String, String)> = snapshots
+ // Clear PENDING_DEMAND only for queue lanes that now have healthy workers.
+ let healthy_worker_groups: std::collections::HashSet<(String, String, String)> = snapshots
.iter()
- .filter(|w| w.healthy && !w.machine_profile.is_empty())
+ .filter(|w| w.healthy && !w.pool_name.is_empty() && !w.machine_profile.is_empty())
.map(|w| {
let bundle = if w.bundle.is_empty() {
"default"
} else {
w.bundle.as_str()
};
- (w.machine_profile.to_lowercase(), bundle.to_lowercase())
+ (
+ w.pool_name.to_lowercase(),
+ w.machine_profile.to_lowercase(),
+ bundle.to_lowercase(),
+ )
})
.collect();
metrics::clear_fulfilled_demand(&healthy_worker_groups, &state.demand_tracker);
diff --git a/packages/sie_gateway/src/state/demand_tracker.rs b/packages/sie_gateway/src/state/demand_tracker.rs
index 8cc6457e1..4be9132ab 100644
--- a/packages/sie_gateway/src/state/demand_tracker.rs
+++ b/packages/sie_gateway/src/state/demand_tracker.rs
@@ -1,5 +1,6 @@
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
@@ -9,12 +10,16 @@ use crate::metrics;
const DEMAND_EXPIRY_SECS: u64 = 120;
-/// Tracks pending demand per (gpu, bundle) with refreshable expiry deadlines.
+type DemandKey = (String, String, String);
+type DemandEntry = (String, String, String, Arc<Notify>, Arc<AtomicU64>);
+
+/// Tracks pending demand per (pool, machine_profile, bundle) with refreshable expiry deadlines.
/// Each active demand entry has a background task that clears the metric
/// after 120s of inactivity. Calling `record` resets the timer.
pub struct DemandTracker {
- /// Map from (gpu_lowercase, bundle_lowercase) to (original_gpu, original_bundle, notify).
- entries: DashMap<(String, String), (String, String, Arc<Notify>)>,
+ /// Map from (pool_lowercase, machine_profile_lowercase, bundle_lowercase) to
+ /// (original_pool, original_machine_profile, original_bundle, notify, generation).
+ entries: DashMap<DemandKey, DemandEntry>,
}
impl Default for DemandTracker {
@@ -30,53 +35,97 @@ impl DemandTracker {
}
}
- /// Record pending demand for a (gpu, bundle) pair.
+ /// Record pending demand for a (pool, machine_profile, bundle) lane.
/// Sets the PENDING_DEMAND gauge to 1.0 and starts/refreshes
/// the 120s auto-expiry timer.
- pub fn record(self: &Arc<Self>, gpu: &str, bundle: &str) {
- let key = (gpu.to_lowercase(), bundle.to_lowercase());
+ pub fn record(self: &Arc<Self>, pool: &str, machine_profile: &str, bundle: &str) {
+ let key = (
+ pool.to_lowercase(),
+ machine_profile.to_lowercase(),
+ bundle.to_lowercase(),
+ );
// Use entry() API for atomic get-or-insert to avoid TOCTOU race
match self.entries.entry(key.clone()) {
Entry::Occupied(entry) => {
- let (ref orig_gpu, ref orig_bundle, ref notify) = *entry.get();
+ let (
+ ref orig_pool,
+ ref orig_machine_profile,
+ ref orig_bundle,
+ ref notify,
+ ref generation,
+ ) = *entry.get();
// Set gauge with the original-case labels to avoid creating duplicate series
metrics::PENDING_DEMAND
- .with_label_values(&[orig_gpu, orig_bundle])
+ .with_label_values(&[orig_pool, orig_machine_profile, orig_bundle])
.set(1.0);
+ generation.fetch_add(1, Ordering::AcqRel);
notify.notify_one();
}
Entry::Vacant(entry) => {
let notify = Arc::new(Notify::new());
- entry.insert((gpu.to_string(), bundle.to_string(), Arc::clone(&notify)));
+ let generation = Arc::new(AtomicU64::new(0));
+ entry.insert((
+ pool.to_string(),
+ machine_profile.to_string(),
+ bundle.to_string(),
+ Arc::clone(&notify),
+ Arc::clone(&generation),
+ ));
// Set gauge with the canonical label casing (first caller defines it)
metrics::PENDING_DEMAND
- .with_label_values(&[gpu, bundle])
+ .with_label_values(&[pool, machine_profile, bundle])
.set(1.0);
- let gpu_owned = gpu.to_string();
+ let pool_owned = pool.to_string();
+ let machine_profile_owned = machine_profile.to_string();
let bundle_owned = bundle.to_string();
let tracker = Arc::clone(self);
tokio::spawn(async move {
- let key = (gpu_owned.to_lowercase(), bundle_owned.to_lowercase());
+ let key = (
+ pool_owned.to_lowercase(),
+ machine_profile_owned.to_lowercase(),
+ bundle_owned.to_lowercase(),
+ );
loop {
- if !tracker.entries.contains_key(&key) {
+ let is_current_entry = tracker
+ .entries
+ .get(&key)
+ .map(|entry| Arc::ptr_eq(&entry.4, &generation))
+ .unwrap_or(false);
+ if !is_current_entry {
return;
}
+ let observed_generation = generation.load(Ordering::Acquire);
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(DEMAND_EXPIRY_SECS)) => {
- metrics::PENDING_DEMAND
- .with_label_values(&[&gpu_owned, &bundle_owned])
- .set(0.0);
- tracker.entries.remove(&key);
- info!(
- gpu = %gpu_owned,
- bundle = %bundle_owned,
- "pending demand expired (no requests for 120s)"
- );
- return;
+ let removed = tracker.entries.remove_if(&key, |_, entry| {
+ Arc::ptr_eq(&entry.4, &generation)
+ && entry.4.load(Ordering::Acquire) == observed_generation
+ });
+ if let Some((_, (orig_pool, orig_machine_profile, orig_bundle, _, _))) = removed {
+ metrics::PENDING_DEMAND
+ .with_label_values(&[&orig_pool, &orig_machine_profile, &orig_bundle])
+ .set(0.0);
+ info!(
+ pool = %orig_pool,
+ machine_profile = %orig_machine_profile,
+ bundle = %orig_bundle,
+ "pending demand expired (no requests for 120s)"
+ );
+ return;
+ }
+ let is_current_entry = tracker
+ .entries
+ .get(&key)
+ .map(|entry| Arc::ptr_eq(&entry.4, &generation))
+ .unwrap_or(false);
+ if !is_current_entry {
+ return;
+ }
+ continue;
}
_ = notify.notified() => {
continue;
@@ -88,19 +137,25 @@ impl DemandTracker {
}
}
- /// Explicitly clear demand for a (gpu, bundle) pair.
+ /// Explicitly clear demand for a (pool, machine_profile, bundle) lane.
/// Removes the entry and zeros the gauge.
- pub fn clear(&self, gpu: &str, bundle: &str) {
- let key = (gpu.to_lowercase(), bundle.to_lowercase());
- if let Some((_, (orig_gpu, orig_bundle, notify))) = self.entries.remove(&key) {
+ pub fn clear(&self, pool: &str, machine_profile: &str, bundle: &str) {
+ let key = (
+ pool.to_lowercase(),
+ machine_profile.to_lowercase(),
+ bundle.to_lowercase(),
+ );
+ if let Some((_, (orig_pool, orig_machine_profile, orig_bundle, notify, _))) =
+ self.entries.remove(&key)
+ {
notify.notify_one();
metrics::PENDING_DEMAND
- .with_label_values(&[&orig_gpu, &orig_bundle])
+ .with_label_values(&[&orig_pool, &orig_machine_profile, &orig_bundle])
.set(0.0);
} else {
// No tracked entry, but clear the gauge anyway with the provided values
metrics::PENDING_DEMAND
- .with_label_values(&[gpu, bundle])
+ .with_label_values(&[pool, machine_profile, bundle])
.set(0.0);
}
}
@@ -114,56 +169,90 @@ mod tests {
async fn test_record_sets_demand_gauge() {
let _ = &*metrics::REGISTRY;
let tracker = Arc::new(DemandTracker::new());
- tracker.record("l4-spot", "default");
+ tracker.record("default", "l4-spot", "default");
let val = metrics::PENDING_DEMAND
- .with_label_values(&["l4-spot", "default"])
+ .with_label_values(&["default", "l4-spot", "default"])
.get();
assert!((val - 1.0).abs() < f64::EPSILON);
- tracker.clear("l4-spot", "default");
+ tracker.clear("default", "l4-spot", "default");
}
#[tokio::test]
async fn test_demand_entry_exists_after_record() {
let _ = &*metrics::REGISTRY;
let tracker = Arc::new(DemandTracker::new());
- tracker.record("test-gpu-expire", "test-bundle-expire");
+ tracker.record("test-pool-expire", "test-gpu-expire", "test-bundle-expire");
assert!(tracker.entries.contains_key(&(
+ "test-pool-expire".to_string(),
"test-gpu-expire".to_string(),
"test-bundle-expire".to_string()
)));
- tracker.clear("test-gpu-expire", "test-bundle-expire");
+ tracker.clear("test-pool-expire", "test-gpu-expire", "test-bundle-expire");
}
#[tokio::test]
async fn test_record_refreshes_existing_timer() {
let _ = &*metrics::REGISTRY;
let tracker = Arc::new(DemandTracker::new());
- tracker.record("l4-refresh", "default");
+ tracker.record("default", "l4-refresh", "default");
// Record again -- should not create a second entry
- tracker.record("l4-refresh", "default");
- assert!(tracker
- .entries
- .contains_key(&("l4-refresh".to_string(), "default".to_string())));
+ tracker.record("default", "l4-refresh", "default");
+ assert!(tracker.entries.contains_key(&(
+ "default".to_string(),
+ "l4-refresh".to_string(),
+ "default".to_string()
+ )));
let val = metrics::PENDING_DEMAND
- .with_label_values(&["l4-refresh", "default"])
+ .with_label_values(&["default", "l4-refresh", "default"])
.get();
assert!((val - 1.0).abs() < f64::EPSILON);
- tracker.clear("l4-refresh", "default");
+ tracker.clear("default", "l4-refresh", "default");
+ }
+
+ #[tokio::test]
+ async fn test_record_refreshes_expiry_generation() {
+ let _ = &*metrics::REGISTRY;
+ let tracker = Arc::new(DemandTracker::new());
+ tracker.record("default", "l4-generation", "default");
+ let key = (
+ "default".to_string(),
+ "l4-generation".to_string(),
+ "default".to_string(),
+ );
+ let before = tracker
+ .entries
+ .get(&key)
+ .expect("entry should exist")
+ .4
+ .load(Ordering::Acquire);
+
+ tracker.record("default", "l4-generation", "default");
+
+ let after = tracker
+ .entries
+ .get(&key)
+ .expect("entry should still exist")
+ .4
+ .load(Ordering::Acquire);
+ assert_eq!(after, before + 1);
+ tracker.clear("default", "l4-generation", "default");
}
#[tokio::test]
async fn test_clear_removes_entry_and_zeros_gauge() {
let _ = &*metrics::REGISTRY;
let tracker = Arc::new(DemandTracker::new());
- tracker.record("l4-clear", "default");
- tracker.clear("l4-clear", "default");
+ tracker.record("default", "l4-clear", "default");
+ tracker.clear("default", "l4-clear", "default");
let val = metrics::PENDING_DEMAND
- .with_label_values(&["l4-clear", "default"])
+ .with_label_values(&["default", "l4-clear", "default"])
.get();
assert!((val - 0.0).abs() < f64::EPSILON);
- assert!(!tracker
- .entries
- .contains_key(&("l4-clear".to_string(), "default".to_string())));
+ assert!(!tracker.entries.contains_key(&(
+ "default".to_string(),
+ "l4-clear".to_string(),
+ "default".to_string()
+ )));
}
#[tokio::test]
@@ -171,23 +260,23 @@ mod tests {
let _ = &*metrics::REGISTRY;
let tracker = Arc::new(DemandTracker::new());
// Should not panic
- tracker.clear("nonexistent", "nonexistent");
+ tracker.clear("nonexistent", "nonexistent", "nonexistent");
}
#[tokio::test]
async fn test_case_insensitive_key_matching() {
let _ = &*metrics::REGISTRY;
let tracker = Arc::new(DemandTracker::new());
- tracker.record("L4-Spot", "Premium");
+ tracker.record("Default", "L4-Spot", "Premium");
// Second record with same case should refresh, not create new
- tracker.record("L4-Spot", "Premium");
+ tracker.record("Default", "L4-Spot", "Premium");
assert_eq!(tracker.entries.len(), 1);
// Gauge was set with the original case labels
let val = metrics::PENDING_DEMAND
- .with_label_values(&["L4-Spot", "Premium"])
+ .with_label_values(&["Default", "L4-Spot", "Premium"])
.get();
assert!((val - 1.0).abs() < f64::EPSILON);
- tracker.clear("L4-SPOT", "PREMIUM");
+ tracker.clear("DEFAULT", "L4-SPOT", "PREMIUM");
assert_eq!(tracker.entries.len(), 0);
}
@@ -197,16 +286,16 @@ mod tests {
let tracker = Arc::new(DemandTracker::new());
// Record demand
- tracker.record("l4-timer", "default-timer");
+ tracker.record("default", "l4-timer", "default-timer");
let val = metrics::PENDING_DEMAND
- .with_label_values(&["l4-timer", "default-timer"])
+ .with_label_values(&["default", "l4-timer", "default-timer"])
.get();
assert!((val - 1.0).abs() < f64::EPSILON);
// Advance 100s (< 120s expiry), then refresh.
tokio::time::advance(Duration::from_secs(100)).await;
tokio::task::yield_now().await;
- tracker.record("l4-timer", "default-timer");
+ tracker.record("default", "l4-timer", "default-timer");
// Let the spawned task process the notify and loop back to start
// a new sleep(120s) before we advance time further.
@@ -220,7 +309,7 @@ mod tests {
// Gauge should STILL be 1.0 because the timer was refreshed
let val = metrics::PENDING_DEMAND
- .with_label_values(&["l4-timer", "default-timer"])
+ .with_label_values(&["default", "l4-timer", "default-timer"])
.get();
assert!(
(val - 1.0).abs() < f64::EPSILON,
@@ -234,7 +323,7 @@ mod tests {
// Gauge should now be 0.0 (expired)
let val = metrics::PENDING_DEMAND
- .with_label_values(&["l4-timer", "default-timer"])
+ .with_label_values(&["default", "l4-timer", "default-timer"])
.get();
assert!(
(val - 0.0).abs() < f64::EPSILON,
@@ -246,14 +335,18 @@ mod tests {
async fn test_multiple_gpu_bundle_pairs_independent() {
let _ = &*metrics::REGISTRY;
let tracker = Arc::new(DemandTracker::new());
- tracker.record("l4-multi", "default");
- tracker.record("a100-multi", "premium");
+ tracker.record("default", "l4-multi", "default");
+ tracker.record("tenant-a", "l4-multi", "default");
+ tracker.record("default", "a100-multi", "premium");
+ assert_eq!(tracker.entries.len(), 3);
+ tracker.clear("default", "l4-multi", "default");
assert_eq!(tracker.entries.len(), 2);
- tracker.clear("l4-multi", "default");
- assert_eq!(tracker.entries.len(), 1);
- assert!(tracker
- .entries
- .contains_key(&("a100-multi".to_string(), "premium".to_string())));
- tracker.clear("a100-multi", "premium");
+ assert!(tracker.entries.contains_key(&(
+ "tenant-a".to_string(),
+ "l4-multi".to_string(),
+ "default".to_string()
+ )));
+ tracker.clear("tenant-a", "l4-multi", "default");
+ tracker.clear("default", "a100-multi", "premium");
}
}
diff --git a/packages/sie_gateway/src/state/pool_manager.rs b/packages/sie_gateway/src/state/pool_manager.rs
index 63c8492a6..75d4aa250 100644
--- a/packages/sie_gateway/src/state/pool_manager.rs
+++ b/packages/sie_gateway/src/state/pool_manager.rs
@@ -59,15 +59,6 @@ pub struct PoolAdmissionStatus {
pub assigned_count: usize,
}
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct PoolAdmissionSummary {
- pub capped_profiles: Vec<String>,
- pub zero_cap_profiles: Vec<String>,
- pub assigned_count: usize,
- pub total_assigned_count: usize,
- pub has_uncapped_profiles: bool,
-}
-
pub struct PoolManager {
pools: RwLock<HashMap<String, Pool>>,
lease_duration_s: f64,
@@ -322,12 +313,13 @@ impl PoolManager {
pools.get(name).cloned()
}
- pub async fn capped_profile_status(
+ pub async fn capped_lane_status(
&self,
pool_name: &str,
- gpu: &str,
+ machine_profile: &str,
+ bundle: &str,
) -> Option<PoolAdmissionStatus> {
- if gpu.is_empty() {
+ if machine_profile.is_empty() {
return None;
}
@@ -337,13 +329,14 @@ impl PoolManager {
.spec
.gpu_caps
.iter()
- .find(|(profile, _)| profile.eq_ignore_ascii_case(gpu))
+ .find(|(profile, _)| profile.eq_ignore_ascii_case(machine_profile))
.map(|(_, cap)| *cap)?;
let assigned_count = pool
.status
.assigned_workers
.iter()
- .filter(|worker| worker.gpu.eq_ignore_ascii_case(gpu))
+ .filter(|worker| worker.gpu.eq_ignore_ascii_case(machine_profile))
+ .filter(|worker| worker.bundle.eq_ignore_ascii_case(bundle))
.count();
Some(PoolAdmissionStatus {
@@ -352,55 +345,75 @@ impl PoolManager {
})
}
- pub async fn capped_pool_status(&self, pool_name: &str) -> Option<PoolAdmissionSummary> {
- let pools = self.pools.read().await;
- let pool = pools.get(pool_name)?;
- if pool.spec.gpu_caps.is_empty() {
+ /// Return the assigned worker names for a capped concrete lane.
+ ///
+ /// `None` means the pool/profile is uncapped, so callers should not apply
+ /// an admission filter. `Some(empty)` means admission is enabled for this
+ /// profile but no worker is currently admitted. This mirrors the
+ /// worker-side pool-admission gate: named pools with missing status fail
+ /// closed, while the default pool remains fail-open.
+ pub async fn admitted_worker_names_for_capped_lane(
+ &self,
+ pool_name: &str,
+ machine_profile: &str,
+ bundle: &str,
+ ) -> Option<HashSet<String>> {
+ if machine_profile.trim().is_empty() {
return None;
}
- let caps_by_profile: HashMap<String, u32> = pool
- .spec
- .gpu_caps
- .iter()
- .map(|(profile, cap)| (profile.to_lowercase(), *cap))
- .collect();
- let mut capped_profiles: Vec<String> = pool.spec.gpu_caps.keys().cloned().collect();
- capped_profiles.sort();
- let mut zero_cap_profiles: Vec<String> = pool
+ let pools = self.pools.read().await;
+ let Some(pool) = pools.get(pool_name) else {
+ return if pool_name.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {
+ None
+ } else {
+ Some(HashSet::new())
+ };
+ };
+ let cap = pool
.spec
.gpu_caps
.iter()
- .filter_map(|(profile, cap)| {
- if *cap == 0 {
- Some(profile.clone())
- } else {
- None
- }
- })
- .collect();
- zero_cap_profiles.sort();
+ .find(|(profile, _)| profile.eq_ignore_ascii_case(machine_profile))
+ .map(|(_, cap)| *cap)?;
+ if cap == 0 {
+ return Some(HashSet::new());
+ }
- let has_uncapped_profiles = pool
- .spec
- .gpus
- .keys()
- .any(|profile| !caps_by_profile.contains_key(&profile.to_lowercase()));
- let assigned_count = pool
- .status
- .assigned_workers
- .iter()
- .filter(|worker| caps_by_profile.contains_key(&worker.gpu.to_lowercase()))
- .count();
- let total_assigned_count = pool.status.assigned_workers.len();
+ Some(
+ pool.status
+ .assigned_workers
+ .iter()
+ .filter(|worker| worker.gpu.eq_ignore_ascii_case(machine_profile))
+ .filter(|worker| worker.bundle.eq_ignore_ascii_case(bundle))
+ .map(|worker| worker.name.clone())
+ .collect(),
+ )
+ }
- Some(PoolAdmissionSummary {
- capped_profiles,
- zero_cap_profiles,
- assigned_count,
- total_assigned_count,
- has_uncapped_profiles,
- })
+ /// Return the pool's only configured machine profile, if the spec is
+ /// unambiguous across both requirements (`gpus`) and admission caps
+ /// (`gpu_caps`). Used by cold queue routing when a caller pins only a
+ /// pool: the NATS subject still needs a concrete machine-profile token so
+ /// KEDA can observe `pending_demand{pool,machine_profile,bundle}`.
+ pub async fn single_machine_profile_for_pool(&self, pool_name: &str) -> Option<String> {
+ let pools = self.pools.read().await;
+ let pool = pools.get(pool_name)?;
+ let mut profiles: Vec<String> = Vec::new();
+ for profile in pool.spec.gpus.keys().chain(pool.spec.gpu_caps.keys()) {
+ if profiles
+ .iter()
+ .any(|existing| existing.eq_ignore_ascii_case(profile))
+ {
+ continue;
+ }
+ profiles.push(profile.to_lowercase());
+ }
+ if profiles.len() == 1 {
+ profiles.pop()
+ } else {
+ None
+ }
}
pub async fn list_pools(&self) -> Vec<Pool> {
@@ -527,6 +540,7 @@ impl PoolManager {
name: w.0.clone(),
url: w.1.clone(),
gpu: w.2.clone(),
+ bundle: w.3.clone(),
});
}
}
@@ -716,10 +730,7 @@ fn worker_consumes_pool(worker_pool: &str, pool_name: &str) -> bool {
}
fn normalize_pool_name(name: &str) -> String {
- match name.trim().to_lowercase().as_str() {
- "" | "_default" => DEFAULT_POOL_NAME.to_string(),
- other => other.to_string(),
- }
+ name.trim().to_ascii_lowercase()
}
#[cfg(test)]
@@ -1065,7 +1076,7 @@ mod tests {
}
#[tokio::test]
- async fn test_capped_profile_status_reports_cap_and_assigned_count() {
+ async fn test_capped_lane_status_reports_cap_and_assigned_count() {
let pm = PoolManager::new(vec!["l4-spot".to_string()]);
let mut gpus = HashMap::new();
@@ -1085,68 +1096,123 @@ mod tests {
)];
pm.assign_workers("test", &workers).await;
- let status = pm
- .capped_profile_status("test", "L4-SPOT")
+ let lane_status = pm
+ .capped_lane_status("test", "L4-SPOT", "default")
+ .await
+ .expect("lane should be capped");
+ assert_eq!(lane_status.cap, 2);
+ assert_eq!(lane_status.assigned_count, 1);
+ assert!(pm
+ .capped_lane_status("test", "a100", "default")
+ .await
+ .is_none());
+ }
+
+ #[tokio::test]
+ async fn test_admitted_worker_names_for_capped_lane_filters_assignment() {
+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);
+
+ let mut gpus = HashMap::new();
+ gpus.insert("l4-spot".to_string(), 0);
+ let mut gpu_caps = HashMap::new();
+ gpu_caps.insert("l4-spot".to_string(), 1);
+ pm.create_pool_with_caps("test", gpus, gpu_caps, None, None, 0)
+ .await
+ .unwrap();
+
+ let workers = vec![
+ worker_in_pool("w1", "http://w1:8080", "l4-spot", "default", "test"),
+ worker_in_pool("w2", "http://w2:8080", "l4-spot", "default", "test"),
+ ];
+ pm.assign_workers("test", &workers).await;
+
+ let admitted = pm
+ .admitted_worker_names_for_capped_lane("test", "L4-SPOT", "default")
.await
.expect("profile should be capped");
- assert_eq!(status.cap, 2);
- assert_eq!(status.assigned_count, 1);
- assert!(pm.capped_profile_status("test", "a100").await.is_none());
+ assert_eq!(admitted, HashSet::from(["w1".to_string()]));
}
#[tokio::test]
- async fn test_capped_pool_status_reports_aggregate_admission() {
- let pm = PoolManager::new(vec!["l4-spot".to_string(), "a100".to_string()]);
+ async fn test_admitted_worker_names_for_capped_lane_respects_bundle() {
+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);
let mut gpus = HashMap::new();
gpus.insert("l4-spot".to_string(), 0);
- gpus.insert("a100".to_string(), 0);
let mut gpu_caps = HashMap::new();
- gpu_caps.insert("l4-spot".to_string(), 0);
+ gpu_caps.insert("l4-spot".to_string(), 2);
pm.create_pool_with_caps("test", gpus, gpu_caps, None, None, 0)
.await
.unwrap();
- let summary = pm
- .capped_pool_status("test")
+ let workers = vec![
+ worker_in_pool("w1", "http://w1:8080", "l4-spot", "default", "test"),
+ worker_in_pool("w2", "http://w2:8080", "l4-spot", "sglang", "test"),
+ ];
+ pm.assign_workers("test", &workers).await;
+
+ let admitted = pm
+ .admitted_worker_names_for_capped_lane("test", "l4-spot", "default")
.await
- .expect("pool should have caps");
- assert_eq!(summary.capped_profiles, vec!["l4-spot"]);
- assert_eq!(summary.zero_cap_profiles, vec!["l4-spot"]);
- assert_eq!(summary.assigned_count, 0);
- assert_eq!(summary.total_assigned_count, 0);
- assert!(summary.has_uncapped_profiles);
+ .expect("profile should be capped");
+ assert_eq!(admitted, HashSet::from(["w1".to_string()]));
+
+ let default_status = pm
+ .capped_lane_status("test", "l4-spot", "default")
+ .await
+ .expect("default lane should be capped");
+ assert_eq!(default_status.assigned_count, 1);
+ let missing_status = pm
+ .capped_lane_status("test", "l4-spot", "rerank")
+ .await
+ .expect("missing bundle lane should still be capped");
+ assert_eq!(missing_status.assigned_count, 0);
}
#[tokio::test]
- async fn test_capped_pool_status_reports_total_assigned_workers() {
+ async fn test_admitted_worker_names_for_uncapped_lane_returns_none() {
let pm = PoolManager::new(vec!["l4-spot".to_string(), "a100".to_string()]);
let mut gpus = HashMap::new();
gpus.insert("l4-spot".to_string(), 0);
- gpus.insert("a100".to_string(), 0);
let mut gpu_caps = HashMap::new();
- gpu_caps.insert("l4-spot".to_string(), 1);
+ gpu_caps.insert("a100".to_string(), 1);
pm.create_pool_with_caps("test", gpus, gpu_caps, None, None, 0)
.await
.unwrap();
- let workers = vec![worker_in_pool(
- "w1",
- "http://w1:8080",
- "a100",
- "default",
- "test",
- )];
- pm.assign_workers("test", &workers).await;
+ assert!(pm
+ .admitted_worker_names_for_capped_lane("test", "l4-spot", "default")
+ .await
+ .is_none());
+ }
- let summary = pm
- .capped_pool_status("test")
+ #[tokio::test]
+ async fn test_admitted_worker_names_for_zero_cap_and_missing_named_pool_fail_closed() {
+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);
+
+ let mut gpus = HashMap::new();
+ gpus.insert("l4-spot".to_string(), 0);
+ let mut gpu_caps = HashMap::new();
+ gpu_caps.insert("l4-spot".to_string(), 0);
+ pm.create_pool_with_caps("test", gpus, gpu_caps, None, None, 0)
.await
- .expect("pool should have caps");
- assert_eq!(summary.assigned_count, 0);
- assert_eq!(summary.total_assigned_count, 1);
- assert!(summary.has_uncapped_profiles);
+ .unwrap();
+
+ assert_eq!(
+ pm.admitted_worker_names_for_capped_lane("test", "l4-spot", "default")
+ .await,
+ Some(HashSet::new())
+ );
+ assert_eq!(
+ pm.admitted_worker_names_for_capped_lane("missing", "l4-spot", "default")
+ .await,
+ Some(HashSet::new())
+ );
+ assert!(pm
+ .admitted_worker_names_for_capped_lane(DEFAULT_POOL_NAME, "l4-spot", "default")
+ .await
+ .is_none());
}
#[tokio::test]
@@ -1324,6 +1390,29 @@ mod tests {
assert_eq!(active.status.assigned_workers.len(), 1);
}
+ #[tokio::test]
+ async fn test_default_pool_requires_explicit_worker_pool() {
+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);
+
+ pm.create_default_pool().await;
+
+ let workers = vec![
+ worker_in_pool("empty", "http://w1:8080", "l4-spot", "default", ""),
+ worker_in_pool(
+ "_default",
+ "http://w2:8080",
+ "l4-spot",
+ "default",
+ "_default",
+ ),
+ ];
+ pm.assign_workers(DEFAULT_POOL_NAME, &workers).await;
+
+ let pool = pm.get_pool(DEFAULT_POOL_NAME).await.unwrap();
+ assert_eq!(pool.status.state, PoolState::Pending);
+ assert!(pool.status.assigned_workers.is_empty());
+ }
+
#[tokio::test]
async fn test_restore_from_k8s_no_backend() {
let pm = PoolManager::new(vec!["l4-spot".to_string()]);
@@ -1410,6 +1499,7 @@ mod tests {
name: "worker-a".to_string(),
url: "http://worker-a:8080".to_string(),
gpu: "l4-spot".to_string(),
+ bundle: "default".to_string(),
}];
pm.apply_remote_pool(remote).await;
diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rs
index 42c241029..6b1c0833c 100644
--- a/packages/sie_gateway/src/state/worker_registry.rs
+++ b/packages/sie_gateway/src/state/worker_registry.rs
@@ -1,4 +1,4 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -69,6 +69,18 @@ pub type OnWorkerHealthy = Arc<dyn Fn(&WorkerState) + Send + Sync>;
/// ring snapshots and (optionally) to log a structured trace.
pub type OnWorkerDegraded = Arc<dyn Fn(&WorkerState) + Send + Sync>;
+/// Concrete queue lane resolved from the worker registry.
+///
+/// `pool_name` is the logical tenant/capacity pool. `machine_profile`
+/// is the hardware lane that must be embedded in the NATS subject so
+/// non-interchangeable worker groups sharing the same pool do not
+/// overlap.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct QueueRoute {
+ pub pool_name: String,
+ pub machine_profile: String,
+}
+
/// Pre-computed snapshot of healthy workers, indexed by bundle.
/// Rebuilt on every worker state change and swapped atomically via Arc.
#[derive(Default)]
@@ -319,11 +331,12 @@ impl WorkerRegistry {
}
}
- /// Dispatch-eligible workers for a `(model, pool)` —
- /// healthy, not saturated, with `model` in `loaded_models` and
- /// `pool_name` matching `pool`. Pool match is case-insensitive
- /// to mirror [`resolve_queue_pool_matching`]. Used by the proxy
- /// to build per-request HRW snapshots.
+ /// Dispatch-eligible workers for a `(model, pool, machine_profile, bundle)` —
+ /// healthy, not saturated, with `model` in `loaded_models`, a matching
+ /// bundle config hash, and the full queue lane matching. Pool /
+ /// machine-profile / bundle matches are case-insensitive to mirror
+ /// [`resolve_queue_route_matching`]. Used by the proxy to build
+ /// per-request HRW snapshots.
///
/// A `model:profile` request is matched against the **base** model
/// id: workers advertise only base model names in `loaded_models`
@@ -333,24 +346,89 @@ impl WorkerRegistry {
/// eligible worker and would always fall through to the pool subject
/// (mislabelled `unhealthy_skipped`). HF model ids never contain `:`,
/// so the suffix split is unambiguous.
- pub fn dispatch_workers_for(&self, model: &str, pool: &str) -> Vec<WorkerState> {
+ #[cfg(test)]
+ pub fn dispatch_workers_for(
+ &self,
+ model: &str,
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ bundle_config_hash: &str,
+ ) -> Vec<WorkerState> {
+ self.dispatch_workers_for_matching(
+ model,
+ pool,
+ machine_profile,
+ bundle,
+ bundle_config_hash,
+ None,
+ )
+ }
+
+ fn dispatch_workers_for_matching(
+ &self,
+ model: &str,
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ bundle_config_hash: &str,
+ admitted_worker_names: Option<&HashSet<String>>,
+ ) -> Vec<WorkerState> {
let base_model = base_model_id(model);
let snap = self.snapshot.load();
snap.all_healthy
.iter()
.filter(|w| {
!w.saturated
+ && worker_allowed_by_admission(w, admitted_worker_names)
+ && !w.machine_profile.is_empty()
&& w.pool_name.eq_ignore_ascii_case(pool)
+ && w.machine_profile.eq_ignore_ascii_case(machine_profile)
+ && w.bundle.eq_ignore_ascii_case(bundle)
+ && bundle_config_hash_matches(&w.bundle_config_hash, bundle_config_hash)
&& w.models.iter().any(|m| m.eq_ignore_ascii_case(base_model))
})
.cloned()
.collect()
}
- /// Build a [`RingSnapshot`] for the given `(model, pool)`. Uses
+ /// Workers that can receive a pool fallback for this concrete lane.
+ ///
+ /// Unlike [`Self::dispatch_workers_for`], this intentionally does not
+ /// require `model` to already be present in `loaded_models`: the pool
+ /// fallback path can land on a healthy same-lane worker that lazy-loads
+ /// the model. This count is used only to decide whether first-chunk
+ /// failover has an alternate consumer.
+ pub fn pool_fallback_lane_worker_count(
+ &self,
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ bundle_config_hash: &str,
+ admitted_worker_names: Option<&HashSet<String>>,
+ ) -> usize {
+ let snap = self.snapshot.load();
+ let bundle_lower = bundle.to_lowercase();
+ let Some(candidates) = snap.by_bundle.get(&bundle_lower) else {
+ return 0;
+ };
+ candidates
+ .iter()
+ .filter(|w| {
+ !w.saturated
+ && worker_allowed_by_admission(w, admitted_worker_names)
+ && !w.machine_profile.is_empty()
+ && w.pool_name.eq_ignore_ascii_case(pool)
+ && w.machine_profile.eq_ignore_ascii_case(machine_profile)
+ && bundle_config_hash_matches(&w.bundle_config_hash, bundle_config_hash)
+ })
+ .count()
+ }
+
+ /// Build a [`RingSnapshot`] for the given concrete queue lane. Uses
/// the worker `name` (direct-dispatch worker_id convention) as the ring
/// key; the same name shows up on the per-worker NATS subject
- /// `sie.work.{model}.{pool}.{worker_id}`.
+ /// `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`.
///
/// The output is sorted by worker name so HRW tie-breaks are
/// identical across gateway replicas regardless of the upstream
@@ -364,8 +442,61 @@ impl WorkerRegistry {
/// choice is deterministic across replicas, and warn (rate-limited)
/// that an operator misconfiguration was observed. The wire-level
/// subject format is unchanged — only which workers enter the ring.
- pub fn ring_snapshot_for(&self, model: &str, pool: &str) -> RingSnapshot {
- let mut workers = self.dispatch_workers_for(model, pool);
+ #[cfg(test)]
+ pub fn ring_snapshot_for(
+ &self,
+ model: &str,
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ bundle_config_hash: &str,
+ ) -> RingSnapshot {
+ self.ring_snapshot_for_matching(
+ model,
+ pool,
+ machine_profile,
+ bundle,
+ bundle_config_hash,
+ None,
+ )
+ }
+
+ pub fn ring_snapshot_for_admitted(
+ &self,
+ model: &str,
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ bundle_config_hash: &str,
+ admitted_worker_names: Option<&HashSet<String>>,
+ ) -> RingSnapshot {
+ self.ring_snapshot_for_matching(
+ model,
+ pool,
+ machine_profile,
+ bundle,
+ bundle_config_hash,
+ admitted_worker_names,
+ )
+ }
+
+ fn ring_snapshot_for_matching(
+ &self,
+ model: &str,
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ bundle_config_hash: &str,
+ admitted_worker_names: Option<&HashSet<String>>,
+ ) -> RingSnapshot {
+ let mut workers = self.dispatch_workers_for_matching(
+ model,
+ pool,
+ machine_profile,
+ bundle,
+ bundle_config_hash,
+ admitted_worker_names,
+ );
// Sort by `(name, url)` so duplicate names are adjacent and the
// smallest-`url` entry comes first within each name group.
workers.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.url.cmp(&b.url)));
@@ -404,10 +535,12 @@ impl WorkerRegistry {
gpu: &str,
bundle_config_hash: &str,
) -> Option<String> {
- self.resolve_queue_pool_matching(bundle, gpu, None, bundle_config_hash)
+ self.resolve_queue_route_matching(bundle, gpu, None, bundle_config_hash)
+ .map(|route| route.pool_name)
}
/// Resolve the NATS pool name, constrained to a specific logical pool.
+ #[cfg(test)]
pub async fn resolve_queue_pool_in_pool(
&self,
bundle: &str,
@@ -415,16 +548,29 @@ impl WorkerRegistry {
pool_name: &str,
bundle_config_hash: &str,
) -> Option<String> {
- self.resolve_queue_pool_matching(bundle, gpu, Some(pool_name), bundle_config_hash)
+ self.resolve_queue_route_in_pool(bundle, gpu, pool_name, bundle_config_hash)
+ .await
+ .map(|route| route.pool_name)
+ }
+
+ /// Resolve a concrete queue lane, constrained to a specific logical pool.
+ pub async fn resolve_queue_route_in_pool(
+ &self,
+ bundle: &str,
+ gpu: &str,
+ pool_name: &str,
+ bundle_config_hash: &str,
+ ) -> Option<QueueRoute> {
+ self.resolve_queue_route_matching(bundle, gpu, Some(pool_name), bundle_config_hash)
}
- fn resolve_queue_pool_matching(
+ fn resolve_queue_route_matching(
&self,
bundle: &str,
gpu: &str,
pool_name: Option<&str>,
bundle_config_hash: &str,
- ) -> Option<String> {
+ ) -> Option<QueueRoute> {
let snap = self.snapshot.load();
// `by_bundle` is keyed with `w.bundle.to_lowercase()` in
@@ -445,6 +591,9 @@ impl WorkerRegistry {
if w.pool_name.is_empty() {
continue;
}
+ if w.machine_profile.is_empty() {
+ continue;
+ }
if let Some(pool_name) = pool_name {
if !w.pool_name.eq_ignore_ascii_case(pool_name) {
continue;
@@ -456,7 +605,10 @@ impl WorkerRegistry {
if !bundle_config_hash_matches(&w.bundle_config_hash, bundle_config_hash) {
continue;
}
- return Some(w.pool_name.clone());
+ return Some(QueueRoute {
+ pool_name: w.pool_name.clone(),
+ machine_profile: w.machine_profile.clone(),
+ });
}
None
}
@@ -591,6 +743,16 @@ fn bundle_config_hash_matches(worker_hash: &str, expected_hash: &str) -> bool {
expected_hash.is_empty() || worker_hash == expected_hash
}
+fn worker_allowed_by_admission(
+ worker: &WorkerState,
+ admitted_worker_names: Option<&HashSet<String>>,
+) -> bool {
+ match admitted_worker_names {
+ Some(names) => names.contains(&worker.name),
+ None => true,
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1014,22 +1176,23 @@ mod tests {
// A `:profile` request must direct-dispatch to the base-model
// worker rather than fall through to the pool.
- let direct = reg.dispatch_workers_for("BAAI/bge-m3:fast", "default");
+ let direct =
+ reg.dispatch_workers_for("BAAI/bge-m3:fast", "default", "l4-spot", "default", "");
assert_eq!(direct.len(), 1, "profile variant should match base worker");
assert_eq!(direct[0].name, "w1");
// The bare base id still works (regression guard).
- let base = reg.dispatch_workers_for("BAAI/bge-m3", "default");
+ let base = reg.dispatch_workers_for("BAAI/bge-m3", "default", "l4-spot", "default", "");
assert_eq!(base.len(), 1);
// The ring snapshot (built from the same filter) is non-empty,
// so HRW can pick a worker for the profile variant.
- let ring = reg.ring_snapshot_for("BAAI/bge-m3:fast", "default");
+ let ring = reg.ring_snapshot_for("BAAI/bge-m3:fast", "default", "l4-spot", "default", "");
assert_eq!(ring.len(), 1);
// An unknown base id still finds nothing.
assert!(reg
- .dispatch_workers_for("unknown/model:fast", "default")
+ .dispatch_workers_for("unknown/model:fast", "default", "l4-spot", "default", "")
.is_empty());
}
@@ -1053,11 +1216,15 @@ mod tests {
reg.update_worker("http://w-a:8080", b).await;
// Both are dispatch-eligible…
- assert_eq!(reg.dispatch_workers_for("BAAI/bge-m3", "default").len(), 2);
+ assert_eq!(
+ reg.dispatch_workers_for("BAAI/bge-m3", "default", "l4-spot", "default", "")
+ .len(),
+ 2
+ );
// …but the ring collapses them to a single deterministic entry so
// the HRW pick is unambiguous and only one per-worker subject is
// targeted.
- let ring = reg.ring_snapshot_for("BAAI/bge-m3", "default");
+ let ring = reg.ring_snapshot_for("BAAI/bge-m3", "default", "l4-spot", "default", "");
assert_eq!(ring.len(), 1);
assert_eq!(ring.entries[0].worker_id, "dup");
}
@@ -1077,7 +1244,7 @@ mod tests {
b.loaded_models = vec!["BAAI/bge-m3".into()];
reg.update_worker("http://w2:8080", b).await;
- let ring = reg.ring_snapshot_for("BAAI/bge-m3", "default");
+ let ring = reg.ring_snapshot_for("BAAI/bge-m3", "default", "l4-spot", "default", "");
assert_eq!(ring.len(), 2);
}
@@ -1336,7 +1503,7 @@ mod tests {
}
#[tokio::test]
- async fn test_dispatch_workers_for_filters_by_model_pool_and_saturation() {
+ async fn test_dispatch_workers_for_filters_by_lane_model_and_saturation() {
let reg = registry();
let mut a = make_dispatch_msg(true, false, "p1", &["BAAI/bge-m3"]).await;
a.name = "worker-a".into();
@@ -1358,11 +1525,129 @@ mod tests {
e.name = "worker-e".into();
reg.update_worker("http://e:8080", e).await;
- let elig = reg.dispatch_workers_for("BAAI/bge-m3", "p1");
+ let mut f = make_dispatch_msg(true, false, "p1", &["BAAI/bge-m3"]).await;
+ f.name = "worker-f".into();
+ f.machine_profile = "a100".into();
+ reg.update_worker("http://f:8080", f).await;
+
+ let mut g = make_dispatch_msg(true, false, "p1", &["BAAI/bge-m3"]).await;
+ g.name = "worker-g".into();
+ g.bundle = "sglang".into();
+ reg.update_worker("http://g:8080", g).await;
+
+ let elig = reg.dispatch_workers_for("BAAI/bge-m3", "p1", "l4", "default", "");
let names: Vec<_> = elig.iter().map(|w| w.name.clone()).collect();
assert_eq!(names, vec!["worker-a".to_string()]);
}
+ #[tokio::test]
+ async fn test_dispatch_workers_for_filters_stale_bundle_hash() {
+ let reg = registry();
+ let mut current = make_dispatch_msg(true, false, "p1", &["BAAI/bge-m3"]).await;
+ current.name = "current".into();
+ current.bundle_config_hash = "h1".into();
+ reg.update_worker("http://current:8080", current).await;
+
+ let mut stale = make_dispatch_msg(true, false, "p1", &["BAAI/bge-m3"]).await;
+ stale.name = "stale".into();
+ stale.bundle_config_hash = "old".into();
+ reg.update_worker("http://stale:8080", stale).await;
+
+ let ring = reg.ring_snapshot_for("BAAI/bge-m3", "p1", "l4", "default", "h1");
+ let ids: Vec<_> = ring.entries.iter().map(|e| e.worker_id.clone()).collect();
+ assert_eq!(ids, vec!["current".to_string()]);
+ }
+
+ #[tokio::test]
+ async fn test_pool_fallback_lane_worker_count_includes_cold_workers() {
+ let reg = registry();
+ let mut warm = make_dispatch_msg(true, false, "p1", &["BAAI/bge-m3"]).await;
+ warm.name = "warm".into();
+ reg.update_worker("http://warm:8080", warm).await;
+
+ let mut cold = make_dispatch_msg(true, false, "p1", &[]).await;
+ cold.name = "cold".into();
+ reg.update_worker("http://cold:8080", cold).await;
+
+ assert_eq!(
+ reg.dispatch_workers_for("BAAI/bge-m3", "p1", "l4", "default", "")
+ .len(),
+ 1
+ );
+ assert_eq!(
+ reg.pool_fallback_lane_worker_count("p1", "l4", "default", "", None),
+ 2
+ );
+ }
+
+ #[tokio::test]
+ async fn test_pool_fallback_lane_worker_count_filters_unusable_workers() {
+ let reg = registry();
+ let mut active = make_dispatch_msg(true, false, "p1", &[]).await;
+ active.name = "active".into();
+ active.bundle_config_hash = "h1".into();
+ reg.update_worker("http://active:8080", active).await;
+
+ let mut saturated = make_dispatch_msg(true, true, "p1", &[]).await;
+ saturated.name = "saturated".into();
+ saturated.bundle_config_hash = "h1".into();
+ reg.update_worker("http://saturated:8080", saturated).await;
+
+ let mut stale_hash = make_dispatch_msg(true, false, "p1", &[]).await;
+ stale_hash.name = "stale-hash".into();
+ stale_hash.bundle_config_hash = "old".into();
+ reg.update_worker("http://stale-hash:8080", stale_hash)
+ .await;
+
+ let mut other_bundle = make_dispatch_msg(true, false, "p1", &[]).await;
+ other_bundle.name = "other-bundle".into();
+ other_bundle.bundle = "sglang".into();
+ other_bundle.bundle_config_hash = "h1".into();
+ reg.update_worker("http://other-bundle:8080", other_bundle)
+ .await;
+
+ assert_eq!(
+ reg.pool_fallback_lane_worker_count("p1", "l4", "default", "h1", None),
+ 1
+ );
+ }
+
+ #[tokio::test]
+ async fn test_pool_fallback_lane_worker_count_respects_admitted_workers() {
+ let reg = registry();
+ let mut assigned = make_dispatch_msg(true, false, "p1", &["BAAI/bge-m3"]).await;
+ assigned.name = "assigned".into();
+ assigned.bundle_config_hash = "h1".into();
+ reg.update_worker("http://assigned:8080", assigned).await;
+
+ let mut paused = make_dispatch_msg(true, false, "p1", &["BAAI/bge-m3"]).await;
+ paused.name = "paused".into();
+ paused.bundle_config_hash = "h1".into();
+ reg.update_worker("http://paused:8080", paused).await;
+
+ let admitted = HashSet::from(["assigned".to_string()]);
+
+ assert_eq!(
+ reg.pool_fallback_lane_worker_count("p1", "l4", "default", "h1", None),
+ 2
+ );
+ assert_eq!(
+ reg.pool_fallback_lane_worker_count("p1", "l4", "default", "h1", Some(&admitted)),
+ 1
+ );
+
+ let ring = reg.ring_snapshot_for_admitted(
+ "BAAI/bge-m3",
+ "p1",
+ "l4",
+ "default",
+ "h1",
+ Some(&admitted),
+ );
+ assert_eq!(ring.len(), 1);
+ assert_eq!(ring.entries[0].worker_id, "assigned");
+ }
+
#[tokio::test]
async fn test_ring_snapshot_for_contains_eligible_only() {
let reg = registry();
@@ -1371,7 +1656,7 @@ mod tests {
m.name = format!("w-{i}");
reg.update_worker(&format!("http://h{i}:8080"), m).await;
}
- let snap = reg.ring_snapshot_for("m", "p1");
+ let snap = reg.ring_snapshot_for("m", "p1", "l4", "default", "");
let ids: Vec<_> = snap.entries.iter().map(|e| e.worker_id.clone()).collect();
assert!(ids.contains(&"w-0".to_string()));
assert!(!ids.contains(&"w-1".to_string()));
diff --git a/packages/sie_gateway/src/types/pool.rs b/packages/sie_gateway/src/types/pool.rs
index 2923dd50b..8b14d8f2e 100644
--- a/packages/sie_gateway/src/types/pool.rs
+++ b/packages/sie_gateway/src/types/pool.rs
@@ -40,6 +40,12 @@ pub struct AssignedWorker {
pub name: String,
pub url: String,
pub gpu: String,
+ #[serde(default = "default_bundle")]
+ pub bundle: String,
+}
+
+fn default_bundle() -> String {
+ "default".to_string()
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
@@ -130,6 +136,7 @@ mod tests {
name: "w1".into(),
url: "http://w1:8080".into(),
gpu: "l4".into(),
+ bundle: "default".into(),
}],
);
assert!(pool.has_worker("http://w1:8080"));
@@ -145,11 +152,13 @@ mod tests {
name: "w1".into(),
url: "http://w1:8080".into(),
gpu: "l4".into(),
+ bundle: "default".into(),
},
AssignedWorker {
name: "w2".into(),
url: "http://w2:8080".into(),
gpu: "l4".into(),
+ bundle: "default".into(),
},
],
);
@@ -187,6 +196,7 @@ mod tests {
name: "w1".into(),
url: "http://w1:8080".into(),
gpu: "l4".into(),
+ bundle: "default".into(),
}],
);
let json = serde_json::to_string(&pool).unwrap();
diff --git a/packages/sie_gateway/tests/nak_republish.rs b/packages/sie_gateway/tests/nak_republish.rs
index 3a00978ad..a064ecf0e 100644
--- a/packages/sie_gateway/tests/nak_republish.rs
+++ b/packages/sie_gateway/tests/nak_republish.rs
@@ -71,10 +71,12 @@ async fn nak_republish_cancels_original_before_pool_publish() {
let router_id = "test-router";
let request_id = unique("req-cancel-ordering");
let pool = unique("pool-cancel-order");
+ let machine = "rtx6000";
+ let bundle = "sglang";
let model = "BAAI__bge-m3"; // already subject-normalized (`/` -> `__`)
let cancel_subject = format!("cancel.{router_id}.{request_id}");
- let pool_subject = format!("sie.work.{model}.{pool}");
+ let pool_subject = format!("sie.work.{pool}.{machine}.{bundle}.{model}");
// Record the order in which the two events are observed by the
// "original worker" (cancel) and a "pool worker" (republished work).
@@ -141,12 +143,14 @@ async fn nak_republish_lands_on_pool_subject() {
};
let pool = unique("pool-lands");
+ let machine = "rtx6000";
+ let bundle = "sglang";
let model = "BAAI__bge-m3";
- let pool_subject = format!("sie.work.{model}.{pool}");
+ let pool_subject = format!("sie.work.{pool}.{machine}.{bundle}.{model}");
- // A pool worker subscribes on the pool subject (3 tokens after
+ // A pool worker subscribes on the pool subject (4 tokens after
// `sie.work.`), confirming the republish target is the pool fan-out
- // subject and not a per-worker (4-token) subject.
+ // subject and not a per-worker (5-token) subject.
let mut pool_sub = client
.subscribe(pool_subject.clone())
.await
diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.toml
index edc337ae7..b0df46057 100644
--- a/packages/sie_sdk/pyproject.toml
+++ b/packages/sie_sdk/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-sdk"
-version = "0.5.0"
+version = "0.6.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/queue_types.py b/packages/sie_sdk/src/sie_sdk/queue_types.py
index 07fc27ed5..17061bc7f 100644
--- a/packages/sie_sdk/src/sie_sdk/queue_types.py
+++ b/packages/sie_sdk/src/sie_sdk/queue_types.py
@@ -10,6 +10,7 @@ class _WorkItemRequired(TypedDict):
model_id: str
profile_id: str
pool_name: str
+ machine_profile: str
router_id: str
reply_subject: str
timestamp: float
@@ -18,7 +19,8 @@ class _WorkItemRequired(TypedDict):
class WorkItem(_WorkItemRequired, total=False):
"""A single inference work item published to NATS JetStream.
- Published by the gateway to ``sie.work.{model_id_normalized}.{pool_name}``.
+ Published by the gateway to
+ ``sie.work.{pool_name}.{machine_profile}.{bundle_id}.{model_id_normalized}``.
Consumed by workers via JetStream pull consumers.
Attributes:
@@ -29,7 +31,7 @@ class WorkItem(_WorkItemRequired, total=False):
operation: Inference operation: ``"encode"`` | ``"score"`` | ``"extract"``.
model_id: Model identifier (e.g., ``"BAAI/bge-m3"``).
profile_id: Profile name (e.g., ``"default"``).
- pool_name: Target pool (e.g., ``"_default"``).
+ pool_name: Target pool (e.g., ``"default"``).
machine_profile: Required GPU type (e.g., ``"l4"``). Workers validate this.
bundle_config_hash: Expected bundle config hash from the gateway's ModelRegistry.
Workers compare this against their own computed hash and NAK items with
@@ -55,7 +57,6 @@ class WorkItem(_WorkItemRequired, total=False):
timestamp: Unix timestamp when the work item was created.
"""
- machine_profile: str
bundle_config_hash: str
# Item payload (inline or reference)
@@ -158,14 +159,12 @@ class WorkResult(_WorkResultRequired, total=False):
# NATS JetStream max message size default is 1MB.
INLINE_THRESHOLD_BYTES = 1_048_576 # 1 MB
-# Stream name prefix for work queues
-WORK_STREAM_PREFIX = "WORK"
-
# Subject prefix for work items
WORK_SUBJECT_PREFIX = "sie.work"
# Dead-letter subject prefix — uses ``sie.dlq`` (not ``sie.work.dead``)
-# to avoid subject overlap with pool-level work streams (``sie.work.*.{pool}``).
+# to avoid subject overlap with pool-level work streams
+# (``sie.work.{pool}.*.*.*``).
DEAD_LETTER_PREFIX = "sie.dlq"
@@ -206,9 +205,9 @@ def normalize_worker_id(worker_id: str) -> str:
Worker IDs flow into three places that all share the same wire contract:
* the gateway's direct-dispatch publish subject
- (``sie.work.{model}.{pool}.{worker_id}``),
+ (``sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}``),
* the per-worker JetStream stream subjects
- (``sie.work.*.{pool}.{worker_id}``), and
+ (``sie.work.{pool}.{machine_profile}.{bundle}.*.{worker_id}``), and
* the durable consumer name (``gen-{worker_id}``).
In production, worker IDs come from ``SIE_WORKER_ID`` / ``HOSTNAME`` /
@@ -262,42 +261,37 @@ def denormalize_model_id(normalized: str) -> str:
return result
-def work_subject(model_id: str, pool_name: str) -> str:
+def work_subject(pool_name: str, machine_profile: str, bundle_id: str, model_id: str) -> str:
"""Build the NATS subject for a work queue.
Args:
- model_id: Model identifier (e.g., ``"BAAI/bge-m3"``).
- pool_name: Pool name (e.g., ``"_default"``).
-
- Returns:
- NATS subject string (e.g., ``"sie.work.BAAI__bge-m3._default"``).
- """
- return f"{WORK_SUBJECT_PREFIX}.{normalize_model_id(model_id)}.{pool_name}"
-
-
-def work_stream_name(model_id: str) -> str:
- """Build the JetStream stream name for a model's work queue.
-
- Args:
+ pool_name: Pool name (e.g., ``"default"``).
+ machine_profile: Hardware lane (e.g., ``"rtx6000"``).
+ bundle_id: Runtime/image bundle identifier (e.g., ``"sglang"``).
model_id: Model identifier (e.g., ``"BAAI/bge-m3"``).
Returns:
- Stream name (e.g., ``"WORK_BAAI__bge-m3"``).
+ NATS subject string, e.g.
+ ``"sie.work.default.rtx6000.sglang.BAAI__bge-m3"``.
"""
- return f"{WORK_STREAM_PREFIX}_{normalize_model_id(model_id)}"
+ return (
+ f"{WORK_SUBJECT_PREFIX}.{pool_name}.{normalize_model_id(machine_profile)}."
+ f"{normalize_model_id(bundle_id)}.{normalize_model_id(model_id)}"
+ )
-def work_consumer_name(bundle_id: str, pool_name: str) -> str:
- """Build the JetStream consumer name for a (bundle, pool) pair.
+def work_consumer_name(pool_name: str, machine_profile: str, bundle_id: str) -> str:
+ """Build the JetStream consumer name for a concrete queue lane.
Args:
+ pool_name: Pool name (e.g., ``"default"``).
+ machine_profile: Hardware lane (e.g., ``"rtx6000"``).
bundle_id: Bundle identifier (e.g., ``"default"``).
- pool_name: Pool name (e.g., ``"_default"``).
Returns:
- Consumer durable name (e.g., ``"default__default"``).
+ Consumer durable name (e.g., ``"default_rtx6000_sglang"``).
"""
- return f"{bundle_id}_{pool_name}"
+ return f"{normalize_model_id(pool_name)}_{normalize_model_id(machine_profile)}_{normalize_model_id(bundle_id)}"
# -- Pool-level (multiplexed) stream helpers --------------------------------
@@ -323,45 +317,59 @@ def work_pool_stream_name(pool_name: str) -> str:
def work_pool_stream_subjects(pool_name: str) -> list[str]:
"""Subjects captured by a pool-level stream.
- Matches ``sie.work.<any-single-token>.<pool_name>`` which covers all
- models for the given pool.
+ Matches ``sie.work.<pool_name>.<machine_profile>.<bundle>.<model>`` for
+ all machine profiles, bundles, and models in the given logical pool.
Args:
pool_name: Pool name (e.g., ``"l4"``).
Returns:
- Subject list, e.g. ``["sie.work.*.l4"]``.
+ Subject list, e.g. ``["sie.work.default.*.*.*"]``.
"""
- return [f"{WORK_SUBJECT_PREFIX}.*.{pool_name}"]
+ return [f"{WORK_SUBJECT_PREFIX}.{pool_name}.*.*.*"]
# -- Per-worker direct-dispatch helpers -----------------------------------
# Each worker subscribes to a second, narrower JetStream stream that
# captures ONLY messages addressed to its own worker_id. The gateway
-# computes an HRW pick and publishes to ``sie.work.{model}.{pool}.{worker_id}``;
-# the pool stream's subjects (``sie.work.*.{pool}``) deliberately do not
-# match those four-token subjects, so the two paths cannot double-deliver.
+# computes an HRW pick and publishes to
+# ``sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}``; the pool
+# stream's subjects (``sie.work.{pool}.*.*.*``) deliberately do not match those
+# worker-addressed subjects, so the two paths cannot double-deliver.
WORK_WORKER_STREAM_PREFIX = "WORK_WORKER"
-def work_worker_subject(model_id: str, pool_name: str, worker_id: str) -> str:
+def work_worker_subject(
+ pool_name: str,
+ machine_profile: str,
+ bundle_id: str,
+ model_id: str,
+ worker_id: str,
+) -> str:
"""Build the NATS subject for a per-worker direct-dispatch.
Args:
+ pool_name: Pool name (e.g., ``"default"``).
+ machine_profile: Hardware lane (e.g., ``"rtx6000"``).
+ bundle_id: Runtime/image bundle identifier (e.g., ``"sglang"``).
model_id: Model identifier (e.g., ``"BAAI/bge-m3"``).
- pool_name: Pool name (e.g., ``"_default"``).
worker_id: Stable worker identity (matches
:attr:`sie_server.nats_pull_loop.NatsPullLoop.worker_id`).
Returns:
- NATS subject like ``"sie.work.BAAI__bge-m3._default.worker-0"``.
+ NATS subject like
+ ``"sie.work.default.rtx6000.sglang.BAAI__bge-m3.worker-0"``.
Raises:
ValueError: ``worker_id`` is empty or whitespace-only — see
:func:`normalize_worker_id`.
"""
- return f"{WORK_SUBJECT_PREFIX}.{normalize_model_id(model_id)}.{pool_name}.{normalize_worker_id(worker_id)}"
+ return (
+ f"{WORK_SUBJECT_PREFIX}.{pool_name}.{normalize_model_id(machine_profile)}."
+ f"{normalize_model_id(bundle_id)}.{normalize_model_id(model_id)}."
+ f"{normalize_worker_id(worker_id)}"
+ )
def work_worker_stream_name(worker_id: str) -> str:
@@ -380,24 +388,37 @@ def work_worker_stream_name(worker_id: str) -> str:
return f"{WORK_WORKER_STREAM_PREFIX}_{normalize_worker_id(worker_id)}"
-def work_worker_stream_subjects(pool_name: str, worker_id: str) -> list[str]:
+def work_worker_stream_subjects(
+ pool_name: str,
+ machine_profile: str,
+ bundle_id: str,
+ worker_id: str,
+) -> list[str]:
"""Subjects captured by a per-worker stream.
- Matches ``sie.work.<any-single-token>.<pool>.<worker_id>`` so any
- model on this pool addressed to this worker lands in the stream.
+ Matches
+ ``sie.work.<pool>.<machine_profile>.<bundle>.<any-model>.<worker_id>``
+ so any model on this concrete lane addressed to this worker lands in
+ the stream.
Args:
pool_name: Pool name.
+ machine_profile: Hardware lane.
+ bundle_id: Runtime/image bundle identifier.
worker_id: Stable worker identity.
Returns:
- Subject list, e.g. ``["sie.work.*.l4.worker-0"]``.
+ Subject list, e.g.
+ ``["sie.work.default.rtx6000.sglang.*.worker-0"]``.
Raises:
ValueError: ``worker_id`` is empty or whitespace-only — see
:func:`normalize_worker_id`.
"""
- return [f"{WORK_SUBJECT_PREFIX}.*.{pool_name}.{normalize_worker_id(worker_id)}"]
+ return [
+ f"{WORK_SUBJECT_PREFIX}.{pool_name}.{normalize_model_id(machine_profile)}."
+ f"{normalize_model_id(bundle_id)}.*.{normalize_worker_id(worker_id)}"
+ ]
def work_worker_consumer_name(worker_id: str) -> str:
diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.py
index cf7adbe68..4a0aeb686 100644
--- a/packages/sie_sdk/src/sie_sdk/types.py
+++ b/packages/sie_sdk/src/sie_sdk/types.py
@@ -10,7 +10,7 @@ These types support flexible Python inputs
from __future__ import annotations
from collections.abc import Sequence
-from typing import TYPE_CHECKING, Any, Literal, TypedDict
+from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypedDict
import numpy as np
@@ -504,7 +504,7 @@ class WorkerInfo(TypedDict, total=False):
loaded_models: list[str]
memory_used_bytes: int
memory_total_bytes: int
- bundle: str
+ bundle: NotRequired[str]
bundle_config_hash: str
@@ -566,11 +566,13 @@ class AssignedWorkerInfo(TypedDict):
name: Worker name/identifier.
url: Worker base URL.
gpu: GPU type (e.g., "l4", "a100-80gb").
+ bundle: Runtime bundle this worker serves.
"""
name: str
url: str
gpu: str
+ bundle: str
class PoolStatusInfo(TypedDict, total=False):
@@ -840,7 +842,7 @@ class WorkerStatusMessage(TypedDict, total=False):
name: Worker name/identifier.
machine_profile: Machine profile for routing. In K8s: from SIE_MACHINE_PROFILE env var
(e.g., "l4-spot"). Standalone: detected GPU type (e.g., "l4").
- pool_name: NATS work-queue pool name (from SIE_POOL env var, e.g., "l4-spot-default").
+ pool_name: Logical NATS work-queue pool name (from SIE_POOL env var, e.g., "default" or "customer-acme").
Used by the gateway in queue mode to publish to the correct JetStream subject.
Empty string when not in queue mode or not set.
gpu_count: Number of GPUs on this worker.
diff --git a/packages/sie_sdk/tests/test_worker_id_normalization.py b/packages/sie_sdk/tests/test_worker_id_normalization.py
index 098424aaf..e782fe9dc 100644
--- a/packages/sie_sdk/tests/test_worker_id_normalization.py
+++ b/packages/sie_sdk/tests/test_worker_id_normalization.py
@@ -1,8 +1,8 @@
"""Cross-language fixture for worker_id NATS subject normalization.
The gateway (Rust) publishes direct-dispatch work items to
-``sie.work.{model}.{pool}.{worker_id}`` and applies its
-``normalize_model_id`` to the worker_id before publishing. The Python SDK
+``sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`` and
+applies its ``normalize_model_id`` to the worker_id before publishing. The Python SDK
helpers (``work_worker_subject``, ``work_worker_stream_subjects``,
``work_worker_stream_name``, ``work_worker_consumer_name``) and the worker
init (``NatsPullLoop.__init__``) now route worker IDs through
@@ -94,13 +94,13 @@ def test_subject_helpers_route_through_normalize() -> None:
assert normalized == "pod-0_dot_svc"
# per-worker publish subject
- subj = work_worker_subject("BAAI/bge-m3", "default", raw)
- assert subj == f"sie.work.BAAI__bge-m3.default.{normalized}"
- assert subj.count(".") == 4, "exactly 4 dots → 5 tokens after split"
+ subj = work_worker_subject("default", "rtx6000", "sglang", "BAAI/bge-m3", raw)
+ assert subj == f"sie.work.default.rtx6000.sglang.BAAI__bge-m3.{normalized}"
+ assert subj.count(".") == 6, "exactly 6 dots -> 7 tokens after split"
# per-worker stream subjects (consumer-side filter)
- subjects = work_worker_stream_subjects("default", raw)
- assert subjects == [f"sie.work.*.default.{normalized}"]
+ subjects = work_worker_stream_subjects("default", "rtx6000", "sglang", raw)
+ assert subjects == [f"sie.work.default.rtx6000.sglang.*.{normalized}"]
# per-worker stream name (no dots — uses an underscore prefix)
assert work_worker_stream_name(raw) == f"WORK_WORKER_{normalized}"
@@ -114,9 +114,9 @@ def test_subject_helpers_reject_empty_worker_id() -> None:
silently substituting a default.
"""
with pytest.raises(ValueError, match="empty"):
- work_worker_subject("m", "p", "")
+ work_worker_subject("p", "m", "b", "m", "")
with pytest.raises(ValueError, match="empty"):
- work_worker_stream_subjects("p", "")
+ work_worker_stream_subjects("p", "m", "b", "")
with pytest.raises(ValueError, match="empty"):
work_worker_stream_name("")
with pytest.raises(ValueError, match="empty"):
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index afd9dbe11..67b16b8ec 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.5.0"
+ "version": "0.6.0"
},
"paths": {
"/": {
diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.toml
index ebd7a161a..899255710 100644
--- a/packages/sie_server/pyproject.toml
+++ b/packages/sie_server/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-server"
-version = "0.5.0"
+version = "0.6.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/api/ws.py b/packages/sie_server/src/sie_server/api/ws.py
index 16bd4569b..bcb6c49fd 100644
--- a/packages/sie_server/src/sie_server/api/ws.py
+++ b/packages/sie_server/src/sie_server/api/ws.py
@@ -299,7 +299,8 @@ async def build_status_message(
# The pull loop owns the canonical resolution
# (``SIE_WORKER_ID > HOSTNAME > POD_NAME > uuid4``); we mirror that
# value here so the gateway's WorkerRegistry keys its dispatch
- # subject (``sie.work.{model}.{pool}.{name}``) on the *same*
+ # subject (``sie.work.{pool}.{machine_profile}.{bundle}.{model}.{name}``)
+ # on the *same*
# identifier the worker is subscribed to. Falling back to the
# legacy ``HOSTNAME``/``POD_NAME`` lookup when the pull loop is
# absent keeps the non-queue path working unchanged.
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index 4c058368a..40ff0a4a8 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -1094,7 +1094,7 @@ class StreamingProcessor:
# as stale even if the terminal races), then ACK so JetStream does
# not redeliver indefinitely.
if self._check_and_consume_tombstone(request_id):
- pool_label = str(wi.get("pool_name") or "_default")
+ pool_label = str(wi.get("pool_name") or "default")
_metrics.GENERATION_FALLBACK_DUPLICATE_TOTAL.labels(model=model_id, pool=pool_label).inc()
logger.warning(
"cancel-tombstone hit: refusing to decode request_id=%s model=%s pool=%s "
diff --git a/packages/sie_server/tests/health/test_worker_id_consistency.py b/packages/sie_server/tests/health/test_worker_id_consistency.py
index e3c652544..94f506400 100644
--- a/packages/sie_server/tests/health/test_worker_id_consistency.py
+++ b/packages/sie_server/tests/health/test_worker_id_consistency.py
@@ -37,7 +37,8 @@ async def test_build_status_message_uses_pull_loop_worker_id(
The scenario this prevents: ``SIE_WORKER_ID="w-prod-3"`` is set and
``HOSTNAME`` is the K8s pod name. Pre-fix, the pull loop subscribed
- on ``sie.work.*.{pool}.w-prod-3`` but the WS payload reported
+ on ``sie.work.{pool}.{machine_profile}.{bundle}.*.w-prod-3`` but the
+ WS payload reported
``name = {pod-name}`` — the gateway's HRW pick used ``{pod-name}``
for the dispatch subject and no worker was listening on it.
"""
diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.py
index 946e3e0d6..469007a6f 100644
--- a/packages/sie_server/tests/processors/test_streaming.py
+++ b/packages/sie_server/tests/processors/test_streaming.py
@@ -95,7 +95,8 @@ def _make_work_item(
"operation": "generate",
"model_id": "test/model",
"profile_id": "default",
- "pool_name": "_default",
+ "pool_name": "default",
+ "machine_profile": "default",
"router_id": "router-1",
"reply_subject": "_INBOX.router-1.req-1",
"timestamp": time.time(),
@@ -2140,12 +2141,12 @@ async def test_duplicate_execution_metric_increments_on_refusal() -> None:
# Cancel before any decode → tombstone.
proc.signal_cancel("req-1")
- before = worker_metrics.GENERATION_FALLBACK_DUPLICATE_TOTAL.labels(model="test/model", pool="_default")._value.get()
+ before = worker_metrics.GENERATION_FALLBACK_DUPLICATE_TOTAL.labels(model="test/model", pool="default")._value.get()
msg = _make_msg(_make_work_item())
await proc.process(msg, "test/model")
- after = worker_metrics.GENERATION_FALLBACK_DUPLICATE_TOTAL.labels(model="test/model", pool="_default")._value.get()
+ after = worker_metrics.GENERATION_FALLBACK_DUPLICATE_TOTAL.labels(model="test/model", pool="default")._value.get()
assert after - before == 1.0, f"counter did not increment: before={before} after={after}"
diff --git a/packages/sie_server/tests/processors/test_streaming_admission.py b/packages/sie_server/tests/processors/test_streaming_admission.py
index d346308ea..79ca6e9fc 100644
--- a/packages/sie_server/tests/processors/test_streaming_admission.py
+++ b/packages/sie_server/tests/processors/test_streaming_admission.py
@@ -97,7 +97,8 @@ def _make_work_item(*, request_id: str = "req-1", max_new_tokens: int = 64) -> d
"operation": "generate",
"model_id": MODEL,
"profile_id": "default",
- "pool_name": "_default",
+ "pool_name": "default",
+ "machine_profile": "default",
"router_id": "router-1",
"reply_subject": f"_INBOX.router-1.{request_id}",
"timestamp": time.time(),
diff --git a/packages/sie_server/tests/processors/test_streaming_integration.py b/packages/sie_server/tests/processors/test_streaming_integration.py
index 75f80f954..8b7871352 100644
--- a/packages/sie_server/tests/processors/test_streaming_integration.py
+++ b/packages/sie_server/tests/processors/test_streaming_integration.py
@@ -46,7 +46,8 @@ def _make_work_item(**overrides: Any) -> dict[str, Any]:
"operation": "generate",
"model_id": "test/model",
"profile_id": "default",
- "pool_name": "_default",
+ "pool_name": "default",
+ "machine_profile": "default",
"router_id": "router-1",
"reply_subject": "_INBOX.router-1.req-1",
"timestamp": time.time(),
diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lock
index 327ee005c..16dd5be98 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.5.0"
+version = "0.6.0"
dependencies = [
"anyhow",
"async-nats",
diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.toml
index 4573f46a6..1789a7ce4 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.5.0"
+version = "0.6.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_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.md
index b55c43192..f28a6418e 100644
--- a/packages/sie_server_sidecar/docs/architecture-guide.md
+++ b/packages/sie_server_sidecar/docs/architecture-guide.md
@@ -51,7 +51,7 @@ the colocated adapter over a Unix domain socket.
## Request Path
-1. Gateway publishes a msgpack `WorkItem` on `sie.work.{model}.{pool}`.
+1. Gateway publishes a msgpack `WorkItem` on `sie.work.{pool}.{machine_profile}.{bundle}.{model}`.
2. The sidecar's long-lived JetStream pull stream receives messages from
stream `WORK_POOL_{pool}`.
3. The dispatcher extracts the model from the subject and rejects malformed
@@ -84,15 +84,23 @@ Worker stream and consumer settings must stay aligned with the gateway and SDK:
| Field | Value |
| --- | --- |
| Stream | `WORK_POOL_{pool}` |
-| Subject filter | `sie.work.*.{pool}` |
+| Stream subjects | `sie.work.{pool}.*.*.*` |
+| Consumer filter | `sie.work.{pool}.{machine_profile}.{bundle}.*` |
| Retention | WorkQueue |
| Storage | Memory |
-| Consumer | `{bundle}_{pool}` |
+| Consumer | `{pool}_{machine_profile}_{bundle}` |
| Ack policy | Explicit |
| Ack wait | 30 s |
| Max deliver | `SIE_MAX_DELIVER`, default 20 |
| Max ack pending | `SIE_MAX_ACK_PENDING`, default 1000 |
+On existing streams, the gateway and sidecar reconcile the subject list to
+exactly `sie.work.{pool}.*.*.*`. Legacy subjects such as `sie.work.*.{pool}` are
+intentionally removed from stream configuration. This release is a cutover to
+the lane-aware subject shape, not a mixed-version bridge: all gateways and
+workers in the cluster must use the new shape, and any old queued work should be
+drained or purged before rollout.
+
The pull stream must be long-lived. Dropping and recreating pull streams inside
the fetch loop can make async-nats mark unread messages as delivered, causing
redelivery only after the 30 s `ack_wait`. The implementation creates one pull
@@ -101,17 +109,17 @@ Integration tests guard this with concurrent and sustained-load scenarios that
watch `sie_worker_nats_redelivery_total`.
The sidecar also runs a slow stream/durable reconciler. It periodically
-re-ensures `WORK_POOL_{pool}` and `{bundle}_{pool}` so NATS metadata drift can
-self-heal without adding reconnect-event work or locks to the fetch loop. It
-does not rebuild the active pull stream; terminal pull-stream errors still use
-the normal pull-loop recovery path.
+re-ensures `WORK_POOL_{pool}` and `{pool}_{machine_profile}_{bundle}` so NATS
+metadata drift can self-heal without adding reconnect-event work or locks to
+the fetch loop. It does not rebuild the active pull stream; terminal
+pull-stream errors still use the normal pull-loop recovery path.
Generation models use a worker-specific JetStream subject
-`sie.work.{model}.{pool}.{worker_id}`. The sidecar creates and polls that
-worker stream only after Python `WorkerCapabilities` reports at least one
-generation model. If live config reconciliation later adds a generation model
-to an already-running sidecar, a capability reconciler activates the direct
-stream and cancel subscriber exactly once.
+`sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`. The sidecar
+creates and polls that worker stream only after Python `WorkerCapabilities`
+reports at least one generation model. If live config reconciliation later adds
+a generation model to an already-running sidecar, a capability reconciler
+activates the direct stream and cancel subscriber exactly once.
When `SIE_GATEWAY_URL` is set, the sidecar runs the pool admission gate before
pulling from either the pool stream or the generation worker stream. Capped
@@ -120,12 +128,6 @@ named pools fail closed unless `/v1/pools/{pool}` lists this pod in
pulling. The default pool fails open during transient gateway/status errors so
baseline capacity remains available.
-On startup the sidecar also performs a best-effort cleanup of empty per-model
-`WORK_<model>` streams whose subjects overlap `sie.work.*.{pool}`. This
-preserves upgrade safety without dropping queued work; non-empty streams must be
-drained or migrated explicitly, and unrelated streams and other pool streams are
-ignored.
-
## IPC Contract
Framing is:
@@ -240,8 +242,9 @@ sidecar container itself.
| Variable | Purpose |
| --- | --- |
| `SIE_NATS_URL` | NATS endpoint; required |
-| `SIE_POOL` | pool segment in `sie.work.*.{pool}` |
-| `SIE_BUNDLE` | consumer-name segment |
+| `SIE_POOL` | pool segment in `sie.work.{pool}.{machine_profile}.{bundle}.{model}` |
+| `SIE_MACHINE_PROFILE` | machine-profile segment; required and set explicitly by Helm |
+| `SIE_BUNDLE` | bundle/runtime segment and consumer-name segment |
| `SIE_IPC_SOCKET_PATH` | UDS path to the adapter |
| `SIE_IPC_POOL_SIZE` | concurrent IPC connections, default matches dispatch concurrency |
| `SIE_NATS_FETCH_BUDGET` | pull-stream credit and fallback model budget |
@@ -313,7 +316,8 @@ task, then creates the worker-specific generation stream.
a matching `sie-config`/worker image rollout; the running sidecar can only
apply configs for adapters already present in the co-located Python image.
- **Subject shape coupling.** The worker extracts the model from subject token
- `parts[2]`. Gateway subject changes must update worker parsing in lock-step.
+ `parts[5]` in `sie.work.{pool}.{machine_profile}.{bundle}.{model}`. Gateway
+ subject changes must update worker parsing in lock-step.
- **Unit integration scope.** Rust integration tests use real NATS and a stub
Python IPC server; local Tilt E2E covers the real gateway-to-worker path.
- **Sidecar enablement changes deployment behavior.** Keeping
diff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rs
index 0541fe136..7c30c726f 100644
--- a/packages/sie_server_sidecar/src/config.rs
+++ b/packages/sie_server_sidecar/src/config.rs
@@ -10,12 +10,12 @@ pub struct WorkerConfig {
/// NATS server URL (e.g. `nats://localhost:4222`).
pub nats_url: String,
- /// Pool name — drives the stream (`WORK_POOL_{pool}`), consumer
- /// (`{bundle}_{pool}`), and subject filter.
+ /// Pool name — drives the stream (`WORK_POOL_{pool}`), durable consumer
+ /// (`{pool}_{machine_profile}_{bundle}`), and subject filters.
pub pool: String,
- /// Bundle ID — forms part of the durable consumer name so multiple
- /// bundles on the same pool don't step on each other.
+ /// Bundle ID — forms part of the durable consumer name and subject lane
+ /// so multiple bundles on the same pool don't step on each other.
pub bundle: String,
/// Unix domain socket used to talk to the Python `ipc_server.py`.
@@ -86,8 +86,7 @@ pub struct WorkerConfig {
/// only — the `X-SIE-MACHINE-PROFILE` route filter compares
/// case-insensitively against this value. Empty disables the
/// filter (route by bundle alone). Sourced from
- /// `SIE_MACHINE_PROFILE`; falls back to `pool` to preserve
- /// the historical convention where pool name == GPU type.
+ /// `SIE_MACHINE_PROFILE`; required so the queue lane is explicit.
pub machine_profile: String,
/// GPU count surfaced in heartbeats. Informational —
@@ -135,14 +134,28 @@ impl WorkerConfig {
format!("WORK_POOL_{}", self.pool)
}
+ pub fn stream_subject_filter(&self) -> String {
+ format!("sie.work.{}.*.*.*", self.pool)
+ }
+
pub fn consumer_name(&self) -> String {
- // Matches `sie_sdk.queue_types.work_consumer_name(bundle, pool)` so
+ // Matches `sie_sdk.queue_types.work_consumer_name(pool, machine, bundle)` so
// Rust and Python adapter processes converge on the same durable consumer.
- format!("{}_{}", self.bundle, self.pool)
+ format!(
+ "{}_{}_{}",
+ crate::subject::normalize_model_id(&self.pool),
+ crate::subject::normalize_model_id(&self.machine_profile),
+ crate::subject::normalize_model_id(&self.bundle)
+ )
}
pub fn subject_filter(&self) -> String {
- format!("sie.work.*.{}", self.pool)
+ format!(
+ "sie.work.{}.{}.{}.*",
+ self.pool,
+ crate::subject::normalize_model_id(&self.machine_profile),
+ crate::subject::normalize_model_id(&self.bundle)
+ )
}
pub fn worker_stream_name(&self) -> String {
@@ -161,8 +174,10 @@ impl WorkerConfig {
pub fn worker_subject_filter(&self) -> String {
format!(
- "sie.work.*.{}.{}",
+ "sie.work.{}.{}.{}.*.{}",
self.pool,
+ crate::subject::normalize_model_id(&self.machine_profile),
+ crate::subject::normalize_model_id(&self.bundle),
crate::subject::normalize_model_id(&self.worker_id)
)
}
@@ -208,17 +223,22 @@ mod tests {
// Must agree with sie_gateway's NATS naming so publisher and
// consumer land on the same stream/consumer.
assert_eq!(c.stream_name(), "WORK_POOL_l4");
- assert_eq!(c.consumer_name(), "default_l4");
- assert_eq!(c.subject_filter(), "sie.work.*.l4");
+ assert_eq!(c.stream_subject_filter(), "sie.work.l4.*.*.*");
+ assert_eq!(c.consumer_name(), "l4_l4_default");
+ assert_eq!(c.subject_filter(), "sie.work.l4.l4.default.*");
assert_eq!(c.worker_stream_name(), "WORK_WORKER_worker-test");
assert_eq!(c.worker_consumer_name(), "gen-worker-test");
- assert_eq!(c.worker_subject_filter(), "sie.work.*.l4.worker-test");
+ assert_eq!(
+ c.worker_subject_filter(),
+ "sie.work.l4.l4.default.*.worker-test"
+ );
}
#[test]
fn subject_filter_contains_pool() {
let mut c = sample();
c.pool = "eval-h100".into();
- assert!(c.subject_filter().ends_with(".eval-h100"));
+ assert!(c.stream_subject_filter().starts_with("sie.work.eval-h100."));
+ assert!(c.subject_filter().starts_with("sie.work.eval-h100."));
}
}
diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rs
index 07e744e42..e9815ca84 100644
--- a/packages/sie_server_sidecar/src/health_publisher.rs
+++ b/packages/sie_server_sidecar/src/health_publisher.rs
@@ -18,11 +18,12 @@
//! * `bundle` — must match the bundle resolved by the gateway's
//! model registry (lowercase compared); routes only consider
//! workers whose bundle index entry contains them.
-//! * `pool_name` — non-empty so [`resolve_queue_pool`] can return
+//! * `pool_name` — non-empty so [`resolve_queue_route`] can return
//! the pool the dispatcher publishes work onto. An empty
//! `pool_name` makes the worker invisible to the queue path.
-//! * `machine_profile` — only consulted when the request carries
-//! `X-SIE-MACHINE-PROFILE`; ignored otherwise.
+//! * `machine_profile` — the hardware lane embedded in the queue
+//! subject. `X-SIE-MACHINE-PROFILE` constrains route resolution to
+//! this value; otherwise the gateway infers it from a healthy worker.
//! * `ready` — drives the `WorkerHealth::Healthy` transition. We
//! gate on the local [`Readiness`] state so the heartbeat agrees
//! with `/readyz`.
@@ -34,7 +35,7 @@
//! plus its own model registry.
//!
//! [`WorkerStatusMessage`]: https://github.com/search?q=WorkerStatusMessage+repo%3Asie-internal
-//! [`resolve_queue_pool`]: https://github.com/search?q=resolve_queue_pool+repo%3Asie-internal
+//! [`resolve_queue_route`]: https://github.com/search?q=resolve_queue_route+repo%3Asie-internal
use std::sync::Arc;
use std::sync::RwLock;
@@ -80,9 +81,10 @@ pub struct HealthPublisherConfig {
/// match `BundleConfig.id`. Sourced from `SIE_BUNDLE`.
pub bundle: String,
/// Pool name. The gateway publishes work onto
- /// `sie.work.<model>.<pool_name>`; the worker must echo the
- /// same pool here or `resolve_queue_pool` returns `None` and
- /// requests 202-provision forever. Sourced from `SIE_POOL`.
+ /// `sie.work.<pool_name>.<machine_profile>.<bundle>.<model>`; the
+ /// worker must echo the same pool here or queue-route resolution
+ /// returns `None` and requests 202-provision forever. Sourced from
+ /// `SIE_POOL`.
pub pool_name: String,
/// Optional machine-profile label (e.g. `l4`, `a100`).
/// Consulted only when the inbound request carries
diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rs
index 05daf35d0..3d48448f0 100644
--- a/packages/sie_server_sidecar/src/lib.rs
+++ b/packages/sie_server_sidecar/src/lib.rs
@@ -512,7 +512,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
//
// In `health_mode=nats` the gateway's `WorkerRegistry` is built
// exclusively from `sie.health.>` messages — no publisher means
- // no registered workers, which makes `resolve_queue_pool`
+ // no registered workers, which makes `resolve_queue_route`
// return `None` and every inbound request `202 provisioning`.
//
// Skipped silently when `SIE_HEALTH_PUBLISH_ENABLED=false` (or
diff --git a/packages/sie_server_sidecar/src/main.rs b/packages/sie_server_sidecar/src/main.rs
index 1387873ee..caa6ec7b7 100644
--- a/packages/sie_server_sidecar/src/main.rs
+++ b/packages/sie_server_sidecar/src/main.rs
@@ -18,10 +18,10 @@ struct Cli {
#[arg(long, env = "SIE_NATS_URL")]
nats_url: String,
- #[arg(long, env = "SIE_POOL", default_value = "_default")]
+ #[arg(long, env = "SIE_POOL")]
pool: String,
- #[arg(long, env = "SIE_BUNDLE", default_value = "default")]
+ #[arg(long, env = "SIE_BUNDLE")]
bundle: String,
#[arg(long, env = "SIE_IPC_SOCKET_PATH", default_value = "/tmp/sie-ipc.sock")]
@@ -83,13 +83,13 @@ struct Cli {
#[arg(long, env = "SIE_WORKER_READYZ_STALE_MULT", default_value = "3")]
ready_stale_mult: u32,
- /// Machine-profile label echoed in NATS health heartbeats.
- /// Used by the gateway when a request carries
- /// `X-SIE-MACHINE-PROFILE`; empty disables that filter.
- /// Defaults to the pool name (the historical convention where
- /// pool == GPU type, e.g. `l4`).
+ /// Machine-profile label echoed in NATS health heartbeats and
+ /// embedded in this worker's queue subject lane. Requests carrying
+ /// `X-SIE-MACHINE-PROFILE` constrain route resolution to this value.
+ /// Required. Helm sets it explicitly from the worker pool's
+ /// machineProfile.
#[arg(long, env = "SIE_MACHINE_PROFILE")]
- machine_profile: Option<String>,
+ machine_profile: String,
/// GPU count surfaced in heartbeats. Informational; the
/// gateway coerces 0 to 1. Defaults to 1.
@@ -143,17 +143,13 @@ async fn main() -> anyhow::Result<()> {
init_tracing();
let cli = Cli::parse();
- let pool = cli.pool;
- // Default machine_profile to the pool name: in practice every
- // existing helm pool we operate (`l4`, `a100`, `h100`) is named
- // after its GPU SKU, and the gateway compares the field
- // case-insensitively. Operators with a non-conventional pool
- // (`mixed-spot-1`) can override via `SIE_MACHINE_PROFILE`.
- let machine_profile = cli.machine_profile.unwrap_or_else(|| pool.clone());
+ let pool = validate_lane_segment("SIE_POOL", cli.pool)?;
+ let bundle = validate_lane_segment("SIE_BUNDLE", cli.bundle)?;
+ let machine_profile = validate_lane_segment("SIE_MACHINE_PROFILE", cli.machine_profile)?;
let config = WorkerConfig {
nats_url: cli.nats_url,
pool,
- bundle: cli.bundle,
+ bundle,
ipc_socket_path: cli.ipc_socket_path.into(),
ipc_pool_size: cli
.ipc_pool_size
@@ -211,6 +207,20 @@ fn init_tracing() {
fmt().with_env_filter(filter).json().init();
}
+fn validate_lane_segment(name: &str, raw: String) -> anyhow::Result<String> {
+ let value = raw.trim();
+ if value.is_empty() {
+ anyhow::bail!("{name} must not be empty");
+ }
+ if value
+ .chars()
+ .any(|c| c.is_whitespace() || matches!(c, '.' | '*' | '>'))
+ {
+ anyhow::bail!("{name} must not contain '.', '*', '>', or whitespace");
+ }
+ Ok(value.to_string())
+}
+
fn env_bool_value(raw: Option<&str>, default: bool) -> bool {
let Some(raw) = raw else {
return default;
@@ -228,3 +238,23 @@ fn seconds_to_millis(seconds: f64, min_ms: u64) -> u64 {
}
((seconds * 1_000.0).round() as u64).max(min_ms)
}
+
+#[cfg(test)]
+mod tests {
+ use super::validate_lane_segment;
+
+ #[test]
+ fn validate_lane_segment_trims_valid_values() {
+ assert_eq!(
+ validate_lane_segment("SIE_POOL", " default-pool ".to_string()).unwrap(),
+ "default-pool"
+ );
+ }
+
+ #[test]
+ fn validate_lane_segment_rejects_subject_wildcards_and_dot_tokens() {
+ for raw in ["", " ", "foo.bar", "foo*", "foo>", "foo bar"] {
+ assert!(validate_lane_segment("SIE_POOL", raw.to_string()).is_err());
+ }
+ }
+}
diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rs
index 23d5719da..a7fd4e4e5 100644
--- a/packages/sie_server_sidecar/src/nats_consumer.rs
+++ b/packages/sie_server_sidecar/src/nats_consumer.rs
@@ -72,15 +72,16 @@ fn generation_stream_max_age_secs() -> u64 {
/// sweep only deletes consumers that have **zero** pull waiters
/// (`num_waiting == 0`) and **zero** in-flight acks
/// (`num_ack_pending == 0`). Default behaviour (env unset / `0`)
-/// keeps the historical aggressive delete because today's topology is
-/// one bundle per pool — flipping bundles on a pool must clobber the
-/// old durable for the new worker to bind.
+/// keeps the historical aggressive delete because a concrete
+/// `(pool, machine_profile, bundle)` lane must have one active durable
+/// owner. Bundle peers can now share the same pool stream safely because
+/// their lane filters do not overlap.
///
-/// Flip this on if you ever introduce a topology where two bundles
-/// legitimately share a pool stream with overlapping filters; we
-/// then refuse to delete a healthy peer consumer and let the
-/// authoritative `get_or_create_consumer` error surface so the
-/// operator can resolve the conflict explicitly.
+/// Flip this on if you ever introduce a topology where two consumers
+/// legitimately share overlapping lane filters; we then refuse to delete
+/// a healthy peer consumer and let the authoritative
+/// `get_or_create_consumer` error surface so the operator can resolve
+/// the conflict explicitly.
fn conservative_cleanup() -> bool {
std::env::var("SIE_NATS_CONSERVATIVE_CLEANUP")
.ok()
@@ -118,6 +119,51 @@ pub async fn connect(nats_url: &str) -> Result<(async_nats::Client, JsContext),
Ok((client, js))
}
+fn canonical_stream_subjects(observed: Vec<String>, desired: &str) -> Option<Vec<String>> {
+ if observed.len() == 1 && observed.first().is_some_and(|subject| subject == desired) {
+ None
+ } else {
+ Some(vec![desired.to_string()])
+ }
+}
+
+async fn reconcile_stream_subjects(
+ js: &JsContext,
+ stream: &mut JsStream,
+ stream_name: &str,
+ desired_subject: &str,
+) -> Result<(), NatsSetupError> {
+ let observed_subjects = stream.cached_info().config.subjects.clone();
+ let Some(updated_subjects) =
+ canonical_stream_subjects(observed_subjects.clone(), desired_subject)
+ else {
+ return Ok(());
+ };
+
+ let mut updated = stream.cached_info().config.clone();
+ updated.subjects = updated_subjects;
+ js.update_stream(updated)
+ .await
+ .map_err(|e| NatsSetupError::EnsureStream {
+ name: stream_name.to_string(),
+ source: e.into(),
+ })?;
+ *stream = js
+ .get_stream(stream_name)
+ .await
+ .map_err(|e| NatsSetupError::EnsureStream {
+ name: stream_name.to_string(),
+ source: e.into(),
+ })?;
+ info!(
+ stream = %stream_name,
+ observed_subjects = ?observed_subjects,
+ desired_subject = %desired_subject,
+ "reconciled NATS stream subjects to canonical queue lane routing"
+ );
+ Ok(())
+}
+
/// Predicate used by [`cleanup_overlapping_consumers`]. Returns true
/// iff any of the consumer's configured filter(s) overlaps the
/// worker's intended `desired_subject` per NATS wildcard semantics.
@@ -137,123 +183,71 @@ fn any_filter_overlaps(
.any(|s| subjects_overlap(s, desired_subject))
}
-fn is_legacy_per_model_work_stream(stream_name: &str) -> bool {
- stream_name.starts_with("WORK_") && !stream_name.starts_with("WORK_POOL_")
-}
-
-fn legacy_stream_overlaps_pool(
- stream_name: &str,
- subjects: &[String],
- desired_stream_name: &str,
+fn consumer_filter_matches_desired(
+ primary_filter: &str,
+ multi_filters: &[String],
desired_subject: &str,
) -> bool {
- stream_name != desired_stream_name
- && is_legacy_per_model_work_stream(stream_name)
- && subjects
- .iter()
- .any(|subject| subjects_overlap(subject, desired_subject))
+ if primary_filter == desired_subject && multi_filters.is_empty() {
+ return true;
+ }
+ primary_filter.is_empty()
+ && multi_filters.len() == 1
+ && multi_filters.first().is_some_and(|s| s == desired_subject)
}
-fn legacy_stream_is_safe_to_delete(
- stream_name: &str,
- subjects: &[String],
- desired_stream_name: &str,
+async fn reconcile_same_name_consumer_filter(
+ stream: &JsStream,
+ mut consumer: PullConsumer,
+ consumer_name: &str,
desired_subject: &str,
- message_count: u64,
-) -> bool {
- message_count == 0
- && legacy_stream_overlaps_pool(stream_name, subjects, desired_stream_name, desired_subject)
-}
+ consumer_cfg: ConsumerConfig,
+) -> Result<PullConsumer, NatsSetupError> {
+ let Ok(info) = consumer.info().await else {
+ return Ok(consumer);
+ };
+ if consumer_filter_matches_desired(
+ &info.config.filter_subject,
+ &info.config.filter_subjects,
+ desired_subject,
+ ) {
+ return Ok(consumer);
+ }
-/// Best-effort: delete empty old per-model `WORK_<model>` streams whose
-/// subjects overlap the pool stream we are about to create.
-///
-/// Older Python adapter processes created one WorkQueue stream per model. The Rust
-/// sidecar creates one pool stream (`WORK_POOL_<pool>`) for
-/// `sie.work.*.<pool>`. NATS forbids overlapping WorkQueue streams, so a
-/// leftover per-model stream can prevent the new pool stream from being
-/// created. We only delete empty streams that match the old naming convention
-/// and overlap this pool's subject filter; non-empty streams must be drained
-/// or migrated explicitly so startup never drops queued work.
-async fn cleanup_legacy_per_model_streams(
- js: &JsContext,
- desired_stream_name: &str,
- desired_subject: &str,
-) {
- let mut listing = js.streams();
- let mut stale = Vec::new();
+ warn!(
+ stream = %stream.cached_info().config.name,
+ consumer = %consumer_name,
+ observed_filter_subject = %info.config.filter_subject,
+ observed_filter_subjects = ?info.config.filter_subjects,
+ desired_subject,
+ "durable consumer filter drift: updating same-name consumer to the current queue lane"
+ );
- loop {
- match listing.try_next().await {
- Ok(Some(info)) => {
- if legacy_stream_overlaps_pool(
- &info.config.name,
- &info.config.subjects,
- desired_stream_name,
- desired_subject,
- ) {
- if legacy_stream_is_safe_to_delete(
- &info.config.name,
- &info.config.subjects,
- desired_stream_name,
- desired_subject,
- info.state.messages,
- ) {
- stale.push((info.config.name, info.config.subjects));
- } else {
- warn!(
- stale_stream = %info.config.name,
- desired_stream = %desired_stream_name,
- desired_subject,
- messages = info.state.messages,
- subjects = ?info.config.subjects,
- "legacy per-model stream overlaps the pool stream but still has \
- queued messages; drain or migrate it before starting this sidecar"
- );
- }
+ match stream.update_consumer(consumer_cfg.clone()).await {
+ Ok(updated) => Ok(updated),
+ Err(update_error) => {
+ warn!(
+ stream = %stream.cached_info().config.name,
+ consumer = %consumer_name,
+ error = %update_error,
+ "durable consumer update failed; deleting and recreating stale same-name consumer"
+ );
+ stream.delete_consumer(consumer_name).await.map_err(|e| {
+ NatsSetupError::EnsureConsumer {
+ name: consumer_name.to_string(),
+ source: e.into(),
}
- }
- Ok(None) => break,
- Err(e) => {
- warn!(
- error = %e,
- desired_stream = %desired_stream_name,
- desired_subject,
- "listing streams failed during legacy per-model stream cleanup; \
- proceeding to pool stream creation"
- );
- return;
- }
- }
- }
-
- let mut deleted = 0usize;
- for (stream_name, subjects) in stale {
- warn!(
- stale_stream = %stream_name,
- desired_stream = %desired_stream_name,
- desired_subject,
- subjects = ?subjects,
- "deleting legacy per-model stream that overlaps the pool stream"
- );
- match js.delete_stream(&stream_name).await {
- Ok(_) => deleted += 1,
- Err(e) => warn!(
- stale_stream = %stream_name,
- error = %e,
- "failed to delete legacy per-model stream; pool stream creation may fail"
- ),
+ })?;
+ consumer = stream
+ .get_or_create_consumer(consumer_name, consumer_cfg)
+ .await
+ .map_err(|e| NatsSetupError::EnsureConsumer {
+ name: consumer_name.to_string(),
+ source: e.into(),
+ })?;
+ Ok(consumer)
}
}
-
- if deleted > 0 {
- info!(
- desired_stream = %desired_stream_name,
- desired_subject,
- deleted,
- "deleted legacy per-model streams before pool stream creation"
- );
- }
}
/// Best-effort: remove any durable consumer on `stream` whose name is
@@ -367,8 +361,9 @@ pub async fn reconcile_stream_and_consumer(
/// Ensure the worker-specific stream used by generation direct-dispatch.
///
/// The gateway publishes direct generation work to
-/// `sie.work.{model}.{pool}.{worker_id}`. That subject intentionally does
-/// not match the pool stream (`sie.work.*.{pool}`), so the sidecar must
+/// `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`. That
+/// subject intentionally does not match the pool stream
+/// (`sie.work.{pool}.*.*.*`), so the sidecar must
/// bind this second stream for generation to avoid relying solely on
/// first-chunk fallback republish to the pool.
pub async fn ensure_worker_stream_and_consumer(
@@ -394,13 +389,14 @@ pub async fn ensure_worker_stream_and_consumer(
let desired_ack_wait = Duration::from_secs(GENERATION_ACK_WAIT_SECS);
let desired_max_deliver = max_deliver();
let desired_max_ack_pending = max_ack_pending();
- let stream =
+ let mut stream =
js.get_or_create_stream(stream_cfg)
.await
.map_err(|e| NatsSetupError::EnsureStream {
name: stream_name.clone(),
source: e.into(),
})?;
+ reconcile_stream_subjects(js, &mut stream, &stream_name, &subject).await?;
cleanup_overlapping_consumers(&stream, &consumer_name, &subject).await;
@@ -420,6 +416,22 @@ pub async fn ensure_worker_stream_and_consumer(
name: consumer_name.clone(),
source: e.into(),
})?;
+ let consumer = reconcile_same_name_consumer_filter(
+ &stream,
+ consumer,
+ &consumer_name,
+ &subject,
+ ConsumerConfig {
+ durable_name: Some(consumer_name.clone()),
+ filter_subject: subject.clone(),
+ ack_policy: AckPolicy::Explicit,
+ ack_wait: desired_ack_wait,
+ max_deliver: desired_max_deliver,
+ max_ack_pending: desired_max_ack_pending,
+ ..Default::default()
+ },
+ )
+ .await?;
info!(
stream = %stream_name,
consumer = %consumer_name,
@@ -445,12 +457,13 @@ async fn ensure_stream_and_consumer_inner(
log_success_at_info: bool,
) -> Result<PullConsumer, NatsSetupError> {
let stream_name = config.stream_name();
+ let stream_subject = config.stream_subject_filter();
let subject = config.subject_filter();
let consumer_name = config.consumer_name();
let stream_cfg = StreamConfig {
name: stream_name.clone(),
- subjects: vec![subject.clone()],
+ subjects: vec![stream_subject.clone()],
retention: RetentionPolicy::WorkQueue,
storage: StorageType::Memory,
max_age: Duration::from_secs(stream_max_age_secs()),
@@ -465,20 +478,23 @@ async fn ensure_stream_and_consumer_inner(
let desired_max_ack_pending = max_ack_pending();
let desired_ack_wait = Duration::from_secs(ACK_WAIT_SECS);
- cleanup_legacy_per_model_streams(js, &stream_name, &subject).await;
-
- let stream =
+ let mut stream =
js.get_or_create_stream(stream_cfg)
.await
.map_err(|e| NatsSetupError::EnsureStream {
name: stream_name.clone(),
source: e.into(),
})?;
+ reconcile_stream_subjects(js, &mut stream, &stream_name, &stream_subject).await?;
// `get_or_create_stream` is a no-op against an EXISTING stream with a
- // different config (the first writer's config wins). If the gateway
- // and the worker disagree on `max_age`, retries may be purged before
- // `max_deliver` is reached — silent data loss. Warn so ops can tell.
+ // different config (the first writer's config wins). We reconcile
+ // subject filters above to the canonical lane-aware shape. This is a
+ // cutover, not a mixed-version bridge: old subjects are intentionally
+ // removed from the stream config. Other config drift (such as max_age)
+ // is still warned below: if the gateway and the worker disagree on
+ // `max_age`, retries may be purged before `max_deliver` is reached —
+ // silent data loss.
let observed_max_age = stream.cached_info().config.max_age;
if observed_max_age != desired_max_age {
warn!(
@@ -491,13 +507,12 @@ async fn ensure_stream_and_consumer_inner(
);
}
- // Self-heal stale durables left behind by a prior bundle deploy on
- // this pool. Without this, NATS rejects our consumer create with
- // `consumer filter subject overlaps with X` and the worker
- // CrashLoops until an operator runs `nats consumer rm` by hand.
- // Concretely: a previous deploy may leave `<old-bundle>_l4`
- // filtering on `sie.work.*.l4` while the new `<new-bundle>_l4`
- // wants the same filter.
+ // Self-heal stale durables whose filters overlap this concrete
+ // `(pool, machine_profile, bundle)` lane. Without this, NATS rejects
+ // our consumer create with `consumer filter subject overlaps with X`
+ // and the worker CrashLoops until an operator removes the stale
+ // durable. Different bundles in the same pool no longer overlap
+ // because the bundle is now a subject token.
cleanup_overlapping_consumers(&stream, &consumer_name, &subject).await;
let consumer_cfg = ConsumerConfig {
@@ -517,6 +532,22 @@ async fn ensure_stream_and_consumer_inner(
name: consumer_name.clone(),
source: e.into(),
})?;
+ consumer = reconcile_same_name_consumer_filter(
+ &stream,
+ consumer,
+ &consumer_name,
+ &subject,
+ ConsumerConfig {
+ durable_name: Some(consumer_name.clone()),
+ filter_subject: subject.clone(),
+ ack_policy: AckPolicy::Explicit,
+ ack_wait: desired_ack_wait,
+ max_deliver: desired_max_deliver,
+ max_ack_pending: desired_max_ack_pending,
+ ..Default::default()
+ },
+ )
+ .await?;
// Same drift warning for the durable consumer. `get_or_create_consumer`
// inherits the existing durable's config; new tuning here is silently
@@ -617,6 +648,36 @@ mod tests {
assert_eq!(STREAM_MAX_MSGS, 100_000);
}
+ #[test]
+ fn canonical_stream_subjects_replaces_legacy_subject() {
+ let observed = vec!["sie.work.*.default".to_string()];
+ assert_eq!(
+ canonical_stream_subjects(observed, "sie.work.default.*.*.*"),
+ Some(vec!["sie.work.default.*.*.*".to_string()])
+ );
+ }
+
+ #[test]
+ fn canonical_stream_subjects_drops_extra_subjects() {
+ let observed = vec![
+ "sie.work.*.default".to_string(),
+ "sie.work.other.*.*.*".to_string(),
+ ];
+ assert_eq!(
+ canonical_stream_subjects(observed, "sie.work.default.*.*.*"),
+ Some(vec!["sie.work.default.*.*.*".to_string()])
+ );
+ }
+
+ #[test]
+ fn canonical_stream_subjects_noops_when_exact() {
+ let observed = vec!["sie.work.default.*.*.*".to_string()];
+ assert_eq!(
+ canonical_stream_subjects(observed, "sie.work.default.*.*.*"),
+ None
+ );
+ }
+
#[test]
fn env_free_accessors_match_defaults() {
// Env-free calls must return the hardcoded defaults. We do not
@@ -665,8 +726,9 @@ mod tests {
health_publish_interval_ms: 5_000,
};
assert_eq!(cfg.stream_name(), "WORK_POOL_default");
- assert_eq!(cfg.consumer_name(), "b_default");
- assert_eq!(cfg.subject_filter(), "sie.work.*.default");
+ assert_eq!(cfg.consumer_name(), "default_default_b");
+ assert_eq!(cfg.stream_subject_filter(), "sie.work.default.*.*.*");
+ assert_eq!(cfg.subject_filter(), "sie.work.default.default.b.*");
}
// Connect/ensure tests need a live NATS and are covered by integration
@@ -674,113 +736,103 @@ mod tests {
#[allow(dead_code)]
fn _compile_check(_js: &JsContext, _cfg: &WorkerConfig) {}
- // ----- legacy per-model stream cleanup predicate --------------------------
+ // ----- stale-durable predicate -------------------------------------------
#[test]
- fn legacy_stream_cleanup_targets_overlapping_per_model_streams() {
- let subjects = vec!["sie.work.BAAI__bge-m3.l4".to_string()];
- assert!(legacy_stream_overlaps_pool(
- "WORK_BAAI__bge-m3",
- &subjects,
- "WORK_POOL_l4",
- "sie.work.*.l4"
- ));
- assert!(legacy_stream_is_safe_to_delete(
- "WORK_BAAI__bge-m3",
- &subjects,
- "WORK_POOL_l4",
- "sie.work.*.l4",
- 0
- ));
+ fn any_filter_overlaps_detects_same_lane_collision() {
+ // Same pool + machine profile + bundle must overlap: replicas of
+ // one StatefulSet intentionally share one durable consumer.
+ let stale_filter = "sie.work.default.rtx6000.sglang.*";
+ let desired = "sie.work.default.rtx6000.sglang.*";
+ assert!(any_filter_overlaps(stale_filter, &[], desired));
}
#[test]
- fn legacy_stream_cleanup_does_not_auto_delete_non_empty_streams() {
- let subjects = vec!["sie.work.BAAI__bge-m3.l4".to_string()];
- assert!(!legacy_stream_is_safe_to_delete(
- "WORK_BAAI__bge-m3",
- &subjects,
- "WORK_POOL_l4",
- "sie.work.*.l4",
- 1
+ fn any_filter_overlaps_allows_different_bundles_in_same_pool() {
+ // The queue-pool fix: default and sglang can share logical pool
+ // `default` and machine profile `rtx6000` without overlapping.
+ assert!(!any_filter_overlaps(
+ "sie.work.default.rtx6000.default.*",
+ &[],
+ "sie.work.default.rtx6000.sglang.*"
));
}
#[test]
- fn legacy_stream_cleanup_ignores_pool_streams() {
- let subjects = vec!["sie.work.*.l4".to_string()];
- assert!(!legacy_stream_overlaps_pool(
- "WORK_POOL_l4",
- &subjects,
- "WORK_POOL_l4",
- "sie.work.*.l4"
- ));
- assert!(!legacy_stream_overlaps_pool(
- "WORK_POOL_other",
- &subjects,
- "WORK_POOL_l4",
- "sie.work.*.l4"
+ fn any_filter_overlaps_ignores_other_pools() {
+ // A `default_h100` consumer on a shared NATS account must not
+ // be deleted just because we're deploying `default_l4`.
+ assert!(!any_filter_overlaps(
+ "sie.work.default.h100.default.*",
+ &[],
+ "sie.work.default.l4.default.*"
));
}
#[test]
- fn legacy_stream_cleanup_ignores_non_overlapping_work_streams() {
- let subjects = vec!["sie.work.BAAI__bge-m3.h100".to_string()];
- assert!(!legacy_stream_overlaps_pool(
- "WORK_BAAI__bge-m3",
- &subjects,
- "WORK_POOL_l4",
- "sie.work.*.l4"
+ fn any_filter_overlaps_handles_filter_subjects_list() {
+ // Newer NATS consumers can use the multi-filter
+ // `filter_subjects` list (with `filter_subject` blank).
+ let multi = vec![
+ "sie.work.foo.h100.default.*".to_string(),
+ "sie.work.default.l4.default.*".to_string(),
+ ];
+ assert!(any_filter_overlaps(
+ "",
+ &multi,
+ "sie.work.default.l4.default.*"
+ ));
+
+ let multi_disjoint = vec![
+ "sie.work.foo.h100.default.*".to_string(),
+ "sie.work.eval-l4.l4.default.*".to_string(),
+ ];
+ assert!(!any_filter_overlaps(
+ "",
+ &multi_disjoint,
+ "sie.work.default.l4.default.*"
));
}
#[test]
- fn legacy_stream_cleanup_ignores_unrelated_stream_names() {
- let subjects = vec!["sie.work.BAAI__bge-m3.l4".to_string()];
- assert!(!legacy_stream_overlaps_pool(
- "ORDERS",
- &subjects,
- "WORK_POOL_l4",
- "sie.work.*.l4"
+ fn consumer_filter_matches_desired_primary_filter() {
+ assert!(consumer_filter_matches_desired(
+ "sie.work.default.rtx6000.sglang.*.worker-0",
+ &[],
+ "sie.work.default.rtx6000.sglang.*.worker-0"
));
}
- // ----- stale-durable predicate -------------------------------------------
-
#[test]
- fn any_filter_overlaps_detects_bundle_flip_collision() {
- // Real-world case: previous deploy left a `<stale-bundle>_l4`
- // consumer with filter `sie.work.*.l4`; new deploy wants
- // `default_l4` with the same filter. The cleanup pass must
- // mark the old one as overlapping.
- let stale_filter = "sie.work.*.l4";
- let desired = "sie.work.*.l4";
- assert!(any_filter_overlaps(stale_filter, &[], desired));
+ fn consumer_filter_matches_desired_single_multi_filter() {
+ let filters = vec!["sie.work.default.rtx6000.sglang.*.worker-0".to_string()];
+ assert!(consumer_filter_matches_desired(
+ "",
+ &filters,
+ "sie.work.default.rtx6000.sglang.*.worker-0"
+ ));
}
#[test]
- fn any_filter_overlaps_ignores_other_pools() {
- // A `default_h100` consumer on a shared NATS account must not
- // be deleted just because we're deploying `default_l4`.
- assert!(!any_filter_overlaps(
- "sie.work.*.h100",
+ fn consumer_filter_matches_desired_rejects_legacy_same_name_filter() {
+ assert!(!consumer_filter_matches_desired(
+ "sie.work.*.default.worker-0",
&[],
- "sie.work.*.l4"
+ "sie.work.default.rtx6000.sglang.*.worker-0"
));
}
#[test]
- fn any_filter_overlaps_handles_filter_subjects_list() {
- // Newer NATS consumers can use the multi-filter
- // `filter_subjects` list (with `filter_subject` blank).
- let multi = vec!["sie.work.foo.h100".to_string(), "sie.work.*.l4".to_string()];
- assert!(any_filter_overlaps("", &multi, "sie.work.*.l4"));
-
- let multi_disjoint = vec![
- "sie.work.foo.h100".to_string(),
- "sie.work.*.eval-l4".to_string(),
+ fn consumer_filter_matches_desired_rejects_extra_multi_filter() {
+ let filters = vec![
+ "sie.work.default.rtx6000.sglang.*.worker-0".to_string(),
+ "sie.work.default.rtx6000.default.*.worker-0".to_string(),
];
- assert!(!any_filter_overlaps("", &multi_disjoint, "sie.work.*.l4"));
+ assert!(!consumer_filter_matches_desired(
+ "",
+ &filters,
+ "sie.work.default.rtx6000.sglang.*.worker-0"
+ ));
}
#[test]
@@ -790,6 +842,10 @@ mod tests {
// creating that on a WorkQueue stream, so it shouldn't
// appear, but if it ever does we don't want to spuriously
// delete it.
- assert!(!any_filter_overlaps("", &[], "sie.work.*.l4"));
+ assert!(!any_filter_overlaps(
+ "",
+ &[],
+ "sie.work.default.l4.default.*"
+ ));
}
}
diff --git a/packages/sie_server_sidecar/src/pool_admission.rs b/packages/sie_server_sidecar/src/pool_admission.rs
index fbe29627a..3756670c7 100644
--- a/packages/sie_server_sidecar/src/pool_admission.rs
+++ b/packages/sie_server_sidecar/src/pool_admission.rs
@@ -201,12 +201,7 @@ impl PoolAdmissionGate {
}
fn normalize_pool_name(name: &str) -> String {
- let value = name.trim().to_ascii_lowercase();
- if value.is_empty() || value == "_default" {
- "default".to_string()
- } else {
- value
- }
+ name.trim().to_ascii_lowercase()
}
fn object_field<'a>(value: &'a Value, key: &str) -> Option<&'a Map<String, Value>> {
diff --git a/packages/sie_server_sidecar/src/subject.rs b/packages/sie_server_sidecar/src/subject.rs
index 2d23906fb..c52183fcd 100644
--- a/packages/sie_server_sidecar/src/subject.rs
+++ b/packages/sie_server_sidecar/src/subject.rs
@@ -1,12 +1,14 @@
//! NATS subject helpers — model-id normalisation + extraction.
//!
-//! Work subject format: `sie.work.{normalized_model_id}.{pool_name}`.
+//! Work subject format:
+//! `sie.work.{pool_name}.{machine_profile}.{bundle}.{normalized_model_id}`.
-/// Subject token index of the normalized model id (`sie.work.<MODEL>.pool`).
-const MODEL_TOKEN_INDEX: usize = 2;
+/// Subject token index of the normalized model id
+/// (`sie.work.<POOL>.<MACHINE>.<BUNDLE>.<MODEL>`).
+const MODEL_TOKEN_INDEX: usize = 5;
/// Minimum number of dot-delimited tokens a valid work subject must have.
-const MIN_SUBJECT_PARTS: usize = 4;
+const MIN_SUBJECT_PARTS: usize = 6;
/// Inverse of [`normalize_model_id`]. Best-effort: `__` → `/`, `_dot_` → `.`.
pub fn denormalize_model_id(normalized: &str) -> String {
@@ -22,7 +24,7 @@ pub fn normalize_model_id(model_id: &str) -> String {
}
/// Extract and denormalise the model id from a work subject.
-/// Returns `None` for malformed subjects (fewer than 4 tokens).
+/// Returns `None` for malformed subjects (fewer than 6 tokens).
pub fn extract_model_id(subject: &str) -> Option<String> {
let parts: Vec<&str> = subject.split('.').collect();
if parts.len() < MIN_SUBJECT_PARTS {
@@ -101,11 +103,11 @@ mod tests {
#[test]
fn extract_from_valid_subject() {
assert_eq!(
- extract_model_id("sie.work.BAAI__bge-m3.l4"),
+ extract_model_id("sie.work.default.rtx6000.default.BAAI__bge-m3"),
Some("BAAI/bge-m3".to_string())
);
assert_eq!(
- extract_model_id("sie.work.a_dot_b.default"),
+ extract_model_id("sie.work.eval-l4.l4.sglang.a_dot_b"),
Some("a.b".to_string())
);
}
@@ -115,28 +117,28 @@ mod tests {
assert_eq!(extract_model_id(""), None);
assert_eq!(extract_model_id("sie.work"), None);
assert_eq!(extract_model_id("sie.work.model"), None);
+ assert_eq!(extract_model_id("sie.work.default.l4.default"), None);
}
// ----- subjects_overlap ---------------------------------------------------
#[test]
fn overlap_identical_filters_with_wildcard_overlap() {
- // The exact case that wedged the GKE worker on bundle flips:
- // two consumers (e.g. `default_l4` from a new deploy and a
- // stale durable left behind by a previous bundle) both
- // filtered on this string.
- assert!(subjects_overlap("sie.work.*.l4", "sie.work.*.l4"));
+ assert!(subjects_overlap(
+ "sie.work.default.rtx6000.sglang.*",
+ "sie.work.default.rtx6000.sglang.*"
+ ));
}
#[test]
fn overlap_wildcard_vs_literal_in_same_slot() {
assert!(subjects_overlap(
- "sie.work.*.l4",
- "sie.work.BAAI__bge-m3.l4"
+ "sie.work.default.rtx6000.sglang.*",
+ "sie.work.default.rtx6000.sglang.BAAI__bge-m3"
));
assert!(subjects_overlap(
- "sie.work.BAAI__bge-m3.l4",
- "sie.work.*.l4"
+ "sie.work.default.rtx6000.sglang.BAAI__bge-m3",
+ "sie.work.default.rtx6000.sglang.*"
));
}
@@ -145,23 +147,41 @@ mod tests {
// Different pools → distinct streams in practice, but the
// predicate must still report no overlap so it's safe to call
// even on cross-stream listings.
- assert!(!subjects_overlap("sie.work.*.l4", "sie.work.*.h100"));
- assert!(!subjects_overlap("sie.work.foo.l4", "sie.work.foo.eval-l4"));
+ assert!(!subjects_overlap(
+ "sie.work.default.l4.default.*",
+ "sie.work.default.h100.default.*"
+ ));
+ assert!(!subjects_overlap(
+ "sie.work.default.rtx6000.default.*",
+ "sie.work.default.rtx6000.sglang.*"
+ ));
}
#[test]
fn overlap_different_lengths_without_gt_do_not_overlap() {
- assert!(!subjects_overlap("sie.work.*.l4", "sie.work.*.l4.extra"));
- assert!(!subjects_overlap("sie.work.*", "sie.work.*.l4"));
+ assert!(!subjects_overlap(
+ "sie.work.default.l4.default.*",
+ "sie.work.default.l4.default.*.extra"
+ ));
+ assert!(!subjects_overlap(
+ "sie.work.default.*",
+ "sie.work.default.l4.default.*"
+ ));
}
#[test]
fn overlap_gt_swallows_trailing_tokens() {
// `>` must match AT LEAST one trailing token, so it overlaps
// with longer filters but not with one of equal length.
- assert!(subjects_overlap("sie.work.>", "sie.work.foo.l4"));
- assert!(subjects_overlap("sie.work.foo.l4", "sie.work.>"));
- assert!(subjects_overlap("sie.>", "sie.work.*.l4"));
+ assert!(subjects_overlap(
+ "sie.work.>",
+ "sie.work.default.l4.default.foo"
+ ));
+ assert!(subjects_overlap(
+ "sie.work.default.l4.default.foo",
+ "sie.work.>"
+ ));
+ assert!(subjects_overlap("sie.>", "sie.work.default.l4.default.*"));
assert!(!subjects_overlap("sie.work.>", "sie.work"));
assert!(!subjects_overlap("sie.>", "nats.work.*.l4"));
}
@@ -174,7 +194,7 @@ mod tests {
#[test]
fn overlap_empty_inputs_are_safe() {
- assert!(!subjects_overlap("", "sie.work.*.l4"));
- assert!(!subjects_overlap("sie.work.*.l4", ""));
+ assert!(!subjects_overlap("", "sie.work.default.l4.default.*"));
+ assert!(!subjects_overlap("sie.work.default.l4.default.*", ""));
}
}
diff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rs
index 9ead74539..12cdca951 100644
--- a/packages/sie_server_sidecar/tests/integration_smoke.rs
+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs
@@ -49,6 +49,33 @@ async fn smoke_test_guard() -> OwnedSemaphorePermit {
.expect("smoke test semaphore is open")
}
+fn pool_work_subject(pool: &str, machine_profile: &str, bundle: &str, model_id: &str) -> String {
+ format!(
+ "sie.work.{}.{}.{}.{}",
+ pool,
+ normalize_model_id(machine_profile),
+ normalize_model_id(bundle),
+ normalize_model_id(model_id)
+ )
+}
+
+fn worker_work_subject(
+ pool: &str,
+ machine_profile: &str,
+ bundle: &str,
+ model_id: &str,
+ worker_id: &str,
+) -> String {
+ format!(
+ "sie.work.{}.{}.{}.{}.{}",
+ pool,
+ normalize_model_id(machine_profile),
+ normalize_model_id(bundle),
+ normalize_model_id(model_id),
+ normalize_model_id(worker_id)
+ )
+}
+
// ---------------------------------------------------------------------------
// Skip helpers — keep the test happy on bare-bones dev machines
// ---------------------------------------------------------------------------
@@ -471,6 +498,7 @@ impl WorkerHarness {
let mut cmd = Command::new(exe);
cmd.env("SIE_NATS_URL", nats_url)
.env("SIE_POOL", pool)
+ .env("SIE_MACHINE_PROFILE", pool)
.env("SIE_BUNDLE", bundle)
.env("SIE_IPC_SOCKET_PATH", ipc_socket)
.env("SIE_WORKER_METRICS_PORT", metrics_port.to_string())
@@ -568,8 +596,7 @@ async fn smoke_encode_request_round_trips_through_rust_worker() {
// 6. Publish a synthetic encode WorkItem on the pool subject.
let model_id = "BAAI/bge-m3";
- let normalized = "BAAI__bge-m3";
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
let request_id = "smoke-req-1";
// Stamp `timestamp` at `now - 0.25s` so the worker sees a realistic
@@ -588,7 +615,7 @@ async fn smoke_encode_request_round_trips_through_rust_worker() {
profile_id: String::new(),
engine: String::new(),
pool_name: pool.into(),
- machine_profile: "cpu".into(),
+ machine_profile: pool.into(),
item: Some(serde_json::json!({"text": "hello rust worker"})),
payload_ref: None,
output_types: Some(vec!["dense".into()]),
@@ -744,12 +771,7 @@ async fn smoke_generate_direct_dispatch_round_trips_through_rust_worker() {
.expect("subscribe reply");
let request_id = "smoke-generate-1";
- let subject = format!(
- "sie.work.{}.{}.{}",
- normalize_model_id(model_id),
- pool,
- normalize_model_id("smoke-worker"),
- );
+ let subject = worker_work_subject(pool, pool, bundle, model_id, "smoke-worker");
let now_s = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
@@ -764,7 +786,7 @@ async fn smoke_generate_direct_dispatch_round_trips_through_rust_worker() {
profile_id: String::new(),
engine: String::new(),
pool_name: pool.into(),
- machine_profile: "cpu".into(),
+ machine_profile: pool.into(),
item: None,
payload_ref: None,
output_types: None,
@@ -890,12 +912,7 @@ async fn smoke_generation_direct_dispatch_activates_after_capability_reconcile()
.expect("subscribe reply");
let request_id = "smoke-generate-hot-add-1";
- let subject = format!(
- "sie.work.{}.{}.{}",
- normalize_model_id(model_id),
- pool,
- normalize_model_id("smoke-worker"),
- );
+ let subject = worker_work_subject(pool, pool, bundle, model_id, "smoke-worker");
let now_s = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
@@ -910,7 +927,7 @@ async fn smoke_generation_direct_dispatch_activates_after_capability_reconcile()
profile_id: String::new(),
engine: String::new(),
pool_name: pool.into(),
- machine_profile: "cpu".into(),
+ machine_profile: pool.into(),
item: None,
payload_ref: None,
output_types: None,
@@ -1048,8 +1065,7 @@ async fn smoke_payload_ref_request_round_trips_through_rust_worker() {
.expect("subscribe reply");
let model_id = "BAAI/bge-m3";
- let normalized = "BAAI__bge-m3";
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
let now_s = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
@@ -1064,7 +1080,7 @@ async fn smoke_payload_ref_request_round_trips_through_rust_worker() {
profile_id: String::new(),
engine: String::new(),
pool_name: pool.into(),
- machine_profile: "cpu".into(),
+ machine_profile: pool.into(),
item: None,
payload_ref: Some(payload_ref.clone()),
output_types: Some(vec!["dense".into()]),
@@ -1232,7 +1248,7 @@ async fn publish_work_item(
profile_id: String::new(),
engine: String::new(),
pool_name: pool.into(),
- machine_profile: "cpu".into(),
+ machine_profile: pool.into(),
item: Some(serde_json::json!({"text": format!("concurrent-{request_id}")})),
payload_ref: None,
output_types: Some(vec!["dense".into()]),
@@ -1307,7 +1323,7 @@ async fn pool_admission_pauses_until_gateway_assigns_worker() {
let model_id = "BAAI/bge-m3";
let normalized = "BAAI__bge-m3";
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
publish_work_item(
&js,
&subject,
@@ -1381,7 +1397,7 @@ async fn stress_concurrent_requests_do_not_stall_on_ack_wait() {
let model_id = "BAAI/bge-m3";
let normalized = "BAAI__bge-m3";
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
// One subscription per request on a unique inbox; collect all N in a
// concurrent `JoinSet` so the publishes are temporally clustered.
@@ -1501,7 +1517,7 @@ async fn stress_sustained_load_finishes_within_budget() {
let model_id = "BAAI/bge-m3";
let normalized = "BAAI__bge-m3";
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
let mut join = tokio::task::JoinSet::new();
let start = Instant::now();
@@ -1742,7 +1758,7 @@ async fn pool_enables_concurrent_in_flight_ipc() {
.subscribe(reply_subject.clone())
.await
.expect("subscribe reply");
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
let model_id = (*model_id).to_string();
let normalized = (*normalized).to_string();
let pool = pool.to_string();
@@ -1893,7 +1909,6 @@ async fn smoke_prepared_tokens_round_trip_through_rust_worker() {
// max_seq_len (64) so we can assert it round-trips through
// PreparedTokens.max_seq_len.
let model_id = "tiny-prepared-tokens";
- let normalized = "tiny-prepared-tokens"; // no slash to normalize
let pool = "smoke-pt";
let bundle = "default";
let metrics_port = find_free_tcp_port();
@@ -1917,7 +1932,7 @@ async fn smoke_prepared_tokens_round_trip_through_rust_worker() {
// 4. Publish a plain-text encode WorkItem that satisfies the
// Rust-tokenisation safety rules (text-only, no instruction,
// is_query = false) so the dispatcher actually pre-tokenizes.
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
let request_id = "smoke-pt-req-1";
let now_s = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -1933,7 +1948,7 @@ async fn smoke_prepared_tokens_round_trip_through_rust_worker() {
profile_id: String::new(),
engine: String::new(),
pool_name: pool.into(),
- machine_profile: "cpu".into(),
+ machine_profile: pool.into(),
item: Some(serde_json::json!({"text": "hello world"})),
payload_ref: None,
output_types: Some(vec!["dense".into()]),
@@ -2109,7 +2124,7 @@ async fn publish_score_work_item(
profile_id: String::new(),
engine: String::new(),
pool_name: pool.into(),
- machine_profile: "cpu".into(),
+ machine_profile: pool.into(),
item: None,
payload_ref: None,
output_types: None,
@@ -2159,7 +2174,7 @@ async fn publish_extract_work_item(
profile_id: String::new(),
engine: String::new(),
pool_name: pool.into(),
- machine_profile: "cpu".into(),
+ machine_profile: pool.into(),
item: Some(serde_json::json!({"text": "Barack Obama was born in Hawaii."})),
payload_ref: None,
output_types: None,
@@ -2221,8 +2236,7 @@ async fn smoke_scheduler_routes_score_request_end_to_end() {
let js = async_nats::jetstream::new(client.clone());
let model_id = "BAAI/bge-m3";
- let normalized = "BAAI__bge-m3";
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
let reply_subject = format!("_INBOX.sched-score.{}", uuid::Uuid::new_v4());
let mut sub = client
@@ -2297,8 +2311,7 @@ async fn smoke_scheduler_routes_extract_request_end_to_end() {
let js = async_nats::jetstream::new(client.clone());
let model_id = "BAAI/bge-m3";
- let normalized = "BAAI__bge-m3";
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
let reply_subject = format!("_INBOX.sched-extract.{}", uuid::Uuid::new_v4());
let mut sub = client
@@ -2383,7 +2396,7 @@ async fn smoke_scheduler_coalesces_concurrent_encodes() {
let model_id = "BAAI/bge-m3";
let normalized = "BAAI__bge-m3";
- let subject = format!("sie.work.{}.{}", normalized, pool);
+ let subject = pool_work_subject(pool, pool, bundle, model_id);
let mut join = tokio::task::JoinSet::new();
for i in 0..CONCURRENCY {
diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.json
index 082cbc917..660ea3810 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.5.0",
+ "version": "0.6.0",
"description": "Official TypeScript SDK for SIE (Search Inference Engine)",
"type": "module",
"main": "./dist/index.cjs",
@@ -75,7 +75,7 @@
"@types/node": "^22.19.19",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
- "vitest": "^2.1.9"
+ "vitest": "^4.1.0"
},
"pnpm": {
"overrides": {
diff --git a/packages/sie_ts_sdk/pnpm-lock.yaml b/packages/sie_ts_sdk/pnpm-lock.yaml
index 6518ff6e4..b29904a1c 100644
--- a/packages/sie_ts_sdk/pnpm-lock.yaml
+++ b/packages/sie_ts_sdk/pnpm-lock.yaml
@@ -35,8 +35,8 @@ importers:
specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.9
- version: 2.1.9(@types/[email protected])([email protected])
+ specifier: ^4.1.0
packages:
@@ -396,17 +396,26 @@ packages:
cpu: [x64]
os: [win32]
+ '@standard-schema/[email protected]':
+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
+
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
resolution: {integrity: sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==}
peerDependencies:
msw: ^2.4.9
vite: ^6.4.2
@@ -416,20 +425,20 @@ packages:
vite:
optional: true
- '@vitest/[email protected]':
- resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==}
resolution: {integrity: sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==}
@@ -453,14 +462,10 @@ packages:
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
+ resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==}
- engines: {node: '>= 16'}
-
resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}
engines: {node: '>= 14.16.0'}
@@ -476,6 +481,9 @@ packages:
resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}
engines: {node: ^14.18.0 || >=16.10.0}
+ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
+
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
@@ -485,16 +493,12 @@ packages:
supports-color:
optional: true
- resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
- engines: {node: '>=6'}
-
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
+ resolution: {integrity: sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==}
resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==}
@@ -615,9 +619,6 @@ packages:
resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
- resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}
-
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
@@ -639,16 +640,13 @@ packages:
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==}
+ resolution: {integrity: sha512-AWGB9WFcRXOQs48Z/udjI5ZcZMHXwX8XPByNpOydgcGsDLIzjGizhoMWJyKAWze7AVW/2W1i+/gPX4YtKe5cyg==}
+ engines: {node: '>=12.20.0'}
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
- resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
- engines: {node: '>= 14.16'}
-
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -722,8 +720,8 @@ packages:
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
- resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
+ resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}
resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}
@@ -743,6 +741,10 @@ packages:
resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
+ resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
engines: {node: '>=12.0.0'}
@@ -751,16 +753,8 @@ packages:
resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==}
engines: {node: '>=12.0.0'}
- resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
- engines: {node: ^18.0.0 || >=20.0.0}
-
- resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==}
- engines: {node: '>=14.0.0'}
-
- resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==}
+ resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
engines: {node: '>=14.0.0'}
@@ -800,11 +794,6 @@ packages:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
- resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==}
- engines: {node: ^18.0.0 || >=20.0.0}
- hasBin: true
-
resolution: {integrity: sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==}
engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
@@ -845,23 +834,39 @@ packages:
yaml:
optional: true
- resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==}
- engines: {node: ^18.0.0 || >=20.0.0}
+ resolution: {integrity: sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==}
+ engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
hasBin: true
peerDependencies:
'@edge-runtime/vm': '*'
- '@types/node': ^18.0.0 || >=20.0.0
- '@vitest/browser': 2.1.9
- '@vitest/ui': 2.1.9
+ '@opentelemetry/api': ^1.9.0
+ '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
+ '@vitest/browser-playwright': 4.1.8
+ '@vitest/browser-preview': 4.1.8
+ '@vitest/browser-webdriverio': 4.1.8
+ '@vitest/coverage-istanbul': 4.1.8
+ '@vitest/coverage-v8': 4.1.8
+ '@vitest/ui': 4.1.8
happy-dom: '*'
jsdom: '*'
+ vite: ^6.4.2
peerDependenciesMeta:
'@edge-runtime/vm':
optional: true
+ '@opentelemetry/api':
+ optional: true
'@types/node':
optional: true
- '@vitest/browser':
+ '@vitest/browser-playwright':
+ optional: true
+ '@vitest/browser-preview':
+ optional: true
+ '@vitest/browser-webdriverio':
+ optional: true
+ '@vitest/coverage-istanbul':
+ optional: true
+ '@vitest/coverage-v8':
optional: true
'@vitest/ui':
optional: true
@@ -1085,51 +1090,61 @@ snapshots:
'@rollup/[email protected]':
optional: true
+ '@standard-schema/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/deep-eql': 4.0.2
+ assertion-error: 2.0.1
+
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
dependencies:
undici-types: 6.21.0
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/spy': 2.1.9
- '@vitest/utils': 2.1.9
- chai: 5.3.3
- tinyrainbow: 1.2.0
-
+ '@standard-schema/spec': 1.1.0
+ '@types/chai': 5.2.3
+ '@vitest/spy': 4.1.8
+ '@vitest/utils': 4.1.8
+ chai: 6.2.2
+ tinyrainbow: 3.1.0
+
dependencies:
- '@vitest/spy': 2.1.9
+ '@vitest/spy': 4.1.8
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- tinyrainbow: 1.2.0
+ tinyrainbow: 3.1.0
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/utils': 2.1.9
- pathe: 1.1.2
+ '@vitest/utils': 4.1.8
+ pathe: 2.0.3
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/pretty-format': 2.1.9
+ '@vitest/pretty-format': 4.1.8
+ '@vitest/utils': 4.1.8
magic-string: 0.30.21
- pathe: 1.1.2
+ pathe: 2.0.3
- '@vitest/[email protected]':
- dependencies:
- tinyspy: 3.0.2
+ '@vitest/[email protected]': {}
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/pretty-format': 2.1.9
- loupe: 3.2.1
- tinyrainbow: 1.2.0
+ '@vitest/pretty-format': 4.1.8
+ convert-source-map: 2.0.0
+ tinyrainbow: 3.1.0
@@ -1144,15 +1159,7 @@ snapshots:
- dependencies:
- assertion-error: 2.0.1
- check-error: 2.1.1
- deep-eql: 5.0.2
- loupe: 3.2.1
- pathval: 2.0.1
-
dependencies:
@@ -1164,16 +1171,16 @@ snapshots:
+
dependencies:
ms: 2.1.3
-
optional: true
optionalDependencies:
@@ -1284,8 +1291,6 @@ snapshots:
-
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -1309,12 +1314,10 @@ snapshots:
-
@@ -1390,7 +1393,7 @@ snapshots:
dependencies:
@@ -1414,6 +1417,8 @@ snapshots:
+
dependencies:
fdir: 6.5.0([email protected])
@@ -1424,11 +1429,7 @@ snapshots:
fdir: 6.5.0([email protected])
picomatch: 4.0.4
-
-
@@ -1468,27 +1469,6 @@ snapshots:
- dependencies:
- cac: 6.7.14
- debug: 4.4.3
- es-module-lexer: 1.7.0
- pathe: 1.1.2
- vite: 6.4.2(@types/[email protected])([email protected])
- transitivePeerDependencies:
- - '@types/node'
- - jiti
- - less
- - lightningcss
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- - tsx
- - yaml
-
dependencies:
esbuild: 0.27.2
@@ -1502,43 +1482,32 @@ snapshots:
fsevents: 2.3.3
lightningcss: 1.32.0
dependencies:
- '@vitest/expect': 2.1.9
- '@vitest/mocker': 2.1.9([email protected](@types/[email protected])([email protected]))
- '@vitest/pretty-format': 2.1.9
- '@vitest/runner': 2.1.9
- '@vitest/snapshot': 2.1.9
- '@vitest/spy': 2.1.9
- '@vitest/utils': 2.1.9
- chai: 5.3.3
- debug: 4.4.3
+ '@vitest/expect': 4.1.8
+ '@vitest/mocker': 4.1.8([email protected](@types/[email protected])([email protected]))
+ '@vitest/pretty-format': 4.1.8
+ '@vitest/runner': 4.1.8
+ '@vitest/snapshot': 4.1.8
+ '@vitest/spy': 4.1.8
+ '@vitest/utils': 4.1.8
+ es-module-lexer: 2.1.0
expect-type: 1.3.0
magic-string: 0.30.21
- pathe: 1.1.2
- std-env: 3.10.0
+ obug: 2.1.2
+ pathe: 2.0.3
+ picomatch: 4.0.4
+ std-env: 4.1.0
tinybench: 2.9.0
- tinyexec: 0.3.2
- tinypool: 1.1.1
- tinyrainbow: 1.2.0
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.16
+ tinyrainbow: 3.1.0
- vite-node: 2.1.9(@types/[email protected])([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 22.19.19
transitivePeerDependencies:
- - jiti
- - less
- - lightningcss
- msw
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- - tsx
- - yaml
dependencies:
diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.ts
index bd3bd8599..8b18ba9e6 100644
--- a/packages/sie_ts_sdk/src/version.ts
+++ b/packages/sie_ts_sdk/src/version.ts
@@ -1 +1 @@
-export const SDK_VERSION = "0.5.0"; // x-release-please-version
+export const SDK_VERSION = "0.6.0"; // x-release-please-version
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 267b644e3..96aafd6da 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -13,6 +13,7 @@ overrides:
tar: '>=7.5.11'
uuid: '>=11.1.1'
vite: ^6.4.2
+ vitest: ^4.1.0
ws: '>=8.20.1'
importers:
@@ -42,8 +43,8 @@ importers:
specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.9
- version: 2.1.9(@types/[email protected])([email protected])
+ specifier: ^4.1.0
integrations/sie_ts_lancedb:
dependencies:
@@ -67,8 +68,8 @@ importers:
specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.9
- version: 2.1.9(@types/[email protected])([email protected])
+ specifier: ^4.1.0
integrations/sie_ts_langchain:
dependencies:
@@ -89,8 +90,8 @@ importers:
specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.9
- version: 2.1.9(@types/[email protected])([email protected])
+ specifier: ^4.1.0
integrations/sie_ts_llamaindex:
dependencies:
@@ -103,7 +104,7 @@ importers:
version: 1.9.4
llamaindex:
specifier: ^0.8.37
tsup:
specifier: ^8.5.1
@@ -111,8 +112,8 @@ importers:
specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.9
- version: 2.1.9(@types/[email protected])([email protected])
+ specifier: ^4.1.0
packages/sie_ts_sdk:
dependencies:
@@ -136,8 +137,8 @@ importers:
specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.9
- version: 2.1.9(@types/[email protected])([email protected])
+ specifier: ^4.1.0
packages:
@@ -1305,15 +1306,24 @@ packages:
'@so-ric/[email protected]':
resolution: {integrity: sha512-/KiKkpHNOBgkFJwu9sh48LkHSMYGyuTcSFK/qMBdnOAlrRJzRSXAOFB5qwzaVQuDl8wAvHVMkaASQDReTahxuw==}
+ '@standard-schema/[email protected]':
+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
+
resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
+
resolution: {integrity: sha512-uv0aG6R0Y8WHZLTamZwtfsDLVRnOa+n+n5rEvFWL5Na5gZ8V2Teab/duDPFzIIIhs9qizDpcavCusCLJZu62Kw==}
resolution: {integrity: sha512-BwR5KP3Es/CSht0xqBcUXS3qCAUVXwpRKsV2+arxeb65atasuXG9LykC9Ab10Cw3s2raH92ZqOeILaQbsB2ACg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
+
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
@@ -1366,11 +1376,11 @@ packages:
'@upstash/[email protected]':
resolution: {integrity: sha512-yXsWKeuHNYyH72BcSZd3bV5ZD5MybAoTvKxkMaeV2UzuGfNzbHBVh5eO+ysTWTFAf8I9XcOueF4tZfAGjCa4Iw==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==}
peerDependencies:
msw: ^2.4.9
vite: ^6.4.2
@@ -1380,20 +1390,20 @@ packages:
vite:
optional: true
- '@vitest/[email protected]':
- resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==}
'@vladfrangu/[email protected]':
resolution: {integrity: sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==}
@@ -1634,8 +1644,8 @@ packages:
resolution: {integrity: sha512-ItanGBMrmRV7Py2Z+Xhs7cT+FNt5K0vPL4p9EZ/UX/Mu7hFbkxSjKF2KVtPwX7UYWp7dRKnrTvReflgrItJbdw==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
+ resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
engines: {node: '>=18'}
@@ -1646,10 +1656,6 @@ packages:
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
- engines: {node: '>= 16'}
-
resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}
engines: {node: '>= 14.16.0'}
@@ -1773,6 +1779,9 @@ packages:
resolution: {integrity: sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==}
+ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
+
resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}
@@ -1806,10 +1815,6 @@ packages:
resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
- engines: {node: '>=6'}
-
resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==}
engines: {node: '>=4.0.0'}
@@ -1905,8 +1910,8 @@ packages:
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
+ resolution: {integrity: sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==}
resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}
@@ -2426,9 +2431,6 @@ packages:
resolution: {integrity: sha512-RefILVDQ4DKoRZsJ4Pj22TxE3omDO47yFpkIBoDKzkqPRISs5U1cnAdg/5583YPkWPaLIYHOKRMQSvjFsO26cw==}
- resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}
-
resolution: {integrity: sha512-ERJq3FOzJTxBbFjZ7iDs+NiK4VI9Wz+RdrrAB8dio1oV+YvdPzUEE4QNiT2VD51DkIbCYRUUzCRkssXCHqSnKQ==}
engines: {node: 14 || >=16.14}
@@ -2641,6 +2643,10 @@ packages:
resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-AWGB9WFcRXOQs48Z/udjI5ZcZMHXwX8XPByNpOydgcGsDLIzjGizhoMWJyKAWze7AVW/2W1i+/gPX4YtKe5cyg==}
+ engines: {node: '>=12.20.0'}
+
resolution: {integrity: sha512-lTFqTf9bo7Cd3hpF6CviBe/DEhewjoZYd9N/uCe7O20qYTvGqrNOFOBDj3lbZgFWHUgDv5EeyusYxsZSLS8nvg==}
@@ -2734,10 +2740,6 @@ packages:
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
- resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
- engines: {node: '>= 14.16'}
-
resolution: {integrity: sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ==}
@@ -3093,8 +3095,8 @@ packages:
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
- resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
+ resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}
resolution: {integrity: sha512-VvNG1K72Po/xwJzxZFnZ++Tbrv4lwSptsbkFuzXCJAYZvCK5nnxsvXU6ajqkv7chyiI1Y0YXq2Jh8Iy8Y7NF/A==}
@@ -3179,20 +3181,16 @@ packages:
resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
+ resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==}
engines: {node: '>=12.0.0'}
- resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
- engines: {node: ^18.0.0 || >=20.0.0}
-
- resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==}
- engines: {node: '>=14.0.0'}
-
- resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==}
+ resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
engines: {node: '>=14.0.0'}
@@ -3324,11 +3322,6 @@ packages:
resolution: {integrity: sha512-cXEIW6cfr15lFv563k4GuVuW/fiwjknytD37jIOLSdSWuOI6WnO/oKwmP2FQTU2l01LP8/M5TSAJpzUaGe3uWg==}
- resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==}
- engines: {node: ^18.0.0 || >=20.0.0}
- hasBin: true
-
resolution: {integrity: sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==}
engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
@@ -3369,23 +3362,39 @@ packages:
yaml:
optional: true
- resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==}
- engines: {node: ^18.0.0 || >=20.0.0}
+ resolution: {integrity: sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==}
+ engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
hasBin: true
peerDependencies:
'@edge-runtime/vm': '*'
- '@types/node': ^18.0.0 || >=20.0.0
- '@vitest/browser': 2.1.9
- '@vitest/ui': 2.1.9
+ '@opentelemetry/api': ^1.9.0
+ '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
+ '@vitest/browser-playwright': 4.1.8
+ '@vitest/browser-preview': 4.1.8
+ '@vitest/browser-webdriverio': 4.1.8
+ '@vitest/coverage-istanbul': 4.1.8
+ '@vitest/coverage-v8': 4.1.8
+ '@vitest/ui': 4.1.8
happy-dom: '*'
jsdom: '*'
+ vite: ^6.4.2
peerDependenciesMeta:
'@edge-runtime/vm':
optional: true
+ '@opentelemetry/api':
+ optional: true
'@types/node':
optional: true
- '@vitest/browser':
+ '@vitest/browser-playwright':
+ optional: true
+ '@vitest/browser-preview':
+ optional: true
+ '@vitest/browser-webdriverio':
+ optional: true
+ '@vitest/coverage-istanbul':
+ optional: true
+ '@vitest/coverage-v8':
optional: true
'@vitest/ui':
optional: true
@@ -4431,39 +4440,34 @@ snapshots:
- openai
- ws
dependencies:
'@anthropic-ai/sdk': 0.32.1
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
remeda: 2.37.0
- vitest: 2.1.9(@types/[email protected])([email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@edge-runtime/vm'
- '@huggingface/transformers'
+ - '@opentelemetry/api'
- '@types/node'
- - '@vitest/browser'
+ - '@vitest/browser-playwright'
+ - '@vitest/browser-preview'
+ - '@vitest/browser-webdriverio'
+ - '@vitest/coverage-istanbul'
+ - '@vitest/coverage-v8'
- '@vitest/ui'
- encoding
- gpt-tokenizer
- happy-dom
- - jiti
- js-tiktoken
- jsdom
- - less
- - lightningcss
- msw
- pathe
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- tiktoken
- - tsx
- - yaml
+ - vite
dependencies:
@@ -5169,14 +5173,23 @@ snapshots:
color: 5.0.3
text-hex: 1.0.0
+ '@standard-schema/[email protected]': {}
+
dependencies:
tslib: 2.8.1
+ '@types/[email protected]':
+ dependencies:
+ '@types/deep-eql': 4.0.2
+ assertion-error: 2.0.1
+
'@types/[email protected]': {}
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -5234,45 +5247,46 @@ snapshots:
'@upstash/[email protected]': {}
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/spy': 2.1.9
- '@vitest/utils': 2.1.9
- chai: 5.3.3
- tinyrainbow: 1.2.0
+ '@standard-schema/spec': 1.1.0
+ '@types/chai': 5.2.3
+ '@vitest/spy': 4.1.8
+ '@vitest/utils': 4.1.8
+ chai: 6.2.2
+ tinyrainbow: 3.1.0
dependencies:
- '@vitest/spy': 2.1.9
+ '@vitest/spy': 4.1.8
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- tinyrainbow: 1.2.0
+ tinyrainbow: 3.1.0
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/utils': 2.1.9
- pathe: 1.1.2
+ '@vitest/utils': 4.1.8
+ pathe: 2.0.3
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/pretty-format': 2.1.9
+ '@vitest/pretty-format': 4.1.8
+ '@vitest/utils': 4.1.8
magic-string: 0.30.21
- pathe: 1.1.2
+ pathe: 2.0.3
- '@vitest/[email protected]':
- dependencies:
- tinyspy: 3.0.2
+ '@vitest/[email protected]': {}
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/pretty-format': 2.1.9
- loupe: 3.2.1
- tinyrainbow: 1.2.0
+ '@vitest/pretty-format': 4.1.8
+ convert-source-map: 2.0.0
+ tinyrainbow: 3.1.0
'@vladfrangu/[email protected]': {}
@@ -5506,13 +5520,7 @@ snapshots:
- supports-color
optional: true
- dependencies:
- assertion-error: 2.0.1
- check-error: 2.1.3
- deep-eql: 5.0.2
- loupe: 3.2.1
- pathval: 2.0.1
dependencies:
@@ -5523,8 +5531,6 @@ snapshots:
ansi-styles: 4.3.0
supports-color: 7.2.0
-
dependencies:
readdirp: 4.1.2
@@ -5653,6 +5659,8 @@ snapshots:
optional: true
+
@@ -5680,8 +5688,6 @@ snapshots:
dependencies:
mimic-response: 3.1.0
-
@@ -5768,7 +5774,7 @@ snapshots:
dependencies:
@@ -6283,9 +6289,9 @@ snapshots:
dependencies:
'@llamaindex/astra': 0.0.4(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
@@ -6328,7 +6334,12 @@ snapshots:
- '@google/generative-ai'
- '@huggingface/transformers'
- '@mongodb-js/zstd'
- - '@vitest/browser'
+ - '@opentelemetry/api'
+ - '@vitest/browser-playwright'
+ - '@vitest/browser-preview'
+ - '@vitest/browser-webdriverio'
+ - '@vitest/coverage-istanbul'
+ - '@vitest/coverage-v8'
- '@vitest/ui'
- bare-abort-controller
- bare-buffer
@@ -6337,12 +6348,9 @@ snapshots:
- encoding
- gcp-metadata
- happy-dom
- - jiti
- js-tiktoken
- jsdom
- kerberos
- - less
- - lightningcss
- mongodb-client-encryption
- msw
- openai
@@ -6352,23 +6360,17 @@ snapshots:
- pg-query-stream
- pgvector
- react-native-b4a
- - sass
- - sass-embedded
- snappy
- socks
- - stylus
- - sugarss
- supports-color
- - terser
- tiktoken
- tree-sitter
- - tsx
- typescript
- utf-8-validate
+ - vite
- voyageai
- web-tree-sitter
- ws
- - yaml
- zod
@@ -6410,8 +6412,6 @@ snapshots:
option: 0.2.4
underscore: 1.13.8
-
@@ -6576,6 +6576,8 @@ snapshots:
+
dependencies:
whatwg-fetch: 3.6.20
@@ -6696,12 +6698,11 @@ snapshots:
+ optional: true
-
@@ -7114,7 +7115,7 @@ snapshots:
dependencies:
@@ -7254,16 +7255,14 @@ snapshots:
+
dependencies:
fdir: 6.5.0([email protected])
picomatch: 4.0.4
-
-
@@ -7383,27 +7382,6 @@ snapshots:
- dependencies:
- cac: 6.7.14
- debug: 4.4.3
- es-module-lexer: 1.7.0
- pathe: 1.1.2
- vite: 6.4.2(@types/[email protected])([email protected])
- transitivePeerDependencies:
- - '@types/node'
- - jiti
- - less
- - lightningcss
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- - tsx
- - yaml
-
dependencies:
esbuild: 0.27.7
@@ -7417,43 +7395,33 @@ snapshots:
fsevents: 2.3.3
lightningcss: 1.32.0
dependencies:
- '@vitest/expect': 2.1.9
- '@vitest/mocker': 2.1.9([email protected](@types/[email protected])([email protected]))
- '@vitest/pretty-format': 2.1.9
- '@vitest/runner': 2.1.9
- '@vitest/snapshot': 2.1.9
- '@vitest/spy': 2.1.9
- '@vitest/utils': 2.1.9
- chai: 5.3.3
- debug: 4.4.3
+ '@vitest/expect': 4.1.8
+ '@vitest/mocker': 4.1.8([email protected](@types/[email protected])([email protected]))
+ '@vitest/pretty-format': 4.1.8
+ '@vitest/runner': 4.1.8
+ '@vitest/snapshot': 4.1.8
+ '@vitest/spy': 4.1.8
+ '@vitest/utils': 4.1.8
+ es-module-lexer: 2.1.0
expect-type: 1.3.0
magic-string: 0.30.21
- pathe: 1.1.2
- std-env: 3.10.0
+ obug: 2.1.2
+ pathe: 2.0.3
+ picomatch: 4.0.4
+ std-env: 4.1.0
tinybench: 2.9.0
- tinyexec: 0.3.2
- tinypool: 1.1.1
- tinyrainbow: 1.2.0
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.16
+ tinyrainbow: 3.1.0
- vite-node: 2.1.9(@types/[email protected])([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
+ '@opentelemetry/api': 1.9.1
'@types/node': 22.19.19
transitivePeerDependencies:
- - jiti
- - less
- - lightningcss
- msw
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- - tsx
- - yaml
dependencies:
diff --git a/uv.lock b/uv.lock
index 04c1648ec..48fe4fc21 100644
--- a/uv.lock
+++ b/uv.lock
@@ -5635,7 +5635,7 @@ dev = [
[[package]]
name = "sie-admin"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "packages/sie_admin" }
dependencies = [
{ name = "httpx" },
@@ -5668,7 +5668,7 @@ requires-dist = [
[[package]]
name = "sie-bench"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "packages/sie_bench" }
dependencies = [
{ name = "aiohttp" },
@@ -5753,7 +5753,7 @@ requires-dist = [
[[package]]
name = "sie-chroma"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "integrations/sie_chroma" }
dependencies = [
{ name = "chromadb" },
@@ -5825,7 +5825,7 @@ dev = [
[[package]]
name = "sie-crewai"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "integrations/sie_crewai" }
dependencies = [
{ name = "crewai" },
@@ -5850,7 +5850,7 @@ requires-dist = [
[[package]]
name = "sie-dspy"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "integrations/sie_dspy" }
dependencies = [
{ name = "dspy" },
@@ -5875,7 +5875,7 @@ requires-dist = [
[[package]]
name = "sie-haystack"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "integrations/sie_haystack" }
dependencies = [
{ name = "haystack-ai" },
@@ -5902,7 +5902,7 @@ requires-dist = [
[[package]]
name = "sie-lancedb"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "integrations/sie_lancedb" }
dependencies = [
{ name = "lancedb" },
@@ -5929,7 +5929,7 @@ requires-dist = [
[[package]]
name = "sie-langchain"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "integrations/sie_langchain" }
dependencies = [
{ name = "langchain-core" },
@@ -5956,7 +5956,7 @@ requires-dist = [
[[package]]
name = "sie-llamaindex"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "integrations/sie_llamaindex" }
dependencies = [
{ name = "llama-index-core" },
@@ -5983,7 +5983,7 @@ requires-dist = [
[[package]]
name = "sie-qdrant"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "integrations/sie_qdrant" }
dependencies = [
{ name = "qdrant-client" },
@@ -6006,7 +6006,7 @@ requires-dist = [
[[package]]
name = "sie-sdk"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "packages/sie_sdk" }
dependencies = [
{ name = "aiohttp" },
@@ -6055,7 +6055,7 @@ requires-dist = [
[[package]]
name = "sie-server"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "packages/sie_server" }
dependencies = [
{ name = "blake3" },
@@ -6170,7 +6170,7 @@ dev = []
[[package]]
name = "sie-weaviate"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "integrations/sie_weaviate" }
dependencies = [
{ name = "sie-sdk" },