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.17

github-actions[bot]822fb1c5ae05
diff --git a/.gitignore b/.gitignore
index 5a2d93fd4..40063cf21 100644
--- a/.gitignore
+++ b/.gitignore
@@ -142,6 +142,11 @@ celerybeat.pid
# Environments
.env
+# Managed-service cloud provisioning secrets (cloud-provision / deploy/cloud).
+# Vendor credentials live in the env or a gitignored secrets file, never the
+# repo (audit §1/§14). Belt-and-braces so a local copy can never be committed.
+*.sie-cloud-secrets.env
+.env.cloud
.venv
env/
venv/
@@ -264,3 +269,4 @@ tmp/
.local/
.requirements-modal.txt
+packages/sie_cloud/deploy/manifests/archive/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e284904b8..1a38afc82 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,42 @@
# Changelog
+## v0.6.17
+
+- chore(main): release 0.6.17
+- docs(gateway): clarify multi-gpu sidecar routing
+- fix(sidecar): refresh ready slots on cancel fanout failure
+- fix(sidecar): release cancelled scheduler pressure
+- fix(sidecar): wire local ingest through adapter pool
+- fix(req6): align candle chart after rebase
+- fix(server): keep ipc ping alive on gpu health errors
+- refactor(sidecar): name adapter worker pool generically
+- feat(worker): support multi-gpu sidecar children
+- fix(req6): harden multi-gpu worker review fixes
+- fix(req6): harden multi-gpu worker routing
+- fix(req6): resolve main rebase fallout
+- fix(req6): wire pressure-aware multi-gpu routing
+- test(tilt): emulate multi-child sidecar on cpu
+- feat(worker): route by child queue pressure
+- feat(worker): route multi-gpu sidecar children
+- docs: state req6 multi-gpu target directly
+- docs: clarify multi-gpu worker target topology
+- feat(server): support multi-gpu worker placement
+- feat(cloud): CLI WorkOS device-flow auth — retire the shared-token shortcut for customer commands (#1697)
+- chore(deps): bump the uv group across 3 directories with 12 updates
+- feat(oss): OSS amendments from the SIE Cloud build — engine, SDKs, gateway/sidecar seams (#1696)
+- fix(sidecar): bound queue admission through scheduler completion
+- chore(models): correct gte-Qwen2-1.5B compute_precision label to fp32 reality
+- fix(candle): address rope review feedback
+- fix(candle): repair rebase conflict resolution
+- fix(candle): remove rust worker forward coalescing
+- fix(sidecar): bulk enqueue scheduler items
+- fix(sidecar): expose scheduler flush reasons
+- feat(candle): add GTE RoPE embedding kernel
+- test(sdk): golden wire-contract fixture for ModelState + fix TS drift
+- refactor(server): move eviction-candidate decision into residency policy
+- refactor(gateway): unify worker-error retry semantics into one classifier
+- refactor(gateway): collapse header/pool/profile resolution into one seam
+
## v0.6.16
- chore(main): release 0.6.16
diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yaml
index e7e65c6da..0b5f3c767 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.6.16 # x-release-please-version
-appVersion: v0.6.16 # x-release-please-version
+version: 0.6.17 # x-release-please-version
+appVersion: v0.6.17 # x-release-please-version
keywords:
- inference
- embedding
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.md
index b554d7d90..1fe9d99ce 100644
--- a/deploy/helm/sie-cluster/README.md
+++ b/deploy/helm/sie-cluster/README.md
@@ -138,8 +138,15 @@ label that KEDA cannot match.
| `sie_gateway_pending_demand` | Gateway | Trigger scale from 0 |
| `sie_gateway_worker_queue_depth` | Gateway worker registry | Scale up on queued work in the exact pool/profile/bundle lane |
| `sie_gateway_active_lease_gpus` | Gateway pool manager | Hold distinct assigned-worker capacity for active pool leases in the exact pool/profile/bundle lane |
+| `sie_gateway_worker_pending_cost` | Gateway worker registry | Track worker-local scheduler pressure by cost, not only item count |
+| `sie_gateway_worker_ready_gpu_slots` | Gateway worker registry | Show how many GPU slots in a worker pod are ready to receive work |
+| `sie_gateway_worker_inflight_batches` | Gateway worker registry | Show batches currently executing inside worker pods |
| `sie_gateway_rejected_requests_total` | Gateway | Scale up on sustained capacity/no-worker rejections after retryable cold-load reasons are excluded |
+KEDA scales worker StatefulSet replicas. It does not add or remove Python
+processes or containers inside a running worker pod, so a multi-GPU worker is
+one larger scaling unit with richer per-replica pressure metrics.
+
### Worker-sidecar Metrics
When `workers.common.workerSidecar.enabled=true`, each worker Pod includes a
@@ -155,9 +162,22 @@ The chart wires sidecar scraping as:
- worker Service port `worker-metrics`
- worker ServiceMonitor endpoint `worker-metrics`
+For multi-child workers, the same worker Service also exposes adapter child
+metrics ports `http-1` through `http-(N-1)` in addition to the baseline `http`
+port, and the worker ServiceMonitor scrapes each of those endpoints. That keeps
+adapter-native metrics visible for every child container, while sidecar
+`sie_worker_child_*` gauges remain the placement/queue-depth source of truth.
+
Alert rules that need the sidecar scrape target match
`endpoint="worker-metrics"` rather than an old `job="sie-worker"` label.
+Multi-child sidecars also expose child-level GPU slot gauges with a `child`
+label: `sie_worker_child_ready`, `sie_worker_child_models`,
+`sie_worker_child_queue_depth`, `sie_worker_child_pending_cost`, and
+`sie_worker_child_inflight_batches`. The gateway receives the pod-level
+heartbeat fields; these sidecar metrics are the per-child view used to audit
+placement and queue pressure inside one worker pod.
+
## Configuration
See `values.yaml` for all options. Key settings:
@@ -216,6 +236,54 @@ autoscaling:
cooldownPeriod: 600 # 10 min before scale-down
```
+### Multi-GPU Worker Shapes
+
+Req6 separates the Kubernetes allocation shape from the worker execution shape.
+Set `workers.pools.<name>.gpu.count` above `1` when one worker pod should
+consume multiple GPUs from a single VM. The chart requests that many
+`nvidia.com/gpu` devices and renders one adapter worker child per GPU.
+
+The queue-mode multi-GPU shape is one pod with one `worker-sidecar` plus
+`worker-0` through `worker-(N-1)` adapter containers. Python/PyTorch and
+Rust/Candle children use the same sidecar IPC fanout. Each child requests one
+GPU, sees `SIE_DEVICES=cuda:0` when the runtime consumes that env var, binds a
+unique HTTP/probe port, and serves a unique IPC socket. The sidecar receives
+`SIE_IPC_SOCKET_PATHS`, owns the pod-level queue consumer, and places models
+onto child sockets by child readiness, placed-model count, pending scheduler
+cost, pending item count, and in-flight batch count. That placement scoring is a
+fixed sidecar policy.
+
+For local CPU-only dev, `workers.pools.<name>.sidecar.emulatedChildCount` can
+render multiple CPU worker children with distinct IPC sockets and no
+`nvidia.com/gpu` request. This is intended for Tilt/e2e coverage of child
+routing and metrics only; GPU pools must use `gpu.count` for real capacity.
+
+This is the Req6 one-child-at-a-time model placement topology. It distributes
+different models from one runtime bundle across the pod's GPU slots. A child can
+own multiple models, but one model is not spread across children, replicated for
+throughput, or tensor/model-parallelized for an oversized model.
+
+Each worker pod serves exactly one runtime bundle. Different bundles render as
+different worker StatefulSets and therefore different worker identities.
+
+Example AWS shape for a 4-GPU L4 node:
+
+```yaml
+workers:
+ pools:
+ l4-4x:
+ enabled: true
+ machineProfile: l4-4x
+ gpuType: nvidia-l4
+ gpu:
+ count: 4
+ product: NVIDIA-L4
+ bundles:
+ default:
+ minReplicas: 0
+ maxReplicas: 3
+```
+
### Queue Pool Patterns
Use one of these patterns deliberately:
@@ -654,7 +722,7 @@ Pre-configured dashboards:
### Distributed Tracing (OTLP)
-Distributed tracing is **off by default** — the rendered chart is unchanged unless you opt in. Enabling injects the OpenTelemetry exporter env onto the gateway, worker sidecar, Python worker, and Rust worker so a request is traced end to end (OTLP gRPC, `:4317`). Non-generation endpoints (encode/score/extract/embeddings) publish through `gateway.publish` before `sidecar.dispatch` and `worker.run_batch`; generation (`/v1/generate`, `/v1/chat/completions`) uses `gateway.proxy_generate` / `gateway.proxy_chat` and `worker.streaming_processor`, bypassing the sidecar. Sampling defaults to a head-based parent sampler (`parentbased_traceidratio` at `0.05`), which honors an inbound `traceparent` decision and otherwise samples 5% of new traces.
+Distributed tracing is **off by default** — the rendered chart is unchanged unless you opt in. Enabling injects the OpenTelemetry exporter env onto the gateway, worker sidecar, adapter worker, and Rust worker so a request is traced end to end (OTLP gRPC, `:4317`). Queue-mode endpoints (encode/score/extract/embeddings) publish through `gateway.publish` before `sidecar.dispatch` and `worker.run_batch`; generation (`/v1/generate`, `/v1/chat/completions`) also opens gateway-originated spans for the streaming path. Sampling defaults to a head-based parent sampler (`parentbased_traceidratio` at `0.05`), which honors an inbound `traceparent` decision and otherwise samples 5% of new traces.
**Bring your own collector** (Tempo, Jaeger, or an existing OTel Collector) — recommended:
diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tpl
index 738e61a44..6b3a8e6bc 100644
--- a/deploy/helm/sie-cluster/templates/_helpers.tpl
+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl
@@ -663,3 +663,33 @@ mcpEdge.existingSecretName is set; otherwise the chart-managed one.
{{- printf "%s-connector-secrets" (include "sie-cluster.mcpEdge.serviceName" .) -}}
{{- end -}}
{{- end }}
+
+{{/*
+Maximum worker child count rendered by any enabled worker pool.
+
+This mirrors worker-statefulset.yaml: GPU pools fan out by gpu.count, and local
+CPU emulation fans out by sidecar.emulatedChildCount. The shared worker Service
+and ServiceMonitor use the maximum to expose/scrape each possible child metrics
+port; pods without a named child port are simply not endpoints for that port.
+*/}}
+{{- define "sie-cluster.worker.maxChildCount" -}}
+{{- $root := . -}}
+{{- $max := 1 -}}
+{{- range $poolName, $pool := $root.Values.workers.pools -}}
+{{- if $pool.enabled -}}
+{{- $gpuCount := int $pool.gpu.count -}}
+{{- $poolSidecar := default dict $pool.sidecar -}}
+{{- $emulatedChildCount := int (dig "emulatedChildCount" 0 $poolSidecar) -}}
+{{- $count := 1 -}}
+{{- if gt $gpuCount 1 -}}
+{{- $count = $gpuCount -}}
+{{- else if gt $emulatedChildCount 1 -}}
+{{- $count = $emulatedChildCount -}}
+{{- end -}}
+{{- if and $root.Values.workers.common.workerSidecar.enabled (gt $count $max) -}}
+{{- $max = $count -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- $max -}}
+{{- end }}
diff --git a/deploy/helm/sie-cluster/templates/config-deployment.yaml b/deploy/helm/sie-cluster/templates/config-deployment.yaml
index 3e667cb9a..80e4176d0 100644
--- a/deploy/helm/sie-cluster/templates/config-deployment.yaml
+++ b/deploy/helm/sie-cluster/templates/config-deployment.yaml
@@ -78,6 +78,12 @@ spec:
- name: SIE_LOG_JSON
value: "true"
{{- end }}
+ # Deployment-env signal (mirrors the worker). Arms the config service's
+ # fail-closed guard: in a production env WITHOUT an admin/inference token
+ # it refuses to serve unauthenticated, rather than exposing an open
+ # (writable) catalog. Self-host dev sets a non-prod value to stay open.
+ - name: SIE_DEPLOYMENT_ENV
+ value: {{ if and .Values.telemetry .Values.telemetry.deploymentEnv }}{{ .Values.telemetry.deploymentEnv | quote }}{{ else }}"production"{{ end }}
{{- if .Values.config.auth.adminTokenSecretName }}
- name: SIE_ADMIN_TOKEN
valueFrom:
diff --git a/deploy/helm/sie-cluster/templates/servicemonitor.yaml b/deploy/helm/sie-cluster/templates/servicemonitor.yaml
index 1f44c44d2..5b2a16a37 100644
--- a/deploy/helm/sie-cluster/templates/servicemonitor.yaml
+++ b/deploy/helm/sie-cluster/templates/servicemonitor.yaml
@@ -1,4 +1,5 @@
{{- if .Values.serviceMonitor.enabled }}
+{{- $maxWorkerChildCount := int (include "sie-cluster.worker.maxChildCount" .) }}
{{/*
Per-component ServiceMonitors. A single monitor with the shared
`sie-cluster.selectorLabels` selector matches the gateway, config, and
@@ -33,7 +34,7 @@ spec:
scrapeTimeout: {{ .Values.serviceMonitor.scrapeTimeout }}
path: /metrics
---
-# Worker ServiceMonitor (Python + optional worker-sidecar)
+# Worker ServiceMonitor (adapter workers + optional worker-sidecar)
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
@@ -56,6 +57,16 @@ spec:
interval: {{ .Values.serviceMonitor.interval }}
scrapeTimeout: {{ .Values.serviceMonitor.scrapeTimeout }}
path: /metrics
+ {{- if gt $maxWorkerChildCount 1 }}
+ {{- range $i := until $maxWorkerChildCount }}
+ {{- if gt $i 0 }}
+ - port: http-{{ $i }}
+ interval: {{ $.Values.serviceMonitor.interval }}
+ scrapeTimeout: {{ $.Values.serviceMonitor.scrapeTimeout }}
+ path: /metrics
+ {{- end }}
+ {{- end }}
+ {{- end }}
{{- if .Values.workers.common.workerSidecar.enabled }}
# worker-sidecar metrics (NATS pull loop, backend routing,
# circuit breaker state, per-backend latency histograms).
diff --git a/deploy/helm/sie-cluster/templates/worker-service.yaml b/deploy/helm/sie-cluster/templates/worker-service.yaml
index acd05b649..dded6fc48 100644
--- a/deploy/helm/sie-cluster/templates/worker-service.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-service.yaml
@@ -1,3 +1,4 @@
+{{- $maxWorkerChildCount := int (include "sie-cluster.worker.maxChildCount" .) }}
apiVersion: v1
kind: Service
metadata:
@@ -13,6 +14,16 @@ spec:
port: {{ .Values.workers.common.port }}
targetPort: http
protocol: TCP
+ {{- if gt $maxWorkerChildCount 1 }}
+ {{- range $i := until $maxWorkerChildCount }}
+ {{- if gt $i 0 }}
+ - name: http-{{ $i }}
+ port: {{ add $.Values.workers.common.port $i }}
+ targetPort: http-{{ $i }}
+ protocol: TCP
+ {{- end }}
+ {{- end }}
+ {{- end }}
{{- if .Values.workers.common.workerSidecar.enabled }}
- name: worker-metrics
port: {{ .Values.workers.common.workerSidecar.metricsPort }}
diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
index 5df4e7020..21661b7fe 100644
--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
@@ -28,7 +28,7 @@ fast at render time.
{{- end }}
{{- $workerLivenessBudgetS := mul $workerLivenessPeriodS $workerLivenessFailures -}}
{{- if le $workerLivenessBudgetS $modelReadyTimeoutS }}
-{{- fail (printf "workers.common.modelReadyTimeoutSec=%d must be lower than the Python worker liveness budget (%d * %d = %ds); increase workers.common.probes.liveness.failureThreshold/periodSeconds or lower modelReadyTimeoutSec" $modelReadyTimeoutS $workerLivenessFailures $workerLivenessPeriodS $workerLivenessBudgetS) }}
+{{- fail (printf "workers.common.modelReadyTimeoutSec=%d must be lower than the adapter worker liveness budget (%d * %d = %ds); increase workers.common.probes.liveness.failureThreshold/periodSeconds or lower modelReadyTimeoutSec" $modelReadyTimeoutS $workerLivenessFailures $workerLivenessPeriodS $workerLivenessBudgetS) }}
{{- end }}
{{- range $poolName, $pool := .Values.workers.pools }}
{{- if $pool.enabled }}
@@ -79,6 +79,33 @@ fast at render time.
{{- if and (eq $engine "candle") (ne $bundle "candle") }}
{{- fail (printf "workers.pools.%s.bundles.%s.engine=candle requires bundle=candle so gateway routing and worker heartbeats agree" $poolName $bundleName) }}
{{- end }}
+{{- $gpuCount := int $pool.gpu.count }}
+{{- $poolSidecar := default dict $pool.sidecar }}
+{{- $emulatedChildCount := int (dig "emulatedChildCount" 0 $poolSidecar) }}
+{{- if and (gt $emulatedChildCount 0) (gt $gpuCount 0) }}
+{{- fail (printf "workers.pools.%s.sidecar.emulatedChildCount is CPU-only; GPU pools use gpu.count for child fanout." $poolName) }}
+{{- end }}
+{{- $workerChildCount := 1 }}
+{{- if gt $gpuCount 1 }}
+{{- $workerChildCount = $gpuCount }}
+{{- else if gt $emulatedChildCount 1 }}
+{{- $workerChildCount = $emulatedChildCount }}
+{{- end }}
+{{- $multiWorkerChildren := and $root.Values.workers.common.workerSidecar.enabled (gt $workerChildCount 1) }}
+{{- if and $multiWorkerChildren $preloadModels }}
+{{- fail (printf "workers.pools.%s.bundles.%s: preloadModels is not supported with multi-child worker pods; each model must be placed on exactly one child by the worker-sidecar" $poolName $bundleName) }}
+{{- end }}
+{{- $workerIndexes := list 0 }}
+{{- if $multiWorkerChildren }}
+{{- $workerIndexes = until $workerChildCount }}
+{{- end }}
+{{- $ipcSocketPaths := list "/var/run/sie/ipc.sock" }}
+{{- if $multiWorkerChildren }}
+{{- $ipcSocketPaths = list }}
+{{- range $i := until $workerChildCount }}
+{{- $ipcSocketPaths = append $ipcSocketPaths (printf "/var/run/sie/ipc-%d.sock" $i) }}
+{{- end }}
+{{- end }}
---
apiVersion: apps/v1
kind: StatefulSet
@@ -135,7 +162,24 @@ spec:
runAsUser: 1000
runAsGroup: 1000
containers:
- - name: worker
+ {{- range $workerIndex := $workerIndexes }}
+ {{- $workerSocket := "/var/run/sie/ipc.sock" }}
+ {{- if $multiWorkerChildren }}
+ {{- $workerSocket = printf "/var/run/sie/ipc-%d.sock" $workerIndex }}
+ {{- end }}
+ {{- $workerPort := int $root.Values.workers.common.port }}
+ {{- if $multiWorkerChildren }}
+ {{- $workerPort = add $workerPort $workerIndex }}
+ {{- end }}
+ {{- $workerPortName := "http" }}
+ {{- if and $multiWorkerChildren (gt $workerIndex 0) }}
+ {{- $workerPortName = printf "http-%d" $workerIndex }}
+ {{- end }}
+ {{- $containerGpuCount := $gpuCount }}
+ {{- if and $multiWorkerChildren (gt $gpuCount 0) }}
+ {{- $containerGpuCount = 1 }}
+ {{- end }}
+ - name: {{ if $multiWorkerChildren }}worker-{{ $workerIndex }}{{ else }}worker{{ end }}
{{- $imageTag := default $root.Chart.AppVersion $root.Values.workers.common.image.tag }}
{{- $rust := $root.Values.workers.common.rust }}
{{- if eq $engine "candle" }}
@@ -144,22 +188,22 @@ spec:
imagePullPolicy: {{ $rust.image.pullPolicy }}
args:
- --host=0.0.0.0
- - --port={{ $root.Values.workers.common.port }}
+ - --port={{ $workerPort }}
{{- else }}
image: {{ printf "%s:%s-%s-%s" $root.Values.workers.common.image.repository $imageTag $platform $imageBundle }}
imagePullPolicy: {{ $root.Values.workers.common.image.pullPolicy }}
args:
- serve
- --host=0.0.0.0
- - --port={{ $root.Values.workers.common.port }}
+ - --port={{ $workerPort }}
- --bundle={{ $bundle }}
{{- if $root.Values.workers.common.clusterCache.enabled }}
- --cluster-cache=$(SIE_CLUSTER_CACHE)
{{- end }}
{{- end }}
ports:
- - name: http
- containerPort: {{ $root.Values.workers.common.port }}
+ - name: {{ $workerPortName }}
+ containerPort: {{ $workerPort }}
protocol: TCP
env:
# GPU type for routing
@@ -192,7 +236,20 @@ spec:
{{- end }}
# Device configuration (cpu if no GPU, cuda otherwise)
- name: SIE_DEVICE
- value: {{ if gt (int $pool.gpu.count) 0 }}cuda{{ else }}cpu{{ end }}
+ value: {{ if gt $gpuCount 0 }}cuda{{ else }}cpu{{ end }}
+ {{- if gt $gpuCount 0 }}
+ {{- $devices := list }}
+ {{- if $multiWorkerChildren }}
+ {{- $devices = append $devices "cuda:0" }}
+ {{- else }}
+ {{- range $i := until $gpuCount }}
+ {{- $devices = append $devices (printf "cuda:%d" $i) }}
+ {{- end }}
+ {{- end }}
+ # Concrete devices visible inside this adapter worker.
+ - name: SIE_DEVICES
+ value: {{ join "," $devices | quote }}
+ {{- end }}
{{- if $preloadModels }}
# Models to eagerly load at startup (before readiness)
- name: SIE_PRELOAD_MODELS
@@ -249,11 +306,17 @@ spec:
# (at the top of this file) if the sidecar is enabled
# without NATS.
- name: SIE_IPC_SOCKET_PATH
- value: /var/run/sie/ipc.sock
+ value: {{ $workerSocket | quote }}
- name: SIE_TOKENIZER_STAGING_DIR
value: /var/run/sie/tokenizers
- name: SIE_IPC_REQUIRE_HEARTBEAT
value: "true"
+ {{- if $root.Values.workers.common.passthroughMode }}
+ # Queue-mode batching is owned by the worker-sidecar. Python
+ # treats each IPC frame as a complete GPU batch for this child.
+ - name: SIE_WORKER_PASSTHROUGH
+ value: "1"
+ {{- end }}
{{- end }}
{{- if $root.Values.observability.tracing.enabled }}
{{- include "sie-cluster.tracing.env" (dict "root" $root "serviceName" $root.Values.observability.tracing.serviceName.worker) | nindent 12 }}
@@ -274,7 +337,7 @@ spec:
startupProbe:
httpGet:
path: /healthz
- port: http
+ port: {{ $workerPortName }}
{{- toYaml $root.Values.workers.common.probes.startup | nindent 12 }}
livenessProbe:
# /livez is GPU-aware: it runs a tiny CUDA sync so a wedged context
@@ -283,23 +346,23 @@ spec:
# CPU workers report healthy from /livez, so this is safe for all pools.
httpGet:
path: /livez
- port: http
+ port: {{ $workerPortName }}
{{- toYaml $root.Values.workers.common.probes.liveness | nindent 12 }}
readinessProbe:
httpGet:
path: /readyz
- port: http
+ port: {{ $workerPortName }}
{{- toYaml $root.Values.workers.common.probes.readiness | nindent 12 }}
resources:
requests:
{{- toYaml $pool.resources.requests | nindent 14 }}
- {{- if gt (int $pool.gpu.count) 0 }}
- nvidia.com/gpu: {{ $pool.gpu.count | quote }}
+ {{- if gt $containerGpuCount 0 }}
+ nvidia.com/gpu: {{ $containerGpuCount | quote }}
{{- end }}
limits:
{{- toYaml $pool.resources.limits | nindent 14 }}
- {{- if gt (int $pool.gpu.count) 0 }}
- nvidia.com/gpu: {{ $pool.gpu.count | quote }}
+ {{- if gt $containerGpuCount 0 }}
+ nvidia.com/gpu: {{ $containerGpuCount | quote }}
{{- end }}
volumeMounts:
- name: model-cache
@@ -310,15 +373,15 @@ spec:
- name: sie-ipc
mountPath: /var/run/sie
{{- end }}
+ {{- end }}
{{- if $root.Values.workers.common.workerSidecar.enabled }}
# worker-sidecar
# Owns the NATS JetStream pull loop and forwards work into
- # the worker adapter process over a shared Unix socket.
+ # the adapter worker process(es) over shared Unix sockets.
- name: worker-sidecar
{{- $rs := $root.Values.workers.common.workerSidecar }}
{{- $configReconcile := default dict $rs.configReconcile }}
{{- $rsTag := default $root.Chart.AppVersion $rs.image.tag }}
- {{- $candleBatcher := default dict $root.Values.workers.common.rust.candle.batcher }}
image: {{ printf "%s:%s" $rs.image.repository $rsTag }}
imagePullPolicy: {{ $rs.image.pullPolicy }}
ports:
@@ -329,9 +392,13 @@ spec:
- name: SIE_WORKER_METRICS_PORT
value: {{ $rs.metricsPort | quote }}
- name: SIE_IPC_SOCKET_PATH
- value: /var/run/sie/ipc.sock
+ value: {{ index $ipcSocketPaths 0 | quote }}
- name: SIE_TOKENIZER_STAGING_DIR
value: /var/run/sie/tokenizers
+ {{- if $multiWorkerChildren }}
+ - name: SIE_IPC_SOCKET_PATHS
+ value: {{ join "," $ipcSocketPaths | quote }}
+ {{- end }}
- name: SIE_POOL
value: {{ $queuePool | quote }}
- name: SIE_BUNDLE
@@ -478,23 +545,17 @@ spec:
value: {{ $rs.pipelineDepth | quote }}
{{- end }}
{{- if $rs.batcher }}
- {{- if and $rs.batcher.coalesceMs (not (and (eq $engine "candle") $candleBatcher.coalesceMs)) }}
+ {{- if $rs.batcher.coalesceMs }}
- name: SIE_BATCHER_COALESCE_MS
value: {{ $rs.batcher.coalesceMs | quote }}
{{- end }}
- {{- if and $rs.batcher.maxBatchRequests (not (and (eq $engine "candle") $candleBatcher.maxBatchRequests)) }}
+ {{- if $rs.batcher.maxBatchRequests }}
- name: SIE_BATCHER_MAX_BATCH_REQUESTS
value: {{ $rs.batcher.maxBatchRequests | quote }}
{{- end }}
- {{- end }}
- {{- if eq $engine "candle" }}
- {{- if $candleBatcher.coalesceMs }}
- - name: SIE_BATCHER_COALESCE_MS
- value: {{ $candleBatcher.coalesceMs | quote }}
- {{- end }}
- {{- if $candleBatcher.maxBatchRequests }}
- - name: SIE_BATCHER_MAX_BATCH_REQUESTS
- value: {{ $candleBatcher.maxBatchRequests | quote }}
+ {{- if hasKey $rs.batcher "idleBypassEnabled" }}
+ - name: SIE_BATCHER_IDLE_BYPASS_ENABLED
+ value: {{ $rs.batcher.idleBypassEnabled | quote }}
{{- end }}
{{- end }}
{{- if $rs.adaptive }}
diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yaml
index 3f30d9cd9..cfa2d688d 100644
--- a/deploy/helm/sie-cluster/values.yaml
+++ b/deploy/helm/sie-cluster/values.yaml
@@ -372,13 +372,6 @@ workers:
# forward path; raise during GPU tuning to test whether Candle can
# safely overlap same-model work without loading duplicate weights.
maxConcurrentForwards: 1
- # -- Candle-native workers run the model directly from the
- # worker-sidecar IPC batch. Keep the default conservative for
- # BGE-M3: larger coalesce/batch limits can form ~16k-token
- # groups on L4 and hurt p99 without improving throughput.
- batcher:
- coalesceMs: 3
- maxBatchRequests: 12
# -- Platform variant for worker images (e.g. "cuda12", "cpu")
platform: cuda12
@@ -486,7 +479,7 @@ workers:
extraEnv: []
# -- Shared model cold-start/ready timeout in seconds. The chart renders
- # this into both containers as SIE_MODEL_READY_TIMEOUT_S: the Python worker
+ # this into both containers as SIE_MODEL_READY_TIMEOUT_S: the adapter worker
# uses it as an SGLang startup-health timeout fallback, and the Rust
# worker-sidecar uses it for EnsureModelReady IPC calls. Keep this >= any
# SGLang profile adapter_options.loadtime.startup_timeout_s. Helm renders
@@ -556,12 +549,12 @@ workers:
# -- Per-model-group batch concurrency cap for the dispatcher.
# Leave empty to use the binary default (4).
maxConcurrentBatches: ""
- # -- Size of the sidecar-to-adapter IPC connection pool. Each slot is an
- # independent Unix-domain socket; concurrent batches check out a
- # slot, perform their round-trip, and return it to the pool.
+ # -- Size of the sidecar-to-adapter IPC connection pool per child
+ # socket. Concurrent batches check out a connection slot, perform
+ # their round-trip, and return it to the pool.
# Should be >= maxConcurrentBatches so the IPC layer is never
# the binding constraint. Leave empty to default to
- # SIE_MAX_CONCURRENT_BATCHES (or its fallback of 4).
+ # SIE_MAX_CONCURRENT_BATCHES (or the binary default of 4).
ipcPoolSize: ""
# -- IPC heartbeat cadence. Must stay comfortably below Python's
# SIE_IPC_STALE_AFTER_MS (default 10000); architecture guide
@@ -632,7 +625,7 @@ workers:
pipelineDepth: 2
# -- Rust scheduler batcher tuning for queue-mode workers. These
# defaults keep sidecar-owned batch formation responsive while
- # leaving the Python adapter process to execute each IPC frame as
+ # leaving the adapter worker process to execute each IPC frame as
# one forward pass.
batcher:
# -- Coalesce window ceiling in ms. Lower = more responsive
@@ -643,10 +636,15 @@ workers:
# headroom for short arrival bursts without unbounded
# tail-batch growth.
maxBatchRequests: 12
- # -- FetchExpiryController tuning (the Rust sidecar pull-loop
- # batch-coalesce quantum). The narrow 2/15/50 window keeps
- # queue-path coalescing bounded while still allowing short bursts
- # to batch.
+ # -- Flush the first item after an idle gap immediately.
+ # Default true preserves low-load p50. Disable selectively
+ # for passthrough GPU runtimes when multi-worker fanout
+ # under-fills local batches.
+ idleBypassEnabled: true
+ # -- FetchExpiryController tuning (the client-side batch-coalesce
+ # quantum that drives the NATS pull loop). The narrow 2/15/50
+ # window keeps queue-path coalescing bounded while still allowing
+ # short bursts to batch.
adaptive:
# -- Quantum floor in ms (`SIE_ADAPTIVE_MIN_QUANTUM_MS`).
minQuantumMs: 2
@@ -667,7 +665,7 @@ workers:
# liveness-budget validation stay in sync.
extraEnv: []
# -- Resource requests/limits for the sidecar. Conservative
- # defaults; the heavy lifting still happens in the Python pod.
+ # defaults; the heavy lifting still happens in the adapter worker.
resources:
requests:
cpu: "500m"
@@ -692,6 +690,12 @@ workers:
# chart for image/label selection, not propagated as a
# worker process env var.
# gpu.count: int. 0 disables nvidia.com/gpu request on the pod.
+ # Values >1 render one adapter child container per GPU
+ # plus one sidecar routing across child IPC sockets.
+ # sidecar.emulatedChildCount:
+ # int. CPU-only local/dev fanout for exercising the same
+ # sidecar child routing without GPU resources. GPU pools
+ # must use gpu.count instead.
# gpu.product: string. nvidia.com/gpu.product node-label match.
# gpuType: GPU/node label used for node selection and display.
# machineProfile: Optional queue-lane label used by KEDA scalers,
@@ -875,6 +879,10 @@ workers:
gpu:
count: 0
product: ""
+ sidecar:
+ # CPU-only local/dev hook for rendering N worker children without
+ # GPU resources. Production GPU fanout is driven by gpu.count.
+ emulatedChildCount: 0
resources:
requests:
cpu: "2"
@@ -913,7 +921,11 @@ autoscaling:
# -- Scale-down stabilization window (seconds)
scaleDownStabilization: 300
- # -- Queue depth threshold per pod
+ # -- Queue depth threshold per worker replica.
+ # KEDA scales worker StatefulSet replicas, not adapter processes or containers
+ # inside a running pod. Multi-GPU workers therefore change capacity
+ # per replica; this threshold is evaluated against the gateway's aggregate
+ # worker queue-depth metric for the lane.
queueDepthThreshold: 10
# -- Queue depth to activate from zero
diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.toml
index 5e39dcf2c..c628b8434 100644
--- a/integrations/sie_chroma/pyproject.toml
+++ b/integrations/sie_chroma/pyproject.toml
@@ -1,12 +1,12 @@
[project]
name = "sie-chroma"
-version = "0.6.16"
+version = "0.6.17"
description = "SIE integration for ChromaDB"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"sie-sdk>=0.1.0",
- "chromadb>=0.4",
+ "chromadb>=1.5.9",
]
[project.optional-dependencies]
diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.toml
index ee18b1c0f..b94839d0b 100644
--- a/integrations/sie_crewai/pyproject.toml
+++ b/integrations/sie_crewai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-crewai"
-version = "0.6.16"
+version = "0.6.17"
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 478f125cc..67e4c3812 100644
--- a/integrations/sie_dspy/pyproject.toml
+++ b/integrations/sie_dspy/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-dspy"
-version = "0.6.16"
+version = "0.6.17"
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 ebb266480..961eede22 100644
--- a/integrations/sie_haystack/pyproject.toml
+++ b/integrations/sie_haystack/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-haystack"
-version = "0.6.16"
+version = "0.6.17"
description = "SIE integration for Haystack"
readme = "README.md"
requires-python = ">=3.10"
@@ -24,7 +24,7 @@ dependencies = [
dev = [
"pytest>=8.0.0",
"pytest-asyncio>=0.23.0",
- "chromadb>=0.4.0",
+ "chromadb>=1.5.9",
"chroma-haystack>=2.0.0"
]
diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.toml
index ea3586f9a..72ea249ab 100644
--- a/integrations/sie_lancedb/pyproject.toml
+++ b/integrations/sie_lancedb/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-lancedb"
-version = "0.6.16"
+version = "0.6.17"
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 d00ec1461..82dc6f86a 100644
--- a/integrations/sie_langchain/pyproject.toml
+++ b/integrations/sie_langchain/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-langchain"
-version = "0.6.16"
+version = "0.6.17"
description = "SIE integration for LangChain"
requires-python = ">=3.10"
dependencies = [
@@ -13,7 +13,7 @@ dev = [
"pytest>=8.0",
"pytest-asyncio>=0.23",
# For integration tests
- "chromadb>=0.4",
+ "chromadb>=1.5.9",
"langchain-chroma>=0.1",
]
diff --git a/integrations/sie_langchain/src/sie_langchain/embeddings.py b/integrations/sie_langchain/src/sie_langchain/embeddings.py
index 1b20618c7..7ea98d52a 100644
--- a/integrations/sie_langchain/src/sie_langchain/embeddings.py
+++ b/integrations/sie_langchain/src/sie_langchain/embeddings.py
@@ -36,6 +36,7 @@ class SIEEmbeddings(Embeddings):
depend on the model - see model documentation for details.
gpu: Target GPU type for routing (e.g., "l4", "a100-80gb").
timeout_s: Request timeout in seconds.
+ api_key: Optional API key for authentication (sent as Bearer token).
"""
def __init__(
@@ -50,6 +51,7 @@ class SIEEmbeddings(Embeddings):
options: dict[str, object] | None = None,
gpu: str | None = None,
timeout_s: float = 180.0,
+ api_key: str | None = None,
) -> None:
"""Initialize SIE embeddings."""
self._base_url = base_url
@@ -59,6 +61,7 @@ class SIEEmbeddings(Embeddings):
self._options = options
self._gpu = gpu
self._timeout_s = timeout_s
+ self._api_key = api_key
# Store provided clients or create lazily
self._client = client
@@ -73,6 +76,7 @@ class SIEEmbeddings(Embeddings):
timeout_s=self._timeout_s,
gpu=self._gpu,
options=self._options,
+ api_key=self._api_key,
)
return self._client
@@ -85,6 +89,7 @@ class SIEEmbeddings(Embeddings):
timeout_s=self._timeout_s,
gpu=self._gpu,
options=self._options,
+ api_key=self._api_key,
)
return self._async_client
@@ -204,6 +209,7 @@ class SIESparseEncoder:
model: Model name/ID to use for encoding. Must support sparse output.
gpu: Target GPU type for routing (e.g., "l4", "a100-80gb").
timeout_s: Request timeout in seconds.
+ api_key: Optional API key for authentication (sent as Bearer token).
"""
def __init__(
@@ -213,12 +219,14 @@ class SIESparseEncoder:
model: str = "BAAI/bge-m3",
gpu: str | None = None,
timeout_s: float = 180.0,
+ api_key: str | None = None,
) -> None:
"""Initialize SIE sparse encoder."""
self._base_url = base_url
self._model = model
self._gpu = gpu
self._timeout_s = timeout_s
+ self._api_key = api_key
self._client: SIEClient | None = None
@property
@@ -229,6 +237,7 @@ class SIESparseEncoder:
self._base_url,
timeout_s=self._timeout_s,
gpu=self._gpu,
+ api_key=self._api_key,
)
return self._client
diff --git a/integrations/sie_langchain/tests/test_embeddings.py b/integrations/sie_langchain/tests/test_embeddings.py
index ca0994076..7196180c8 100644
--- a/integrations/sie_langchain/tests/test_embeddings.py
+++ b/integrations/sie_langchain/tests/test_embeddings.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from unittest.mock import patch
+
import pytest
from sie_langchain import SIEEmbeddings, SIESparseEncoder
@@ -77,6 +79,20 @@ class TestSIEEmbeddings:
call_kwargs = mock_sie_client.encode.call_args[1]
assert call_kwargs["instruction"] == "Represent this for search:"
+ def test_api_key_forwarded_to_sync_client(self) -> None:
+ """api_key must reach the lazily-created SIEClient as a Bearer header (design §9.4)."""
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ embeddings = SIEEmbeddings(base_url="http://localhost:8080", api_key="sk-sie-test")
+ client = embeddings.client
+ call_kwargs = mock_client.call_args.kwargs
+ assert call_kwargs["headers"]["Authorization"] == "Bearer sk-sie-test"
+ client.close()
+
+ def test_api_key_forwarded_to_async_client(self) -> None:
+ """api_key must reach the lazily-created SIEAsyncClient (design §9.4)."""
+ embeddings = SIEEmbeddings(base_url="http://localhost:8080", api_key="sk-sie-test")
+ assert embeddings.async_client._api_key == "sk-sie-test"
+
class TestSIEEmbeddingsAsync:
"""Tests for async SIEEmbeddings methods."""
@@ -219,3 +235,12 @@ class TestSIESparseEncoder:
encoder = SIESparseEncoder(model="test-model")
assert encoder._client is None
+
+ def test_api_key_forwarded_to_sync_client(self) -> None:
+ """api_key must reach the lazily-created SIEClient as a Bearer header (design §9.4)."""
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ encoder = SIESparseEncoder(base_url="http://localhost:8080", api_key="sk-sie-test")
+ client = encoder.client
+ call_kwargs = mock_client.call_args.kwargs
+ assert call_kwargs["headers"]["Authorization"] == "Bearer sk-sie-test"
+ client.close()
diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.toml
index 093344d26..a555baf04 100644
--- a/integrations/sie_llamaindex/pyproject.toml
+++ b/integrations/sie_llamaindex/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-llamaindex"
-version = "0.6.16"
+version = "0.6.17"
description = "SIE integration for LlamaIndex"
requires-python = ">=3.10"
dependencies = [
@@ -12,7 +12,7 @@ dependencies = [
dev = [
"pytest>=8.0",
"pytest-asyncio>=0.23",
- "chromadb>=0.5",
+ "chromadb>=1.5.9",
"llama-index-vector-stores-chroma>=0.2",
]
diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.toml
index 038a415ae..8cbed0d58 100644
--- a/integrations/sie_qdrant/pyproject.toml
+++ b/integrations/sie_qdrant/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-qdrant"
-version = "0.6.16"
+version = "0.6.17"
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 5833ebc1d..9c75c47ed 100644
--- a/integrations/sie_ts_chroma/package.json
+++ b/integrations/sie_ts_chroma/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-chroma",
- "version": "0.6.16",
+ "version": "0.6.17",
"description": "SIE embedding function for ChromaDB",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.json
index 8e5d34e27..aff1b1bc6 100644
--- a/integrations/sie_ts_lancedb/package.json
+++ b/integrations/sie_ts_lancedb/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-lancedb",
- "version": "0.6.16",
+ "version": "0.6.17",
"description": "SIE embedding function and reranker for LanceDB",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.json
index 2eb682c9f..f2a19b3ac 100644
--- a/integrations/sie_ts_langchain/package.json
+++ b/integrations/sie_ts_langchain/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-langchain",
- "version": "0.6.16",
+ "version": "0.6.17",
"description": "SIE embeddings integration for LangChain.js",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.json
index cc6e66ec9..05e4d6372 100644
--- a/integrations/sie_ts_llamaindex/package.json
+++ b/integrations/sie_ts_llamaindex/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-llamaindex",
- "version": "0.6.16",
+ "version": "0.6.17",
"description": "SIE embeddings integration for LlamaIndex.TS",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.toml
index ac864b113..11a7fdc4b 100644
--- a/integrations/sie_weaviate/pyproject.toml
+++ b/integrations/sie_weaviate/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-weaviate"
-version = "0.6.16"
+version = "0.6.17"
description = "SIE integration for Weaviate"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/packages/sie_config/src/sie_config/config_api.py b/packages/sie_config/src/sie_config/config_api.py
index e08e3de9e..a3ff4b62a 100644
--- a/packages/sie_config/src/sie_config/config_api.py
+++ b/packages/sie_config/src/sie_config/config_api.py
@@ -260,12 +260,35 @@ def _load_filesystem_yaml(models_dir: Any, model_name: str) -> str | None:
return None
+# A config service reachable at a public URL with NO token is world-readable and
+# (for writes) world-writable — a catalog-poisoning vector. A production deploy
+# MUST configure a token; refuse to serve open when it hasn't. Self-host / dev
+# (no prod env signal) keeps the open-localhost posture.
+_PROD_ENVS = frozenset({"prod", "production"})
+# The deployment-environment signal. `SIE_DEPLOYMENT_ENV` is what the Helm charts
+# set (worker/config deployments, from telemetry.deploymentEnv); `SIE_ENV` is the
+# managed control-plane convention (mirrors encryption.py's prod gate). Honor both
+# so the guard is armed by whichever the deploy vehicle already sets.
+_ENV_SIGNAL_VARS = ("SIE_DEPLOYMENT_ENV", "SIE_ENV")
+
+
+def _refuse_open_in_prod() -> None:
+ """Raise 403 when no auth token is configured in a production environment."""
+ if any(os.environ.get(var, "").strip().lower() in _PROD_ENVS for var in _ENV_SIGNAL_VARS):
+ raise HTTPException(
+ status_code=403,
+ detail="config service requires SIE_ADMIN_TOKEN/SIE_AUTH_TOKEN in production "
+ "(refusing to serve unauthenticated)",
+ )
+
+
def _check_read_auth(request: Request) -> None:
"""Validate read auth (inference token or admin token)."""
auth_token = os.environ.get("SIE_AUTH_TOKEN")
admin_token = os.environ.get("SIE_ADMIN_TOKEN")
if auth_token is None and admin_token is None:
- return # No auth configured
+ _refuse_open_in_prod()
+ return # No auth configured (dev / self-host localhost posture)
token = request.headers.get("Authorization", "").removeprefix("Bearer ").strip()
if not token:
@@ -288,7 +311,8 @@ def _check_write_auth(request: Request) -> None:
status_code=403,
detail="Write operations require SIE_ADMIN_TOKEN (inference token is not sufficient).",
)
- return # No auth configured at all
+ _refuse_open_in_prod()
+ return # No auth configured at all (dev / self-host localhost posture)
token = request.headers.get("Authorization", "").removeprefix("Bearer ").strip()
if not token:
diff --git a/packages/sie_config/tests/test_config_api.py b/packages/sie_config/tests/test_config_api.py
index a7e3481c8..b97b8e8b3 100644
--- a/packages/sie_config/tests/test_config_api.py
+++ b/packages/sie_config/tests/test_config_api.py
@@ -385,6 +385,31 @@ class TestConfigAPIEdgeCases:
)
assert resp.status_code == 200
+ @pytest.mark.parametrize("env_var", ["SIE_ENV", "SIE_DEPLOYMENT_ENV"])
+ def test_prod_without_any_token_refuses_reads_and_writes(self, monkeypatch, env_var: str) -> None:
+ # A production deploy with NO auth token must fail closed, not serve open —
+ # armed by EITHER env signal (SIE_ENV managed / SIE_DEPLOYMENT_ENV Helm).
+ monkeypatch.delenv("SIE_ADMIN_TOKEN", raising=False)
+ monkeypatch.delenv("SIE_AUTH_TOKEN", raising=False)
+ monkeypatch.delenv("SIE_ENV", raising=False)
+ monkeypatch.delenv("SIE_DEPLOYMENT_ENV", raising=False)
+ monkeypatch.setenv(env_var, "production")
+ app = _create_test_app(self._bundles, self._models)
+ client = TestClient(app)
+ yaml_body = "sie_id: test/model\nprofiles:\n default:\n adapter_path: sie_server.adapters.bert_flash:B\n max_batch_tokens: 1\n"
+ assert client.get("/v1/configs/models").status_code == 403
+ assert client.post("/v1/configs/models", content=yaml_body).status_code == 403
+
+ def test_dev_without_any_token_stays_open(self, monkeypatch) -> None:
+ # Self-host / dev (no prod env signal) keeps the open-localhost posture.
+ monkeypatch.delenv("SIE_ADMIN_TOKEN", raising=False)
+ monkeypatch.delenv("SIE_AUTH_TOKEN", raising=False)
+ monkeypatch.delenv("SIE_ENV", raising=False)
+ monkeypatch.delenv("SIE_DEPLOYMENT_ENV", raising=False)
+ app = _create_test_app(self._bundles, self._models)
+ client = TestClient(app)
+ assert client.get("/v1/configs/models").status_code == 200
+
class TestConfigAPIIdempotency:
def setup_method(self) -> None:
diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lock
index e35c8c0f0..c0b3e4d24 100644
--- a/packages/sie_gateway/Cargo.lock
+++ b/packages/sie_gateway/Cargo.lock
@@ -3164,7 +3164,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "sie-gateway"
-version = "0.6.16"
+version = "0.6.17"
dependencies = [
"arc-swap",
"async-nats",
diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.toml
index 926bdc9b7..4e2a1bb70 100644
--- a/packages/sie_gateway/Cargo.toml
+++ b/packages/sie_gateway/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-gateway"
-version = "0.6.16"
+version = "0.6.17"
edition = "2021"
publish = false
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index e907c1566..72d107fdb 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -601,15 +601,20 @@ optional client traceparent
`/v1/embeddings` is rewritten to `/v1/encode`, and the gateway explicitly forwards `traceparent` / `tracestate` onto the queue work item. `gateway.publish` is opened only when the exporter is active; otherwise the gateway scopes the inbound context over publish so downstream workers can still attach to the caller's trace. The sidecar opens `sidecar.dispatch` around the coalesced batch, then serializes that span back onto IPC items so `worker.run_batch` nests under it. If the sidecar exporter is off, it falls back to the original gateway context.
+On multi-GPU worker pods, this same sidecar hop is where non-generation work is assigned to the model's placed child GPU before IPC dispatch; `/v1/embeddings` inherits that behavior after the encode rewrite.
+
Generation path (`/v1/generate`, `/v1/chat/completions`):
```
optional client traceparent
-> gateway.proxy_generate or gateway.proxy_chat
+ -> worker-sidecar IPC ProcessGenerate
-> worker.streaming_processor
```
-Streaming generation bypasses the sidecar. The gateway opens `gateway.proxy_generate` (the OTel-renamed export of the internal `gateway.proxy` tracing span) for native generation or `gateway.proxy_chat` for OpenAI-compatible chat, injects that context into the streaming work item, and the Python worker extracts it before `worker.streaming_processor`.
+Streaming generation goes through the worker-sidecar. The gateway opens `gateway.proxy_generate` (the OTel-renamed export of the internal `gateway.proxy` tracing span) for native generation or `gateway.proxy_chat` for OpenAI-compatible chat, injects that context into the streaming work item, and publishes the item to the worker-direct generation stream. The sidecar receives the generation item, resolves any offloaded payload, selects the model's placed child GPU, forwards `ProcessGenerate` over that child's IPC socket, and publishes Python's streaming events back to the gateway reply subject. The Python worker extracts the gateway trace context before `worker.streaming_processor`.
+
+Multi-GPU caveat: one hot generation model is still bound to one child GPU at a time. This does not shard one model across N GPUs and does not replicate the same model across all child GPUs. Multiple generation models can be placed across children; the same model stays sticky to its child unless that child becomes unready or fails.
Batch fan-in parents on the first valid inbound context and records the remaining distinct valid contexts as OpenTelemetry links. The sidecar does this before `sidecar.dispatch`; Python and Rust workers do the same before `worker.run_batch`. The propagator is installed even when export is off, so trace context flows with tracing disabled. Runtime shutdown uses a bounded ~3 s trace flush. The Helm default sampler is `parentbased_traceidratio` at `0.05`, which preserves inbound sampling decisions and samples 5% of new roots.
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json
index 0b32f897e..98ffb8ae2 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -2948,6 +2948,10 @@
"healthy": {
"type": "boolean"
},
+ "inflight_batches": {
+ "format": "int32",
+ "type": "integer"
+ },
"loaded_models": {
"items": {
"type": "string"
@@ -2965,10 +2969,18 @@
"name": {
"type": "string"
},
+ "pending_cost": {
+ "format": "int64",
+ "type": "integer"
+ },
"queue_depth": {
"format": "int32",
"type": "integer"
},
+ "ready_gpu_slots": {
+ "format": "int32",
+ "type": "integer"
+ },
"url": {
"type": "string"
}
@@ -2978,8 +2990,11 @@
"url",
"gpu",
"gpu_count",
+ "ready_gpu_slots",
"loaded_models",
"queue_depth",
+ "pending_cost",
+ "inflight_batches",
"memory_used_bytes",
"memory_total_bytes",
"healthy",
@@ -3005,7 +3020,7 @@
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
},
"title": "SIE Gateway",
- "version": "0.6.16"
+ "version": "0.6.17"
},
"openapi": "3.1.0",
"paths": {
diff --git a/packages/sie_gateway/src/discovery/nats_health.rs b/packages/sie_gateway/src/discovery/nats_health.rs
index 2e25ff0f2..9788fdc91 100644
--- a/packages/sie_gateway/src/discovery/nats_health.rs
+++ b/packages/sie_gateway/src/discovery/nats_health.rs
@@ -299,6 +299,8 @@ mod tests {
name: "worker-1".into(),
ready,
gpu_count: 1,
+ total_gpu_slots: None,
+ ready_gpu_slots: None,
machine_profile: "rtx6000".into(),
pool_name: "default".into(),
bundle: "sglang".into(),
@@ -307,6 +309,8 @@ mod tests {
models: vec![],
gpus: vec![],
queue_depth: None,
+ pending_cost: None,
+ inflight_batches: None,
memory_used_bytes: None,
memory_total_bytes: None,
saturated: false,
diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rs
index 9c5920029..4ec773f6c 100644
--- a/packages/sie_gateway/src/handlers/config_api.rs
+++ b/packages/sie_gateway/src/handlers/config_api.rs
@@ -808,12 +808,16 @@ mod tests {
crate::types::worker::WorkerStatusMessage {
name: name.into(),
gpu_count: 1,
+ total_gpu_slots: None,
+ ready_gpu_slots: None,
machine_profile: "A100".into(),
bundle: bundle.into(),
bundle_config_hash: hash.into(),
ready: true,
loaded_models: Vec::new(),
queue_depth: Some(0),
+ pending_cost: None,
+ inflight_batches: None,
models: Vec::new(),
memory_used_bytes: Some(0),
memory_total_bytes: Some(0),
diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rs
index b4bf76152..0c906aaf1 100644
--- a/packages/sie_gateway/src/handlers/models.rs
+++ b/packages/sie_gateway/src/handlers/models.rs
@@ -633,12 +633,16 @@ mod route_tests {
WorkerStatusMessage {
name: name.into(),
gpu_count: 1,
+ total_gpu_slots: None,
+ ready_gpu_slots: None,
machine_profile: "A100".into(),
bundle: "default".into(),
bundle_config_hash: String::new(),
ready: true,
loaded_models,
queue_depth: Some(0),
+ pending_cost: None,
+ inflight_batches: None,
models: Vec::new(),
memory_used_bytes: Some(0),
memory_total_bytes: Some(0),
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 6d4cdb92e..c825229fa 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -18,6 +18,7 @@ use crate::http_error::{
openai_code as oai_code, openai_type as oai_type,
};
use crate::metrics;
+use crate::queue::dispatch::{WorkDispatcher, WorkDispatcherExt};
use crate::queue::publisher;
use crate::server::AppState;
@@ -1015,6 +1016,119 @@ fn resolve_bundle_for_request(
Ok(bundle)
}
+/// Normalized machine-profile + pool routing resolved from the request
+/// headers. Shared by the primitive (`resolve_routing`) and generation
+/// (`resolve_generation_route`) paths so the header parse → pool validate →
+/// model-pool default → machine-profile resolution lives in one place.
+struct ProfilePoolRoute {
+ gpu: String,
+ pool_name: String,
+ gpu_configured: bool,
+}
+
+/// Failure modes of [`resolve_profile_and_pool`].
+///
+/// Error *rendering* stays with each caller so the native
+/// (`endpoint_error_response`) and OpenAI (`json_openai_error`) surfaces keep
+/// their exact status / code / param wire shape; this enum only carries the
+/// labels both callers need for the rejection metric.
+enum ProfilePoolError {
+ /// Caller-supplied pool failed the strict `[A-Za-z0-9_-]` allowlist.
+ /// Carries the post-split machine profile for the metric label.
+ InvalidPool { gpu: String },
+ /// Model is assigned to a different pool than the request targeted.
+ /// Carries the metric labels (machine profile + normalized pool) and the
+ /// caller-facing explanation.
+ PoolMismatch {
+ gpu: String,
+ pool_name: String,
+ message: String,
+ },
+}
+
+/// Resolve the machine-profile + pool routing carried by the request headers.
+///
+/// Parses `X-SIE-MACHINE-PROFILE` (optionally a combined
+/// `pool/machine-profile`) and `X-SIE-Pool`, validates the pool against the
+/// strict allowlist BEFORE it can flow into the JetStream work subject
+/// `sie.work.{pool}.{machine_profile}.{bundle}.{model}` (an out-of-charset pool
+/// would re-tokenise the subject — subject injection — and silently mis-route,
+/// so reject rather than mangle), applies the model's default pool, resolves a
+/// bare GPU to its spot variant, and reports whether the GPU is configured.
+///
+/// Pure resolution: it records no metrics and builds no response bodies, so
+/// each caller keeps its own rejection metric and error envelope. Behaviour
+/// mirrors the inline block it replaced in both callers exactly.
+async fn resolve_profile_and_pool(
+ state: &AppState,
+ headers: &HeaderMap,
+ model_name: &str,
+) -> Result<ProfilePoolRoute, ProfilePoolError> {
+ // Parse GPU from X-SIE-MACHINE-PROFILE header
+ let mut gpu = headers
+ .get("x-sie-machine-profile")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("")
+ .to_string();
+
+ let mut pool_name = headers
+ .get("x-sie-pool")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("")
+ .to_string();
+
+ // Parse pool from GPU param (e.g., "eval-l4/l4")
+ if !gpu.is_empty() && gpu.contains('/') {
+ let parts: Vec<&str> = gpu.splitn(2, '/').collect();
+ pool_name = parts[0].to_string();
+ gpu = parts[1].to_string();
+ }
+
+ if !pool_name.is_empty() && !is_valid_pool_name(&pool_name) {
+ return Err(ProfilePoolError::InvalidPool { gpu });
+ }
+ if !pool_name.is_empty() {
+ pool_name = normalize_pool_name(&pool_name);
+ }
+
+ let model_pool = state.model_registry.get_model_pool_name(model_name);
+ if let Err(message) = apply_model_pool_default(
+ &mut pool_name,
+ model_pool.as_deref(),
+ Some(&state.pool_manager),
+ )
+ .await
+ {
+ return Err(ProfilePoolError::PoolMismatch {
+ gpu,
+ pool_name,
+ message,
+ });
+ }
+
+ // Resolve bare GPU to spot variant
+ if !gpu.is_empty() && !state.config.configured_gpus.is_empty() {
+ gpu = resolve_machine_profile(&gpu, &state.config.gpu_profile_map);
+ }
+
+ // Validate GPU is configured. Compute this *before* tagging the metric
+ // label slot so an arbitrary, unconfigured, caller-supplied GPU never
+ // reaches a Prometheus label (unbounded cardinality / DoS).
+ let gpu_configured = gpu.is_empty()
+ || state.config.configured_gpus.is_empty()
+ || state
+ .config
+ .configured_gpus
+ .iter()
+ .any(|cg| cg.eq_ignore_ascii_case(&gpu));
+
+ Ok(ProfilePoolRoute {
+ gpu,
+ pool_name,
+ gpu_configured,
+ })
+}
+
/// The routing decision for a request: canonical model name, serving bundle,
/// and engine. Produced by [`resolve_routing`].
struct RoutingResult {
@@ -1138,83 +1252,44 @@ async fn resolve_routing(
.or_else(|| engine_pin.clone())
.unwrap_or_else(|| crate::types::bundle::DEFAULT_ENGINE.to_string());
- // Parse GPU from X-SIE-MACHINE-PROFILE header
- let mut gpu = headers
- .get("x-sie-machine-profile")
- .and_then(|v| v.to_str().ok())
- .unwrap_or("")
- .to_string();
-
- let mut pool_name = headers
- .get("x-sie-pool")
- .and_then(|v| v.to_str().ok())
- .unwrap_or("")
- .to_string();
-
- // Parse pool from GPU param (e.g., "eval-l4/l4")
- if !gpu.is_empty() && gpu.contains('/') {
- let parts: Vec<&str> = gpu.splitn(2, '/').collect();
- pool_name = parts[0].to_string();
- gpu = parts[1].to_string();
- }
-
- // Validate the caller-supplied pool against a strict allowlist BEFORE it can
- // flow into the JetStream work subject
- // `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 "gateway picks the default pool" and is left
- // untouched.
- if !pool_name.is_empty() && !is_valid_pool_name(&pool_name) {
- metrics::record_rejected_request_for_pool("unknown", &gpu, &bundle, "invalid_pool");
- return Err(Box::new(endpoint_error_response(
- endpoint,
- StatusCode::BAD_REQUEST,
- err_code::INVALID_REQUEST,
- oai_type::INVALID_REQUEST,
- oai_code::INVALID_REQUEST,
- Some("pool"),
- "Invalid pool name: only [A-Za-z0-9_-] are allowed (max 128 chars)",
- )));
- }
- if !pool_name.is_empty() {
- pool_name = normalize_pool_name(&pool_name);
- }
- let model_pool = state.model_registry.get_model_pool_name(&model_name);
- if let Err(message) = apply_model_pool_default(
- &mut pool_name,
- model_pool.as_deref(),
- Some(&state.pool_manager),
- )
- .await
- {
- metrics::record_rejected_request_for_pool(&pool_name, &gpu, &bundle, "pool_mismatch");
- return Err(Box::new(endpoint_error_response(
- endpoint,
- StatusCode::BAD_REQUEST,
- err_code::INVALID_REQUEST,
- oai_type::INVALID_REQUEST,
- oai_code::INVALID_REQUEST,
- Some("pool"),
+ // Machine-profile + pool resolution, shared with the generation path via
+ // `resolve_profile_and_pool`. Errors are rendered here in this endpoint's
+ // envelope (native `detail` or OpenAI, per `endpoint_error_response`).
+ let ProfilePoolRoute {
+ gpu,
+ pool_name,
+ gpu_configured,
+ } = match resolve_profile_and_pool(state, headers, &model_name).await {
+ Ok(route) => route,
+ Err(ProfilePoolError::InvalidPool { gpu }) => {
+ metrics::record_rejected_request_for_pool("unknown", &gpu, &bundle, "invalid_pool");
+ return Err(Box::new(endpoint_error_response(
+ endpoint,
+ StatusCode::BAD_REQUEST,
+ err_code::INVALID_REQUEST,
+ oai_type::INVALID_REQUEST,
+ oai_code::INVALID_REQUEST,
+ Some("pool"),
+ "Invalid pool name: only [A-Za-z0-9_-] are allowed (max 128 chars)",
+ )));
+ }
+ Err(ProfilePoolError::PoolMismatch {
+ gpu,
+ pool_name,
message,
- )));
- }
-
- // Resolve bare GPU to spot variant
- if !gpu.is_empty() && !state.config.configured_gpus.is_empty() {
- gpu = resolve_machine_profile(&gpu, &state.config.gpu_profile_map);
- }
-
- // Validate GPU is configured. Compute this *before* tagging the metric label
- // slot so an arbitrary, unconfigured, caller-supplied GPU never reaches a
- // Prometheus label (unbounded cardinality / DoS).
- let gpu_configured = gpu.is_empty()
- || state.config.configured_gpus.is_empty()
- || state
- .config
- .configured_gpus
- .iter()
- .any(|cg| cg.eq_ignore_ascii_case(&gpu));
+ }) => {
+ metrics::record_rejected_request_for_pool(&pool_name, &gpu, &bundle, "pool_mismatch");
+ return Err(Box::new(endpoint_error_response(
+ endpoint,
+ StatusCode::BAD_REQUEST,
+ err_code::INVALID_REQUEST,
+ oai_type::INVALID_REQUEST,
+ oai_code::INVALID_REQUEST,
+ Some("pool"),
+ message,
+ )));
+ }
+ };
Ok(RoutingResult {
model_name,
@@ -1520,7 +1595,7 @@ async fn proxy_request(
let publish_fut = queue_mode_proxy(
&state,
- work_publisher,
+ work_publisher.as_ref(),
endpoint,
&model_name,
&bundle,
@@ -1595,7 +1670,7 @@ fn should_trace_proxy_request(endpoint: &str) -> bool {
#[allow(clippy::too_many_arguments)]
async fn queue_mode_proxy(
state: &AppState,
- work_publisher: &publisher::WorkPublisher,
+ work_publisher: &dyn WorkDispatcher,
endpoint: &str,
model: &str,
bundle: &str,
@@ -2115,7 +2190,7 @@ async fn queue_mode_proxy(
/// the client-disconnect / axum task-abort path to trigger the cancel
/// (axum drops the handler task when the connection closes).
pub(crate) struct StreamCancelGuard {
- publisher: Arc<publisher::WorkPublisher>,
+ publisher: Arc<dyn WorkDispatcher>,
request_id: String,
model: String,
pool: String,
@@ -2124,7 +2199,7 @@ pub(crate) struct StreamCancelGuard {
impl StreamCancelGuard {
pub(crate) fn new(
- publisher: Arc<publisher::WorkPublisher>,
+ publisher: Arc<dyn WorkDispatcher>,
request_id: String,
model: String,
pool: String,
@@ -2293,7 +2368,7 @@ pub(crate) enum StreamingDriverErr {
#[allow(clippy::too_many_arguments)]
pub(crate) async fn run_streaming_generate(
state: &AppState,
- work_publisher: Arc<publisher::WorkPublisher>,
+ work_publisher: Arc<dyn WorkDispatcher>,
// DISPLAY id (the requested model) — drives metric labels + the cancel
// guard. ``dispatch_model`` below is the id actually published to NATS /
// the work item (the grammar ``:no-spec`` variant when routing fired);
@@ -2309,7 +2384,7 @@ pub(crate) async fn run_streaming_generate(
params: &publisher::WorkParams,
) -> Result<StreamingDriverOk, StreamingDriverErr> {
let publish_start = Instant::now();
- // Resolve the routing key, build the HRW ring snapshot,
+ // Resolve the routing key, build the pressure-aware routing snapshot,
// pick a worker. Falls back to pool publish when:
// - generate params are absent (caller will surface a 400).
// - the resolved key has no hash (no routing_key / prompt_cache_key
@@ -2391,7 +2466,7 @@ pub(crate) async fn run_streaming_generate(
worker_id = %worker_id,
key = %crate::routing::fmt_key_hash(resolved_key.hash.unwrap_or(0)),
source = resolved_key.source.as_label(),
- "HRW pick"
+ "pressure-aware worker pick"
);
(
publisher::PublishTarget::Worker {
@@ -2767,6 +2842,27 @@ pub(crate) fn worker_error_openai_type(code: &str) -> &'static str {
}
}
+/// Retry semantics for a transient worker-emitted error code: the
+/// `Retry-After` header value (seconds, as a string) paired with the
+/// canonical SIE error code, or `None` when the code is not a known
+/// retryable signal.
+///
+/// Single source of truth shared by the streaming (OpenAI-envelope) and unary
+/// (SIE-native [`build_retryable_error_response`]) paths — the two surfaces
+/// render the error body differently but agree on the retry semantics. Pairs
+/// with [`worker_error_http_status`] / [`worker_error_openai_type`].
+fn worker_error_retry_after(code: &str) -> Option<(&'static str, &'static str)> {
+ match code {
+ RESOURCE_EXHAUSTED_ERROR_CODE => Some((
+ RESOURCE_EXHAUSTED_RETRY_AFTER,
+ RESOURCE_EXHAUSTED_ERROR_CODE,
+ )),
+ MODEL_LOADING_ERROR_CODE => Some((MODEL_LOADING_RETRY_AFTER, MODEL_LOADING_ERROR_CODE)),
+ LORA_LOADING_ERROR_CODE => Some((LORA_LOADING_RETRY_AFTER, LORA_LOADING_ERROR_CODE)),
+ _ => None,
+ }
+}
+
/// Build the OpenAI-envelope error response for one of the
/// :class:`StreamingDriverErr` variants. Used by both
/// ``proxy_generate`` (via :func:`queue_mode_streaming_generate`) and
@@ -2902,19 +2998,7 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {
HeaderValue::from_static("1"),
);
}
- let retryable = match code.as_str() {
- RESOURCE_EXHAUSTED_ERROR_CODE => Some((
- RESOURCE_EXHAUSTED_RETRY_AFTER,
- RESOURCE_EXHAUSTED_ERROR_CODE,
- )),
- MODEL_LOADING_ERROR_CODE => {
- Some((MODEL_LOADING_RETRY_AFTER, MODEL_LOADING_ERROR_CODE))
- }
- LORA_LOADING_ERROR_CODE => {
- Some((LORA_LOADING_RETRY_AFTER, LORA_LOADING_ERROR_CODE))
- }
- _ => None,
- };
+ let retryable = worker_error_retry_after(code.as_str());
if let Some((retry_after, error_code)) = retryable {
resp.headers_mut().insert(
HeaderName::from_static("retry-after"),
@@ -2982,7 +3066,7 @@ pub(crate) fn build_streaming_publish_failed_for_sse(
#[allow(clippy::too_many_arguments)]
async fn queue_mode_streaming_generate(
state: &AppState,
- work_publisher: Arc<publisher::WorkPublisher>,
+ work_publisher: Arc<dyn WorkDispatcher>,
// DISPLAY id (requested model) — response body, success metrics, audit log.
model: &str,
// DISPATCH id (grammar ``:no-spec`` variant when routed) — NATS subject +
@@ -5007,7 +5091,7 @@ struct ResolvedRoute {
effective_pool: String,
effective_machine_profile: String,
bundle_config_hash: String,
- work_publisher: Arc<publisher::WorkPublisher>,
+ work_publisher: Arc<dyn WorkDispatcher>,
token_id: String,
content_length: i64,
}
@@ -5023,93 +5107,69 @@ async fn resolve_generation_route(
bundle: &str,
model_name: &str,
) -> Result<ResolvedRoute, Response> {
- let mut gpu = hdr
- .get("x-sie-machine-profile")
- .and_then(|v| v.to_str().ok())
- .unwrap_or("")
- .to_string();
- let mut pool_name = hdr
- .get("x-sie-pool")
- .and_then(|v| v.to_str().ok())
- .unwrap_or("")
- .to_string();
-
- if !gpu.is_empty() && gpu.contains('/') {
- let parts: Vec<&str> = gpu.splitn(2, '/').collect();
- pool_name = parts[0].to_string();
- gpu = parts[1].to_string();
- }
-
- if !pool_name.is_empty() && !is_valid_pool_name(&pool_name) {
- 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(),
- oai_type::INVALID_REQUEST,
- Some("X-SIE-Pool"),
- oai_code::INVALID_REQUEST,
- )),
- )
- .into_response());
- }
- if !pool_name.is_empty() {
- pool_name = normalize_pool_name(&pool_name);
- }
- let model_pool = state.model_registry.get_model_pool_name(model_name);
- if let Err(message) = apply_model_pool_default(
- &mut pool_name,
- model_pool.as_deref(),
- Some(&state.pool_manager),
- )
- .await
- {
- metrics::record_rejected_request_for_pool(&pool_name, &gpu, bundle, "pool_mismatch");
- return Err((
- StatusCode::BAD_REQUEST,
- Json(json_openai_error(
- message,
- oai_type::INVALID_REQUEST,
- Some("X-SIE-Pool"),
- oai_code::INVALID_REQUEST,
- )),
- )
- .into_response());
- }
-
- if !gpu.is_empty() && !state.config.configured_gpus.is_empty() {
- gpu = resolve_machine_profile(&gpu, &state.config.gpu_profile_map);
- }
-
- if !gpu.is_empty() && !state.config.configured_gpus.is_empty() {
- let found = state
- .config
- .configured_gpus
- .iter()
- .any(|cg| cg.eq_ignore_ascii_case(&gpu));
- if !found {
- 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",
- );
+ // Machine-profile + pool resolution, shared with the primitive path via
+ // `resolve_profile_and_pool`. Errors are rendered here in the OpenAI
+ // envelope (`json_openai_error`), preserving the compat surface.
+ let ProfilePoolRoute {
+ gpu,
+ pool_name,
+ gpu_configured,
+ } = match resolve_profile_and_pool(state, hdr, model_name).await {
+ Ok(route) => route,
+ Err(ProfilePoolError::InvalidPool { gpu }) => {
+ metrics::record_rejected_request_for_pool("unknown", &gpu, bundle, "invalid_pool");
return Err((
- StatusCode::SERVICE_UNAVAILABLE,
+ StatusCode::BAD_REQUEST,
Json(json_openai_error(
- format!("GPU type '{gpu}' is not configured in this cluster."),
- oai_type::SERVER_ERROR,
- Some("X-SIE-MACHINE-PROFILE"),
- oai_code::TRANSPORT_FAILURE,
+ "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,
+ )),
+ )
+ .into_response());
+ }
+ Err(ProfilePoolError::PoolMismatch {
+ gpu,
+ pool_name,
+ message,
+ }) => {
+ metrics::record_rejected_request_for_pool(&pool_name, &gpu, bundle, "pool_mismatch");
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ message,
+ oai_type::INVALID_REQUEST,
+ Some("X-SIE-Pool"),
+ oai_code::INVALID_REQUEST,
)),
)
.into_response());
}
+ };
+
+ if !gpu_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(
+ format!("GPU type '{gpu}' is not configured in this cluster."),
+ oai_type::SERVER_ERROR,
+ Some("X-SIE-MACHINE-PROFILE"),
+ oai_code::TRANSPORT_FAILURE,
+ )),
+ )
+ .into_response());
}
let Some(work_publisher_arc) = state.work_publisher.clone() else {
@@ -7154,24 +7214,23 @@ fn batch_direct_fallback_delay(request_timeout_s: f64) -> Duration {
/// The worker is **not** marked unhealthy — these codes are transient
/// per-request signals, not worker-health signals.
fn build_retryable_error_response(code: &'static str, message: &str) -> Response {
- let retry_after = match code {
- RESOURCE_EXHAUSTED_ERROR_CODE => RESOURCE_EXHAUSTED_RETRY_AFTER,
- MODEL_LOADING_ERROR_CODE => MODEL_LOADING_RETRY_AFTER,
- LORA_LOADING_ERROR_CODE => LORA_LOADING_RETRY_AFTER,
- // Defensive default. Should be unreachable given the
- // ``unanimous_retryable_error_code`` allow-list (the only caller
- // pathway), but if a future code is added there without here, fall
- // back to the most conservative retry hint we know rather than
- // panicking in production. The ``debug_assert!`` ensures any such
- // mismatch fails loudly in tests / dev builds.
- _ => {
+ // Retry hint via the shared `worker_error_retry_after` classifier — the
+ // same source of truth the streaming path uses.
+ let retry_after = worker_error_retry_after(code)
+ .map(|(retry_after, _)| retry_after)
+ .unwrap_or_else(|| {
+ // Defensive default. Should be unreachable given the
+ // ``unanimous_retryable_error_code`` allow-list (the only caller
+ // pathway), but if a future code is added there without here, fall
+ // back to the most conservative retry hint we know rather than
+ // panicking in production. The ``debug_assert!`` ensures any such
+ // mismatch fails loudly in tests / dev builds.
debug_assert!(
false,
"build_retryable_error_response called with unmapped code: {code}"
);
MODEL_LOADING_RETRY_AFTER
- }
- };
+ });
let mut resp = (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({
@@ -10801,6 +10860,8 @@ mod tests {
name: "assigned-cold".to_string(),
ready: true,
gpu_count: 1,
+ total_gpu_slots: Some(1),
+ ready_gpu_slots: Some(1),
machine_profile: "l4".to_string(),
pool_name: DEFAULT_POOL_NAME.to_string(),
bundle: "default".to_string(),
@@ -10809,6 +10870,8 @@ mod tests {
models: Vec::new(),
gpus: Vec::new(),
queue_depth: None,
+ pending_cost: None,
+ inflight_batches: None,
memory_used_bytes: None,
memory_total_bytes: None,
saturated: false,
@@ -11707,6 +11770,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
};
let body = build_generate_success_body("Qwen/Qwen3-4B-Instruct", &[&r], false);
@@ -12099,6 +12163,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
}
}
@@ -12119,6 +12184,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
}
}
@@ -13153,6 +13219,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
};
let resp_body = result.result_msgpack.clone();
@@ -13189,6 +13256,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
},
publisher::WorkResult {
@@ -13206,6 +13274,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
},
];
@@ -13399,6 +13468,8 @@ mod tests {
name: "worker-1".into(),
ready: true,
gpu_count: 1,
+ total_gpu_slots: None,
+ ready_gpu_slots: None,
machine_profile: gpu.into(),
pool_name: pool.into(),
bundle: bundle.into(),
@@ -13410,6 +13481,8 @@ mod tests {
memory_total_bytes: 4000,
}],
queue_depth: None,
+ pending_cost: None,
+ inflight_batches: None,
memory_used_bytes: None,
memory_total_bytes: None,
saturated: false,
@@ -16646,6 +16719,32 @@ mod tests {
);
}
+ /// The shared retry classifier maps each retryable worker code to its
+ /// `Retry-After` + canonical code and returns `None` for terminal codes.
+ /// Locks the single source of truth the streaming and unary error paths
+ /// share (see `worker_error_retry_after`).
+ #[test]
+ fn test_worker_error_retry_after_maps_retryable_codes() {
+ assert_eq!(
+ worker_error_retry_after(RESOURCE_EXHAUSTED_ERROR_CODE),
+ Some((
+ RESOURCE_EXHAUSTED_RETRY_AFTER,
+ RESOURCE_EXHAUSTED_ERROR_CODE
+ ))
+ );
+ assert_eq!(
+ worker_error_retry_after(MODEL_LOADING_ERROR_CODE),
+ Some((MODEL_LOADING_RETRY_AFTER, MODEL_LOADING_ERROR_CODE))
+ );
+ assert_eq!(
+ worker_error_retry_after(LORA_LOADING_ERROR_CODE),
+ Some((LORA_LOADING_RETRY_AFTER, LORA_LOADING_ERROR_CODE))
+ );
+ // Terminal / non-retryable codes carry no retry hint.
+ assert_eq!(worker_error_retry_after("invalid_request"), None);
+ assert_eq!(worker_error_retry_after("transport_failure"), None);
+ }
+
// ── SSE: generate-endpoint `stream` flag extraction ────────────
/// JSON body without ``stream`` → ``Ok(false)``. The aggregating
diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rs
index 20eb5c95d..e5bb3f3f8 100644
--- a/packages/sie_gateway/src/handlers/sse.rs
+++ b/packages/sie_gateway/src/handlers/sse.rs
@@ -52,7 +52,8 @@ use tokio_stream::wrappers::ReceiverStream;
use tracing::{debug, warn};
use crate::metrics;
-use crate::queue::publisher::{self, WorkPublisher};
+use crate::queue::dispatch::WorkDispatcher;
+use crate::queue::publisher;
use crate::queue::streaming::{ChunkEnvelope, StreamOutcome};
use crate::server::AppState;
@@ -75,7 +76,7 @@ pub enum SseEndpoint {
/// :func:`build_sse_response`.
pub struct SseParams<'a> {
pub state: &'a AppState,
- pub work_publisher: Arc<WorkPublisher>,
+ pub work_publisher: Arc<dyn WorkDispatcher>,
/// DISPLAY id (the requested model) — surfaced in the streamed chunk
/// ``model`` field and the routing/timeout metric labels.
pub model: String,
@@ -360,7 +361,7 @@ struct SseDriverArgs {
event_tx: tokio::sync::mpsc::Sender<Result<Event, Infallible>>,
chunk_rx: broadcast::Receiver<ChunkEnvelope>,
outcome_rx: tokio::sync::oneshot::Receiver<StreamOutcome>,
- publisher: Arc<WorkPublisher>,
+ publisher: Arc<dyn WorkDispatcher>,
request_id: String,
model: String,
pool: String,
diff --git a/packages/sie_gateway/src/lib.rs b/packages/sie_gateway/src/lib.rs
new file mode 100644
index 000000000..d29fc914d
--- /dev/null
+++ b/packages/sie_gateway/src/lib.rs
@@ -0,0 +1,30 @@
+//! Library target for the SIE gateway.
+//!
+//! Exposes the gateway's module tree as a library so a downstream
+//! composition crate can reuse the HTTP router, registries, and the
+//! [`queue::dispatch::WorkDispatcher`] seam without forking the
+//! binary. The `sie-gateway` binary keeps its own module tree in
+//! `main.rs`; the two targets compile the same module files
+//! independently — an accepted POC tradeoff (a single-tree split where
+//! `main.rs` consumes the lib is deferred).
+//!
+//! Everything here is a plain re-declaration of the binary's modules;
+//! no lib-only code lives in this file.
+
+pub mod config;
+pub mod discovery;
+pub mod endpoint;
+pub mod error;
+pub mod handlers;
+pub mod health_mode;
+pub mod http_error;
+pub mod metrics;
+pub mod middleware;
+pub mod nats;
+pub mod observability;
+pub mod openapi;
+pub mod queue;
+pub mod routing;
+pub mod server;
+pub mod state;
+pub mod types;
diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rs
index a70b6dba4..3bcb0831b 100644
--- a/packages/sie_gateway/src/main.rs
+++ b/packages/sie_gateway/src/main.rs
@@ -708,7 +708,10 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {
config: Arc::clone(&config),
model_registry: Arc::clone(&model_registry),
pool_manager: Arc::clone(&pool_manager),
- work_publisher,
+ // Handlers see the transport-neutral dispatch trait; lifecycle
+ // methods stay on the concrete clones retained above.
+ work_publisher: work_publisher
+ .map(|publisher| publisher as Arc<dyn queue::dispatch::WorkDispatcher>),
demand_tracker,
config_epoch: config_epoch.clone(),
});
diff --git a/packages/sie_gateway/src/metrics.rs b/packages/sie_gateway/src/metrics.rs
index c97712957..ffa9b894e 100644
--- a/packages/sie_gateway/src/metrics.rs
+++ b/packages/sie_gateway/src/metrics.rs
@@ -112,6 +112,11 @@ pub static REGISTRY: LazyLock<Registry> = LazyLock::new(|| {
r.register(Box::new(ACTIVE_LEASE_GPUS.clone())).unwrap();
r.register(Box::new(WORKER_COUNT.clone())).unwrap();
r.register(Box::new(WORKER_QUEUE_DEPTH.clone())).unwrap();
+ r.register(Box::new(WORKER_READY_GPU_SLOTS.clone()))
+ .unwrap();
+ r.register(Box::new(WORKER_PENDING_COST.clone())).unwrap();
+ r.register(Box::new(WORKER_INFLIGHT_BATCHES.clone()))
+ .unwrap();
r.register(Box::new(WORKER_MEMORY_USED.clone())).unwrap();
r.register(Box::new(MODEL_WORKERS.clone())).unwrap();
r.register(Box::new(QUEUE_PUBLISH_SECONDS.clone())).unwrap();
@@ -339,6 +344,39 @@ pub static WORKER_QUEUE_DEPTH: LazyLock<GaugeVec> = LazyLock::new(|| {
.unwrap()
});
+pub static WORKER_READY_GPU_SLOTS: LazyLock<GaugeVec> = LazyLock::new(|| {
+ GaugeVec::new(
+ Opts::new(
+ "sie_gateway_worker_ready_gpu_slots",
+ "Per-worker GPU slots currently ready to receive work",
+ ),
+ &["pool", "worker", "machine_profile", "bundle"],
+ )
+ .unwrap()
+});
+
+pub static WORKER_PENDING_COST: LazyLock<GaugeVec> = LazyLock::new(|| {
+ GaugeVec::new(
+ Opts::new(
+ "sie_gateway_worker_pending_cost",
+ "Per-worker scheduler pending cost as reported by the worker sidecar",
+ ),
+ &["pool", "worker", "machine_profile", "bundle"],
+ )
+ .unwrap()
+});
+
+pub static WORKER_INFLIGHT_BATCHES: LazyLock<GaugeVec> = LazyLock::new(|| {
+ GaugeVec::new(
+ Opts::new(
+ "sie_gateway_worker_inflight_batches",
+ "Per-worker batches currently in flight as reported by the worker sidecar",
+ ),
+ &["pool", "worker", "machine_profile", "bundle"],
+ )
+ .unwrap()
+});
+
// 8. sie_gateway_worker_memory_used_bytes
pub static WORKER_MEMORY_USED: LazyLock<GaugeVec> = LazyLock::new(|| {
GaugeVec::new(
@@ -1060,6 +1098,9 @@ pub struct WorkerSnapshot {
/// workers that pre-date the pool registration message.
pub pool_name: String,
pub queue_depth: i32,
+ pub ready_gpu_slots: i32,
+ pub pending_cost: i64,
+ pub inflight_batches: i32,
pub memory_used_bytes: i64,
pub healthy: bool,
}
@@ -1072,6 +1113,9 @@ pub fn update_worker_metrics(workers: &[WorkerSnapshot]) {
// long-gone worker as still active. `ACTIVE_LEASE_GPUS` uses the
// same reset-then-repopulate pattern in `update_pool_metrics`.
WORKER_QUEUE_DEPTH.reset();
+ WORKER_READY_GPU_SLOTS.reset();
+ WORKER_PENDING_COST.reset();
+ WORKER_INFLIGHT_BATCHES.reset();
WORKER_MEMORY_USED.reset();
// Keep `kv_reservation_known` series in sync with the
// current worker set. The actual value lands once the worker
@@ -1096,6 +1140,15 @@ pub fn update_worker_metrics(workers: &[WorkerSnapshot]) {
WORKER_QUEUE_DEPTH
.with_label_values(&[&pool_name, &w.name, &w.machine_profile, &w.bundle])
.set(w.queue_depth as f64);
+ WORKER_READY_GPU_SLOTS
+ .with_label_values(&[&pool_name, &w.name, &w.machine_profile, &w.bundle])
+ .set(w.ready_gpu_slots as f64);
+ WORKER_PENDING_COST
+ .with_label_values(&[&pool_name, &w.name, &w.machine_profile, &w.bundle])
+ .set(w.pending_cost as f64);
+ WORKER_INFLIGHT_BATCHES
+ .with_label_values(&[&pool_name, &w.name, &w.machine_profile, &w.bundle])
+ .set(w.inflight_batches as f64);
WORKER_MEMORY_USED
.with_label_values(&[&w.name, &w.machine_profile, &w.bundle])
.set(w.memory_used_bytes as f64);
@@ -1259,6 +1312,9 @@ mod tests {
ACTIVE_LEASE_GPUS.reset();
WORKER_COUNT.reset();
WORKER_QUEUE_DEPTH.reset();
+ WORKER_READY_GPU_SLOTS.reset();
+ WORKER_PENDING_COST.reset();
+ WORKER_INFLIGHT_BATCHES.reset();
WORKER_MEMORY_USED.reset();
MODEL_WORKERS.reset();
PENDING_DEMAND.reset();
@@ -1564,6 +1620,9 @@ mod tests {
bundle: "default".to_string(),
pool_name: "pool-a".to_string(),
queue_depth: 5,
+ ready_gpu_slots: 1,
+ pending_cost: 55,
+ inflight_batches: 2,
memory_used_bytes: 1000,
healthy: true,
},
@@ -1573,6 +1632,9 @@ mod tests {
bundle: "premium".to_string(),
pool_name: "pool-b".to_string(),
queue_depth: 2,
+ ready_gpu_slots: 0,
+ pending_cost: 20,
+ inflight_batches: 1,
memory_used_bytes: 2000,
healthy: false,
},
@@ -1584,6 +1646,10 @@ mod tests {
let unhealthy = WORKER_COUNT.with_label_values(&["unhealthy"]).get();
assert!((healthy - 1.0).abs() < f64::EPSILON);
assert!((unhealthy - 1.0).abs() < f64::EPSILON);
+ let ready_slots = WORKER_READY_GPU_SLOTS
+ .with_label_values(&["pool-a", "w1", "l4", "default"])
+ .get();
+ assert!((ready_slots - 1.0).abs() < f64::EPSILON);
}
#[test]
@@ -1598,29 +1664,51 @@ mod tests {
bundle: "default".to_string(),
pool_name: "Customer-Acme".to_string(),
queue_depth: 5,
+ ready_gpu_slots: 2,
+ pending_cost: 55,
+ inflight_batches: 3,
memory_used_bytes: 1000,
healthy: true,
}]);
- let canonical = WORKER_QUEUE_DEPTH
+ let queue_depth = WORKER_QUEUE_DEPTH
+ .with_label_values(&["customer-acme", "w1", "l4", "default"])
+ .get();
+ assert!((queue_depth - 5.0).abs() < f64::EPSILON);
+ let ready_slots = WORKER_READY_GPU_SLOTS
.with_label_values(&["customer-acme", "w1", "l4", "default"])
.get();
- assert!((canonical - 5.0).abs() < f64::EPSILON);
+ assert!((ready_slots - 2.0).abs() < f64::EPSILON);
+ let pending_cost = WORKER_PENDING_COST
+ .with_label_values(&["customer-acme", "w1", "l4", "default"])
+ .get();
+ assert!((pending_cost - 55.0).abs() < f64::EPSILON);
+ let inflight_batches = WORKER_INFLIGHT_BATCHES
+ .with_label_values(&["customer-acme", "w1", "l4", "default"])
+ .get();
+ assert!((inflight_batches - 3.0).abs() < f64::EPSILON);
let families = REGISTRY.gather();
- let mixed_case_present = families
- .iter()
- .filter(|mf| mf.name() == "sie_gateway_worker_queue_depth")
- .flat_map(|mf| mf.get_metric().iter())
- .any(|m| {
- m.get_label()
- .iter()
- .any(|l| l.name() == "pool" && l.value() == "Customer-Acme")
- });
- assert!(
- !mixed_case_present,
- "worker queue-depth labels must use canonical lowercase pool names"
- );
+ for metric_name in [
+ "sie_gateway_worker_queue_depth",
+ "sie_gateway_worker_ready_gpu_slots",
+ "sie_gateway_worker_pending_cost",
+ "sie_gateway_worker_inflight_batches",
+ ] {
+ let mixed_case_present = families
+ .iter()
+ .filter(|mf| mf.name() == metric_name)
+ .flat_map(|mf| mf.get_metric().iter())
+ .any(|m| {
+ m.get_label()
+ .iter()
+ .any(|l| l.name() == "pool" && l.value() == "Customer-Acme")
+ });
+ assert!(
+ !mixed_case_present,
+ "{metric_name} labels must use canonical lowercase pool names"
+ );
+ }
}
#[test]
@@ -1656,6 +1744,9 @@ mod tests {
bundle: "default".to_string(),
pool_name: "default-pool".to_string(),
queue_depth: 42,
+ ready_gpu_slots: 1,
+ pending_cost: 420,
+ inflight_batches: 3,
memory_used_bytes: 123_456,
healthy: true,
}];
@@ -1673,6 +1764,9 @@ mod tests {
bundle: "premium".to_string(),
pool_name: "premium-pool".to_string(),
queue_depth: 7,
+ ready_gpu_slots: 1,
+ pending_cost: 70,
+ inflight_batches: 1,
memory_used_bytes: 999,
healthy: true,
}];
diff --git a/packages/sie_gateway/src/middleware/audit.rs b/packages/sie_gateway/src/middleware/audit.rs
index c1e300265..e2e9ca9f7 100644
--- a/packages/sie_gateway/src/middleware/audit.rs
+++ b/packages/sie_gateway/src/middleware/audit.rs
@@ -12,6 +12,11 @@ use tracing::info;
pub struct AuditLayer;
impl AuditLayer {
+ // `new_without_default` only fires on exported items, so this lint
+ // surfaced when the lib target (src/lib.rs) made the type public API.
+ // Kept as an `allow` rather than a `Default` impl to leave the OSS
+ // surface unchanged.
+ #[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self
}
diff --git a/packages/sie_gateway/src/queue/dispatch.rs b/packages/sie_gateway/src/queue/dispatch.rs
new file mode 100644
index 000000000..b345acfcf
--- /dev/null
+++ b/packages/sie_gateway/src/queue/dispatch.rs
@@ -0,0 +1,261 @@
+//! Transport-neutral dispatch seam between the HTTP handlers and the
+//! queue publisher (roadmap P2.1, design §4.2/§13).
+//!
+//! [`WorkDispatcher`] captures the exact handler-facing surface of
+//! [`WorkPublisher`] — publish, cancel, republish, and pending-state
+//! snapshots — so handlers depend on `Arc<dyn WorkDispatcher>` rather
+//! than the concrete NATS-backed publisher. NATS stays the only
+//! implementation; lifecycle methods (inbox subscription, backpressure
+//! monitor, cleanup, drain) deliberately stay on the concrete type
+//! owned by `main.rs`.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use async_trait::async_trait;
+use tokio::sync::{broadcast, oneshot};
+use tracing::warn;
+
+use super::publisher::WorkPublisher;
+// Re-exports for future consumers of the dispatch seam (also serve as
+// this module's own imports for the trait signatures below).
+pub use super::publisher::{PendingGenerationSnapshot, PublishTarget, WorkParams, WorkResult};
+pub use super::streaming::{ChunkEnvelope, StreamOutcome};
+
+/// Handler→publisher dispatch boundary. Signatures mirror the inherent
+/// [`WorkPublisher`] methods exactly; see the inherent methods for the
+/// full behavioural documentation.
+#[async_trait]
+pub trait WorkDispatcher: Send + Sync {
+ #[allow(clippy::too_many_arguments)]
+ async fn publish_work(
+ &self,
+ target: PublishTarget,
+ admission_pool: &str,
+ endpoint: &str,
+ model: &str,
+ engine: &str,
+ bundle_config_hash: &str,
+ items: Vec<rmpv::Value>,
+ params: &WorkParams,
+ ) -> Result<(String, oneshot::Receiver<Vec<WorkResult>>), String>;
+
+ #[allow(clippy::too_many_arguments)]
+ async fn publish_generate_streaming(
+ &self,
+ target: PublishTarget,
+ display_model: &str,
+ engine: &str,
+ bundle_config_hash: &str,
+ params: &WorkParams,
+ admission_pool: &str,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<StreamOutcome>,
+ Arc<tokio::sync::Notify>,
+ ),
+ String,
+ >;
+
+ #[allow(clippy::too_many_arguments)]
+ async fn publish_generate_streaming_sse(
+ &self,
+ target: PublishTarget,
+ display_model: &str,
+ engine: &str,
+ bundle_config_hash: &str,
+ params: &WorkParams,
+ admission_pool: &str,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<StreamOutcome>,
+ broadcast::Receiver<ChunkEnvelope>,
+ ),
+ String,
+ >;
+
+ async fn publish_cancel(&self, request_id: &str);
+
+ async fn republish_to_pool(
+ &self,
+ request_id: &str,
+ reason: &'static str,
+ ) -> Result<bool, String>;
+
+ async fn republish_pending_result_to_pool(
+ &self,
+ request_id: &str,
+ reason: &'static str,
+ ) -> Result<bool, String>;
+
+ fn drop_pending_stream(&self, request_id: &str);
+
+ fn pending_generation_snapshot(&self) -> PendingGenerationSnapshot;
+
+ fn pending_generation_for_model(&self, model_id: &str) -> PendingGenerationSnapshot;
+
+ fn stream_observed_first_chunk(&self, request_id: &str) -> bool;
+
+ fn stream_chunk_timing(&self, request_id: &str) -> Option<(Option<Instant>, Option<Instant>)>;
+}
+
+#[async_trait]
+impl WorkDispatcher for WorkPublisher {
+ async fn publish_work(
+ &self,
+ target: PublishTarget,
+ admission_pool: &str,
+ endpoint: &str,
+ model: &str,
+ engine: &str,
+ bundle_config_hash: &str,
+ items: Vec<rmpv::Value>,
+ params: &WorkParams,
+ ) -> Result<(String, oneshot::Receiver<Vec<WorkResult>>), String> {
+ WorkPublisher::publish_work(
+ self,
+ target,
+ admission_pool,
+ endpoint,
+ model,
+ engine,
+ bundle_config_hash,
+ items,
+ params,
+ )
+ .await
+ }
+
+ async fn publish_generate_streaming(
+ &self,
+ target: PublishTarget,
+ display_model: &str,
+ engine: &str,
+ bundle_config_hash: &str,
+ params: &WorkParams,
+ admission_pool: &str,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<StreamOutcome>,
+ Arc<tokio::sync::Notify>,
+ ),
+ String,
+ > {
+ WorkPublisher::publish_generate_streaming(
+ self,
+ target,
+ display_model,
+ engine,
+ bundle_config_hash,
+ params,
+ admission_pool,
+ )
+ .await
+ }
+
+ async fn publish_generate_streaming_sse(
+ &self,
+ target: PublishTarget,
+ display_model: &str,
+ engine: &str,
+ bundle_config_hash: &str,
+ params: &WorkParams,
+ admission_pool: &str,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<StreamOutcome>,
+ broadcast::Receiver<ChunkEnvelope>,
+ ),
+ String,
+ > {
+ WorkPublisher::publish_generate_streaming_sse(
+ self,
+ target,
+ display_model,
+ engine,
+ bundle_config_hash,
+ params,
+ admission_pool,
+ )
+ .await
+ }
+
+ async fn publish_cancel(&self, request_id: &str) {
+ WorkPublisher::publish_cancel(self, request_id).await
+ }
+
+ async fn republish_to_pool(
+ &self,
+ request_id: &str,
+ reason: &'static str,
+ ) -> Result<bool, String> {
+ WorkPublisher::republish_to_pool(self, request_id, reason).await
+ }
+
+ async fn republish_pending_result_to_pool(
+ &self,
+ request_id: &str,
+ reason: &'static str,
+ ) -> Result<bool, String> {
+ WorkPublisher::republish_pending_result_to_pool(self, request_id, reason).await
+ }
+
+ fn drop_pending_stream(&self, request_id: &str) {
+ WorkPublisher::drop_pending_stream(self, request_id)
+ }
+
+ fn pending_generation_snapshot(&self) -> PendingGenerationSnapshot {
+ WorkPublisher::pending_generation_snapshot(self)
+ }
+
+ fn pending_generation_for_model(&self, model_id: &str) -> PendingGenerationSnapshot {
+ WorkPublisher::pending_generation_for_model(self, model_id)
+ }
+
+ fn stream_observed_first_chunk(&self, request_id: &str) -> bool {
+ WorkPublisher::stream_observed_first_chunk(self, request_id)
+ }
+
+ fn stream_chunk_timing(&self, request_id: &str) -> Option<(Option<Instant>, Option<Instant>)> {
+ WorkPublisher::stream_chunk_timing(self, request_id)
+ }
+}
+
+/// Extension methods that need an owned `Arc<dyn WorkDispatcher>` handle
+/// (they spawn detached tasks holding a clone), so they cannot live on
+/// the object-safe [`WorkDispatcher`] trait itself.
+pub trait WorkDispatcherExt {
+ /// Arm a one-shot recovery for non-streaming worker-direct batch work.
+ ///
+ /// Capped logical pools direct-dispatch encode/score/extract to one
+ /// admitted worker so unassigned peers do not burn the JetStream
+ /// delivery budget. If that worker or its private consumer disappears
+ /// after the gateway publishes, the worker-specific stream cannot fail
+ /// over by itself. This timer republishes any still-missing items to the
+ /// lane's pool subject once; late duplicate results are harmless because
+ /// the result collector removes itself on first complete response.
+ fn spawn_batch_direct_fallback(&self, request_id: String, delay: Duration);
+}
+
+impl WorkDispatcherExt for Arc<dyn WorkDispatcher> {
+ fn spawn_batch_direct_fallback(&self, request_id: String, delay: Duration) {
+ let publisher = Arc::clone(self);
+ tokio::spawn(async move {
+ tokio::time::sleep(delay).await;
+ if let Err(e) = publisher
+ .republish_pending_result_to_pool(&request_id, "batch_direct_timeout")
+ .await
+ {
+ warn!(
+ request_id = %request_id,
+ error = %e,
+ "batch direct-dispatch fallback failed"
+ );
+ }
+ });
+ }
+}
diff --git a/packages/sie_gateway/src/queue/mod.rs b/packages/sie_gateway/src/queue/mod.rs
index 27411348d..712998e3d 100644
--- a/packages/sie_gateway/src/queue/mod.rs
+++ b/packages/sie_gateway/src/queue/mod.rs
@@ -1,3 +1,4 @@
+pub mod dispatch;
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 8775e65ad..cfb869e5b 100644
--- a/packages/sie_gateway/src/queue/publisher.rs
+++ b/packages/sie_gateway/src/queue/publisher.rs
@@ -108,7 +108,12 @@ impl TokenBucket {
/// `serde_json::Value` — they never carry binary data, and keeping
/// them JSON-shaped avoids rewriting the (de)serializer for the
/// small config surface.
-#[derive(Debug, Clone, Default)]
+///
+/// `Serialize` exists for dispatch implementations behind the
+/// [`super::dispatch::WorkDispatcher`] seam that ship the params block
+/// whole over a transport (the NATS path instead borrows individual
+/// fields into `WorkItemRef`); it is not used on the JetStream wire.
+#[derive(Debug, Clone, Default, Serialize)]
pub struct WorkParams {
pub output_types: Option<Vec<String>>,
pub instruction: Option<String>,
@@ -500,6 +505,74 @@ struct WorkItemShared<'a> {
tracestate: Option<&'a str>,
}
+/// Deserialize a msgpack field that is EITHER a byte array OR `nil`.
+///
+/// `WorkResult.result_msgpack` is typed `bytes | None` on the Python worker
+/// (`sie_sdk.queue_types.WorkResult`): a per-item FAILURE legitimately
+/// carries `result_msgpack: None`, which msgpack encodes as `nil` —
+/// `serde_bytes` alone rejects that with "invalid type: unit value,
+/// expected byte array", turning a worker's typed per-item error into an
+/// opaque transport-level decode failure (the whole result batch is
+/// dropped and the request times out). Same fix and visitor shape as the
+/// sidecar's `deserialize_optional_bytes`
+/// (`sie_server_sidecar/src/protocol/ipc_types.rs`).
+fn deserialize_optional_bytes<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ use serde::de::{Error, Visitor};
+ use std::fmt;
+
+ struct OptBytesVisitor;
+
+ impl<'de> Visitor<'de> for OptBytesVisitor {
+ type Value = Vec<u8>;
+
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("bytes, a byte sequence, or nil")
+ }
+
+ fn visit_unit<E: Error>(self) -> Result<Self::Value, E> {
+ Ok(Vec::new())
+ }
+ fn visit_none<E: Error>(self) -> Result<Self::Value, E> {
+ Ok(Vec::new())
+ }
+ fn visit_some<D: serde::Deserializer<'de>>(
+ self,
+ deserializer: D,
+ ) -> Result<Self::Value, D::Error> {
+ deserializer.deserialize_any(self)
+ }
+
+ fn visit_borrowed_bytes<E: Error>(self, v: &'de [u8]) -> Result<Self::Value, E> {
+ Ok(v.to_vec())
+ }
+ fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
+ Ok(v.to_vec())
+ }
+ fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
+ Ok(v)
+ }
+ fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
+ Ok(v.as_bytes().to_vec())
+ }
+
+ fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
+ where
+ A: serde::de::SeqAccess<'de>,
+ {
+ let mut out = seq.size_hint().map(Vec::with_capacity).unwrap_or_default();
+ while let Some(b) = seq.next_element::<u8>()? {
+ out.push(b);
+ }
+ Ok(out)
+ }
+ }
+
+ deserializer.deserialize_any(OptBytesVisitor)
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkResult {
#[serde(default)]
@@ -509,7 +582,11 @@ pub struct WorkResult {
pub item_index: u32,
#[serde(default)]
pub success: bool,
- #[serde(default, with = "serde_bytes")]
+ #[serde(
+ default,
+ serialize_with = "serde_bytes::serialize",
+ deserialize_with = "deserialize_optional_bytes"
+ )]
pub result_msgpack: Vec<u8>,
#[serde(default)]
pub error: Option<String>,
@@ -529,10 +606,32 @@ pub struct WorkResult {
pub postprocessing_ms: Option<f64>,
#[serde(default)]
pub payload_fetch_ms: Option<f64>,
+ /// Authoritative billable-unit counts emitted by the worker engine
+ /// (`sie_server.ipc_types.UnitCounts`): `input_tokens` is the real
+ /// tokenizer count taken post-tokenization, never an estimate.
+ /// `#[serde(default)]` keeps the wire backward-compatible — workers
+ /// that don't emit it (and array-encoded legacy results) decode to
+ /// `None`. Consumed by metering edges (e.g. the managed gateway's
+ /// settle path); the OSS gateway itself only carries it through.
+ #[serde(default)]
+ pub units: Option<UnitCounts>,
#[serde(default)]
pub worker_direct: bool,
}
+/// Typed unit counts on the result path (see [`WorkResult::units`]).
+/// Every field optional: a field is present only when the worker had an
+/// authoritative count for it.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct UnitCounts {
+ #[serde(default)]
+ pub input_tokens: Option<u64>,
+ #[serde(default)]
+ pub pages: Option<u64>,
+ #[serde(default)]
+ pub images: Option<u64>,
+}
+
struct CachedStreamInfo {
num_pending: u64,
num_consumers: usize,
@@ -812,11 +911,13 @@ fn canonical_stream_subjects(observed: Vec<String>, desired: &str) -> Option<Vec
/// (`sie_sdk.queue_types.normalize_model_id`) so that workers and the gateway
/// agree on the wire-level subject:
///
-/// `/` -> `__`
-/// `.` -> `_dot_`
-/// `*` -> `_`
-/// `>` -> `_`
-/// ` ` -> `_`
+/// ```text
+/// `/` -> `__`
+/// `.` -> `_dot_`
+/// `*` -> `_`
+/// `>` -> `_`
+/// ` ` -> `_`
+/// ```
///
/// The encoding is not fully reversible — e.g. `org/a__b` and `org/a/b` both
/// collapse to the same token — but this is safe in practice because
@@ -1880,32 +1981,10 @@ impl WorkPublisher {
}
}
- /// Arm a one-shot recovery for non-streaming worker-direct batch work.
- ///
- /// Capped logical pools direct-dispatch encode/score/extract to one
- /// admitted worker so unassigned peers do not burn the JetStream
- /// delivery budget. If that worker or its private consumer disappears
- /// after the gateway publishes, the worker-specific stream cannot fail
- /// over by itself. This timer republishes any still-missing items to the
- /// lane's pool subject once. After those fallback publishes are durably
- /// acked, it emits a worker-scoped batch cancel so the original sidecar
- /// can ACK queued worker-direct items that have not reached IPC yet.
- pub fn spawn_batch_direct_fallback(self: &Arc<Self>, request_id: String, delay: Duration) {
- let publisher = Arc::clone(self);
- tokio::spawn(async move {
- tokio::time::sleep(delay).await;
- if let Err(e) = publisher
- .republish_pending_result_to_pool(&request_id, "batch_direct_timeout")
- .await
- {
- warn!(
- request_id = %request_id,
- error = %e,
- "batch direct-dispatch fallback failed"
- );
- }
- });
- }
+ // NOTE: main's inherent `spawn_batch_direct_fallback` lives on the
+ // composition seam instead (queue/dispatch.rs `WorkDispatcherExt` on
+ // `Arc<dyn WorkDispatcher>`) so proprietary dispatchers inherit the
+ // same one-shot direct-batch recovery.
pub async fn republish_pending_result_to_pool(
&self,
@@ -3842,6 +3921,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
}),
None,
@@ -3902,6 +3982,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
};
let duplicate = WorkResult {
@@ -3957,11 +4038,13 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: true,
};
let pool_result = WorkResult {
result_msgpack: vec![2],
worker_id: Some("pool-worker".into()),
+ units: None,
worker_direct: false,
..stale_direct.clone()
};
@@ -4324,6 +4407,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: true,
};
@@ -4337,6 +4421,43 @@ mod tests {
assert!(decoded.worker_direct);
}
+ #[test]
+ fn test_work_result_decodes_nil_result_msgpack() {
+ // The Python worker types `result_msgpack: bytes | None`
+ // (sie_sdk.queue_types.WorkResult) and error results carry None —
+ // msgpack `nil` on the wire. The decoder must accept it (empty
+ // bytes) so a typed per-item failure never becomes an opaque
+ // transport-level decode error (see deserialize_optional_bytes).
+ let failure = rmpv::Value::Map(vec![
+ ("work_item_id".into(), "req-9.0".into()),
+ ("request_id".into(), "req-9".into()),
+ ("item_index".into(), 0u32.into()),
+ ("success".into(), false.into()),
+ ("result_msgpack".into(), rmpv::Value::Nil),
+ ("error".into(), "unsupported operation".into()),
+ ("error_code".into(), "inference_error".into()),
+ ]);
+ let encoded = rmp_serde::to_vec_named(&failure).unwrap();
+ let decoded: WorkResult = rmp_serde::from_slice(&encoded).unwrap();
+ assert!(!decoded.success);
+ assert!(decoded.result_msgpack.is_empty());
+ assert_eq!(decoded.error_code.as_deref(), Some("inference_error"));
+
+ // And a whole array containing a mix of success + nil-failure
+ // results (the real lane-batch shape) decodes item-per-item.
+ let ok = rmpv::Value::Map(vec![
+ ("work_item_id".into(), "req-9.1".into()),
+ ("request_id".into(), "req-9".into()),
+ ("item_index".into(), 1u32.into()),
+ ("success".into(), true.into()),
+ ("result_msgpack".into(), rmpv::Value::Binary(vec![1, 2, 3])),
+ ]);
+ let encoded = rmp_serde::to_vec_named(&vec![failure, ok]).unwrap();
+ let decoded: Vec<WorkResult> = rmp_serde::from_slice(&encoded).unwrap();
+ assert_eq!(decoded.len(), 2);
+ assert_eq!(decoded[1].result_msgpack, vec![1, 2, 3]);
+ }
+
#[test]
fn test_work_item_with_payload_ref() {
let item = WorkItem {
@@ -4440,6 +4561,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
};
let encoded = rmp_serde::to_vec(&result).unwrap();
@@ -4464,6 +4586,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
};
let encoded = rmp_serde::to_vec_named(&result).unwrap();
@@ -4505,6 +4628,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: false,
};
let encoded = rmp_serde::to_vec(&result).unwrap();
diff --git a/packages/sie_gateway/src/routing/hrw.rs b/packages/sie_gateway/src/routing/hrw.rs
index 155a13da1..f3ee18f2d 100644
--- a/packages/sie_gateway/src/routing/hrw.rs
+++ b/packages/sie_gateway/src/routing/hrw.rs
@@ -1,10 +1,10 @@
//! Highest-Random-Weight (rendezvous) hashing for direct-dispatch routing.
//!
//! Given a request hash and a snapshot of candidate workers, pick the
-//! single worker whose combined hash with the request key is largest.
-//! This is `O(n)` per pick, stable across all callers without
-//! coordination, and degrades gracefully when workers come and go
-//! (only `1/n` of keys move on membership change).
+//! least-pressured worker and use the HRW score as the deterministic
+//! tie-breaker. This is `O(n)` per pick, stable across all callers without
+//! coordination for equal-pressure workers, and still degrades gracefully
+//! when workers come and go.
//!
//! Snapshots are immutable. The
//! [`crate::state::worker_registry::WorkerRegistry`] owns the source
@@ -15,21 +15,41 @@ use xxhash_rust::xxh3::xxh3_64;
use super::key::RoutingKeyResolved;
-/// One entry on the HRW ring. Pre-hashing `worker_id` once at snapshot
-/// build time keeps `pick_worker` cheap.
+/// One entry on the direct-dispatch ring. Pre-hashing `worker_id` once at
+/// snapshot build time keeps `pick_worker` cheap; pressure fields are copied
+/// from worker heartbeats so gateway selection can avoid already-busy pods.
#[derive(Debug, Clone)]
pub struct RingEntry {
pub worker_id: String,
pub worker_id_hash: u64,
+ pub ready_gpu_slots: i32,
+ pub queue_depth: i32,
+ pub pending_cost: i64,
+ pub inflight_batches: i32,
}
impl RingEntry {
+ #[cfg(test)]
pub fn new(worker_id: impl Into<String>) -> Self {
+ Self::with_pressure(worker_id, 1, 0, 0, 0)
+ }
+
+ pub fn with_pressure(
+ worker_id: impl Into<String>,
+ ready_gpu_slots: i32,
+ queue_depth: i32,
+ pending_cost: i64,
+ inflight_batches: i32,
+ ) -> Self {
let worker_id = worker_id.into();
let worker_id_hash = xxh3_64(worker_id.as_bytes());
Self {
worker_id,
worker_id_hash,
+ ready_gpu_slots: ready_gpu_slots.max(1),
+ queue_depth: queue_depth.max(0),
+ pending_cost: pending_cost.max(0),
+ inflight_batches: inflight_batches.max(0),
}
}
}
@@ -44,12 +64,19 @@ pub struct RingSnapshot {
}
impl RingSnapshot {
+ #[cfg(test)]
pub fn new(worker_ids: impl IntoIterator<Item = String>) -> Self {
Self {
entries: worker_ids.into_iter().map(RingEntry::new).collect(),
}
}
+ pub fn from_entries(entries: impl IntoIterator<Item = RingEntry>) -> Self {
+ Self {
+ entries: entries.into_iter().collect(),
+ }
+ }
+
pub fn len(&self) -> usize {
self.entries.len()
}
@@ -62,7 +89,11 @@ impl RingSnapshot {
}
}
-/// HRW pick: highest `combine(request_hash, worker_id_hash)` wins.
+/// Pressure-aware HRW pick.
+///
+/// Lower slot-normalized `pending_cost`, `queue_depth`, and
+/// `inflight_batches` win first. HRW is then used as a stable tie-breaker so
+/// equal-pressure workers still distribute cache/routing keys deterministically.
///
/// Returns `None` when the snapshot is empty (caller falls back to the
/// pool subject) or when the resolved key has no hash (caller may
@@ -80,14 +111,38 @@ pub fn pick_worker<'a>(snapshot: &'a RingSnapshot, key: &RoutingKeyResolved) ->
snapshot
.entries
.iter()
- .max_by(|a, b| {
- combine(request_hash, a.worker_id_hash)
- .cmp(&combine(request_hash, b.worker_id_hash))
- .then_with(|| a.worker_id.cmp(&b.worker_id))
+ .min_by(|a, b| {
+ pressure_key(a)
+ .cmp(&pressure_key(b))
+ .then_with(|| {
+ combine(request_hash, b.worker_id_hash)
+ .cmp(&combine(request_hash, a.worker_id_hash))
+ })
+ .then_with(|| b.worker_id.cmp(&a.worker_id))
})
.map(|e| e.worker_id.as_str())
}
+fn pressure_key(entry: &RingEntry) -> (i64, i64, i64, i64, i64, i64) {
+ let slots = i64::from(entry.ready_gpu_slots.max(1));
+ (
+ ceil_div_i64(entry.pending_cost.max(0), slots),
+ ceil_div_i64(i64::from(entry.queue_depth.max(0)), slots),
+ ceil_div_i64(i64::from(entry.inflight_batches.max(0)), slots),
+ entry.pending_cost.max(0),
+ i64::from(entry.queue_depth.max(0)),
+ i64::from(entry.inflight_batches.max(0)),
+ )
+}
+
+fn ceil_div_i64(value: i64, divisor: i64) -> i64 {
+ if value <= 0 {
+ 0
+ } else {
+ (value + divisor.max(1) - 1) / divisor.max(1)
+ }
+}
+
/// Combine the request key hash with a worker-id hash.
///
/// Uses an asymmetric mix (`worker_id_hash.rotate_left(32) ^ request_hash`,
diff --git a/packages/sie_gateway/src/routing/mod.rs b/packages/sie_gateway/src/routing/mod.rs
index 5d387800a..0ca28255b 100644
--- a/packages/sie_gateway/src/routing/mod.rs
+++ b/packages/sie_gateway/src/routing/mod.rs
@@ -1,7 +1,7 @@
//! Direct-dispatch routing.
//!
//! Public API:
-//! - [`pick_worker`]: HRW (rendezvous-hash) selection for a `(model, pool)` ring.
+//! - [`pick_worker`]: pressure-aware selection with HRW tie-breaks for a `(model, pool)` ring.
//! - [`key::resolve`]: priority-ordered routing-key extraction + xxh3 hashing.
//! - [`fmt_key_hash`]: privacy-safe log formatter (`xxh:XXXXXXXX`).
//! - [`log_raw_keys_enabled`] / [`warn_if_raw_logging_enabled`]: opt-in raw-key logging.
diff --git a/packages/sie_gateway/src/routing/tests.rs b/packages/sie_gateway/src/routing/tests.rs
index c4c64140e..543138b26 100644
--- a/packages/sie_gateway/src/routing/tests.rs
+++ b/packages/sie_gateway/src/routing/tests.rs
@@ -7,7 +7,7 @@
//! - xxh3 prefix-truncation semantics.
//! - Privacy: `fmt_key_hash` never reveals the raw string; `xxh:` prefix only.
-use super::hrw::{pick_worker, RingSnapshot};
+use super::hrw::{pick_worker, RingEntry, RingSnapshot};
use super::key::{
derive_prefix_key, derive_prefix_key_with, hash_bytes, resolve, resolve_with_prefix, KeySource,
PrefixConfig, PROMPT_PREFIX_BYTES,
@@ -116,6 +116,36 @@ fn duplicate_worker_ids_hash_and_tiebreak_identically() {
assert_eq!(snap.entries[0].worker_id, snap.entries[1].worker_id);
}
+#[test]
+fn pick_prefers_lower_pressure_over_hrw_winner() {
+ let key = resolve(Some("pressure-key"), None, None, None);
+ let pure = RingSnapshot::new(vec!["busy".to_string(), "idle".to_string()]);
+ let pure_winner = pick_worker(&pure, &key).expect("pure HRW winner");
+ let other = if pure_winner == "busy" {
+ "idle"
+ } else {
+ "busy"
+ };
+
+ let snap = RingSnapshot::from_entries([
+ RingEntry::with_pressure(pure_winner, 1, 100, 1000, 10),
+ RingEntry::with_pressure(other, 1, 0, 0, 0),
+ ]);
+
+ assert_eq!(pick_worker(&snap, &key), Some(other));
+}
+
+#[test]
+fn pick_normalizes_pressure_by_ready_gpu_slots() {
+ let key = resolve(Some("slot-pressure-key"), None, None, None);
+ let snap = RingSnapshot::from_entries([
+ RingEntry::with_pressure("wide", 4, 4, 40, 4),
+ RingEntry::with_pressure("narrow", 1, 2, 20, 2),
+ ]);
+
+ assert_eq!(pick_worker(&snap, &key), Some("wide"));
+}
+
#[test]
fn empty_snapshot_returns_none() {
let snap = RingSnapshot::default();
diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rs
index 30c88a668..9a8c8aee0 100644
--- a/packages/sie_gateway/src/server.rs
+++ b/packages/sie_gateway/src/server.rs
@@ -9,7 +9,7 @@ use crate::middleware::audit::AuditLayer;
use crate::middleware::auth::AuthLayer;
use crate::middleware::metrics::MetricsLayer;
use crate::openapi;
-use crate::queue::publisher::WorkPublisher;
+use crate::queue::dispatch::WorkDispatcher;
use crate::state::config_epoch::ConfigEpoch;
use crate::state::demand_tracker::DemandTracker;
use crate::state::model_registry::ModelRegistry;
@@ -21,7 +21,7 @@ pub struct AppState {
pub config: Arc<Config>,
pub model_registry: Arc<ModelRegistry>,
pub pool_manager: Arc<PoolManager>,
- pub work_publisher: Option<Arc<WorkPublisher>>,
+ pub work_publisher: Option<Arc<dyn WorkDispatcher>>,
pub demand_tracker: Arc<DemandTracker>,
/// Monotonic view of the furthest-known control-plane epoch. Written by
/// bootstrap, the NATS delta handler, and the epoch poller; read by
@@ -127,6 +127,9 @@ pub(crate) async fn metrics_handler(
bundle: w.bundle.clone(),
pool_name: w.pool_name.clone(),
queue_depth: w.queue_depth,
+ ready_gpu_slots: w.ready_gpu_slots,
+ pending_cost: w.pending_cost,
+ inflight_batches: w.inflight_batches,
memory_used_bytes: w.memory_used_bytes,
healthy: w.healthy(),
})
diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rs
index 9c0f27a65..e6f6fe9ea 100644
--- a/packages/sie_gateway/src/state/worker_registry.rs
+++ b/packages/sie_gateway/src/state/worker_registry.rs
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
use arc_swap::ArcSwap;
use tokio::sync::RwLock;
-use crate::routing::hrw::RingSnapshot;
+use crate::routing::hrw::{RingEntry, RingSnapshot};
use crate::state::pool_manager::normalize_pool_name;
use crate::types::{
ClusterStatus, ModelInfo, WorkerHealth, WorkerInfo, WorkerState, WorkerStatusMessage,
@@ -192,11 +192,14 @@ impl WorkerRegistry {
name: String::new(),
health: WorkerHealth::Unknown,
gpu_count: 1,
+ ready_gpu_slots: 0,
machine_profile: String::new(),
bundle: "default".to_string(),
bundle_config_hash: String::new(),
models: Vec::new(),
queue_depth: 0,
+ pending_cost: 0,
+ inflight_batches: 0,
memory_used_bytes: 0,
memory_total_bytes: 0,
last_heartbeat: Instant::now(),
@@ -212,7 +215,8 @@ impl WorkerRegistry {
} else {
msg.name.clone()
};
- w.gpu_count = if msg.gpu_count == 0 { 1 } else { msg.gpu_count };
+ let reported_gpu_slots = msg.total_gpu_slots.unwrap_or(msg.gpu_count);
+ w.gpu_count = reported_gpu_slots.max(1);
w.bundle = if msg.bundle.is_empty() {
"default".to_string()
} else {
@@ -229,6 +233,12 @@ impl WorkerRegistry {
} else {
msg.queue_depth.unwrap_or(0)
};
+ w.pending_cost = msg.pending_cost.unwrap_or(0).max(0);
+ w.inflight_batches = msg.inflight_batches.unwrap_or(0).max(0);
+ w.ready_gpu_slots = msg
+ .ready_gpu_slots
+ .unwrap_or(if msg.ready { w.gpu_count } else { 0 })
+ .clamp(0, w.gpu_count);
// Aggregate GPU memory (fallback to compact top-level fields)
if !msg.gpus.is_empty() {
@@ -241,12 +251,12 @@ impl WorkerRegistry {
w.last_heartbeat = Instant::now();
- // A worker that heartbeats `ready: false` is no longer serviceable
- // and must leave the dispatch set / HRW ring promptly — waiting for
- // the heartbeat timeout would keep routing direct dispatches to a
- // worker that has declared itself not ready. The exact transition
- // depends on its prior state (see the per-branch notes below).
- if msg.ready {
+ // A worker that heartbeats `ready: false` or has zero ready GPU
+ // slots is no longer serviceable and must leave the dispatch set /
+ // HRW ring promptly. Waiting for the heartbeat timeout would keep
+ // routing direct dispatches to a worker that has declared no usable
+ // child capacity. The exact transition depends on its prior state.
+ if msg.ready && w.ready_gpu_slots > 0 {
w.health = WorkerHealth::Healthy;
} else if w.health == WorkerHealth::Healthy {
// Was serving and now reports not-ready: the worker has
@@ -268,7 +278,7 @@ impl WorkerRegistry {
// edge so the HRW ring cache can invalidate.
w.saturated = msg.saturated;
- let became_healthy = msg.ready && (!exists || !was_healthy);
+ let became_healthy = w.healthy() && (!exists || !was_healthy);
// Falling edge into "ineligible for HRW dispatch", reported
// exactly once so the degrade callback (ring invalidation)
// fires the same way regardless of the trigger. Two triggers
@@ -479,7 +489,15 @@ impl WorkerRegistry {
if workers.len() != before {
warn_duplicate_worker_names(model, pool, before - workers.len());
}
- RingSnapshot::new(workers.into_iter().map(|w| w.name))
+ RingSnapshot::from_entries(workers.into_iter().map(|w| {
+ RingEntry::with_pressure(
+ w.name,
+ w.ready_gpu_slots,
+ w.queue_depth,
+ w.pending_cost,
+ w.inflight_batches,
+ )
+ }))
}
/// Build a [`RingSnapshot`] for the given concrete queue lane. Uses
@@ -563,7 +581,15 @@ impl WorkerRegistry {
if workers.len() != before {
warn_duplicate_worker_names(model, pool, before - workers.len());
}
- RingSnapshot::new(workers.into_iter().map(|w| w.name))
+ RingSnapshot::from_entries(workers.into_iter().map(|w| {
+ RingEntry::with_pressure(
+ w.name,
+ w.ready_gpu_slots,
+ w.queue_depth,
+ w.pending_cost,
+ w.inflight_batches,
+ )
+ }))
}
pub async fn check_heartbeats(&self) -> HeartbeatSweep {
@@ -747,8 +773,11 @@ impl WorkerRegistry {
url: w.url.clone(),
gpu: w.machine_profile.clone(),
gpu_count: w.gpu_count,
+ ready_gpu_slots: w.ready_gpu_slots,
loaded_models: w.models.clone(),
queue_depth: w.queue_depth,
+ pending_cost: w.pending_cost,
+ inflight_batches: w.inflight_batches,
memory_used_bytes: w.memory_used_bytes,
memory_total_bytes: w.memory_total_bytes,
healthy: w.healthy(),
@@ -829,6 +858,8 @@ mod tests {
name: "worker-1".into(),
ready,
gpu_count: 1,
+ total_gpu_slots: None,
+ ready_gpu_slots: None,
machine_profile: "l4-spot".into(),
pool_name: String::new(),
bundle: "default".into(),
@@ -840,6 +871,8 @@ mod tests {
memory_total_bytes: 4000,
}],
queue_depth: None,
+ pending_cost: None,
+ inflight_batches: None,
memory_used_bytes: None,
memory_total_bytes: None,
saturated: false,
@@ -872,6 +905,28 @@ mod tests {
assert_eq!(w.memory_total_bytes, 4000);
}
+ #[tokio::test]
+ async fn test_update_worker_ready_with_zero_ready_slots_is_not_healthy() {
+ let reg = registry();
+ let mut msg = make_msg(true);
+ msg.pool_name = "default".into();
+ msg.total_gpu_slots = Some(4);
+ msg.ready_gpu_slots = Some(0);
+
+ let became_healthy = reg.update_worker("http://w1:8080", msg).await;
+
+ assert!(!became_healthy);
+ let workers = reg.workers().await;
+ let w = &workers["http://w1:8080"];
+ assert_eq!(w.gpu_count, 4);
+ assert_eq!(w.ready_gpu_slots, 0);
+ assert_eq!(w.health, WorkerHealth::Unknown);
+ assert!(reg
+ .resolve_queue_route_in_pool("default", "l4-spot", "default", "abc123")
+ .await
+ .is_none());
+ }
+
#[tokio::test]
async fn test_update_worker_first_seen_not_ready_stays_unknown() {
let reg = registry();
@@ -1061,6 +1116,8 @@ mod tests {
name: "w-compact".into(),
ready: true,
gpu_count: 1,
+ total_gpu_slots: Some(1),
+ ready_gpu_slots: Some(1),
machine_profile: "l4".into(),
pool_name: String::new(),
bundle: "default".into(),
@@ -1069,6 +1126,8 @@ mod tests {
models: vec![], // empty — should use compact fallback
gpus: vec![], // empty — should use compact fallback
queue_depth: Some(7),
+ pending_cost: Some(42),
+ inflight_batches: Some(3),
memory_used_bytes: Some(2000),
memory_total_bytes: Some(8000),
saturated: false,
@@ -1078,6 +1137,9 @@ mod tests {
let w = &reg.workers().await["http://w1:8080"];
assert_eq!(w.queue_depth, 7);
+ assert_eq!(w.ready_gpu_slots, 1);
+ assert_eq!(w.pending_cost, 42);
+ assert_eq!(w.inflight_batches, 3);
assert_eq!(w.memory_used_bytes, 2000);
assert_eq!(w.memory_total_bytes, 8000);
}
@@ -1089,6 +1151,8 @@ mod tests {
name: "w-none".into(),
ready: true,
gpu_count: 1,
+ total_gpu_slots: None,
+ ready_gpu_slots: None,
machine_profile: "l4".into(),
pool_name: String::new(),
bundle: "default".into(),
@@ -1097,6 +1161,8 @@ mod tests {
models: vec![],
gpus: vec![],
queue_depth: None,
+ pending_cost: None,
+ inflight_batches: None,
memory_used_bytes: None,
memory_total_bytes: None,
saturated: false,
@@ -1106,6 +1172,9 @@ mod tests {
let w = &reg.workers().await["http://w1:8080"];
assert_eq!(w.queue_depth, 0);
+ assert_eq!(w.ready_gpu_slots, 1);
+ assert_eq!(w.pending_cost, 0);
+ assert_eq!(w.inflight_batches, 0);
assert_eq!(w.memory_used_bytes, 0);
assert_eq!(w.memory_total_bytes, 0);
}
@@ -1654,6 +1723,8 @@ mod tests {
name: "w".into(),
ready,
gpu_count: 1,
+ total_gpu_slots: None,
+ ready_gpu_slots: None,
machine_profile: "l4".into(),
pool_name: pool.into(),
bundle: "default".into(),
@@ -1662,6 +1733,8 @@ mod tests {
models: vec![],
gpus: vec![],
queue_depth: None,
+ pending_cost: None,
+ inflight_batches: None,
memory_used_bytes: None,
memory_total_bytes: None,
saturated,
@@ -1869,6 +1942,28 @@ mod tests {
assert!(ids.contains(&"w-2".to_string()));
}
+ #[tokio::test]
+ async fn test_ring_snapshot_carries_worker_pressure() {
+ let reg = registry();
+ let mut msg = make_dispatch_msg(true, false, "p1", &["m"]).await;
+ msg.name = "pressured".into();
+ msg.total_gpu_slots = Some(4);
+ msg.ready_gpu_slots = Some(3);
+ msg.queue_depth = Some(9);
+ msg.pending_cost = Some(90);
+ msg.inflight_batches = Some(6);
+ reg.update_worker("http://pressured:8080", msg).await;
+
+ let snap = reg.ring_snapshot_for("m", "p1", "l4", "default", "");
+
+ assert_eq!(snap.len(), 1);
+ assert_eq!(snap.entries[0].worker_id, "pressured");
+ assert_eq!(snap.entries[0].ready_gpu_slots, 3);
+ assert_eq!(snap.entries[0].queue_depth, 9);
+ assert_eq!(snap.entries[0].pending_cost, 90);
+ assert_eq!(snap.entries[0].inflight_batches, 6);
+ }
+
#[tokio::test]
async fn test_degrade_callback_fires_on_saturation_rising_edge() {
use std::sync::atomic::{AtomicUsize, Ordering};
diff --git a/packages/sie_gateway/src/types/worker.rs b/packages/sie_gateway/src/types/worker.rs
index bafaa2fe5..5b73d9bbc 100644
--- a/packages/sie_gateway/src/types/worker.rs
+++ b/packages/sie_gateway/src/types/worker.rs
@@ -25,11 +25,14 @@ pub struct WorkerState {
pub name: String,
pub health: WorkerHealth,
pub gpu_count: i32,
+ pub ready_gpu_slots: i32,
pub machine_profile: String,
pub bundle: String,
pub bundle_config_hash: String,
pub models: Vec<String>,
pub queue_depth: i32,
+ pub pending_cost: i64,
+ pub inflight_batches: i32,
pub memory_used_bytes: i64,
pub memory_total_bytes: i64,
pub last_heartbeat: Instant,
@@ -48,12 +51,12 @@ impl WorkerState {
self.health == WorkerHealth::Healthy
}
- /// Eligible for HRW direct dispatch: healthy *and* not saturated.
+ /// Eligible for dispatch: healthy, with at least one ready slot, and not saturated.
/// Saturated workers stay in the registry (so the pool fallback
/// still drains to them via the bundle index) but are excluded
/// from the per-`(model, pool)` HRW ring.
pub fn eligible_for_dispatch(&self) -> bool {
- self.healthy() && !self.saturated
+ self.healthy() && self.ready_gpu_slots > 0 && !self.saturated
}
#[allow(dead_code)]
@@ -82,8 +85,11 @@ pub struct WorkerInfo {
pub url: String,
pub gpu: String,
pub gpu_count: i32,
+ pub ready_gpu_slots: i32,
pub loaded_models: Vec<String>,
pub queue_depth: i32,
+ pub pending_cost: i64,
+ pub inflight_batches: i32,
pub memory_used_bytes: i64,
pub memory_total_bytes: i64,
pub healthy: bool,
@@ -149,6 +155,14 @@ pub struct WorkerStatusMessage {
pub ready: bool,
#[serde(default)]
pub gpu_count: i32,
+ /// Total GPU slots visible to the worker pod. Defaults to
+ /// `gpu_count` when absent.
+ #[serde(default)]
+ pub total_gpu_slots: Option<i32>,
+ /// Slots ready to receive work. Defaults to all slots when
+ /// `ready=true`, otherwise zero.
+ #[serde(default)]
+ pub ready_gpu_slots: Option<i32>,
#[serde(default)]
pub machine_profile: String,
#[serde(default)]
@@ -166,6 +180,12 @@ pub struct WorkerStatusMessage {
/// Compact top-level queue depth (fallback when models array is empty)
#[serde(default)]
pub queue_depth: Option<i32>,
+ /// Compact top-level pending scheduler cost.
+ #[serde(default)]
+ pub pending_cost: Option<i64>,
+ /// Compact top-level in-flight batch count.
+ #[serde(default)]
+ pub inflight_batches: Option<i32>,
/// Compact top-level memory used (fallback when gpus array is empty)
#[serde(default)]
pub memory_used_bytes: Option<i64>,
@@ -210,11 +230,18 @@ mod tests {
name: "w1".into(),
health,
gpu_count: 1,
+ ready_gpu_slots: if health == WorkerHealth::Healthy {
+ 1
+ } else {
+ 0
+ },
machine_profile: "l4".into(),
bundle: "default".into(),
bundle_config_hash: String::new(),
models: vec![],
queue_depth: 0,
+ pending_cost: 0,
+ inflight_batches: 0,
memory_used_bytes: mem_used,
memory_total_bytes: mem_total,
last_heartbeat: Instant::now(),
@@ -224,12 +251,15 @@ mod tests {
}
#[test]
- fn test_eligible_for_dispatch_requires_healthy_and_not_saturated() {
+ fn test_eligible_for_dispatch_requires_healthy_ready_slot_and_not_saturated() {
let mut w = make_worker(WorkerHealth::Healthy, 0, 0);
assert!(w.eligible_for_dispatch());
w.saturated = true;
assert!(!w.eligible_for_dispatch());
w.saturated = false;
+ w.ready_gpu_slots = 0;
+ assert!(!w.eligible_for_dispatch());
+ w.ready_gpu_slots = 1;
w.health = WorkerHealth::Unhealthy;
assert!(!w.eligible_for_dispatch());
}
@@ -296,9 +326,13 @@ mod tests {
assert!(msg.ready);
assert!(msg.name.is_empty());
assert_eq!(msg.gpu_count, 0);
+ assert_eq!(msg.total_gpu_slots, None);
+ assert_eq!(msg.ready_gpu_slots, None);
assert!(msg.loaded_models.is_empty());
assert!(msg.models.is_empty());
assert!(msg.gpus.is_empty());
+ assert_eq!(msg.pending_cost, None);
+ assert_eq!(msg.inflight_batches, None);
assert!(!msg.terminated);
}
@@ -308,17 +342,25 @@ mod tests {
"name": "worker-1",
"ready": true,
"gpu_count": 2,
+ "total_gpu_slots": 2,
+ "ready_gpu_slots": 1,
"machine_profile": "a100",
"bundle": "premium",
"bundle_config_hash": "abc",
"loaded_models": ["model-a", "model-b"],
+ "pending_cost": 99,
+ "inflight_batches": 2,
"models": [{"queue_depth": 3}],
"gpus": [{"memory_used_bytes": 1000, "memory_total_bytes": 4000}]
}"#;
let msg: WorkerStatusMessage = serde_json::from_str(json).unwrap();
assert_eq!(msg.name, "worker-1");
assert_eq!(msg.gpu_count, 2);
+ assert_eq!(msg.total_gpu_slots, Some(2));
+ assert_eq!(msg.ready_gpu_slots, Some(1));
assert_eq!(msg.loaded_models.len(), 2);
+ assert_eq!(msg.pending_cost, Some(99));
+ assert_eq!(msg.inflight_batches, Some(2));
assert_eq!(msg.models[0].queue_depth, 3);
assert_eq!(msg.gpus[0].memory_used_bytes, 1000);
}
diff --git a/packages/sie_mcp/pyproject.toml b/packages/sie_mcp/pyproject.toml
index 5a9f9528e..d34e07c8a 100644
--- a/packages/sie_mcp/pyproject.toml
+++ b/packages/sie_mcp/pyproject.toml
@@ -7,7 +7,7 @@ license = { text = "Apache-2.0" }
dependencies = [
"mcp>=1.9,<2",
"sie-sdk>=0.1",
- "starlette>=0.40",
+ "starlette>=1.3.1",
"uvicorn[standard]>=0.32,<1",
"typer>=0.14,<1",
# Post-validation of cluster output against the requested schema. Already a
diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.toml
index 9a00e519d..a4799c337 100644
--- a/packages/sie_sdk/pyproject.toml
+++ b/packages/sie_sdk/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-sdk"
-version = "0.6.16"
+version = "0.6.17"
description = "Search Inference Engine - Python SDK"
requires-python = ">=3.12"
license = { text = "Apache-2.0" }
@@ -14,7 +14,7 @@ dependencies = [
"websockets>=14,<15",
# Serialization
- "msgpack>=1.1,<2",
+ "msgpack>=1.2.1,<2",
"msgpack-numpy>=0.4,<1",
# Data handling
diff --git a/packages/sie_sdk/src/sie_sdk/__init__.py b/packages/sie_sdk/src/sie_sdk/__init__.py
index 79514cbe7..ef73ae558 100644
--- a/packages/sie_sdk/src/sie_sdk/__init__.py
+++ b/packages/sie_sdk/src/sie_sdk/__init__.py
@@ -33,9 +33,14 @@ from sie_sdk.encoding import (
sparse_embedding,
sparse_embedding_dict,
)
+from sie_sdk.files import resolve_upload
+from sie_sdk.jobs import build_job_body, connection_name
from sie_sdk.types import (
# Response types
AssignedWorkerInfo,
+ Batch,
+ BatchList,
+ BatchRequestCounts,
CapacityInfo,
ChatCompletion,
ChatCompletionChunk,
@@ -43,14 +48,27 @@ from sie_sdk.types import (
ChatUsage,
ClusterStatusMessage,
ClusterSummary,
+ Connection,
+ ConnectionCreated,
+ ConnectionRevoked,
EncodeResult,
Entity,
ExtractResult,
+ File,
+ FileDeleted,
GenerateChunk,
GenerateResult,
GenerationUsage,
HealthResponse,
Item,
+ JobChunk,
+ JobFieldMap,
+ JobList,
+ JobResultItem,
+ JobResults,
+ JobState,
+ JobStatus,
+ JobSubmitResult,
ModelInfo,
ModelSummary,
PoolInfo,
@@ -71,6 +89,9 @@ __version__ = "0.1.0"
__all__ = [
"AssignedWorkerInfo",
+ "Batch",
+ "BatchList",
+ "BatchRequestCounts",
"CapacityInfo",
"ChatCompletion",
"ChatCompletionChunk",
@@ -78,15 +99,28 @@ __all__ = [
"ChatUsage",
"ClusterStatusMessage",
"ClusterSummary",
+ "Connection",
+ "ConnectionCreated",
+ "ConnectionRevoked",
"EncodeResult",
"Entity",
"ExtractResult",
+ "File",
+ "FileDeleted",
"GenerateChunk",
"GenerateResult",
"GenerationUsage",
"HealthResponse",
"InputTooLongError",
"Item",
+ "JobChunk",
+ "JobFieldMap",
+ "JobList",
+ "JobResultItem",
+ "JobResults",
+ "JobState",
+ "JobStatus",
+ "JobSubmitResult",
"LoraLoadingError",
"ModelInfo",
"ModelLoadFailedError",
@@ -113,9 +147,12 @@ __all__ = [
"TimingInfo",
"WorkerInfo",
"WorkerStatusMessage",
+ "build_job_body",
+ "connection_name",
"dense_embedding",
"multivector_embedding",
"normalize_sparse_vector",
+ "resolve_upload",
"sparse_embedding",
"sparse_embedding_dict",
]
diff --git a/packages/sie_sdk/src/sie_sdk/cache.py b/packages/sie_sdk/src/sie_sdk/cache.py
index 5dfb69d28..b474a9620 100644
--- a/packages/sie_sdk/src/sie_sdk/cache.py
+++ b/packages/sie_sdk/src/sie_sdk/cache.py
@@ -351,14 +351,21 @@ def populate_cluster_cache(
) -> bool:
"""Upload model from local cache to cluster cache.
- Used by sie-admin to pre-populate cluster cache.
+ Used by sie-admin to pre-populate cluster cache. Inverse of
+ :func:`_download_from_cluster_cache`: the model's HF-style cache
+ directory (``models--{org}--{name}``) is mirrored recursively to the
+ same folder name under ``config.cluster_cache``, so workers hydrating
+ via :func:`ensure_model_cached` see an identical layout.
Args:
model_id: HuggingFace model ID.
- config: Cache configuration.
+ config: Cache configuration. If None, reads from environment.
Returns:
- True if successfully uploaded, False if model not in local cache.
+ True if at least one file was uploaded, False if no cluster cache
+ is configured, the model is not in local cache, or nothing was
+ uploaded (per-file upload failures are logged by the backend and
+ reflected in its returned count).
"""
if config is None:
config = get_cache_config()
@@ -371,7 +378,16 @@ def populate_cluster_cache(
logger.warning("Model %s not in local cache, cannot populate cluster", model_id)
return False
- # TODO: Implement upload to cluster cache
- # This requires adding upload methods to storage backends
- logger.info("populate_cluster_cache not yet implemented")
- return False
+ backend = get_storage_backend(config.cluster_cache)
+
+ model_folder = f"models--{model_id.replace('/', '--')}"
+ local_model_path = config.local_cache / model_folder
+ cluster_model_path = join_path(config.cluster_cache, model_folder)
+
+ file_count = backend.upload_directory(local_model_path, cluster_model_path)
+ if file_count == 0:
+ logger.warning("No files uploaded for %s to %s", model_id, cluster_model_path)
+ return False
+
+ logger.info("Uploaded %d file(s) for %s to cluster cache %s", file_count, model_id, cluster_model_path)
+ return True
diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.py
index a7787e83d..6a0f342eb 100644
--- a/packages/sie_sdk/src/sie_sdk/client/async_.py
+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py
@@ -34,25 +34,38 @@ import json
import logging
import time
import warnings
-from collections.abc import AsyncIterator
-from typing import Any, Literal, Self, overload
+from collections.abc import AsyncIterator, Mapping, Sequence
+from pathlib import Path
+from typing import IO, Any, Literal, Self, overload
+from urllib.parse import urlencode
import aiohttp
import msgpack
import msgpack_numpy as m
from sie_sdk.documents import convert_item_document
+from sie_sdk.files import resolve_upload
from sie_sdk.images import convert_item_images
+from sie_sdk.jobs import TERMINAL_JOB_STATES, build_job_body, decode_chunk_bytes, job_chunks
from sie_sdk.types import (
+ Batch,
CapacityInfo,
ChatCompletion,
ChatCompletionChunk,
ChatMessage,
+ Connection,
+ ConnectionCreated,
+ ConnectionRevoked,
EncodeResult,
ExtractResult,
+ File,
+ FileDeleted,
GenerateChunk,
GenerateResult,
Item,
+ JobResults,
+ JobStatus,
+ JobSubmitResult,
ModelInfo,
OutputType,
PoolInfo,
@@ -358,6 +371,8 @@ class SIEAsyncClient:
pool: PoolSpec | None = None,
max_connections: int | None = None,
max_concurrency: int | None = None,
+ control_plane_url: str | None = None,
+ org: str | None = None,
) -> None:
# Ensure msgpack-numpy hooks are installed (once per process).
# Done lazily here instead of at module level to avoid monkey-patching
@@ -373,6 +388,10 @@ class SIEAsyncClient:
self._default_gpu = gpu
self._default_options = options
self._api_key = api_key
+ # Control-plane base URL + org for the connections namespace (connector
+ # auth lives on the control plane, not the keyed gateway).
+ self._control_plane_url = control_plane_url.rstrip("/") if control_plane_url else None
+ self._org = org
# Multi-pool state: track in-flight creations and lease renewal tasks
self._pools: dict[str, _PoolTaskEntry] = {}
@@ -407,6 +426,14 @@ class SIEAsyncClient:
self._session: aiohttp.ClientSession | None = None
self._closed = False
+ # First-class batch + connector surface.
+ self.jobs = _AsyncJobs(self)
+ self.connections = _AsyncConnections(self)
+ # OpenAI-compatible Files + Batches surface — a
+ # `base_url` swap makes an `openai` batch caller work unchanged.
+ self.files = _AsyncFiles(self)
+ self.batches = _AsyncBatches(self)
+
def _ensure_session(self) -> aiohttp.ClientSession:
"""Lazily create the aiohttp session on first use (requires a running loop)."""
if self._session is None:
@@ -1477,11 +1504,23 @@ class SIEAsyncClient:
workers: list[WorkerInfo] = [
WorkerInfo(
+ name=w.get("name", ""),
url=w.get("url", ""),
gpu=w.get("gpu", ""),
+ gpu_count=w.get("gpu_count", 0),
+ ready_gpu_slots=w.get(
+ "ready_gpu_slots",
+ w.get("gpu_count", 1 if w.get("healthy", False) else 0),
+ ),
healthy=w.get("healthy", False),
queue_depth=w.get("queue_depth", 0),
+ pending_cost=w.get("pending_cost", 0),
+ inflight_batches=w.get("inflight_batches", 0),
loaded_models=w.get("loaded_models", []),
+ memory_used_bytes=w.get("memory_used_bytes", 0),
+ memory_total_bytes=w.get("memory_total_bytes", 0),
+ bundle=w.get("bundle", ""),
+ bundle_config_hash=w.get("bundle_config_hash", ""),
)
for w in workers_data
]
@@ -2484,3 +2523,300 @@ class SIEAsyncClient:
results = parse_extract_results(response_data["items"])
return results[0] if single_item else results
+
+
+# ---------------------------------------------------------------------------
+# Jobs + connections namespaces — async variants of the sync
+# namespaces; reuse the client's aiohttp session and bearer auth.
+# ---------------------------------------------------------------------------
+
+
+class _AsyncNamespace:
+ """Shared JSON transport for the async jobs/connections namespaces."""
+
+ def __init__(self, client: SIEAsyncClient) -> None:
+ self._c = client
+
+ async def _request_json(
+ self, method: str, url: str, *, json_body: Any = None, timeout_s: float | None = None
+ ) -> Any:
+ """One JSON request over the client's aiohttp session (bearer auth reused).
+
+ ``timeout_s`` overrides the session default for a single call — long-running
+ POSTs (jobs.submit / batches.create) floor it to 120s so a large preflight
+ does not abort while the server keeps working.
+ """
+ try:
+ if method == "GET":
+ response = await self._c._get(url, headers={"Accept": JSON_CONTENT_TYPE})
+ elif method == "DELETE":
+ response = await self._c._delete(url, headers={"Accept": JSON_CONTENT_TYPE})
+ else:
+ # Pre-serialize so the Content-Type is unambiguously application/json.
+ response = await self._c._post(
+ url,
+ data=json.dumps(json_body).encode("utf-8"),
+ headers={"Accept": JSON_CONTENT_TYPE, "Content-Type": JSON_CONTENT_TYPE},
+ timeout_s=timeout_s,
+ )
+ except TimeoutError as e:
+ msg = f"Request timed out: {e}"
+ raise SIEConnectionError(msg) from e
+ except (aiohttp.ClientError, OSError) as e:
+ msg = f"Failed to connect to {url}: {e}"
+ raise SIEConnectionError(msg) from e
+ if response.status_code >= HTTP_CLIENT_ERROR:
+ handle_error(response)
+ self._c._check_server_version(response)
+ if not response.content:
+ return {}
+ return response.json()
+
+
+class _AsyncJobs(_AsyncNamespace):
+ """Async batch class — see :class:`SIEClient` ``.jobs`` for the contract."""
+
+ async def submit(
+ self,
+ *,
+ source: Any,
+ model: str,
+ operation: str = "encode",
+ sink: Any = None,
+ connection: str | None = None,
+ sink_connection: str | None = None,
+ field_map: Mapping[str, Any] | None = None,
+ output_field: str | None = None,
+ when: Any = None,
+ output_types: Sequence[str] | None = None,
+ options: Mapping[str, Any] | None = None,
+ ) -> JobSubmitResult:
+ """Async ``jobs.submit``. See :class:`SIEClient` ``.jobs.submit`` for details."""
+ body = build_job_body(
+ source=source,
+ operation=operation,
+ model=model,
+ sink=sink,
+ connection=connection,
+ sink_connection=sink_connection,
+ field_map=field_map,
+ output_field=output_field,
+ when=when,
+ output_types=output_types,
+ options=options,
+ )
+ return await self._request_json("POST", "/v1/jobs", json_body=body, timeout_s=max(self._c._timeout, 120.0))
+
+ async def get(self, job_id: str) -> JobStatus:
+ """Async ``jobs.get``."""
+ return await self._request_json("GET", f"/v1/jobs/{job_id}")
+
+ async def list(self) -> Sequence[JobStatus]:
+ """Async ``jobs.list``."""
+ data = await self._request_json("GET", "/v1/jobs")
+ if isinstance(data, dict):
+ return data.get("data", [])
+ return data if isinstance(data, list) else []
+
+ async def cancel(self, job_id: str) -> JobStatus:
+ """Async ``jobs.cancel``."""
+ return await self._request_json("POST", f"/v1/jobs/{job_id}/cancel")
+
+ async def results(self, job_id: str) -> JobResults:
+ """Async ``jobs.results`` — read + decode the finished job's chunk refs."""
+ job = await self.get(job_id)
+ chunks = job_chunks(job)
+ items = []
+ for chunk in chunks:
+ ref = chunk.get("ref")
+ if chunk.get("state") != "succeeded" or not ref:
+ continue
+ items.extend(decode_chunk_bytes(await self._read_ref(ref)))
+ dims = next((it["dims"] for it in items if it.get("dims")), None)
+ return {
+ "job_id": job.get("id", job_id),
+ "state": job.get("state"),
+ "total_items": job.get("total_items"),
+ "settled_credits": job.get("settled_credits"),
+ "chunks": chunks,
+ "retrieved": len(items),
+ "dims": dims,
+ "items": items,
+ }
+
+ async def wait(self, job_id: str, *, timeout_s: float = 600.0, poll_s: float = 2.0) -> JobStatus:
+ """Poll ``get`` until the job reaches a terminal state or ``timeout_s`` elapses."""
+ deadline = time.monotonic() + timeout_s
+ while True:
+ job = await self.get(job_id)
+ if job.get("state") in TERMINAL_JOB_STATES:
+ return job
+ if time.monotonic() >= deadline:
+ msg = f"job {job_id} still {job.get('state')!r} after {timeout_s:.0f}s"
+ raise RequestError(msg, code="job_wait_timeout", status_code=504)
+ await asyncio.sleep(poll_s)
+
+ async def _read_ref(self, ref: str) -> bytes:
+ """Retrieve a chunk's payload-store ref (local path or http(s) URL, POC).
+
+ http(s) refs are fetched on a bare session that does NOT carry the
+ client's ``Authorization`` header: a ref points at the payload store,
+ not the SIE API, so the bearer token must never leak to the ref host
+ (matches the TS SDK, which fetches refs with a plain ``fetch``).
+ """
+ if ref.startswith(("http://", "https://")):
+ timeout = aiohttp.ClientTimeout(total=self._c._timeout)
+ async with (
+ aiohttp.ClientSession(timeout=timeout) as session,
+ session.get(ref, headers={"Accept": "application/octet-stream"}) as resp,
+ ):
+ response = _AioResponse(resp.status, await resp.read(), resp.headers)
+ if response.status_code >= HTTP_CLIENT_ERROR:
+ handle_error(response)
+ return response.content
+ path = Path(ref)
+ if await asyncio.to_thread(path.exists):
+ return await asyncio.to_thread(path.read_bytes)
+ msg = f"cannot retrieve payload-store ref {ref!r} (POC reads local-path and http(s) refs)"
+ raise RequestError(msg, code="bad_ref", status_code=400)
+
+
+class _AsyncConnections(_AsyncNamespace):
+ """Async org-scoped connections — see :class:`SIEClient` ``.connections``."""
+
+ def _base(self) -> str:
+ if not self._c._control_plane_url:
+ msg = "connections require control_plane_url on the client: SIEAsyncClient(..., control_plane_url=..., org=...)"
+ raise ValueError(msg)
+ if not self._c._org:
+ msg = "connections require org on the client: SIEAsyncClient(..., org=...)"
+ raise ValueError(msg)
+ return f"{self._c._control_plane_url}/internal/orgs/{self._c._org}/connections"
+
+ async def add(self, name: str, type: str, secret: str) -> ConnectionCreated:
+ """Async ``connections.add``."""
+ body = {"type": type, "name": name, "secret": secret}
+ return await self._request_json("POST", self._base(), json_body=body)
+
+ async def list(self) -> Sequence[Connection]:
+ """Async ``connections.list`` (secrets redacted)."""
+ data = await self._request_json("GET", self._base())
+ if isinstance(data, dict):
+ return data.get("connections", [])
+ return data if isinstance(data, list) else []
+
+ async def revoke(self, name: str) -> ConnectionRevoked:
+ """Async ``connections.revoke``."""
+ return await self._request_json("DELETE", f"{self._base()}/{name}")
+
+
+# ---------------------------------------------------------------------------
+# Files + batches namespaces — async variants of the sync
+# namespaces; reuse the client's aiohttp session and bearer auth. Method
+# names/args mirror `openai.files` / `openai.batches`.
+# ---------------------------------------------------------------------------
+
+
+class _AsyncFiles(_AsyncNamespace):
+ """Async OpenAI-compatible Files API — see :class:`SIEClient` ``.files``."""
+
+ async def upload(
+ self,
+ file: str | Path | bytes | bytearray | IO[bytes],
+ *,
+ purpose: str = "batch",
+ filename: str | None = None,
+ ) -> File:
+ """Async ``files.upload`` (``POST /v1/files``)."""
+ # resolve_upload does blocking path/file-like reads; off-load it so a
+ # large upload does not stall the event loop.
+ content, name = await asyncio.to_thread(resolve_upload, file, filename)
+ query = urlencode({"purpose": purpose, "filename": name})
+ try:
+ response = await self._c._post(
+ f"/v1/files?{query}",
+ data=content,
+ headers={"Accept": JSON_CONTENT_TYPE, "Content-Type": "application/jsonl"},
+ timeout_s=max(self._c._timeout, 120.0),
+ )
+ except TimeoutError as e:
+ msg = f"Request timed out: {e}"
+ raise SIEConnectionError(msg) from e
+ except (aiohttp.ClientError, OSError) as e:
+ msg = f"Failed to connect to {self._c._base_url}: {e}"
+ raise SIEConnectionError(msg) from e
+ if response.status_code >= HTTP_CLIENT_ERROR:
+ handle_error(response)
+ self._c._check_server_version(response)
+ return response.json()
+
+ async def create(
+ self,
+ *,
+ file: str | Path | bytes | bytearray | IO[bytes],
+ purpose: str = "batch",
+ ) -> File:
+ """OpenAI-exact alias for :meth:`upload` (``files.create(file=, purpose=)``)."""
+ return await self.upload(file, purpose=purpose)
+
+ async def retrieve(self, file_id: str) -> File:
+ """Async ``files.retrieve`` (``GET /v1/files/{id}``)."""
+ return await self._request_json("GET", f"/v1/files/{file_id}")
+
+ async def content(self, file_id: str) -> bytes:
+ """Async ``files.content`` — download a file's raw bytes (``GET /v1/files/{id}/content``)."""
+ try:
+ response = await self._c._get(
+ f"/v1/files/{file_id}/content",
+ headers={"Accept": "application/jsonl"},
+ )
+ except TimeoutError as e:
+ msg = f"Request timed out: {e}"
+ raise SIEConnectionError(msg) from e
+ except (aiohttp.ClientError, OSError) as e:
+ msg = f"Failed to connect to {self._c._base_url}: {e}"
+ raise SIEConnectionError(msg) from e
+ if response.status_code >= HTTP_CLIENT_ERROR:
+ handle_error(response)
+ return response.content
+
+ async def delete(self, file_id: str) -> FileDeleted:
+ """Async ``files.delete`` (``DELETE /v1/files/{id}``; additive OpenAI-parity)."""
+ return await self._request_json("DELETE", f"/v1/files/{file_id}")
+
+
+class _AsyncBatches(_AsyncNamespace):
+ """Async OpenAI-compatible Batch API — see :class:`SIEClient` ``.batches``."""
+
+ async def create(
+ self,
+ *,
+ input_file_id: str,
+ endpoint: str = "/v1/embeddings",
+ completion_window: str = "24h",
+ metadata: dict[str, Any] | None = None,
+ ) -> Batch:
+ """Async ``batches.create`` (``POST /v1/batches``)."""
+ body: dict[str, Any] = {
+ "input_file_id": input_file_id,
+ "endpoint": endpoint,
+ "completion_window": completion_window,
+ }
+ if metadata is not None:
+ body["metadata"] = metadata
+ return await self._request_json("POST", "/v1/batches", json_body=body, timeout_s=max(self._c._timeout, 120.0))
+
+ async def retrieve(self, batch_id: str) -> Batch:
+ """Async ``batches.retrieve`` (``GET /v1/batches/{id}``)."""
+ return await self._request_json("GET", f"/v1/batches/{batch_id}")
+
+ async def list(self) -> Sequence[Batch]:
+ """Async ``batches.list`` (``GET /v1/batches``; additive OpenAI-parity)."""
+ data = await self._request_json("GET", "/v1/batches")
+ if isinstance(data, dict):
+ return data.get("data", [])
+ return data if isinstance(data, list) else []
+
+ async def cancel(self, batch_id: str) -> Batch:
+ """Async ``batches.cancel`` (``POST /v1/batches/{id}/cancel``; additive OpenAI-parity)."""
+ return await self._request_json("POST", f"/v1/batches/{batch_id}/cancel")
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.py
index 8e9bfb257..9055dc9bd 100644
--- a/packages/sie_sdk/src/sie_sdk/client/sync.py
+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py
@@ -41,25 +41,38 @@ import logging
import threading
import time
import weakref
-from collections.abc import Iterator
-from typing import Any, Literal, Self, overload
+from collections.abc import Iterator, Mapping, Sequence
+from pathlib import Path
+from typing import IO, Any, Literal, Self, overload
+from urllib.parse import urlencode
import httpx
import msgpack
import msgpack_numpy as m
from sie_sdk.documents import convert_item_document
+from sie_sdk.files import resolve_upload
from sie_sdk.images import convert_item_images
+from sie_sdk.jobs import TERMINAL_JOB_STATES, build_job_body, decode_chunk_bytes, job_chunks
from sie_sdk.types import (
+ Batch,
CapacityInfo,
ChatCompletion,
ChatCompletionChunk,
ChatMessage,
+ Connection,
+ ConnectionCreated,
+ ConnectionRevoked,
EncodeResult,
ExtractResult,
+ File,
+ FileDeleted,
GenerateChunk,
GenerateResult,
Item,
+ JobResults,
+ JobStatus,
+ JobSubmitResult,
ModelInfo,
OutputType,
PoolInfo,
@@ -314,6 +327,8 @@ class SIEClient:
gpu: str | None = None,
options: dict[str, Any] | None = None,
pool: PoolSpec | None = None,
+ control_plane_url: str | None = None,
+ org: str | None = None,
) -> None:
# Ensure msgpack-numpy hooks are installed (once per process).
# Done lazily here instead of at module level to avoid monkey-patching
@@ -329,6 +344,10 @@ class SIEClient:
self._default_gpu = gpu
self._default_options = options
self._api_key = api_key
+ # Control-plane base URL + org for the connections namespace (connector
+ # auth lives on the control plane, not the keyed gateway).
+ self._control_plane_url = control_plane_url.rstrip("/") if control_plane_url else None
+ self._org = org
# Multi-pool state: track created pools and their lease renewal threads
# Key: pool name, Value: (lease_thread, stop_event)
@@ -375,6 +394,14 @@ class SIEClient:
if pool is not None:
atexit.register(self._cleanup_pool)
+ # First-class batch + connector surface.
+ self.jobs = _SyncJobs(self)
+ self.connections = _SyncConnections(self)
+ # OpenAI-compatible Files + Batches surface — a
+ # `base_url` swap makes an `openai` batch caller work unchanged.
+ self.files = _SyncFiles(self)
+ self.batches = _SyncBatches(self)
+
@property
def base_url(self) -> str:
"""Return the base URL of the SIE server."""
@@ -1506,11 +1533,23 @@ class SIEClient:
workers: list[WorkerInfo] = [
WorkerInfo(
+ name=w.get("name", ""),
url=w.get("url", ""),
gpu=w.get("gpu", ""),
+ gpu_count=w.get("gpu_count", 0),
+ ready_gpu_slots=w.get(
+ "ready_gpu_slots",
+ w.get("gpu_count", 1 if w.get("healthy", False) else 0),
+ ),
healthy=w.get("healthy", False),
queue_depth=w.get("queue_depth", 0),
+ pending_cost=w.get("pending_cost", 0),
+ inflight_batches=w.get("inflight_batches", 0),
loaded_models=w.get("loaded_models", []),
+ memory_used_bytes=w.get("memory_used_bytes", 0),
+ memory_total_bytes=w.get("memory_total_bytes", 0),
+ bundle=w.get("bundle", ""),
+ bundle_config_hash=w.get("bundle_config_hash", ""),
)
for w in workers_data
]
@@ -2720,3 +2759,353 @@ class SIEClient:
# Return single result if single item was passed
return results[0] if single_item else results
+
+
+# ---------------------------------------------------------------------------
+# Jobs + connections namespaces — reuse the client's transport
+# and bearer auth. Jobs ride the keyed gateway (`/v1/jobs`); connections ride
+# the control plane (`/internal/orgs/{org}/connections`).
+# ---------------------------------------------------------------------------
+
+
+class _SyncNamespace:
+ """Shared JSON transport for the sync jobs/connections namespaces."""
+
+ def __init__(self, client: SIEClient) -> None:
+ self._c = client
+
+ def _request_json(
+ self,
+ method: str,
+ url: str,
+ *,
+ json_body: Any = None,
+ timeout_s: float | None = None,
+ ) -> Any:
+ """One JSON request over the client's httpx transport (bearer auth reused)."""
+ headers = {"Accept": JSON_CONTENT_TYPE, "Content-Type": JSON_CONTENT_TYPE}
+ try:
+ response = self._c._client.request(
+ method,
+ url,
+ json=json_body,
+ headers=headers,
+ timeout=timeout_s if timeout_s is not None else self._c._timeout,
+ )
+ except httpx.ConnectError as e:
+ msg = f"Failed to connect to {url}: {e}"
+ raise SIEConnectionError(msg) from e
+ except httpx.TimeoutException as e:
+ msg = f"Request timed out: {e}"
+ raise SIEConnectionError(msg) from e
+ if response.status_code >= HTTP_CLIENT_ERROR:
+ handle_error(response)
+ self._c._check_server_version(response)
+ if not response.content:
+ return {}
+ return response.json()
+
+
+class _SyncJobs(_SyncNamespace):
+ """The batch class — ``POST/GET /v1/jobs`` on the keyed gateway.
+
+ ``submit``/``get``/``results`` bind to the shipped ``/v1/jobs`` contract;
+ ``list``/``cancel`` bind to the additive ``GET /v1/jobs`` /
+ ``POST /v1/jobs/{id}/cancel`` completion of that REST surface (``/v1``
+ additive-only — the shipped E2E is the ``sie.process`` submit/get/results
+ path).
+ """
+
+ def submit(
+ self,
+ *,
+ source: Any,
+ model: str,
+ operation: str = "encode",
+ sink: Any = None,
+ connection: str | None = None,
+ sink_connection: str | None = None,
+ field_map: Mapping[str, Any] | None = None,
+ output_field: str | None = None,
+ when: Any = None,
+ output_types: Sequence[str] | None = None,
+ options: Mapping[str, Any] | None = None,
+ ) -> JobSubmitResult:
+ """Submit a batch job (``POST /v1/jobs``); returns the created-job envelope.
+
+ ``source`` is either inline items (a list, or a bare string = one text
+ item) or a connector ``scheme://<connection>/…`` URI (incl.
+ the internal ``upload://<file-id>`` push-to-us source); ``sink``
+ is ``"return"`` (default), ``"inplace"``, or a connector URI; ``when`` is
+ ``"now"`` (default), ``"schedule:<cron>"``, or ``"watch:<source>"``.
+ ``field_map`` names the uniform source slots
+ (``{"id_field", "input_field", "carry", "input_type"}``) and
+ ``output_field`` the sink target — connector jobs only; the
+ per-connector URI params keep working as aliases. ``options`` carries
+ the per-item options plus the op inputs (operation matrix:
+ score → ``options["query"]``, extract → ``options["labels"]`` /
+ ``options["output_schema"]``, generate → sampling such as
+ ``max_new_tokens``), forwarded as-is.
+ """
+ body = build_job_body(
+ source=source,
+ operation=operation,
+ model=model,
+ sink=sink,
+ connection=connection,
+ sink_connection=sink_connection,
+ field_map=field_map,
+ output_field=output_field,
+ when=when,
+ output_types=output_types,
+ options=options,
+ )
+ return self._request_json("POST", "/v1/jobs", json_body=body, timeout_s=max(self._c._timeout, 120.0))
+
+ def get(self, job_id: str) -> JobStatus:
+ """Fetch a job's public status doc (``GET /v1/jobs/{id}``)."""
+ return self._request_json("GET", f"/v1/jobs/{job_id}")
+
+ def list(self) -> Sequence[JobStatus]:
+ """List the org's jobs (``GET /v1/jobs``; scoped to the key's org)."""
+ data = self._request_json("GET", "/v1/jobs")
+ if isinstance(data, dict):
+ return data.get("data", [])
+ return data if isinstance(data, list) else []
+
+ def cancel(self, job_id: str) -> JobStatus:
+ """Cancel a job (``POST /v1/jobs/{id}/cancel``); the hold's remainder releases."""
+ return self._request_json("POST", f"/v1/jobs/{job_id}/cancel")
+
+ def results(self, job_id: str) -> JobResults:
+ """Retrieve a finished job's chunk refs and decode the per-item results.
+
+ Reads each succeeded chunk's TTL'd payload-store ref (local path or
+ http(s) URL in the POC) and unpacks the msgpack ``WorkResult`` array;
+ dense embeddings decode to numpy arrays (like :meth:`encode`).
+ """
+ job = self.get(job_id)
+ chunks = job_chunks(job)
+ items = []
+ for chunk in chunks:
+ ref = chunk.get("ref")
+ if chunk.get("state") != "succeeded" or not ref:
+ continue
+ items.extend(decode_chunk_bytes(self._read_ref(ref)))
+ dims = next((it["dims"] for it in items if it.get("dims")), None)
+ return {
+ "job_id": job.get("id", job_id),
+ "state": job.get("state"),
+ "total_items": job.get("total_items"),
+ "settled_credits": job.get("settled_credits"),
+ "chunks": chunks,
+ "retrieved": len(items),
+ "dims": dims,
+ "items": items,
+ }
+
+ def wait(self, job_id: str, *, timeout_s: float = 600.0, poll_s: float = 2.0) -> JobStatus:
+ """Poll ``get`` until the job reaches a terminal state or ``timeout_s`` elapses."""
+ deadline = time.monotonic() + timeout_s
+ while True:
+ job = self.get(job_id)
+ if job.get("state") in TERMINAL_JOB_STATES:
+ return job
+ if time.monotonic() >= deadline:
+ msg = f"job {job_id} still {job.get('state')!r} after {timeout_s:.0f}s"
+ raise RequestError(msg, code="job_wait_timeout", status_code=504)
+ time.sleep(poll_s)
+
+ def _read_ref(self, ref: str) -> bytes:
+ """Retrieve a chunk's payload-store ref (local path or http(s) URL, POC).
+
+ http(s) refs are fetched with a bare request that does NOT carry the
+ client's ``Authorization`` header: a ref points at the payload store,
+ not the SIE API, so the bearer token must never leak to the ref host
+ (matches the TS SDK, which fetches refs with a plain ``fetch``).
+ """
+ if ref.startswith(("http://", "https://")):
+ response = httpx.get(
+ ref,
+ headers={"Accept": "application/octet-stream"},
+ timeout=self._c._client.timeout,
+ )
+ if response.status_code >= HTTP_CLIENT_ERROR:
+ handle_error(response)
+ return response.content
+ path = Path(ref)
+ if path.exists():
+ return path.read_bytes()
+ msg = f"cannot retrieve payload-store ref {ref!r} (POC reads local-path and http(s) refs)"
+ raise RequestError(msg, code="bad_ref", status_code=400)
+
+
+class _SyncConnections(_SyncNamespace):
+ """Org-scoped connections (connector auth by name) on the control plane.
+
+ Requires ``control_plane_url`` + ``org`` on the client; the secret is sent on
+ ``add`` and is never returned by ``list`` (only the job-runner resolve path
+ sees it).
+ """
+
+ def _base(self) -> str:
+ if not self._c._control_plane_url:
+ msg = "connections require control_plane_url on the client: SIEClient(..., control_plane_url=..., org=...)"
+ raise ValueError(msg)
+ if not self._c._org:
+ msg = "connections require org on the client: SIEClient(..., org=...)"
+ raise ValueError(msg)
+ return f"{self._c._control_plane_url}/internal/orgs/{self._c._org}/connections"
+
+ def add(self, name: str, type: str, secret: str) -> ConnectionCreated:
+ """Create an org-scoped connection (connector auth). ``type`` is the connector family."""
+ body = {"type": type, "name": name, "secret": secret}
+ return self._request_json("POST", self._base(), json_body=body)
+
+ def list(self) -> Sequence[Connection]:
+ """List the org's active connections (secrets redacted)."""
+ data = self._request_json("GET", self._base())
+ if isinstance(data, dict):
+ return data.get("connections", [])
+ return data if isinstance(data, list) else []
+
+ def revoke(self, name: str) -> ConnectionRevoked:
+ """Revoke (soft-delete) a connection; frees the name for reuse."""
+ return self._request_json("DELETE", f"{self._base()}/{name}")
+
+
+# ---------------------------------------------------------------------------
+# Files + batches namespaces — the OpenAI-compatible file/batch
+# surface on the keyed gateway. Method names/args mirror `openai.files` /
+# `openai.batches` so switching an OpenAI-batch caller to the SDK is mechanical.
+# ---------------------------------------------------------------------------
+
+
+class _SyncFiles(_SyncNamespace):
+ """OpenAI-compatible Files API — ``POST/GET /v1/files`` on the keyed gateway.
+
+ Mirrors ``openai.files``: :meth:`upload` (aliased :meth:`create` for a
+ byte-for-byte ``openai`` → ``sie_sdk`` swap), :meth:`retrieve`,
+ :meth:`content` (raw bytes), and :meth:`delete`. Bytes live in the gateway's
+ file store the batch path reads/writes; ``purpose="batch"`` is the only
+ purpose the store serves today. :meth:`delete` is the additive OpenAI-parity
+ completion of the surface (served when the delete-on-complete seam lands).
+ """
+
+ def upload(
+ self,
+ file: str | Path | bytes | bytearray | IO[bytes],
+ *,
+ purpose: str = "batch",
+ filename: str | None = None,
+ ) -> File:
+ """Upload a file (``POST /v1/files``); returns the created File object.
+
+ ``file`` is a filesystem path, raw bytes, or a binary file-like object
+ (the same inputs OpenAI's ``files.create(file=...)`` accepts);
+ ``purpose`` is ``"batch"`` (the only purpose the mode-B store serves).
+ """
+ content, name = resolve_upload(file, filename)
+ query = urlencode({"purpose": purpose, "filename": name})
+ headers = {"Accept": JSON_CONTENT_TYPE, "Content-Type": "application/jsonl"}
+ try:
+ response = self._c._client.post(
+ f"/v1/files?{query}",
+ content=content,
+ headers=headers,
+ timeout=max(self._c._timeout, 120.0),
+ )
+ except httpx.ConnectError as e:
+ msg = f"Failed to connect to {self._c._base_url}: {e}"
+ raise SIEConnectionError(msg) from e
+ except httpx.TimeoutException as e:
+ msg = f"Request timed out: {e}"
+ raise SIEConnectionError(msg) from e
+ if response.status_code >= HTTP_CLIENT_ERROR:
+ handle_error(response)
+ self._c._check_server_version(response)
+ return response.json()
+
+ def create(
+ self,
+ *,
+ file: str | Path | bytes | bytearray | IO[bytes],
+ purpose: str = "batch",
+ ) -> File:
+ """OpenAI-exact alias for :meth:`upload` (``files.create(file=, purpose=)``)."""
+ return self.upload(file, purpose=purpose)
+
+ def retrieve(self, file_id: str) -> File:
+ """Fetch a file's metadata (``GET /v1/files/{id}``)."""
+ return self._request_json("GET", f"/v1/files/{file_id}")
+
+ def content(self, file_id: str) -> bytes:
+ """Download a file's raw bytes (``GET /v1/files/{id}/content``)."""
+ try:
+ response = self._c._client.get(
+ f"/v1/files/{file_id}/content",
+ headers={"Accept": "application/jsonl"},
+ )
+ except httpx.ConnectError as e:
+ msg = f"Failed to connect to {self._c._base_url}: {e}"
+ raise SIEConnectionError(msg) from e
+ except httpx.TimeoutException as e:
+ msg = f"Request timed out: {e}"
+ raise SIEConnectionError(msg) from e
+ if response.status_code >= HTTP_CLIENT_ERROR:
+ handle_error(response)
+ return response.content
+
+ def delete(self, file_id: str) -> FileDeleted:
+ """Delete a file (``DELETE /v1/files/{id}``; additive OpenAI-parity surface)."""
+ return self._request_json("DELETE", f"/v1/files/{file_id}")
+
+
+class _SyncBatches(_SyncNamespace):
+ """OpenAI-compatible Batch API — ``POST/GET /v1/batches`` on the keyed gateway.
+
+ Mirrors ``openai.batches``: :meth:`create`, :meth:`retrieve`, :meth:`list`,
+ :meth:`cancel`. A batch is a job over an uploaded file's JSONL lines run
+ on the batch lane (same ``spawn_encode_job`` engine as
+ ``/v1/jobs``). :meth:`list` / :meth:`cancel` are the additive OpenAI-parity
+ completion of the surface (served when the batch store hardens; the shipped path is
+ create → retrieve → download the output file via ``client.files.content``).
+ """
+
+ def create(
+ self,
+ *,
+ input_file_id: str,
+ endpoint: str = "/v1/embeddings",
+ completion_window: str = "24h",
+ metadata: dict[str, Any] | None = None,
+ ) -> Batch:
+ """Create a batch (``POST /v1/batches``); returns the Batch object.
+
+ ``input_file_id`` is a ``file-…`` id from :meth:`SIEClient.files.upload`
+ with ``purpose="batch"``; ``endpoint`` is ``/v1/embeddings`` (the only
+ endpoint the encode-only jobs POC serves).
+ """
+ body: dict[str, Any] = {
+ "input_file_id": input_file_id,
+ "endpoint": endpoint,
+ "completion_window": completion_window,
+ }
+ if metadata is not None:
+ body["metadata"] = metadata
+ return self._request_json("POST", "/v1/batches", json_body=body, timeout_s=max(self._c._timeout, 120.0))
+
+ def retrieve(self, batch_id: str) -> Batch:
+ """Fetch a batch's status (``GET /v1/batches/{id}``)."""
+ return self._request_json("GET", f"/v1/batches/{batch_id}")
+
+ def list(self) -> Sequence[Batch]:
+ """List the org's batches (``GET /v1/batches``; additive OpenAI-parity)."""
+ data = self._request_json("GET", "/v1/batches")
+ if isinstance(data, dict):
+ return data.get("data", [])
+ return data if isinstance(data, list) else []
+
+ def cancel(self, batch_id: str) -> Batch:
+ """Cancel a batch (``POST /v1/batches/{id}/cancel``; additive OpenAI-parity)."""
+ return self._request_json("POST", f"/v1/batches/{batch_id}/cancel")
diff --git a/packages/sie_sdk/src/sie_sdk/files.py b/packages/sie_sdk/src/sie_sdk/files.py
new file mode 100644
index 000000000..b41223d57
--- /dev/null
+++ b/packages/sie_sdk/src/sie_sdk/files.py
@@ -0,0 +1,43 @@
+"""Pure helpers for the files surface (``client.files``) — no transport.
+
+The files API is the OpenAI-compatible file store. ``client.files.upload``
+binds to ``POST /v1/files``; this module owns the transport-free piece — turning
+a path / bytes / file-like into ``(content, filename)`` — so it stays
+unit-testable without a gateway (mirroring ``sie_sdk.jobs``).
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import IO
+
+
+def resolve_upload(
+ file: str | Path | bytes | bytearray | IO[bytes],
+ filename: str | None = None,
+) -> tuple[bytes, str]:
+ """Normalize an upload argument to ``(content_bytes, filename)``.
+
+ Accepts a filesystem path (``str``/``Path``), raw ``bytes``, or a binary
+ file-like object (anything with ``.read()``) — the same inputs OpenAI's
+ ``files.create(file=...)`` accepts. ``filename`` overrides the derived name;
+ a file-like's ``.name`` (which may be a full path) is reduced to its
+ basename.
+
+ Raises:
+ TypeError: If ``file`` is none of the accepted shapes.
+ """
+ if isinstance(file, (bytes, bytearray)):
+ return bytes(file), filename or "upload.jsonl"
+ if isinstance(file, (str, Path)):
+ path = Path(file)
+ return path.read_bytes(), filename or path.name
+ read = getattr(file, "read", None)
+ if callable(read):
+ data = read()
+ if isinstance(data, str):
+ data = data.encode("utf-8")
+ name = filename or getattr(file, "name", None) or "upload.jsonl"
+ return bytes(data), Path(str(name)).name
+ msg = f"file must be a path, bytes, or a binary file-like object, got {type(file).__name__}"
+ raise TypeError(msg)
diff --git a/packages/sie_sdk/src/sie_sdk/jobs.py b/packages/sie_sdk/src/sie_sdk/jobs.py
new file mode 100644
index 000000000..677371156
--- /dev/null
+++ b/packages/sie_sdk/src/sie_sdk/jobs.py
@@ -0,0 +1,328 @@
+"""Pure helpers for the jobs surface (``client.jobs``) — no transport.
+
+The jobs API is the gateway's batch class. ``client.jobs.submit(...)`` binds
+to ``POST /v1/jobs``; this module owns the transport-free pieces so they stay
+unit-testable without a gateway:
+
+* :func:`build_job_body` — the ``source → operation → sink / when`` slot
+ mapping onto the ``POST /v1/jobs`` body (inline items vs a connector
+ ``src``/``sink`` + connection name).
+* :func:`connection_name` — derive a connection name from a connector URI.
+* :func:`decode_result_item` / :func:`job_chunks` — decode a finished job's
+ msgpack chunk refs into per-item results (results are refs, not payloads).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from typing import TYPE_CHECKING, Any
+from urllib.parse import urlsplit
+
+import msgpack
+import msgpack_numpy
+import numpy as np
+
+from sie_sdk.types import JobChunk, JobResultItem
+
+if TYPE_CHECKING:
+ from numpy.typing import NDArray
+
+# Job states with no further transitions (job lifecycle).
+TERMINAL_JOB_STATES = frozenset({"succeeded", "failed", "suspended", "cancelled"})
+
+# Sink sentinels: return the results (default) or write next to the source.
+_SINK_RETURN = frozenset({"return", "default"})
+_SINK_INPLACE = frozenset({"inplace", "in_place", "in place"})
+
+# Internal push-to-us schemes (OUR Files store) — no org connection to
+# name, so no `connection`/`sink_connection` is derived from the URI.
+_INTERNAL_SCHEMES = frozenset({"upload"})
+
+# Uniform source-mapping slots (the sink slot is `output_field`).
+_FIELD_MAP_KEYS = frozenset({"id_field", "input_field", "carry", "input_type"})
+_INPUT_TYPES = frozenset({"text", "document"})
+
+# msgpack + the numpy codec are hard deps of the SDK, so always importable here.
+_RESULT_OBJECT_HOOK = msgpack_numpy.decode
+
+
+def _norm_item(item: Any, index: int) -> dict[str, Any]:
+ """Normalize a job item to the ``/v1/encode`` item contract (``{text}``/``{id,text}``)."""
+ if isinstance(item, str):
+ return {"text": item}
+ if isinstance(item, dict):
+ return item
+ msg = f"item {index} must be a string or an object, got {type(item).__name__}"
+ raise ValueError(msg)
+
+
+def _is_connector_uri(value: Any) -> bool:
+ """A connector source/sink is a ``scheme://…`` URI (inline items are a list)."""
+ return isinstance(value, str) and "://" in value
+
+
+def connection_name(uri: str) -> str:
+ """The connection an org registered, referenced by the URI authority.
+
+ ``postgres://warehouse?query=…`` → ``warehouse``; ``s3://customer-bucket/in/``
+ → ``customer-bucket``. Credentials never appear in the call — the job only
+ names the connection; the runner resolves it org-scoped.
+ """
+ parts = urlsplit(uri)
+ name = parts.netloc or parts.path.lstrip("/").split("/", 1)[0]
+ if not name:
+ msg = f"connector URI {uri!r} names no connection (expected 'scheme://<connection>/…')"
+ raise ValueError(msg)
+ return name
+
+
+def _is_internal_uri(uri: str) -> bool:
+ """True for the internal push-to-us schemes (``upload://`` — OUR store)."""
+ return urlsplit(uri).scheme in _INTERNAL_SCHEMES
+
+
+def _resolve_source(source: Any, connection: str | None) -> dict[str, Any]:
+ """Map the ``source`` slot onto jobs-API fields (inline items | connector URI).
+
+ An internal-scheme URI (``upload://<file-id>``) names no org
+ connection — the address is OUR Files store — so no ``connection`` rides
+ unless explicitly given.
+ """
+ if isinstance(source, list):
+ if not source:
+ msg = "inline source has no items"
+ raise ValueError(msg)
+ return {"items": [_norm_item(item, i) for i, item in enumerate(source)]}
+ if _is_connector_uri(source):
+ if _is_internal_uri(source):
+ return {"src": source, **({"connection": connection} if connection else {})}
+ return {"src": source, "connection": connection or connection_name(source)}
+ if isinstance(source, str) and source.strip():
+ # A bare string is one inline text item (the "embed this text" case).
+ return {"items": [{"text": source}]}
+ msg = "source must be inline items (a list/string) or a connector URI (scheme://<connection>/…)"
+ raise ValueError(msg)
+
+
+def _resolve_sink(sink: Any, *, source_connection: str | None, sink_connection: str | None) -> dict[str, Any]:
+ """Map the ``sink`` slot: return (default) | in place | a connector URI."""
+ if sink is None or (isinstance(sink, str) and sink.strip().lower() in _SINK_RETURN):
+ return {}
+ if isinstance(sink, str) and sink.strip().lower() in _SINK_INPLACE:
+ return {"sink": "inplace"}
+ if _is_connector_uri(sink):
+ body: dict[str, Any] = {"sink": sink}
+ if _is_internal_uri(sink):
+ # Internal scheme: OUR Files store, no connection to name.
+ if sink_connection is not None:
+ body["sink_connection"] = sink_connection
+ return body
+ resolved = sink_connection if sink_connection is not None else connection_name(sink)
+ # Thread the sink connection when explicitly overridden or distinct from
+ # the source's (the common "index my own store" case reuses the source).
+ if sink_connection is not None or resolved != source_connection:
+ body["sink_connection"] = resolved
+ return body
+ msg = f"sink must be 'return', 'inplace', or a connector URI (got {sink!r})"
+ raise ValueError(msg)
+
+
+def _resolve_field_map(field_map: Mapping[str, Any] | None, output_field: str | None) -> dict[str, Any]:
+ """Validate + map the uniform slots onto the wire fields.
+
+ ``field_map`` carries the source slots (``id_field``/``input_field``/
+ ``carry``/``input_type``); ``output_field`` is the sink slot (≈
+ ``response.body``, aliasing PG ``column`` / object-store ``suffix``). Only
+ set fields ride the wire (`/v1` additive-only).
+ """
+ body: dict[str, Any] = {}
+ if field_map is not None:
+ if not isinstance(field_map, Mapping):
+ msg = f"field_map must be a mapping of the uniform slots, got {type(field_map).__name__}"
+ raise ValueError(msg)
+ unknown = set(field_map) - _FIELD_MAP_KEYS
+ if unknown:
+ msg = f"unknown field_map key(s) {sorted(unknown)} (known: {sorted(_FIELD_MAP_KEYS)})"
+ raise ValueError(msg)
+ carry = field_map.get("carry")
+ if carry is not None and (
+ not isinstance(carry, (list, tuple)) or not all(isinstance(c, str) and c for c in carry)
+ ):
+ msg = f"field_map.carry must be a list of field names, got {carry!r}"
+ raise ValueError(msg)
+ input_type = field_map.get("input_type")
+ if input_type is not None and input_type not in _INPUT_TYPES:
+ msg = f"field_map.input_type must be one of {sorted(_INPUT_TYPES)}, got {input_type!r}"
+ raise ValueError(msg)
+ mapped = {
+ key: field_map[key] for key in ("id_field", "input_field", "input_type") if field_map.get(key) is not None
+ }
+ if carry:
+ mapped["carry"] = list(carry)
+ if mapped:
+ body["field_map"] = mapped
+ if output_field is not None:
+ if not isinstance(output_field, str) or not output_field:
+ msg = f"output_field must be a non-empty string, got {output_field!r}"
+ raise ValueError(msg)
+ body["output_field"] = output_field
+ return body
+
+
+def _resolve_when(when: Any) -> dict[str, Any]:
+ """Map the ``when`` trigger: now (default) | schedule(cron) | watch(source)."""
+ if when is None or not isinstance(when, str) or when.strip().lower() in {"", "now"}:
+ return {}
+ text = when.strip()
+ if text.lower().startswith("schedule:"):
+ return {"when": "schedule", "schedule": text.split(":", 1)[1].strip()}
+ if text.lower().startswith("watch:"):
+ return {"when": "watch", "watch": text.split(":", 1)[1].strip()}
+ if text.lower() == "schedule":
+ msg = "schedule trigger needs a cron expr: when='schedule:<cron>'"
+ raise ValueError(msg)
+ # A bare cron expression (5 whitespace-separated fields) is a schedule.
+ if len(text.split()) == 5:
+ return {"when": "schedule", "schedule": text}
+ msg = f"unrecognized when {when!r}: use 'now', 'schedule:<cron>', or 'watch:<source>'"
+ raise ValueError(msg)
+
+
+def build_job_body(
+ *,
+ source: Any,
+ operation: str,
+ model: str,
+ sink: Any = None,
+ connection: str | None = None,
+ sink_connection: str | None = None,
+ field_map: Mapping[str, Any] | None = None,
+ output_field: str | None = None,
+ when: Any = None,
+ output_types: Sequence[str] | None = None,
+ options: Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Compose the ``POST /v1/jobs`` body from the source/op/sink/when slots.
+
+ A thin, pure mapping: inline ``items`` or connector ``src``/``sink``
+ + connection name, plus an optional trigger. ``connection`` /
+ ``sink_connection`` override the names derived from the URIs; ``field_map``
+ + ``output_field`` are the uniform mapping slots (connector jobs
+ only — per-connector ``id_column``/``text_column``/``column`` params keep
+ working as aliases). ``options`` is the opaque per-item options map plus
+ the op inputs (operation matrix: score → ``options.query``,
+ extract → ``options.labels`` / ``options.output_schema``, generate →
+ sampling such as ``max_new_tokens``); it is forwarded as-is. Only the
+ fields that are set ride the wire, so an inline submit is byte-for-byte
+ the realtime POC body and the connector body is additive (``/v1``
+ additive-only rule).
+
+ Raises:
+ ValueError: If the source/sink/when/field_map/options slots cannot be
+ resolved.
+ """
+ body: dict[str, Any] = {"operation": operation, "model": model}
+ source_fields = _resolve_source(source, connection)
+ body.update(source_fields)
+ body.update(_resolve_sink(sink, source_connection=source_fields.get("connection"), sink_connection=sink_connection))
+ mapping_fields = _resolve_field_map(field_map, output_field)
+ if mapping_fields and "src" not in body:
+ msg = "field_map/output_field apply to connector-src jobs; an inline items job maps nothing"
+ raise ValueError(msg)
+ body.update(mapping_fields)
+ body.update(_resolve_when(when))
+ if output_types:
+ body["output_types"] = list(output_types)
+ if options is not None:
+ if not isinstance(options, Mapping):
+ msg = f"options must be a mapping (per-item options + op inputs), got {type(options).__name__}"
+ raise ValueError(msg)
+ if options:
+ body["options"] = dict(options)
+ return body
+
+
+def _to_array(value: Any) -> NDArray[Any] | None:
+ if value is None:
+ return None
+ if isinstance(value, np.ndarray):
+ return value
+ if isinstance(value, (list, tuple)):
+ return np.asarray(value)
+ if hasattr(value, "tolist"):
+ return np.asarray(value)
+ return None
+
+
+def _dense_info(dense: Any) -> tuple[int | None, NDArray[Any] | None]:
+ """Extract (dims, vector) from a decoded dense embedding of unknown shape.
+
+ The vector may be a numpy array (msgpack-numpy) or a plain list, so keys are
+ probed with explicit ``is None`` checks — ``a or b`` on an ndarray raises.
+ """
+ if dense is None:
+ return None, None
+ if isinstance(dense, dict):
+ raw: Any = None
+ for candidate in ("values", "vector", "dense"):
+ if dense.get(candidate) is not None:
+ raw = dense.get(candidate)
+ break
+ vector = _to_array(raw)
+ dims = dense.get("dims")
+ if dims is None and vector is not None:
+ dims = int(vector.shape[0])
+ return dims, vector
+ vector = _to_array(dense)
+ return (int(vector.shape[0]) if vector is not None else None), vector
+
+
+def decode_result_item(result: Any) -> JobResultItem:
+ """Decode one WorkResult map (from a chunk ref) into a per-item result.
+
+ The chunk's ``result_msgpack`` bytes carry the same wire shape the realtime
+ path returns per item; the dense vector decodes to a numpy array (SDK-native,
+ like :meth:`SIEClient.encode`).
+ """
+ payload = result.get("result_msgpack") if isinstance(result, dict) else None
+ decoded: Any = None
+ if isinstance(payload, (bytes, bytearray)):
+ try:
+ decoded = msgpack.unpackb(payload, raw=False, object_hook=_RESULT_OBJECT_HOOK)
+ except Exception: # noqa: BLE001 - a malformed payload should not abort retrieval
+ decoded = None
+ dense = decoded.get("dense") if isinstance(decoded, dict) else None
+ dims, vector = _dense_info(dense)
+ item: JobResultItem = {
+ "id": result.get("id") if isinstance(result, dict) else None,
+ "success": result.get("success") if isinstance(result, dict) else None,
+ "units": result.get("units") if isinstance(result, dict) else None,
+ "dims": dims,
+ "dense": vector,
+ }
+ return item
+
+
+def job_chunks(job_doc: Mapping[str, Any]) -> list[JobChunk]:
+ """The chunk-ref metadata from a job status doc (``output.chunks`` refs)."""
+ raw = (job_doc.get("output") or {}).get("chunks") or []
+ return [
+ {
+ "seq": chunk.get("seq"),
+ "items": chunk.get("items"),
+ "state": chunk.get("state"),
+ "ref": chunk.get("ref"),
+ "units": chunk.get("units"),
+ "credits": chunk.get("credits"),
+ "error": chunk.get("error"),
+ }
+ for chunk in raw
+ ]
+
+
+def decode_chunk_bytes(raw: bytes) -> list[JobResultItem]:
+ """Decode a chunk ref's msgpack ``WorkResult`` array into per-item results."""
+ results = msgpack.unpackb(raw, raw=False)
+ if not isinstance(results, list):
+ return []
+ return [decode_result_item(r) for r in results]
diff --git a/packages/sie_sdk/src/sie_sdk/queue_types.py b/packages/sie_sdk/src/sie_sdk/queue_types.py
index 51214b927..7ff356dbe 100644
--- a/packages/sie_sdk/src/sie_sdk/queue_types.py
+++ b/packages/sie_sdk/src/sie_sdk/queue_types.py
@@ -137,6 +137,13 @@ class WorkResult(_WorkResultRequired, total=False):
tokenization_ms: Time spent tokenizing the input (ms).
postprocessing_ms: Time spent on output post-processing (ms).
payload_fetch_ms: Time spent fetching from payload store, 0 if inline (ms).
+
+ units: Authoritative billable-unit counts emitted by the engine
+ (``{"input_tokens": int, "pages": int, "images": int}``, every
+ key optional). ``input_tokens`` is the real tokenizer count
+ taken post-tokenization — never a bytes/4-style estimate.
+ Optional: absent on results from workers that don't emit it,
+ so the wire shape stays backward-compatible.
"""
result_msgpack: bytes | None
@@ -153,6 +160,10 @@ class WorkResult(_WorkResultRequired, total=False):
postprocessing_ms: float
payload_fetch_ms: float
+ # Authoritative unit counts for metering (see docstring). Optional —
+ # older workers omit it and decoders ignore unknown keys.
+ units: dict[str, int] | None
+
# -- NATS subject helpers ---------------------------------------------------
diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.py
index 87e43a993..06b3d1e76 100644
--- a/packages/sie_sdk/src/sie_sdk/types.py
+++ b/packages/sie_sdk/src/sie_sdk/types.py
@@ -324,7 +324,7 @@ class ExtractResult(TypedDict, total=False):
# Streaming generation result. Streaming happens inside the gateway/worker;
# the SDK surfaces the aggregated outcome plus SIE-native timing metadata
# (TTFT, TPOT, attempt_id). Future SDK additions may surface chunks as an
-# async iterator — see the POC plan §4.5.4.
+# async iterator.
FinishReason = Literal["stop", "length", "cancelled", "content_filter", "error"]
@@ -509,8 +509,11 @@ class WorkerInfo(TypedDict, total=False):
url: Worker base URL.
gpu: GPU type (e.g., "l4", "a100-80gb").
gpu_count: Number of GPUs on this worker.
+ ready_gpu_slots: Number of worker GPU slots ready to receive work.
healthy: Whether the worker is healthy.
queue_depth: Number of items in the worker's queue.
+ pending_cost: Worker-local scheduler pending cost.
+ inflight_batches: Number of batches currently executing on the worker.
loaded_models: List of model names loaded on this worker.
memory_used_bytes: Total GPU memory in use.
memory_total_bytes: Total GPU memory available.
@@ -522,8 +525,11 @@ class WorkerInfo(TypedDict, total=False):
url: str
gpu: str
gpu_count: int
+ ready_gpu_slots: int
healthy: bool
queue_depth: int
+ pending_cost: int
+ inflight_batches: int
loaded_models: list[str]
memory_used_bytes: int
memory_total_bytes: int
@@ -942,3 +948,236 @@ class ClusterStatusMessage(TypedDict, total=False):
StatusMessage = WorkerStatusMessage | ClusterStatusMessage
+
+
+# ---------------------------------------------------------------------------
+# Jobs API (client.jobs) — the gateway's batch class.
+# ---------------------------------------------------------------------------
+
+# A job's lifecycle state (queued → running → terminal).
+JobState = Literal["queued", "running", "succeeded", "failed", "suspended", "cancelled"]
+
+
+class JobFieldMap(TypedDict, total=False):
+ """The uniform source-mapping slots for ``jobs.submit(field_map=...)``.
+
+ ``id_field`` ≈ ``custom_id``, ``input_field`` ≈ ``body.input``, ``carry`` =
+ source fields echoed to the sink keyed by id, ``input_type`` pins the item
+ shape (``"text"`` | ``"document"``). The sink slot rides separately as
+ ``output_field``. All optional — per-connector params stay as aliases.
+ """
+
+ id_field: str
+ input_field: str
+ carry: list[str]
+ input_type: str
+
+
+class JobPreflight(TypedDict, total=False):
+ """The preflight reservation echoed on submit / status."""
+
+ estimated_credits: int
+ estimate_basis: str
+
+
+class JobChunk(TypedDict, total=False):
+ """One spawned chunk's settle metadata (``output.chunks[]``; results-as-refs).
+
+ ``ref`` is a TTL'd payload-store location holding the chunk's msgpack
+ ``WorkResult`` array — never the payload itself.
+ """
+
+ seq: int
+ items: int
+ state: str
+ ref: str | None
+ units: int | None
+ credits: int | None
+ error: Any
+
+
+class JobSubmitResult(TypedDict, total=False):
+ """The ``201`` envelope from ``POST /v1/jobs`` (inline or connector job)."""
+
+ id: str
+ object: str
+ operation: str
+ model: str
+ state: JobState
+ total_items: int
+ chunks: int
+ preflight: JobPreflight
+ # Connector jobs echo the resolved ends instead of total_items.
+ input_source: str
+ source: str
+ sink: str
+
+
+class JobStatus(TypedDict, total=False):
+ """A job's public status doc from ``GET /v1/jobs/{id}`` (refs, never payloads)."""
+
+ id: str
+ object: str
+ operation: str
+ model: str
+ state: JobState
+ total_items: int
+ completed_items: int
+ preflight: JobPreflight
+ settled_credits: int
+ created_at: float
+ finished_at: float | None
+ output: dict[str, Any]
+
+
+class JobList(TypedDict, total=False):
+ """The listing envelope from ``GET /v1/jobs`` (the org's jobs, keyed by bearer)."""
+
+ object: str
+ data: list[JobStatus]
+
+
+class JobResultItem(TypedDict, total=False):
+ """One decoded per-item result retrieved from a finished job's chunk refs."""
+
+ id: str | None
+ success: bool | None
+ units: Any
+ dims: int | None
+ dense: Any
+
+
+class JobResults(TypedDict, total=False):
+ """A finished job's decoded results — the chunk refs read and unpacked."""
+
+ job_id: str
+ state: JobState | None
+ total_items: int | None
+ settled_credits: int | None
+ chunks: list[JobChunk]
+ retrieved: int
+ dims: int | None
+ items: list[JobResultItem]
+
+
+# ---------------------------------------------------------------------------
+# Connections API (client.connections) — org-scoped connector auth by name.
+# ---------------------------------------------------------------------------
+
+
+class Connection(TypedDict, total=False):
+ """An org-scoped connection (connector auth by name). The secret is never returned."""
+
+ id: int
+ type: str
+ name: str
+ created_at: float
+
+
+class ConnectionCreated(TypedDict, total=False):
+ """The ``201`` envelope from creating a connection (org + connection, no secret)."""
+
+ org: str
+ account_id: int
+ id: int
+ type: str
+ name: str
+ created_at: float
+
+
+class ConnectionRevoked(TypedDict, total=False):
+ """The envelope from revoking (soft-deleting) a connection."""
+
+ org: str
+ account_id: int
+ name: str
+ state: str
+
+
+# ---------------------------------------------------------------------------
+# Files API (client.files) — the OpenAI-compatible file store. Byte-for-byte the
+# OpenAI File object, so switching `openai` → `sie_sdk` is a base_url-swap
+# drop-in for the batch flow.
+# ---------------------------------------------------------------------------
+
+
+class File(TypedDict, total=False):
+ """An OpenAI-shaped file object (``POST/GET /v1/files``).
+
+ Mirrors OpenAI's ``FileObject``: the gateway emits ``{id, object:"file",
+ bytes, created_at, filename, purpose}``. ``status`` /
+ ``expires_at`` are the optional OpenAI fields surfaced when the TTL-GC
+ lands (batch files expire, matching OpenAI's 30-day window).
+ """
+
+ id: str
+ object: str
+ bytes: int
+ created_at: int
+ filename: str
+ purpose: str
+ status: str
+ expires_at: int
+
+
+class FileDeleted(TypedDict, total=False):
+ """The envelope from deleting a file (OpenAI ``FileDeleted``)."""
+
+ id: str
+ object: str
+ deleted: bool
+
+
+# ---------------------------------------------------------------------------
+# Batches API (client.batches) — the OpenAI-compatible batch surface. Runs on
+# the same jobs engine as /v1/jobs (`spawn_encode_job`), one engine two front
+# doors: a `base_url` swap makes an OpenAI-batch caller work unchanged.
+# ---------------------------------------------------------------------------
+
+
+class BatchRequestCounts(TypedDict, total=False):
+ """Per-batch request tally (OpenAI ``request_counts``)."""
+
+ total: int
+ completed: int
+ failed: int
+
+
+class Batch(TypedDict, total=False):
+ """An OpenAI-shaped batch object (``POST/GET /v1/batches``).
+
+ Mirrors OpenAI's ``Batch``: the gateway emits ``{id, object:"batch",
+ endpoint, input_file_id, completion_window, status, output_file_id,
+ error_file_id, created_at, finished_at, request_counts, errors}``
+ (``batches.rs``). The granular OpenAI timestamps (``completed_at`` etc.) are
+ optional — a strict OpenAI SDK reads them when the gateway surfaces them.
+ """
+
+ id: str
+ object: str
+ endpoint: str
+ input_file_id: str
+ completion_window: str
+ status: str
+ output_file_id: str | None
+ error_file_id: str | None
+ created_at: int
+ finished_at: int | None
+ in_progress_at: int | None
+ completed_at: int | None
+ failed_at: int | None
+ expired_at: int | None
+ cancelled_at: int | None
+ request_counts: BatchRequestCounts
+ errors: Any
+ metadata: dict[str, Any] | None
+
+
+class BatchList(TypedDict, total=False):
+ """The listing envelope from ``GET /v1/batches`` (OpenAI cursor page)."""
+
+ object: str
+ data: list[Batch]
+ first_id: str
+ last_id: str
+ has_more: bool
diff --git a/packages/sie_sdk/tests/client/test_async.py b/packages/sie_sdk/tests/client/test_async.py
index 39ea69467..cd52db739 100644
--- a/packages/sie_sdk/tests/client/test_async.py
+++ b/packages/sie_sdk/tests/client/test_async.py
@@ -108,6 +108,75 @@ class TestSIEAsyncClientInit:
await client.close()
+class TestAsyncCapacity:
+ """Tests for async gateway capacity parsing."""
+
+ @pytest.mark.asyncio
+ async def test_get_capacity_preserves_worker_pressure_fields(self) -> None:
+ payload = {
+ "type": "gateway",
+ "status": "healthy",
+ "cluster": {"worker_count": 1, "gpu_count": 4, "models_loaded": 1},
+ "workers": [
+ {
+ "name": "worker-l4-0",
+ "url": "http://worker-l4-0:8080",
+ "gpu": "l4",
+ "gpu_count": 4,
+ "ready_gpu_slots": 3,
+ "healthy": True,
+ "queue_depth": 7,
+ "pending_cost": 128,
+ "inflight_batches": 2,
+ "loaded_models": ["BAAI/bge-m3"],
+ "memory_used_bytes": 1024,
+ "memory_total_bytes": 4096,
+ "bundle": "default",
+ "bundle_config_hash": "hash-1",
+ }
+ ],
+ }
+ client = SIEAsyncClient("http://localhost:8080")
+ client._get = AsyncMock(return_value=_make_json_response(payload)) # type: ignore
+
+ capacity = await client.get_capacity()
+ await client.close()
+
+ worker = capacity["workers"][0]
+ assert worker["gpu_count"] == 4
+ assert worker["ready_gpu_slots"] == 3
+ assert worker["queue_depth"] == 7
+ assert worker["pending_cost"] == 128
+ assert worker["inflight_batches"] == 2
+
+ @pytest.mark.asyncio
+ async def test_get_capacity_defaults_baseline_worker_to_one_ready_slot(self) -> None:
+ payload = {
+ "type": "gateway",
+ "status": "healthy",
+ "cluster": {"worker_count": 1, "gpu_count": 1, "models_loaded": 0},
+ "workers": [
+ {
+ "url": "http://worker-l4-0:8080",
+ "gpu": "l4",
+ "healthy": True,
+ "queue_depth": 0,
+ "loaded_models": [],
+ }
+ ],
+ }
+ client = SIEAsyncClient("http://localhost:8080")
+ client._get = AsyncMock(return_value=_make_json_response(payload)) # type: ignore
+
+ capacity = await client.get_capacity()
+ await client.close()
+
+ worker = capacity["workers"][0]
+ assert worker["ready_gpu_slots"] == 1
+ assert worker["pending_cost"] == 0
+ assert worker["inflight_batches"] == 0
+
+
class TestMaxConcurrency:
"""Tests for max_concurrency semaphore throttling."""
diff --git a/packages/sie_sdk/tests/client/test_batches.py b/packages/sie_sdk/tests/client/test_batches.py
new file mode 100644
index 000000000..a6b93a6bb
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_batches.py
@@ -0,0 +1,157 @@
+"""client.batches namespace — request-shape assertions against a mocked transport.
+
+Mirrors the OpenAI ``client.batches`` surface (create/retrieve/list/cancel) so
+an ``openai`` → ``sie_sdk`` swap is mechanical.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from sie_sdk import SIEAsyncClient, SIEClient
+
+GW = "http://gw.test:8080"
+KEY = "sk-sie-testkey"
+
+_BATCH = {
+ "id": "batch-1",
+ "object": "batch",
+ "endpoint": "/v1/embeddings",
+ "input_file_id": "file-in",
+ "completion_window": "24h",
+ "status": "completed",
+ "output_file_id": "file-out",
+ "error_file_id": None,
+ "created_at": 1000,
+ "finished_at": 1001,
+ "request_counts": {"total": 2, "completed": 2, "failed": 0},
+}
+
+
+def _resp(status: int, body: Any) -> MagicMock:
+ r = MagicMock()
+ r.status_code = status
+ r.headers = {"content-type": "application/json"}
+ r.content = json.dumps(body).encode()
+ r.json.return_value = body
+ return r
+
+
+class _FakeAio:
+ def __init__(self, status: int, body: Any) -> None:
+ self.status_code = status
+ self.content = json.dumps(body).encode()
+ self.headers = {"content-type": "application/json"}
+ self._body = body
+
+ def json(self) -> Any:
+ return self._body
+
+
+# ---------------------------------------------------------------------------
+# sync
+# ---------------------------------------------------------------------------
+
+
+def test_create_posts_v1_batches_with_openai_body() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(200, _BATCH))
+ client = SIEClient(GW, api_key=KEY)
+ out = client.batches.create(input_file_id="file-in", endpoint="/v1/embeddings")
+ assert out["id"] == "batch-1"
+ assert out["request_counts"]["total"] == 2
+ method, url = mock_client.return_value.request.call_args.args
+ body = mock_client.return_value.request.call_args.kwargs["json"]
+ assert (method, url) == ("POST", "/v1/batches")
+ assert body == {
+ "input_file_id": "file-in",
+ "endpoint": "/v1/embeddings",
+ "completion_window": "24h",
+ }
+ client.close()
+
+
+def test_create_includes_metadata_when_set() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(200, _BATCH))
+ client = SIEClient(GW, api_key=KEY)
+ client.batches.create(
+ input_file_id="file-in",
+ endpoint="/v1/embeddings",
+ completion_window="24h",
+ metadata={"run": "eval-7"},
+ )
+ body = mock_client.return_value.request.call_args.kwargs["json"]
+ assert body["metadata"] == {"run": "eval-7"}
+ client.close()
+
+
+def test_retrieve_and_cancel_hit_expected_urls() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(200, _BATCH))
+ client = SIEClient(GW, api_key=KEY)
+ client.batches.retrieve("batch-1")
+ assert mock_client.return_value.request.call_args.args == ("GET", "/v1/batches/batch-1")
+ client.batches.cancel("batch-1")
+ assert mock_client.return_value.request.call_args.args == ("POST", "/v1/batches/batch-1/cancel")
+ client.close()
+
+
+def test_list_returns_data_array() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(
+ return_value=_resp(200, {"object": "list", "data": [{"id": "batch-1"}, {"id": "batch-2"}]})
+ )
+ client = SIEClient(GW, api_key=KEY)
+ batches = client.batches.list()
+ assert [b["id"] for b in batches] == ["batch-1", "batch-2"]
+ assert mock_client.return_value.request.call_args.args == ("GET", "/v1/batches")
+ client.close()
+
+
+# ---------------------------------------------------------------------------
+# async
+# ---------------------------------------------------------------------------
+
+
+async def test_async_create_serializes_json_body() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._post = AsyncMock(return_value=_FakeAio(200, _BATCH))
+ out = await client.batches.create(input_file_id="file-in", endpoint="/v1/embeddings")
+ assert out["id"] == "batch-1"
+ call = client._post.call_args
+ assert call.args[0] == "/v1/batches"
+ assert json.loads(call.kwargs["data"]) == {
+ "input_file_id": "file-in",
+ "endpoint": "/v1/embeddings",
+ "completion_window": "24h",
+ }
+ await client.close()
+
+
+async def test_async_create_floors_long_running_timeout() -> None:
+ """batches.create floors the per-call timeout to 120s (parity with the sync client)."""
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._post = AsyncMock(return_value=_FakeAio(200, _BATCH))
+ await client.batches.create(input_file_id="file-in")
+ assert client._post.call_args.kwargs["timeout_s"] == max(client._timeout, 120.0)
+ await client.close()
+
+
+async def test_async_retrieve_and_cancel() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._get = AsyncMock(return_value=_FakeAio(200, _BATCH))
+ client._post = AsyncMock(return_value=_FakeAio(200, {"id": "batch-1", "status": "cancelling"}))
+ got = await client.batches.retrieve("batch-1")
+ assert got["status"] == "completed"
+ assert client._get.call_args.args[0] == "/v1/batches/batch-1"
+ out = await client.batches.cancel("batch-1")
+ assert out["status"] == "cancelling"
+ assert client._post.call_args.args[0] == "/v1/batches/batch-1/cancel"
+ await client.close()
diff --git a/packages/sie_sdk/tests/client/test_connections.py b/packages/sie_sdk/tests/client/test_connections.py
new file mode 100644
index 000000000..2c81b55b3
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_connections.py
@@ -0,0 +1,104 @@
+"""client.connections namespace — control-plane request-shape assertions (mocked)."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from sie_sdk import SIEAsyncClient, SIEClient
+
+GW = "http://gw.test:8080"
+CP = "http://cp.test:9000"
+KEY = "sk-sie-testkey"
+
+
+def _resp(status: int, body: Any) -> MagicMock:
+ r = MagicMock()
+ r.status_code = status
+ r.headers = {"content-type": "application/json"}
+ r.content = json.dumps(body).encode()
+ r.json.return_value = body
+ return r
+
+
+class _FakeAio:
+ def __init__(self, status: int, body: Any) -> None:
+ self.status_code = status
+ self.content = json.dumps(body).encode()
+ self.headers = {"content-type": "application/json"}
+ self._body = body
+
+ def json(self) -> Any:
+ return self._body
+
+
+def test_add_posts_to_control_plane_with_secret() -> None:
+ created = {"org": "acme", "account_id": 7, "id": 1, "type": "postgres", "name": "wh", "created_at": 1.0}
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(201, created))
+ client = SIEClient(GW, api_key=KEY, control_plane_url=CP, org="acme")
+ out = client.connections.add(name="wh", type="postgres", secret="postgres://u:p@h/db") # noqa: S106
+ assert out["name"] == "wh"
+ method, url = mock_client.return_value.request.call_args.args
+ body = mock_client.return_value.request.call_args.kwargs["json"]
+ assert method == "POST"
+ assert url == f"{CP}/internal/orgs/acme/connections"
+ assert body == {"type": "postgres", "name": "wh", "secret": "postgres://u:p@h/db"}
+ client.close()
+
+
+def test_list_returns_connections_array() -> None:
+ payload = {"org": "acme", "account_id": 7, "connections": [{"id": 1, "type": "postgres", "name": "wh"}]}
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(200, payload))
+ client = SIEClient(GW, api_key=KEY, control_plane_url=CP, org="acme")
+ conns = client.connections.list()
+ assert [c["name"] for c in conns] == ["wh"]
+ assert mock_client.return_value.request.call_args.args == ("GET", f"{CP}/internal/orgs/acme/connections")
+ client.close()
+
+
+def test_revoke_deletes_named_connection() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(
+ return_value=_resp(200, {"org": "acme", "name": "wh", "state": "revoked"})
+ )
+ client = SIEClient(GW, api_key=KEY, control_plane_url=CP, org="acme")
+ out = client.connections.revoke("wh")
+ assert out["state"] == "revoked"
+ assert mock_client.return_value.request.call_args.args == ("DELETE", f"{CP}/internal/orgs/acme/connections/wh")
+ client.close()
+
+
+def test_connections_without_control_plane_raises() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client"):
+ client = SIEClient(GW, api_key=KEY)
+ with pytest.raises(ValueError, match="control_plane_url"):
+ client.connections.list()
+ client.close()
+
+
+def test_connections_without_org_raises() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client"):
+ client = SIEClient(GW, api_key=KEY, control_plane_url=CP)
+ with pytest.raises(ValueError, match="org"):
+ client.connections.list()
+ client.close()
+
+
+async def test_async_add_and_revoke() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY, control_plane_url=CP, org="acme")
+ created = {"org": "acme", "id": 1, "type": "postgres", "name": "wh"}
+ client._post = AsyncMock(return_value=_FakeAio(201, created))
+ client._delete = AsyncMock(return_value=_FakeAio(200, {"name": "wh", "state": "revoked"}))
+ out = await client.connections.add(name="wh", type="postgres", secret="dsn") # noqa: S106
+ assert out["name"] == "wh"
+ assert client._post.call_args.args[0] == f"{CP}/internal/orgs/acme/connections"
+ assert json.loads(client._post.call_args.kwargs["data"]) == {"type": "postgres", "name": "wh", "secret": "dsn"}
+ revoked = await client.connections.revoke("wh")
+ assert revoked["state"] == "revoked"
+ assert client._delete.call_args.args[0] == f"{CP}/internal/orgs/acme/connections/wh"
+ await client.close()
diff --git a/packages/sie_sdk/tests/client/test_files.py b/packages/sie_sdk/tests/client/test_files.py
new file mode 100644
index 000000000..7b1e23af4
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_files.py
@@ -0,0 +1,188 @@
+"""client.files namespace — request-shape assertions against a mocked transport.
+
+Mirrors the OpenAI ``client.files`` surface (upload/create/retrieve/content/
+delete) so an ``openai`` → ``sie_sdk`` swap is mechanical.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from sie_sdk import SIEAsyncClient, SIEClient
+from sie_sdk.files import resolve_upload
+
+GW = "http://gw.test:8080"
+KEY = "sk-sie-testkey"
+
+_FILE = {
+ "id": "file-abc",
+ "object": "file",
+ "bytes": 42,
+ "created_at": 1,
+ "filename": "in.jsonl",
+ "purpose": "batch",
+}
+
+
+def _json_resp(status: int, body: Any) -> MagicMock:
+ r = MagicMock()
+ r.status_code = status
+ r.headers = {"content-type": "application/json"}
+ r.json.return_value = body
+ r.content = b"{}"
+ return r
+
+
+def _bytes_resp(status: int, data: bytes) -> MagicMock:
+ r = MagicMock()
+ r.status_code = status
+ r.headers = {"content-type": "application/jsonl"}
+ r.content = data
+ return r
+
+
+class _FakeAio:
+ def __init__(self, status: int, body: Any, *, raw: bytes | None = None) -> None:
+ self.status_code = status
+ self.content = raw if raw is not None else b"{}"
+ self.headers = {"content-type": "application/json"}
+ self._body = body
+
+ def json(self) -> Any:
+ return self._body
+
+
+# ---------------------------------------------------------------------------
+# resolve_upload (pure helper)
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_upload_bytes_defaults_filename() -> None:
+ assert resolve_upload(b"hi") == (b"hi", "upload.jsonl")
+ assert resolve_upload(b"hi", "x.jsonl") == (b"hi", "x.jsonl")
+
+
+def test_resolve_upload_path_reads_bytes_and_basename(tmp_path: Any) -> None:
+ p = tmp_path / "batch_input.jsonl"
+ p.write_bytes(b'{"custom_id":"a"}\n')
+ content, name = resolve_upload(p)
+ assert content == b'{"custom_id":"a"}\n'
+ assert name == "batch_input.jsonl"
+
+
+def test_resolve_upload_file_like_uses_basename_of_name(tmp_path: Any) -> None:
+ p = tmp_path / "sub.jsonl"
+ p.write_bytes(b"data")
+ with p.open("rb") as fh:
+ content, name = resolve_upload(fh)
+ assert content == b"data"
+ assert name == "sub.jsonl"
+
+
+def test_resolve_upload_rejects_other_types() -> None:
+ with pytest.raises(TypeError, match="path, bytes"):
+ resolve_upload(123) # type: ignore[arg-type]
+
+
+# ---------------------------------------------------------------------------
+# sync
+# ---------------------------------------------------------------------------
+
+
+def test_upload_bytes_posts_to_v1_files_raw_body() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_json_resp(200, _FILE))
+ client = SIEClient(GW, api_key=KEY)
+ out = client.files.upload(b'{"custom_id":"a"}\n', purpose="batch", filename="in.jsonl")
+ assert out["id"] == "file-abc"
+ url = mock_client.return_value.post.call_args.args[0]
+ kwargs = mock_client.return_value.post.call_args.kwargs
+ assert url.startswith("/v1/files?")
+ assert "purpose=batch" in url
+ assert "filename=in.jsonl" in url
+ assert kwargs["content"] == b'{"custom_id":"a"}\n'
+ assert kwargs["headers"]["Content-Type"] == "application/jsonl"
+ client.close()
+
+
+def test_upload_path_derives_filename(tmp_path: Any) -> None:
+ p = tmp_path / "batch.jsonl"
+ p.write_bytes(b"x")
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_json_resp(200, _FILE))
+ client = SIEClient(GW, api_key=KEY)
+ client.files.upload(p)
+ url = mock_client.return_value.post.call_args.args[0]
+ assert "filename=batch.jsonl" in url
+ assert mock_client.return_value.post.call_args.kwargs["content"] == b"x"
+ client.close()
+
+
+def test_create_is_openai_exact_alias() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.post = MagicMock(return_value=_json_resp(200, _FILE))
+ client = SIEClient(GW, api_key=KEY)
+ out = client.files.create(file=b"x", purpose="batch")
+ assert out["id"] == "file-abc"
+ assert "purpose=batch" in mock_client.return_value.post.call_args.args[0]
+ client.close()
+
+
+def test_retrieve_and_delete_hit_expected_urls() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_json_resp(200, _FILE))
+ client = SIEClient(GW, api_key=KEY)
+ client.files.retrieve("file-abc")
+ assert mock_client.return_value.request.call_args.args == ("GET", "/v1/files/file-abc")
+ mock_client.return_value.request.return_value = _json_resp(
+ 200, {"id": "file-abc", "object": "file", "deleted": True}
+ )
+ out = client.files.delete("file-abc")
+ assert out["deleted"] is True
+ assert mock_client.return_value.request.call_args.args == ("DELETE", "/v1/files/file-abc")
+ client.close()
+
+
+def test_content_returns_raw_bytes() -> None:
+ payload = b'{"custom_id":"a","response":{"status_code":200}}\n'
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.get = MagicMock(return_value=_bytes_resp(200, payload))
+ client = SIEClient(GW, api_key=KEY)
+ out = client.files.content("file-out")
+ assert out == payload
+ assert mock_client.return_value.get.call_args.args[0] == "/v1/files/file-out/content"
+ client.close()
+
+
+# ---------------------------------------------------------------------------
+# async
+# ---------------------------------------------------------------------------
+
+
+async def test_async_upload_sends_raw_body() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._post = AsyncMock(return_value=_FakeAio(200, _FILE))
+ out = await client.files.upload(b"x", filename="in.jsonl")
+ assert out["id"] == "file-abc"
+ call = client._post.call_args
+ assert call.args[0].startswith("/v1/files?")
+ assert "filename=in.jsonl" in call.args[0]
+ assert call.kwargs["data"] == b"x"
+ assert call.kwargs["headers"]["Content-Type"] == "application/jsonl"
+ await client.close()
+
+
+async def test_async_content_and_delete() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._get = AsyncMock(return_value=_FakeAio(200, None, raw=b"jsonl-bytes"))
+ client._delete = AsyncMock(return_value=_FakeAio(200, {"id": "file-1", "object": "file", "deleted": True}))
+ assert await client.files.content("file-1") == b"jsonl-bytes"
+ assert client._get.call_args.args[0] == "/v1/files/file-1/content"
+ out = await client.files.delete("file-1")
+ assert out["deleted"] is True
+ assert client._delete.call_args.args[0] == "/v1/files/file-1"
+ await client.close()
diff --git a/packages/sie_sdk/tests/client/test_jobs.py b/packages/sie_sdk/tests/client/test_jobs.py
new file mode 100644
index 000000000..5edbcf78e
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_jobs.py
@@ -0,0 +1,260 @@
+"""client.jobs namespace — request-shape assertions against a mocked transport."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import msgpack
+import pytest
+from sie_sdk import SIEAsyncClient, SIEClient
+
+GW = "http://gw.test:8080"
+KEY = "sk-sie-testkey"
+
+_SUBMIT_RESP = {
+ "id": "job-1",
+ "object": "job",
+ "operation": "encode",
+ "model": "BAAI/bge-m3",
+ "state": "queued",
+ "total_items": 2,
+ "chunks": 1,
+ "preflight": {"estimated_credits": 64},
+}
+
+
+def _resp(status: int, body: Any) -> MagicMock:
+ r = MagicMock()
+ r.status_code = status
+ r.headers = {"content-type": "application/json"}
+ payload = json.dumps(body).encode()
+ r.content = payload
+ r.json.return_value = body
+ return r
+
+
+class _FakeAio:
+ """Minimal stand-in for the async client's _AioResponse."""
+
+ def __init__(self, status: int, body: Any) -> None:
+ self.status_code = status
+ self.content = json.dumps(body).encode()
+ self.headers = {"content-type": "application/json"}
+ self._body = body
+
+ def json(self) -> Any:
+ return self._body
+
+
+# ---------------------------------------------------------------------------
+# sync
+# ---------------------------------------------------------------------------
+
+
+def test_submit_inline_maps_items_and_posts_v1_jobs() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(201, _SUBMIT_RESP))
+ client = SIEClient(GW, api_key=KEY)
+ result = client.jobs.submit(source=["a", "b"], model="BAAI/bge-m3")
+ assert result["id"] == "job-1"
+ method, url = mock_client.return_value.request.call_args.args
+ body = mock_client.return_value.request.call_args.kwargs["json"]
+ assert (method, url) == ("POST", "/v1/jobs")
+ assert body == {"operation": "encode", "model": "BAAI/bge-m3", "items": [{"text": "a"}, {"text": "b"}]}
+ client.close()
+
+
+def test_submit_connector_job_body() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(201, _SUBMIT_RESP))
+ client = SIEClient(GW, api_key=KEY)
+ client.jobs.submit(
+ source="postgres://warehouse?query=x",
+ model="BAAI/bge-m3",
+ sink="s3://out/vecs",
+ )
+ body = mock_client.return_value.request.call_args.kwargs["json"]
+ assert body["src"] == "postgres://warehouse?query=x"
+ assert body["connection"] == "warehouse"
+ assert body["sink"] == "s3://out/vecs"
+ assert body["sink_connection"] == "out"
+ client.close()
+
+
+def test_submit_field_map_job_body() -> None:
+ """field_map + output_field ride the wire; upload:// derives no connection."""
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(201, _SUBMIT_RESP))
+ client = SIEClient(GW, api_key=KEY)
+ client.jobs.submit(
+ source="upload://file-abc?format=csv",
+ model="BAAI/bge-m3",
+ sink="upload://file-out",
+ field_map={"id_field": "doc_id", "input_field": "text", "carry": ["source_url"], "input_type": "text"},
+ output_field="embedding",
+ )
+ body = mock_client.return_value.request.call_args.kwargs["json"]
+ assert body["src"] == "upload://file-abc?format=csv"
+ assert body["sink"] == "upload://file-out"
+ assert "connection" not in body # internal scheme: OUR store, no org connection
+ assert body["field_map"] == {
+ "id_field": "doc_id",
+ "input_field": "text",
+ "carry": ["source_url"],
+ "input_type": "text",
+ }
+ assert body["output_field"] == "embedding"
+ client.close()
+
+
+def test_submit_score_options_query_rides_the_wire() -> None:
+ """Op inputs ride `options` (op matrix): a score job's query reaches the body."""
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(201, _SUBMIT_RESP))
+ client = SIEClient(GW, api_key=KEY)
+ client.jobs.submit(
+ source="postgres://warehouse?query=x",
+ model="BAAI/bge-m3",
+ operation="score",
+ sink="postgres://warehouse?table=scores",
+ options={"query": "rank these documents"},
+ )
+ body = mock_client.return_value.request.call_args.kwargs["json"]
+ assert body["operation"] == "score"
+ assert body["options"] == {"query": "rank these documents"}
+ client.close()
+
+
+def test_get_and_cancel_hit_expected_urls() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(200, {"id": "job-1", "state": "cancelled"}))
+ client = SIEClient(GW, api_key=KEY)
+ client.jobs.get("job-1")
+ assert mock_client.return_value.request.call_args.args == ("GET", "/v1/jobs/job-1")
+ out = client.jobs.cancel("job-1")
+ assert mock_client.return_value.request.call_args.args == ("POST", "/v1/jobs/job-1/cancel")
+ assert out["state"] == "cancelled"
+ client.close()
+
+
+def test_list_returns_data_array() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(
+ return_value=_resp(200, {"object": "list", "data": [{"id": "job-1"}, {"id": "job-2"}]})
+ )
+ client = SIEClient(GW, api_key=KEY)
+ jobs = client.jobs.list()
+ assert [j["id"] for j in jobs] == ["job-1", "job-2"]
+ assert mock_client.return_value.request.call_args.args == ("GET", "/v1/jobs")
+ client.close()
+
+
+def test_results_reads_local_refs_and_decodes(tmp_path: Any) -> None:
+ ref = tmp_path / "chunk0.msgpack"
+ ref.write_bytes(
+ msgpack.packb(
+ [
+ {
+ "success": True,
+ "id": str(i),
+ "units": {"input_tokens": 5},
+ "result_msgpack": msgpack.packb(
+ {"dense": {"dims": 4, "values": [0.1, 0.2, 0.3, 0.4]}}, use_bin_type=True
+ ),
+ }
+ for i in range(3)
+ ],
+ use_bin_type=True,
+ )
+ )
+ job = {
+ "id": "job-1",
+ "state": "succeeded",
+ "total_items": 3,
+ "settled_credits": 15,
+ "output": {"kind": "refs", "chunks": [{"seq": 0, "items": 3, "state": "succeeded", "ref": str(ref)}]},
+ }
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.request = MagicMock(return_value=_resp(200, job))
+ client = SIEClient(GW, api_key=KEY)
+ results = client.jobs.results("job-1")
+ assert results["retrieved"] == 3
+ assert results["dims"] == 4
+ assert results["items"][0]["dense"].shape == (4,)
+ client.close()
+
+
+# ---------------------------------------------------------------------------
+# async
+# ---------------------------------------------------------------------------
+
+
+async def test_async_submit_serializes_json_body() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._post = AsyncMock(return_value=_FakeAio(201, _SUBMIT_RESP))
+ result = await client.jobs.submit(source=["a"], model="m")
+ assert result["id"] == "job-1"
+ call = client._post.call_args
+ assert call.args[0] == "/v1/jobs"
+ assert json.loads(call.kwargs["data"]) == {"operation": "encode", "model": "m", "items": [{"text": "a"}]}
+ await client.close()
+
+
+async def test_async_submit_floors_long_running_timeout() -> None:
+ """jobs.submit floors the per-call timeout to 120s (parity with the sync client)."""
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._post = AsyncMock(return_value=_FakeAio(201, _SUBMIT_RESP))
+ await client.jobs.submit(source=["a"], model="m")
+ assert client._post.call_args.kwargs["timeout_s"] == max(client._timeout, 120.0)
+ await client.close()
+
+
+async def test_async_submit_field_map_body() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._post = AsyncMock(return_value=_FakeAio(201, _SUBMIT_RESP))
+ await client.jobs.submit(
+ source="postgres://wh?query=select id, body, source_url from docs",
+ model="BAAI/bge-m3",
+ sink="postgres://wh?table=doc_vectors",
+ field_map={"id_field": "id", "input_field": "body", "carry": ["source_url"]},
+ output_field="embedding",
+ )
+ body = json.loads(client._post.call_args.kwargs["data"])
+ assert body["field_map"] == {"id_field": "id", "input_field": "body", "carry": ["source_url"]}
+ assert body["output_field"] == "embedding"
+ assert body["connection"] == "wh"
+ await client.close()
+
+
+async def test_async_submit_extract_options_labels_body() -> None:
+ """Async parity: an extract job's labels/output_schema ride `options` as-is."""
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._post = AsyncMock(return_value=_FakeAio(201, _SUBMIT_RESP))
+ await client.jobs.submit(
+ source=["some text"],
+ model="urchade/gliner_small-v2.1",
+ operation="extract",
+ options={"labels": ["PERSON", "ORG"], "output_schema": {"type": "object"}},
+ )
+ body = json.loads(client._post.call_args.kwargs["data"])
+ assert body["operation"] == "extract"
+ assert body["options"] == {"labels": ["PERSON", "ORG"], "output_schema": {"type": "object"}}
+ await client.close()
+
+
+async def test_async_list_and_cancel() -> None:
+ client = SIEAsyncClient(GW, api_key=KEY)
+ client._get = AsyncMock(return_value=_FakeAio(200, {"object": "list", "data": [{"id": "job-9"}]}))
+ client._post = AsyncMock(return_value=_FakeAio(200, {"id": "job-9", "state": "cancelled"}))
+ assert [j["id"] for j in await client.jobs.list()] == ["job-9"]
+ out = await client.jobs.cancel("job-9")
+ assert out["state"] == "cancelled"
+ assert client._post.call_args.args[0] == "/v1/jobs/job-9/cancel"
+ await client.close()
diff --git a/packages/sie_sdk/tests/client/test_sync.py b/packages/sie_sdk/tests/client/test_sync.py
index 6afe766bb..4e9bf1cd3 100644
--- a/packages/sie_sdk/tests/client/test_sync.py
+++ b/packages/sie_sdk/tests/client/test_sync.py
@@ -117,6 +117,79 @@ class TestSIEClientInit:
client.close()
+class TestCapacity:
+ """Tests for gateway capacity parsing."""
+
+ def test_get_capacity_preserves_worker_pressure_fields(self) -> None:
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "type": "gateway",
+ "status": "healthy",
+ "cluster": {"worker_count": 1, "gpu_count": 4, "models_loaded": 1},
+ "workers": [
+ {
+ "name": "worker-l4-0",
+ "url": "http://worker-l4-0:8080",
+ "gpu": "l4",
+ "gpu_count": 4,
+ "ready_gpu_slots": 3,
+ "healthy": True,
+ "queue_depth": 7,
+ "pending_cost": 128,
+ "inflight_batches": 2,
+ "loaded_models": ["BAAI/bge-m3"],
+ "memory_used_bytes": 1024,
+ "memory_total_bytes": 4096,
+ "bundle": "default",
+ "bundle_config_hash": "hash-1",
+ }
+ ],
+ }
+
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.get.return_value = mock_response
+ client = SIEClient("http://localhost:8080")
+ capacity = client.get_capacity()
+ client.close()
+
+ worker = capacity["workers"][0]
+ assert worker["gpu_count"] == 4
+ assert worker["ready_gpu_slots"] == 3
+ assert worker["queue_depth"] == 7
+ assert worker["pending_cost"] == 128
+ assert worker["inflight_batches"] == 2
+
+ def test_get_capacity_defaults_baseline_worker_to_one_ready_slot(self) -> None:
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "type": "gateway",
+ "status": "healthy",
+ "cluster": {"worker_count": 1, "gpu_count": 1, "models_loaded": 0},
+ "workers": [
+ {
+ "url": "http://worker-l4-0:8080",
+ "gpu": "l4",
+ "healthy": True,
+ "queue_depth": 0,
+ "loaded_models": [],
+ }
+ ],
+ }
+
+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
+ mock_client.return_value.get.return_value = mock_response
+ client = SIEClient("http://localhost:8080")
+ capacity = client.get_capacity()
+ client.close()
+
+ worker = capacity["workers"][0]
+ assert worker["ready_gpu_slots"] == 1
+ assert worker["pending_cost"] == 0
+ assert worker["inflight_batches"] == 0
+
+
class TestEncode:
"""Tests for encode() method."""
diff --git a/packages/sie_sdk/tests/test_cache.py b/packages/sie_sdk/tests/test_cache.py
index 40b280a28..8ac2a7dc2 100644
--- a/packages/sie_sdk/tests/test_cache.py
+++ b/packages/sie_sdk/tests/test_cache.py
@@ -14,6 +14,7 @@ from sie_sdk.cache import (
ensure_model_cached,
get_cache_config,
is_model_cached,
+ populate_cluster_cache,
)
from sie_sdk.exceptions import GatedModelError
@@ -247,6 +248,96 @@ class TestCacheHierarchy:
mock_get.assert_called_once()
+class TestPopulateClusterCache:
+ """Tests for populate_cluster_cache()."""
+
+ @staticmethod
+ def _cached_model(local_cache: Path, model_id: str = "BAAI/bge-m3") -> Path:
+ """Create an HF-style cached model directory and return its root."""
+ model_dir = local_cache / f"models--{model_id.replace('/', '--')}"
+ snapshot = model_dir / "snapshots" / "abc123"
+ snapshot.mkdir(parents=True)
+ (snapshot / "model.safetensors").write_text("weights")
+ (snapshot / "config.json").write_text("{}")
+ return model_dir
+
+ def test_no_cluster_cache_configured(self, tmp_path: Path) -> None:
+ """Returns False without touching storage when cluster cache is unset."""
+ self._cached_model(tmp_path)
+ config = CacheConfig(local_cache=tmp_path, cluster_cache=None)
+
+ with patch("sie_sdk.cache.get_storage_backend") as mock_get:
+ assert populate_cluster_cache("BAAI/bge-m3", config) is False
+ mock_get.assert_not_called()
+
+ def test_model_not_in_local_cache(self, tmp_path: Path) -> None:
+ """Returns False without touching storage when the model is not cached."""
+ config = CacheConfig(local_cache=tmp_path, cluster_cache="s3://bucket/cache")
+
+ with patch("sie_sdk.cache.get_storage_backend") as mock_get:
+ assert populate_cluster_cache("BAAI/bge-m3", config) is False
+ mock_get.assert_not_called()
+
+ def test_uploads_model_directory(self, tmp_path: Path) -> None:
+ """Happy path: uploads the model dir to the mirrored cluster path."""
+ model_dir = self._cached_model(tmp_path)
+ config = CacheConfig(local_cache=tmp_path, cluster_cache="s3://bucket/cache")
+
+ with patch("sie_sdk.cache.get_storage_backend") as mock_get:
+ mock_backend = MagicMock()
+ mock_backend.upload_directory.return_value = 2
+ mock_get.return_value = mock_backend
+
+ assert populate_cluster_cache("BAAI/bge-m3", config) is True
+
+ mock_get.assert_called_once_with("s3://bucket/cache")
+ mock_backend.upload_directory.assert_called_once_with(
+ model_dir,
+ "s3://bucket/cache/models--BAAI--bge-m3",
+ )
+
+ def test_zero_files_uploaded_returns_false(self, tmp_path: Path) -> None:
+ """Backend reporting zero uploaded files is surfaced as failure."""
+ self._cached_model(tmp_path)
+ config = CacheConfig(local_cache=tmp_path, cluster_cache="s3://bucket/cache")
+
+ with patch("sie_sdk.cache.get_storage_backend") as mock_get:
+ mock_backend = MagicMock()
+ mock_backend.upload_directory.return_value = 0
+ mock_get.return_value = mock_backend
+
+ assert populate_cluster_cache("BAAI/bge-m3", config) is False
+
+ def test_reads_config_from_environment(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """config=None resolves via get_cache_config() (env variables)."""
+ self._cached_model(tmp_path)
+ monkeypatch.setenv("SIE_LOCAL_CACHE", str(tmp_path))
+ monkeypatch.setenv("SIE_CLUSTER_CACHE", "s3://env-bucket/cache")
+
+ with patch("sie_sdk.cache.get_storage_backend") as mock_get:
+ mock_backend = MagicMock()
+ mock_backend.upload_directory.return_value = 1
+ mock_get.return_value = mock_backend
+
+ assert populate_cluster_cache("BAAI/bge-m3") is True
+ mock_get.assert_called_once_with("s3://env-bucket/cache")
+
+ def test_roundtrip_with_local_backend(self, tmp_path: Path) -> None:
+ """Uploading via the real LocalBackend mirrors the HF cache layout."""
+ local_cache = tmp_path / "local"
+ local_cache.mkdir()
+ self._cached_model(local_cache)
+ cluster = tmp_path / "cluster"
+ cluster.mkdir()
+
+ config = CacheConfig(local_cache=local_cache, cluster_cache=str(cluster))
+
+ assert populate_cluster_cache("BAAI/bge-m3", config) is True
+ uploaded = cluster / "models--BAAI--bge-m3" / "snapshots" / "abc123"
+ assert (uploaded / "model.safetensors").read_text() == "weights"
+ assert (uploaded / "config.json").read_text() == "{}"
+
+
class TestGatedModelErrorHandling:
"""Tests for gated model error handling in HuggingFace downloads."""
diff --git a/packages/sie_sdk/tests/test_jobs_body.py b/packages/sie_sdk/tests/test_jobs_body.py
new file mode 100644
index 000000000..511ce7f95
--- /dev/null
+++ b/packages/sie_sdk/tests/test_jobs_body.py
@@ -0,0 +1,306 @@
+"""Pure jobs helpers: build_job_body slot mapping + result decoding (no transport)."""
+
+from __future__ import annotations
+
+import msgpack
+import numpy as np
+import pytest
+from sie_sdk import build_job_body, connection_name
+from sie_sdk.jobs import decode_chunk_bytes, decode_result_item, job_chunks
+
+
+def test_inline_list_source_becomes_items() -> None:
+ body = build_job_body(source=["a", "b"], operation="encode", model="BAAI/bge-m3")
+ assert body == {"operation": "encode", "model": "BAAI/bge-m3", "items": [{"text": "a"}, {"text": "b"}]}
+
+
+def test_bare_string_source_is_one_text_item() -> None:
+ body = build_job_body(source="embed me", operation="encode", model="m")
+ assert body["items"] == [{"text": "embed me"}]
+ assert "src" not in body
+
+
+def test_connector_uri_source_derives_connection() -> None:
+ body = build_job_body(
+ source="postgres://warehouse?query=SELECT+1",
+ operation="encode",
+ model="m",
+ sink="postgres://warehouse?table=vecs",
+ )
+ assert body["src"] == "postgres://warehouse?query=SELECT+1"
+ assert body["connection"] == "warehouse"
+ assert body["sink"] == "postgres://warehouse?table=vecs"
+ # Same-store sink reuses the source connection — no redundant sink_connection.
+ assert "sink_connection" not in body
+
+
+def test_distinct_sink_threads_sink_connection() -> None:
+ body = build_job_body(
+ source="postgres://wh?query=x",
+ operation="encode",
+ model="m",
+ sink="s3://out-bucket/vecs",
+ )
+ assert body["sink_connection"] == "out-bucket"
+
+
+def test_explicit_connection_overrides_derived() -> None:
+ body = build_job_body(
+ source="postgres://wh?query=x",
+ operation="encode",
+ model="m",
+ sink="postgres://wh?table=t",
+ connection="prod-wh",
+ sink_connection="prod-wh",
+ )
+ assert body["connection"] == "prod-wh"
+ assert body["sink_connection"] == "prod-wh"
+
+
+def test_inplace_sink_sentinel() -> None:
+ body = build_job_body(source="postgres://wh?query=x", operation="encode", model="m", sink="inplace")
+ assert body["sink"] == "inplace"
+
+
+def test_return_sink_is_omitted() -> None:
+ assert "sink" not in build_job_body(source=["a"], operation="encode", model="m", sink="return")
+ assert "sink" not in build_job_body(source=["a"], operation="encode", model="m", sink=None)
+
+
+ ("when", "expected"),
+ [
+ ("now", {}),
+ (None, {}),
+ ("schedule:*/5 * * * *", {"when": "schedule", "schedule": "*/5 * * * *"}),
+ ("*/5 * * * *", {"when": "schedule", "schedule": "*/5 * * * *"}),
+ ("watch:s3://in", {"when": "watch", "watch": "s3://in"}),
+ ],
+)
+def test_when_trigger_mapping(when: str | None, expected: dict[str, str]) -> None:
+ body = build_job_body(source=["a"], operation="encode", model="m", when=when)
+ for key, value in expected.items():
+ assert body[key] == value
+ if not expected:
+ assert "when" not in body
+
+
+def test_output_types_ride_only_when_set() -> None:
+ assert build_job_body(source=["a"], operation="encode", model="m", output_types=["dense"])["output_types"] == [
+ "dense"
+ ]
+ assert "output_types" not in build_job_body(source=["a"], operation="encode", model="m")
+
+
+def test_options_forward_op_inputs_as_is() -> None:
+ """Op inputs ride `options` (JOBS.md matrix): score query, extract labels/schema, generate sampling."""
+ # score (connector form): options.query rides the wire untouched.
+ score = build_job_body(
+ source="postgres://wh?query=x",
+ operation="score",
+ model="BAAI/bge-m3",
+ sink="postgres://wh?table=scores",
+ options={"query": "rank these documents"},
+ )
+ assert score["options"] == {"query": "rank these documents"}
+
+ # extract (inline form): labels + output_schema forwarded as-is.
+ extract = build_job_body(
+ source=["some text"],
+ operation="extract",
+ model="urchade/gliner_small-v2.1",
+ options={"labels": ["PERSON", "ORG"], "output_schema": {"type": "object"}},
+ )
+ assert extract["options"] == {"labels": ["PERSON", "ORG"], "output_schema": {"type": "object"}}
+
+ # generate sampling forwarded as-is.
+ generate = build_job_body(
+ source="postgres://wh?query=x",
+ operation="generate",
+ model="Qwen/Qwen3-4B-Instruct-2507",
+ sink="postgres://wh?table=docs&mode=inplace&column=summary",
+ options={"max_new_tokens": 64, "temperature": 0.0},
+ )
+ assert generate["options"] == {"max_new_tokens": 64, "temperature": 0.0}
+
+
+def test_options_stay_off_the_wire_when_unset_or_empty() -> None:
+ # Absent or empty options never ride (the shipped body stays byte-identical).
+ assert "options" not in build_job_body(source=["a"], operation="encode", model="m")
+ assert "options" not in build_job_body(source=["a"], operation="encode", model="m", options={})
+
+
+def test_non_mapping_options_raises() -> None:
+ with pytest.raises(ValueError, match="options must be a mapping"):
+ build_job_body(source=["a"], operation="score", model="m", options=["query"]) # ty: ignore[invalid-argument-type]
+
+
+def test_empty_inline_source_raises() -> None:
+ with pytest.raises(ValueError, match="no items"):
+ build_job_body(source=[], operation="encode", model="m")
+
+
+# ---- §4.5.4 field_map / output_field ----------------------------------------
+
+
+def test_field_map_and_output_field_ride_connector_jobs() -> None:
+ # The §4.5.4 before/after example, byte-shaped for the wire.
+ body = build_job_body(
+ source="postgres://wh?query=select id, body, source_url from docs",
+ operation="encode",
+ model="BAAI/bge-m3",
+ field_map={"id_field": "id", "input_field": "body", "carry": ["source_url"], "input_type": "text"},
+ sink="postgres://wh?table=doc_vectors",
+ output_field="embedding",
+ )
+ assert body["field_map"] == {
+ "id_field": "id",
+ "input_field": "body",
+ "carry": ["source_url"],
+ "input_type": "text",
+ }
+ assert body["output_field"] == "embedding"
+
+
+def test_field_map_omitted_keys_do_not_ride() -> None:
+ body = build_job_body(
+ source="postgres://wh?query=x",
+ operation="encode",
+ model="m",
+ sink="postgres://wh?table=t",
+ field_map={"id_field": "id"},
+ )
+ assert body["field_map"] == {"id_field": "id"}
+ assert "output_field" not in body
+ # An all-empty field_map rides nothing (additive-only wire).
+ body = build_job_body(
+ source="postgres://wh?query=x", operation="encode", model="m", sink="postgres://wh?table=t", field_map={}
+ )
+ assert "field_map" not in body
+
+
+ ("field_map", "match"),
+ [
+ ({"id_column": "id"}, "unknown field_map key"), # alias params are URI-side, not field_map keys
+ ({"carry": "source_url"}, "carry"), # a bare string is not a list of fields
+ ({"input_type": "rows"}, "input_type"),
+ ],
+)
+def test_bad_field_map_raises(field_map: dict, match: str) -> None:
+ with pytest.raises(ValueError, match=match):
+ build_job_body(
+ source="postgres://wh?query=x",
+ operation="encode",
+ model="m",
+ sink="postgres://wh?table=t",
+ field_map=field_map,
+ )
+
+
+def test_field_map_on_inline_items_raises() -> None:
+ with pytest.raises(ValueError, match="connector-src"):
+ build_job_body(source=["a"], operation="encode", model="m", field_map={"id_field": "id"})
+ with pytest.raises(ValueError, match="connector-src"):
+ build_job_body(source=["a"], operation="encode", model="m", output_field="embedding")
+
+
+# ---- §4.5.4 upload:// (internal scheme — no connection derived) ----------------
+
+
+def test_upload_source_derives_no_connection() -> None:
+ body = build_job_body(
+ source="upload://file-abc?format=csv",
+ operation="encode",
+ model="m",
+ sink="upload://file-out",
+ field_map={"id_field": "doc_id", "input_field": "text", "input_type": "text"},
+ )
+ assert body["src"] == "upload://file-abc?format=csv"
+ assert body["sink"] == "upload://file-out"
+ assert "connection" not in body
+ assert "sink_connection" not in body
+
+
+def test_upload_source_to_external_sink_threads_sink_connection() -> None:
+ body = build_job_body(
+ source="upload://file-abc",
+ operation="encode",
+ model="m",
+ sink="postgres://wh?table=doc_vectors",
+ sink_connection="wh",
+ )
+ assert "connection" not in body
+ assert body["sink_connection"] == "wh"
+
+
+def test_bad_sink_raises() -> None:
+ with pytest.raises(ValueError, match="sink must be"):
+ build_job_body(source=["a"], operation="encode", model="m", sink="garbage")
+
+
+ ("uri", "expected"),
+ [
+ ("postgres://warehouse?query=x", "warehouse"),
+ ("s3://customer-bucket/in/", "customer-bucket"),
+ ("gs://my-bucket", "my-bucket"),
+ ],
+)
+def test_connection_name(uri: str, expected: str) -> None:
+ assert connection_name(uri) == expected
+
+
+def _chunk_bytes(n: int, dims: int) -> bytes:
+ items = [
+ {
+ "success": True,
+ "id": str(i),
+ "units": {"input_tokens": 5},
+ "result_msgpack": msgpack.packb(
+ {"dense": {"dims": dims, "values": [0.1 * j for j in range(dims)]}}, use_bin_type=True
+ ),
+ }
+ for i in range(n)
+ ]
+ return msgpack.packb(items, use_bin_type=True)
+
+
+def test_decode_result_item_yields_numpy_dense() -> None:
+ raw = _chunk_bytes(n=1, dims=4)
+ (item,) = msgpack.unpackb(raw, raw=False)
+ decoded = decode_result_item(item)
+ assert decoded["id"] == "0"
+ assert decoded["success"] is True
+ assert decoded["dims"] == 4
+ assert isinstance(decoded["dense"], np.ndarray)
+ assert decoded["dense"].shape == (4,)
+
+
+def test_decode_chunk_bytes_all_items() -> None:
+ decoded = decode_chunk_bytes(_chunk_bytes(n=3, dims=8))
+ assert len(decoded) == 3
+ assert all(d["dims"] == 8 for d in decoded)
+
+
+def test_job_chunks_extracts_ref_metadata() -> None:
+ job = {
+ "output": {
+ "kind": "refs",
+ "chunks": [
+ {"seq": 0, "items": 3, "state": "succeeded", "ref": "payload-store/c0", "units": 15, "credits": 15}
+ ],
+ }
+ }
+ chunks = job_chunks(job)
+ assert chunks == [
+ {
+ "seq": 0,
+ "items": 3,
+ "state": "succeeded",
+ "ref": "payload-store/c0",
+ "units": 15,
+ "credits": 15,
+ "error": None,
+ }
+ ]
diff --git a/packages/sie_sdk/tests/test_wire_contract.py b/packages/sie_sdk/tests/test_wire_contract.py
new file mode 100644
index 000000000..2c71172e1
--- /dev/null
+++ b/packages/sie_sdk/tests/test_wire_contract.py
@@ -0,0 +1,25 @@
+"""The Python SDK's wire enums must match the shared golden fixtures.
+
+Round-trips ``packages/wire-fixtures/model_state.json`` against the SDK's typed
+``ModelState`` so drift (for example a state added on one side only) fails in CI
+rather than shipping. See ``packages/wire-fixtures/README.md``.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import get_args
+
+from sie_sdk.types import ModelState
+
+_FIXTURES = Path(__file__).parents[2] / "wire-fixtures"
+
+
+def _load(name: str) -> dict:
+ return json.loads((_FIXTURES / name).read_text())
+
+
+def test_model_state_matches_golden_fixture() -> None:
+ fixture = _load("model_state.json")
+ assert set(get_args(ModelState)) == set(fixture["model_states"])
diff --git a/packages/sie_server/bundles/default.yaml b/packages/sie_server/bundles/default.yaml
index 8e0baa7f6..c59f2c199 100644
--- a/packages/sie_server/bundles/default.yaml
+++ b/packages/sie_server/bundles/default.yaml
@@ -13,6 +13,7 @@ adapters:
- sie_server.adapters.colpali
- sie_server.adapters.colqwen2
- sie_server.adapters.colqwen3
+- sie_server.adapters.colsmol
- sie_server.adapters.grounding_dino
- sie_server.adapters.gte_sparse_flash
- sie_server.adapters.jina_flash_cross_encoder
diff --git a/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-1.5B-instruct.yaml b/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-1.5B-instruct.yaml
index a09763498..5972a954c 100644
--- a/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-1.5B-instruct.yaml
+++ b/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-1.5B-instruct.yaml
@@ -17,7 +17,13 @@ max_sequence_length: 32768
profiles:
default:
max_batch_tokens: 16384
- compute_precision: bfloat16
+ # The sentence_transformer adapter ignores compute_precision: the model
+ # loads in its stored checkpoint dtype, which is float32 here (fp32
+ # safetensors, config.json torch_dtype float32). The committed floors are
+ # therefore fp32 self-measures — no higher-precision serving mode exists
+ # to close the ~3.6% CosQA/CQADupstackPhysics gap vs the official
+ # leaderboard numbers (#1625).
+ compute_precision: null
# gte-Qwen2 is a decoder converted to BIDIRECTIONAL attention (config
# is_causal=false) with last-token pooling, served via its custom
# trust_remote_code modeling. The qwen2_flash adapter reimplements the
diff --git a/packages/sie_server/models/Alibaba-NLP__gte-multilingual-base.yaml b/packages/sie_server/models/Alibaba-NLP__gte-multilingual-base.yaml
index 51dfff846..9796c05f0 100644
--- a/packages/sie_server/models/Alibaba-NLP__gte-multilingual-base.yaml
+++ b/packages/sie_server/models/Alibaba-NLP__gte-multilingual-base.yaml
@@ -24,3 +24,11 @@ profiles:
runtime:
pooling: cls
normalize: true
+ candle:
+ extends: default
+ compute_precision: float16
+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter
+ adapter_options:
+ runtime:
+ pooling: cls
+ normalize: true
diff --git a/packages/sie_server/models/BAAI__bge-m3.yaml b/packages/sie_server/models/BAAI__bge-m3.yaml
index a176e4f26..7e21cc279 100644
--- a/packages/sie_server/models/BAAI__bge-m3.yaml
+++ b/packages/sie_server/models/BAAI__bge-m3.yaml
@@ -1,5 +1,6 @@
sie_id: BAAI/bge-m3
hf_id: BAAI/bge-m3
+hf_revision: 5617a9f61b028005a4858fdac845db406aefb181
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/BAAI__bge-reranker-base.yaml b/packages/sie_server/models/BAAI__bge-reranker-base.yaml
index e3842f2ff..da6abd95b 100644
--- a/packages/sie_server/models/BAAI__bge-reranker-base.yaml
+++ b/packages/sie_server/models/BAAI__bge-reranker-base.yaml
@@ -1,5 +1,6 @@
sie_id: BAAI/bge-reranker-base
hf_id: BAAI/bge-reranker-base
+hf_revision: 2cfc18c9415c912f9d8155881c133215df768a70
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/BAAI__bge-reranker-v2-m3.yaml b/packages/sie_server/models/BAAI__bge-reranker-v2-m3.yaml
index 7dfd7e7f7..997b54057 100644
--- a/packages/sie_server/models/BAAI__bge-reranker-v2-m3.yaml
+++ b/packages/sie_server/models/BAAI__bge-reranker-v2-m3.yaml
@@ -1,5 +1,6 @@
sie_id: BAAI/bge-reranker-v2-m3
hf_id: BAAI/bge-reranker-v2-m3
+hf_revision: 953dc6f6f85a1b2dbfca4c34a2796e7dde08d41e
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/BAAI__bge-small-en-v1.5.yaml b/packages/sie_server/models/BAAI__bge-small-en-v1.5.yaml
index 221b8ae10..13b3f237d 100644
--- a/packages/sie_server/models/BAAI__bge-small-en-v1.5.yaml
+++ b/packages/sie_server/models/BAAI__bge-small-en-v1.5.yaml
@@ -1,5 +1,6 @@
sie_id: BAAI/bge-small-en-v1.5
hf_id: BAAI/bge-small-en-v1.5
+hf_revision: 5c38ec7c405ec4b44b94cc5a9bb96e735b38267a
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/NeuML__gliner-bert-tiny.yaml b/packages/sie_server/models/NeuML__gliner-bert-tiny.yaml
index 2679e1e3d..501fc0e2f 100644
--- a/packages/sie_server/models/NeuML__gliner-bert-tiny.yaml
+++ b/packages/sie_server/models/NeuML__gliner-bert-tiny.yaml
@@ -1,5 +1,6 @@
sie_id: NeuML/gliner-bert-tiny
hf_id: NeuML/gliner-bert-tiny
+hf_revision: 6d9e1fce43af8cab4ab13ff3a6a9762ebfd1a1cf
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml b/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml
index eb39b309b..5e6d08341 100644
--- a/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml
@@ -1,5 +1,6 @@
sie_id: Qwen/Qwen3-0.6B
hf_id: Qwen/Qwen3-0.6B
+hf_revision: c1899de289a04d12100db370d81485cdf75e47ca
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml b/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml
index 72e865ab2..67c042523 100644
--- a/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml
@@ -1,5 +1,6 @@
sie_id: Qwen/Qwen3-4B-Instruct-2507
hf_id: Qwen/Qwen3-4B-Instruct-2507
+hf_revision: cdbee75f17c01a7cc42f958dc650907174af0554
inputs:
text: true
image: false
@@ -14,15 +15,18 @@ tasks:
context_length: 32768
max_output_tokens: 4096
capabilities:
- # Same constraint as Qwen3.5-4B / Qwen3.6-27B: this profile runs the
- # default ``grammar_backend: outlines``, and SGLang's outlines_backend
- # does NOT implement ebnf (it logs ``Skip unsupported key_type='ebnf'``
- # then fails the compile — confirmed on A100 smoke 2026-05-26). Only
- # advertise ``"ebnf"`` here once a profile pins an EBNF-capable backend
- # (``grammar_backend: xgrammar``) AND a via-SIE EBNF smoke passes; the
- # gateway gates requests on this exact list, so advertising ebnf without
- # an ebnf-capable backend admits requests the worker then fails to serve.
- # The ``test_advertised_ebnf_requires_capable_backend`` consistency test
+ # This model pins ``grammar_backend: xgrammar`` on every profile (see
+ # adapter_options.loadtime below). The switch off the default Outlines
+ # backend was forced by a request-time crash: Outlines' FSM engine
+ # (interegular) raises ``Unsupported`` on regex anchors (``^``/``$``) and
+ # that uncaught exception SIGQUITs SGLang's scheduler — a single
+ # user-supplied anchored regex (e.g. ``^[0-9]{5}$``) killed the whole
+ # lane (peer-closed-connection 500s for every later request). XGrammar
+ # tolerates anchors and serves ``json_schema`` + ``regex`` identically.
+ # ``"ebnf"`` is still NOT advertised: XGrammar can compile it, but the
+ # gateway gates on this exact list and the via-SIE EBNF smoke for this
+ # model has not been run — add ``"ebnf"`` only once it passes. The
+ # ``test_advertised_ebnf_requires_capable_backend`` consistency test
# guards this invariant. Adding a new ``grammar.kind`` variant requires
# both the gateway parser and this list to be updated.
grammar: ["json_schema", "regex"]
@@ -56,10 +60,14 @@ tasks:
# without blocking model load — add entries only for shapes you
# know are hot.
prewarm_grammars:
- # Bare pattern, NOT anchored: this model uses the default Outlines
- # grammar backend, and Outlines regexes are implicitly anchored —
- # its FSM engine (interegular) rejects ``^``/``$`` with
- # ``Unsupported``, which crashes SGLang's scheduler. Use ``(yes|no)``.
+ # NOTE: the worker only prewarms the Outlines backend (XGrammar compiles
+ # are cheap and done on demand), so under ``grammar_backend: xgrammar``
+ # (above) this block is an inert no-op — retained as valid config for the
+ # Outlines fallback. Kept de-anchored so it stays crash-safe if a profile
+ # is ever switched back to Outlines (interegular rejects ``^``/``$`` with
+ # ``Unsupported``, which SIGQUITs SGLang's scheduler); the
+ # ``test_outlines_models_have_no_anchored_prewarm_regex`` guard enforces
+ # this. Use ``(yes|no)``.
- name: yes_no
kind: regex
value: "(yes|no)"
@@ -97,6 +105,13 @@ profiles:
loadtime:
mem_fraction_static: 0.85
served_model_name: Qwen/Qwen3-4B-Instruct-2507
+ # XGrammar (not the adapter-default Outlines): Outlines' interegular
+ # FSM engine raises ``Unsupported`` on regex anchors (``^``/``$``) and
+ # SIGQUITs SGLang's scheduler, so a user-supplied anchored ``regex``
+ # response_format crashed the whole lane. XGrammar tolerates anchors
+ # and serves json_schema + regex identically (GPU-verified on L4,
+ # SGLang 0.5.10.post1). Same backend the Gemma-4 profiles pin.
+ grammar_backend: xgrammar
# speculative decoding (MTP/EAGLE/NGRAM) intentionally absent;
# week-1 validation decides whether to promote a side-cell. See §4.9.
runtime:
@@ -131,6 +146,9 @@ profiles:
loadtime:
mem_fraction_static: 0.85
served_model_name: Qwen/Qwen3-4B-Instruct-2507
+ # XGrammar, matching the default profile — Outlines crashes SGLang's
+ # scheduler on anchored regexes (``^``/``$``). See the default profile.
+ grammar_backend: xgrammar
runtime:
first_chunk_timeout_s: 30
inter_chunk_timeout_s: 10
@@ -156,6 +174,9 @@ profiles:
loadtime:
mem_fraction_static: 0.85
served_model_name: Qwen/Qwen3-4B-Instruct-2507
+ # XGrammar, matching the default profile — Outlines crashes SGLang's
+ # scheduler on anchored regexes (``^``/``$``). See the default profile.
+ grammar_backend: xgrammar
runtime:
first_chunk_timeout_s: 30
inter_chunk_timeout_s: 10
diff --git a/packages/sie_server/models/Qwen__Qwen3-Embedding-0.6B.yaml b/packages/sie_server/models/Qwen__Qwen3-Embedding-0.6B.yaml
index d980dfc01..cd73de833 100644
--- a/packages/sie_server/models/Qwen__Qwen3-Embedding-0.6B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3-Embedding-0.6B.yaml
@@ -1,5 +1,6 @@
sie_id: Qwen/Qwen3-Embedding-0.6B
hf_id: Qwen/Qwen3-Embedding-0.6B
+hf_revision: 97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/Qwen__Qwen3-Embedding-4B.yaml b/packages/sie_server/models/Qwen__Qwen3-Embedding-4B.yaml
index 38ac7497e..92ba0eda6 100644
--- a/packages/sie_server/models/Qwen__Qwen3-Embedding-4B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3-Embedding-4B.yaml
@@ -1,5 +1,6 @@
sie_id: Qwen/Qwen3-Embedding-4B
hf_id: Qwen/Qwen3-Embedding-4B
+hf_revision: 5cf2132abc99cad020ac570b19d031efec650f2b
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml b/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml
index aeddd4d67..4cac01640 100644
--- a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml
@@ -1,5 +1,6 @@
sie_id: Qwen/Qwen3.5-4B
hf_id: Qwen/Qwen3.5-4B
+hf_revision: 851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a
inputs:
# Qwen3.5-4B is a unified vision-language model (Gated DeltaNet + sparse MoE
# with an integrated vision encoder). The wire surface accepts text+image
diff --git a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml
index 5a58b7968..5e8b2e86b 100644
--- a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml
@@ -1,5 +1,6 @@
sie_id: Qwen/Qwen3.6-27B
hf_id: Qwen/Qwen3.6-27B
+hf_revision: 6a9e13bd6fc8f0983b9b99948120bc37f49c13e9
inputs:
# Qwen3.6-27B is a unified vision-language model (Gated DeltaNet + Gated
# Attention with an integrated vision encoder; same hybrid family as
@@ -261,6 +262,61 @@ profiles:
min_new_tokens: 10
stop_tokens:
- "<|im_end|>"
+ # Throughput profile (H100-80GB) — the flagship's batch story. The
+ # ``default`` NEXTN-spec shape is latency-optimized single-stream and
+ # throughput-FLAT (~44 tok/s aggregate c=1→32, effective batch ≈1 —
+ # MP.4 gen-smartest measurement): speculative verification + cuda-graphs
+ # off + ``--disable-overlap-schedule`` serialize decode. This profile
+ # mirrors what made Qwen3-4B-Instruct-2507 scale 36× (c=1→64) on its
+ # spec-off default: speculative OFF, cuda graphs ON (no
+ # ``--disable-cuda-graph``), overlap schedule ON (no
+ # ``--disable-overlap-schedule``), so SGLang's continuous batcher can
+ # actually run a deep decode batch.
+ #
+ # Launch-shape notes:
+ # * No ``--mamba-scheduler-strategy extra_buffer``: that flag (and the
+ # overlap disable) is the required NEXTN pair-flag set on the hybrid
+ # Gated-DeltaNet arch; with spec off the adapter guard doesn't demand
+ # it and the default mamba scheduler serves batch decode.
+ # * ``mem_fraction_static: 0.90``: no NEXTN draft weights/KV to host,
+ # but cuda-graph capture needs workspace outside the static pool —
+ # 0.90 leaves headroom on top of the ~54 GB BF16 weights.
+ # * ``--cuda-graph-max-bs 32``: pin graph coverage through the measured
+ # c=32 operating point so deep decode batches stay on graphs.
+ # * triton attention + outlines grammar kept for Qwen3.x family parity.
+ #
+ # UX story: ``Qwen/Qwen3.6-27B`` (default, latency / single-stream) ·
+ # ``:batch`` (this profile, throughput) · ``:thinking`` (reasoning).
+ # Standalone block (no ``extends``) — same rationale as ``rtx-pro-6000``.
+ batch:
+ max_batch_tokens: 32768
+ compute_precision: bfloat16
+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter
+ kv_budget_tokens: 32768
+ adapter_options:
+ loadtime:
+ mem_fraction_static: 0.90
+ served_model_name: Qwen/Qwen3.6-27B
+ attention_backend: triton
+ grammar_backend: outlines
+ reasoning_parser: qwen3
+ tool_call_parser: qwen3_coder
+ speculative:
+ enabled: false
+ extra_launch_args:
+ - "--cuda-graph-max-bs"
+ - "32"
+ runtime:
+ first_chunk_timeout_s: 90
+ inter_chunk_timeout_s: 15
+ overall_timeout_s: 600
+ default_sampling:
+ temperature: 0.7
+ top_p: 0.8
+ presence_penalty: 1.5
+ min_new_tokens: 10
+ stop_tokens:
+ - "<|im_end|>"
# No-speculative baseline — for SIE-vs-raw-SGLang ablation cells so
# spec-decoding's contribution can be measured independently. Keeps
# the same ``extra_launch_args`` as ``default`` / ``h100`` so a config
diff --git a/packages/sie_server/models/Snowflake__snowflake-arctic-embed-l-v2.0.yaml b/packages/sie_server/models/Snowflake__snowflake-arctic-embed-l-v2.0.yaml
index 82cab4c0e..0d3955dcb 100644
--- a/packages/sie_server/models/Snowflake__snowflake-arctic-embed-l-v2.0.yaml
+++ b/packages/sie_server/models/Snowflake__snowflake-arctic-embed-l-v2.0.yaml
@@ -1,5 +1,6 @@
sie_id: Snowflake/snowflake-arctic-embed-l-v2.0
hf_id: Snowflake/snowflake-arctic-embed-l-v2.0
+hf_revision: ac6544c8a46e00af67e330e85a9028c66b8cfd9a
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml b/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml
index 9b869f6fd..44496baaf 100644
--- a/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml
+++ b/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml
@@ -1,5 +1,6 @@
sie_id: answerdotai/answerai-colbert-small-v1
hf_id: answerdotai/answerai-colbert-small-v1
+hf_revision: c72aa89bc61afdd85373643f3a1a75b2aad6e0fe
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/cross-encoder__ms-marco-MiniLM-L-6-v2.yaml b/packages/sie_server/models/cross-encoder__ms-marco-MiniLM-L-6-v2.yaml
index 1b5bf4018..b9a5a053d 100644
--- a/packages/sie_server/models/cross-encoder__ms-marco-MiniLM-L-6-v2.yaml
+++ b/packages/sie_server/models/cross-encoder__ms-marco-MiniLM-L-6-v2.yaml
@@ -1,5 +1,6 @@
sie_id: cross-encoder/ms-marco-MiniLM-L-6-v2
hf_id: cross-encoder/ms-marco-MiniLM-L-6-v2
+hf_revision: c5ee24cb16019beea0893ab7796b1df96625c6b8
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/google__embeddinggemma-300m.yaml b/packages/sie_server/models/google__embeddinggemma-300m.yaml
index 633528933..113b7a13a 100644
--- a/packages/sie_server/models/google__embeddinggemma-300m.yaml
+++ b/packages/sie_server/models/google__embeddinggemma-300m.yaml
@@ -9,12 +9,12 @@
# which the registry classifies as ``DEPENDENCY``.
sie_id: google/embeddinggemma-300m
hf_id: google/embeddinggemma-300m
-# Track the default branch. Note: ``main`` is mutable on the Hub, so
-# this does NOT guarantee bit-for-bit reproducibility — it merely names
-# the branch we expect HuggingFace to resolve. For a true pin, replace
-# this with an immutable commit SHA after verifying the new revision
-# against ``test_google_embeddinggemma_300m_dense``.
-hf_revision: main
+# Pinned to an immutable commit SHA (design §6.6): a served id maps to
+# identical weights forever. ``main`` was mutable and did NOT guarantee
+# bit-for-bit reproducibility; resolved 2026-07-05 via the HF metadata API.
+# A weights change must be published as a NEW versioned id, not a re-pin
+# under this id (re-verify against ``test_google_embeddinggemma_300m_dense``).
+hf_revision: 57c266a740f537b4dc058e1b0cda161fd15afa75
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/google__siglip-so400m-patch14-384.yaml b/packages/sie_server/models/google__siglip-so400m-patch14-384.yaml
index 5598afd57..108dcb364 100644
--- a/packages/sie_server/models/google__siglip-so400m-patch14-384.yaml
+++ b/packages/sie_server/models/google__siglip-so400m-patch14-384.yaml
@@ -1,5 +1,6 @@
sie_id: google/siglip-so400m-patch14-384
hf_id: google/siglip-so400m-patch14-384
+hf_revision: 9fdffc58afc957d1a03a25b10dba0329ab15c2a3
inputs:
text: true
image: true
diff --git a/packages/sie_server/models/ibm-granite__granite-embedding-30m-sparse.yaml b/packages/sie_server/models/ibm-granite__granite-embedding-30m-sparse.yaml
index e0f87f17f..16fd5b993 100644
--- a/packages/sie_server/models/ibm-granite__granite-embedding-30m-sparse.yaml
+++ b/packages/sie_server/models/ibm-granite__granite-embedding-30m-sparse.yaml
@@ -1,5 +1,6 @@
sie_id: ibm-granite/granite-embedding-30m-sparse
hf_id: ibm-granite/granite-embedding-30m-sparse
+hf_revision: ad82b1fd09541c998c8d45045d601c51fdb8a9b7
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/intfloat__e5-base-v2.yaml b/packages/sie_server/models/intfloat__e5-base-v2.yaml
index 1ed3f208b..4ae54a1e4 100644
--- a/packages/sie_server/models/intfloat__e5-base-v2.yaml
+++ b/packages/sie_server/models/intfloat__e5-base-v2.yaml
@@ -1,5 +1,6 @@
sie_id: intfloat/e5-base-v2
hf_id: intfloat/e5-base-v2
+hf_revision: f52bf8ec8c7124536f0efb74aca902b2995e5bcd
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/laion__CLIP-ViT-B-32-laion2B-s34B-b79K.yaml b/packages/sie_server/models/laion__CLIP-ViT-B-32-laion2B-s34B-b79K.yaml
index 4054a39e8..c3f27a55d 100644
--- a/packages/sie_server/models/laion__CLIP-ViT-B-32-laion2B-s34B-b79K.yaml
+++ b/packages/sie_server/models/laion__CLIP-ViT-B-32-laion2B-s34B-b79K.yaml
@@ -1,5 +1,6 @@
sie_id: laion/CLIP-ViT-B-32-laion2B-s34B-b79K
hf_id: laion/CLIP-ViT-B-32-laion2B-s34B-b79K
+hf_revision: 1a25a446712ba5ee05982a381eed697ef9b435cf
inputs:
text: true
image: true
diff --git a/packages/sie_server/models/laion__CLIP-ViT-H-14-laion2B-s32B-b79K.yaml b/packages/sie_server/models/laion__CLIP-ViT-H-14-laion2B-s32B-b79K.yaml
index 88c4c366e..b23c34ea5 100644
--- a/packages/sie_server/models/laion__CLIP-ViT-H-14-laion2B-s32B-b79K.yaml
+++ b/packages/sie_server/models/laion__CLIP-ViT-H-14-laion2B-s32B-b79K.yaml
@@ -1,5 +1,6 @@
sie_id: laion/CLIP-ViT-H-14-laion2B-s32B-b79K
hf_id: laion/CLIP-ViT-H-14-laion2B-s32B-b79K
+hf_revision: 1c2b8495b28150b8a4922ee1c8edee224c284c0c
inputs:
text: true
image: true
diff --git a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml
index a2dd9339c..af19f61f6 100644
--- a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml
+++ b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml
@@ -1,5 +1,6 @@
sie_id: lightonai/GTE-ModernColBERT-v1
hf_id: lightonai/GTE-ModernColBERT-v1
+hf_revision: cbbe53366e564450558f5e639dd499171f127538
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/microsoft__Florence-2-base.yaml b/packages/sie_server/models/microsoft__Florence-2-base.yaml
index fa6bbf067..ff417f013 100644
--- a/packages/sie_server/models/microsoft__Florence-2-base.yaml
+++ b/packages/sie_server/models/microsoft__Florence-2-base.yaml
@@ -1,5 +1,6 @@
sie_id: microsoft/Florence-2-base
hf_id: microsoft/Florence-2-base
+hf_revision: 5ca5edf5bd017b9919c05d08aebef5e4c7ac3bac
inputs:
text: false
image: true
diff --git a/packages/sie_server/models/microsoft__Florence-2-large.yaml b/packages/sie_server/models/microsoft__Florence-2-large.yaml
index 0a987b2aa..8824a11aa 100644
--- a/packages/sie_server/models/microsoft__Florence-2-large.yaml
+++ b/packages/sie_server/models/microsoft__Florence-2-large.yaml
@@ -1,5 +1,6 @@
sie_id: microsoft/Florence-2-large
hf_id: microsoft/Florence-2-large
+hf_revision: 21a599d414c4d928c9032694c424fb94458e3594
inputs:
text: false
image: true
diff --git a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml
index 8d5e6612b..ba0ad5f36 100644
--- a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml
+++ b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml
@@ -1,5 +1,6 @@
sie_id: mixedbread-ai/mxbai-edge-colbert-v0-32m
hf_id: mixedbread-ai/mxbai-edge-colbert-v0-32m
+hf_revision: 963e23afa1478d8bcc12e5d7115adcfdbd22c3af
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/openai__clip-vit-base-patch32.yaml b/packages/sie_server/models/openai__clip-vit-base-patch32.yaml
index 904042059..04ffd2a2c 100644
--- a/packages/sie_server/models/openai__clip-vit-base-patch32.yaml
+++ b/packages/sie_server/models/openai__clip-vit-base-patch32.yaml
@@ -1,5 +1,6 @@
sie_id: openai/clip-vit-base-patch32
hf_id: openai/clip-vit-base-patch32
+hf_revision: 3d74acf9a28c67741b2f4f2ea7635f0aaf6f0268
inputs:
text: true
image: true
diff --git a/packages/sie_server/models/prithivida__Splade_PP_en_v2.yaml b/packages/sie_server/models/prithivida__Splade_PP_en_v2.yaml
index a11da1349..0e82a2e09 100644
--- a/packages/sie_server/models/prithivida__Splade_PP_en_v2.yaml
+++ b/packages/sie_server/models/prithivida__Splade_PP_en_v2.yaml
@@ -1,5 +1,6 @@
sie_id: prithivida/Splade_PP_en_v2
hf_id: prithivida/Splade_PP_en_v2
+hf_revision: f0d4aa214dcb60c274052a52c0497535e3aec64c
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/sugiv__stablebridge-pruner-highlighter.yaml b/packages/sie_server/models/sugiv__stablebridge-pruner-highlighter.yaml
index 48fcc79e0..b32c9cc40 100644
--- a/packages/sie_server/models/sugiv__stablebridge-pruner-highlighter.yaml
+++ b/packages/sie_server/models/sugiv__stablebridge-pruner-highlighter.yaml
@@ -1,5 +1,6 @@
sie_id: sugiv/stablebridge-pruner-highlighter
hf_id: BAAI/bge-reranker-v2-m3
+hf_revision: 953dc6f6f85a1b2dbfca4c34a2796e7dde08d41e
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/urchade__gliner_multi-v2.1.yaml b/packages/sie_server/models/urchade__gliner_multi-v2.1.yaml
index a7325b166..d36f1af2c 100644
--- a/packages/sie_server/models/urchade__gliner_multi-v2.1.yaml
+++ b/packages/sie_server/models/urchade__gliner_multi-v2.1.yaml
@@ -1,5 +1,6 @@
sie_id: urchade/gliner_multi-v2.1
hf_id: urchade/gliner_multi-v2.1
+hf_revision: 443d26d654e0324125a96bebd8e796c14ff2efe6
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/urchade__gliner_multi_pii-v1.yaml b/packages/sie_server/models/urchade__gliner_multi_pii-v1.yaml
index 70bdfc557..b4abaca2d 100644
--- a/packages/sie_server/models/urchade__gliner_multi_pii-v1.yaml
+++ b/packages/sie_server/models/urchade__gliner_multi_pii-v1.yaml
@@ -1,5 +1,6 @@
sie_id: urchade/gliner_multi_pii-v1
hf_id: urchade/gliner_multi_pii-v1
+hf_revision: 1fcf13e85f4eef5394e1fcd406cf2ca9ea82351d
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/urchade__gliner_small-v2.1.yaml b/packages/sie_server/models/urchade__gliner_small-v2.1.yaml
index 9000f85fe..cea000ade 100644
--- a/packages/sie_server/models/urchade__gliner_small-v2.1.yaml
+++ b/packages/sie_server/models/urchade__gliner_small-v2.1.yaml
@@ -1,5 +1,6 @@
sie_id: urchade/gliner_small-v2.1
hf_id: urchade/gliner_small-v2.1
+hf_revision: 4e091416cf7c3481db542c2a3d26156916f3a47f
inputs:
text: true
image: false
diff --git a/packages/sie_server/models/vidore__colSmol-256M.yaml b/packages/sie_server/models/vidore__colSmol-256M.yaml
new file mode 100644
index 000000000..ffdd44255
--- /dev/null
+++ b/packages/sie_server/models/vidore__colSmol-256M.yaml
@@ -0,0 +1,42 @@
+sie_id: vidore/colSmol-256M
+hf_id: vidore/colSmol-256M
+hf_revision: a59110fdf114638b8018e6c9a018907e12f14855
+inputs:
+ text: true
+ image: true
+ audio: false
+ video: false
+tasks:
+ encode:
+ dense: null
+ sparse: null
+ multivector:
+ dim: 128
+ score: null
+ extract: null
+max_sequence_length: 2048
+profiles:
+ default:
+ max_batch_tokens: 4096
+ compute_precision: bfloat16
+ adapter_path: sie_server.adapters.colsmol:ColSmolAdapter
+ adapter_options:
+ loadtime:
+ muvera_config:
+ num_repetitions: 40
+ num_simhash_projections: 6
+ projection_dim: null
+ final_projection_dim: 10240
+ token_dim: 128
+ runtime:
+ normalize: true
+ muvera:
+ extends: default
+ adapter_options:
+ runtime:
+ normalize: true
+ output_types:
+ - dense
+ output_similarity:
+ dense: dot
+ muvera: {}
diff --git a/packages/sie_server/models/zai-org__GLM-OCR.yaml b/packages/sie_server/models/zai-org__GLM-OCR.yaml
index fdad7822d..2a0bb40d0 100644
--- a/packages/sie_server/models/zai-org__GLM-OCR.yaml
+++ b/packages/sie_server/models/zai-org__GLM-OCR.yaml
@@ -1,5 +1,6 @@
sie_id: zai-org/GLM-OCR
hf_id: zai-org/GLM-OCR
+hf_revision: ca5d8b3e287e52589e37c28385d9655ee4372f9d
inputs:
text: false
image: true
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index 4936b49a2..3eb8f93c1 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -3,7 +3,7 @@
"info": {
"title": "SIE Server",
"description": "Search Inference Engine - GPU inference server for search workloads",
- "version": "0.6.16"
+ "version": "0.6.17"
},
"paths": {
"/": {
@@ -955,6 +955,17 @@
"title": "Profiles",
"default": {}
},
+ "revision": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Revision"
+ },
"capabilities": {
"anyOf": [
{
diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.toml
index 4c4caf923..f2fab7057 100644
--- a/packages/sie_server/pyproject.toml
+++ b/packages/sie_server/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-server"
-version = "0.6.16"
+version = "0.6.17"
description = "Search Inference Engine - GPU inference server for search workloads"
requires-python = ">=3.12,<3.13"
license = { text = "Apache-2.0" }
@@ -11,7 +11,7 @@ dependencies = [
"fastapi>=0.115,<1",
"uvicorn[standard]>=0.32,<1",
# Serialization
- "msgpack>=1.1,<2",
+ "msgpack>=1.2.1,<2",
"msgpack-numpy>=0.4,<1",
"orjson>=3.10,<4",
# ML / Inference
@@ -26,6 +26,9 @@ dependencies = [
"sentence-transformers>=5.0,<6",
"safetensors>=0.4,<1",
"FlagEmbedding>=1.3,<2",
+ # LoRA runtime (adapters/peft_lora_mixin: PeftModel wrap + hot-swap).
+ # Load-bearing for BYO-LoRA; previously only a transitive pin.
+ "peft>=0.19,<1",
"einops>=0.8,<1", # Tensor ops (required by NV-Embed-v2 trust_remote_code)
# GLiNER / GLiREL / GLiClass extraction adapters
"gliner>=0.2,<1",
diff --git a/packages/sie_server/src/sie_server/adapters/_base_adapter.py b/packages/sie_server/src/sie_server/adapters/_base_adapter.py
index b3f1b6e82..d5ed33ff9 100644
--- a/packages/sie_server/src/sie_server/adapters/_base_adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/_base_adapter.py
@@ -165,6 +165,144 @@ class BaseAdapter(ModelAdapter):
raise NotImplementedError(msg)
return grouped_score_pairs(self.score, queries, docs, instruction=instruction)
+ # -- Unit-meter token counting (§7.3) ------------------------------------
+
+ def _metering_tokenizer(self) -> Any | None:
+ """Return this adapter's in-process HF tokenizer for authoritative
+ token counting, or ``None`` when it has none (server-backed adapters
+ like SGLang, image/audio adapters).
+
+ Every in-tree text adapter stores its tokenizer as ``self._tokenizer``;
+ image-text adapters (CLIP/SigLIP) instead keep it inside their
+ ``self._processor`` (a ``CLIPProcessor`` / ``SiglipProcessor``), which
+ bundles the image processor and the text tokenizer. Falling back to
+ ``processor.tokenizer`` here lets those adapters surface real §7.3 text
+ counts through the shared hook — otherwise CLIP/SigLIP TEXT bills
+ nothing, since its internal tokenization bypasses the pipeline's
+ preprocessor counts. Adapters that keep the tokenizer elsewhere
+ override this hook rather than re-implementing the counting logic.
+ """
+ tokenizer = getattr(self, "_tokenizer", None)
+ if tokenizer is not None:
+ return tokenizer
+ processor = getattr(self, "_processor", None)
+ if processor is not None:
+ return getattr(processor, "tokenizer", None)
+ return None
+
+ def _metering_max_length(self) -> int | None:
+ """Resolve the truncation cap for token counting from the adapter's
+ configured max sequence length (``_max_seq_length`` / ``_max_length``).
+
+ ``None`` means "no cap" — count the full tokenizer length.
+ """
+ for attr in ("_max_seq_length", "_max_length"):
+ value = getattr(self, attr, None)
+ if isinstance(value, int) and not isinstance(value, bool) and value > 0:
+ return value
+ # Processor-tokenizer adapters (CLIP/SigLIP) declare no
+ # ``_max_seq_length``; cap at the tokenizer's own ``model_max_length``
+ # so a long text counts exactly where the forward pass truncates it
+ # (CLIP 77, SigLIP 64) rather than over-billing beyond the context
+ # window. Consulted ONLY when the adapter has no dedicated
+ # ``_tokenizer`` (it does have a ``_processor``), so every existing
+ # ``_tokenizer``-based emitter keeps its exact behaviour.
+ if getattr(self, "_tokenizer", None) is None and getattr(self, "_processor", None) is not None:
+ tokenizer = self._metering_tokenizer()
+ model_max = getattr(tokenizer, "model_max_length", None)
+ if isinstance(model_max, int) and not isinstance(model_max, bool) and 0 < model_max <= 100_000:
+ return model_max
+ return None
+
+ def count_input_tokens(self, items: list[Item]) -> list[int] | None:
+ """Real per-item input-token counts via this adapter's own tokenizer.
+
+ Tokenizes each item's text with the same subword vocabulary the forward
+ pass uses and returns the per-item ``len(input_ids)`` (special tokens
+ included) — the identical ground-truth basis the encode preprocessor
+ records for pipeline-tokenized adapters (§P3.5). Best-effort: returns
+ ``None`` (reserve fallback, never an estimate billed as a count) when
+ there is no in-process tokenizer, any item is non-text, or the tokenizer
+ raises. Never raises — metering must not fail inference.
+ """
+ tokenizer = self._metering_tokenizer()
+ if tokenizer is None:
+ return None
+ texts: list[str] = []
+ for item in items:
+ text = getattr(item, "text", None)
+ if not isinstance(text, str):
+ return None
+ texts.append(text)
+ if not texts:
+ return []
+ return self._token_counts_or_none(tokenizer, texts, expected_len=len(items))
+
+ def count_pair_input_tokens(
+ self,
+ query: Item,
+ docs: list[Item],
+ *,
+ instruction: str | None = None,
+ ) -> list[int] | None:
+ """Real per-pair input-token counts for reranker metering (§7.3).
+
+ Tokenizes each ``(query, doc)`` pair jointly (query and doc packed into
+ one sequence with the model's separators, mirroring the cross-encoder
+ forward pass), applying ``instruction`` to the query the same way the
+ adapter does. Best-effort with the same ``None`` contract as
+ :meth:`count_input_tokens`.
+ """
+ tokenizer = self._metering_tokenizer()
+ if tokenizer is None:
+ return None
+ query_text = getattr(query, "text", None)
+ if not isinstance(query_text, str):
+ return None
+ if instruction is not None:
+ query_text = f"{instruction} {query_text}"
+ doc_texts: list[str] = []
+ for doc in docs:
+ doc_text = getattr(doc, "text", None)
+ if not isinstance(doc_text, str):
+ return None
+ doc_texts.append(doc_text)
+ if not doc_texts:
+ return []
+ return self._token_counts_or_none(
+ tokenizer,
+ [query_text] * len(doc_texts),
+ doc_texts,
+ expected_len=len(docs),
+ )
+
+ def _token_counts_or_none(
+ self,
+ tokenizer: Any,
+ text_or_pairs: list[str],
+ text_pair: list[str] | None = None,
+ *,
+ expected_len: int,
+ ) -> list[int] | None:
+ """Run ``tokenizer`` over texts (or joint text/text_pair) and return the
+ per-entry ``len(input_ids)``; ``None`` on any quirk so a malformed count
+ is never mis-attributed.
+ """
+ max_length = self._metering_max_length()
+ try:
+ if text_pair is not None:
+ encoded = tokenizer(text_or_pairs, text_pair, truncation=max_length is not None, max_length=max_length)
+ else:
+ encoded = tokenizer(text_or_pairs, truncation=max_length is not None, max_length=max_length)
+ counts = [len(ids) for ids in encoded["input_ids"]]
+ except Exception: # noqa: BLE001 — metering must never fail inference
+ return None
+ if len(counts) != expected_len:
+ return None
+ if not all(isinstance(count, int) and not isinstance(count, bool) for count in counts):
+ return None
+ return counts
+
# -- Shared helpers ------------------------------------------------------
def _check_loaded(self) -> None:
diff --git a/packages/sie_server/src/sie_server/adapters/_pylate_dense.py b/packages/sie_server/src/sie_server/adapters/_pylate_dense.py
index 60f72f33c..8967cd12d 100644
--- a/packages/sie_server/src/sie_server/adapters/_pylate_dense.py
+++ b/packages/sie_server/src/sie_server/adapters/_pylate_dense.py
@@ -34,13 +34,13 @@ from safetensors.torch import load_file
logger = logging.getLogger(__name__)
-def _repo_file(model_name_or_path: str, rel: str) -> str | None:
+def _repo_file(model_name_or_path: str, rel: str, *, revision: str | None = None) -> str | None:
"""Resolve a repo-relative file locally or via the HF hub; None if absent."""
local = Path(model_name_or_path) / rel
if local.is_file():
return str(local)
try:
- return hf_hub_download(model_name_or_path, rel)
+ return hf_hub_download(model_name_or_path, rel, revision=revision)
except Exception: # noqa: BLE001 - missing file/offline -> caller decides severity
return None
@@ -52,6 +52,7 @@ def load_pylate_dense_chain(
token_dim: int,
device: str | torch.device | None,
dtype: torch.dtype,
+ revision: str | None = None,
) -> list[torch.Tensor] | None:
"""Load the trained pylate Dense chain for a checkpoint.
@@ -64,13 +65,18 @@ def load_pylate_dense_chain(
truncation, preserving the old single-head semantics).
device: Device to move the weights to.
dtype: Dtype to cast the weights to.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ downloading the checkpoint's Dense-chain artifacts (``modules.json``,
+ per-module config/weights) from the Hub. The head lives in the same
+ repo as the backbone, so callers pass their pinned model revision so
+ the whole snapshot is version-consistent.
Returns:
The chain weights in modules.json order, or None to signal the caller
to fall back to its existing behavior (backbone truncation / legacy
projection probes).
"""
- modules_path = _repo_file(model_name_or_path, "modules.json")
+ modules_path = _repo_file(model_name_or_path, "modules.json", revision=revision)
if modules_path is None:
# Normal for stanford-format ColBERT repos (no modules.json shipped).
logger.debug("No modules.json for %s; no pylate Dense chain to load", model_name_or_path)
@@ -122,7 +128,7 @@ def load_pylate_dense_chain(
weights: list[torch.Tensor] = []
for module in dense_modules:
rel_dir = str(module.get("path", ""))
- config_path = _repo_file(model_name_or_path, f"{rel_dir}/config.json")
+ config_path = _repo_file(model_name_or_path, f"{rel_dir}/config.json", revision=revision)
if config_path is None:
logger.warning("Missing %s/config.json for %s; using backbone truncation", rel_dir, model_name_or_path)
return None
@@ -162,7 +168,7 @@ def load_pylate_dense_chain(
)
return None
- weights_path = _repo_file(model_name_or_path, f"{rel_dir}/model.safetensors")
+ weights_path = _repo_file(model_name_or_path, f"{rel_dir}/model.safetensors", revision=revision)
if weights_path is None:
logger.warning(
"Missing %s/model.safetensors for %s; using backbone truncation. "
diff --git a/packages/sie_server/src/sie_server/adapters/base.py b/packages/sie_server/src/sie_server/adapters/base.py
index ddeff2f93..78d9851b1 100644
--- a/packages/sie_server/src/sie_server/adapters/base.py
+++ b/packages/sie_server/src/sie_server/adapters/base.py
@@ -353,6 +353,71 @@ class ModelAdapter(ABC):
msg = f"{self.__class__.__name__} does not support extract()"
raise NotImplementedError(msg)
+ def count_input_tokens(self, items: list[Item]) -> list[int] | None:
+ """Authoritative per-item input-token counts for the unit meter (§7.3).
+
+ Shared metering seam for adapters that own their tokenization (flash
+ packers, library wrappers) and therefore leave the encode preprocessor
+ blind: returning the real per-item ``len(input_ids)`` here lets the
+ encode/extract result path bill $/1M input tokens (§7.1) off the same
+ ground-truth basis the pipeline records for adapters that tokenize in
+ the preprocessor (§P3.5), with no per-adapter code.
+
+ Default: ``None`` — leaving ``ItemOutcome.units`` unset so the metering
+ edge falls back to its reserve estimate rather than billing an
+ approximation. Concrete adapters with an in-process tokenizer override
+ this (see :class:`BaseAdapter`); server-backed / image adapters keep the
+ ``None`` default.
+ """
+ _ = items
+ return None
+
+ def count_pair_input_tokens(
+ self,
+ query: Item,
+ docs: list[Item],
+ *,
+ instruction: str | None = None,
+ ) -> list[int] | None:
+ """Authoritative per-pair input-token counts for reranker metering (§7.3).
+
+ Reranker analogue of :meth:`count_input_tokens`: a cross-encoder
+ tokenizes each ``(query, doc)`` pair jointly, so the pair's billable
+ input is the length of that joint encoding — the same basis the in-tree
+ ``cross_encoder`` adapter surfaces on its ``ScoreOutput``. Lets rerankers
+ that own their tokenization (flash cross-encoders) surface real counts
+ without per-adapter code.
+
+ Default ``None`` (reserve fallback); overridden by :class:`BaseAdapter`.
+ """
+ _ = (query, docs, instruction)
+ return None
+
+ def count_input_images(self, items: list[Item]) -> list[int] | None:
+ """Authoritative per-item input-IMAGE counts for the unit meter (§7).
+
+ Vision analogue of :meth:`count_input_tokens` for the "$ per image"
+ price dimension (§7). Unlike tokens, an image count needs no model or
+ tokenizer — it is simply the number of image inputs the adapter
+ consumed for the item — so the default counts them straight off the
+ wire ``Item`` and EVERY vision adapter (CLIP/SigLIP encode, Florence-2
+ extract, …) inherits authoritative per-image metering with no
+ per-adapter code.
+
+ Returns per-item ``len(item.images)`` (``0`` for text-only items). The
+ encode/extract result seam treats an all-zero total as absent so a
+ pure-text request never emits a spurious ``images=0`` — the meter then
+ stays on its token/reserve basis. Best-effort: never raises, since
+ metering must not fail inference. Adapters that expand one input image
+ into several billable tiles/crops may override this to bill the real
+ count.
+ """
+ counts: list[int] = []
+ for item in items:
+ images = getattr(item, "images", None)
+ counts.append(len(images) if images else 0)
+ return counts
+
def get_preprocessor(self) -> Any | None:
"""Get the preprocessor for this adapter if available.
diff --git a/packages/sie_server/src/sie_server/adapters/bert_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/bert_flash/__init__.py
index 06601cb64..42b5c105a 100644
--- a/packages/sie_server/src/sie_server/adapters/bert_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/bert_flash/__init__.py
@@ -32,7 +32,6 @@ from sie_server.adapters._utils import (
resolve_embedding_options,
validate_output_types,
)
-from sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin
from sie_server.core.inference_output import EncodeOutput
from sie_server.types.inputs import Item
@@ -46,13 +45,23 @@ logger = logging.getLogger(__name__)
_ERR_CPU_NOT_SUPPORTED = "BertFlashAdapter requires CUDA. Use pytorch_embedding adapter for CPU."
-class BertFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
+class BertFlashAdapter(FlashBaseAdapter):
"""BERT adapter using Flash Attention 2 with variable-length sequences.
This adapter eliminates padding waste by packing sequences and using
flash_attn_varlen_func. Achieves higher throughput than SDPA-based adapters.
Works with any BERT-based model for dense embeddings.
+
+ No LoRA support (``supports_lora() == False``, the base default): this
+ adapter fuses ``query``/``key``/``value`` weights into ``_fused_qkv_weights``
+ at load time and runs attention via ``functional.linear`` on those cached
+ tensors, so a PEFT wrapper around ``self._model`` is never consulted for the
+ attention projections — an attention-targeting LoRA would be silently
+ dropped (served without the customer's adapter, no error). Do not re-add
+ ``PEFTLoRAMixin`` unless the forward re-reads the (possibly LoRA-wrapped)
+ submodules; per the LoRA capability audit, LoRA on this family goes through
+ the merge-at-staging path instead.
"""
fallback_adapter_path: ClassVar[str | None] = "sentence_transformer:SentenceTransformerDenseAdapter"
@@ -80,6 +89,7 @@ class BertFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
pooling: PoolingStrategy = "mean",
query_template: str | None = None,
doc_template: str | None = None,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -92,6 +102,8 @@ class BertFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
pooling: Pooling strategy - "cls" or "mean".
query_template: Optional template for queries, e.g. "query: {text}".
doc_template: Optional template for documents, e.g. "passage: {text}".
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
@@ -102,6 +114,7 @@ class BertFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._pooling = pooling
self._query_template = query_template
self._doc_template = doc_template
+ self._revision = revision
self._model: BertModel | None = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -136,13 +149,18 @@ class BertFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._pooling,
)
- self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path, **shared_kwargs)
# Load model with eager attention - we'll run our own flash attention
self._model = AutoModel.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation="eager", # We handle attention manually
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -273,12 +291,25 @@ class BertFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Transfer 16-bit to CPU first, then upcast to float32 — halves GPU→CPU bandwidth
dense_np = dense_vecs.cpu().float().numpy()
- return EncodeOutput(
+ output = EncodeOutput(
dense=dense_np,
batch_size=len(items),
is_query=is_query,
dense_dim=self._dense_dim,
)
+ # Unit-meter seam (§7.3): this adapter owns tokenization (the registry
+ # preprocessor for flash adapters is a char-count ESTIMATOR) AND applies
+ # the model's query/doc template before tokenizing, so the real per-item
+ # token counts — post-template, post-truncation — exist only here.
+ # ``seq_lengths`` is the exact ``len(input_ids)`` the model processed for
+ # each item; expose it through ``EncodeOutput.extra`` (the designated
+ # adapter-extension point) aligned 1:1 with ``items``. The encode
+ # pipeline forwards these to the result path for metering, in preference
+ # to the base ``count_input_tokens`` fallback which re-tokenizes raw
+ # ``item.text`` and would undercount by the template's tokens. Mirrors
+ # ``bge_m3_flash``.
+ output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
+ return output
def _build_position_ids(self, seq_lengths_tensor: torch.Tensor, total_tokens: int) -> torch.Tensor:
"""Build BERT-style position IDs for packed sequences (vectorized).
diff --git a/packages/sie_server/src/sie_server/adapters/bert_flash_cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/bert_flash_cross_encoder/__init__.py
index 84d6dfb63..9faa8f1ec 100644
--- a/packages/sie_server/src/sie_server/adapters/bert_flash_cross_encoder/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/bert_flash_cross_encoder/__init__.py
@@ -44,6 +44,7 @@ class BertFlashCrossEncoderAdapter(FlashBaseAdapter):
trust_remote_code: bool = False,
max_seq_length: int = 512,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -53,6 +54,8 @@ class BertFlashCrossEncoderAdapter(FlashBaseAdapter):
trust_remote_code: Whether to trust remote code.
max_seq_length: Maximum sequence length for query+document.
compute_precision: Compute precision (float16, bfloat16, float32).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored).
"""
_ = kwargs
@@ -60,6 +63,7 @@ class BertFlashCrossEncoderAdapter(FlashBaseAdapter):
self._trust_remote_code = trust_remote_code
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
+ self._revision = revision
# Loaded state
self._model: Any = None
@@ -102,10 +106,14 @@ class BertFlashCrossEncoderAdapter(FlashBaseAdapter):
self._dtype,
)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
# Load tokenizer
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# Load model with eager attention (we handle flash attention manually)
@@ -113,7 +121,7 @@ class BertFlashCrossEncoderAdapter(FlashBaseAdapter):
self._model_name_or_path,
torch_dtype=self._dtype,
attn_implementation="eager",
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py b/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py
index f7b3e3560..9e06a35e3 100644
--- a/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py
@@ -67,6 +67,7 @@ class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):
normalize: bool = True,
max_seq_length: int = 8192,
compute_precision: ComputePrecision | None = None,
+ revision: str | None = None,
**kwargs: Any, # Accept extra args from loader (e.g., pooling)
) -> None:
"""Initialize the adapter.
@@ -78,6 +79,8 @@ class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):
compute_precision: Compute precision. None (default) selects fp32 off-CUDA
(safe on MPS) and bfloat16 on CUDA; set explicitly to override (e.g.
float16 to opt a curated model into fp16 on MPS).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs # Unused, but accepted for loader compatibility
@@ -85,6 +88,7 @@ class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):
self._normalize = normalize
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
+ self._revision = revision
self._model: XLMRobertaModel | None = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -113,14 +117,19 @@ class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):
attn_impl,
)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
# Load tokenizer (fast Rust tokenizer)
- self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path, **shared_kwargs)
# Load base model with Flash Attention 2 if available
self._model = AutoModel.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation=attn_impl,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -166,7 +175,7 @@ class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):
# Resolve the actual directory: could be a local path or HF model ID
base_path = Path(model_path)
if not base_path.is_dir():
- base_path = Path(snapshot_download(model_path))
+ base_path = Path(snapshot_download(model_path, revision=self._revision))
# ColBERT linear: hidden_size -> hidden_size (1024 -> 1024)
colbert_path = base_path / "colbert_linear.pt"
@@ -246,7 +255,13 @@ class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):
normalize=normalize,
)
- return self._to_encode_output(results, output_types, len(items), is_query)
+ output = self._to_encode_output(results, output_types, len(items), is_query)
+ # Unit-meter seam (same rationale as bge_m3_flash): this adapter owns
+ # tokenization, so the real per-item token counts exist only here.
+ # ``padding=True`` pads input_ids, so per-item counts come from the
+ # attention mask (identical to the unpadded tokenizer length).
+ output.extra["input_token_counts"] = [int(n) for n in inputs["attention_mask"].sum(dim=1).tolist()]
+ return output
def _validate_output_types(self, output_types: list[str]) -> None:
"""Validate that output types are supported."""
diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3_flag/__init__.py b/packages/sie_server/src/sie_server/adapters/bge_m3_flag/__init__.py
index f1208e756..b0a5879ee 100644
--- a/packages/sie_server/src/sie_server/adapters/bge_m3_flag/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/bge_m3_flag/__init__.py
@@ -70,6 +70,7 @@ class BGEM3FlagAdapter(BGEM3ScoreMixin, BaseAdapter):
normalize: bool = True,
max_seq_length: int = 8192,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -79,6 +80,10 @@ class BGEM3FlagAdapter(BGEM3ScoreMixin, BaseAdapter):
normalize: Whether to L2-normalize dense embeddings.
max_seq_length: Maximum sequence length (default 8192).
compute_precision: Compute precision (float16, bfloat16, float32).
+ revision: Accepted for loader compatibility but NOT honored on this
+ path — FlagEmbedding's ``BGEM3FlagModel`` exposes no revision seam
+ (see the note in ``load()``). Use the ``bge_m3`` / ``bge_m3_flash``
+ adapters to actually pin a revision.
**kwargs: Additional arguments (ignored, for loader compatibility).
"""
_ = kwargs
@@ -86,6 +91,7 @@ class BGEM3FlagAdapter(BGEM3ScoreMixin, BaseAdapter):
self._normalize = normalize
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
+ self._revision = revision
self._model: BGEM3FlagModel | None = None
self._device: str | None = None
@@ -112,6 +118,10 @@ class BGEM3FlagAdapter(BGEM3ScoreMixin, BaseAdapter):
self._compute_precision,
)
+ # NOTE: FlagEmbedding's BGEM3FlagModel (pinned 1.4.0) exposes no ``revision``
+ # kwarg — its constructor forwards nothing to the internal
+ # ``from_pretrained`` load — so ``self._revision`` cannot be honored on this
+ # path. Use the ``bge_m3`` / ``bge_m3_flash`` adapters to pin a revision.
self._model = BGEM3FlagModel(
self._model_name_or_path,
use_fp16=use_fp16,
diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py
index a855e86d8..c046ab5ed 100644
--- a/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py
@@ -57,6 +57,7 @@ class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):
normalize: bool = True,
max_seq_length: int = 8192,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -66,6 +67,8 @@ class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):
normalize: Whether to L2-normalize dense embeddings.
max_seq_length: Maximum sequence length (default 8192).
compute_precision: Compute precision (float16 recommended for flash).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
@@ -73,6 +76,7 @@ class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):
self._normalize = normalize
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
+ self._revision = revision
self._model: XLMRobertaModel | None = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -105,13 +109,18 @@ class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):
dtype,
)
- self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path, **shared_kwargs)
# Load model with eager attention - we'll run our own flash attention
self._model = AutoModel.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation="eager", # We handle attention manually
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -129,7 +138,7 @@ class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):
# Resolve the actual directory: could be a local path or HF model ID
base_path = Path(model_path)
if not base_path.is_dir():
- base_path = Path(snapshot_download(model_path))
+ base_path = Path(snapshot_download(model_path, revision=self._revision))
colbert_path = base_path / "colbert_linear.pt"
if colbert_path.exists():
@@ -232,7 +241,15 @@ class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):
normalize=normalize,
)
- return self._to_inference_output(results, output_types, len(items), is_query)
+ output = self._to_inference_output(results, output_types, len(items), is_query)
+ # Unit-meter seam: this adapter owns tokenization (the registry-level
+ # preprocessor for flash adapters is a char-count ESTIMATOR), so the
+ # real per-item token counts exist only here. Expose them through
+ # ``EncodeOutput.extra`` — the designated adapter-extension point —
+ # aligned 1:1 with ``items``; the encode pipeline forwards them to
+ # the result path for metering (never estimates).
+ output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
+ return output
# score() and score_pairs() are provided by BGEM3ScoreMixin.
diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3_score_mixin.py b/packages/sie_server/src/sie_server/adapters/bge_m3_score_mixin.py
index 5b286179a..7e789941f 100644
--- a/packages/sie_server/src/sie_server/adapters/bge_m3_score_mixin.py
+++ b/packages/sie_server/src/sie_server/adapters/bge_m3_score_mixin.py
@@ -152,7 +152,32 @@ class BGEM3ScoreMixin:
[self._compute_pair_score(queries_out, i, docs_out, i, score_mode, weights) for i in range(len(queries))],
dtype=np.float32,
)
- return ScoreOutput(scores=scores)
+ return ScoreOutput(scores=scores, input_token_counts=self._pair_input_token_counts(queries_out, docs_out))
+
+ @staticmethod
+ def _pair_input_token_counts(queries_out: EncodeOutput, docs_out: EncodeOutput) -> list[int] | None:
+ """Real per-pair input-token counts for the unit meter (§7.3).
+
+ BGE-M3 scores are bi-encoder: each pair's input is the query encoded
+ plus the doc encoded, so the pair's real token count is the sum of the
+ two per-item encode counts. ``encode()`` already exposes those counts
+ via ``EncodeOutput.extra["input_token_counts"]`` (the same authoritative
+ seq lengths P3.5 records for /v1/encode). Returns ``None`` — leaving the
+ meter on its reserve estimate — unless BOTH encode outputs carry
+ well-formed, aligned counts, so a partial/estimated count can never
+ masquerade as an authoritative one.
+ """
+ q_counts = queries_out.extra.get("input_token_counts") if queries_out.extra else None
+ d_counts = docs_out.extra.get("input_token_counts") if docs_out.extra else None
+ if not (isinstance(q_counts, list) and isinstance(d_counts, list)):
+ return None
+ if len(q_counts) != len(d_counts):
+ return None
+ q_ints = [c for c in q_counts if isinstance(c, int) and not isinstance(c, bool)]
+ d_ints = [c for c in d_counts if isinstance(c, int) and not isinstance(c, bool)]
+ if len(q_ints) != len(q_counts) or len(d_ints) != len(d_counts):
+ return None
+ return [q + d for q, d in zip(q_ints, d_ints, strict=True)]
# ------------------------------------------------------------ option resolve
diff --git a/packages/sie_server/src/sie_server/adapters/clip/__init__.py b/packages/sie_server/src/sie_server/adapters/clip/__init__.py
index cc626f0e3..1ed31318d 100644
--- a/packages/sie_server/src/sie_server/adapters/clip/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/clip/__init__.py
@@ -21,10 +21,15 @@ from __future__ import annotations
import io
import logging
+import os
+import threading
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
import torch
+from PIL import Image
+from torch.nn import functional
from sie_server.adapters._base_adapter import BaseAdapter
from sie_server.adapters._spec import AdapterSpec
@@ -33,7 +38,6 @@ from sie_server.core.inference_output import EncodeOutput
from sie_server.types.inputs import media_bytes
if TYPE_CHECKING:
- from PIL import Image
from transformers import CLIPModel, CLIPProcessor
from sie_server.types.inputs import Item
@@ -43,6 +47,31 @@ logger = logging.getLogger(__name__)
# Error messages
_ERR_NO_INPUT = "CLIPAdapter requires either text or images input"
+# Cross-item preprocessing is CPU-bound (PIL decode + resize). Fan the flat
+# image set across a small bounded thread pool so decode/resize overlaps —
+# PIL and the HF image processor release the GIL on the heavy numpy/C work.
+_MAX_PREPROCESS_THREADS = 8
+
+
+def _feature_tensor(out: Any) -> torch.Tensor:
+ """Return the projected feature tensor from a ``get_*_features`` result.
+
+ transformers <= 4.57.x (the Modal lane pin) returns the projected
+ ``[B, dim]`` feature tensor directly; transformers 5.x wraps it in a
+ ``BaseModelOutputWithPooling`` whose ``pooler_output`` is that *same*
+ projected tensor (verified on 5.3.0: image/text ``pooler_output`` is
+ ``[B, 512]`` = ``projection_dim``, while ``last_hidden_state`` is the
+ un-projected hidden state). Unwrap so the adapter is robust across the pin
+ instead of raising ``AttributeError`` in ``functional.normalize``.
+ """
+ if isinstance(out, torch.Tensor):
+ return out
+ pooled = getattr(out, "pooler_output", None)
+ if isinstance(pooled, torch.Tensor):
+ return pooled
+ msg = f"unexpected get_*_features return type: {type(out).__name__}"
+ raise TypeError(msg)
+
class CLIPAdapter(BaseAdapter):
"""Adapter for CLIP image-text embedding models.
@@ -66,6 +95,7 @@ class CLIPAdapter(BaseAdapter):
compute_precision: ComputePrecision = "float16",
trust_remote_code: bool = False,
max_seq_length: int | None = None,
+ revision: str | None = None,
dense_dim: int | None = None,
) -> None:
"""Initialize the adapter.
@@ -76,6 +106,9 @@ class CLIPAdapter(BaseAdapter):
compute_precision: Compute precision for inference.
trust_remote_code: Whether to trust remote code (False for standard CLIP).
max_seq_length: Ignored - CLIP uses fixed token length from model config.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading the processor and model. If None, the default branch is
+ used. Forwarded to ``from_pretrained(..., revision=...)``.
dense_dim: Catalog-declared dense embedding dimension. If provided,
validated against the loaded model's projection dimension.
"""
@@ -83,12 +116,26 @@ class CLIPAdapter(BaseAdapter):
self._normalize = normalize
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._configured_dense_dim = dense_dim
self._model: CLIPModel | None = None
self._processor: CLIPProcessor | None = None
self._device: str | None = None
self._dense_dim: int | None = dense_dim
+ # HF fast tokenizers are NOT thread-safe: applying per-call
+ # padding/truncation flags reconfigures the underlying Rust tokenizer,
+ # which takes a mutable borrow. Concurrent text encodes (e.g. the
+ # managed lane's ``@modal.concurrent`` inputs dispatched to a thread
+ # pool) otherwise race with ``RuntimeError: Already borrowed``.
+ # Serialise the tokenizer call — microseconds vs the GPU forward.
+ self._tokenizer_lock = threading.Lock()
+ # Lazily-created bounded pool used to overlap per-image CPU
+ # preprocessing (decode + resize) within a batched encode call.
+ # Guards lazy pool creation against concurrent first callers (same
+ # hazard class as ``_tokenizer_lock``) so a race can't orphan a pool.
+ self._preprocess_pool_lock = threading.Lock()
+ self._preprocess_pool: ThreadPoolExecutor | None = None
def load(self, device: str) -> None:
"""Load the model onto the specified device.
@@ -110,17 +157,21 @@ class CLIPAdapter(BaseAdapter):
dtype,
)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
# Load processor (handles both text tokenization and image preprocessing)
self._processor = CLIPProcessor.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# Load model
self._model = CLIPModel.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -168,6 +219,12 @@ class CLIPAdapter(BaseAdapter):
embeddings. For items with both, returns image embeddings (common
for image-text retrieval where images are the documents).
+ Items are partitioned by modality and each modality is run as ONE
+ stacked GPU forward (image tower and text tower). Semantics are
+ preserved exactly per item: an item carrying more than one image is
+ mean-pooled to a single vector (after per-image L2-normalize when
+ ``normalize`` is set), and output order matches input order.
+
Args:
items: List of items to encode (with text and/or images).
output_types: Which outputs to return (only "dense" supported).
@@ -184,125 +241,174 @@ class CLIPAdapter(BaseAdapter):
self._validate_output_types(output_types)
- # Encode each item individually and stack into batch
import numpy as np
- embeddings_list = []
- for item in items:
- embedding = self._encode_single_item(item)
- embeddings_list.append(embedding)
+ # Partition items by modality (image takes precedence over text),
+ # preserving original positions so the stacked output stays in order.
+ image_indices: list[int] = []
+ text_indices: list[int] = []
+ for i, item in enumerate(items):
+ has_text = item.text is not None
+ images = item.images
+ has_images = images is not None and len(images) > 0
+ if not has_text and not has_images:
+ raise ValueError(_ERR_NO_INPUT)
+ if has_images:
+ image_indices.append(i)
+ else:
+ text_indices.append(i)
+
+ embeddings: list[Any] = [None] * len(items)
+
+ if image_indices:
+ image_vecs = self._encode_image_items([items[i] for i in image_indices])
+ for slot, i in enumerate(image_indices):
+ embeddings[i] = image_vecs[slot]
+
+ per_item_token_counts: list[int] | None = None
+ if text_indices:
+ text_vecs, text_counts = self._encode_texts([items[i].text for i in text_indices]) # ty: ignore[invalid-argument-type]
+ for slot, i in enumerate(text_indices):
+ embeddings[i] = text_vecs[slot]
+ # Scatter the per-text token counts back to their item positions
+ # (image items → 0 text tokens), aligned 1:1 with ``items``.
+ if isinstance(text_counts, list) and len(text_counts) == len(text_indices):
+ per_item_token_counts = [0] * len(items)
+ for slot, i in enumerate(text_indices):
+ per_item_token_counts[i] = text_counts[slot]
# Stack into batched array [batch, dim]
- dense_batch = np.stack(embeddings_list, axis=0)
+ dense_batch = np.stack(embeddings, axis=0)
- return EncodeOutput(
+ output = EncodeOutput(
dense=dense_batch,
batch_size=len(items),
is_query=is_query,
dense_dim=self._dense_dim,
)
-
- def _encode_single_item(self, item: Item) -> Any:
- """Encode a single item (text, image, or both).
-
- Returns:
- Numpy array of shape [dense_dim].
+ # Unit-meter seam (§7.3): stamp exact per-item TEXT-tower token counts.
+ # Image items took the image tower (metered per image via the
+ # ``count_input_images`` hook) and contribute 0 text tokens; only stamp
+ # when at least one text item was encoded so a pure-image batch stays on
+ # the image dimension. The encode pipeline forwards ``extra`` to the
+ # result path for metering (§P3.5), in preference to re-tokenizing raw
+ # text (which also misses the open_clip / mixed-batch cases).
+ if per_item_token_counts is not None:
+ output.extra["input_token_counts"] = per_item_token_counts
+ return output
+
+ def _get_preprocess_pool(self) -> ThreadPoolExecutor:
+ """Return the lazily-created bounded preprocessing thread pool."""
+ pool = self._preprocess_pool
+ if pool is None:
+ with self._preprocess_pool_lock:
+ pool = self._preprocess_pool
+ if pool is None:
+ workers = min(_MAX_PREPROCESS_THREADS, os.cpu_count() or 1)
+ pool = ThreadPoolExecutor(max_workers=max(1, workers), thread_name_prefix="clip-preproc")
+ self._preprocess_pool = pool
+ return pool
+
+ def _preprocess_one(self, img_input: Any) -> torch.Tensor:
+ """Decode + preprocess a single image input into a ``[C, H, W]`` tensor.
+
+ Stateless per call — the HF image processor and PIL release the GIL on
+ the heavy work, so this is safe to fan across the preprocessing pool.
"""
- has_text = item.text is not None
- images = item.images
- has_images = images is not None and len(images) > 0
-
- if not has_text and not has_images:
- raise ValueError(_ERR_NO_INPUT)
-
- # Determine what to encode
- if has_images:
- # Image encoding (or image+text where image takes precedence)
- pil_images = self._load_images(item)
- return self._encode_images(pil_images)
- # Text-only encoding (text is guaranteed non-None if no images)
- return self._encode_text(item.text) # type: ignore
+ assert self._processor is not None
- def _load_images(self, item: Item) -> list[Image.Image]:
- """Load images from item into PIL Images.
+ img_bytes = media_bytes(img_input, kind="image")
+ pil_img = Image.open(io.BytesIO(img_bytes))
+ # Convert to RGB if necessary (CLIP expects RGB)
+ if pil_img.mode != "RGB":
+ pil_img = pil_img.convert("RGB")
+ processed = self._processor(images=pil_img, return_tensors="pt")
+ return processed["pixel_values"][0]
- Args:
- item: Item with images field.
+ def _preprocess_image_batch(self, img_inputs: list[Any]) -> torch.Tensor:
+ """Preprocess a flat list of image inputs into a ``[N, C, H, W]`` tensor.
- Returns:
- List of PIL Images.
+ Per-image preprocessing is independent, so a single stacked tensor is
+ bit-identical to preprocessing each image on its own — it is only fanned
+ across threads to overlap the CPU-bound decode/resize.
"""
- from PIL import Image
-
- pil_images = []
- for img_input in item.images or []:
- # img_input is ImageInput TypedDict with data (bytes) and optional format
- img_bytes = media_bytes(img_input, kind="image")
- pil_img = Image.open(io.BytesIO(img_bytes))
- # Convert to RGB if necessary (CLIP expects RGB)
- if pil_img.mode != "RGB":
- pil_img = pil_img.convert("RGB")
- pil_images.append(pil_img)
-
- return pil_images
+ if len(img_inputs) == 1:
+ tensors = [self._preprocess_one(img_inputs[0])]
+ else:
+ pool = self._get_preprocess_pool()
+ tensors = list(pool.map(self._preprocess_one, img_inputs))
+ return torch.stack(tensors, dim=0)
- def _encode_images(self, images: list[Image.Image]) -> Any:
- """Encode images into embeddings.
+ def _encode_image_items(self, items: list[Item]) -> Any:
+ """Encode image items as one stacked forward, mean-pooling per item.
- Args:
- images: List of PIL Images.
-
- Returns:
- Numpy array of shape [dense_dim] (averaged if multiple images).
+ Returns a ``[len(items), dim]`` float32 array, one row per item.
"""
assert self._model is not None
- assert self._processor is not None
- from torch.nn import functional
+ # Flatten every image across the items, remembering per-item counts so
+ # the stacked features can be split back and mean-pooled per item.
+ counts = [len(item.images or []) for item in items]
+ flat_inputs = [img for item in items for img in (item.images or [])]
- # Process images
- inputs = self._processor(images=images, return_tensors="pt")
- inputs = {k: v.to(self._device) for k, v in inputs.items()}
+ pixel_values = self._preprocess_image_batch(flat_inputs).to(self._device)
with torch.inference_mode():
- image_features = self._model.get_image_features(**inputs)
-
- # L2 normalize if configured
+ image_features = _feature_tensor(self._model.get_image_features(pixel_values=pixel_values))
+ # L2 normalize per image, before any mean-pool (matches serial).
if self._normalize:
image_features = functional.normalize(image_features, p=2, dim=-1)
- # If multiple images, average the embeddings
- if len(images) > 1:
- image_features = image_features.mean(dim=0, keepdim=True)
+ # Split by per-item image counts; mean-pool multi-image items (the
+ # mean runs on-device in the model dtype, exactly as the serial path).
+ vecs = []
+ offset = 0
+ for count in counts:
+ group = image_features[offset : offset + count]
+ offset += count
+ vecs.append(group[0] if count == 1 else group.mean(dim=0))
- return image_features[0].float().cpu().numpy()
-
- def _encode_text(self, text: str) -> Any:
- """Encode text into embeddings.
+ return torch.stack(vecs, dim=0).float().cpu().numpy()
- Args:
- text: Text string to encode.
+ def _encode_texts(self, texts: list[str]) -> tuple[Any, list[int] | None]:
+ """Encode a list of texts as one stacked forward.
- Returns:
- Numpy array of shape [dense_dim].
+ Returns ``(embeddings, token_counts)``: a ``[len(texts), dim]`` float32
+ array (one row per text) and the exact per-text token counts the text
+ tower encoded (§7.3), or ``None`` when the tokenizer could not surface a
+ clean count.
"""
assert self._model is not None
assert self._processor is not None
- from torch.nn import functional
-
- # Process text
- inputs = self._processor(text=[text], return_tensors="pt", padding=True, truncation=True)
+ # Process text as one batch. The HF fast tokenizer is not thread-safe
+ # under the per-call padding/truncation reconfiguration, so serialise
+ # the single batched call (microseconds vs the GPU forward).
+ with self._tokenizer_lock:
+ inputs = self._processor(text=list(texts), return_tensors="pt", padding=True, truncation=True)
+ # Unit-meter seam (§7.3): the exact per-text token counts — post
+ # truncation at the model context window (CLIP 77), special tokens
+ # included — the tower actually encoded. Reuses the shared base
+ # counter over the processor's own tokenizer (padding adds no
+ # billable content, so a content-only recount equals the forward's
+ # real length). ``None`` on any quirk leaves the meter on its reserve.
+ token_counts = self._token_counts_or_none(
+ self._processor.tokenizer, # ty: ignore[unresolved-attribute]
+ list(texts),
+ expected_len=len(texts),
+ )
inputs = {k: v.to(self._device) for k, v in inputs.items()}
with torch.inference_mode():
- text_features = self._model.get_text_features(**inputs)
-
- # L2 normalize if configured
+ text_features = _feature_tensor(self._model.get_text_features(**inputs))
if self._normalize:
text_features = functional.normalize(text_features, p=2, dim=-1)
- return text_features[0].float().cpu().numpy()
+ return text_features.float().cpu().numpy(), token_counts
+
+ def _encode_text(self, text: str) -> Any:
+ """Encode a single text into a ``[dim]`` embedding (thin batch wrapper)."""
+ return self._encode_texts([text])[0][0]
def _validate_output_types(self, output_types: list[str]) -> None:
"""Validate that output types are supported."""
@@ -323,3 +429,11 @@ class CLIPAdapter(BaseAdapter):
from sie_server.core.preprocessor import ImagePreprocessor
return ImagePreprocessor(self._processor, self._model_name_or_path)
+
+ def unload(self) -> None:
+ """Shut down the preprocessing pool, then unload model weights."""
+ pool = self._preprocess_pool
+ self._preprocess_pool = None
+ if pool is not None:
+ pool.shutdown(wait=False)
+ super().unload()
diff --git a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert/__init__.py
index a1d50b6d7..b717cf5af 100644
--- a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colbert/__init__.py
@@ -98,6 +98,7 @@ class ColBERTAdapter(BaseAdapter):
query_expansion: bool = True,
doc_punctuation_skiplist: bool = True,
muvera_config: dict[str, Any] | None = None,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -127,10 +128,14 @@ class ColBERTAdapter(BaseAdapter):
not). Default: True.
muvera_config: MUVERA configuration dict with keys like num_repetitions,
num_simhash_projections, normalize. Used for FDE postprocessing.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading the tokenizer, config, model, and Dense-chain/projection
+ artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
self._model_name_or_path = str(model_name_or_path)
+ self._revision = revision
self._token_dim = token_dim
self._normalize = normalize
self._max_seq_length = max_seq_length
@@ -171,15 +176,20 @@ class ColBERTAdapter(BaseAdapter):
dtype = self._resolve_dtype()
logger.info(
- "Loading ColBERT model %s on device=%s with dtype=%s",
+ "Loading ColBERT model %s on device=%s with dtype=%s revision=%s",
self._model_name_or_path,
device,
dtype,
+ self._revision,
)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": True}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
- trust_remote_code=True,
+ **shared_kwargs,
)
# Register prefix tokens (e.g. [Q], [D]) as special tokens if they are
@@ -240,7 +250,7 @@ class ColBERTAdapter(BaseAdapter):
# Determine whether to use native attention or manual flash attention
config = AutoConfig.from_pretrained(
self._model_name_or_path,
- trust_remote_code=True,
+ **shared_kwargs,
)
self._native_mode = self._is_cuda and self._should_use_native_mode(config)
@@ -257,7 +267,7 @@ class ColBERTAdapter(BaseAdapter):
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation=attn_impl,
- trust_remote_code=True,
+ **shared_kwargs,
)
else:
# Load model with eager attention - we'll run our own flash attention
@@ -266,7 +276,7 @@ class ColBERTAdapter(BaseAdapter):
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation="eager",
- trust_remote_code=True,
+ **shared_kwargs,
)
# Resize token embeddings if we added new prefix tokens above.
@@ -291,6 +301,7 @@ class ColBERTAdapter(BaseAdapter):
token_dim=self._token_dim,
device=self._device,
dtype=dtype,
+ revision=self._revision,
)
# Check for linear projection layer (ColBERT-specific)
# Different ColBERT implementations use different names
@@ -401,7 +412,7 @@ class ColBERTAdapter(BaseAdapter):
# Try to get safetensors file
try:
- file_path = hf_hub_download(self._model_name_or_path, "model.safetensors")
+ file_path = hf_hub_download(self._model_name_or_path, "model.safetensors", revision=self._revision)
except (OSError, ValueError):
return None
diff --git a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py
index 1de2a045d..afbb494d5 100644
--- a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py
@@ -76,6 +76,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
query_prefix: str = "",
doc_prefix: str = "",
muvera_config: dict[str, Any] | None = None,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -92,10 +93,14 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
doc_prefix: Prefix to prepend to documents.
muvera_config: MUVERA configuration dict with keys like num_repetitions,
num_simhash_projections, normalize. Used for FDE postprocessing.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading the tokenizer, model, and Dense-chain artifacts.
+ Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored).
"""
_ = kwargs
self._model_name_or_path = str(model_name_or_path)
+ self._revision = revision
self._token_dim = token_dim
self._multivector_dim = token_dim
self._normalize = normalize
@@ -144,6 +149,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
torch_dtype=dtype,
attn_implementation="eager",
trust_remote_code=True,
+ revision=self._revision,
)
self._model.to(device)
self._model.eval()
@@ -154,6 +160,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
token_dim=self._token_dim,
device=self._device,
dtype=dtype,
+ revision=self._revision,
)
if self._dense_chain is None:
logger.warning(
@@ -185,6 +192,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
return AutoTokenizer.from_pretrained(
self._model_name_or_path,
trust_remote_code=True,
+ revision=self._revision,
)
except (ValueError, KeyError) as exc:
logger.warning(
@@ -193,7 +201,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._model_name_or_path,
exc,
)
- return PreTrainedTokenizerFast.from_pretrained(self._model_name_or_path)
+ return PreTrainedTokenizerFast.from_pretrained(self._model_name_or_path, revision=self._revision)
def _resolve_dtype(self) -> torch.dtype:
"""Resolve compute dtype (default: bfloat16)."""
diff --git a/packages/sie_server/src/sie_server/adapters/colbert_rotary_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert_rotary_flash/__init__.py
index 210dcff09..78d96f83c 100644
--- a/packages/sie_server/src/sie_server/adapters/colbert_rotary_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colbert_rotary_flash/__init__.py
@@ -61,6 +61,7 @@ class ColBERTRotaryFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
doc_prefix: str = "",
query_expansion: bool = True,
muvera_config: dict[str, Any] | None = None,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -80,6 +81,8 @@ class ColBERTRotaryFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
"virtual" query tokens. Default: True.
muvera_config: MUVERA configuration dict with keys like num_repetitions,
num_simhash_projections, normalize. Used for FDE postprocessing.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts.
**kwargs: Additional arguments (ignored).
"""
_ = kwargs
@@ -95,6 +98,7 @@ class ColBERTRotaryFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._doc_prefix = doc_prefix
self._query_expansion = query_expansion
self._muvera_config = muvera_config
+ self._revision = revision
self._model: Any = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -125,9 +129,14 @@ class ColBERTRotaryFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
dtype,
)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
trust_remote_code=True,
+ **shared_kwargs,
)
# Configure tokenizer for query expansion (pad queries with MASK tokens)
@@ -154,6 +163,7 @@ class ColBERTRotaryFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
torch_dtype=dtype,
attn_implementation="eager",
trust_remote_code=True,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
diff --git a/packages/sie_server/src/sie_server/adapters/colpali/__init__.py b/packages/sie_server/src/sie_server/adapters/colpali/__init__.py
index 150d4f8f4..358c9d171 100644
--- a/packages/sie_server/src/sie_server/adapters/colpali/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colpali/__init__.py
@@ -69,6 +69,7 @@ class ColPaliAdapter(BaseAdapter):
normalize: bool = True,
compute_precision: ComputePrecision = "float32",
trust_remote_code: bool = False,
+ revision: str | None = None,
max_seq_length: int | None = None,
muvera_config: dict[str, Any] | None = None,
token_dim: int | None = None,
@@ -82,6 +83,8 @@ class ColPaliAdapter(BaseAdapter):
Note: ColPali with eager attention may require float32 due to
attention mask dtype issues. flash_attention_2 allows fp16/bf16.
trust_remote_code: Whether to trust remote code.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
max_seq_length: Ignored - ColPali uses dynamic sequence length.
muvera_config: Optional MUVERA configuration for converting
multi-vector to dense representation. Reserved for future use.
@@ -91,6 +94,7 @@ class ColPaliAdapter(BaseAdapter):
self._normalize = normalize
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._muvera_config = muvera_config
self._token_dim = token_dim
@@ -121,10 +125,14 @@ class ColPaliAdapter(BaseAdapter):
attn_impl,
)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
# Load processor
self._processor = ColPaliProcessor.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# WORKAROUND: The ColPali model config on HuggingFace (vidore/colpali-v1.3-hf) has
@@ -136,7 +144,7 @@ class ColPaliAdapter(BaseAdapter):
# (text_config.torch_dtype should be "bfloat16", not "float32")
config = ColPaliConfig.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._fix_config_dtype(config, dtype)
@@ -148,6 +156,7 @@ class ColPaliAdapter(BaseAdapter):
device_map=device,
attn_implementation=attn_impl,
trust_remote_code=self._trust_remote_code,
+ revision=self._revision,
).eval()
# Get embedding dimension from model config
diff --git a/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py b/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py
index a9708e86a..9f9e0d780 100644
--- a/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py
@@ -150,6 +150,7 @@ class ColQwen2Adapter(BaseAdapter):
normalize: bool = True,
compute_precision: ComputePrecision = "bfloat16",
trust_remote_code: bool = False,
+ revision: str | None = None,
max_seq_length: int | None = None,
muvera_config: dict[str, Any] | None = None,
token_dim: int = 128,
@@ -161,6 +162,8 @@ class ColQwen2Adapter(BaseAdapter):
normalize: Not used — ColQwen2.5 normalizes internally.
compute_precision: Compute precision for inference.
trust_remote_code: Whether to trust remote code.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
max_seq_length: Ignored — ColQwen2.5 uses dynamic sequence length.
muvera_config: MUVERA config (passed to postprocessor).
token_dim: Token embedding dimension (fixed at 128).
@@ -169,6 +172,7 @@ class ColQwen2Adapter(BaseAdapter):
self._normalize = normalize
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._model: Any = None
self._processor: Any = None
@@ -196,11 +200,13 @@ class ColQwen2Adapter(BaseAdapter):
# Reduce max_pixels to limit visual token count for faster inference.
# Default 1280*28*28 produces 2000-4000 tokens through the 3B decoder;
# 768*28*28 caps at ~768 tokens for a ~2-3x speedup with modest quality impact.
- self._processor = Qwen2VLProcessor.from_pretrained(
- self._model_name_or_path,
- min_pixels=256 * 28 * 28,
- max_pixels=768 * 28 * 28,
- )
+ proc_kwargs: dict[str, Any] = {
+ "min_pixels": 256 * 28 * 28,
+ "max_pixels": 768 * 28 * 28,
+ }
+ if self._revision is not None:
+ proc_kwargs["revision"] = self._revision
+ self._processor = Qwen2VLProcessor.from_pretrained(self._model_name_or_path, **proc_kwargs)
tokenizer = self._processor.tokenizer # ty: ignore[unresolved-attribute]
tokenizer.padding_side = "left"
@@ -213,6 +219,8 @@ class ColQwen2Adapter(BaseAdapter):
}
if attn_impl is not None:
load_kwargs["attn_implementation"] = attn_impl
+ if self._revision is not None:
+ load_kwargs["revision"] = self._revision
self._model = ColQwen2_5.from_pretrained( # ty: ignore[unresolved-attribute]
self._model_name_or_path,
diff --git a/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py
index 39cd506a3..5651d35b7 100644
--- a/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py
@@ -56,6 +56,7 @@ class ColQwen3Adapter(BaseAdapter):
normalize: bool = True,
compute_precision: ComputePrecision = "bfloat16",
trust_remote_code: bool = True,
+ revision: str | None = None,
max_seq_length: int | None = None,
muvera_config: dict[str, Any] | None = None,
token_dim: int = 320,
@@ -69,6 +70,8 @@ class ColQwen3Adapter(BaseAdapter):
already normalizes; kept for interface parity).
compute_precision: Compute precision for inference.
trust_remote_code: Required for ColQwen3 (custom processor + model classes).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
max_seq_length: Ignored — ColQwen3 uses dynamic sequence length.
muvera_config: Optional MUVERA configuration (passed to postprocessor).
token_dim: Per-token embedding dimension (320 for ColQwen3).
@@ -78,6 +81,7 @@ class ColQwen3Adapter(BaseAdapter):
self._normalize = normalize
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._max_num_visual_tokens = max_num_visual_tokens
self._model: Any = None
@@ -106,6 +110,7 @@ class ColQwen3Adapter(BaseAdapter):
self._model_name_or_path,
trust_remote_code=self._trust_remote_code,
max_num_visual_tokens=self._max_num_visual_tokens,
+ revision=self._revision,
)
load_kwargs: dict[str, Any] = {
@@ -115,6 +120,8 @@ class ColQwen3Adapter(BaseAdapter):
}
if attn_impl is not None:
load_kwargs["attn_implementation"] = attn_impl
+ if self._revision is not None:
+ load_kwargs["revision"] = self._revision
self._model = AutoModel.from_pretrained(
self._model_name_or_path,
diff --git a/packages/sie_server/src/sie_server/adapters/colsmol/__init__.py b/packages/sie_server/src/sie_server/adapters/colsmol/__init__.py
new file mode 100644
index 000000000..83b5fc8c7
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/colsmol/__init__.py
@@ -0,0 +1,435 @@
+"""ColSmol adapter for small, permissive visual document retrieval.
+
+ColSmol (``vidore/colSmol-256M``, ``vidore/colSmol-500M``) is a ColPali-style
+visual late-interaction retriever built on **SmolVLM** (Idefics3 architecture).
+It encodes document page images into 128-dim per-patch multi-vectors and text
+queries into per-token multi-vectors for MaxSim late-interaction scoring — the
+small/fast permissive counterpart to the 3-4B ColQwen picks.
+
+License (both permissive → hosted-serving-allowed):
+- ColSmol adapter weights (``vidore/colSmol-*``): **MIT**
+- SmolVLM backbone (``HuggingFaceTB/SmolVLM-*-Instruct``): **Apache-2.0**
+
+The published ``vidore/colSmol-*`` repos are PEFT LoRA adapters over a
+``vidore/ColSmolVLM-Instruct-*-base`` checkpoint (full ColIdefics3 weights,
+including the 128-dim projection ``linear``). We resolve the base from the LoRA's
+``adapter_config.json``, load it, apply the LoRA, and ``merge_and_unload`` so
+inference is a plain forward. The ColIdefics3 wrapper (``Idefics3Model`` + a
+``linear`` projection to 128-dim) is inlined here to avoid a colpali-engine
+dependency, which conflicts with our torch>=2.9 requirement (same rationale as
+the colqwen2 adapter).
+
+Unlike the Qwen/GLM vision towers, Idefics3's SigLIP patch-embed conv runs over
+full images (not pre-patched input), so the ``rebind_vision_patch_embed`` fast
+path does not apply here (matching the colpali adapter).
+
+Reference: https://github.com/illuin-tech/colpali
+See: https://huggingface.co/vidore/colSmol-256M
+"""
+
+from __future__ import annotations
+
+import io
+import logging
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, ClassVar
+
+import numpy as np
+import torch
+from torch.nn import functional as F
+
+from sie_server.adapters._base_adapter import BaseAdapter
+from sie_server.adapters._multivector import maxsim_scores
+from sie_server.adapters._spec import AdapterSpec
+from sie_server.adapters._types import ComputePrecision
+from sie_server.core.inference_output import EncodeOutput
+from sie_server.types.inputs import media_bytes
+
+if TYPE_CHECKING:
+ from PIL import Image as PILImage
+
+ from sie_server.types.inputs import Item
+
+logger = logging.getLogger(__name__)
+
+_ERR_NO_INPUT = "ColSmolAdapter requires either text or images input"
+
+# ColIdefics3Processor constants (from colpali-engine). Images are described with
+# a fixed visual prompt; text queries are augmented with a repeated end-of-turn
+# token so the query has enough tokens for a stable late-interaction match.
+_VISUAL_PROMPT_PREFIX = "<|im_start|>User:<image>Describe the image.<end_of_utterance>\nAssistant:"
+_QUERY_AUGMENTATION_TOKEN = "<end_of_utterance>" # noqa: S105 — model special token, not a password
+_QUERY_AUGMENTATION_COUNT = 10
+
+
+# ---------------------------------------------------------------------------
+# Inlined ColIdefics3 model class
+# (from colpali-engine, avoids dependency conflict with torch>=2.9)
+# ---------------------------------------------------------------------------
+
+
+def _make_colidefics3_cls() -> type:
+ """Lazily create the ColIdefics3 model class.
+
+ Defers the transformers import so the module can be imported without
+ transformers installed (for config-only operations).
+ """
+ from torch import nn
+ from transformers import Idefics3Model, Idefics3PreTrainedModel
+
+ class ColIdefics3(Idefics3PreTrainedModel):
+ """SmolVLM (Idefics3) with a ColBERT-style multi-vector projection.
+
+ Projects the base model's last hidden state to 128-dim, L2-normalizes,
+ and masks padding via ``attention_mask``. Weight layout matches the
+ ``vidore/ColSmolVLM-Instruct-*-base`` checkpoints: ``model.*`` for the
+ Idefics3 tower and ``linear.*`` for the projection.
+
+ Inlined from colpali-engine to avoid a torch version conflict.
+ Reference: https://github.com/illuin-tech/colpali
+ """
+
+ main_input_name: ClassVar[str] = "doc_input_ids"
+
+ def __init__(self, config: Any) -> None:
+ super().__init__(config=config)
+ self.model = Idefics3Model(config)
+ self.dim = 128
+ self.linear = nn.Linear(config.text_config.hidden_size, self.dim)
+ self.post_init()
+
+ def forward(self, *args: Any, **kwargs: Any) -> torch.Tensor:
+ kwargs.pop("output_hidden_states", None)
+ kwargs.pop("return_dict", None)
+ outputs = self.model(*args, **kwargs)
+ last_hidden_states = outputs.last_hidden_state # (batch, seq, hidden_size)
+ proj = self.linear(last_hidden_states) # (batch, seq, 128)
+ proj = proj / proj.norm(dim=-1, keepdim=True) # L2 normalize
+ proj = proj * kwargs["attention_mask"].unsqueeze(-1) # mask padding
+ return proj
+
+ return ColIdefics3
+
+
+class ColSmolAdapter(BaseAdapter):
+ """Adapter for ColSmol visual document retrieval models (SmolVLM/Idefics3).
+
+ Encodes document page images into 128-dim per-patch multi-vectors and text
+ queries into per-token multi-vectors for MaxSim late-interaction retrieval.
+ """
+
+ spec = AdapterSpec(
+ inputs=("text", "image"),
+ outputs=("multivector", "score"),
+ multivector_dim=128,
+ unload_fields=("_model", "_processor"),
+ default_preprocessor="image",
+ )
+
+ def __init__(
+ self,
+ model_name_or_path: str | Path,
+ *,
+ normalize: bool = True,
+ compute_precision: ComputePrecision = "bfloat16",
+ trust_remote_code: bool = False,
+ revision: str | None = None,
+ max_seq_length: int | None = None,
+ muvera_config: dict[str, Any] | None = None,
+ token_dim: int = 128,
+ ) -> None:
+ """Initialize the adapter.
+
+ Args:
+ model_name_or_path: HuggingFace model ID (a ``vidore/colSmol-*`` LoRA
+ repo) or local path.
+ normalize: Kept for interface parity — the model wrapper already
+ L2-normalizes; this is a no-op safety belt for downstream parity.
+ compute_precision: Compute precision for inference (float32 on CPU).
+ trust_remote_code: Unused — ColSmol loads via native transformers
+ Idefics3 classes (no remote code).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
+ max_seq_length: Ignored — ColSmol uses dynamic sequence length.
+ muvera_config: Accepted for interface parity with the other Col*
+ adapters; ColSmol builds no MUVERA postprocessor, so this is
+ currently a no-op (neither stored nor applied).
+ token_dim: Per-token embedding dimension (128 for ColSmol).
+ """
+ self._model_name_or_path = str(model_name_or_path)
+ self._normalize = normalize
+ self._compute_precision = compute_precision
+ self._trust_remote_code = trust_remote_code
+ self._revision = revision
+
+ self._model: Any = None
+ self._processor: Any = None
+ self._device: str | None = None
+ self._multivector_dim: int = token_dim
+
+ def load(self, device: str) -> None:
+ """Load base + LoRA, merge, and place the model on ``device``."""
+ from peft import PeftConfig, PeftModel
+ from transformers import Idefics3Config, Idefics3Processor
+
+ self._device = device
+
+ dtype = self._resolve_dtype()
+ attn_impl = self._resolve_attn_implementation(device)
+
+ # The colSmol-* repos are LoRA adapters; discover the full base checkpoint
+ # (which carries the ColIdefics3 projection ``linear``) from adapter_config.
+ peft_cfg = PeftConfig.from_pretrained(self._model_name_or_path, revision=self._revision)
+ base_id = peft_cfg.base_model_name_or_path
+ if not base_id:
+ msg = f"ColSmol repo {self._model_name_or_path!r} has no base_model_name_or_path in adapter_config"
+ raise ValueError(msg)
+
+ logger.info(
+ "Loading ColSmol model %s (base=%s) on device=%s with dtype=%s, attn=%s",
+ self._model_name_or_path,
+ base_id,
+ device,
+ dtype,
+ attn_impl,
+ )
+
+ # The pin identifies a commit in the LoRA repo (``self._model_name_or_path``);
+ # guard it so the str-typed ``revision`` param keeps its "main" default when
+ # unset. It applies ONLY to loads that read the LoRA repo (the processor here
+ # and the PEFT config/adapter below). ``base_id`` is a *separate* base
+ # checkpoint repo, so its loads must NOT receive this SHA — the commit does
+ # not exist there and would raise RevisionNotFoundError (503 on first request).
+ rev_kwargs: dict[str, Any] = {"revision": self._revision} if self._revision is not None else {}
+
+ self._processor = Idefics3Processor.from_pretrained(self._model_name_or_path, **rev_kwargs)
+ self._processor.tokenizer.padding_side = "left" # ty: ignore[unresolved-attribute]
+
+ # base_id is a different repo → load at its own default revision (no pin).
+ config = Idefics3Config.from_pretrained(base_id)
+ col_idefics3_cls = _make_colidefics3_cls()
+
+ load_kwargs: dict[str, Any] = {
+ "config": config,
+ "dtype": dtype,
+ "device_map": device,
+ }
+ if attn_impl is not None:
+ load_kwargs["attn_implementation"] = attn_impl
+
+ base_model = col_idefics3_cls.from_pretrained(base_id, **load_kwargs) # ty: ignore[unresolved-attribute]
+ merged = PeftModel.from_pretrained(
+ base_model, self._model_name_or_path, revision=self._revision
+ ).merge_and_unload()
+ self._model = merged.eval()
+
+ self._multivector_dim = getattr(self._model, "dim", 128)
+
+ def _resolve_dtype(self) -> torch.dtype:
+ if not self._device or not str(self._device).startswith("cuda"):
+ return torch.float32
+ dtype_map = {
+ "float16": torch.float16,
+ "bfloat16": torch.bfloat16,
+ "float32": torch.float32,
+ }
+ return dtype_map.get(self._compute_precision, torch.bfloat16)
+
+ def _resolve_attn_implementation(self, device: str) -> str | None:
+ if not device.startswith("cuda"):
+ return None
+ try:
+ import flash_attn # ty: ignore[unresolved-import]
+
+ return "flash_attention_2"
+ except ImportError:
+ logger.info("flash_attn not available, using sdpa attention")
+ return "sdpa"
+
+ # ------------------------------------------------------------------
+ # Encode
+ # ------------------------------------------------------------------
+
+ def encode(
+ self,
+ items: list[Item],
+ output_types: list[str],
+ *,
+ instruction: str | None = None,
+ is_query: bool = False,
+ prepared_items: Any = None,
+ options: dict[str, Any] | None = None,
+ ) -> EncodeOutput:
+ self._check_loaded()
+ self._validate_output_types(output_types)
+
+ if is_query:
+ multivector_list: list[np.ndarray] = []
+ for item in items:
+ if item.text is None:
+ raise ValueError(_ERR_NO_INPUT)
+ multivector_list.append(self._encode_text(item.text))
+ return EncodeOutput(
+ multivector=multivector_list,
+ batch_size=len(items),
+ is_query=is_query,
+ multivector_token_dim=self._multivector_dim,
+ )
+
+ # Preallocate by index so output order matches input order regardless of
+ # text/image mix, and so multi-image items collapse to one multivector.
+ results: list[np.ndarray | None] = [None] * len(items)
+ all_images: list[PILImage.Image] = []
+ image_slots: list[tuple[int, int]] = [] # (item_idx, image_count)
+ for idx, item in enumerate(items):
+ has_images = item.images is not None and len(item.images) > 0
+ if has_images:
+ images = self._load_images(item)
+ all_images.extend(images)
+ image_slots.append((idx, len(images)))
+ elif item.text is not None:
+ results[idx] = self._encode_text(item.text)
+ else:
+ raise ValueError(_ERR_NO_INPUT)
+
+ if all_images:
+ per_image_mvs = self._encode_images(all_images)
+ cursor = 0
+ for idx, count in image_slots:
+ segment = per_image_mvs[cursor : cursor + count]
+ cursor += count
+ results[idx] = segment[0] if count == 1 else np.concatenate(segment, axis=0)
+
+ multivector_list = [mv for mv in results if mv is not None]
+ assert len(multivector_list) == len(items)
+
+ return EncodeOutput(
+ multivector=multivector_list,
+ batch_size=len(items),
+ is_query=is_query,
+ multivector_token_dim=self._multivector_dim,
+ )
+
+ # ------------------------------------------------------------------
+ # Image encoding
+ # ------------------------------------------------------------------
+
+ def _load_images(self, item: Any) -> list[PILImage.Image]:
+ from PIL import Image
+
+ pil_images: list[PILImage.Image] = []
+ for img_input in item.images or []:
+ pil_img = Image.open(io.BytesIO(media_bytes(img_input, kind="image")))
+ if pil_img.mode != "RGB":
+ pil_img = pil_img.convert("RGB")
+ pil_images.append(pil_img)
+ return pil_images
+
+ def _encode_images(self, images: list[PILImage.Image]) -> list[np.ndarray]:
+ """Encode a batch of images and return per-image multi-vectors."""
+ assert self._model is not None
+ assert self._processor is not None
+
+ # One text prompt per image; nested image lists pair image i with prompt i.
+ batch = self._processor(
+ text=[_VISUAL_PROMPT_PREFIX] * len(images),
+ images=[[img] for img in images],
+ padding="longest",
+ return_tensors="pt",
+ )
+ batch = {k: v.to(self._device) for k, v in batch.items() if hasattr(v, "to")}
+
+ with torch.inference_mode():
+ embeddings = self._model(**batch) # (batch, seq, 128)
+ if self._normalize:
+ embeddings = F.normalize(embeddings, p=2, dim=-1)
+
+ results = [embeddings[i].float().cpu().numpy() for i in range(embeddings.shape[0])]
+
+ # Free GPU memory between batches to prevent OOM on subsequent calls
+ # (L4 22GB GPUs are tight for VLM models).
+ del embeddings, batch
+ if self._device and self._device.startswith("cuda"):
+ torch.cuda.empty_cache()
+
+ return results
+
+ # ------------------------------------------------------------------
+ # Text encoding
+ # ------------------------------------------------------------------
+
+ def _encode_text(self, text: str) -> np.ndarray:
+ """Encode a single text query with the query-augmentation suffix."""
+ assert self._model is not None
+ assert self._processor is not None
+
+ augmented = text + _QUERY_AUGMENTATION_TOKEN * _QUERY_AUGMENTATION_COUNT
+ batch = self._processor(
+ text=[augmented],
+ return_tensors="pt",
+ padding="longest",
+ )
+ batch = {k: v.to(self._device) for k, v in batch.items() if hasattr(v, "to")}
+
+ with torch.inference_mode():
+ embeddings = self._model(**batch) # (1, seq, 128)
+ if self._normalize:
+ embeddings = F.normalize(embeddings, p=2, dim=-1)
+
+ result = embeddings[0].float().cpu().numpy()
+
+ del embeddings, batch
+ if self._device and self._device.startswith("cuda"):
+ torch.cuda.empty_cache()
+
+ return result
+
+ # ------------------------------------------------------------------
+ # Scoring
+ # ------------------------------------------------------------------
+
+ def score(
+ self,
+ query: Any,
+ items: list[Any],
+ *,
+ instruction: str | None = None,
+ options: dict[str, Any] | None = None,
+ ) -> list[float]:
+ """Score documents against a text query using MaxSim.
+
+ ``instruction`` and ``options`` are accepted for interface parity with
+ ``BaseAdapter.score_pairs()`` but are not used: ColSmol (a ColPali-family
+ model) distinguishes queries from documents via ``is_query``, not an
+ instruction prefix, so a caller-supplied instruction has no effect here.
+ """
+ self._check_loaded()
+
+ query_output = self.encode([query], output_types=["multivector"], is_query=True)
+ if query_output.multivector is None:
+ raise RuntimeError("Failed to encode query: no multivector output")
+ query_vecs = query_output.multivector[0]
+
+ doc_output = self.encode(items, output_types=["multivector"], is_query=False)
+ if doc_output.multivector is None:
+ raise RuntimeError("Failed to encode documents: no multivector output")
+
+ query_tensor = torch.from_numpy(query_vecs).to(self._device)
+ doc_tensors = [torch.from_numpy(d).to(self._device) for d in doc_output.multivector]
+ return maxsim_scores(query_tensor, doc_tensors)
+
+ # ------------------------------------------------------------------
+ # Helpers
+ # ------------------------------------------------------------------
+
+ def _validate_output_types(self, output_types: list[str]) -> None:
+ unsupported = set(output_types) - {"multivector"}
+ if unsupported:
+ msg = f"Unsupported output types: {unsupported}. ColSmolAdapter only supports 'multivector'."
+ raise ValueError(msg)
+
+ def get_preprocessor(self) -> Any | None:
+ # ColSmol uses the Idefics3Processor, which requires the visual prompt
+ # text alongside images; the generic ImagePreprocessor does not match
+ # that call pattern (same as colqwen2/colqwen3).
+ return None
diff --git a/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py
index 1fcf74cde..07939f831 100644
--- a/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py
@@ -60,6 +60,7 @@ class CrossEncoderAdapter(BaseAdapter):
max_length: int | None = None,
compute_precision: ComputePrecision | None = None,
attn_implementation: AttnImplementation = "sdpa",
+ revision: str | None = None,
**kwargs: Any, # Accept extra args from loader (e.g., pooling)
) -> None:
"""Initialize the adapter.
@@ -72,6 +73,9 @@ class CrossEncoderAdapter(BaseAdapter):
fp32 off-CUDA (safe on MPS) and fp16 on CUDA; set explicitly to override
(e.g. float16 to opt a curated model into fp16 on MPS).
attn_implementation: Attention implementation ("sdpa" for optimized, "eager" for baseline).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading the model. If None, the default branch is used. Forwarded
+ to ``CrossEncoder(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs # Unused, but accepted for loader compatibility
@@ -80,6 +84,7 @@ class CrossEncoderAdapter(BaseAdapter):
self._max_length = max_length
self._compute_precision = compute_precision
self._attn_implementation = attn_implementation
+ self._revision = revision
self._model: CrossEncoder | None = None
self._device: str | None = None
@@ -123,6 +128,7 @@ class CrossEncoderAdapter(BaseAdapter):
self._model_name_or_path,
device=device,
trust_remote_code=self._trust_remote_code,
+ revision=self._revision,
model_kwargs=model_kwargs or None,
)
@@ -215,7 +221,65 @@ class CrossEncoderAdapter(BaseAdapter):
# Convert to float32 numpy array and wrap in ScoreOutput
import numpy as np
- return ScoreOutput(scores=np.asarray(scores, dtype=np.float32))
+ return ScoreOutput(
+ scores=np.asarray(scores, dtype=np.float32),
+ input_token_counts=self._pair_input_token_counts(pairs),
+ )
+
+ def _metering_tokenizer(self) -> Any | None:
+ """Return the CrossEncoder's own tokenizer for §7.3 pair counting.
+
+ Unlike in-tree text adapters, this adapter keeps no ``self._tokenizer``:
+ the tokenizer lives inside the sentence-transformers ``CrossEncoder``
+ (``self._model``). Sourcing it here lets the shared BaseAdapter counting
+ helpers (:meth:`count_pair_input_tokens`, :meth:`_token_counts_or_none`)
+ operate over the exact tokenizer the forward pass uses.
+ """
+ return getattr(self._model, "tokenizer", None)
+
+ def _metering_max_length(self) -> int | None:
+ """Resolve the truncation cap ``predict()`` applies, for §7.3 counting.
+
+ ``CrossEncoder.predict`` always tokenizes with ``truncation=True`` at the
+ model's ``max_length`` (falling back to the tokenizer's
+ ``model_max_length`` when unset). Returning that same cap keeps the
+ shared counter's truncation ON and its length equal to the forward
+ pass's real joint-pair length — reusing BaseAdapter's tokenizer/count
+ core without under- or over-billing long pairs. ``None`` only when no
+ real cap exists (the base counter then leaves truncation off, matching
+ ``predict`` tokenizing to an effectively-unbounded ``model_max_length``).
+ """
+ max_length = getattr(self._model, "max_length", None) or self._max_length
+ if isinstance(max_length, int) and not isinstance(max_length, bool) and max_length > 0:
+ return max_length
+ model_max = getattr(self._metering_tokenizer(), "model_max_length", None)
+ if isinstance(model_max, int) and not isinstance(model_max, bool) and 0 < model_max <= 100_000:
+ return model_max
+ return None
+
+ def _pair_input_token_counts(self, pairs: list[tuple[str, str]]) -> list[int] | None:
+ """Real per-pair input-token counts for the unit meter (§7.3).
+
+ A cross-encoder tokenizes each (query, doc) pair JOINTLY (query and doc
+ packed into one sequence with the model's separators), so the pair's
+ billable input tokens is the length of that joint encoding. ``predict``
+ owns the forward-pass tokenization opaquely; we recover the count by
+ reusing BaseAdapter's shared joint-encoding counter
+ (:meth:`_token_counts_or_none`) over the model's own tokenizer
+ (:meth:`_metering_tokenizer`) and the same truncation cap ``predict``
+ applies (:meth:`_metering_max_length`). Best-effort: any tokenizer quirk
+ returns ``None`` so the meter falls back to its reserve estimate rather
+ than failing the score or billing an approximation as a count.
+ """
+ tokenizer = self._metering_tokenizer()
+ if tokenizer is None:
+ return None
+ return self._token_counts_or_none(
+ tokenizer,
+ [q for q, _ in pairs],
+ [d for _, d in pairs],
+ expected_len=len(pairs),
+ )
def _extract_text(self, item: Item) -> str:
"""Extract text from an item."""
diff --git a/packages/sie_server/src/sie_server/adapters/docling/__init__.py b/packages/sie_server/src/sie_server/adapters/docling/__init__.py
index 77f368d97..6577c860d 100644
--- a/packages/sie_server/src/sie_server/adapters/docling/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/docling/__init__.py
@@ -16,6 +16,25 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+def _document_page_count(doc: Any) -> int:
+ """Real page count of a parsed ``DoclingDocument`` (the §7 parse unit).
+
+ Prefers the document model's ``num_pages()`` and falls back to ``len(pages)``.
+ Best-effort: any docling-version quirk degrades to ``0`` so metering never
+ fails the parse — the meter then stays on its reserve estimate for the item.
+ """
+ try:
+ num_pages = getattr(doc, "num_pages", None)
+ if callable(num_pages):
+ return max(int(num_pages()), 0)
+ pages = getattr(doc, "pages", None)
+ if pages is not None:
+ return max(len(pages), 0)
+ except Exception: # noqa: BLE001 — metering must never fail the parse
+ return 0
+ return 0
+
+
_ERR_REQUIRES_DOCUMENT = "Docling requires Item.document or Item.images[0] with raw bytes"
# Minimal one-page PDF used to warm Docling's layout/table model downloads
@@ -120,23 +139,39 @@ class DoclingAdapter(BaseAdapter):
ocr_enabled = bool(options and options.get("ocr"))
results = self._run_extract(items, ocr_enabled=ocr_enabled)
+ data = [result for result, _pages in results]
+ # Unit-meter seam (§7): the canonical parse/OCR billing dimension is
+ # PAGES ("$ per 1k pages", design §7). Docling's document model knows
+ # exactly how many pages it parsed per item, so surface that real count
+ # to the queue executor (folded into ``ItemOutcome.units.pages``).
+ # Only emit the dimension when at least one page was parsed — an
+ # all-error batch (0 pages) leaves it unset so the meter falls back to
+ # its reserve estimate rather than billing zero.
+ page_counts = [pages for _result, pages in results]
+ emit_pages = page_counts if any(p > 0 for p in page_counts) else None
+
return ExtractOutput(
entities=[[] for _ in items],
- data=results,
+ data=data,
batch_size=len(items),
+ pages=emit_pages,
)
- def _run_extract(self, items: list[Item], *, ocr_enabled: bool) -> list[dict[str, Any]]:
+ def _run_extract(self, items: list[Item], *, ocr_enabled: bool) -> list[tuple[dict[str, Any], int]]:
"""Run extract per-item, serially.
Items are processed one at a time so we can share a single cached
DocumentConverter (see class docstring). At GPU-bound concurrency the
worker-level inference executor is already saturating the device, so
intra-batch parallelism does not buy real throughput.
+
+ Returns per item a ``(result, page_count)`` pair: ``page_count`` is the
+ number of document pages Docling parsed (``0`` on a per-item error), the
+ §7 parse-billing dimension.
"""
return [self._extract_one(item, ocr_enabled=ocr_enabled) for item in items]
- def _extract_one(self, item: Item, *, ocr_enabled: bool) -> dict[str, Any]:
+ def _extract_one(self, item: Item, *, ocr_enabled: bool) -> tuple[dict[str, Any], int]:
# Prefer document when both are provided: PDF/DOCX/HTML carry layout
# that Docling's pipeline exploits; an image is the rasterized
# fallback for callers that only have a page render.
@@ -148,7 +183,7 @@ class DoclingAdapter(BaseAdapter):
images = item.images or []
first_image = images[0] if images else None
if not is_image_input(first_image):
- return {"error": _ERR_REQUIRES_DOCUMENT}
+ return {"error": _ERR_REQUIRES_DOCUMENT}, 0
payload = first_image["data"]
format_hint = first_image.get("format") or "png"
try:
@@ -156,7 +191,7 @@ class DoclingAdapter(BaseAdapter):
return self._convert_bytes(converter, payload, format_hint=format_hint)
except Exception as e: # noqa: BLE001 - per-item failure must not poison the batch
logger.warning("Docling extract failed for item id=%s: %s", item.id, e)
- return {"error": str(e)}
+ return {"error": str(e)}, 0
def _get_converter(self, *, ocr_enabled: bool) -> Any:
"""Return the cached DocumentConverter for this ocr_enabled value, building lazily on first use."""
@@ -167,7 +202,7 @@ class DoclingAdapter(BaseAdapter):
self._converters[ocr_enabled] = converter
return converter
- def _convert_bytes(self, converter: Any, data: bytes, *, format_hint: str | None) -> dict[str, Any]:
+ def _convert_bytes(self, converter: Any, data: bytes, *, format_hint: str | None) -> tuple[dict[str, Any], int]:
from docling.datamodel.base_models import DocumentStream # ty: ignore[unresolved-import]
# Docling auto-detects format from bytes; the hint becomes the source name
@@ -176,11 +211,12 @@ class DoclingAdapter(BaseAdapter):
stream = DocumentStream(name=source_name, stream=io.BytesIO(data))
result = converter.convert(stream)
doc = result.document
- return {
+ payload = {
"text": doc.export_to_text(),
"markdown": doc.export_to_markdown(),
"document": doc.export_to_dict(),
}
+ return payload, _document_page_count(doc)
def _make_converter(self, *, ocr_enabled: bool) -> Any:
"""Build a fresh DocumentConverter. Callers should usually go through _get_converter() for caching.
diff --git a/packages/sie_server/src/sie_server/adapters/donut/__init__.py b/packages/sie_server/src/sie_server/adapters/donut/__init__.py
index 8678a710f..714c19f88 100644
--- a/packages/sie_server/src/sie_server/adapters/donut/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/donut/__init__.py
@@ -83,6 +83,7 @@ class DonutAdapter(BaseAdapter):
max_new_tokens: int = 512,
num_beams: int = 1,
attn_implementation: str = "eager",
+ revision: str | None = None,
**kwargs: Any, # Accept and ignore extra kwargs (e.g., normalize, max_seq_length)
) -> None:
"""Initialize the adapter.
@@ -95,6 +96,8 @@ class DonutAdapter(BaseAdapter):
num_beams: Number of beams for beam search (1 = greedy).
attn_implementation: Attention implementation - "eager" or "sdpa".
Use "sdpa" for optimized inference with PyTorch's scaled dot-product attention.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when loading model artifacts.
+ Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Ignored extra arguments from the loader.
"""
del kwargs # Unused - accepts normalize, max_seq_length, etc.
@@ -104,6 +107,7 @@ class DonutAdapter(BaseAdapter):
self._max_new_tokens = max_new_tokens
self._num_beams = num_beams
self._attn_implementation = attn_implementation
+ self._revision = revision
self._model: Any = None
self._processor: Any = None # HuggingFace DonutProcessor
@@ -123,6 +127,10 @@ class DonutAdapter(BaseAdapter):
# Determine dtype
dtype = self._resolve_dtype()
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
logger.info(
"Loading Donut model %s on device=%s with dtype=%s, attn=%s",
self._model_name_or_path,
@@ -132,7 +140,10 @@ class DonutAdapter(BaseAdapter):
)
# Load processor
- self._processor = DonutProcessor.from_pretrained(self._model_name_or_path)
+ self._processor = DonutProcessor.from_pretrained(
+ self._model_name_or_path,
+ **shared_kwargs,
+ )
# Load model with optional SDPA
# Note: VisionEncoderDecoderModel supports SDPA but not flash_attention_2
@@ -140,6 +151,7 @@ class DonutAdapter(BaseAdapter):
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation=self._attn_implementation,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
diff --git a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py b/packages/sie_server/src/sie_server/adapters/florence2/__init__.py
index 0e06b01d8..f89746b96 100644
--- a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/florence2/__init__.py
@@ -84,6 +84,7 @@ class Florence2Adapter(BaseAdapter):
default_task: str = TASK_OCR_WITH_REGION,
compute_precision: ComputePrecision = "float16",
trust_remote_code: bool = True,
+ revision: str | None = None,
max_new_tokens: int = 1024,
num_beams: int = 1,
attn_implementation: str = "eager",
@@ -96,6 +97,8 @@ class Florence2Adapter(BaseAdapter):
default_task: Default task prompt if not specified in options.
compute_precision: Compute precision for inference.
trust_remote_code: Whether to trust remote code (required for Florence-2).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when loading model artifacts.
+ Forwarded to ``from_pretrained(..., revision=...)``.
max_new_tokens: Maximum tokens to generate.
num_beams: Number of beams for beam search.
attn_implementation: Attention implementation - "eager", "sdpa", or "flash_attention_2".
@@ -107,6 +110,7 @@ class Florence2Adapter(BaseAdapter):
self._default_task = default_task
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._max_new_tokens = max_new_tokens
self._num_beams = num_beams
self._attn_implementation = attn_implementation
@@ -129,6 +133,10 @@ class Florence2Adapter(BaseAdapter):
# Determine dtype
dtype = self._resolve_dtype()
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
logger.info(
"Loading Florence-2 model %s on device=%s with dtype=%s, attn=%s",
self._model_name_or_path,
@@ -140,7 +148,7 @@ class Florence2Adapter(BaseAdapter):
# Load processor with trust_remote_code (required for Florence-2 custom processor)
self._processor = AutoProcessor.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# Load model with trust_remote_code to use model's custom code
@@ -148,8 +156,8 @@ class Florence2Adapter(BaseAdapter):
self._model = AutoModelForCausalLM.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
- trust_remote_code=self._trust_remote_code,
attn_implementation=self._attn_implementation,
+ **shared_kwargs,
)
self._model.to(device) # ty: ignore[invalid-argument-type]
diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
index dda87093d..a3d77cca4 100644
--- a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
@@ -73,6 +73,7 @@ class GLiClassAdapter(BaseAdapter):
threshold: float = 0.0,
max_seq_length: int | None = None,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize GLiClass adapter.
@@ -88,6 +89,8 @@ class GLiClassAdapter(BaseAdapter):
tokenization inside the gliclass pipeline so inputs cannot exceed
the model's position-embedding capacity.
compute_precision: Precision for inference (float16, float32, bfloat16).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts.
**kwargs: Additional arguments (ignored for compatibility).
"""
self._model_name_or_path = str(model_name_or_path)
@@ -95,6 +98,7 @@ class GLiClassAdapter(BaseAdapter):
self._threshold = threshold
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
+ self._revision = revision
self._pipeline: ZeroShotClassificationPipeline | None = None
self._tokenizer: PreTrainedTokenizerBase | None = None
@@ -123,9 +127,12 @@ class GLiClassAdapter(BaseAdapter):
torch_dtype = torch.float32
# Load model and tokenizer
- model = GLiClassModel.from_pretrained(self._model_name_or_path)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+ model = GLiClassModel.from_pretrained(self._model_name_or_path, **shared_kwargs)
model = model.to(device, dtype=torch_dtype)
- self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path, **shared_kwargs)
# Bound the tokenizer's max length so any internal tokenization in the
# gliclass library auto-truncates to the model's actual capacity.
diff --git a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py b/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
index 20c8d11a2..73b99bf06 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
@@ -65,6 +65,7 @@ class GLiNERAdapter(BaseAdapter):
multi_label: bool = False,
merge_adjacent_entities: bool = False,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any, # Accept extra args from loader (e.g., pooling)
) -> None:
"""Initialize the adapter.
@@ -77,6 +78,8 @@ class GLiNERAdapter(BaseAdapter):
merge_adjacent_entities: If True, merge adjacent entities with same label.
Required for token-based models like numind/NuNER_Zero.
compute_precision: Compute precision for inference.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs # Unused, but accepted for loader compatibility
@@ -86,6 +89,7 @@ class GLiNERAdapter(BaseAdapter):
self._multi_label = multi_label
self._merge_adjacent_entities = merge_adjacent_entities
self._compute_precision = compute_precision
+ self._revision = revision
self._model: Any = None # GLiNER model type
self._device: str | None = None
@@ -110,8 +114,12 @@ class GLiNERAdapter(BaseAdapter):
dtype = torch.bfloat16
# Load model
+ load_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ load_kwargs["revision"] = self._revision
self._model = GLiNER.from_pretrained(
self._model_name_or_path,
+ **load_kwargs,
)
# Move to device with precision
@@ -202,7 +210,39 @@ class GLiNERAdapter(BaseAdapter):
all_entities.append(entity_results)
- return ExtractOutput(entities=all_entities)
+ return ExtractOutput(entities=all_entities, input_token_counts=self._doc_input_token_counts(texts))
+
+ def _doc_input_token_counts(self, texts: list[str]) -> list[int] | None:
+ """Real per-document input-token counts for the unit meter (§7.3).
+
+ GLiNER's ``inference`` owns tokenization opaquely, so we recover the
+ billable count by running each document through the model's own
+ transformer tokenizer (``data_processor.transformer_tokenizer``) — the
+ same subword vocabulary the forward pass uses. We count the DOCUMENT
+ tokens only; the entity-type label prompt is request schema (re-used
+ across docs, not billed content), matching "$ per 1M input tokens" over
+ the document (§7.1). Best-effort: any tokenizer-shape quirk returns
+ ``None`` so the meter falls back to its reserve estimate rather than
+ billing an approximation as a count.
+ """
+ processor = getattr(self._model, "data_processor", None)
+ tokenizer = getattr(processor, "transformer_tokenizer", None)
+ if tokenizer is None:
+ return None
+ # Cap truncation at the tokenizer's own ``model_max_length`` when it
+ # declares a plausible one; HF sets an ``int(1e30)`` sentinel for
+ # uncapped tokenizers, which we treat as "no cap" (documents are short
+ # relative to that and counting the full length is still authoritative).
+ raw_max = getattr(tokenizer, "model_max_length", None)
+ max_length = raw_max if isinstance(raw_max, int) and 0 < raw_max < 1_000_000 else None
+ try:
+ encoded = tokenizer(texts, truncation=max_length is not None, max_length=max_length)
+ counts = [len(ids) for ids in encoded["input_ids"]]
+ except Exception: # noqa: BLE001 — metering must never fail an extraction
+ return None
+ if len(counts) != len(texts):
+ return None
+ return counts
def _merge_entities(self, entities: list[Entity], text: str) -> list[Entity]:
"""Merge adjacent entities with the same label.
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/__init__.py b/packages/sie_server/src/sie_server/adapters/gliner2/__init__.py
index b7c5d2cc8..7c890dae8 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner2/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner2/__init__.py
@@ -43,6 +43,7 @@ class GLiNER2Adapter(BaseAdapter):
*,
threshold: float = 0.5,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -51,12 +52,15 @@ class GLiNER2Adapter(BaseAdapter):
model_name_or_path: HuggingFace model ID or local path.
threshold: Minimum confidence score for entity extraction (0-1).
compute_precision: Compute precision for inference.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
self._model_name_or_path = str(model_name_or_path)
self._threshold = threshold
self._compute_precision = compute_precision
+ self._revision = revision
self._model: Any = None
self._device: str | None = None
@@ -73,6 +77,10 @@ class GLiNER2Adapter(BaseAdapter):
# GLiNER2 uses map_location for device placement and quantize for fp16
use_quantize = device != "cpu" and self._compute_precision == "float16"
+ # gliner2.GLiNER2.from_pretrained exposes no revision seam: it pops only
+ # quantize/compile/map_location and discards the rest of **kwargs, so a
+ # revision never reaches hf_hub_download. self._revision is stored but
+ # cannot be honored here.
self._model = GLiNER2.from_pretrained(
self._model_name_or_path,
map_location=device,
diff --git a/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py b/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py
index eba24e531..b2fb8fa1d 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner_bi/__init__.py
@@ -53,6 +53,7 @@ class GLiNERBiAdapter(BaseAdapter):
attn_implementation: str | None = None,
max_len: int | None = None,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -69,6 +70,8 @@ class GLiNERBiAdapter(BaseAdapter):
``"flash_attention_2"`` for ModernBERT-based models).
max_len: Maximum sequence length override for the model.
compute_precision: Compute precision for inference.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
@@ -80,6 +83,7 @@ class GLiNERBiAdapter(BaseAdapter):
self._attn_implementation = attn_implementation
self._max_len = max_len
self._compute_precision = compute_precision
+ self._revision = revision
self._model: Any = None
self._device: str | None = None
@@ -124,6 +128,8 @@ class GLiNERBiAdapter(BaseAdapter):
load_kwargs["_attn_implementation"] = attn_impl
if self._max_len is not None:
load_kwargs["max_length"] = self._max_len
+ if self._revision is not None:
+ load_kwargs["revision"] = self._revision
self._model = GLiNER.from_pretrained(
self._model_name_or_path,
diff --git a/packages/sie_server/src/sie_server/adapters/glirel/__init__.py b/packages/sie_server/src/sie_server/adapters/glirel/__init__.py
index 2b82ee292..667f941f5 100644
--- a/packages/sie_server/src/sie_server/adapters/glirel/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/glirel/__init__.py
@@ -65,6 +65,7 @@ class GLiRELAdapter(BaseAdapter):
*,
threshold: float = 0.3,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any, # Accept extra args from loader
) -> None:
"""Initialize the adapter.
@@ -73,12 +74,15 @@ class GLiRELAdapter(BaseAdapter):
model_name_or_path: HuggingFace model ID or local path to GLiREL model.
threshold: Minimum confidence score for relation extraction (0-1).
compute_precision: Compute precision for inference.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs # Unused, but accepted for loader compatibility
self._model_name_or_path = str(model_name_or_path)
self._threshold = threshold
self._compute_precision = compute_precision
+ self._revision = revision
self._model: Any = None # GLiREL model type
self._device: str | None = None
@@ -95,7 +99,10 @@ class GLiRELAdapter(BaseAdapter):
self._device = device
# Load model
- self._model = GLiREL.from_pretrained(self._model_name_or_path)
+ load_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ load_kwargs["revision"] = self._revision
+ self._model = GLiREL.from_pretrained(self._model_name_or_path, **load_kwargs)
# Move to device
self._model = self._model.to(device)
diff --git a/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py b/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py
index acb92e019..803ca504c 100644
--- a/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py
@@ -48,6 +48,7 @@ class GlmOcrAdapter(ModelAdapter):
max_new_tokens: int = 8192,
num_beams: int = 1,
attn_implementation: str = "sdpa",
+ revision: str | None = None,
user_text: str = DEFAULT_USER_TEXT,
**kwargs: Any,
) -> None:
@@ -59,6 +60,8 @@ class GlmOcrAdapter(ModelAdapter):
max_new_tokens: Maximum tokens to generate.
num_beams: Number of beams for beam search.
attn_implementation: Attention implementation - "eager", "sdpa", or "flash_attention_2".
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when loading model artifacts.
+ Forwarded to ``from_pretrained(..., revision=...)``.
user_text: Default user text appended to the image in the chat prompt.
**kwargs: Ignored extra arguments from the loader.
"""
@@ -68,6 +71,7 @@ class GlmOcrAdapter(ModelAdapter):
self._max_new_tokens = max_new_tokens
self._num_beams = num_beams
self._attn_implementation = attn_implementation
+ self._revision = revision
self._user_text = user_text
self._model: Any = None
@@ -100,6 +104,10 @@ class GlmOcrAdapter(ModelAdapter):
dtype = self._resolve_dtype(device)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
logger.info(
"Loading GLM-OCR model %s on device=%s with dtype=%s, attn=%s",
self._model_name_or_path,
@@ -108,12 +116,13 @@ class GlmOcrAdapter(ModelAdapter):
self._attn_implementation,
)
- self._processor = AutoProcessor.from_pretrained(self._model_name_or_path)
+ self._processor = AutoProcessor.from_pretrained(self._model_name_or_path, **shared_kwargs)
self._model = AutoModelForImageTextToText.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation=self._attn_implementation,
+ **shared_kwargs,
)
self._model.to(device) # ty: ignore[invalid-argument-type]
diff --git a/packages/sie_server/src/sie_server/adapters/grounding_dino/__init__.py b/packages/sie_server/src/sie_server/adapters/grounding_dino/__init__.py
index 902a4aa83..0d0e37a7a 100644
--- a/packages/sie_server/src/sie_server/adapters/grounding_dino/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/grounding_dino/__init__.py
@@ -81,6 +81,7 @@ class GroundingDINOAdapter(BaseAdapter):
"_model_name_or_path",
"_preprocessor",
"_processor",
+ "_revision",
"_text_threshold",
)
@@ -89,6 +90,7 @@ class GroundingDINOAdapter(BaseAdapter):
model_name_or_path: str | Path,
*,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
box_threshold: float = 0.25,
text_threshold: float = 0.25,
**kwargs: Any,
@@ -96,6 +98,7 @@ class GroundingDINOAdapter(BaseAdapter):
del kwargs
self._model_name_or_path = str(model_name_or_path)
self._compute_precision = compute_precision
+ self._revision = revision
self._box_threshold = box_threshold
self._text_threshold = text_threshold
@@ -115,6 +118,10 @@ class GroundingDINOAdapter(BaseAdapter):
self._device_type = "cuda" if device.startswith("cuda") else "cpu"
dtype = self._resolve_dtype()
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
logger.info(
"Loading GroundingDINO model %s on device=%s with dtype=%s",
self._model_name_or_path,
@@ -122,10 +129,11 @@ class GroundingDINOAdapter(BaseAdapter):
dtype,
)
- self._processor = AutoProcessor.from_pretrained(self._model_name_or_path)
+ self._processor = AutoProcessor.from_pretrained(self._model_name_or_path, **shared_kwargs)
self._model = AutoModelForZeroShotObjectDetection.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
diff --git a/packages/sie_server/src/sie_server/adapters/gte_sparse_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/gte_sparse_flash/__init__.py
index 20fee804d..5d271e52b 100644
--- a/packages/sie_server/src/sie_server/adapters/gte_sparse_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gte_sparse_flash/__init__.py
@@ -73,6 +73,7 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
query_template: str | None = None,
doc_template: str | None = None,
trust_remote_code: bool = True,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -84,6 +85,8 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
query_template: Optional template for queries.
doc_template: Optional template for documents.
trust_remote_code: Whether to trust remote code (required for NewForMaskedLM).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
@@ -93,6 +96,7 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._query_template = query_template
self._doc_template = doc_template
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._model: Any = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -130,15 +134,19 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
attn_mode,
)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model = AutoModelForMaskedLM.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -498,6 +506,7 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
cached_path = try_to_load_from_cache(
repo_id=self._model_name_or_path,
filename="idf.json",
+ revision=self._revision,
)
# try_to_load_from_cache returns a str path, None (not cached),
# or _CACHED_NO_EXIST sentinel (explicitly absent). Only a str
@@ -509,6 +518,7 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
cached_path = hf_hub_download(
repo_id=self._model_name_or_path,
filename="idf.json",
+ revision=self._revision,
)
if not isinstance(cached_path, str):
logger.warning("IDF not found for %s", self._model_name_or_path)
diff --git a/packages/sie_server/src/sie_server/adapters/jina_flash_cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/jina_flash_cross_encoder/__init__.py
index 5f693fb50..12c93e698 100644
--- a/packages/sie_server/src/sie_server/adapters/jina_flash_cross_encoder/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/jina_flash_cross_encoder/__init__.py
@@ -45,6 +45,7 @@ class JinaFlashCrossEncoderAdapter(FlashBaseAdapter):
trust_remote_code: bool = True,
max_seq_length: int = 8192,
compute_precision: ComputePrecision = "bfloat16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -54,6 +55,8 @@ class JinaFlashCrossEncoderAdapter(FlashBaseAdapter):
trust_remote_code: Whether to trust remote code (required for Jina).
max_seq_length: Maximum sequence length for query+document.
compute_precision: Compute precision (bfloat16 recommended for Jina).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored).
"""
_ = kwargs
@@ -61,6 +64,7 @@ class JinaFlashCrossEncoderAdapter(FlashBaseAdapter):
self._trust_remote_code = trust_remote_code
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
+ self._revision = revision
# Loaded state
self._model: Any = None
@@ -91,10 +95,14 @@ class JinaFlashCrossEncoderAdapter(FlashBaseAdapter):
self._dtype,
)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
# Load tokenizer
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# Load model - let it use its built-in flash attention (use_flash_attn in config)
@@ -102,7 +110,7 @@ class JinaFlashCrossEncoderAdapter(FlashBaseAdapter):
self._model = AutoModelForSequenceClassification.from_pretrained(
self._model_name_or_path,
torch_dtype=self._dtype,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
diff --git a/packages/sie_server/src/sie_server/adapters/lighton_ocr/__init__.py b/packages/sie_server/src/sie_server/adapters/lighton_ocr/__init__.py
index 56f984f02..3deef167b 100644
--- a/packages/sie_server/src/sie_server/adapters/lighton_ocr/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/lighton_ocr/__init__.py
@@ -48,6 +48,7 @@ class LightOnOCRAdapter(ModelAdapter):
max_new_tokens: int = 4096,
num_beams: int = 1,
attn_implementation: str = "sdpa",
+ revision: str | None = None,
system_prompt: str = DEFAULT_SYSTEM_PROMPT,
max_batch_images: int = 4,
**kwargs: Any,
@@ -60,6 +61,8 @@ class LightOnOCRAdapter(ModelAdapter):
max_new_tokens: Maximum tokens to generate.
num_beams: Number of beams for beam search.
attn_implementation: Attention implementation - "eager", "sdpa", or "flash_attention_2".
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when loading model artifacts.
+ Forwarded to ``from_pretrained(..., revision=...)``.
system_prompt: System prompt for the chat template.
max_batch_images: Max images per batched ``generate()`` call. Bounds KV-cache /
vision-activation memory so a large incoming batch cannot OOM (issue #33,
@@ -74,6 +77,7 @@ class LightOnOCRAdapter(ModelAdapter):
self._max_new_tokens = max_new_tokens
self._num_beams = num_beams
self._attn_implementation = attn_implementation
+ self._revision = revision
self._system_prompt = system_prompt
self._max_batch_images = max(1, max_batch_images)
@@ -110,6 +114,10 @@ class LightOnOCRAdapter(ModelAdapter):
dtype = self._resolve_dtype(device)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
logger.info(
"Loading LightOnOCR model %s on device=%s with dtype=%s, attn=%s",
self._model_name_or_path,
@@ -120,6 +128,7 @@ class LightOnOCRAdapter(ModelAdapter):
self._processor = LightOnOcrProcessor.from_pretrained(
self._model_name_or_path,
+ **shared_kwargs,
)
# Batched generation left-pads input_ids (prompt length varies with image
@@ -134,6 +143,7 @@ class LightOnOCRAdapter(ModelAdapter):
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation=self._attn_implementation,
+ **shared_kwargs,
)
self._model.to(device) # ty: ignore[invalid-argument-type]
diff --git a/packages/sie_server/src/sie_server/adapters/mlx/generation.py b/packages/sie_server/src/sie_server/adapters/mlx/generation.py
index d2f74cd9b..c380ae1af 100644
--- a/packages/sie_server/src/sie_server/adapters/mlx/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/mlx/generation.py
@@ -115,6 +115,12 @@ class MLXGenerationAdapter(GenerationAdapter):
stop_tokens: list[str] | None = None,
served_model_name: str | None = None,
trust_remote_code: bool = False,
+ # Pinned HuggingFace revision. Accepted for constructor parity with the
+ # SGLang adapters, but NOT forwarded: this backend serves the pre-pinned
+ # ``mlx_repo`` (not ``model_name_or_path``) via an ``mlx_lm.server``
+ # subprocess whose argv is built in ``_server.build_launch_command``,
+ # which exposes no ``--revision`` seam. No pinned YAML routes here today.
+ revision: str | None = None,
startup_timeout_s: float | None = None,
**kwargs: Any, # accept (and drop) CUDA/SGLang-only kwargs from the swap
) -> None:
@@ -131,6 +137,7 @@ class MLXGenerationAdapter(GenerationAdapter):
self._stop_tokens = stop_tokens or []
self._served_model_name = served_model_name or self._model_name_or_path
self._trust_remote_code = trust_remote_code
+ self._revision = revision # stored for parity; mlx_lm.server exposes no revision seam (see __init__)
self._startup_timeout_s = startup_timeout_s
self._process: subprocess.Popen[bytes] | None = None
diff --git a/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py
index 69986248e..a23170bee 100644
--- a/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py
@@ -60,6 +60,7 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
query_template: str | None = None,
doc_template: str | None = None,
trust_remote_code: bool = True,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -73,6 +74,8 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
query_template: Optional template for queries, e.g. "query: {text}".
doc_template: Optional template for documents, e.g. "passage: {text}".
trust_remote_code: Whether to trust remote code for model/tokenizer.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
@@ -84,6 +87,7 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._query_template = query_template
self._doc_template = doc_template
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._model: Any = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -115,9 +119,13 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._pooling,
)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# Load model with eager attention — we handle flash attention manually
@@ -125,7 +133,7 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation="eager",
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -261,12 +269,25 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Transfer 16-bit to CPU first, then upcast to float32 — halves GPU->CPU bandwidth
dense_np = dense_vecs.cpu().float().numpy()
- return EncodeOutput(
+ output = EncodeOutput(
dense=dense_np,
batch_size=len(items),
is_query=is_query,
dense_dim=self._dense_dim,
)
+ # Unit-meter seam (§7.3): this adapter owns tokenization (the registry
+ # preprocessor for flash adapters is a char-count ESTIMATOR) AND applies
+ # the model's query/doc template before tokenizing (e.g. modernbert-embed's
+ # ``search_query:``/``search_document:``), so the real post-template,
+ # post-truncation per-item token counts exist only here. ``seq_lengths``
+ # is the exact ``len(input_ids)`` the model processed; expose it through
+ # ``EncodeOutput.extra`` (the designated adapter-extension point) aligned
+ # 1:1 with ``items``. The encode pipeline forwards these for metering, in
+ # preference to the base ``count_input_tokens`` fallback which re-tokenizes
+ # raw ``item.text`` and would undercount by the template's tokens (a no-op
+ # for templateless models like gte-modernbert/granite). Mirrors ``bert_flash``.
+ output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
+ return output
def _build_position_ids(self, seq_lengths_tensor: torch.Tensor, total_tokens: int) -> torch.Tensor:
"""Build position IDs for packed sequences (vectorized).
diff --git a/packages/sie_server/src/sie_server/adapters/modernbert_flash_cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/modernbert_flash_cross_encoder/__init__.py
index 6d7973002..ac9e0aaf1 100644
--- a/packages/sie_server/src/sie_server/adapters/modernbert_flash_cross_encoder/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/modernbert_flash_cross_encoder/__init__.py
@@ -45,6 +45,7 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
trust_remote_code: bool = True,
max_seq_length: int = 8192,
compute_precision: ComputePrecision = "bfloat16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -54,6 +55,8 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
trust_remote_code: Whether to trust remote code.
max_seq_length: Maximum sequence length for query+document.
compute_precision: Compute precision (bfloat16 recommended for ModernBERT).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored).
"""
_ = kwargs
@@ -61,6 +64,7 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
self._trust_remote_code = trust_remote_code
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
+ self._revision = revision
# Loaded state
self._model: Any = None
@@ -91,10 +95,14 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
self._dtype,
)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
# Load tokenizer
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# Load model with flash_attention_2 to use model's optimized rotary embeddings
@@ -102,7 +110,7 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
self._model_name_or_path,
torch_dtype=self._dtype,
attn_implementation="flash_attention_2",
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
diff --git a/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py b/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py
index b38d02448..987aee0ba 100644
--- a/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/nemo_colembed/__init__.py
@@ -84,6 +84,7 @@ class NemoColEmbedAdapter(BaseAdapter):
*,
normalize: bool = True,
compute_precision: ComputePrecision = "bfloat16",
+ revision: str | None = None,
max_seq_length: int | None = None,
batch_size: int = 8,
muvera_config: dict[str, Any] | None = None,
@@ -95,6 +96,8 @@ class NemoColEmbedAdapter(BaseAdapter):
model_name_or_path: HuggingFace model ID or local path.
normalize: Whether to L2-normalize embeddings.
compute_precision: Compute precision for inference.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
max_seq_length: Ignored - model uses dynamic sequence length.
batch_size: Batch size for encoding (passed to model methods).
muvera_config: MUVERA configuration (passed to postprocessor, not used by adapter).
@@ -103,6 +106,7 @@ class NemoColEmbedAdapter(BaseAdapter):
self._model_name_or_path = str(model_name_or_path)
self._normalize = normalize
self._compute_precision = compute_precision
+ self._revision = revision
self._batch_size = batch_size
self._model: Any = None
@@ -144,14 +148,19 @@ class NemoColEmbedAdapter(BaseAdapter):
# top (v1 ships its own modeling file that does this)
# - AttributeError: v1's config.to_dict() bug fires inside transformers'
# to_diff_dict() comparison when vision_config is absent
+ automodel_kwargs: dict[str, Any] = {
+ "trust_remote_code": True,
+ "device_map": device,
+ "torch_dtype": dtype,
+ "attn_implementation": attn_impl,
+ }
+ if self._revision is not None:
+ automodel_kwargs["revision"] = self._revision
loaded_via_v1_path = False
try:
self._model = AutoModel.from_pretrained(
self._model_name_or_path,
- trust_remote_code=True,
- device_map=device,
- torch_dtype=dtype,
- attn_implementation=attn_impl,
+ **automodel_kwargs,
)
except (KeyError, ValueError, ImportError, AttributeError) as automodel_err:
logger.info(
@@ -226,6 +235,7 @@ class NemoColEmbedAdapter(BaseAdapter):
"modeling_llama_nemoretrievercolembed.llama_NemoRetrieverColEmbed",
self._model_name_or_path,
trust_remote_code=True,
+ revision=self._revision,
)
# v1's config.to_dict() bug: assumes vision_config exists but it doesn't.
@@ -247,15 +257,20 @@ class NemoColEmbedAdapter(BaseAdapter):
output["model_type"] = self.__class__.model_type
return output
+ v1_kwargs: dict[str, Any] = {
+ "device_map": device,
+ "torch_dtype": dtype,
+ "attn_implementation": "flash_attention_2",
+ }
+ if self._revision is not None:
+ v1_kwargs["revision"] = self._revision
with _V1_TO_DICT_PATCH_LOCK:
original_to_dict = config_class.to_dict
config_class.to_dict = patched_to_dict
try:
return model_class.from_pretrained( # ty:ignore[unresolved-attribute]
self._model_name_or_path,
- device_map=device,
- torch_dtype=dtype,
- attn_implementation="flash_attention_2",
+ **v1_kwargs,
)
finally:
config_class.to_dict = original_to_dict
diff --git a/packages/sie_server/src/sie_server/adapters/nli_classification/__init__.py b/packages/sie_server/src/sie_server/adapters/nli_classification/__init__.py
index 9eadf8588..d0f50f498 100644
--- a/packages/sie_server/src/sie_server/adapters/nli_classification/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/nli_classification/__init__.py
@@ -52,6 +52,7 @@ class NLIClassificationAdapter(BaseAdapter):
hypothesis_template: str = "This text is about {}.",
multi_label: bool = False,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize NLI classification adapter.
@@ -64,12 +65,15 @@ class NLIClassificationAdapter(BaseAdapter):
multi_label: If True, allows multiple labels per text.
If False, forces single-label classification.
compute_precision: Precision for inference (float16, float32, bfloat16).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``pipeline(..., revision=...)``.
**kwargs: Additional arguments (ignored for compatibility).
"""
self._model_name_or_path = str(model_name_or_path)
self._hypothesis_template = hypothesis_template
self._multi_label = multi_label
self._compute_precision = compute_precision
+ self._revision = revision
self._pipeline: Pipeline | None = None
self._device: str | None = None
@@ -102,12 +106,14 @@ class NLIClassificationAdapter(BaseAdapter):
else:
torch_dtype = torch.float32
- self._pipeline = pipeline(
- "zero-shot-classification",
- model=self._model_name_or_path,
- device=device_idx,
- dtype=torch_dtype,
- )
+ pipeline_kwargs: dict[str, Any] = {
+ "model": self._model_name_or_path,
+ "device": device_idx,
+ "dtype": torch_dtype,
+ }
+ if self._revision is not None:
+ pipeline_kwargs["revision"] = self._revision
+ self._pipeline = pipeline("zero-shot-classification", **pipeline_kwargs)
def _extract_text(self, item: Item) -> str:
"""Extract text from an item.
diff --git a/packages/sie_server/src/sie_server/adapters/nli_classification_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/nli_classification_flash/__init__.py
index 662cbf528..e6dc6c462 100644
--- a/packages/sie_server/src/sie_server/adapters/nli_classification_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/nli_classification_flash/__init__.py
@@ -46,6 +46,7 @@ class NLIClassificationFlashAdapter(FlashBaseAdapter):
multi_label: bool = False,
max_length: int = 512,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize native NLI classification adapter.
@@ -58,6 +59,8 @@ class NLIClassificationFlashAdapter(FlashBaseAdapter):
If False, use softmax for mutually exclusive labels.
max_length: Maximum sequence length for tokenization.
compute_precision: Precision for inference (float16, bfloat16, float32).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored for compatibility).
"""
_ = kwargs
@@ -66,6 +69,7 @@ class NLIClassificationFlashAdapter(FlashBaseAdapter):
self._multi_label = multi_label
self._max_length = max_length
self._compute_precision = compute_precision
+ self._revision = revision
# Loaded state
self._model: Any = None
@@ -95,12 +99,17 @@ class NLIClassificationFlashAdapter(FlashBaseAdapter):
device,
)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
# Load tokenizer
- self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path, **shared_kwargs)
# Load model (use 'dtype' not deprecated 'torch_dtype')
self._model = AutoModelForSequenceClassification.from_pretrained(
self._model_name_or_path,
+ **shared_kwargs,
)
self._model = self._model.to(dtype=self._dtype)
self._model.to(device)
diff --git a/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py
index 75100f6db..658ef7953 100644
--- a/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py
@@ -13,7 +13,6 @@ from sie_server.adapters._flash_pack import build_position_ids, mean_pool_packed
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision, PoolingStrategy
from sie_server.adapters._utils import apply_rotary_pos_emb, extract_texts, validate_output_types
-from sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin
from sie_server.core.inference_output import EncodeOutput
from sie_server.types.inputs import Item
@@ -25,11 +24,20 @@ logger = logging.getLogger(__name__)
_ERR_CPU_NOT_SUPPORTED = "NomicFlashAdapter requires CUDA. Use pytorch_embedding adapter for CPU."
-class NomicFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
+class NomicFlashAdapter(FlashBaseAdapter):
"""Nomic BERT MoE adapter using Flash Attention 2 with variable-length sequences.
This adapter eliminates padding waste by packing sequences and using
flash_attn_varlen_func. Implements MoE routing in pure PyTorch.
+
+ No LoRA support (``supports_lora() == False``, the base default): weights
+ are hand-loaded from raw safetensors into plain tensor dicts
+ (``self._layers``) and the forward is fully hand-rolled with ``F.linear``
+ — there is no wrappable ``self._model`` module, so ``PEFTLoRAMixin`` could
+ neither load a LoRA (``load_lora`` needs ``self._model``) nor have its
+ delta seen by this forward. Advertising support here previously meant a
+ customer LoRA was silently non-functional. Per the LoRA capability audit,
+ LoRA on this family goes through the merge-at-staging path instead.
"""
fallback_adapter_path: ClassVar[str | None] = "sentence_transformer:SentenceTransformerDenseAdapter"
@@ -63,6 +71,7 @@ class NomicFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
pooling: PoolingStrategy = "mean",
query_template: str | None = None,
doc_template: str | None = None,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -75,6 +84,8 @@ class NomicFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
pooling: Pooling strategy - "cls" or "mean".
query_template: Template for queries, e.g. "search_query: {text}".
doc_template: Template for documents, e.g. "search_document: {text}".
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
@@ -85,6 +96,7 @@ class NomicFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._pooling = pooling
self._query_template = query_template or "search_query: {text}"
self._doc_template = doc_template or "search_document: {text}"
+ self._revision = revision
# Model components (loaded in load())
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -135,11 +147,15 @@ class NomicFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._pooling,
)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
# Load tokenizer
- self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path, **shared_kwargs)
# Download and load weights
- model_path = hf_hub_download(self._model_name_or_path, "model.safetensors")
+ model_path = hf_hub_download(self._model_name_or_path, "model.safetensors", **shared_kwargs)
self._load_weights(model_path)
self._dense_dim = self._hidden_size
@@ -295,12 +311,25 @@ class NomicFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Convert to numpy and return EncodeOutput
dense_np = dense_vecs.float().cpu().numpy()
- return EncodeOutput(
+ output = EncodeOutput(
dense=dense_np,
batch_size=len(items),
is_query=is_query,
dense_dim=self._dense_dim,
)
+ # Unit-meter seam (§7.3): this adapter owns tokenization (the registry
+ # preprocessor for flash adapters is a char-count ESTIMATOR) AND always
+ # applies a query/doc template before tokenizing (Nomic defaults to
+ # ``search_query:``/``search_document:``), so the real post-template,
+ # post-truncation per-item token counts exist only here. ``seq_lengths``
+ # is the exact ``len(input_ids)`` the model processed; expose it through
+ # ``EncodeOutput.extra`` (the designated adapter-extension point) aligned
+ # 1:1 with ``items``. The encode pipeline forwards these for metering, in
+ # preference to the base ``count_input_tokens`` fallback which re-tokenizes
+ # raw ``item.text`` and would undercount by the template's tokens. Mirrors
+ # ``bert_flash``.
+ output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
+ return output
def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:
"""Build position IDs for packed sequences (starting from 0 for each)."""
diff --git a/packages/sie_server/src/sie_server/adapters/owlv2/__init__.py b/packages/sie_server/src/sie_server/adapters/owlv2/__init__.py
index 927527169..6605d4eb9 100644
--- a/packages/sie_server/src/sie_server/adapters/owlv2/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/owlv2/__init__.py
@@ -83,6 +83,7 @@ class Owlv2Adapter(BaseAdapter):
"_model_name_or_path",
"_preprocessor",
"_processor",
+ "_revision",
"_score_threshold",
)
@@ -91,12 +92,14 @@ class Owlv2Adapter(BaseAdapter):
model_name_or_path: str | Path,
*,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
score_threshold: float = 0.1,
**kwargs: Any,
) -> None:
del kwargs
self._model_name_or_path = str(model_name_or_path)
self._compute_precision = compute_precision
+ self._revision = revision
self._score_threshold = score_threshold
self._model: Any = None
@@ -115,6 +118,10 @@ class Owlv2Adapter(BaseAdapter):
self._device_type = "cuda" if device.startswith("cuda") else "cpu"
dtype = self._resolve_dtype()
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
logger.info(
"Loading OWL-v2 model %s on device=%s with dtype=%s",
self._model_name_or_path,
@@ -122,10 +129,11 @@ class Owlv2Adapter(BaseAdapter):
dtype,
)
- self._processor = Owlv2Processor.from_pretrained(self._model_name_or_path)
+ self._processor = Owlv2Processor.from_pretrained(self._model_name_or_path, **shared_kwargs)
self._model = Owlv2ForObjectDetection.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
diff --git a/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py b/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py
index c9e62f755..a34e171ad 100644
--- a/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py
@@ -6,6 +6,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
import torch
+from huggingface_hub import snapshot_download
from sie_server.adapters._base_adapter import BaseAdapter
from sie_server.adapters._spec import AdapterSpec
@@ -137,13 +138,15 @@ class PaddleOCRVLAdapter(BaseAdapter):
self._device = device
dtype = self._resolve_dtype_for(device)
- shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
- if self._revision is not None:
- shared_kwargs["revision"] = self._revision
+ # Resolve to a local snapshot dir so from_pretrained reads config files
+ # straight from disk instead of re-probing the Hub by a dropped revision
+ # (see _resolve_model_dir for why AutoProcessor breaks offline otherwise).
+ model_dir = self._resolve_model_dir()
logger.info(
- "Loading PaddleOCR-VL model %s on device=%s dtype=%s revision=%s attn=%s",
+ "Loading PaddleOCR-VL model %s (dir=%s) on device=%s dtype=%s revision=%s attn=%s",
self._model_name_or_path,
+ model_dir,
device,
dtype,
self._revision,
@@ -151,18 +154,18 @@ class PaddleOCRVLAdapter(BaseAdapter):
)
self._processor = AutoProcessor.from_pretrained(
- self._model_name_or_path,
- **shared_kwargs,
+ model_dir,
+ trust_remote_code=self._trust_remote_code,
)
# Model's ``auto_map`` registers ``AutoModelForCausalLM`` (not
# ``AutoModelForImageTextToText``), even though the README suggests
# the latter. Using the registered class avoids "Unrecognized
# configuration class" on transformers 4.57.
self._model = AutoModelForCausalLM.from_pretrained(
- self._model_name_or_path,
+ model_dir,
dtype=dtype,
attn_implementation=self._attn_implementation,
- **shared_kwargs,
+ trust_remote_code=self._trust_remote_code,
)
self._model.to(device) # ty: ignore[invalid-argument-type]
self._model.eval()
@@ -176,6 +179,35 @@ class PaddleOCRVLAdapter(BaseAdapter):
self._create_preprocessor()
logger.info("PaddleOCR-VL model loaded successfully")
+ def _resolve_model_dir(self) -> str:
+ """Resolve the model reference to a local snapshot directory.
+
+ Works around a transformers 4.57.x quirk that silently breaks offline
+ loading of ``trust_remote_code`` processors. ``AutoProcessor.from_pretrained``
+ probes for the processor/preprocessor/tokenizer config via ``cached_file``,
+ but filters its kwargs by ``cached_file``'s *named* parameters — and
+ ``cached_file(path_or_repo_id, filename, **kwargs)`` swallows ``revision``
+ into ``**kwargs``. So ``revision`` is dropped and every probe defaults to
+ ``main``. Offline (the Modal lane bakes ``HF_HUB_OFFLINE=1``) only the
+ pinned revision is staged and no ``main`` snapshot exists, so all probes
+ miss, the custom-processor ``auto_map`` is never discovered, and
+ AutoProcessor silently returns the bare tokenizer (``LlamaTokenizerFast``)
+ — which has no ``image_processor`` and cannot preprocess images.
+
+ Passing an already-resolved local directory sidesteps the probe: config
+ files are read straight from disk, revision-free. ``snapshot_download``
+ honours ``HF_HUB_OFFLINE`` (cache-only offline, download when online), so
+ this is safe in both the Modal lane and local dev. A ``weights_path`` that
+ already points at a local directory is returned unchanged.
+ """
+ path = Path(self._model_name_or_path)
+ if path.is_dir():
+ return str(path)
+ download_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ download_kwargs["revision"] = self._revision
+ return snapshot_download(self._model_name_or_path, **download_kwargs)
+
def _resolve_dtype_for(self, device: str) -> torch.dtype:
if not device.startswith("cuda"):
return torch.float32
diff --git a/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py b/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py
index 99bb21f37..19785b935 100644
--- a/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py
+++ b/packages/sie_server/src/sie_server/adapters/peft_lora_mixin.py
@@ -18,14 +18,83 @@ import gc
import hashlib
import logging
import re
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, ClassVar
if TYPE_CHECKING:
+ from collections.abc import Collection
+
from peft import PeftModel
logger = logging.getLogger(__name__)
+def validate_lora_target_modules(
+ lora_path: str,
+ target_modules: Any,
+ called_module_names: Collection[str],
+) -> None:
+ """Reject a LoRA whose ``target_modules`` misses every module the serving
+ forward actually calls.
+
+ Manual (module-call) flash forwards invoke a fixed set of submodules
+ directly instead of the model's top-level ``forward``. PEFT wraps exactly
+ the modules named in the LoRA's ``target_modules`` — so a LoRA targeting
+ only modules the manual forward never calls (e.g. ``pooler.dense``) is
+ applied to nothing and serves base weights with **zero error** (the
+ negative-control failure mode in the LoRA capability audit §3). This check
+ makes that mismatch fail loudly at load/staging time instead.
+
+ Args:
+ lora_path: Public LoRA id (HF/local path), for error messages.
+ target_modules: The PEFT config's ``target_modules`` — typically a
+ list/set of module-name suffixes (``"query"``, ``"q_proj"``,
+ possibly dotted like ``"encoder.layer.0.attention.self.query"``)
+ or a regex string matched against full module paths.
+ called_module_names: Leaf module names the adapter's serving forward
+ actually invokes (e.g. ``{"query", "key", "value", "dense"}``).
+
+ Raises:
+ ValueError: If ``target_modules`` is a collection and none of its
+ entries resolve (by leaf name) to a called module. A regex-string
+ ``target_modules`` that matches no called leaf name only warns —
+ regexes may legitimately target full dotted paths this check
+ cannot resolve without the model instance.
+ """
+ if not target_modules or not called_module_names:
+ # Nothing to check (PEFT will resolve/refuse its own defaults).
+ return
+
+ called = set(called_module_names)
+
+ if isinstance(target_modules, str):
+ # PEFT regex form (fullmatched against full module paths). Leaf names
+ # are all we have here, so treat no-match as a warning, not an error.
+ if not any(re.fullmatch(target_modules, name) for name in called):
+ logger.warning(
+ "LoRA '%s' declares regex target_modules %r which matches none "
+ "of the modules the serving forward calls (%s) — if it also "
+ "matches no full module path, the LoRA will have no effect",
+ lora_path,
+ target_modules,
+ sorted(called),
+ )
+ return
+
+ targets = [str(t) for t in target_modules]
+ # Compare by leaf component: PEFT matches suffixes, and dotted targets
+ # ("encoder.layer.0.attention.self.query") end in the module's leaf name.
+ if any(t.rsplit(".", 1)[-1] in called for t in targets):
+ return
+
+ msg = (
+ f"LoRA '{lora_path}' targets modules {sorted(targets)!r}, but the "
+ f"serving forward only calls {sorted(called)!r} — the LoRA would be "
+ f"silently ignored (zero effect). Retrain/export the LoRA against the "
+ f"called projections, or serve it via the merge-at-staging path."
+ )
+ raise ValueError(msg)
+
+
class PEFTLoRAMixin:
"""Mixin providing PEFT-based LoRA support for PyTorch adapters.
@@ -60,6 +129,16 @@ class PEFTLoRAMixin:
_loaded_loras: set[str] # Track which LoRAs are loaded
_lora_adapter_names: dict[str, str] # Public LoRA id -> PEFT-safe adapter name
+ #: Leaf names of the submodules the adapter's serving forward actually
+ #: invokes (e.g. ``frozenset({"query", "key", "value", "dense"})``).
+ #: ``None`` (default) skips the staging-side ``target_modules`` check —
+ #: appropriate for adapters that run the model's standard ``forward``,
+ #: where every PEFT-wrapped module is reached. Manual/module-call flash
+ #: adapters should declare their called set so a LoRA whose
+ #: ``target_modules`` intersect none of them is rejected at load instead
+ #: of silently serving base weights (LoRA capability audit §3).
+ lora_called_module_names: ClassVar[frozenset[str] | None] = None
+
def __init_subclass__(cls, **kwargs: Any) -> None:
"""Initialize _loaded_loras set for subclasses."""
super().__init_subclass__(**kwargs)
@@ -133,6 +212,11 @@ class PEFTLoRAMixin:
raise RuntimeError(msg) from e
logger.info("Loading LoRA adapter: %s", lora_path)
+
+ # Fail loudly on a LoRA the serving forward would silently ignore
+ # (target_modules ∩ called modules = ∅) before any PEFT wrapping.
+ self._validate_lora_target_modules(lora_path)
+
peft_adapter_name = self._peft_adapter_name(lora_path)
if self._peft_model is None:
@@ -167,6 +251,37 @@ class PEFTLoRAMixin:
return memory_bytes
+ def _validate_lora_target_modules(self, lora_path: str) -> None:
+ """Check the LoRA's ``target_modules`` against the called-module set.
+
+ No-op when the adapter does not declare
+ :attr:`lora_called_module_names` (standard-forward adapters). Reads
+ only the LoRA's ``adapter_config.json`` via ``PeftConfig`` — no
+ weights are loaded. A failure to *fetch* the config is logged and
+ skipped (the actual ``PeftModel`` load will surface the real error);
+ a fetched config whose targets miss every called module raises
+ ``ValueError`` (see :func:`validate_lora_target_modules`).
+ """
+ called = self.lora_called_module_names
+ if not called:
+ return
+
+ try:
+ from peft import PeftConfig
+
+ peft_config = PeftConfig.from_pretrained(lora_path)
+ target_modules = getattr(peft_config, "target_modules", None)
+ except Exception as e: # noqa: BLE001 — config fetch is best-effort
+ logger.warning(
+ "Could not read PEFT config for LoRA '%s' to validate target_modules (%s); "
+ "skipping the check — the load itself will surface any real error",
+ lora_path,
+ e,
+ )
+ return
+
+ validate_lora_target_modules(lora_path, target_modules, called)
+
def unload_lora(self, lora_name: str) -> None:
"""Unload a LoRA adapter.
diff --git a/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py
index bdbe8dc03..e04b398f1 100644
--- a/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py
@@ -49,6 +49,7 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
normalize: bool = True,
max_seq_length: int = 8192,
compute_precision: ComputePrecision = "bfloat16",
+ revision: str | None = None,
pooling: PoolingStrategy = "mean",
query_template: str | None = None,
doc_template: str | None = None,
@@ -64,6 +65,8 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
normalize: Whether to L2-normalize dense embeddings.
max_seq_length: Maximum sequence length.
compute_precision: Compute precision (bfloat16 recommended for Qwen2).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
pooling: Pooling strategy - "cls", "mean", or "last".
query_template: Optional template for queries, e.g. "query: {text}".
doc_template: Optional template for documents, e.g. "passage: {text}".
@@ -82,6 +85,7 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._normalize = normalize
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
+ self._revision = revision
self._pooling = pooling
self._query_template = query_template
self._doc_template = doc_template
@@ -129,10 +133,14 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._pooling,
)
- self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path, **shared_kwargs)
# Load config first to disable optional xformers features
- config = AutoConfig.from_pretrained(self._model_name_or_path, trust_remote_code=True)
+ config = AutoConfig.from_pretrained(self._model_name_or_path, trust_remote_code=True, **shared_kwargs)
if hasattr(config, "use_memory_efficient_attention"):
config.use_memory_efficient_attention = False
if hasattr(config, "unpad_inputs"):
@@ -145,6 +153,7 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
torch_dtype=dtype,
attn_implementation="eager",
trust_remote_code=True,
+ **shared_kwargs,
)
# Disable KV cache for models using the legacy transformers cache API
@@ -175,9 +184,17 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
from huggingface_hub import hf_hub_download
from huggingface_hub.errors import EntryNotFoundError
+ # Dense projection artifacts live in the SAME base repo, so the pinned
+ # revision applies to these downloads too (but not to the local
+ # json/torch/safetensors reads of the already-downloaded files).
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
config_file = hf_hub_download(
self._model_name_or_path,
f"{self._dense_projection_path}/config.json",
+ **shared_kwargs,
)
with open(config_file) as f:
@@ -193,12 +210,14 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
weights_path = hf_hub_download(
self._model_name_or_path,
f"{self._dense_projection_path}/model.safetensors",
+ **shared_kwargs,
)
state_dict = safetensors.torch.load_file(weights_path)
except (EntryNotFoundError, OSError):
weights_path = hf_hub_download(
self._model_name_or_path,
f"{self._dense_projection_path}/pytorch_model.bin",
+ **shared_kwargs,
)
state_dict = torch.load(weights_path, map_location="cpu", weights_only=True)
@@ -307,12 +326,22 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Convert to numpy and return EncodeOutput
dense_np = dense_vecs.float().cpu().numpy()
- return EncodeOutput(
+ output = EncodeOutput(
dense=dense_np,
batch_size=len(items),
is_query=is_query,
dense_dim=self._dense_dim,
)
+ # Unit-meter seam: this adapter owns tokenization (the registry-level
+ # preprocessor for flash adapters is a char-count ESTIMATOR) and applies
+ # ``extract_texts`` templating/instruction before tokenizing, so the real
+ # per-item token counts — including those template/instruction tokens —
+ # exist only here. Expose them through ``EncodeOutput.extra`` — the
+ # designated adapter-extension point — aligned 1:1 with ``items``; the
+ # encode pipeline forwards them to the result path for metering (never
+ # estimates from raw ``item.text``).
+ output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
+ return output
def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:
"""Build position IDs for packed sequences (each restarts at 0)."""
diff --git a/packages/sie_server/src/sie_server/adapters/qwen2_flash_cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen2_flash_cross_encoder/__init__.py
index e0a917d5b..94b1ec331 100644
--- a/packages/sie_server/src/sie_server/adapters/qwen2_flash_cross_encoder/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/qwen2_flash_cross_encoder/__init__.py
@@ -92,6 +92,7 @@ class Qwen2FlashCrossEncoderAdapter(FlashBaseAdapter):
trust_remote_code: bool = False,
max_seq_length: int = 8192,
compute_precision: ComputePrecision = "bfloat16",
+ revision: str | None = None,
yes_token: str = "1", # noqa: S107
no_token: str = "0", # noqa: S107
input_format: InputFormat = "mxbai",
@@ -106,6 +107,8 @@ class Qwen2FlashCrossEncoderAdapter(FlashBaseAdapter):
trust_remote_code: Whether to trust remote code.
max_seq_length: Maximum sequence length for query+document.
compute_precision: Compute precision (bfloat16 recommended).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
yes_token: Text whose first token ID is the "positive" logit.
no_token: Text whose first token ID is the "negative" logit.
input_format: Template preset — ``"mxbai"`` or ``"qwen3"``.
@@ -120,6 +123,7 @@ class Qwen2FlashCrossEncoderAdapter(FlashBaseAdapter):
self._trust_remote_code = trust_remote_code
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
+ self._revision = revision
# Configurable template / scoring params
self._yes_token: str = yes_token
@@ -168,10 +172,14 @@ class Qwen2FlashCrossEncoderAdapter(FlashBaseAdapter):
self._score_mode,
)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
# Load tokenizer
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# Load model with eager attention - we handle flash attention manually
@@ -179,7 +187,7 @@ class Qwen2FlashCrossEncoderAdapter(FlashBaseAdapter):
self._model_name_or_path,
torch_dtype=self._dtype,
attn_implementation="eager",
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
diff --git a/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py
index f33e2c45d..11e1d922d 100644
--- a/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py
@@ -118,6 +118,7 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):
normalize: bool = True,
compute_precision: ComputePrecision = "bfloat16",
trust_remote_code: bool = False,
+ revision: str | None = None,
max_seq_length: int | None = None,
pooling: str = "last",
default_instruction: str = _DEFAULT_INSTRUCTION,
@@ -131,6 +132,7 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):
self._normalize = normalize
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._max_seq_length = max_seq_length
self._pooling = pooling
self._default_instruction = default_instruction
@@ -163,6 +165,8 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):
"min_pixels": 256 * 28 * 28,
"max_pixels": 1280 * 28 * 28,
}
+ if self._revision is not None:
+ proc_kwargs["revision"] = self._revision
self._processor = AutoProcessor.from_pretrained(
self._model_name_or_path,
**proc_kwargs,
@@ -177,6 +181,8 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):
}
if attn_impl is not None:
load_kwargs["attn_implementation"] = attn_impl
+ if self._revision is not None:
+ load_kwargs["revision"] = self._revision
self._model = Qwen3VLForConditionalGeneration.from_pretrained(
self._model_name_or_path,
diff --git a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py
index f51e71487..4b16ea759 100644
--- a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py
@@ -103,12 +103,14 @@ class Qwen3VLRerankerAdapter(BaseAdapter):
*,
compute_precision: ComputePrecision = "bfloat16",
trust_remote_code: bool = False,
+ revision: str | None = None,
max_seq_length: int | None = None,
default_instruction: str = _DEFAULT_INSTRUCTION,
) -> None:
self._model_name_or_path = str(model_name_or_path)
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._max_seq_length = max_seq_length
self._default_instruction = default_instruction
@@ -144,6 +146,7 @@ class Qwen3VLRerankerAdapter(BaseAdapter):
trust_remote_code=self._trust_remote_code,
min_pixels=256 * 28 * 28,
max_pixels=1280 * 28 * 28,
+ revision=self._revision,
)
except (TypeError, OSError) as exc:
logger.info(
@@ -151,7 +154,10 @@ class Qwen3VLRerankerAdapter(BaseAdapter):
self._model_name_or_path,
exc,
)
- # Load processor from base model (same vision architecture)
+ # Load processor from base model (same vision architecture).
+ # NOTE: no ``revision`` here — this is a different repo than
+ # ``self._model_name_or_path``, so the pinned revision (a ref in the
+ # reranker repo) does not apply to the base model's artifacts.
base_model = "Qwen/Qwen3-VL-2B-Instruct"
self._processor = AutoProcessor.from_pretrained(
base_model,
@@ -164,6 +170,7 @@ class Qwen3VLRerankerAdapter(BaseAdapter):
self._processor.tokenizer = AutoTokenizer.from_pretrained( # ty: ignore[unresolved-attribute]
self._model_name_or_path,
trust_remote_code=self._trust_remote_code,
+ revision=self._revision,
)
if self._max_seq_length is not None and hasattr(self._processor, "tokenizer"):
@@ -176,6 +183,8 @@ class Qwen3VLRerankerAdapter(BaseAdapter):
}
if attn_impl is not None:
load_kwargs["attn_implementation"] = attn_impl
+ if self._revision is not None:
+ load_kwargs["revision"] = self._revision
self._model = Qwen3VLForConditionalGeneration.from_pretrained(
self._model_name_or_path,
diff --git a/packages/sie_server/src/sie_server/adapters/rope_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/rope_flash/__init__.py
index 9d7e23165..77735b600 100644
--- a/packages/sie_server/src/sie_server/adapters/rope_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/rope_flash/__init__.py
@@ -52,6 +52,7 @@ class RoPEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
query_template: str | None = None,
doc_template: str | None = None,
uses_legacy_transformers_cache: bool = False,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -67,6 +68,8 @@ class RoPEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
uses_legacy_transformers_cache: If True, disable the KV cache after
loading by setting model.config.use_cache = False. Required for
models that use the legacy transformers cache API (pre-4.54).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
@@ -78,6 +81,7 @@ class RoPEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._query_template = query_template
self._doc_template = doc_template
self._uses_legacy_transformers_cache = uses_legacy_transformers_cache
+ self._revision = revision
self._model: Any = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -110,12 +114,16 @@ class RoPEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._pooling,
)
- self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path, **shared_kwargs)
# Load config first to disable optional xformers features
# Some models (e.g., stella_en_400M_v5) have these enabled in their saved config
# but we replace attention with flash_attn_varlen_func anyway
- config = AutoConfig.from_pretrained(self._model_name_or_path, trust_remote_code=True)
+ config = AutoConfig.from_pretrained(self._model_name_or_path, trust_remote_code=True, **shared_kwargs)
if hasattr(config, "use_memory_efficient_attention"):
config.use_memory_efficient_attention = False
if hasattr(config, "unpad_inputs"):
@@ -128,6 +136,7 @@ class RoPEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
torch_dtype=dtype,
attn_implementation="eager",
trust_remote_code=True,
+ **shared_kwargs,
)
# Disable KV cache for models using the legacy transformers cache API
@@ -240,12 +249,25 @@ class RoPEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Convert to numpy and return EncodeOutput
dense_np = dense_vecs.float().cpu().numpy()
- return EncodeOutput(
+ output = EncodeOutput(
dense=dense_np,
batch_size=len(items),
is_query=is_query,
dense_dim=self._dense_dim,
)
+ # Unit-meter seam (§7.3): this adapter owns tokenization (the registry
+ # preprocessor for flash adapters is a char-count ESTIMATOR) AND applies
+ # the model's query/doc template before tokenizing (e.g. arctic-embed-m's
+ # ``query: {text}``, stella's ``Instruct: ...``), so the real post-template,
+ # post-truncation per-item token counts exist only here. ``seq_lengths``
+ # is the exact ``len(input_ids)`` the model processed; expose it through
+ # ``EncodeOutput.extra`` (the designated adapter-extension point) aligned
+ # 1:1 with ``items``. The encode pipeline forwards these for metering, in
+ # preference to the base ``count_input_tokens`` fallback which re-tokenizes
+ # raw ``item.text`` and would undercount by the template's tokens (a no-op
+ # for templateless models like gte-multilingual-base). Mirrors ``bert_flash``.
+ output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
+ return output
def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:
"""Build position IDs for packed sequences.
diff --git a/packages/sie_server/src/sie_server/adapters/sentence_transformer/__init__.py b/packages/sie_server/src/sie_server/adapters/sentence_transformer/__init__.py
index 47e73e2eb..87312c1ec 100644
--- a/packages/sie_server/src/sie_server/adapters/sentence_transformer/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/sentence_transformer/__init__.py
@@ -43,6 +43,7 @@ class SentenceTransformerDenseAdapter(BaseAdapter):
max_seq_length: int | None = None,
compute_precision: ComputePrecision = "float16",
config_kwargs: dict[str, Any] | None = None,
+ revision: str | None = None,
**kwargs: Any, # Accept extra args from loader (e.g., pooling)
) -> None:
"""Initialize the adapter.
@@ -56,6 +57,8 @@ class SentenceTransformerDenseAdapter(BaseAdapter):
config_kwargs: Additional kwargs passed to model config (e.g., for models
with custom code that need specific settings like
{"use_memory_efficient_attention": False, "unpad_inputs": False}).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs # Unused, but accepted for loader compatibility
@@ -64,6 +67,7 @@ class SentenceTransformerDenseAdapter(BaseAdapter):
self._normalize = normalize
self._max_seq_length = max_seq_length
self._config_kwargs = config_kwargs
+ self._revision = revision
self._model: SentenceTransformer | None = None
self._device: str | None = None
@@ -76,12 +80,15 @@ class SentenceTransformerDenseAdapter(BaseAdapter):
device: Device string (e.g., "cuda:0", "cpu").
"""
self._device = device
- self._model = SentenceTransformer(
- self._model_name_or_path,
- device=device,
- trust_remote_code=self._trust_remote_code,
- config_kwargs=self._config_kwargs,
- )
+ load_kwargs: dict[str, Any] = {
+ "device": device,
+ "trust_remote_code": self._trust_remote_code,
+ "config_kwargs": self._config_kwargs,
+ }
+ # Omit revision unless pinned so the library default (main) is unchanged.
+ if self._revision is not None:
+ load_kwargs["revision"] = self._revision
+ self._model = SentenceTransformer(self._model_name_or_path, **load_kwargs)
if self._max_seq_length is not None:
self._model.max_seq_length = self._max_seq_length
@@ -197,6 +204,7 @@ class SentenceTransformerSparseAdapter(BaseAdapter):
trust_remote_code: bool = True,
max_seq_length: int | None = None,
compute_precision: ComputePrecision = "float16",
+ revision: str | None = None,
**kwargs: Any, # Accept extra args from loader (e.g., pooling)
) -> None:
"""Initialize the adapter.
@@ -206,12 +214,15 @@ class SentenceTransformerSparseAdapter(BaseAdapter):
trust_remote_code: Whether to trust remote code in model files.
max_seq_length: Override default max sequence length.
compute_precision: Compute precision (ignored, sentence-transformers handles internally).
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs # Unused, but accepted for loader compatibility
self._model_name_or_path = str(model_name_or_path)
self._trust_remote_code = trust_remote_code
self._max_seq_length = max_seq_length
+ self._revision = revision
self._model: SparseEncoder | None = None
self._device: str | None = None
@@ -224,11 +235,14 @@ class SentenceTransformerSparseAdapter(BaseAdapter):
device: Device string (e.g., "cuda:0", "cpu").
"""
self._device = device
- self._model = SparseEncoder(
- self._model_name_or_path,
- device=device,
- trust_remote_code=self._trust_remote_code,
- )
+ load_kwargs: dict[str, Any] = {
+ "device": device,
+ "trust_remote_code": self._trust_remote_code,
+ }
+ # Omit revision unless pinned so the library default (main) is unchanged.
+ if self._revision is not None:
+ load_kwargs["revision"] = self._revision
+ self._model = SparseEncoder(self._model_name_or_path, **load_kwargs)
if self._max_seq_length is not None:
self._model.max_seq_length = self._max_seq_length
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
index c4c8767bb..9d0405ca3 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
@@ -17,14 +17,18 @@ Engine API to avoid event loop conflicts with uvicorn/uvloop.
from __future__ import annotations
import logging
+import math
+import os
import subprocess
import sys
import tempfile
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import TYPE_CHECKING, Any
import numpy as np
import requests
+from requests.adapters import HTTPAdapter
from sie_server.adapters._base_adapter import BaseAdapter
from sie_server.adapters._spec import AdapterSpec
@@ -38,6 +42,36 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+# Fan-out knob for the SGLang embedding HTTP client. A single blocking
+# ``requests.post`` per ``encode()`` presents only ONE request to SGLang's
+# continuous batcher at a time — on the single-threaded serving loop (local
+# ``sie-server serve`` / ``ModelWorker`` runs one forward at a time) that
+# starves the batcher and the served path lands far below the engine knee
+# (measured Qwen3-Embedding-4B: A100 ~13k served vs 30.8k engine @ C=16;
+# evidence: commit ``9ecae860a``). Sharding a
+# batch into ``concurrency`` concurrent POSTs keeps that many requests in
+# flight so SGLang's batcher fills. ``1`` restores the legacy single-post
+# behavior (used to A/B the lift). Overridable per-deploy via the env var.
+_EMBED_CONCURRENCY_ENV = "SIE_SGLANG_EMBED_CONCURRENCY"
+_DEFAULT_EMBED_CONCURRENCY = 8
+
+
+def _resolve_embed_concurrency(configured: int | None) -> int:
+ """Resolve the embedding POST concurrency (env override wins, then config)."""
+ raw = os.environ.get(_EMBED_CONCURRENCY_ENV)
+ if raw is not None and raw.strip():
+ try:
+ value = int(raw)
+ except ValueError:
+ logger.warning("Ignoring invalid %s=%r; expected an integer", _EMBED_CONCURRENCY_ENV, raw)
+ else:
+ if value >= 1:
+ return value
+ logger.warning("Ignoring %s=%r; must be >= 1", _EMBED_CONCURRENCY_ENV, raw)
+ if configured is not None and configured >= 1:
+ return configured
+ return _DEFAULT_EMBED_CONCURRENCY
+
class SGLangEmbeddingAdapter(BaseAdapter):
"""Adapter for LLM embedding models using SGLang HTTP server backend.
@@ -84,6 +118,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
mem_fraction_static: float = 0.85,
compute_precision: ComputePrecision = "bfloat16",
trust_remote_code: bool = True,
+ revision: str | None = None,
query_template: str | None = None,
doc_template: str | None = None,
default_instruction: str | None = None,
@@ -93,6 +128,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
max_loras_per_batch: int = 8,
dense_dim: int | None = None,
startup_timeout_s: float | None = None,
+ embed_concurrency: int | None = None,
**kwargs: Any, # Accept extra args from loader (e.g., pooling)
) -> None:
r"""Initialize the adapter.
@@ -105,6 +141,9 @@ class SGLangEmbeddingAdapter(BaseAdapter):
Lower values leave more headroom for other models. Default 0.85.
compute_precision: Compute precision (bfloat16 recommended).
trust_remote_code: Whether to trust remote code in model files.
+ revision: Pinned HuggingFace revision (commit SHA / branch / tag) to serve.
+ Forwarded to ``sglang.launch_server`` as ``--revision`` so the served
+ weights match the YAML-pinned SHA. None serves the repo default.
query_template: Template for formatting queries. Use {instruction} and
{text} placeholders. Example: "Instruct: {instruction}\nQuery:{text}"
doc_template: Template for formatting documents. Use {text} placeholder.
@@ -138,6 +177,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._mem_fraction_static = mem_fraction_static
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._query_template = query_template
self._doc_template = doc_template
self._default_instruction = default_instruction
@@ -147,14 +187,27 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._lora_paths = lora_paths or {}
self._max_loras_per_batch = max_loras_per_batch
self._startup_timeout_s = _server.resolve_startup_timeout(startup_timeout_s)
+ self._embed_concurrency = _resolve_embed_concurrency(embed_concurrency)
self._process: subprocess.Popen[bytes] | None = None
self._server_url: str | None = None
+ # Shared HTTP client + thread pool for concurrent POSTs to SGLang. Only
+ # populated (in ``load``) when concurrency > 1; a single-post encode
+ # keeps using module-level ``requests.post`` so the concurrency=1 A/B
+ # baseline is byte-identical to the legacy path.
+ self._session: requests.Session | None = None
+ self._post_executor: ThreadPoolExecutor | None = None
self._device: str | None = None
self._configured_dense_dim: int | None = dense_dim
self._dense_dim: int | None = dense_dim
self._active_lora: str | None = None # Set by set_active_lora() before encode()
self._output_file: tempfile._TemporaryFileWrapper | None = None
+ # Lazy, weights-free tokenizer used ONLY for exact §7.3 input-token
+ # metering (see ``_get_metering_tokenizer`` / ``_stamp_input_token_counts``).
+ # Loaded on first ``encode`` and cached; a load failure degrades to the
+ # meter's reserve estimate rather than failing inference.
+ self._metering_tokenizer_obj: Any = None
+ self._metering_tokenizer_loaded: bool = False
@property
def available_loras(self) -> list[str]:
@@ -222,6 +275,9 @@ class SGLangEmbeddingAdapter(BaseAdapter):
if self._trust_remote_code:
cmd.append("--trust-remote-code")
+ if self._revision is not None:
+ cmd.extend(["--revision", self._revision])
+
if self._pooling_method:
cmd.extend(["--pooling-method", self._pooling_method])
@@ -250,14 +306,37 @@ class SGLangEmbeddingAdapter(BaseAdapter):
self._process = None
raise _server.startup_failure_error(self._output_file)
+ # Concurrent-POST fan-out: a keep-alive session with a connection pool
+ # sized to the concurrency and a matching thread pool, so a sharded
+ # ``encode`` keeps ``embed_concurrency`` requests in flight against
+ # SGLang's continuous batcher (see ``_embed_texts``). Left as ``None``
+ # for concurrency==1 (legacy single blocking post).
+ if self._embed_concurrency > 1:
+ self._session = requests.Session()
+ pool_size = max(self._embed_concurrency, 10)
+ http_adapter = HTTPAdapter(pool_connections=pool_size, pool_maxsize=pool_size)
+ self._session.mount("http://", http_adapter)
+ self._session.mount("https://", http_adapter)
+ self._post_executor = ThreadPoolExecutor(
+ max_workers=self._embed_concurrency,
+ thread_name_prefix="sglang-embed-post",
+ )
+
logger.info(
- "SGLang server ready: %s at %s",
+ "SGLang server ready: %s at %s (embed_concurrency=%d)",
self._model_name_or_path,
self._server_url,
+ self._embed_concurrency,
)
def unload(self) -> None:
"""Unload the model by stopping SGLang server subprocess."""
+ if self._post_executor is not None:
+ self._post_executor.shutdown(wait=False)
+ self._post_executor = None
+ if self._session is not None:
+ self._session.close()
+ self._session = None
if self._process is not None:
logger.info("Shutting down SGLang server for %s", self._model_name_or_path)
_server.terminate_process(self._process)
@@ -357,38 +436,24 @@ class SGLangEmbeddingAdapter(BaseAdapter):
raise RuntimeError(msg)
dim = self._dense_dim
embeddings = np.zeros((len(items), dim), dtype=np.float32)
- return EncodeOutput(
+ empty_output = EncodeOutput(
dense=embeddings,
batch_size=len(items),
is_query=is_query,
dense_dim=dim,
)
-
- # Call SGLang HTTP API (OpenAI-compatible embeddings endpoint)
- # When LoRA is specified, use it as the model name; otherwise use "default"
+ # Nothing was posted to sglang, so every item bills zero input
+ # tokens — exact, since the zero-vector fallback runs no inference.
+ empty_output.extra["input_token_counts"] = [0] * len(items)
+ return empty_output
+
+ # Call SGLang HTTP API (OpenAI-compatible embeddings endpoint).
+ # When LoRA is specified, use it as the model name; otherwise "default".
+ # ``_embed_texts`` fans the batch out into ``embed_concurrency``
+ # concurrent POSTs so SGLang's continuous batcher stays fed (the serving
+ # loop is single-threaded, so a lone blocking POST under-drives it).
model_name = lora if lora is not None else "default"
- response = requests.post(
- f"{self._server_url}/v1/embeddings",
- json={
- "model": model_name,
- "input": non_empty_texts,
- "encoding_format": "float",
- },
- timeout=60,
- )
- if response.status_code != 200:
- logger.error(
- "SGLang error %d for %d texts: %s",
- response.status_code,
- len(non_empty_texts),
- response.text[:500],
- )
- response.raise_for_status()
- result = response.json()
-
- # Extract embeddings from OpenAI-format result
- # Response format: {"data": [{"embedding": [...], "index": 0}, ...]}
- non_empty_embeddings = self._extract_embeddings(result, len(non_empty_texts))
+ non_empty_embeddings = self._embed_texts(non_empty_texts, model_name)
dense_dim = self._validate_or_set_dense_dim(non_empty_embeddings)
@@ -401,12 +466,147 @@ class SGLangEmbeddingAdapter(BaseAdapter):
for result_idx, original_idx in enumerate(non_empty_indices):
embeddings[original_idx] = non_empty_embeddings[result_idx]
- return EncodeOutput(
+ output = EncodeOutput(
dense=embeddings,
batch_size=len(items),
is_query=is_query,
dense_dim=dense_dim,
)
+ # Unit-meter seam (§7.3): stamp exact per-item input-token counts for the
+ # texts we actually POSTed to sglang. Server-backed, so this is the only
+ # place the real counts exist (see ``_stamp_input_token_counts``).
+ self._stamp_input_token_counts(output, non_empty_texts, non_empty_indices, len(items))
+ return output
+
+ def _get_metering_tokenizer(self) -> Any | None:
+ """Lazily load a weights-free HF tokenizer for exact §7.3 metering.
+
+ SGLang runs the model in a subprocess, so this adapter has no
+ in-process tokenizer for the base ``count_input_tokens`` seam and
+ ``units.input_tokens`` would otherwise stay 0 (the meter's reserve
+ fallback) for this promoted dense-SMARTEST tier. Loading the served
+ model's own tokenizer is tokenizer-only (no weights) and cheap; it is
+ cached after the first call. Best-effort: a load failure is logged once
+ and degrades metering to the reserve estimate rather than failing
+ inference (mirrors ``_resolve_eos_token``).
+ """
+ if self._metering_tokenizer_loaded:
+ return self._metering_tokenizer_obj
+ self._metering_tokenizer_loaded = True
+ try:
+ self._metering_tokenizer_obj = load_tokenizer(
+ self._model_name_or_path, trust_remote_code=self._trust_remote_code
+ )
+ except Exception: # noqa: BLE001 — metering must never take the model down
+ logger.warning(
+ "metering: could not load tokenizer for %s; units.input_tokens will "
+ "fall back to the meter's reserve estimate",
+ self._model_name_or_path,
+ exc_info=True,
+ )
+ self._metering_tokenizer_obj = None
+ return self._metering_tokenizer_obj
+
+ def _stamp_input_token_counts(
+ self,
+ output: EncodeOutput,
+ non_empty_texts: list[str],
+ non_empty_indices: list[int],
+ total: int,
+ ) -> None:
+ """Stamp exact per-item input-token counts (§7.3) onto ``output.extra``.
+
+ SGLang is server-backed, so the base ``count_input_tokens`` seam has no
+ in-process tokenizer and ``units.input_tokens`` would fall to the
+ meter's reserve estimate — never exact for this promoted dense tier. We
+ count the EXACT strings POSTed to sglang (``non_empty_texts`` — already
+ query/doc-template- and (when enabled) EOS-formatted by
+ ``_format_texts``, and truncated at ``max_seq_length`` the same way
+ sglang's ``--context-length`` truncates), then scatter them back to item
+ positions with ``0`` for the empty items that took the zero-vector
+ fallback and were never sent. The summed counts equal sglang's own
+ ``usage.prompt_tokens`` for the request. Mirrors the ``bert_flash`` /
+ ``bge_m3_flash`` seam; ``_token_counts_or_none`` is the shared base
+ helper. Best-effort: any tokenizer quirk (or a load failure) leaves
+ ``extra`` unstamped so the meter falls back to its reserve estimate
+ rather than billing an approximation.
+ """
+ tokenizer = self._get_metering_tokenizer()
+ if tokenizer is None:
+ return
+ counts = self._token_counts_or_none(tokenizer, non_empty_texts, expected_len=len(non_empty_texts))
+ if counts is None:
+ return
+ per_item = [0] * total
+ for result_idx, original_idx in enumerate(non_empty_indices):
+ per_item[original_idx] = counts[result_idx]
+ output.extra["input_token_counts"] = per_item
+
+ def _embed_texts(self, texts: list[str], model_name: str) -> np.ndarray:
+ """Embed ``texts`` via SGLang, fanning out concurrent POSTs.
+
+ A single blocking POST presents one request to SGLang's continuous
+ batcher; on the single-threaded serving loop that means the batcher
+ rarely sees more than one request at a time and the served throughput
+ lands far below the engine knee. Sharding the batch into up to
+ ``embed_concurrency`` contiguous chunks and POSTing them concurrently
+ keeps that many requests in flight, so the batcher fills.
+
+ Correctness is preserved: each shard's embeddings are re-ordered by the
+ response ``index`` inside :meth:`_extract_embeddings`, and the shards are
+ concatenated back in input order, so the returned rows align 1:1 with
+ ``texts`` exactly as the single-POST path did.
+ """
+ concurrency = self._embed_concurrency
+ if concurrency <= 1 or len(texts) <= 1:
+ return self._post_embedding_batch(texts, model_name, session=None)
+
+ n_shards = min(concurrency, len(texts))
+ shard_size = math.ceil(len(texts) / n_shards)
+ shards = [texts[i : i + shard_size] for i in range(0, len(texts), shard_size)]
+
+ executor = self._post_executor
+ session = self._session
+ if executor is None or session is None:
+ # Defensive: load() populates both when concurrency > 1. Fall back
+ # to a serial pass rather than fail if they are somehow missing.
+ return np.vstack([self._post_embedding_batch(shard, model_name, session=session) for shard in shards])
+
+ futures = [executor.submit(self._post_embedding_batch, shard, model_name, session) for shard in shards]
+ # Iterating in submission order preserves shard order; ``.result()``
+ # re-raises any shard error just like the single-POST path did.
+ parts = [future.result() for future in futures]
+ return np.vstack(parts)
+
+ def _post_embedding_batch(
+ self,
+ texts: list[str],
+ model_name: str,
+ session: requests.Session | None,
+ ) -> np.ndarray:
+ """POST one (possibly sharded) batch of texts and return its embeddings."""
+ poster = session.post if session is not None else requests.post
+ response = poster(
+ f"{self._server_url}/v1/embeddings",
+ json={
+ "model": model_name,
+ "input": texts,
+ "encoding_format": "float",
+ },
+ timeout=60,
+ )
+ if response.status_code != 200:
+ logger.error(
+ "SGLang error %d for %d texts: %s",
+ response.status_code,
+ len(texts),
+ response.text[:500],
+ )
+ response.raise_for_status()
+ result = response.json()
+
+ # Response format: {"data": [{"embedding": [...], "index": 0}, ...]}
+ return self._extract_embeddings(result, len(texts))
def _validate_or_set_dense_dim(self, embeddings: np.ndarray) -> int:
"""Validate observed SGLang embedding width against configured dense_dim."""
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
index a05eb42c2..1ebc369e5 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -228,6 +228,10 @@ class SGLangGenerationAdapter(GenerationAdapter):
mem_fraction_static: float = 0.85,
compute_precision: ComputePrecision = "bfloat16",
trust_remote_code: bool = True,
+ # Pinned HuggingFace revision (commit SHA / branch / tag). Forwarded to
+ # ``sglang.launch_server`` as ``--revision`` so the served weights match
+ # the YAML-pinned SHA; None serves the repo default.
+ revision: str | None = None,
served_model_name: str | None = None,
default_sampling: dict[str, Any] | None = None,
stop_tokens: list[str] | None = None,
@@ -270,6 +274,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
self._mem_fraction_static = mem_fraction_static
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._served_model_name = served_model_name or model_name_or_path
self._default_sampling = default_sampling or {}
self._stop_tokens = stop_tokens or []
@@ -435,6 +440,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
]
if self._trust_remote_code:
cmd.append("--trust-remote-code")
+ if self._revision is not None:
+ cmd.extend(["--revision", self._revision])
if self._disable_cuda_graph:
cmd.append("--disable-cuda-graph")
if self._attention_backend:
diff --git a/packages/sie_server/src/sie_server/adapters/siglip/__init__.py b/packages/sie_server/src/sie_server/adapters/siglip/__init__.py
index 9b5754cb8..dcccee984 100644
--- a/packages/sie_server/src/sie_server/adapters/siglip/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/siglip/__init__.py
@@ -41,6 +41,9 @@ from __future__ import annotations
import io
import logging
+import os
+import threading
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, Literal
@@ -53,12 +56,49 @@ from sie_server.core.inference_output import EncodeOutput
from sie_server.types.inputs import media_bytes
if TYPE_CHECKING:
- from PIL import Image
-
from sie_server.types.inputs import Item
logger = logging.getLogger(__name__)
+
+def _open_clip_token_counts(input_ids: Any) -> list[int] | None:
+ """Per-row non-pad token counts for an ``open_clip`` tokenizer batch (§7.3).
+
+ open_clip pads every text to the fixed context length with id ``0``, so the
+ count of non-zero ids per row is the real billable length (content plus the
+ sot/eot markers) the text tower encoded. Best-effort: any tensor quirk
+ yields ``None`` so the meter falls back to its reserve estimate rather than
+ mis-billing — metering must never fail inference.
+ """
+ try:
+ return [int((row != 0).sum().item()) for row in input_ids]
+ except Exception: # noqa: BLE001 — metering must never fail inference
+ return None
+
+
+# Cross-item preprocessing is CPU-bound (PIL decode + resize). Fan the flat
+# image set across a small bounded thread pool so decode/resize overlaps.
+_MAX_PREPROCESS_THREADS = 8
+
+
+def _feature_tensor(out: Any) -> torch.Tensor:
+ """Return the pooled feature tensor from a ``get_*_features`` result.
+
+ transformers <= 4.57.x (the Modal lane pin) returns the ``[B, dim]`` feature
+ tensor directly; transformers 5.x wraps it in a ``BaseModelOutputWithPooling``
+ whose ``pooler_output`` is that *same* tensor. Unwrap so the transformers
+ backend is robust across the pin instead of raising ``AttributeError`` in
+ ``functional.normalize``. (open_clip's ``encode_*`` always returns a tensor.)
+ """
+ if isinstance(out, torch.Tensor):
+ return out
+ pooled = getattr(out, "pooler_output", None)
+ if isinstance(pooled, torch.Tensor):
+ return pooled
+ msg = f"unexpected get_*_features return type: {type(out).__name__}"
+ raise TypeError(msg)
+
+
# Error messages
_ERR_NO_INPUT = "SiglipAdapter requires either text or images input"
_ERR_OPEN_CLIP_ID = (
@@ -106,6 +146,7 @@ class SiglipAdapter(BaseAdapter):
compute_precision: ComputePrecision = "float16",
trust_remote_code: bool = False,
max_seq_length: int | None = None,
+ revision: str | None = None,
backend: SiglipBackend = "transformers",
open_clip_model_id: str | None = None,
dense_dim: int | None = None,
@@ -123,6 +164,11 @@ class SiglipAdapter(BaseAdapter):
``SiglipProcessor.from_pretrained`` in the transformers
backend. Ignored by the ``open_clip`` backend.
max_seq_length: Ignored - SigLIP uses fixed token length from model config.
+ revision: Optional HuggingFace revision/branch/commit SHA to pin
+ when loading the processor and model in the ``transformers``
+ backend. If None, the default branch is used. Forwarded to
+ ``from_pretrained(..., revision=...)``. Ignored by the
+ ``open_clip`` backend, which pins via its own model identifier.
backend: Which loader to use. ``transformers`` (default) for stock
SigLIP checkpoints; ``open_clip`` for open_clip-distributed
SigLIP checkpoints (e.g. Marqo).
@@ -139,6 +185,7 @@ class SiglipAdapter(BaseAdapter):
self._normalize = normalize
self._compute_precision = compute_precision
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._backend: SiglipBackend = backend
self._open_clip_model_id = open_clip_model_id
self._dense_dim_override = dense_dim
@@ -157,6 +204,20 @@ class SiglipAdapter(BaseAdapter):
self._open_clip_tokenizer: Any | None = None
self._device: str | None = None
self._dense_dim: int | None = None
+ # HF fast tokenizers are NOT thread-safe: applying per-call
+ # padding/truncation flags reconfigures the underlying Rust tokenizer,
+ # which takes a mutable borrow. Concurrent text encodes (e.g. the
+ # managed lane's ``@modal.concurrent`` inputs dispatched to a thread
+ # pool) otherwise race with ``RuntimeError: Already borrowed``.
+ # Serialise the tokenizer call — microseconds vs the GPU forward.
+ # Guards both backends' tokenizers.
+ self._tokenizer_lock = threading.Lock()
+ # Lazily-created bounded pool used to overlap per-image CPU
+ # preprocessing (decode + resize) within a batched encode call.
+ # Guards lazy pool creation against concurrent first callers (same
+ # hazard class as ``_tokenizer_lock``) so a race can't orphan a pool.
+ self._preprocess_pool_lock = threading.Lock()
+ self._preprocess_pool: ThreadPoolExecutor | None = None
def load(self, device: str) -> None:
"""Load the model onto the specified device.
@@ -200,15 +261,19 @@ class SiglipAdapter(BaseAdapter):
"""Load via transformers SiglipModel/SiglipProcessor."""
from transformers import SiglipModel, SiglipProcessor
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
self._processor = SiglipProcessor.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model = SiglipModel.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -291,11 +356,11 @@ class SiglipAdapter(BaseAdapter):
self._validate_output_types(output_types)
# Index prepared image tensors by the original item index so the
- # per-item loop can reuse them. Only the open_clip backend currently
- # consumes these; the transformers ImagePreprocessor produces tensors
- # in a layout matching SiglipProcessor, but the existing transformers
- # code path re-runs the processor inline — left untouched here to
- # avoid behavioral drift on the google/siglip* regression tests.
+ # batched image path can reuse them. Only the open_clip backend
+ # currently consumes these; the transformers ImagePreprocessor produces
+ # tensors in a layout matching SiglipProcessor, but the transformers
+ # code path re-runs the processor inline — left untouched here to avoid
+ # behavioral drift on the google/siglip* regression tests.
prepared_by_index: dict[int, Any] = {}
if self._backend == "open_clip" and prepared_items:
for prepared in prepared_items:
@@ -307,153 +372,182 @@ class SiglipAdapter(BaseAdapter):
continue
prepared_by_index[prepared.original_index] = pixel_values
- # Encode each item individually and stack into batch
import numpy as np
- embeddings_list = []
+ # Partition items by modality (image takes precedence over text),
+ # preserving original positions so the stacked output stays in order.
+ image_indices: list[int] = []
+ text_indices: list[int] = []
for i, item in enumerate(items):
- embedding = self._encode_single_item(item, prepared_pixel_values=prepared_by_index.get(i))
- embeddings_list.append(embedding)
+ has_text = item.text is not None
+ images = item.images
+ has_images = images is not None and len(images) > 0
+ if not has_text and not has_images:
+ raise ValueError(_ERR_NO_INPUT)
+ if has_images:
+ image_indices.append(i)
+ else:
+ text_indices.append(i)
+
+ embeddings: list[Any] = [None] * len(items)
+
+ if image_indices:
+ image_vecs = self._encode_image_items(image_indices, items, prepared_by_index)
+ for slot, i in enumerate(image_indices):
+ embeddings[i] = image_vecs[slot]
+
+ per_item_token_counts: list[int] | None = None
+ if text_indices:
+ text_vecs, text_counts = self._encode_texts([items[i].text for i in text_indices]) # ty: ignore[invalid-argument-type]
+ for slot, i in enumerate(text_indices):
+ embeddings[i] = text_vecs[slot]
+ # Scatter the per-text token counts back to their item positions
+ # (image items → 0 text tokens), aligned 1:1 with ``items``.
+ if isinstance(text_counts, list) and len(text_counts) == len(text_indices):
+ per_item_token_counts = [0] * len(items)
+ for slot, i in enumerate(text_indices):
+ per_item_token_counts[i] = text_counts[slot]
# Stack into batched array [batch, dim]
- dense_batch = np.stack(embeddings_list, axis=0)
+ dense_batch = np.stack(embeddings, axis=0)
- return EncodeOutput(
+ output = EncodeOutput(
dense=dense_batch,
batch_size=len(items),
is_query=is_query,
dense_dim=self._dense_dim,
)
-
- def _encode_single_item(self, item: Item, prepared_pixel_values: Any = None) -> Any:
- """Encode a single item (text, image, or both).
-
- Args:
- item: Input item.
- prepared_pixel_values: Optional pre-processed ``[C, H, W]`` tensor
- from the framework's image preprocessor. Only honored on the
- ``open_clip`` backend and only when the item has exactly one
- image (matching what the preprocessor consumed). Falls back
- to inline preprocessing otherwise.
-
- Returns:
- Numpy array of shape [dense_dim].
+ # Unit-meter seam (§7.3): stamp exact per-item TEXT-tower token counts
+ # (both backends). Image items took the image tower (metered per image
+ # via ``count_input_images``) and contribute 0 text tokens; only stamp
+ # when at least one text item was encoded so a pure-image batch stays on
+ # the image dimension. The encode pipeline forwards ``extra`` to the
+ # result path for metering (§P3.5).
+ if per_item_token_counts is not None:
+ output.extra["input_token_counts"] = per_item_token_counts
+ return output
+
+ def _get_preprocess_pool(self) -> ThreadPoolExecutor:
+ """Return the lazily-created bounded preprocessing thread pool."""
+ pool = self._preprocess_pool
+ if pool is None:
+ with self._preprocess_pool_lock:
+ pool = self._preprocess_pool
+ if pool is None:
+ workers = min(_MAX_PREPROCESS_THREADS, os.cpu_count() or 1)
+ pool = ThreadPoolExecutor(max_workers=max(1, workers), thread_name_prefix="siglip-preproc")
+ self._preprocess_pool = pool
+ return pool
+
+ def _preprocess_one(self, img_input: Any) -> torch.Tensor:
+ """Decode + preprocess a single image input into a ``[C, H, W]`` tensor.
+
+ Stateless per call (PIL / processor / val_preproc release the GIL on
+ the heavy work), so this is safe to fan across the preprocessing pool.
"""
- has_text = item.text is not None
- images = item.images
- has_images = images is not None and len(images) > 0
-
- if not has_text and not has_images:
- raise ValueError(_ERR_NO_INPUT)
-
- # Determine what to encode
- if has_images:
- # Image encoding (or image+text where image takes precedence).
- # The framework's preprocessor only handles the first image per
- # item, so we can only reuse it when the item has exactly one.
- if (
- self._backend == "open_clip"
- and prepared_pixel_values is not None
- and images is not None
- and len(images) == 1
- ):
- return self._encode_images([], prepared_pixel_values=prepared_pixel_values)
- pil_images = self._load_images(item)
- return self._encode_images(pil_images)
- # Text-only encoding (text is guaranteed non-None if no images)
- return self._encode_text(item.text) # type: ignore
-
- def _load_images(self, item: Item) -> list[Image.Image]:
- """Load images from item into PIL Images.
+ from PIL import Image
- Args:
- item: Item with images field.
+ img_bytes = media_bytes(img_input, kind="image")
+ pil_img = Image.open(io.BytesIO(img_bytes))
+ # Convert to RGB if necessary
+ if pil_img.mode != "RGB":
+ pil_img = pil_img.convert("RGB")
+ if self._backend == "open_clip":
+ assert self._open_clip_preprocess is not None
+ return self._open_clip_preprocess(pil_img)
+ assert self._processor is not None
+ processed = self._processor(images=pil_img, return_tensors="pt")
+ return processed["pixel_values"][0]
- Returns:
- List of PIL Images.
+ def _preprocess_image_batch(
+ self,
+ image_indices: list[int],
+ items: list[Item],
+ prepared_by_index: dict[int, Any],
+ ) -> tuple[torch.Tensor, list[int]]:
+ """Build a stacked ``[N, C, H, W]`` pixel tensor + per-item image counts.
+
+ Reuses the framework's prepared ``[C, H, W]`` tensor for single-image
+ items on the open_clip backend (matching the previous fast path); every
+ other image is decoded + preprocessed, fanned across the pool. Per-image
+ preprocessing is independent, so the stacked tensor is identical to
+ preprocessing each image serially.
"""
- from PIL import Image
+ # Build the flat list of preprocessing jobs in stacked order. A job is
+ # either a ready ``[C, H, W]`` tensor (open_clip prepared fast path) or
+ # a raw image input to decode + preprocess.
+ jobs: list[tuple[str, Any]] = []
+ counts: list[int] = []
+ for slot, item in enumerate(items):
+ item_images = item.images or []
+ counts.append(len(item_images))
+ orig_index = image_indices[slot]
+ prepared = prepared_by_index.get(orig_index)
+ if self._backend == "open_clip" and prepared is not None and len(item_images) == 1:
+ jobs.append(("ready", prepared))
+ else:
+ jobs.extend(("decode", img_input) for img_input in item_images)
- pil_images = []
- for img_input in item.images or []:
- # img_input is ImageInput TypedDict with data (bytes) and optional format
- img_bytes = media_bytes(img_input, kind="image")
- pil_img = Image.open(io.BytesIO(img_bytes))
- # Convert to RGB if necessary
- if pil_img.mode != "RGB":
- pil_img = pil_img.convert("RGB")
- pil_images.append(pil_img)
+ def run(job: tuple[str, Any]) -> torch.Tensor:
+ kind, payload = job
+ return payload if kind == "ready" else self._preprocess_one(payload)
- return pil_images
+ if len(jobs) == 1:
+ tensors = [run(jobs[0])]
+ else:
+ pool = self._get_preprocess_pool()
+ tensors = list(pool.map(run, jobs))
+ return torch.stack(tensors, dim=0), counts
- def _encode_images(
+ def _encode_image_items(
self,
- images: list[Image.Image],
- prepared_pixel_values: Any = None,
+ image_indices: list[int],
+ all_items: list[Item],
+ prepared_by_index: dict[int, Any],
) -> Any:
- """Encode images into embeddings.
+ """Encode image items as one stacked forward, mean-pooling per item.
- Args:
- images: List of PIL Images. Ignored on the ``open_clip`` backend
- when ``prepared_pixel_values`` is supplied.
- prepared_pixel_values: Optional pre-processed ``[C, H, W]`` tensor
- from the framework's preprocessor. Only the ``open_clip``
- backend uses this fast path; when supplied, ``val_preproc``
- is skipped and the tensor is moved to device and batched
- directly.
-
- Returns:
- Numpy array of shape [dense_dim] (averaged if multiple images).
+ Returns a ``[len(image_indices), dim]`` float32 array, one row per item.
"""
assert self._model is not None
from torch.nn import functional
+ items = [all_items[i] for i in image_indices]
+ pixel_values, counts = self._preprocess_image_batch(image_indices, items, prepared_by_index)
+
if self._backend == "open_clip":
- # ``val_preproc`` and the framework preprocessor both return
- # float32 tensors. The open_clip model was cast to ``dtype`` at
- # load time (e.g. fp16 on CUDA), so we must match here — unlike
- # ``transformers.SiglipModel``, ``open_clip``'s ``encode_image``
- # does not auto-cast inputs.
+ # open_clip's encode_image does not auto-cast inputs; match the
+ # model dtype (e.g. fp16 on CUDA) as the serial path did.
model_dtype = next(self._model.parameters()).dtype
- if prepared_pixel_values is not None:
- # Fast path: framework preprocessor already produced a
- # [C, H, W] tensor in the val_preproc layout. Add the batch
- # dim, move to device, and cast to the model's dtype.
- pixel_values = prepared_pixel_values.unsqueeze(0).to(device=self._device, dtype=model_dtype)
- effective_count = 1
- else:
- assert self._open_clip_preprocess is not None
- pixel_values = torch.stack([self._open_clip_preprocess(img) for img in images]).to(
- device=self._device, dtype=model_dtype
- )
- effective_count = len(images)
+ pixel_values = pixel_values.to(device=self._device, dtype=model_dtype)
with torch.inference_mode():
image_features = self._model.encode_image(pixel_values, normalize=self._normalize)
else:
- assert self._processor is not None
- inputs = self._processor(images=images, return_tensors="pt")
- inputs = {k: v.to(self._device) for k, v in inputs.items()}
+ pixel_values = pixel_values.to(self._device)
with torch.inference_mode():
- image_features = self._model.get_image_features(**inputs)
+ image_features = _feature_tensor(self._model.get_image_features(pixel_values=pixel_values))
if self._normalize:
image_features = functional.normalize(image_features, p=2, dim=-1)
- effective_count = len(images)
- # If multiple images, average the embeddings
- if effective_count > 1:
- image_features = image_features.mean(dim=0, keepdim=True)
+ # Split by per-item image counts; mean-pool multi-image items on-device
+ # in the model dtype, exactly as the serial path did.
+ vecs = []
+ offset = 0
+ for count in counts:
+ group = image_features[offset : offset + count]
+ offset += count
+ vecs.append(group[0] if count == 1 else group.mean(dim=0))
- return image_features[0].float().cpu().numpy()
+ return torch.stack(vecs, dim=0).float().cpu().numpy()
- def _encode_text(self, text: str) -> Any:
- """Encode text into embeddings.
-
- Args:
- text: Text string to encode.
+ def _encode_texts(self, texts: list[str]) -> tuple[Any, list[int] | None]:
+ """Encode a list of texts as one stacked forward.
- Returns:
- Numpy array of shape [dense_dim].
+ Returns ``(embeddings, token_counts)``: a ``[len(texts), dim]`` float32
+ array (one row per text) and the exact per-text token counts the text
+ tower encoded (§7.3, both backends), or ``None`` when no clean count
+ could be surfaced.
"""
assert self._model is not None
@@ -461,21 +555,45 @@ class SiglipAdapter(BaseAdapter):
if self._backend == "open_clip":
assert self._open_clip_tokenizer is not None
- input_ids = self._open_clip_tokenizer([text]).to(self._device)
+ # Serialise tokenization: fast tokenizers are not thread-safe.
+ with self._tokenizer_lock:
+ input_ids = self._open_clip_tokenizer(list(texts))
+ # Unit-meter seam (§7.3): open_clip pads to a fixed context
+ # length with id 0, so the non-pad count per row is the real
+ # billable length (content + sot/eot) the tower encoded.
+ token_counts = _open_clip_token_counts(input_ids)
+ input_ids = input_ids.to(self._device)
with torch.inference_mode():
text_features = self._model.encode_text(input_ids, normalize=self._normalize)
else:
assert self._processor is not None
- # Process text - use max_length padding to match MTEB behavior
- # SigLIP text embeddings depend on sequence length, so consistent padding is required
- inputs = self._processor(text=[text], return_tensors="pt", padding="max_length", truncation=True)
+ # Process text as one batch - use max_length padding to match MTEB
+ # behavior. SigLIP text embeddings depend on sequence length, so
+ # consistent padding is required (per-item results are unchanged by
+ # batching since max_length pads every item to the same length).
+ # The HF fast tokenizer is not thread-safe under the per-call
+ # padding/truncation reconfiguration, so serialise this call.
+ with self._tokenizer_lock:
+ inputs = self._processor(text=list(texts), return_tensors="pt", padding="max_length", truncation=True)
+ # Unit-meter seam (§7.3): SigLIP pads every text to a fixed
+ # length (and its tokenizer omits an attention mask), so count
+ # the exact content tokens via a padding-free recount over the
+ # processor tokenizer (capped at the model context window,
+ # SigLIP 64) — the real billable length, excluding padding.
+ token_counts = self._token_counts_or_none(
+ self._processor.tokenizer, list(texts), expected_len=len(texts)
+ )
inputs = {k: v.to(self._device) for k, v in inputs.items()}
with torch.inference_mode():
- text_features = self._model.get_text_features(**inputs)
+ text_features = _feature_tensor(self._model.get_text_features(**inputs))
if self._normalize:
text_features = functional.normalize(text_features, p=2, dim=-1)
- return text_features[0].float().cpu().numpy()
+ return text_features.float().cpu().numpy(), token_counts
+
+ def _encode_text(self, text: str) -> Any:
+ """Encode a single text into a ``[dim]`` embedding (thin batch wrapper)."""
+ return self._encode_texts([text])[0][0]
def _validate_output_types(self, output_types: list[str]) -> None:
"""Validate that output types are supported."""
@@ -506,3 +624,11 @@ class SiglipAdapter(BaseAdapter):
from sie_server.core.preprocessor import ImagePreprocessor
return ImagePreprocessor(self._processor, self._model_name_or_path)
+
+ def unload(self) -> None:
+ """Shut down the preprocessing pool, then unload model weights."""
+ pool = self._preprocess_pool
+ self._preprocess_pool = None
+ if pool is not None:
+ pool.shutdown(wait=False)
+ super().unload()
diff --git a/packages/sie_server/src/sie_server/adapters/splade_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/splade_flash/__init__.py
index 3aaa2bd9b..4b9075eb7 100644
--- a/packages/sie_server/src/sie_server/adapters/splade_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/splade_flash/__init__.py
@@ -8,6 +8,7 @@ import numpy as np
import torch
from sie_server.adapters._flash_base import FlashBaseAdapter
+from sie_server.adapters._flash_pack import build_position_ids
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision
from sie_server.adapters._utils import extract_texts, validate_output_types
@@ -72,6 +73,7 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
query_template: str | None = None,
doc_template: str | None = None,
trust_remote_code: bool = False,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
_ = kwargs
@@ -81,6 +83,7 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._query_template = query_template
self._doc_template = doc_template
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._model: Any = None # AutoModelForMaskedLM
self._tokenizer: PreTrainedTokenizerBase | None = None
@@ -108,9 +111,13 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Use float32 on CPU/MPS for correctness; configured precision on CUDA
dtype = self._resolve_dtype() if device.startswith("cuda") else torch.float32
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# Load with eager attention — the flash path runs its own attention;
@@ -119,7 +126,7 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._model_name_or_path,
torch_dtype=dtype,
attn_implementation="eager",
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -128,11 +135,22 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._vocab_size = self._model.config.vocab_size
self._use_flash = device.startswith("cuda") and _has_flash_attn()
- # Disable packed flash path for RoBERTa until position-id parity is
- # verified — fall back to native model forward which handles this
- # correctly via its own embeddings module.
- if self._arch == "roberta" and self._use_flash:
- logger.warning("Disabling packed flash path for RoBERTa until position-id parity is verified")
+ # The packed flash path adds only *absolute* learned position embeddings
+ # (same assumption as bert_flash / xlm_roberta_flash). Relative/rotary
+ # position types inject a position-dependent bias *inside* attention that
+ # the varlen kernel does not reproduce, so those stay on the native
+ # forward. RoBERTa-family absolute-position SPLADE models (e.g.
+ # granite-embedding-30m-sparse) run packed: their only difference from
+ # BERT is the padding_idx+1 position offset, handled in
+ # ``_build_position_ids`` via the shared varlen packer (parity verified
+ # against the native padded path — see test_splade_packed_parity).
+ pos_emb_type = getattr(self._model.config, "position_embedding_type", "absolute")
+ if self._use_flash and pos_emb_type != "absolute":
+ logger.warning(
+ "Disabling packed flash path: position_embedding_type=%r is not 'absolute' "
+ "(the varlen path only supports absolute position embeddings)",
+ pos_emb_type,
+ )
self._use_flash = False
logger.info(
@@ -297,23 +315,19 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# ------------------------------------------------------------------
def _build_position_ids(self, cu_seqlens: torch.Tensor) -> torch.Tensor:
- """Build position IDs for packed sequences.
-
- BERT uses 0-based positions. RoBERTa offsets by padding_idx + 1.
+ """Build position IDs for packed sequences, restarting per sequence.
+
+ BERT/DistilBERT use 0-based positions; RoBERTa offsets each sequence by
+ ``padding_idx + 1`` — bit-identical to HF
+ ``create_position_ids_from_input_ids`` for unpadded input. Delegates to
+ the shared varlen packer (``_flash_pack.build_position_ids``) that the
+ other RoBERTa-family flash adapter (``xlm_roberta_flash``) already uses,
+ so all packed encoders share one deep implementation.
"""
- total_tokens = int(cu_seqlens[-1].item())
- positions = torch.arange(total_tokens, device=self._device, dtype=torch.long)
- offsets = torch.repeat_interleave(
- cu_seqlens[:-1],
- cu_seqlens[1:] - cu_seqlens[:-1],
- )
- position_ids = positions - offsets
-
+ offset = 0
if self._arch == "roberta":
- padding_idx = self._get_base_model().embeddings.padding_idx
- position_ids = position_ids + padding_idx + 1
-
- return position_ids
+ offset = self._get_base_model().embeddings.padding_idx + 1
+ return build_position_ids(cu_seqlens, offset=offset)
def _get_base_model(self) -> Any:
if self._arch == "bert":
@@ -475,7 +489,7 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
("query_token_weights.txt", self._parse_query_token_weights),
("idf.json", self._parse_idf_json),
):
- resolved = self._resolve_repo_file(Path(self._model_name_or_path), filename)
+ resolved = self._resolve_repo_file(Path(self._model_name_or_path), filename, self._revision)
if resolved is None:
continue
idf = loader(resolved)
@@ -501,19 +515,19 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
return None
@staticmethod
- def _resolve_repo_file(model_path: Path, filename: str) -> str | None:
+ def _resolve_repo_file(model_path: Path, filename: str, revision: str | None = None) -> str | None:
if model_path.exists() and model_path.is_dir():
candidate = model_path / filename
return str(candidate) if candidate.exists() else None
try:
from huggingface_hub import try_to_load_from_cache
- cached = try_to_load_from_cache(repo_id=str(model_path), filename=filename)
+ cached = try_to_load_from_cache(repo_id=str(model_path), filename=filename, revision=revision)
if isinstance(cached, str):
return cached
from huggingface_hub import hf_hub_download
- downloaded = hf_hub_download(repo_id=str(model_path), filename=filename)
+ downloaded = hf_hub_download(repo_id=str(model_path), filename=filename, revision=revision)
return downloaded if isinstance(downloaded, str) else None
except Exception: # noqa: BLE001
return None
diff --git a/packages/sie_server/src/sie_server/adapters/stablebridge_pruner/__init__.py b/packages/sie_server/src/sie_server/adapters/stablebridge_pruner/__init__.py
index cdba81f4c..ca31733dd 100644
--- a/packages/sie_server/src/sie_server/adapters/stablebridge_pruner/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/stablebridge_pruner/__init__.py
@@ -75,6 +75,7 @@ class StablebridgePrunerAdapter(ModelAdapter):
prune_threshold: float = DEFAULT_PRUNE_THRESHOLD,
highlight_threshold: float = DEFAULT_HIGHLIGHT_THRESHOLD,
trust_remote_code: bool = False,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
_ = kwargs
@@ -89,6 +90,7 @@ class StablebridgePrunerAdapter(ModelAdapter):
self._prune_threshold = prune_threshold
self._highlight_threshold = highlight_threshold
self._trust_remote_code = trust_remote_code
+ self._revision = revision
self._model: Any | None = None
self._pruning_head: PruningHead | None = None
@@ -113,9 +115,13 @@ class StablebridgePrunerAdapter(ModelAdapter):
}
dtype = dtype_map.get(self._compute_precision, torch.bfloat16)
+ shared_kwargs: dict[str, Any] = {"trust_remote_code": self._trust_remote_code}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
self._tokenizer = AutoTokenizer.from_pretrained(
self._model_name_or_path,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
# ``output_hidden_states`` is requested per-call from ``extract``;
@@ -123,7 +129,7 @@ class StablebridgePrunerAdapter(ModelAdapter):
self._model = AutoModelForSequenceClassification.from_pretrained(
self._model_name_or_path,
torch_dtype=dtype,
- trust_remote_code=self._trust_remote_code,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -187,6 +193,9 @@ class StablebridgePrunerAdapter(ModelAdapter):
return str(local_path / self._pruning_head_file)
try:
+ # The pruning head lives in a SEPARATE HuggingFace repo
+ # (``pruning_head_path``); the base-model ``revision`` pin does not
+ # apply here, so it is deliberately not forwarded.
return hf_hub_download(
repo_id=self._pruning_head_path,
filename=self._pruning_head_file,
diff --git a/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py
index 120700d8f..465b68e6a 100644
--- a/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py
@@ -57,6 +57,7 @@ class XLMRobertaFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
pooling: PoolingStrategy = "mean",
query_template: str | None = None,
doc_template: str | None = None,
+ revision: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -69,6 +70,8 @@ class XLMRobertaFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
pooling: Pooling strategy - "cls" or "mean".
query_template: Optional template for queries, e.g. "query: {text}".
doc_template: Optional template for documents, e.g. "passage: {text}".
+ revision: Optional HuggingFace revision/branch/commit SHA to pin when
+ loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
**kwargs: Additional arguments (ignored, for compatibility).
"""
_ = kwargs
@@ -79,6 +82,7 @@ class XLMRobertaFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._pooling = pooling
self._query_template = query_template
self._doc_template = doc_template
+ self._revision = revision
self._model: XLMRobertaModel | None = None
self._tokenizer: PreTrainedTokenizerFast | None = None
@@ -109,7 +113,11 @@ class XLMRobertaFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._pooling,
)
- self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path)
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
+ self._tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path, **shared_kwargs)
# Load model with eager attention - we'll run our own flash attention
self._model = AutoModel.from_pretrained(
@@ -117,6 +125,7 @@ class XLMRobertaFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
torch_dtype=dtype,
attn_implementation="eager", # We handle attention manually
trust_remote_code=True,
+ **shared_kwargs,
)
self._model.to(device)
self._model.eval()
@@ -226,12 +235,25 @@ class XLMRobertaFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Convert to numpy and return EncodeOutput
dense_np = dense_vecs.float().cpu().numpy()
- return EncodeOutput(
+ output = EncodeOutput(
dense=dense_np,
batch_size=len(items),
is_query=is_query,
dense_dim=self._dense_dim,
)
+ # Unit-meter seam (§7.3): this adapter owns tokenization (the registry
+ # preprocessor for flash adapters is a char-count ESTIMATOR) AND applies
+ # the model's query/doc template before tokenizing (e.g. arctic-embed's
+ # ``query: {text}``, multilingual-e5's ``query:``/``passage:``), so the
+ # real post-template, post-truncation per-item token counts exist only
+ # here. ``seq_lengths`` is the exact ``len(input_ids)`` the model
+ # processed; expose it through ``EncodeOutput.extra`` (the designated
+ # adapter-extension point) aligned 1:1 with ``items``. The encode
+ # pipeline forwards these for metering, in preference to the base
+ # ``count_input_tokens`` fallback which re-tokenizes raw ``item.text``
+ # and would undercount by the template's tokens. Mirrors ``bert_flash``.
+ output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
+ return output
def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:
"""Build XLMRoberta-style position IDs (each restarts at padding_idx + 1)."""
diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.py
index f909f0909..9f8ed6b7e 100644
--- a/packages/sie_server/src/sie_server/api/models.py
+++ b/packages/sie_server/src/sie_server/api/models.py
@@ -87,6 +87,15 @@ class ModelInfo(BaseModel):
max_sequence_length: int | None = None
profiles: dict[str, ProfileInfo] = {}
+ revision: str | None = None
+ """Pinned HF commit SHA for the model's weights (design §6.6).
+
+ Additive field so customers can pin/verify the exact weights behind an id:
+ a served ``sie_id`` maps to identical weights forever, and a weights change
+ is published as a NEW versioned id. ``None`` for ``weights_path`` /
+ ``package_backed`` models (no Hub revision) or an unpinned dev config.
+ """
+
capabilities: ModelCapabilities | None = None
"""Advertised generation capabilities, ``None`` for non-generate models."""
@@ -193,6 +202,7 @@ async def list_models(http_request: Request) -> ModelsListResponse:
last_error=last_error,
max_sequence_length=config.max_sequence_length,
profiles=profiles,
+ revision=getattr(config, "hf_revision", None),
capabilities=_resolve_capabilities(config),
)
)
@@ -246,5 +256,6 @@ async def get_model(model: str, http_request: Request) -> ModelInfo:
last_error=last_error,
max_sequence_length=config.max_sequence_length,
profiles=profiles,
+ revision=getattr(config, "hf_revision", None),
capabilities=_resolve_capabilities(config),
)
diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.py
index ed4086ef1..fc717645f 100644
--- a/packages/sie_server/src/sie_server/app/app_factory.py
+++ b/packages/sie_server/src/sie_server/app/app_factory.py
@@ -168,6 +168,7 @@ class AppFactory:
model_filter=config.model_filter,
memory_config=memory_config,
device=config.device,
+ devices=config.devices,
engine_config=engine_config,
pool_name=config.pool_name,
pinned_models=config.pinned_models,
diff --git a/packages/sie_server/src/sie_server/app/app_state_config.py b/packages/sie_server/src/sie_server/app/app_state_config.py
index 42db30e99..744b705a3 100644
--- a/packages/sie_server/src/sie_server/app/app_state_config.py
+++ b/packages/sie_server/src/sie_server/app/app_state_config.py
@@ -6,6 +6,7 @@ from pathlib import Path
# Environment variable names for configuration
ENV_DEVICE = "SIE_DEVICE"
+ENV_DEVICES = "SIE_DEVICES"
ENV_MODELS_DIR = "SIE_MODELS_DIR"
ENV_MODEL_FILTER = "SIE_MODEL_FILTER"
ENV_PRELOAD_MODELS = "SIE_PRELOAD_MODELS"
@@ -27,6 +28,9 @@ class AppStateConfig:
device: str = "cpu"
"""Device to load models on (e.g., "cuda:0", "cpu", "mps")."""
+ devices: list[str] | None = None
+ """Optional device list for whole-model placement (e.g., ["cuda:0", "cuda:1"])."""
+
model_filter: list[str] | None = None
"""Optional list of model names to include. If None, all models are available."""
@@ -39,6 +43,33 @@ class AppStateConfig:
pool_name: str | None = None
"""Optional worker pool identity used by ModelRegistry pool-isolation checks."""
+ def __post_init__(self) -> None:
+ """Keep scalar and concrete device settings in the same device family."""
+ if not self.devices:
+ return
+
+ devices = [d.strip() for d in self.devices if d.strip()]
+ if not devices:
+ self.devices = None
+ return
+
+ self.devices = devices
+ device_families = {d.split(":", maxsplit=1)[0].lower() for d in devices}
+ configured_family = self.device.strip().split(":", maxsplit=1)[0].lower()
+ families = ", ".join(sorted(device_families))
+
+ if len(device_families) != 1:
+ raise ValueError(
+ f"SIE_DEVICE family '{configured_family}' must match SIE_DEVICES families; got multiple: {families}"
+ )
+
+ if configured_family == "cpu" and len(device_families) == 1:
+ self.device = next(iter(device_families))
+ return
+
+ if configured_family not in device_families:
+ raise ValueError(f"SIE_DEVICE family '{configured_family}' must match SIE_DEVICES families: {families}")
+
def save_to_env_vars(self) -> None:
"""Serialize configuration to environment variables for uvicorn reload mode."""
if self.models_dir:
@@ -48,6 +79,11 @@ class AppStateConfig:
os.environ[ENV_DEVICE] = self.device
+ if self.devices:
+ os.environ[ENV_DEVICES] = ",".join(self.devices)
+ elif ENV_DEVICES in os.environ:
+ del os.environ[ENV_DEVICES]
+
if self.model_filter:
os.environ[ENV_MODEL_FILTER] = ",".join(self.model_filter)
elif ENV_MODEL_FILTER in os.environ:
@@ -72,6 +108,8 @@ class AppStateConfig:
def from_env_vars(cls) -> AppStateConfig:
"""Deserialize configuration from environment variables."""
device = os.environ.get(ENV_DEVICE, "cpu")
+ devices_str = os.environ.get(ENV_DEVICES)
+ devices = [d.strip() for d in devices_str.split(",") if d.strip()] if devices_str else None
models_dir = os.environ.get(ENV_MODELS_DIR)
model_filter_str = os.environ.get(ENV_MODEL_FILTER)
model_filter = [m.strip() for m in model_filter_str.split(",") if m.strip()] if model_filter_str else None
@@ -84,6 +122,7 @@ class AppStateConfig:
return cls(
models_dir=models_dir,
device=device,
+ devices=devices,
model_filter=model_filter,
preload_models=preload_models,
pinned_models=pinned_models,
diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.py
index 8ad9d4f0c..69ba32dd6 100644
--- a/packages/sie_server/src/sie_server/cli.py
+++ b/packages/sie_server/src/sie_server/cli.py
@@ -32,7 +32,7 @@ import typer
from sie_sdk.bundle_utils import find_bundle_for_models, match_bundle_models
import sie_server
-from sie_server.app.app_state_config import ENV_POOL, AppStateConfig
+from sie_server.app.app_state_config import ENV_DEVICES, ENV_POOL, AppStateConfig
from sie_server.core.loader import load_model_configs
from sie_server.main import run_server
@@ -72,6 +72,14 @@ def resolve_device(device: str) -> str:
return device
+def parse_devices(value: str | None) -> list[str] | None:
+ """Parse comma-separated concrete devices from an env var."""
+ if value is None:
+ return None
+ devices = [item.strip() for item in value.split(",") if item.strip()]
+ return devices or None
+
+
app = typer.Typer(
name="sie-server",
help="Search Inference Engine - GPU inference server for search workloads",
@@ -290,6 +298,8 @@ def serve(
# Resolve device (auto-detect if needed)
resolved_device = resolve_device(device)
pool_name = os.environ.get(ENV_POOL) or None
+ resolved_devices = parse_devices(os.environ.get(ENV_DEVICES))
+ pool_name = os.environ.get(ENV_POOL) or None
# Handle bundle/models filter
model_filter: list[str] | None = None
@@ -375,6 +385,8 @@ def serve(
typer.echo(f"Models directory: {models_dir_resolved}")
typer.echo(f"Device: {resolved_device}")
+ if resolved_devices:
+ typer.echo(f"Devices: {', '.join(resolved_devices)}")
if resolved_device == "mps":
# Apple-Silicon banner: surface the one-command local OpenAI endpoint so the
# first-run experience points at the playground / docs / OpenAI base URL.
@@ -416,6 +428,7 @@ def serve(
config = AppStateConfig(
models_dir=models_dir_resolved,
device=resolved_device,
+ devices=resolved_devices,
model_filter=model_filter,
preload_models=preload_models,
pool_name=pool_name,
diff --git a/packages/sie_server/src/sie_server/core/encode_pipeline.py b/packages/sie_server/src/sie_server/core/encode_pipeline.py
index ddffbb50e..a300ca570 100644
--- a/packages/sie_server/src/sie_server/core/encode_pipeline.py
+++ b/packages/sie_server/src/sie_server/core/encode_pipeline.py
@@ -102,6 +102,44 @@ class EncodePipeline:
)
timing.add_postprocessing_ms(postprocess_ms)
+ # Unit-meter fallback: adapters that own their tokenization (flash
+ # packing — the registry preprocessor is a char-count estimator
+ # there) expose real per-item counts via ``EncodeOutput.extra``.
+ # The preprocessor-recorded counts (authoritative too) win when both
+ # exist; malformed/misaligned values are dropped rather than
+ # mis-attributed — metering falls back to its reserve estimate.
+ if timing.input_token_counts is None:
+ extra_counts = encode_output.extra.get("input_token_counts")
+ if (
+ isinstance(extra_counts, list)
+ and len(extra_counts) == len(items)
+ and all(isinstance(count, int) and not isinstance(count, bool) for count in extra_counts)
+ ):
+ timing.input_token_counts = [int(count) for count in extra_counts]
+
+ # Shared metering seam: adapters that own their tokenization but do not
+ # pre-stamp ``extra`` (every flash text encoder — e5/bert_flash,
+ # ColBERT, …) still expose real counts through the base
+ # ``count_input_tokens`` hook, which re-tokenizes ``items`` with the
+ # adapter's own tokenizer (the §P3.5 ground-truth basis). This is a
+ # pure fallback: it never runs when the preprocessor or ``extra``
+ # already recorded counts, so bge-m3(-flash) keep their exact values.
+ # ``None`` (server-backed / image adapters) leaves the meter on its
+ # reserve estimate rather than billing an approximation.
+ if timing.input_token_counts is None:
+ try:
+ adapter = registry.get(model)
+ except KeyError:
+ adapter = None
+ if adapter is not None:
+ counts = await asyncio.to_thread(adapter.count_input_tokens, items)
+ if (
+ isinstance(counts, list)
+ and len(counts) == len(items)
+ and all(isinstance(count, int) and not isinstance(count, bool) for count in counts)
+ ):
+ timing.input_token_counts = [int(count) for count in counts]
+
formatted_output = EncodeHandler.format_output(
encode_output,
output_types=response_output_types if response_output_types is not None else output_types,
@@ -149,10 +187,12 @@ class EncodePipeline:
)
if fast_path is not None:
timing.end_tokenization()
+ cls._record_input_token_counts(preprocessor_registry, model, fast_path, timing)
return fast_path
prepared_batch = await preprocessor_registry.prepare(model, items, config, is_query=is_query)
timing.end_tokenization()
+ cls._record_input_token_counts(preprocessor_registry, model, prepared_batch, timing)
return prepared_batch
# Image path: use image preprocessor if available
@@ -180,6 +220,39 @@ class EncodePipeline:
# No preprocessor available - return None to signal direct adapter call
return None
+ @classmethod
+ def _record_input_token_counts(
+ cls,
+ preprocessor_registry: PreprocessorRegistry,
+ model: str,
+ prepared_batch: PreparedBatch | None,
+ timing: RequestTiming,
+ ) -> None:
+ """Record authoritative per-item input-token counts on ``timing``.
+
+ Only when the model's text preprocessor is the real
+ :class:`TextPreprocessor` — its ``PreparedItem.cost`` is
+ ``len(input_ids)`` from the actual tokenizer. Char-count estimators
+ (``CharCountPreprocessor`` for library-wrapped adapters) are skipped:
+ the unit meter counts, it never approximates, so estimated costs
+ must not masquerade as authoritative counts on the result path.
+ """
+ if prepared_batch is None or not prepared_batch.items:
+ return
+ try:
+ preprocessor = preprocessor_registry.get_preprocessor(model, "text")
+ except Exception: # noqa: BLE001 — descriptor lookup must never fail the request
+ return
+ if not isinstance(preprocessor, TextPreprocessor):
+ return
+ counts = [0] * len(prepared_batch.items)
+ for prepared in prepared_batch.items:
+ index = prepared.original_index
+ if not isinstance(index, int) or not 0 <= index < len(counts):
+ return # malformed batch — leave counts unset rather than mis-attribute
+ counts[index] = int(prepared.cost)
+ timing.input_token_counts = counts
+
@classmethod
async def _try_fast_path(
cls,
diff --git a/packages/sie_server/src/sie_server/core/inference_output.py b/packages/sie_server/src/sie_server/core/inference_output.py
index f3ea60908..b733fbb12 100644
--- a/packages/sie_server/src/sie_server/core/inference_output.py
+++ b/packages/sie_server/src/sie_server/core/inference_output.py
@@ -112,6 +112,17 @@ class ScoreOutput:
# Metadata
batch_size: int = 0
+ # Unit-meter seam (§7.3): authoritative per-pair input-token counts,
+ # aligned 1:1 with ``scores`` — the REAL tokenizer length of each
+ # (query, doc) pair the model processed, summed by the queue executor
+ # into ``ItemOutcome.units.input_tokens`` for the score work item.
+ # ``None`` when the adapter cannot surface a real count (char-proxy
+ # rerankers): metering then falls back to its reserve estimate rather
+ # than billing an estimate as a count. Sliced/assembled positionally
+ # with ``scores`` (see ScoreHandler) so fused cross-request batches
+ # keep each pair's count attributed to the right work item.
+ input_token_counts: list[int] | None = None
+
def __post_init__(self) -> None:
"""Validate consistency of output fields."""
if len(self.scores.shape) != 1:
@@ -122,6 +133,9 @@ class ScoreOutput:
elif self.scores.shape[0] != self.batch_size:
msg = f"scores batch size {self.scores.shape[0]} != {self.batch_size}"
raise ValueError(msg)
+ if self.input_token_counts is not None and len(self.input_token_counts) != self.batch_size:
+ msg = f"input_token_counts length {len(self.input_token_counts)} != batch_size {self.batch_size}"
+ raise ValueError(msg)
@dataclass
@@ -150,6 +164,25 @@ class ExtractOutput:
# Metadata
batch_size: int = 0
+ # Unit-meter seam (§7.3): authoritative per-item input-token counts,
+ # aligned 1:1 with ``entities`` — the REAL tokenizer length of each
+ # document as counted by the extractor's own tokenizer, surfaced by
+ # the queue executor as ``ItemOutcome.units.input_tokens``. ``None``
+ # when the adapter owns tokenization opaquely and cannot cheaply
+ # expose a count: metering then falls back to its reserve estimate
+ # rather than billing an estimate as a count. Sliced/assembled
+ # positionally with ``entities`` (see ExtractHandler).
+ input_token_counts: list[int] | None = None
+
+ # Unit-meter seam (§7): authoritative per-item PAGE counts, aligned 1:1
+ # with ``entities`` — the canonical parse/OCR billing dimension ("$ per
+ # 1k pages", design §7). Document-model parsers (docling) surface the real
+ # page count they processed here, which the queue executor folds into
+ # ``ItemOutcome.units.pages``. ``None`` when the adapter processes no
+ # document pages (text/NER extractors like GLiNER): metering then stays on
+ # its token/reserve basis. Sliced/assembled positionally with ``entities``.
+ pages: list[int] | None = None
+
def __post_init__(self) -> None:
"""Validate consistency of output fields."""
if self.batch_size == 0:
@@ -173,3 +206,11 @@ class ExtractOutput:
if self.data is not None and len(self.data) != self.batch_size:
msg = f"data list length {len(self.data)} != batch_size {self.batch_size}"
raise ValueError(msg)
+
+ if self.pages is not None and len(self.pages) != self.batch_size:
+ msg = f"pages list length {len(self.pages)} != batch_size {self.batch_size}"
+ raise ValueError(msg)
+
+ if self.input_token_counts is not None and len(self.input_token_counts) != self.batch_size:
+ msg = f"input_token_counts length {len(self.input_token_counts)} != batch_size {self.batch_size}"
+ raise ValueError(msg)
diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.py
index 0c63c4545..d146adf75 100644
--- a/packages/sie_server/src/sie_server/core/loader.py
+++ b/packages/sie_server/src/sie_server/core/loader.py
@@ -3,6 +3,7 @@ import importlib.util
import inspect
import logging
import os
+import re
import sys
import tempfile
import threading
@@ -28,6 +29,22 @@ logger = logging.getLogger(__name__)
# Error messages
_ERR_CONFIG_NOT_FOUND = "Config file not found: {path}"
+# Served-model version identity. An *immutable* HF revision is a
+# full 40-char git commit SHA (SHA-1, lowercase hex). Branch/tag names ("main",
+# "v1.0") resolve to *moving* targets on the Hub, so they are NOT acceptable
+# pins for a promoted/served model — the immutable-id contract is that a given
+# ``sie_id`` maps to identical weights forever. This regex is the single
+# authoritative rule; the staging/deploy tooling mirrors it rather than
+# importing this module, which would pull the adapter/torch stack into the
+# deploy tool.
+_IMMUTABLE_REVISION_RE = re.compile(r"^[0-9a-f]{40}$")
+
+
+def is_immutable_revision(revision: str | None) -> bool:
+ """Return True when ``revision`` is a full 40-char git commit SHA (immutable)."""
+ return revision is not None and _IMMUTABLE_REVISION_RE.match(revision) is not None
+
+
# Local cache for downloaded configs (used when models_dir is cloud)
_CONFIG_CACHE_DIR: Path | None = None
@@ -46,24 +63,68 @@ def _get_config_cache_dir() -> Path:
return _CONFIG_CACHE_DIR
-def load_model_configs(models_dir: Path | str) -> dict[str, ModelConfig]:
+def validate_pinned_revision(config: ModelConfig) -> None:
+ """Enforce the served-model version-identity contract.
+
+ A promoted/served, HF-backed model MUST pin ``hf_revision`` to an immutable
+ commit SHA so its ``sie_id`` maps to identical weights forever. ``weights_path``
+ and ``package_backed`` models are exempt: they carry their own immutable
+ weights / package version and have no Hub revision that can drift. Raises
+ ``ValueError`` naming the fix.
+ """
+ if config.hf_id is None:
+ # weights_path or package_backed: nothing on the Hub to pin.
+ return
+ revision = config.hf_revision
+ if revision is None:
+ msg = (
+ f"Served model '{config.sie_id}' (hf_id '{config.hf_id}') has no 'hf_revision'. "
+ "A promoted/served model must pin an immutable HF commit SHA so its id maps to "
+ "identical weights forever. Resolve the current SHA and pin it."
+ )
+ raise ValueError(msg)
+ if not is_immutable_revision(revision):
+ msg = (
+ f"Served model '{config.sie_id}' pins hf_revision={revision!r}, which is not an "
+ "immutable 40-char commit SHA — a branch/tag name (e.g. 'main') drifts on the Hub. "
+ "Pin the resolved commit SHA instead."
+ )
+ raise ValueError(msg)
+
+
+def require_pinned_revisions(configs: Mapping[str, ModelConfig]) -> None:
+ """Apply :func:`validate_pinned_revision` across a catalog; raise on the first violation."""
+ for config in configs.values():
+ validate_pinned_revision(config)
+
+
+def load_model_configs(models_dir: Path | str, *, require_pinned_revision: bool = False) -> dict[str, ModelConfig]:
"""Load all model configs from a directory (local or cloud).
Args:
models_dir: Path to the models directory (local path, s3://, gs://, abfs://, or abfss://).
+ require_pinned_revision: When True, reject any HF-backed config that does not pin an
+ immutable ``hf_revision``. Off by default so the full dev catalog
+ (which carries an unpinned long tail) still loads; the managed serving/staging
+ path opts in.
Returns:
Dictionary mapping model names to their ModelConfig objects.
Raises:
FileNotFoundError: If models_dir doesn't exist (local only).
- ValueError: If a config file is invalid.
+ ValueError: If a config file is invalid, or (when ``require_pinned_revision``)
+ a served model is missing an immutable revision pin.
"""
models_dir_str = str(models_dir)
if is_cloud_path(models_dir_str):
- return _load_configs_from_cloud(models_dir_str)
- return _load_configs_from_local(Path(models_dir_str))
+ configs = _load_configs_from_cloud(models_dir_str)
+ else:
+ configs = _load_configs_from_local(Path(models_dir_str))
+ if require_pinned_revision:
+ require_pinned_revisions(configs)
+ return configs
def _load_configs_from_local(models_dir: Path) -> dict[str, ModelConfig]:
diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.py
index 3329f8548..0e30c329d 100644
--- a/packages/sie_server/src/sie_server/core/model_loader.py
+++ b/packages/sie_server/src/sie_server/core/model_loader.py
@@ -620,9 +620,15 @@ class ModelLoader:
max_loras=self._max_loras_per_model,
)
- # Preload profile LoRAs if adapter supports LoRA
+ # Preload profile LoRAs if adapter supports LoRA. Engine-owned adapters
+ # (sglang: ``supports_hot_lora_reload() == False``) consume
+ # ``loadtime.lora_paths`` themselves at engine launch, so only
+ # hot-reload (PEFT) adapters take the loadtime declarations from here.
if adapter.supports_lora():
- profile_loras = self._collect_profile_loras(config)
+ profile_loras = self._collect_profile_loras(
+ config,
+ include_loadtime_paths=adapter.supports_hot_lora_reload(),
+ )
if profile_loras:
logger.info(
"Preloading %d profile LoRAs for model '%s': %s",
@@ -654,28 +660,70 @@ class ModelLoader:
logger.info("Model '%s' loaded successfully", name)
return loaded_model
- def _collect_profile_loras(self, config: ModelConfig) -> set[str]:
+ def _collect_profile_loras(
+ self,
+ config: ModelConfig,
+ *,
+ include_loadtime_paths: bool = True,
+ ) -> set[str]:
"""Collect all LoRA paths from model profiles.
- Profiles can specify a `lora_id` in `adapter_options.runtime` that points
- to a HuggingFace path or local path for a LoRA adapter. This method
- collects all unique LoRA paths across all profiles for preloading.
+ The canonical spelling is
+ ``adapter_options.loadtime["lora_paths"]`` — either a list of
+ HuggingFace/local paths (each path doubles as the public LoRA id on
+ the PEFT path) or a dict of served-name → path (the sglang shape,
+ whose paths are what a PEFT adapter would load). The scalar
+ ``adapter_options.runtime["lora_id"]`` is the DEPRECATED legacy alias:
+ it is still accepted here for existing embedding profiles, but new
+ profiles should declare ``loadtime.lora_paths`` (the scalar form is
+ already rejected outright on generation models — see
+ ``core.pool_isolation.validate_no_legacy_scalar_lora_id``).
Args:
config: Model configuration.
+ include_loadtime_paths: Collect the canonical
+ ``loadtime.lora_paths`` declarations. Pass ``False`` for
+ engine-owned adapters (sglang) that load those at engine
+ launch themselves — preloading them again here would
+ double-load.
Returns:
Set of unique LoRA paths from profiles.
"""
loras: set[str] = set()
- # Collect LoRAs from profiles (lora_id lives in adapter_options.runtime)
for profile_name, profile_config in config.profiles.items():
+ # Canonical key: adapter_options.loadtime["lora_paths"].
+ if include_loadtime_paths:
+ lora_paths = profile_config.adapter_options.loadtime.get("lora_paths")
+ entries: list[str] = []
+ if isinstance(lora_paths, dict):
+ entries = [str(path) for path in lora_paths.values() if path]
+ elif isinstance(lora_paths, (list, tuple)):
+ entries = [str(path) for path in lora_paths if path]
+ elif lora_paths:
+ logger.warning(
+ "Profile '%s' declares loadtime.lora_paths with unexpected "
+ "shape %s (expected list of paths or dict name->path); ignoring",
+ profile_name,
+ type(lora_paths).__name__,
+ )
+ for lora_path in entries:
+ loras.add(lora_path)
+ logger.debug(
+ "Found LoRA '%s' in profile '%s' (loadtime.lora_paths)",
+ lora_path,
+ profile_name,
+ )
+
+ # DEPRECATED alias: the scalar runtime["lora_id"] predates the
+ # canonical loadtime.lora_paths spelling and is kept only for
+ # backward compatibility with existing embedding profiles.
lora_id = profile_config.adapter_options.runtime.get("lora_id")
if lora_id:
loras.add(lora_id)
logger.debug(
- "Found LoRA '%s' in profile '%s'",
+ "Found LoRA '%s' in profile '%s' (legacy runtime.lora_id)",
lora_id,
profile_name,
)
diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.py
index 1616c2175..23a1790fb 100644
--- a/packages/sie_server/src/sie_server/core/registry.py
+++ b/packages/sie_server/src/sie_server/core/registry.py
@@ -43,7 +43,7 @@ from sie_server.core.pool_isolation import (
)
from sie_server.core.postprocessor_registry import PostprocessorRegistry
from sie_server.core.preprocessor_registry import PreprocessorRegistry
-from sie_server.core.residency import EvictionResult
+from sie_server.core.residency import EvictionResult, select_eviction_candidate
from sie_server.core.worker import ModelWorker
from sie_server.core.worker.types import AdaptiveBatchingParams
from sie_server.observability.metrics import record_idle_eviction
@@ -132,6 +132,25 @@ def _adapter_load_required_bytes(adapter: ModelAdapter, memory_manager: MemoryMa
return min(required, stats.total_bytes)
+def _normalize_devices(device: str, devices: list[str] | None) -> list[str]:
+ """Return a non-empty, de-duplicated device list preserving order."""
+ raw_devices = devices or [device]
+ normalized: list[str] = []
+ seen: set[str] = set()
+ for raw in raw_devices:
+ item = raw.strip()
+ if not item or item in seen:
+ continue
+ normalized.append(item)
+ seen.add(item)
+ return normalized or [device]
+
+
+def _device_family(device: str) -> str:
+ """Return the root device family (``cuda`` for ``cuda:0``)."""
+ return device.split(":", 1)[0].lower()
+
+
class ModelRegistry:
"""Registry for managing model configs and loaded models.
@@ -155,6 +174,7 @@ class ModelRegistry:
drain_timeout_s: float = 30.0,
model_filter: list[str] | None = None,
device: str = "cpu",
+ devices: list[str] | None = None,
engine_config: EngineConfig | None = None,
enable_hot_reload: bool = True,
pool_name: str | None = None,
@@ -169,6 +189,9 @@ class ModelRegistry:
drain_timeout_s: Timeout in seconds to wait for worker drain before unload.
model_filter: Optional list of model names to include. If None, all models are available.
device: Default device for memory tracking (e.g., "cuda:0", "mps", "cpu").
+ devices: Optional ordered list of devices available to this worker.
+ When set, lazy model loads place whole models across these
+ devices; adapters still receive a single concrete device.
enable_hot_reload: Whether to enable hot reload of model configs when models_dir is set.
pool_name: The worker's pool identity (``SIE_POOL``).
Used to gate the pool-isolation validator that rejects mixing
@@ -185,6 +208,8 @@ class ModelRegistry:
self._models_dir: str | None = str(models_dir) if models_dir is not None else None
self._model_filter = set(model_filter) if model_filter else None
self._device = device
+ self._devices = _normalize_devices(device, devices)
+ self._device_order = {name: i for i, name in enumerate(self._devices)}
self._enable_hot_reload = enable_hot_reload
self._pool_name = pool_name.strip().lower() if pool_name else None
# Normalised pinned set: bare lowercase sie_ids, never chosen for eviction.
@@ -197,7 +222,13 @@ class ModelRegistry:
# Share CPU pool between preprocessor and postprocessor registries
self._postprocessor_registry = PostprocessorRegistry(self._preprocessor_registry._executor)
self._memory_config = memory_config or MemoryConfig()
- self._memory_manager = MemoryManager(device=device, config=self._memory_config)
+ self._memory_managers = {
+ device_name: MemoryManager(device=device_name, config=self._memory_config) for device_name in self._devices
+ }
+ # Default manager for callers that operate on the registry's primary
+ # device. Multi-device code paths use ``_memory_manager_for_device``
+ # with the loaded model's concrete device.
+ self._memory_manager = self._memory_managers[self._devices[0]]
self._drain_timeout_s = drain_timeout_s
# Disk cache management
@@ -533,8 +564,16 @@ class ModelRegistry:
@property
def memory_manager(self) -> MemoryManager:
"""Return the memory manager for device memory tracking."""
+ active_managers = [manager for manager in self._memory_managers.values() if manager.loaded_model_count > 0]
+ if len(active_managers) == 1:
+ return active_managers[0]
return self._memory_manager
+ @property
+ def memory_managers(self) -> dict[str, MemoryManager]:
+ """Return memory managers keyed by concrete device."""
+ return dict(self._memory_managers)
+
@property
def engine_config(self) -> EngineConfig | None:
"""Return the engine config (or None if running without one).
@@ -550,6 +589,65 @@ class ModelRegistry:
"""Return the default device for model loading."""
return self._device
+ @property
+ def devices(self) -> list[str]:
+ """Return concrete devices available for whole-model placement."""
+ return list(self._devices)
+
+ def _memory_manager_for_device(self, device: str) -> MemoryManager:
+ manager = self._memory_managers.get(device)
+ if manager is None:
+ manager = MemoryManager(device=device, config=self._memory_config)
+ self._memory_managers[device] = manager
+ self._device_order[device] = len(self._device_order)
+ return manager
+
+ def _memory_manager_for_model(self, name: str) -> MemoryManager:
+ loaded = self._loaded.get(name)
+ if loaded is None:
+ return self._memory_manager
+ return self._memory_manager_for_device(loaded.device)
+
+ def _select_device_for_model(self, requested_family: str | None = None) -> str:
+ candidates = [
+ device for device in self._devices if requested_family is None or _device_family(device) == requested_family
+ ]
+
+ def score(device: str) -> tuple[bool, int, int]:
+ manager = self._memory_manager_for_device(device)
+ try:
+ under_pressure = manager.check_pressure()
+ except Exception:
+ logger.exception("Failed to check memory pressure for device %s; keeping it eligible", device)
+ under_pressure = False
+ return (under_pressure, manager.loaded_model_count, self._device_order[device])
+
+ return min(candidates, key=score)
+
+ def _resolve_load_device(self, requested_device: str) -> str:
+ """Resolve a request/default device to one concrete load target."""
+ if len(self._devices) == 1:
+ only_device = self._devices[0]
+ if (
+ requested_device != only_device
+ and _device_family(requested_device) == _device_family(only_device)
+ and ":" in only_device
+ and ":" not in requested_device
+ ):
+ return only_device
+ return requested_device
+ if requested_device in self._memory_managers and requested_device not in self._devices:
+ return requested_device
+ if requested_device in self._devices:
+ return requested_device
+ if ":" in requested_device:
+ return requested_device
+ requested_family = _device_family(requested_device)
+ device_families = {_device_family(device) for device in self._devices}
+ if requested_family in device_families:
+ return self._select_device_for_model(requested_family)
+ return requested_device
+
def has_model(self, name: str) -> bool:
"""Check if a model config exists in the registry."""
return name in self._configs
@@ -712,7 +810,7 @@ class ModelRegistry:
protected from eviction. No-op for a model that is not loaded.
"""
if name in self._loaded:
- self._memory_manager.touch(name)
+ self._memory_manager_for_model(name).touch(name)
def load(self, name: str, device: str) -> ModelAdapter:
"""Load a model onto a device.
@@ -739,6 +837,9 @@ class ModelRegistry:
msg = _ERR_MODEL_ALREADY_LOADED.format(name=name)
raise ValueError(msg)
+ load_device = self._resolve_load_device(device)
+ memory_manager = self._memory_manager_for_device(load_device)
+
# Ensure model weights are cached (download from HF / cluster cache
# if needed). Kept as a distinct phase from instantiate so the
# post-download timeout in ``ModelLoader`` does not cover the
@@ -746,23 +847,24 @@ class ModelRegistry:
# ``HF_HUB_DOWNLOAD_TIMEOUT`` stall detection only.
self._loader.ensure_weights_cached(config)
- # Instantiate the adapter with device-aware fallback selection
- adapter = self._loader.instantiate_adapter(name, config, model_dir, device)
+ # Instantiate the adapter on the resolved concrete device.
+ adapter = self._loader.instantiate_adapter(name, config, model_dir, load_device)
- required_load_bytes = _adapter_load_required_bytes(adapter, self._memory_manager)
- while self._memory_manager.should_evict_for_load(required_load_bytes):
- lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)
+ required_load_bytes = _adapter_load_required_bytes(adapter, memory_manager)
+ while memory_manager.should_evict_for_load(required_load_bytes):
+ lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)
if lru_model is None:
break
- stats = self._memory_manager.get_stats()
+ stats = memory_manager.get_stats()
logger.info(
- "Pre-load eviction: %.2f GB free, %.2f GB required, %.1f%% used "
+ "Pre-load eviction: %s %.2f GB free, %.2f GB required, %.1f%% used "
"(threshold %.1f%%); evicting '%s' before loading '%s'",
+ load_device,
stats.available_gb,
(required_load_bytes or 0) / (1024**3),
stats.usage_ratio * 100,
- self._memory_manager.pressure_threshold_pct,
+ memory_manager.pressure_threshold_pct,
lru_model,
name,
)
@@ -770,13 +872,13 @@ class ModelRegistry:
# Try to load onto device, with OOM retry
try:
- loaded = self._loader.load_and_register(name, device, adapter, config)
+ loaded = self._loader.load_and_register(name, load_device, adapter, config)
except RuntimeError as e:
if not self._is_oom_error(e):
raise
# OOM - try to evict LRU non-pinned model and retry
- lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)
+ lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)
if lru_model is None:
logger.error("OOM loading '%s' but no non-pinned models to evict", name)
raise
@@ -790,14 +892,14 @@ class ModelRegistry:
# Retry once after eviction - weights still on disk so we
# skip ``ensure_weights_cached`` here.
- adapter = self._loader.instantiate_adapter(name, config, model_dir, device)
- loaded = self._loader.load_and_register(name, device, adapter, config)
+ adapter = self._loader.instantiate_adapter(name, config, model_dir, load_device)
+ loaded = self._loader.load_and_register(name, load_device, adapter, config)
# Track loaded state
self._loaded[name] = loaded
# Register with memory manager for LRU tracking
- self._memory_manager.register_model(name, estimated_bytes=loaded.memory_bytes)
+ self._memory_manager_for_device(loaded.device).register_model(name, estimated_bytes=loaded.memory_bytes)
# Clear any stale failure record from a prior attempt.
self._failed.pop(name, None)
@@ -834,15 +936,19 @@ class ModelRegistry:
async with lock:
# Double-check after acquiring lock (another request may have loaded it)
if name in self._loaded:
- self._memory_manager.touch(name)
+ self._memory_manager_for_model(name).touch(name)
return self._loaded[name].adapter
+ load_device = self._resolve_load_device(device)
+ memory_manager = self._memory_manager_for_device(load_device)
+
# Check if model is being unloaded - caller should retry
if name in self._unloading:
msg = f"Model '{name}' is currently being unloaded"
raise RuntimeError(msg)
config = self._configs[name]
+ config = self._configs[name]
# Mark as loading before starting (visible to WebSocket status)
self._loading.add(name)
@@ -859,14 +965,14 @@ class ModelRegistry:
await self._loader.ensure_weights_cached_async(name, config)
# Instantiate adapter (in thread pool, post-download timeout applies)
- adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, device)
+ adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, load_device)
- required_load_bytes = _adapter_load_required_bytes(adapter, self._memory_manager)
+ required_load_bytes = _adapter_load_required_bytes(adapter, memory_manager)
# Pre-load eviction: evict LRU non-pinned models until current pressure
# and any adapter-provided load headroom requirement are satisfied.
- while self._memory_manager.should_evict_for_load(required_load_bytes):
- lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)
+ while memory_manager.should_evict_for_load(required_load_bytes):
+ lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)
if lru_model is None:
break # No non-pinned models to evict, proceed with load attempt
@@ -880,17 +986,18 @@ class ModelRegistry:
"Evictor found ghost '%s' (in memory manager, not loaded); dropping stale entry",
lru_model,
)
- self._memory_manager.unregister_model(lru_model)
+ memory_manager.unregister_model(lru_model)
continue
- stats = self._memory_manager.get_stats()
+ stats = memory_manager.get_stats()
logger.info(
- "Pre-load eviction: %.2f GB free, %.2f GB required, %.1f%% used "
+ "Pre-load eviction: %s %.2f GB free, %.2f GB required, %.1f%% used "
"(threshold %.1f%%); evicting '%s' before loading '%s'",
+ load_device,
stats.available_gb,
(required_load_bytes or 0) / (1024**3),
stats.usage_ratio * 100,
- self._memory_manager.pressure_threshold_pct,
+ memory_manager.pressure_threshold_pct,
lru_model,
name,
)
@@ -898,13 +1005,13 @@ class ModelRegistry:
try:
# Load onto device (loader handles main thread vs executor)
- loaded = await self._loader.load_and_register_async(name, device, adapter, config)
+ loaded = await self._loader.load_and_register_async(name, load_device, adapter, config)
except RuntimeError as e:
if not self._is_oom_error(e):
raise
# OOM despite pre-load eviction: evict LRU non-pinned model and retry once
- lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)
+ lru_model = memory_manager.get_lru_model(exclude=self._pinned_models)
if lru_model is None:
logger.error("OOM loading '%s' but no non-pinned models to evict", name)
raise
@@ -918,14 +1025,17 @@ class ModelRegistry:
# Retry once after eviction. Weights are still cached
# on disk so we skip ``ensure_weights_cached_async``.
- adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, device)
- loaded = await self._loader.load_and_register_async(name, device, adapter, config)
+ adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, load_device)
+ loaded = await self._loader.load_and_register_async(name, load_device, adapter, config)
# Track loaded state
self._loaded[name] = loaded
# Register with memory manager for LRU tracking
- self._memory_manager.register_model(name, estimated_bytes=loaded.memory_bytes)
+ self._memory_manager_for_device(loaded.device).register_model(
+ name,
+ estimated_bytes=loaded.memory_bytes,
+ )
load_duration = time.monotonic() - load_start
if load_duration > 300:
@@ -1103,7 +1213,7 @@ class ModelRegistry:
self._loader.unregister(name, device)
# Unregister from memory manager
- self._memory_manager.unregister_model(name)
+ self._memory_manager_for_device(device).unregister_model(name)
logger.info("Model '%s' unloaded", name)
@@ -1198,7 +1308,7 @@ class ModelRegistry:
except Exception: # noqa: BLE001 - best-effort; must not skip below
logger.warning("loader.unregister failed during unload of '%s'", name, exc_info=True)
# Unregister from memory manager (a plain dict-pop; never raises)
- self._memory_manager.unregister_model(name)
+ self._memory_manager_for_device(device).unregister_model(name)
# Freeing memory makes any prior OOM-class load failure on a
# *sibling* model retryable; clear those records so the next
@@ -1610,7 +1720,7 @@ class ModelRegistry:
msg = f"Worker not available for model '{name}'"
raise RuntimeError(msg)
- self._memory_manager.touch(name)
+ self._memory_manager_for_model(name).touch(name)
if not worker.is_running:
await worker.start()
@@ -1702,30 +1812,32 @@ class ModelRegistry:
return EvictionResult.LOCK_TIMEOUT
try:
- # Walk LRU order and pick the first that is not ``exclude_name``,
- # not pinned, and is still loaded (the OrderedDict in the memory
- # manager may include entries already torn down by another path).
- for candidate in self._memory_manager.loaded_models:
- if candidate == exclude_name:
- continue
- if self._is_pinned(candidate):
- continue
- if candidate not in self._loaded:
- continue
- if candidate in self._unloading:
- continue
- logger.info(
- "OOM recovery: evicting LRU sibling '%s' (caller='%s')",
- candidate,
- exclude_name,
- )
- try:
- await self._do_unload(candidate)
- except Exception:
- logger.exception("OOM recovery: failed to evict '%s'", candidate)
- return EvictionResult.UNLOAD_FAILED
- return EvictionResult.EVICTED
- return EvictionResult.NO_CANDIDATE
+ manager = self._memory_manager_for_model(exclude_name)
+ # Residency policy owns the *decision* (which sibling to evict);
+ # the registry owns the *action* (draining + unloading it). Use
+ # the caller's device-local LRU order so multi-device OOM recovery
+ # frees memory on the GPU that actually hit pressure.
+ candidate = select_eviction_candidate(
+ manager.loaded_models,
+ exclude_name=exclude_name,
+ is_pinned=self._is_pinned,
+ loaded=self._loaded,
+ unloading=self._unloading,
+ )
+ if candidate is None:
+ return EvictionResult.NO_CANDIDATE
+ logger.info(
+ "OOM recovery: evicting LRU sibling '%s' on %s (caller='%s')",
+ candidate,
+ manager.device,
+ exclude_name,
+ )
+ try:
+ await self._do_unload(candidate)
+ except Exception:
+ logger.exception("OOM recovery: failed to evict '%s'", candidate)
+ return EvictionResult.UNLOAD_FAILED
+ return EvictionResult.EVICTED
finally:
lock.release()
@@ -1831,7 +1943,11 @@ class ModelRegistry:
while self._idle_evict_running:
try:
await asyncio.sleep(interval)
- stale = self._memory_manager.get_idle_models(idle_threshold_s=threshold, exclude=self._pinned_models)
+ stale = [
+ name
+ for manager in self._memory_managers.values()
+ for name in manager.get_idle_models(idle_threshold_s=threshold, exclude=self._pinned_models)
+ ]
if not stale:
continue
@@ -1843,7 +1959,7 @@ class ModelRegistry:
# arrived after the snapshot.
if name not in self._loaded:
continue
- info = self._memory_manager.get_model_info(name)
+ info = self._memory_manager_for_model(name).get_model_info(name)
if info is None:
continue
age = time.monotonic() - info.last_used_at
@@ -1921,48 +2037,49 @@ class ModelRegistry:
await asyncio.sleep(self._memory_config.memory_check_interval_s)
# Quick check without lock
- if not self._memory_manager.check_pressure():
+ pressured_managers = [manager for manager in self._memory_managers.values() if manager.check_pressure()]
+ if not pressured_managers:
continue
# Pressure detected - acquire lock and evict
lock = self._get_load_lock()
async with lock:
- # Re-check under lock (may have resolved)
- while self._memory_manager.check_pressure():
- # Don't evict if only 1 model loaded - would cause immediate reload
- if self._memory_manager.loaded_model_count <= 1:
- logger.debug(
- "Memory pressure detected but only %d model loaded, skipping eviction",
- self._memory_manager.loaded_model_count,
- )
- break
-
- lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)
- if lru_model is None:
- logger.debug(
- "Memory pressure detected but no non-pinned models to evict, skipping",
- )
- break
-
- if lru_model not in self._loaded:
- # Belt-and-braces ghost guard (see #1600): drop a
- # stale MemoryManager entry with no ``_loaded``
- # model instead of spinning on a no-op _do_unload.
- logger.warning(
- "Memory monitor found ghost '%s' (not loaded); dropping stale entry",
+ for manager in pressured_managers:
+ # Re-check under lock (may have resolved)
+ while manager.check_pressure():
+ # Don't evict if only 1 model loaded - would cause immediate reload
+ if manager.loaded_model_count <= 1:
+ logger.debug(
+ "Memory pressure detected on %s but only %d model loaded, skipping eviction",
+ manager.device,
+ manager.loaded_model_count,
+ )
+ break
+
+ lru_model = manager.get_lru_model(exclude=self._pinned_models)
+ if lru_model is None:
+ break
+
+ if lru_model not in self._loaded:
+ # Belt-and-braces ghost guard (see #1600): drop a
+ # stale MemoryManager entry with no ``_loaded``
+ # model instead of spinning on a no-op _do_unload.
+ logger.warning(
+ "Memory monitor found ghost '%s' (not loaded); dropping stale entry",
+ lru_model,
+ )
+ manager.unregister_model(lru_model)
+ continue
+
+ stats = manager.get_stats()
+ logger.info(
+ "Memory monitor: %s pressure %.1f%% > %.1f%% threshold, evicting LRU model '%s'",
+ manager.device,
+ stats.usage_ratio * 100,
+ manager.pressure_threshold_pct,
lru_model,
)
- self._memory_manager.unregister_model(lru_model)
- continue
-
- stats = self._memory_manager.get_stats()
- logger.info(
- "Memory monitor: pressure %.1f%% > %.1f%% threshold, evicting LRU model '%s'",
- stats.usage_ratio * 100,
- self._memory_manager.pressure_threshold_pct,
- lru_model,
- )
- await self._do_unload(lru_model)
+ await self._do_unload(lru_model)
except asyncio.CancelledError:
break
diff --git a/packages/sie_server/src/sie_server/core/residency.py b/packages/sie_server/src/sie_server/core/residency.py
index 49278a10d..be5bb12c0 100644
--- a/packages/sie_server/src/sie_server/core/residency.py
+++ b/packages/sie_server/src/sie_server/core/residency.py
@@ -13,6 +13,10 @@ import the registry).
from __future__ import annotations
from enum import Enum
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Container, Iterable
class EvictionResult(Enum):
@@ -40,3 +44,37 @@ class EvictionResult(Enum):
UNLOAD_FAILED = "unload_failed"
"""A candidate was selected but its unload raised."""
+
+
+def select_eviction_candidate(
+ lru_order: Iterable[str],
+ *,
+ exclude_name: str,
+ is_pinned: Callable[[str], bool],
+ loaded: Container[str],
+ unloading: Container[str],
+) -> str | None:
+ """Pick the first LRU-ordered model eligible for eviction, or ``None``.
+
+ Walks ``lru_order`` (least-recently-used first) and returns the first entry
+ that is not the caller's own ``exclude_name``, not pinned, still ``loaded``,
+ and not already ``unloading``. Pure decision — no I/O, no unload — so the
+ OOM-recovery eviction *policy* is testable in isolation and lives in one
+ place instead of inline in ``ModelRegistry.evict_lru_excluding``.
+
+ The registry state is injected (``is_pinned`` predicate, ``loaded`` /
+ ``unloading`` containers) so this stays free of any registry import — the
+ worker's OOM-recovery path must not import the registry. This is the next
+ slice of the ResidencyPolicy seam described in this module's docstring.
+ """
+ for candidate in lru_order:
+ if candidate == exclude_name:
+ continue
+ if is_pinned(candidate):
+ continue
+ if candidate not in loaded:
+ continue
+ if candidate in unloading:
+ continue
+ return candidate
+ return None
diff --git a/packages/sie_server/src/sie_server/core/timing.py b/packages/sie_server/src/sie_server/core/timing.py
index 36a896413..166005ffb 100644
--- a/packages/sie_server/src/sie_server/core/timing.py
+++ b/packages/sie_server/src/sie_server/core/timing.py
@@ -34,6 +34,17 @@ class RequestTiming:
_postprocess_end: float | None = field(default=None, repr=False)
_end_time: float | None = field(default=None, repr=False)
+ # Authoritative per-item input-token counts, aligned with the request's
+ # item order; ``None`` when no real tokenizer count exists (image path,
+ # char-count estimators). Set by ``EncodePipeline._prepare_batch`` from
+ # ``PreparedItem.cost`` — the same post-tokenization value used for
+ # batching — because this object is the only per-request carrier that
+ # already travels from tokenization to the result path. Consumers
+ # (``queue_executor``) surface it as ``ItemOutcome.units`` for metering;
+ # estimates are deliberately never recorded here (billing must count,
+ # not approximate).
+ input_token_counts: list[int] | None = field(default=None, repr=False)
+
def start_tokenization(self) -> None:
"""Mark tokenization start."""
self._tokenize_start = time.monotonic()
diff --git a/packages/sie_server/src/sie_server/core/worker/handlers/encode.py b/packages/sie_server/src/sie_server/core/worker/handlers/encode.py
index c99e07b32..2533ab90e 100644
--- a/packages/sie_server/src/sie_server/core/worker/handlers/encode.py
+++ b/packages/sie_server/src/sie_server/core/worker/handlers/encode.py
@@ -134,6 +134,16 @@ class EncodeHandler(OperationHandler[EncodeOutput]):
Returns:
Single-item EncodeOutput.
"""
+ # Per-item unit counts (``extra["input_token_counts"]``, emitted by
+ # adapters that own their tokenization) are positional like dense/
+ # sparse, so they must be sliced with the item — dropping them here
+ # would silently strip the meter's counts whenever the worker fuses
+ # requests into one GPU batch. Other ``extra`` keys have no defined
+ # per-item semantics and are intentionally not propagated.
+ extra: dict[str, Any] = {}
+ counts = output.extra.get("input_token_counts") if output.extra else None
+ if isinstance(counts, list) and 0 <= index < len(counts):
+ extra["input_token_counts"] = [counts[index]]
return EncodeOutput(
dense=output.dense[index : index + 1] if output.dense is not None else None,
sparse=[output.sparse[index]] if output.sparse is not None else None,
@@ -142,6 +152,7 @@ class EncodeHandler(OperationHandler[EncodeOutput]):
is_query=output.is_query,
dense_dim=output.dense_dim,
multivector_token_dim=output.multivector_token_dim,
+ extra=extra,
)
def assemble_output(
@@ -190,6 +201,21 @@ class EncodeHandler(OperationHandler[EncodeOutput]):
if first.multivector is not None:
multivector = [partials[i].multivector[0] for i in range(batch_size)] # ty: ignore[not-subscriptable]
+ # Reassemble per-item unit counts (see slice_output). All-or-nothing:
+ # a partial without a count means the meter cannot attribute the
+ # request exactly, so no counts are surfaced (metering then falls
+ # back to its reserve estimate rather than under-counting).
+ extra: dict[str, Any] = {}
+ assembled_counts: list[int] = []
+ for i in range(batch_size):
+ partial_counts = partials[i].extra.get("input_token_counts") if partials[i].extra else None
+ if not (isinstance(partial_counts, list) and len(partial_counts) == 1):
+ assembled_counts = []
+ break
+ assembled_counts.append(partial_counts[0])
+ if assembled_counts:
+ extra["input_token_counts"] = assembled_counts
+
return EncodeOutput(
dense=dense,
sparse=sparse,
@@ -198,6 +224,7 @@ class EncodeHandler(OperationHandler[EncodeOutput]):
is_query=first.is_query,
dense_dim=first.dense_dim,
multivector_token_dim=first.multivector_token_dim,
+ extra=extra,
)
@classmethod
diff --git a/packages/sie_server/src/sie_server/core/worker/handlers/extract.py b/packages/sie_server/src/sie_server/core/worker/handlers/extract.py
index 2dfe9dca3..0747ae709 100644
--- a/packages/sie_server/src/sie_server/core/worker/handlers/extract.py
+++ b/packages/sie_server/src/sie_server/core/worker/handlers/extract.py
@@ -93,6 +93,16 @@ class ExtractHandler(OperationHandler[ExtractOutput]):
relations = [output.relations[index]] if output.relations is not None else None
objects = [output.objects[index]] if output.objects is not None else None
data = [output.data[index]] if output.data is not None else None
+ # Unit-meter counts are positional like ``entities``; slice them with
+ # the item so fused cross-request batches keep each doc's real token
+ # count attributed to the right work item (see EncodeHandler).
+ counts = output.input_token_counts
+ sliced_counts = [counts[index]] if counts is not None and 0 <= index < len(counts) else None
+ # Per-item page counts are positional like token counts (see above):
+ # slice them with the item so the parse/OCR page dimension (§7) stays
+ # attributed to the right work item under cross-request fusion.
+ pages = output.pages
+ sliced_pages = [pages[index]] if pages is not None and 0 <= index < len(pages) else None
return ExtractOutput(
entities=[output.entities[index]],
classifications=classifications,
@@ -100,6 +110,8 @@ class ExtractHandler(OperationHandler[ExtractOutput]):
objects=objects,
data=data,
batch_size=1,
+ input_token_counts=sliced_counts,
+ pages=sliced_pages,
)
def assemble_output(
@@ -157,6 +169,29 @@ class ExtractHandler(OperationHandler[ExtractOutput]):
p_data = partials[i].data
data.append(p_data[0] if p_data is not None else {})
+ # Reassemble per-item unit counts (see slice_output). All-or-nothing:
+ # a partial without a count means the meter cannot attribute the item
+ # exactly, so no counts are surfaced (metering falls back to its
+ # reserve estimate rather than under-counting).
+ assembled_counts: list[int] = []
+ for i in range(batch_size):
+ partial_counts = partials[i].input_token_counts
+ if not (isinstance(partial_counts, list) and len(partial_counts) == 1):
+ assembled_counts = []
+ break
+ assembled_counts.append(partial_counts[0])
+
+ # Reassemble per-item page counts (same all-or-nothing contract as the
+ # token counts): a partial missing its page count means the parse
+ # dimension cannot be attributed exactly, so no pages are surfaced.
+ assembled_pages: list[int] = []
+ for i in range(batch_size):
+ partial_pages = partials[i].pages
+ if not (isinstance(partial_pages, list) and len(partial_pages) == 1):
+ assembled_pages = []
+ break
+ assembled_pages.append(partial_pages[0])
+
return ExtractOutput(
entities=entities,
classifications=classifications,
@@ -164,6 +199,8 @@ class ExtractHandler(OperationHandler[ExtractOutput]):
objects=objects,
data=data,
batch_size=batch_size,
+ input_token_counts=assembled_counts or None,
+ pages=assembled_pages or None,
)
@classmethod
diff --git a/packages/sie_server/src/sie_server/core/worker/handlers/score.py b/packages/sie_server/src/sie_server/core/worker/handlers/score.py
index 256bede77..5eb6000f4 100644
--- a/packages/sie_server/src/sie_server/core/worker/handlers/score.py
+++ b/packages/sie_server/src/sie_server/core/worker/handlers/score.py
@@ -89,9 +89,17 @@ class ScoreHandler(OperationHandler[ScoreOutput]):
Returns:
Single-item ScoreOutput.
"""
+ # Unit-meter counts (``input_token_counts``) are positional like
+ # ``scores``, so they must be sliced with the pair — dropping them
+ # here would strip the meter's real per-pair token count whenever
+ # the worker fuses score requests into one GPU batch (mirrors
+ # EncodeHandler.slice_output's handling of ``input_token_counts``).
+ counts = output.input_token_counts
+ sliced_counts = [counts[index]] if counts is not None and 0 <= index < len(counts) else None
return ScoreOutput(
scores=output.scores[index : index + 1],
batch_size=1,
+ input_token_counts=sliced_counts,
)
def assemble_output(
@@ -112,4 +120,20 @@ class ScoreHandler(OperationHandler[ScoreOutput]):
return ScoreOutput(scores=np.array([], dtype=np.float32), batch_size=0)
scores = np.concatenate([partials[i].scores for i in range(batch_size)])
- return ScoreOutput(scores=scores, batch_size=batch_size)
+
+ # Reassemble per-pair unit counts (see slice_output). All-or-nothing:
+ # a partial without a count means the meter cannot attribute the work
+ # item exactly, so no counts are surfaced (metering then falls back to
+ # its reserve estimate rather than under-counting).
+ assembled_counts: list[int] = []
+ for i in range(batch_size):
+ partial_counts = partials[i].input_token_counts
+ if not (isinstance(partial_counts, list) and len(partial_counts) == 1):
+ assembled_counts = []
+ break
+ assembled_counts.append(partial_counts[0])
+ return ScoreOutput(
+ scores=scores,
+ batch_size=batch_size,
+ input_token_counts=assembled_counts or None,
+ )
diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.py
index 1f15321cf..f1861c134 100644
--- a/packages/sie_server/src/sie_server/ipc_server.py
+++ b/packages/sie_server/src/sie_server/ipc_server.py
@@ -13,6 +13,8 @@ from typing import Any, Self
import msgpack
from sie_server.adapter_call_loop import handle_run_batch
+from sie_server.core.gpu_health import gpu_is_healthy_async
+from sie_server.core.readiness import is_ready
from sie_server.ipc_types import (
IPC_VERSION,
METHOD_APPLY_MODEL_CONFIG,
@@ -516,6 +518,11 @@ class IpcServer:
async def _handle_ping(self, req: PingRequest) -> PingResponse:
self._last_ping_monotonic = time.monotonic()
+ ready = False
+ try:
+ ready = is_ready() and await gpu_is_healthy_async()
+ except Exception: # noqa: BLE001
+ logger.debug("Could not compute readiness for ping", exc_info=True)
bundle_config_hash = ""
if self._bundle_id:
try:
@@ -530,6 +537,7 @@ class IpcServer:
return PingResponse(
timestamp_ms=req.timestamp_ms,
worker_id=self._worker_id,
+ ready=ready,
bundle_config_hash=bundle_config_hash,
loaded_models=loaded_models,
)
diff --git a/packages/sie_server/src/sie_server/ipc_types.py b/packages/sie_server/src/sie_server/ipc_types.py
index f0c5ce145..07cd92f2e 100644
--- a/packages/sie_server/src/sie_server/ipc_types.py
+++ b/packages/sie_server/src/sie_server/ipc_types.py
@@ -62,6 +62,7 @@ class PingRequest(msgspec.Struct):
class PingResponse(msgspec.Struct):
timestamp_ms: float
worker_id: str
+ ready: bool = False
bundle_config_hash: str = ""
loaded_models: list[str] = msgspec.field(default_factory=list)
@@ -469,6 +470,27 @@ class RawOutput(msgspec.Struct):
# -----------------------------------------------------------------------------
+class UnitCounts(msgspec.Struct):
+ """Authoritative billable-unit counts for one work item.
+
+ Emitted by the engine on the result path so metering edges (gateways,
+ usage pipelines) never re-derive units from estimates: ``input_tokens``
+ is the REAL tokenizer count taken post-tokenization (``PreparedItem.cost``
+ for text preprocessing), not a bytes/4-style approximation.
+
+ All fields are optional: a field is set only when the engine has an
+ authoritative count for it. ``pages`` (docling parse/OCR) and ``images``
+ (vision extract/encode) are populated by the queue executor when the
+ pipeline surfaces per-item counts (see ``queue_executor._with_pages`` /
+ ``_with_images`` / ``_per_item_image_counts``); they stay ``None`` for
+ work that carries no such count.
+ """
+
+ input_tokens: int | None = None
+ pages: int | None = None
+ images: int | None = None
+
+
class ItemOutcome(msgspec.Struct):
work_item_id: str
request_id: str
@@ -487,6 +509,11 @@ class ItemOutcome(msgspec.Struct):
# empty and the Rust publisher produces the final wire bytes. See
# ``RawOutput`` above for the fallback matrix.
raw_output: RawOutput | None = None
+ # Authoritative billable-unit counts (see ``UnitCounts``). Optional and
+ # appended last: msgspec encodes Structs as msgpack maps, so decoders
+ # that don't know the key (older Rust sidecars) ignore it and older
+ # producers simply omit it — the NATS wire contract is unchanged.
+ units: UnitCounts | None = None
class BatchOutcome(msgspec.Struct):
diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.py
index 2d2b4b7e0..049d19835 100644
--- a/packages/sie_server/src/sie_server/queue_executor.py
+++ b/packages/sie_server/src/sie_server/queue_executor.py
@@ -43,6 +43,7 @@ from sie_server.ipc_types import (
SetPinnedModelsRequest,
SetPinnedModelsResponse,
SparseOutput,
+ UnitCounts,
)
from sie_server.observability.metrics import record_ipc_batch_shape
from sie_server.types.inputs import InvalidMediaError, Item, decode_item
@@ -906,6 +907,20 @@ class QueueExecutor:
# path (#1489). An unknown profile name raises ValueError, which
# the surrounding except turns into per-item failures.
options = merge_runtime_options(config, options)
+ # Profile-default ``output_types`` parity with the OSS HTTP path
+ # (api.encode resolves ``profile > request > default``). The
+ # gateway forwards only the request-level output_types, so a
+ # profile whose runtime declares an output_types default (e.g.
+ # the ``bge-m3:sparse`` variant, whose promoted "default" profile
+ # carries ``output_types: [sparse]``) would otherwise be served
+ # dense-only here — the managed path silently dropped it. Reuse
+ # the merged profile runtime (same resolver, no duplicated
+ # precedence) and apply it exactly as api.encode does. The group
+ # key already folded request→``["dense"]``, so this is precisely
+ # ``profile or request or default``, keeping managed == OSS (P6.6).
+ profile_output_types = options.get("output_types")
+ if profile_output_types:
+ output_types = list(profile_output_types)
formatted_outputs, timing = await EncodePipeline.run_encode(
registry=self._registry,
model=model_id,
@@ -936,6 +951,28 @@ class QueueExecutor:
"adapter returned fewer outputs than items",
)
else:
+ # Authoritative unit counts for metering: per-item real
+ # tokenizer counts recorded by the pipeline during
+ # tokenization (see ``RequestTiming.input_token_counts``).
+ # ``None`` (image path / char-count estimators) leaves
+ # ``ItemOutcome.units`` unset — metering edges fall back
+ # to their reserve estimate rather than bill an estimate
+ # as a count.
+ token_counts = timing.input_token_counts
+ if token_counts is not None and len(token_counts) != len(good_group):
+ token_counts = None # misaligned — never mis-attribute counts
+ # Authoritative per-image counts for the §7 "$ per image"
+ # dimension: any vision adapter (CLIP/SigLIP) inherits the
+ # base ``count_input_images`` hook, so an image-input encode
+ # bills per image the same way a text encode bills per
+ # token. ``None`` (adapter evicted, or an all-text batch)
+ # leaves ``images`` unset. Aligned 1:1 with ``server_items``
+ # (== ``good_group`` order).
+ try:
+ encode_adapter = self._registry.get(model_id)
+ except KeyError:
+ encode_adapter = None
+ image_counts = _per_item_image_counts(encode_adapter, server_items, len(good_group))
for idx, bi in enumerate(good_group):
raw_output: RawOutput | None = None
result_msgpack: bytes | None = None
@@ -966,6 +1003,19 @@ class QueueExecutor:
)
if raw_output is None:
output = _wrap_encode_output(formatted_outputs[idx], config)
+ # Echo the caller's item id (G2b, P2.8 finding): the
+ # HTTP path stamps ``result["id"] = item.id`` in
+ # ``api.encode._build_response_items`` and the SDK
+ # copies it back (``parse_encode_results``), but the
+ # queue-path result blob dropped it. Bake it into the
+ # legacy blob here so it round-trips like SCORE's
+ # ``item_id``. The RawOutput fast paths carry the id
+ # at framing time instead (frame_raw_output on the
+ # lane); this branch is the multi-output / non-f32
+ # fallback.
+ item_id = server_items[idx].id
+ if item_id is not None:
+ output = {"id": item_id, **output}
result_msgpack = msgpack.packb(output, use_bin_type=True)
outcomes[bi.work_item_id] = ItemOutcome(
work_item_id=bi.work_item_id,
@@ -977,6 +1027,10 @@ class QueueExecutor:
inference_ms=timing.inference_ms,
tokenization_ms=timing.tokenization_ms if timing.tokenization_ms > 0 else None,
postprocessing_ms=timing.postprocessing_ms if timing.postprocessing_ms > 0 else None,
+ units=_encode_units(
+ token_counts[idx] if token_counts is not None else None,
+ image_counts[idx] if image_counts is not None else None,
+ ),
)
except Exception as e: # noqa: BLE001
logger.warning("Encode sub-batch failed for model %s: %s", model_id, e)
@@ -1013,7 +1067,7 @@ class QueueExecutor:
outcomes: dict[str, ItemOutcome] = {}
requests: list[PreformedScoreRequest] = []
- request_context: list[tuple[ScoreBatchItem, list[Item]]] = []
+ request_context: list[tuple[ScoreBatchItem, Item, list[Item]]] = []
for bi in req.items:
try:
@@ -1022,6 +1076,11 @@ class QueueExecutor:
timing = RequestTiming()
timing.start_tokenization()
+ # ``score_pair_cost`` here is the char-count BATCHING proxy
+ # only. Authoritative billable counts (§7.3) are the reranker's
+ # real per-pair tokenizer lengths, surfaced on the resulting
+ # ScoreOutput and summed into ``ItemOutcome.units`` in
+ # ``_score_success_outcome`` — never this proxy.
prepared_items = build_score_prepared_items(query_item, score_items)
timing.end_tokenization()
@@ -1036,25 +1095,35 @@ class QueueExecutor:
timing=timing,
)
)
- request_context.append((bi, score_items))
+ request_context.append((bi, query_item, score_items))
except Exception as e: # noqa: BLE001
logger.warning("Score preparation failed for %s: %s", bi.work_item_id, e)
outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)
+ # Adapter for the metering backfill (§7.3). Read via the registry — the
+ # same sync accessor the encode seam uses — so a reranker that owns its
+ # tokenization can re-derive real per-pair counts. ``None`` (evicted
+ # mid-batch) simply leaves the meter on its reserve estimate.
+ try:
+ score_adapter = self._registry.get(model_id)
+ except KeyError:
+ score_adapter = None
+
if requests:
try:
futures = await worker.submit_score_preformed_batch(requests)
results = await asyncio.gather(*futures, return_exceptions=True)
except Exception as e: # noqa: BLE001
logger.warning("Score batch failed for model %s: %s", model_id, e)
- for bi, _score_items in request_context:
+ for bi, _query_item, _score_items in request_context:
outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)
else:
- for (bi, score_items), result in zip(request_context, results, strict=True):
+ for (bi, query_item, score_items), result in zip(request_context, results, strict=True):
if isinstance(result, BaseException):
logger.warning("Score failed for %s: %s", bi.work_item_id, result)
outcomes[bi.work_item_id] = _inference_exception_outcome(bi, result)
else:
+ _backfill_score_units(score_adapter, bi, query_item, score_items, result)
outcomes[bi.work_item_id] = _score_success_outcome(
bi,
score_items,
@@ -1086,7 +1155,18 @@ class QueueExecutor:
outcomes: dict[str, ItemOutcome] = {}
grouped_requests: dict[str | None, list[PreformedExtractRequest]] = {}
- grouped_context: dict[str | None, list[ExtractBatchItem]] = {}
+ # Carry the decoded ``Item`` alongside each ``ExtractBatchItem`` so the
+ # success path can bill vision extract (Florence-2) per image via the
+ # adapter's ``count_input_images`` hook (§7 "$ per image").
+ grouped_context: dict[str | None, list[tuple[ExtractBatchItem, Item]]] = {}
+
+ # Adapter for the per-image metering seam (§7), read via the registry —
+ # the same sync accessor the encode/score seams use. ``None`` (evicted
+ # mid-batch) simply leaves the images dimension unset.
+ try:
+ extract_adapter = self._registry.get(model_id)
+ except KeyError:
+ extract_adapter = None
for bi in req.items:
try:
@@ -1094,6 +1174,12 @@ class QueueExecutor:
timing = RequestTiming()
timing.start_tokenization()
+ # ``char_count`` here is the BATCHING cost proxy only.
+ # Authoritative billable counts (§7.3) are the extractor's real
+ # per-doc tokenizer length, surfaced on the resulting
+ # ExtractOutput and stamped into ``ItemOutcome.units`` in
+ # ``_extract_success_outcome`` — never this proxy. (``pages``
+ # for future docling/OCR inputs stays a separate seam.)
char_count = len(server_item.text) if server_item.text else 0
prepared_items = [ExtractPreparedItem(cost=char_count, original_index=0)]
timing.end_tokenization()
@@ -1111,7 +1197,7 @@ class QueueExecutor:
timing=timing,
)
)
- grouped_context.setdefault(lora, []).append(bi)
+ grouped_context.setdefault(lora, []).append((bi, server_item))
except Exception as e: # noqa: BLE001
logger.warning("Extract preparation failed for %s: %s", bi.work_item_id, e)
outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)
@@ -1123,19 +1209,158 @@ class QueueExecutor:
results = await asyncio.gather(*futures, return_exceptions=True)
except Exception as e: # noqa: BLE001
logger.warning("Extract batch failed for model %s: %s", model_id, e)
- for bi in context:
+ for bi, _server_item in context:
outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)
else:
- for bi, result in zip(context, results, strict=True):
+ for (bi, server_item), result in zip(context, results, strict=True):
if isinstance(result, BaseException):
logger.warning("Extract failed for %s: %s", bi.work_item_id, result)
outcomes[bi.work_item_id] = _inference_exception_outcome(bi, result)
else:
- outcomes[bi.work_item_id] = _extract_success_outcome(bi, result)
+ outcomes[bi.work_item_id] = _extract_success_outcome(extract_adapter, bi, server_item, result)
return BatchOutcome(outcomes=[outcomes[bi.work_item_id] for bi in req.items])
+def _per_item_image_counts(adapter: Any, items: list[Item], expected_len: int) -> list[int] | None:
+ """Per-item authoritative input-image counts via the adapter's shared
+ ``count_input_images`` hook (§7 "$ per image").
+
+ Returns ``None`` — leaving the images dimension unset so the metering edge
+ stays on its token/reserve basis — on a missing adapter or any misaligned /
+ malformed list, so a per-image count is never mis-attributed. Never raises:
+ metering must not fail inference.
+ """
+ if adapter is None:
+ return None
+ try:
+ counts = adapter.count_input_images(items)
+ except Exception: # noqa: BLE001 — metering must never fail inference
+ return None
+ if (
+ isinstance(counts, list)
+ and len(counts) == expected_len
+ and all(isinstance(c, int) and not isinstance(c, bool) and c >= 0 for c in counts)
+ ):
+ return counts
+ return None
+
+
+def _encode_units(token_count: int | None, image_count: int | None) -> UnitCounts | None:
+ """Assemble one encode item's ``UnitCounts`` from its authoritative token
+ and image counts.
+
+ Each dimension is set only when present, and ``images`` only when ``> 0``
+ (a text-only item never emits ``images=0``). An item with neither yields
+ ``None`` so the metering edge falls back to its reserve estimate. Kept
+ byte-identical to the prior ``UnitCounts(input_tokens=...)`` emitter when
+ there are no images: ``images`` defaults to ``None`` on the struct.
+ """
+ images = image_count if (image_count is not None and image_count > 0) else None
+ if token_count is None and images is None:
+ return None
+ return UnitCounts(input_tokens=token_count, images=images)
+
+
+def _with_images(units: UnitCounts | None, image_count: int | None) -> UnitCounts | None:
+ """Fold an authoritative image count into an existing ``UnitCounts`` (§7
+ "$ per image"), minting one when only images are present.
+
+ ``image_count`` of ``None`` / ``<= 0`` is a no-op (never emits ``images=0``)
+ so text extract (GLiNER, …) is unchanged.
+ """
+ if image_count is None or image_count <= 0:
+ return units
+ if units is None:
+ return UnitCounts(images=image_count)
+ return UnitCounts(input_tokens=units.input_tokens, pages=units.pages, images=image_count)
+
+
+def _with_pages(units: UnitCounts | None, page_count: int | None) -> UnitCounts | None:
+ """Fold an authoritative page count into an existing ``UnitCounts`` — the §7
+ canonical parse/OCR dimension ("$ per 1k pages") — minting one when only
+ pages are present.
+
+ ``page_count`` of ``None`` / ``<= 0`` is a no-op (never emits ``pages=0``)
+ so token/vision extract is unchanged. Preserves the token and image
+ dimensions so folds compose in any order.
+ """
+ if page_count is None or page_count <= 0:
+ return units
+ if units is None:
+ return UnitCounts(pages=page_count)
+ return UnitCounts(input_tokens=units.input_tokens, pages=page_count, images=units.images)
+
+
+def _page_total(pages: Any, expected_len: int) -> int | None:
+ """Sum an adapter-surfaced per-item page list (``ExtractOutput.pages``) into a
+ single billable page count for the work item.
+
+ Returns ``None`` — leaving the pages dimension unset so the meter falls back
+ to its reserve estimate — unless the list is well-formed (aligned 1:1 with
+ the item's outputs, non-negative ints) and sums to ``> 0``. A misaligned or
+ malformed list is dropped rather than mis-attributed.
+ """
+ if not isinstance(pages, list) or len(pages) != expected_len:
+ return None
+ if not all(isinstance(p, int) and not isinstance(p, bool) and p >= 0 for p in pages):
+ return None
+ total = sum(pages)
+ return total if total > 0 else None
+
+
+def _units_from_token_counts(counts: Any, expected_len: int) -> UnitCounts | None:
+ """Sum authoritative per-item token counts into a work item's ``UnitCounts``.
+
+ Mirrors the encode metering contract (§7.3): billing counts, never
+ estimates. Returns ``None`` — leaving ``ItemOutcome.units`` unset so the
+ metering edge falls back to its reserve estimate — unless the adapter
+ surfaced a well-formed list aligned 1:1 with the item's outputs. A
+ misaligned or malformed list is dropped rather than mis-attributed.
+ """
+ if not isinstance(counts, list) or len(counts) != expected_len:
+ return None
+ if not all(isinstance(c, int) and not isinstance(c, bool) for c in counts):
+ return None
+ return UnitCounts(input_tokens=sum(int(c) for c in counts))
+
+
+def _backfill_score_units(
+ adapter: Any,
+ bi: ScoreBatchItem,
+ query_item: Item,
+ score_items: list[Item],
+ worker_result: Any,
+) -> None:
+ """Shared metering seam: stamp authoritative per-pair token counts onto the
+ ``ScoreOutput`` when the reranker did not surface them itself.
+
+ Rerankers that own their tokenization but don't populate
+ ``ScoreOutput.input_token_counts`` (every flash cross-encoder) otherwise
+ leave the meter blind. The base ``count_pair_input_tokens`` hook recovers
+ the real joint (query, doc) lengths with the adapter's own tokenizer — the
+ §7.3 basis the in-tree ``cross_encoder`` already surfaces. Pure fallback:
+ never overwrites counts an adapter already produced (so bge-m3 / cross_encoder
+ keep their exact values), and a ``None`` recovery (server-backed adapters)
+ leaves the meter on its reserve estimate.
+ """
+ if adapter is None:
+ return
+ output = getattr(worker_result, "output", None)
+ if output is None or getattr(output, "input_token_counts", None) is not None:
+ return
+ try:
+ counts = adapter.count_pair_input_tokens(query_item, score_items, instruction=bi.instruction)
+ except Exception: # noqa: BLE001 — metering must never fail inference
+ return
+ if (
+ isinstance(counts, list)
+ and len(counts) == output.batch_size
+ and all(isinstance(count, int) and not isinstance(count, bool) for count in counts)
+ ):
+ output.input_token_counts = counts
+
+
def _score_success_outcome(
bi: ScoreBatchItem,
score_items: list[Item],
@@ -1146,6 +1371,16 @@ def _score_success_outcome(
item_ids: list[str] = [
(sid if (sid := score_items[i].id) is not None else f"item-{i}") for i in range(score_output.batch_size)
]
+ # Authoritative unit counts (§7.3): the reranker tokenizes each (query, doc)
+ # pair, and the score handler carries those real per-pair counts on the
+ # assembled ScoreOutput. Bill their sum — the total input tokens the model
+ # processed for this query × N-docs work item — as $/1M input tokens
+ # (§7.1). ``None`` (char-proxy rerankers) leaves units unset → reserve
+ # fallback, never an estimate billed as a count.
+ units = _units_from_token_counts(
+ getattr(score_output, "input_token_counts", None),
+ score_output.batch_size,
+ )
# Score output is always Rust-frameable: the Python and Rust
# sort/rank paths produce byte-identical results (see the
@@ -1170,14 +1405,18 @@ def _score_success_outcome(
postprocessing_ms=worker_result.timing.postprocessing_ms
if worker_result.timing.postprocessing_ms > 0
else None,
+ units=units,
)
def _extract_success_outcome(
+ adapter: Any,
bi: ExtractBatchItem,
+ server_item: Item,
worker_result: Any,
) -> ItemOutcome:
- extraction_results = ExtractHandler.format_output(worker_result.output)
+ extract_output = worker_result.output
+ extraction_results = ExtractHandler.format_output(extract_output)
if not extraction_results:
# Adapter returned no results for a single-item request —
# surface as an error instead of silently publishing an
@@ -1186,6 +1425,27 @@ def _extract_success_outcome(
return _error_outcome(bi, "inference_error", "adapter returned no extraction results")
result_msgpack = msgpack.packb(extraction_results[0], use_bin_type=True)
+ # Authoritative unit counts (§7.3): the extractor tokenizes the document
+ # and the extract handler carries that real per-doc count on the assembled
+ # ExtractOutput. Extract work items are single-doc, so ``batch_size == 1``;
+ # bill the count as $/1M input tokens (§7.1). ``None`` leaves units unset →
+ # reserve fallback, never an estimate billed as a count.
+ units = _units_from_token_counts(
+ getattr(extract_output, "input_token_counts", None),
+ extract_output.batch_size,
+ )
+ # Parse/OCR extract (docling) has no token count but parses document PAGES —
+ # bill it per page (§7 "$ per 1k pages", the canonical parse dimension) from
+ # the real page count the adapter surfaced on ``ExtractOutput.pages``. Folds
+ # alongside any token/image count; token/vision extract (no pages) unchanged.
+ units = _with_pages(units, _page_total(getattr(extract_output, "pages", None), extract_output.batch_size))
+ # Vision extract (Florence-2 caption/OCR/extract) has no token count but
+ # consumes image inputs — bill it per image (§7 "$ per image") via the
+ # shared ``count_input_images`` hook. Folds alongside any token count;
+ # text extract (GLiNER, single text doc, no images) is unchanged.
+ image_counts = _per_item_image_counts(adapter, [server_item], 1)
+ units = _with_images(units, image_counts[0] if image_counts is not None else None)
+
return ItemOutcome(
work_item_id=bi.work_item_id,
request_id=bi.request_id,
@@ -1197,6 +1457,7 @@ def _extract_success_outcome(
postprocessing_ms=worker_result.timing.postprocessing_ms
if worker_result.timing.postprocessing_ms > 0
else None,
+ units=units,
)
diff --git a/packages/sie_server/tests/adapters/test_adapter_revision_contract.py b/packages/sie_server/tests/adapters/test_adapter_revision_contract.py
new file mode 100644
index 000000000..02dc0d313
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_adapter_revision_contract.py
@@ -0,0 +1,202 @@
+"""Loader contract: every adapter must accept (and honor) a pinned HF ``revision``.
+
+The model loader adds ``revision=config.hf_revision`` to the adapter constructor
+kwargs whenever a model YAML pins ``hf_revision`` (version identity).
+An adapter whose ``__init__`` rejects ``revision`` hard-fails at load
+(``TypeError: __init__() got an unexpected keyword argument 'revision'`` — the
+CI eval-loader failure this suite regresses against), and an adapter that accepts
+it via ``**kwargs`` but never forwards it silently drops the pin.
+
+This module enforces the *acceptance* half of that contract for EVERY adapter
+class the package exposes, parameterized so a future adapter cannot regress
+silently, plus *forwarding* spot-checks (clip / siglip / a flash adapter) that a
+pinned revision actually reaches the HuggingFace ``from_pretrained`` call.
+
+Pure and offline: no weights are downloaded and no model is loaded — HF loaders
+are mocked, and signature inspection imports only the adapter modules.
+"""
+
+from __future__ import annotations
+
+import importlib
+import inspect
+import pkgutil
+from unittest.mock import MagicMock, patch
+
+import pytest
+import sie_server.adapters as adapters_pkg
+from sie_server.adapters.base import ModelAdapter
+
+# Shared/abstract bases that are never instantiated as concrete adapters. The
+# ``inspect.isabstract`` filter already drops these (they leave ``load`` etc.
+# unimplemented), but naming them keeps the intent explicit and stable.
+_ABSTRACT_BASES = frozenset({"ModelAdapter", "BaseAdapter", "FlashBaseAdapter"})
+
+
+def _discover_adapter_classes() -> list[type[ModelAdapter]]:
+ """Import every adapter submodule and return the concrete adapter classes.
+
+ Modules that cannot be imported because an optional heavy dependency is
+ absent from the unit environment (e.g. ``sglang``/``mlx_lm`` off their target
+ platforms) are skipped — those adapters are exercised in the image that ships
+ the dependency. Real import errors surface via the count/core guards below.
+ """
+ discovered: dict[str, type[ModelAdapter]] = {}
+ for mod_info in pkgutil.walk_packages(adapters_pkg.__path__, prefix=f"{adapters_pkg.__name__}."):
+ try:
+ module = importlib.import_module(mod_info.name)
+ except Exception: # noqa: BLE001, S112 — optional deps may be absent in the unit env; skip
+ continue
+ for name, obj in inspect.getmembers(module, inspect.isclass):
+ if obj.__module__ != mod_info.name:
+ continue # skip base classes / symbols imported into the module
+ if not issubclass(obj, ModelAdapter) or name in _ABSTRACT_BASES:
+ continue
+ if inspect.isabstract(obj):
+ continue
+ discovered[f"{obj.__module__}.{name}"] = obj
+ return [discovered[key] for key in sorted(discovered)]
+
+
+_ADAPTER_CLASSES = _discover_adapter_classes()
+
+
+def _accepts_revision(cls: type) -> bool:
+ """True if ``cls.__init__`` accepts a ``revision`` kwarg (explicit or VAR_KEYWORD)."""
+ params = inspect.signature(cls.__init__).parameters.values()
+ return any(param.name == "revision" or param.kind is inspect.Parameter.VAR_KEYWORD for param in params)
+
+
+def test_discovery_imported_the_adapter_package() -> None:
+ """Guard: discovery actually walked the package (not a mass import failure)."""
+ # There are dozens of adapters; a tiny count means imports broke wholesale.
+ assert len(_ADAPTER_CLASSES) >= 20, f"only discovered {len(_ADAPTER_CLASSES)} adapters — imports likely broke"
+ names = {cls.__name__ for cls in _ADAPTER_CLASSES}
+ # These depend only on always-present core deps (transformers /
+ # sentence-transformers), so they must always be discovered.
+ for required in ("CLIPAdapter", "SiglipAdapter", "CrossEncoderAdapter", "PyTorchEmbeddingAdapter"):
+ assert required in names, f"{required} not discovered — adapter import regressed"
+
+
[email protected]("adapter_cls", _ADAPTER_CLASSES, ids=lambda cls: cls.__name__)
+def test_adapter_init_accepts_revision(adapter_cls: type) -> None:
+ """Every adapter ``__init__`` must accept the loader's pinned ``revision`` kwarg."""
+ assert _accepts_revision(adapter_cls), (
+ f"{adapter_cls.__module__}.{adapter_cls.__name__}.__init__ must accept a 'revision' keyword "
+ "(explicit 'revision: str | None = None' or **kwargs) so a YAML-pinned hf_revision is not "
+ "rejected by the loader (see core/loader._build_adapter_kwargs)."
+ )
+
+
+class TestRevisionReachesFromPretrained:
+ """Forwarding spot-checks: a pinned revision reaches the HF load calls."""
+
+ def test_clip_forwards_revision(self) -> None:
+ from sie_server.adapters.clip import CLIPAdapter
+
+ adapter = CLIPAdapter("openai/clip-vit-base-patch32", revision="deadbeef")
+ assert adapter._revision == "deadbeef"
+
+ mock_model = MagicMock()
+ mock_model.to.return_value = mock_model
+ with (
+ patch("transformers.CLIPProcessor") as mock_proc,
+ patch("transformers.CLIPModel") as mock_mdl,
+ ):
+ mock_mdl.from_pretrained.return_value = mock_model
+ adapter.load("cpu")
+
+ assert mock_proc.from_pretrained.call_args.kwargs["revision"] == "deadbeef"
+ assert mock_mdl.from_pretrained.call_args.kwargs["revision"] == "deadbeef"
+
+ def test_clip_without_revision_omits_kwarg(self) -> None:
+ from sie_server.adapters.clip import CLIPAdapter
+
+ adapter = CLIPAdapter("openai/clip-vit-base-patch32")
+ mock_model = MagicMock()
+ mock_model.to.return_value = mock_model
+ with (
+ patch("transformers.CLIPProcessor") as mock_proc,
+ patch("transformers.CLIPModel") as mock_mdl,
+ ):
+ mock_mdl.from_pretrained.return_value = mock_model
+ adapter.load("cpu")
+
+ assert "revision" not in mock_proc.from_pretrained.call_args.kwargs
+ assert "revision" not in mock_mdl.from_pretrained.call_args.kwargs
+
+ def test_siglip_transformers_backend_forwards_revision(self) -> None:
+ from sie_server.adapters.siglip import SiglipAdapter
+
+ adapter = SiglipAdapter("google/siglip-so400m-patch14-384", revision="cafef00d")
+ assert adapter._revision == "cafef00d"
+
+ mock_model = MagicMock()
+ mock_model.to.return_value = mock_model
+ with (
+ patch("transformers.SiglipProcessor") as mock_proc,
+ patch("transformers.SiglipModel") as mock_mdl,
+ ):
+ mock_mdl.from_pretrained.return_value = mock_model
+ adapter.load("cpu")
+
+ assert mock_proc.from_pretrained.call_args.kwargs["revision"] == "cafef00d"
+ assert mock_mdl.from_pretrained.call_args.kwargs["revision"] == "cafef00d"
+
+ def test_flash_adapter_forwards_revision(self) -> None:
+ """A representative flash embedding adapter threads revision into both loaders."""
+ from sie_server.adapters.bert_flash import BertFlashAdapter
+
+ adapter = BertFlashAdapter("intfloat/e5-base-v2", revision="0ff1ce")
+ assert adapter._revision == "0ff1ce"
+
+ mock_model = MagicMock()
+ mock_model.to.return_value = mock_model
+ with (
+ patch("transformers.AutoTokenizer") as mock_tok,
+ patch("transformers.AutoModel") as mock_mdl,
+ ):
+ mock_mdl.from_pretrained.return_value = mock_model
+ # Flash adapters require a CUDA device string; the HF loaders and
+ # ``.to()`` are mocked, so no real GPU is touched.
+ adapter.load("cuda:0")
+
+ assert mock_tok.from_pretrained.call_args.kwargs["revision"] == "0ff1ce"
+ assert mock_mdl.from_pretrained.call_args.kwargs["revision"] == "0ff1ce"
+
+ def test_colsmol_pins_lora_repo_only_not_base(self) -> None:
+ """ColSmol pins the LoRA-repo loads but never the separate base-checkpoint repo.
+
+ Regression: ``base_id`` is a *different* repo discovered from the LoRA's
+ ``adapter_config``; forwarding the LoRA repo's revision SHA to it raises
+ RevisionNotFoundError → 503 on the first request under a pinned YAML.
+ """
+ from sie_server.adapters import colsmol
+ from sie_server.adapters.colsmol import ColSmolAdapter
+
+ base_repo = "vidore/ColSmolVLM-Instruct-256M-base"
+ adapter = ColSmolAdapter("vidore/colSmol-256M", revision="feedface")
+ assert adapter._revision == "feedface"
+
+ peft_cfg = MagicMock()
+ peft_cfg.base_model_name_or_path = base_repo
+ base_cls = MagicMock()
+ with (
+ patch("peft.PeftConfig") as mock_peft_cfg,
+ patch("peft.PeftModel") as mock_peft_model,
+ patch("transformers.Idefics3Config") as mock_config,
+ patch("transformers.Idefics3Processor") as mock_proc,
+ patch.object(colsmol, "_make_colidefics3_cls", return_value=base_cls),
+ ):
+ mock_peft_cfg.from_pretrained.return_value = peft_cfg
+ adapter.load("cpu")
+
+ # LoRA-repo loads (they read vidore/colSmol-256M) carry the pin.
+ assert mock_peft_cfg.from_pretrained.call_args.kwargs["revision"] == "feedface"
+ assert mock_proc.from_pretrained.call_args.kwargs["revision"] == "feedface"
+ assert mock_peft_model.from_pretrained.call_args.kwargs["revision"] == "feedface"
+ # base_id loads target the *base* repo and must NOT carry the LoRA revision.
+ assert mock_config.from_pretrained.call_args.args[0] == base_repo
+ assert "revision" not in mock_config.from_pretrained.call_args.kwargs
+ assert base_cls.from_pretrained.call_args.args[0] == base_repo
+ assert "revision" not in base_cls.from_pretrained.call_args.kwargs
diff --git a/packages/sie_server/tests/adapters/test_clip.py b/packages/sie_server/tests/adapters/test_clip.py
index a5b5ff0a0..b02f67a0c 100644
--- a/packages/sie_server/tests/adapters/test_clip.py
+++ b/packages/sie_server/tests/adapters/test_clip.py
@@ -1,16 +1,125 @@
from __future__ import annotations
+import io
+import threading
+import time
+from typing import Any
from unittest.mock import MagicMock, patch
import numpy as np
import pytest
+import torch
+from PIL import Image
from sie_server.adapters.clip import CLIPAdapter
from sie_server.types.inputs import Item
+from torch.nn import functional
# Create a random generator for tests
_RNG = np.random.default_rng(42)
+def _png_bytes(color: tuple[int, int, int]) -> bytes:
+ """Encode a solid-color 8x8 RGB PNG (a real image the decode path can open)."""
+ buf = io.BytesIO()
+ Image.new("RGB", (8, 8), color).save(buf, format="PNG")
+ return buf.getvalue()
+
+
+def _img_item(item_id: str, colors: list[tuple[int, int, int]]) -> Item:
+ return Item(id=item_id, images=[{"data": _png_bytes(c), "format": "png"} for c in colors])
+
+
+class _SimpleTokenizer:
+ """Minimal HF-tokenizer stand-in for the §7.3 text-metering seam.
+
+ ``_token_counts_or_none`` calls ``tokenizer(texts, truncation=..., max_length=...)``
+ and reads ``["input_ids"]`` as a list of per-text id lists.
+ """
+
+ def __call__(self, texts: list[str], truncation: bool = False, max_length: int | None = None, **_kw: Any):
+ return {"input_ids": [list(range(len(t))) for t in texts]}
+
+
+class _FakeVisionProcessor:
+ """Deterministic, pure-function stand-in for CLIP/SigLIP processors.
+
+ Maps each image to its mean RGB (a ``[3]`` feature) and each text to a
+ ``[3]`` id vector, so per-item preprocessing is independent and the model
+ below can be a pure per-row linear map — making a stacked forward exactly
+ equal to per-item serial forwards.
+ """
+
+ def __init__(self) -> None:
+ self.image_calls = 0
+ self.text_calls = 0
+ # The §7.3 text-metering seam recounts tokens off ``processor.tokenizer``.
+ self.tokenizer = _SimpleTokenizer()
+
+ def __call__(
+ self, images: Any = None, text: Any = None, return_tensors: Any = None, **_kw: Any
+ ) -> dict[str, torch.Tensor]:
+ if images is not None:
+ self.image_calls += 1
+ imgs = images if isinstance(images, list) else [images]
+ rows = [np.asarray(im, dtype=np.float32).reshape(-1, 3).mean(axis=0) / 255.0 for im in imgs]
+ return {"pixel_values": torch.tensor(np.stack(rows), dtype=torch.float32)}
+ self.text_calls += 1
+ txts = text if isinstance(text, list) else [text]
+ rows = [[float(len(t)), float(sum(ord(c) for c in t) % 89), 1.0] for t in txts]
+ return {"input_ids": torch.tensor(rows, dtype=torch.float32)}
+
+
+class _FakeVisionModel:
+ """Pure per-row linear model; counts stacked forwards to prove batching."""
+
+ def __init__(self, dim: int) -> None:
+ gen = torch.Generator().manual_seed(7)
+ self.img_w = torch.randn(3, dim, generator=gen)
+ self.txt_w = torch.randn(3, dim, generator=gen)
+ self.image_forward_calls = 0
+ self.text_forward_calls = 0
+
+ def get_image_features(self, pixel_values: torch.Tensor = None, **_kw: Any) -> torch.Tensor: # type: ignore[assignment]
+ self.image_forward_calls += 1
+ return pixel_values @ self.img_w
+
+ def get_text_features(self, input_ids: torch.Tensor = None, **_kw: Any) -> torch.Tensor: # type: ignore[assignment]
+ self.text_forward_calls += 1
+ return input_ids @ self.txt_w
+
+
+class _RaceDetectingTokenizer:
+ """Stand-in for an HF fast tokenizer that is NOT thread-safe.
+
+ Mimics the ``RuntimeError: Already borrowed`` failure: it raises if a
+ second call enters while another is in flight, and records the peak
+ observed concurrency so a serialising lock can be asserted (peak == 1).
+ """
+
+ def __init__(self) -> None:
+ self._active = 0
+ self._guard = threading.Lock()
+ self.peak_concurrency = 0
+ # The §7.3 metering seam reads ``processor.tokenizer``; a stateless stub
+ # keeps the race detection focused on the processor's text call.
+ self.tokenizer = _SimpleTokenizer()
+
+ def __call__(self, *args: object, **kwargs: object) -> dict[str, MagicMock]:
+ with self._guard:
+ self._active += 1
+ self.peak_concurrency = max(self.peak_concurrency, self._active)
+ concurrent = self._active > 1
+ try:
+ if concurrent:
+ raise RuntimeError("Already borrowed")
+ # Hold the "borrow" briefly so an unsynchronised racer would overlap.
+ time.sleep(0.002)
+ return {"input_ids": MagicMock()}
+ finally:
+ with self._guard:
+ self._active -= 1
+
+
class TestCLIPAdapter:
"""Tests for CLIPAdapter with mocked model."""
@@ -158,6 +267,42 @@ class TestCLIPAdapter:
with pytest.raises(ValueError, match="configured dense_dim=768, model projection_dim=512"):
adapter.load("cpu")
+ def test_encode_text_tokenizer_thread_safe(self) -> None:
+ """Regression (MP.4 34026b6cd): concurrent text encodes must not race
+ on the shared HF fast tokenizer (``RuntimeError: Already borrowed``).
+
+ Drives ``_encode_text`` from several threads through a tokenizer that
+ raises on concurrent entry; the adapter's ``_tokenizer_lock`` must
+ serialise the call so no overlap and no error occurs. Not a strict
+ serialisability proof — a threaded smoke test that the lock holds.
+ """
+ adapter = CLIPAdapter("openai/clip-vit-base-patch32", normalize=False)
+ adapter._model = MagicMock()
+ # get_text_features must yield a real tensor (the adapter unwraps the
+ # feature tensor from the model output before returning).
+ adapter._model.get_text_features.return_value = torch.zeros((1, 8))
+ adapter._device = "cpu"
+ tokenizer = _RaceDetectingTokenizer()
+ adapter._processor = tokenizer # ty: ignore[invalid-assignment]
+
+ errors: list[Exception] = []
+
+ def worker() -> None:
+ try:
+ for _ in range(20):
+ adapter._encode_text("a photo of a cat")
+ except Exception as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target=worker, daemon=True) for _ in range(8)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=10.0)
+
+ assert not errors, f"tokenizer race under concurrent encode: {errors!r}"
+ assert tokenizer.peak_concurrency == 1
+
@patch("sie_server.adapters.clip.torch")
def test_unload(self, mock_torch: MagicMock, adapter: CLIPAdapter) -> None:
"""Unload clears the model."""
@@ -172,3 +317,70 @@ class TestCLIPAdapter:
assert adapter._processor is None
assert adapter._dense_dim is None
assert adapter.dims.dense is None
+
+ def test_unload_shuts_down_preprocess_pool(self, adapter: CLIPAdapter) -> None:
+ """Unload shuts down and clears the lazily-created preprocessing pool."""
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ adapter._device = "cpu"
+ pool = adapter._get_preprocess_pool()
+ assert adapter._preprocess_pool is pool
+
+ adapter.unload()
+
+ assert adapter._preprocess_pool is None
+ assert pool._shutdown
+
+ @pytest.mark.parametrize("normalize", [True, False])
+ def test_encode_batched_matches_serial(self, normalize: bool) -> None:
+ """EQUIVALENCE GATE: one stacked forward per modality must reproduce the
+ per-item serial semantics exactly — output order, per-image normalize,
+ multi-image mean-pool, and mixed image/text batches.
+ """
+ dim = 16
+ adapter = CLIPAdapter("openai/clip-vit-base-patch32", normalize=normalize)
+ model = _FakeVisionModel(dim)
+ proc = _FakeVisionProcessor()
+ adapter._model = model # ty: ignore[invalid-assignment]
+ adapter._processor = proc # ty: ignore[invalid-assignment]
+ adapter._device = "cpu"
+ adapter._dense_dim = dim
+
+ items = [
+ _img_item("a", [(200, 10, 10)]), # single image
+ _img_item("bc", [(10, 200, 10), (10, 10, 200)]), # multi-image -> mean-pool
+ Item(id="t1", text="a red circle"), # text
+ _img_item("d", [(90, 90, 90)]), # single image
+ Item(id="t2", text="a blue rectangle here and there"), # text
+ ]
+
+ out = adapter.encode(items, ["dense"])
+ assert out.dense is not None
+ assert out.dense.shape == (5, dim)
+ # Batching proof: exactly one stacked forward per tower for the whole call.
+ assert model.image_forward_calls == 1
+ assert model.text_forward_calls == 1
+
+ # Serial reference — replicate the pre-batch per-item algorithm exactly.
+ def ref_image(item: Item) -> np.ndarray:
+ pils = [Image.open(io.BytesIO(im["data"])).convert("RGB") for im in item.images] # type: ignore[index]
+ feats = model.get_image_features(**proc(images=pils))
+ if normalize:
+ feats = functional.normalize(feats, p=2, dim=-1)
+ if len(pils) > 1:
+ feats = feats.mean(dim=0, keepdim=True)
+ return feats[0].numpy()
+
+ def ref_text(item: Item) -> np.ndarray:
+ feats = model.get_text_features(**proc(text=[item.text]))
+ if normalize:
+ feats = functional.normalize(feats, p=2, dim=-1)
+ return feats[0].numpy()
+
+ for i, item in enumerate(items):
+ expected = ref_image(item) if item.images else ref_text(item)
+ got = out.dense[i]
+ denom = float(np.linalg.norm(got) * np.linalg.norm(expected)) or 1.0
+ cos = float(np.dot(got, expected) / denom)
+ assert cos >= 0.9999, f"item {i} cosine {cos}"
+ assert np.allclose(got, expected, atol=1e-5), f"item {i} value mismatch"
diff --git a/packages/sie_server/tests/adapters/test_docling.py b/packages/sie_server/tests/adapters/test_docling.py
index 3c2d409fb..e01eb0003 100644
--- a/packages/sie_server/tests/adapters/test_docling.py
+++ b/packages/sie_server/tests/adapters/test_docling.py
@@ -60,6 +60,45 @@ class TestDoclingExtract:
assert out.data[0]["markdown"] == "# md:default"
assert out.data[0]["document"] == {"name": "document.pdf"}
+ def test_surfaces_real_page_count_for_metering(self) -> None:
+ # §7 parse dimension: the adapter reads the DoclingDocument page count
+ # (num_pages()) and surfaces it on ExtractOutput.pages so the result
+ # seam can bill "$ per 1k pages".
+ adapter = DoclingAdapter()
+ adapter._loaded = True
+
+ def _paged_converter(*, ocr_enabled: bool) -> MagicMock:
+ _ = ocr_enabled
+ converter = MagicMock(name="DocumentConverter[paged]")
+
+ def _convert(stream: Any) -> MagicMock:
+ result = MagicMock()
+ result.document.export_to_text.return_value = "text"
+ result.document.export_to_markdown.return_value = "# md"
+ result.document.export_to_dict.return_value = {"name": stream.name}
+ result.document.num_pages.return_value = 3
+ return result
+
+ converter.convert.side_effect = _convert
+ return converter
+
+ adapter._make_converter = MagicMock(side_effect=_paged_converter) # type: ignore[method-assign]
+
+ out = adapter.extract([Item(document={"data": b"%PDF-1.4 fake", "format": "pdf"})])
+
+ assert out.pages == [3]
+
+ def test_per_item_error_reports_zero_pages(self) -> None:
+ # A per-item failure (no document/image) surfaces 0 pages; an all-error
+ # batch emits no pages dimension at all (metering falls back to reserve).
+ adapter, _ = _make_adapter()
+
+ out = adapter.extract([Item(text="no document here")])
+
+ assert out.data is not None
+ assert "error" in out.data[0]
+ assert out.pages is None
+
def test_format_hint_drives_stream_name(self) -> None:
adapter, _ = _make_adapter()
diff --git a/packages/sie_server/tests/adapters/test_lora.py b/packages/sie_server/tests/adapters/test_lora.py
index c132d56fc..8b753a38a 100644
--- a/packages/sie_server/tests/adapters/test_lora.py
+++ b/packages/sie_server/tests/adapters/test_lora.py
@@ -6,17 +6,25 @@ Tests cover:
3. PEFTLoRAMixin methods
4. Registry LoRA management
5. Worker per-LoRA batching (covered in test_worker.py)
+6. Honest capability + typed rejection for adapters whose forward cannot
+ honor a LoRA (bert_flash, nomic_flash — LoRA capability audit)
+7. Staging-side target_modules validation (audit §3 negative control)
"""
from __future__ import annotations
from collections import OrderedDict
+from types import SimpleNamespace
+from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDims
-from sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin
+from sie_server.adapters.bert_flash import BertFlashAdapter
+from sie_server.adapters.nomic_flash import NomicFlashAdapter
+from sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin, validate_lora_target_modules
from sie_server.core.model_loader import DEFAULT_MAX_LORAS, LoadedLora, LoadedModel
+from sie_server.core.registry import ModelRegistry
from sie_server.types.responses import ErrorCode
# =============================================================================
@@ -470,6 +478,84 @@ class TestModelLoaderProfileLoras:
result = loader._collect_profile_loras(config)
assert result == {"org/shared-lora"}
+ @staticmethod
+ def _make_loader() -> Any:
+ from sie_server.core.model_loader import ModelLoader
+
+ return ModelLoader(
+ preprocessor_registry=MagicMock(),
+ postprocessor_registry=MagicMock(),
+ all_configs={},
+ )
+
+ @staticmethod
+ def _profile(runtime: dict | None = None, loadtime: dict | None = None) -> MagicMock:
+ profile = MagicMock()
+ profile.adapter_options.runtime = runtime or {}
+ profile.adapter_options.loadtime = loadtime or {}
+ return profile
+
+ def test_collect_canonical_loadtime_lora_paths_list(self) -> None:
+ """Canonical key: adapter_options.loadtime["lora_paths"] as a list of paths."""
+ loader = self._make_loader()
+ config = MagicMock()
+ config.profiles = {
+ "byo": self._profile(loadtime={"lora_paths": ["org/lora-a", "org/lora-b"]}),
+ }
+
+ assert loader._collect_profile_loras(config) == {"org/lora-a", "org/lora-b"}
+
+ def test_collect_canonical_loadtime_lora_paths_dict(self) -> None:
+ """The sglang dict shape (served-name -> path) contributes its paths."""
+ loader = self._make_loader()
+ config = MagicMock()
+ config.profiles = {
+ "byo": self._profile(loadtime={"lora_paths": {"banking": "org/lora-a"}}),
+ }
+
+ assert loader._collect_profile_loras(config) == {"org/lora-a"}
+
+ def test_collect_canonical_and_legacy_alias_union(self) -> None:
+ """Canonical loadtime.lora_paths and the deprecated runtime.lora_id merge."""
+ loader = self._make_loader()
+ config = MagicMock()
+ config.profiles = {
+ "new-style": self._profile(loadtime={"lora_paths": ["org/lora-new"]}),
+ "legacy": self._profile(runtime={"lora_id": "org/lora-legacy"}),
+ }
+
+ assert loader._collect_profile_loras(config) == {"org/lora-new", "org/lora-legacy"}
+
+ def test_include_loadtime_paths_false_skips_canonical_only(self) -> None:
+ """Engine-owned adapters (sglang) must not double-load loadtime.lora_paths.
+
+ The loader passes include_loadtime_paths=adapter.supports_hot_lora_reload();
+ sglang consumes its loadtime declarations at engine launch itself, so
+ only the legacy runtime.lora_id survives collection for it.
+ """
+ loader = self._make_loader()
+ config = MagicMock()
+ config.profiles = {
+ "engine-owned": self._profile(
+ runtime={"lora_id": "org/lora-legacy"},
+ loadtime={"lora_paths": ["org/lora-engine"]},
+ ),
+ }
+
+ result = loader._collect_profile_loras(config, include_loadtime_paths=False)
+ assert result == {"org/lora-legacy"}
+
+ def test_collect_ignores_empty_lora_paths_entries(self) -> None:
+ """Empty entries and non-list/dict shapes are skipped, not crashed on."""
+ loader = self._make_loader()
+ config = MagicMock()
+ config.profiles = {
+ "empties": self._profile(loadtime={"lora_paths": ["", None]}),
+ "scalar-shape": self._profile(loadtime={"lora_paths": "org/not-a-list"}),
+ }
+
+ assert loader._collect_profile_loras(config) == set()
+
# =============================================================================
# SDK LoraLoadingError Tests
@@ -487,3 +573,193 @@ class TestSDKLoraLoadingError:
assert str(error) == "Test error"
assert error.lora == "org/my-lora"
assert error.model == "bge-m3"
+
+
+# =============================================================================
+# Honest LoRA capability for forwards that cannot honor a LoRA (audit fix)
+# =============================================================================
+
+
+class TestBrokenFlashAdaptersHonestLoraCapability:
+ """bert_flash and nomic_flash must NOT advertise LoRA support.
+
+ LoRA capability audit: ``bert_flash`` fuses Q/K/V weights at load and runs
+ attention via ``functional.linear`` on the cached tensors; ``nomic_flash``
+ hand-loads raw safetensors into tensor dicts with no wrappable
+ ``self._model``. In both cases a PEFT LoRA would be silently dropped
+ (served without the customer's adapter, no error) — the worst failure
+ class. Honest capability = base-default ``supports_lora() == False`` so
+ the request path rejects with the typed 400 instead.
+
+ Constructors only — no model weights are loaded (no heavy local compute).
+ """
+
+ @pytest.mark.parametrize("adapter_cls", [BertFlashAdapter, NomicFlashAdapter])
+ def test_supports_lora_is_false(self, adapter_cls: type) -> None:
+ adapter = adapter_cls(model_name_or_path="stub/model")
+ assert adapter.supports_lora() is False
+ assert adapter.supports_hot_lora_reload() is False
+
+ @pytest.mark.parametrize("adapter_cls", [BertFlashAdapter, NomicFlashAdapter])
+ def test_not_a_peft_mixin(self, adapter_cls: type) -> None:
+ """The PEFT mixin must not be re-added without fixing the forward."""
+ assert not issubclass(adapter_cls, PEFTLoRAMixin)
+
+ @pytest.mark.parametrize("adapter_cls", [BertFlashAdapter, NomicFlashAdapter])
+ def test_load_lora_raises_not_implemented(self, adapter_cls: type) -> None:
+ adapter = adapter_cls(model_name_or_path="stub/model")
+ with pytest.raises(NotImplementedError, match="does not support LoRA"):
+ adapter.load_lora("org/customer-lora")
+ with pytest.raises(NotImplementedError, match="does not support LoRA"):
+ adapter.unload_lora("org/customer-lora")
+
+ @pytest.mark.parametrize("adapter_cls", [BertFlashAdapter, NomicFlashAdapter])
+ def test_set_active_lora_is_noop(self, adapter_cls: type) -> None:
+ """Base-class no-op — the worker may call this with lora=None freely."""
+ adapter = adapter_cls(model_name_or_path="stub/model")
+ assert adapter.set_active_lora(None) is None
+
+
+class TestLoraRejectionOnNonSupportingAdapters:
+ """The registry must raise the typed ValueError for these adapters.
+
+ This is the real rejection seam: ``api/encode.py`` translates this exact
+ ``ValueError`` into HTTP 400 INVALID_INPUT (locked by
+ ``tests/api/test_encode_endpoint.py::TestEncodeLoraRouting::``
+ ``test_lora_on_non_supporting_model_returns_typed_400``). Together they
+ prove a lora_id aimed at bert_flash/nomic_flash is rejected loudly instead
+ of silently served from base weights.
+ """
+
+ @pytest.mark.parametrize("adapter_cls", [BertFlashAdapter, NomicFlashAdapter])
+ async def test_ensure_lora_loaded_async_raises_value_error(self, adapter_cls: type) -> None:
+ registry = ModelRegistry()
+ adapter = adapter_cls(model_name_or_path="stub/model")
+ loaded = MagicMock()
+ loaded.adapter = adapter
+ registry._configs["stub-model"] = MagicMock()
+ registry._loaded["stub-model"] = loaded
+
+ with pytest.raises(ValueError, match="does not support LoRA"):
+ await registry.ensure_lora_loaded_async("stub-model", "org/customer-lora")
+
+
+# =============================================================================
+# Staging-side target_modules validation (audit §3 negative control)
+# =============================================================================
+
+
+class TestValidateLoraTargetModules:
+ """Direct tests for validate_lora_target_modules."""
+
+ CALLED = frozenset({"query", "key", "value", "dense"})
+
+ def test_no_intersection_rejects(self) -> None:
+ """The audit's negative control: LoRA on modules the forward never calls."""
+ with pytest.raises(ValueError, match="silently ignored"):
+ validate_lora_target_modules("org/lora", ["pooler.dense2", "classifier"], self.CALLED)
+
+ def test_intersection_passes(self) -> None:
+ validate_lora_target_modules("org/lora", ["query", "value"], self.CALLED)
+
+ def test_partial_intersection_passes(self) -> None:
+ """One honored target is enough to have an effect (not zero-effect)."""
+ validate_lora_target_modules("org/lora", ["classifier", "query"], self.CALLED)
+
+ def test_dotted_target_matches_by_leaf_name(self) -> None:
+ validate_lora_target_modules(
+ "org/lora",
+ ["encoder.layer.0.attention.self.query"],
+ self.CALLED,
+ )
+
+ def test_set_shape_accepted(self) -> None:
+ validate_lora_target_modules("org/lora", {"value"}, self.CALLED)
+
+ def test_regex_string_matching_a_called_module_passes(self) -> None:
+ validate_lora_target_modules("org/lora", ".*query", self.CALLED)
+
+ def test_regex_string_matching_nothing_warns_but_does_not_raise(self, caplog: pytest.LogCaptureFixture) -> None:
+ """Regexes may target full dotted paths we cannot resolve — warn only."""
+ with caplog.at_level("WARNING"):
+ validate_lora_target_modules("org/lora", r"pooler\.dense2", self.CALLED)
+ assert "matches none" in caplog.text
+
+ def test_empty_target_modules_skips_check(self) -> None:
+ validate_lora_target_modules("org/lora", None, self.CALLED)
+ validate_lora_target_modules("org/lora", [], self.CALLED)
+
+ def test_empty_called_set_skips_check(self) -> None:
+ validate_lora_target_modules("org/lora", ["anything"], frozenset())
+
+
+class MockAdapterWithCalledModules(MockAdapterWithLoRA):
+ """PEFT mixin adapter declaring the modules its forward actually calls."""
+
+ lora_called_module_names = frozenset({"query", "value"})
+
+
+class TestMixinTargetModulesValidation:
+ """load_lora must consult the LoRA's PEFT config against the called set."""
+
+ @staticmethod
+ def _peft_module(target_modules: object) -> MagicMock:
+ peft = MagicMock()
+ peft.PeftConfig.from_pretrained.return_value = SimpleNamespace(target_modules=target_modules)
+ mock_peft_model = MagicMock()
+ mock_peft_model.named_parameters.return_value = []
+ peft.PeftModel.from_pretrained.return_value = mock_peft_model
+ return peft
+
+ def test_mismatched_lora_rejected_before_wrapping(self) -> None:
+ peft = self._peft_module(["pooler.dense2"])
+ with patch.dict("sys.modules", {"peft": peft}):
+ adapter = MockAdapterWithCalledModules()
+ adapter.load("cuda:0")
+
+ with pytest.raises(ValueError, match="silently ignored"):
+ adapter.load_lora("org/mismatched-lora")
+
+ # Rejected before any PEFT wrapping or tracking.
+ peft.PeftModel.from_pretrained.assert_not_called()
+ assert "org/mismatched-lora" not in adapter._loaded_loras
+ assert adapter._peft_model is None
+
+ def test_matching_lora_loads(self) -> None:
+ peft = self._peft_module(["query"])
+ with patch.dict("sys.modules", {"peft": peft}):
+ adapter = MockAdapterWithCalledModules()
+ adapter.load("cuda:0")
+
+ adapter.load_lora("org/matching-lora")
+
+ peft.PeftConfig.from_pretrained.assert_called_once_with("org/matching-lora")
+ peft.PeftModel.from_pretrained.assert_called_once()
+ assert "org/matching-lora" in adapter._loaded_loras
+
+ def test_config_fetch_failure_skips_check_and_proceeds(self, caplog: pytest.LogCaptureFixture) -> None:
+ """A config-fetch error must not mask the real load error path."""
+ peft = self._peft_module(["query"])
+ peft.PeftConfig.from_pretrained.side_effect = RuntimeError("offline")
+ with patch.dict("sys.modules", {"peft": peft}):
+ adapter = MockAdapterWithCalledModules()
+ adapter.load("cuda:0")
+
+ with caplog.at_level("WARNING"):
+ adapter.load_lora("org/unfetchable-lora")
+
+ assert "skipping the check" in caplog.text
+ peft.PeftModel.from_pretrained.assert_called_once()
+ assert "org/unfetchable-lora" in adapter._loaded_loras
+
+ def test_default_none_declaration_skips_check(self) -> None:
+ """Standard-forward adapters (no declaration) never consult PeftConfig."""
+ peft = self._peft_module(["anything"])
+ with patch.dict("sys.modules", {"peft": peft}):
+ adapter = MockAdapterWithLoRA()
+ adapter.load("cuda:0")
+
+ adapter.load_lora("org/any-lora")
+
+ peft.PeftConfig.from_pretrained.assert_not_called()
+ peft.PeftModel.from_pretrained.assert_called_once()
diff --git a/packages/sie_server/tests/adapters/test_paddleocr_vl.py b/packages/sie_server/tests/adapters/test_paddleocr_vl.py
index a440d4a37..b55049d68 100644
--- a/packages/sie_server/tests/adapters/test_paddleocr_vl.py
+++ b/packages/sie_server/tests/adapters/test_paddleocr_vl.py
@@ -115,8 +115,15 @@ class TestPaddleOCRVLAdapter:
with pytest.raises(ValueError, match="must be one of"):
adapter.extract(items, options={"task": "bogus"})
- def test_load_passes_revision_and_trust_remote_code(self) -> None:
- """load() threads revision + trust_remote_code to both from_pretrained calls."""
+ def test_load_resolves_revision_snapshot_and_passes_trust_remote_code(self) -> None:
+ """load() resolves the pinned revision to a local dir, then loads from it.
+
+ The revision must reach ``snapshot_download`` (not from_pretrained): on
+ transformers 4.57.x ``AutoProcessor.from_pretrained`` drops ``revision``
+ during its offline config probe, so the adapter hands it a pre-resolved
+ local directory instead. ``trust_remote_code`` still threads to both
+ from_pretrained calls.
+ """
from sie_server.adapters.paddleocr_vl import PaddleOCRVLAdapter
adapter = PaddleOCRVLAdapter(
@@ -130,22 +137,28 @@ class TestPaddleOCRVLAdapter:
mock_model.to.return_value = mock_model
with (
+ patch("sie_server.adapters.paddleocr_vl.snapshot_download") as mock_snap,
patch("transformers.AutoProcessor") as mock_ap_cls,
patch("transformers.AutoModelForCausalLM") as mock_am_cls,
):
+ mock_snap.return_value = "/models/paddleocr-vl-snapshot"
mock_ap_cls.from_pretrained.return_value = mock_processor
mock_am_cls.from_pretrained.return_value = mock_model
adapter.load("cpu")
- ap_kwargs = mock_ap_cls.from_pretrained.call_args.kwargs
- am_kwargs = mock_am_cls.from_pretrained.call_args.kwargs
- assert ap_kwargs["revision"] == "abc123"
+ assert mock_snap.call_args.kwargs["revision"] == "abc123"
+ ap_args, ap_kwargs = mock_ap_cls.from_pretrained.call_args
+ am_args, am_kwargs = mock_am_cls.from_pretrained.call_args
+ assert ap_args[0] == "/models/paddleocr-vl-snapshot"
+ assert am_args[0] == "/models/paddleocr-vl-snapshot"
assert ap_kwargs["trust_remote_code"] is True
- assert am_kwargs["revision"] == "abc123"
assert am_kwargs["trust_remote_code"] is True
+ # revision must NOT reach from_pretrained (it is dropped offline).
+ assert "revision" not in ap_kwargs
+ assert "revision" not in am_kwargs
- def test_load_without_revision_omits_kwarg(self) -> None:
+ def test_load_without_revision_omits_snapshot_kwarg(self) -> None:
from sie_server.adapters.paddleocr_vl import PaddleOCRVLAdapter
adapter = PaddleOCRVLAdapter(
@@ -158,6 +171,33 @@ class TestPaddleOCRVLAdapter:
mock_model.to.return_value = mock_model
with (
+ patch("sie_server.adapters.paddleocr_vl.snapshot_download") as mock_snap,
+ patch("transformers.AutoProcessor") as mock_ap_cls,
+ patch("transformers.AutoModelForCausalLM") as mock_am_cls,
+ ):
+ mock_snap.return_value = "/models/paddleocr-vl-snapshot"
+ mock_ap_cls.from_pretrained.return_value = MagicMock()
+ mock_am_cls.from_pretrained.return_value = mock_model
+
+ adapter.load("cpu")
+
+ assert "revision" not in mock_snap.call_args.kwargs
+
+ def test_load_uses_local_dir_without_download(self, tmp_path: object) -> None:
+ """A model_name_or_path that is already a local dir skips snapshot_download."""
+ from pathlib import Path
+
+ from sie_server.adapters.paddleocr_vl import PaddleOCRVLAdapter
+
+ local_dir = Path(str(tmp_path)) / "paddleocr-vl"
+ local_dir.mkdir()
+ adapter = PaddleOCRVLAdapter(str(local_dir), revision="abc123")
+
+ mock_model = MagicMock()
+ mock_model.to.return_value = mock_model
+
+ with (
+ patch("sie_server.adapters.paddleocr_vl.snapshot_download") as mock_snap,
patch("transformers.AutoProcessor") as mock_ap_cls,
patch("transformers.AutoModelForCausalLM") as mock_am_cls,
):
@@ -166,8 +206,8 @@ class TestPaddleOCRVLAdapter:
adapter.load("cpu")
- assert "revision" not in mock_ap_cls.from_pretrained.call_args.kwargs
- assert "revision" not in mock_am_cls.from_pretrained.call_args.kwargs
+ mock_snap.assert_not_called()
+ assert mock_ap_cls.from_pretrained.call_args.args[0] == str(local_dir)
def test_preprocessor_built_after_load(self) -> None:
from sie_server.adapters.paddleocr_vl import PaddleOCRVLAdapter
@@ -178,9 +218,11 @@ class TestPaddleOCRVLAdapter:
mock_model.to.return_value = mock_model
with (
+ patch("sie_server.adapters.paddleocr_vl.snapshot_download") as mock_snap,
patch("transformers.AutoProcessor") as mock_ap_cls,
patch("transformers.AutoModelForCausalLM") as mock_am_cls,
):
+ mock_snap.return_value = "/models/paddleocr-vl-snapshot"
mock_ap_cls.from_pretrained.return_value = MagicMock()
mock_am_cls.from_pretrained.return_value = mock_model
diff --git a/packages/sie_server/tests/adapters/test_sglang.py b/packages/sie_server/tests/adapters/test_sglang.py
index ca2932a60..cded52adb 100644
--- a/packages/sie_server/tests/adapters/test_sglang.py
+++ b/packages/sie_server/tests/adapters/test_sglang.py
@@ -1,5 +1,6 @@
"""Tests for SGLang embedding adapter (HTTP server mode)."""
+from concurrent.futures import ThreadPoolExecutor
from unittest.mock import MagicMock, patch
import numpy as np
@@ -198,7 +199,12 @@ class TestSGLangEmbeddingAdapter:
mock_response.status_code = 200
mock_post.return_value = mock_response
- adapter = SGLangEmbeddingAdapter("test-model", normalize=False)
+ # Pin single-POST concurrency: the default fan-out (SIE_SGLANG_EMBED_
+ # CONCURRENCY=8) shards this 2-text batch into two 1-text POSTs, but the
+ # mock above serves 2 embeddings per POST — the shard/response mismatch
+ # (a893384ba) is what broke this test. concurrency=1 keeps the legacy
+ # single blocking POST so the asserts on the one call still hold.
+ adapter = SGLangEmbeddingAdapter("test-model", normalize=False, embed_concurrency=1)
adapter._server_url = "http://localhost:30000"
items = [Item(text="hello"), Item(text="world")]
@@ -426,6 +432,46 @@ class TestSGLangEmbeddingAdapter:
with pytest.raises(ValueError, match="configured dense_dim=1024, observed=2048"):
adapter.encode([Item(text="test")], output_types=["dense"])
+ def test_embed_texts_concurrent_preserves_order(self) -> None:
+ """Sharded concurrent embedding concatenates shards back in input order."""
+ adapter = SGLangEmbeddingAdapter("test-model", embed_concurrency=3)
+ adapter._embed_concurrency = 3 # pin past any env override
+ adapter._session = MagicMock()
+ adapter._post_executor = ThreadPoolExecutor(max_workers=3)
+ try:
+ # One row per text valued by the text's int id, so a mis-ordered
+ # concat across shards would be detectable.
+ def fake_post(texts: list[str], model_name: str, session: object) -> np.ndarray:
+ return np.array([[float(t)] for t in texts], dtype=np.float32)
+
+ with patch.object(adapter, "_post_embedding_batch", side_effect=fake_post):
+ out = adapter._embed_texts([str(i) for i in range(6)], "test-model")
+ assert out.shape == (6, 1)
+ assert [int(v) for v in out[:, 0]] == list(range(6))
+ finally:
+ adapter._post_executor.shutdown(wait=True)
+
+ def test_embed_texts_concurrent_propagates_shard_error(self) -> None:
+ """A failure in any shard propagates out of the concurrent gather."""
+ adapter = SGLangEmbeddingAdapter("test-model", embed_concurrency=3)
+ adapter._embed_concurrency = 3 # pin past any env override
+ adapter._session = MagicMock()
+ adapter._post_executor = ThreadPoolExecutor(max_workers=3)
+ try:
+
+ def fake_post(texts: list[str], model_name: str, session: object) -> np.ndarray:
+ if "3" in texts:
+ raise RuntimeError("shard boom")
+ return np.array([[float(t)] for t in texts], dtype=np.float32)
+
+ with (
+ patch.object(adapter, "_post_embedding_batch", side_effect=fake_post),
+ pytest.raises(RuntimeError, match="shard boom"),
+ ):
+ adapter._embed_texts([str(i) for i in range(6)], "test-model")
+ finally:
+ adapter._post_executor.shutdown(wait=True)
+
class TestSGLangLoRA:
"""Tests for SGLang LoRA support."""
diff --git a/packages/sie_server/tests/adapters/test_siglip.py b/packages/sie_server/tests/adapters/test_siglip.py
index 74e572e44..34f6b291a 100644
--- a/packages/sie_server/tests/adapters/test_siglip.py
+++ b/packages/sie_server/tests/adapters/test_siglip.py
@@ -1,12 +1,121 @@
from __future__ import annotations
+import io
+import threading
+import time
+from typing import Any
from unittest.mock import MagicMock, patch
+import numpy as np
import pytest
+import torch
+from PIL import Image
from sie_server.adapters.siglip import SiglipAdapter
from sie_server.types.inputs import Item
+def _png_bytes(color: tuple[int, int, int]) -> bytes:
+ """Encode a solid-color 8x8 RGB PNG (a real image the decode path can open)."""
+ buf = io.BytesIO()
+ Image.new("RGB", (8, 8), color).save(buf, format="PNG")
+ return buf.getvalue()
+
+
+def _img_item(item_id: str, colors: list[tuple[int, int, int]]) -> Item:
+ return Item(id=item_id, images=[{"data": _png_bytes(c), "format": "png"} for c in colors])
+
+
+class _SimpleTokenizer:
+ """Minimal HF-tokenizer stand-in for the §7.3 text-metering seam.
+
+ ``_token_counts_or_none`` calls ``tokenizer(texts, truncation=..., max_length=...)``
+ and reads ``["input_ids"]`` as a list of per-text id lists.
+ """
+
+ def __call__(self, texts: list[str], truncation: bool = False, max_length: int | None = None, **_kw: Any):
+ return {"input_ids": [list(range(len(t))) for t in texts]}
+
+
+class _FakeVisionProcessor:
+ """Deterministic, pure-function stand-in for the SigLIP processor.
+
+ Maps each image to its mean RGB (a ``[3]`` feature) and each text to a
+ ``[3]`` id vector, so per-item preprocessing is independent and the model
+ below can be a pure per-row linear map — making a stacked forward exactly
+ equal to per-item serial forwards.
+ """
+
+ def __init__(self) -> None:
+ self.image_calls = 0
+ self.text_calls = 0
+ # The §7.3 text-metering seam recounts tokens off ``processor.tokenizer``.
+ self.tokenizer = _SimpleTokenizer()
+
+ def __call__(
+ self, images: Any = None, text: Any = None, return_tensors: Any = None, **_kw: Any
+ ) -> dict[str, torch.Tensor]:
+ if images is not None:
+ self.image_calls += 1
+ imgs = images if isinstance(images, list) else [images]
+ rows = [np.asarray(im, dtype=np.float32).reshape(-1, 3).mean(axis=0) / 255.0 for im in imgs]
+ return {"pixel_values": torch.tensor(np.stack(rows), dtype=torch.float32)}
+ self.text_calls += 1
+ txts = text if isinstance(text, list) else [text]
+ rows = [[float(len(t)), float(sum(ord(c) for c in t) % 89), 1.0] for t in txts]
+ return {"input_ids": torch.tensor(rows, dtype=torch.float32)}
+
+
+class _FakeVisionModel:
+ """Pure per-row linear model; counts stacked forwards to prove batching."""
+
+ def __init__(self, dim: int) -> None:
+ gen = torch.Generator().manual_seed(11)
+ self.img_w = torch.randn(3, dim, generator=gen)
+ self.txt_w = torch.randn(3, dim, generator=gen)
+ self.image_forward_calls = 0
+ self.text_forward_calls = 0
+
+ def get_image_features(self, pixel_values: torch.Tensor = None, **_kw: Any) -> torch.Tensor: # type: ignore[assignment]
+ self.image_forward_calls += 1
+ return pixel_values @ self.img_w
+
+ def get_text_features(self, input_ids: torch.Tensor = None, **_kw: Any) -> torch.Tensor: # type: ignore[assignment]
+ self.text_forward_calls += 1
+ return input_ids @ self.txt_w
+
+
+class _RaceDetectingTokenizer:
+ """Stand-in for an HF fast tokenizer that is NOT thread-safe.
+
+ Mimics the ``RuntimeError: Already borrowed`` failure: it raises if a
+ second call enters while another is in flight, and records the peak
+ observed concurrency so a serialising lock can be asserted (peak == 1).
+ """
+
+ def __init__(self) -> None:
+ self._active = 0
+ self._guard = threading.Lock()
+ self.peak_concurrency = 0
+ # The §7.3 metering seam reads ``processor.tokenizer``; a stateless stub
+ # keeps the race detection focused on the processor's text call.
+ self.tokenizer = _SimpleTokenizer()
+
+ def __call__(self, *args: object, **kwargs: object) -> dict[str, MagicMock]:
+ with self._guard:
+ self._active += 1
+ self.peak_concurrency = max(self.peak_concurrency, self._active)
+ concurrent = self._active > 1
+ try:
+ if concurrent:
+ raise RuntimeError("Already borrowed")
+ # Hold the "borrow" briefly so an unsynchronised racer would overlap.
+ time.sleep(0.002)
+ return {"input_ids": MagicMock()}
+ finally:
+ with self._guard:
+ self._active -= 1
+
+
class TestSiglipAdapter:
"""Tests for SiglipAdapter with mocked model."""
@@ -89,6 +198,42 @@ class TestSiglipAdapter:
mock_processor_class.from_pretrained.assert_called_once()
assert adapter.dims.dense == 1152
+ def test_encode_text_tokenizer_thread_safe(self) -> None:
+ """Regression (MP.4 34026b6cd): concurrent text encodes must not race
+ on the shared HF fast tokenizer (``RuntimeError: Already borrowed``).
+
+ Drives the transformers-backend ``_encode_text`` from several threads
+ through a tokenizer that raises on concurrent entry; the adapter's
+ ``_tokenizer_lock`` must serialise the call so no overlap and no error
+ occurs. Not a strict serialisability proof — a threaded smoke test.
+ """
+ adapter = SiglipAdapter("google/siglip-so400m-patch14-384", normalize=False)
+ adapter._model = MagicMock()
+ # get_text_features must yield a real tensor (the adapter unwraps the
+ # feature tensor from the model output before returning).
+ adapter._model.get_text_features.return_value = torch.zeros((1, 8))
+ adapter._device = "cpu"
+ tokenizer = _RaceDetectingTokenizer()
+ adapter._processor = tokenizer
+
+ errors: list[Exception] = []
+
+ def worker() -> None:
+ try:
+ for _ in range(20):
+ adapter._encode_text("a photo of a cat")
+ except Exception as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target=worker, daemon=True) for _ in range(8)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=10.0)
+
+ assert not errors, f"tokenizer race under concurrent encode: {errors!r}"
+ assert tokenizer.peak_concurrency == 1
+
@patch("sie_server.adapters.siglip.torch")
def test_unload(self, mock_torch: MagicMock, adapter: SiglipAdapter) -> None:
"""Unload clears the model."""
@@ -103,3 +248,72 @@ class TestSiglipAdapter:
assert adapter._processor is None
assert adapter._dense_dim is None
assert adapter.dims.dense is None
+
+ def test_unload_shuts_down_preprocess_pool(self, adapter: SiglipAdapter) -> None:
+ """Unload shuts down and clears the lazily-created preprocessing pool."""
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ adapter._device = "cpu"
+ pool = adapter._get_preprocess_pool()
+ assert adapter._preprocess_pool is pool
+
+ adapter.unload()
+
+ assert adapter._preprocess_pool is None
+ assert pool._shutdown
+
+ @pytest.mark.parametrize("normalize", [True, False])
+ def test_encode_batched_matches_serial(self, normalize: bool) -> None:
+ """EQUIVALENCE GATE: one stacked forward per modality must reproduce the
+ per-item serial semantics exactly — output order, per-image normalize,
+ multi-image mean-pool, and mixed image/text batches (transformers backend).
+ """
+ from torch.nn import functional
+
+ dim = 16
+ adapter = SiglipAdapter("google/siglip-so400m-patch14-384", normalize=normalize)
+ model = _FakeVisionModel(dim)
+ proc = _FakeVisionProcessor()
+ adapter._model = model
+ adapter._processor = proc
+ adapter._device = "cpu"
+ adapter._dense_dim = dim
+
+ items = [
+ _img_item("a", [(200, 10, 10)]), # single image
+ _img_item("bc", [(10, 200, 10), (10, 10, 200)]), # multi-image -> mean-pool
+ Item(id="t1", text="a red circle"), # text
+ _img_item("d", [(90, 90, 90)]), # single image
+ Item(id="t2", text="a blue rectangle here and there"), # text
+ ]
+
+ out = adapter.encode(items, ["dense"])
+ assert out.dense is not None
+ assert out.dense.shape == (5, dim)
+ # Batching proof: exactly one stacked forward per tower for the whole call.
+ assert model.image_forward_calls == 1
+ assert model.text_forward_calls == 1
+
+ # Serial reference — replicate the pre-batch per-item algorithm exactly.
+ def ref_image(item: Item) -> np.ndarray:
+ pils = [Image.open(io.BytesIO(im["data"])).convert("RGB") for im in item.images] # type: ignore[index]
+ feats = model.get_image_features(**proc(images=pils))
+ if normalize:
+ feats = functional.normalize(feats, p=2, dim=-1)
+ if len(pils) > 1:
+ feats = feats.mean(dim=0, keepdim=True)
+ return feats[0].numpy()
+
+ def ref_text(item: Item) -> np.ndarray:
+ feats = model.get_text_features(**proc(text=[item.text]))
+ if normalize:
+ feats = functional.normalize(feats, p=2, dim=-1)
+ return feats[0].numpy()
+
+ for i, item in enumerate(items):
+ expected = ref_image(item) if item.images else ref_text(item)
+ got = out.dense[i]
+ denom = float(np.linalg.norm(got) * np.linalg.norm(expected)) or 1.0
+ cos = float(np.dot(got, expected) / denom)
+ assert cos >= 0.9999, f"item {i} cosine {cos}"
+ assert np.allclose(got, expected, atol=1e-5), f"item {i} value mismatch"
diff --git a/packages/sie_server/tests/adapters/test_splade_packed_parity.py b/packages/sie_server/tests/adapters/test_splade_packed_parity.py
new file mode 100644
index 000000000..a81263ac4
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_splade_packed_parity.py
@@ -0,0 +1,110 @@
+"""GPU output-equivalence gate: SPLADE packed-flash vs native-padded forward.
+
+This is the acceptance gate for enabling the RoBERTa packed flash path
+(granite-embedding-30m-sparse). It loads a real SPLADE model on CUDA with
+flash-attn, runs the SAME texts through both ``_encode_flash`` (packed varlen)
+and ``_encode_native`` (padded model forward), and asserts the sparse
+term-weight vectors are equivalent (cosine >= 0.9999, tiny max-abs-diff) across
+varied lengths incl. boundary cases.
+
+GPU-gated: skips in CI (no CUDA / no flash-attn / model not cached). Run on a
+CUDA box with the model cached locally:
+
+ SIE_SPLADE_PARITY_MODEL=ibm-granite/granite-embedding-30m-sparse \
+ mise exec -- uv run pytest \
+ packages/sie_server/tests/adapters/test_splade_packed_parity.py -v -s
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+
+import numpy as np
+import pytest
+import torch
+from sie_server.adapters.splade_flash import SPLADEFlashAdapter
+from sie_server.core.inference_output import SparseVector
+
+_HAS_CUDA = torch.cuda.is_available()
+_HAS_FLASH = importlib.util.find_spec("flash_attn") is not None
+_MODEL_ID = os.environ.get("SIE_SPLADE_PARITY_MODEL", "ibm-granite/granite-embedding-30m-sparse")
+
+pytestmark = pytest.mark.skipif(
+ not (_HAS_CUDA and _HAS_FLASH),
+ reason="packed-flash parity requires CUDA + flash-attn (GPU box only)",
+)
+
+# Query + document texts spanning boundary cases: single token, short query,
+# medium doc, a long doc that trips max_seq truncation, and repeated tokens.
+_TEXTS = [
+ "cache",
+ "how do i shard a batch across gpus",
+ (
+ "The managed inference edge coalesces concurrent single-item requests into "
+ "deeper GPU forwards over a persistent low-latency channel, then meters exact "
+ "on-wire token counts per item for billing and returns a learned-sparse "
+ "term-weight vector for each document chunk in the batch."
+ ),
+ " ".join(["model batch cache index shard metric chunk hash probe split"] * 40),
+ "aaa aaa aaa aaa aaa",
+]
+
+
+def _densify(vec: SparseVector, dim: int) -> np.ndarray:
+ dense = np.zeros(dim, dtype=np.float64)
+ dense[vec.indices.astype(np.int64)] = vec.values.astype(np.float64)
+ return dense
+
+
+def _cosine(a: np.ndarray, b: np.ndarray) -> float:
+ na, nb = np.linalg.norm(a), np.linalg.norm(b)
+ if na == 0.0 and nb == 0.0:
+ return 1.0
+ if na == 0.0 or nb == 0.0:
+ return 0.0
+ return float(np.dot(a, b) / (na * nb))
+
+
[email protected](scope="module")
+def adapter() -> SPLADEFlashAdapter:
+ try:
+ a = SPLADEFlashAdapter(_MODEL_ID, max_seq_length=512, compute_precision="float16")
+ a.load("cuda")
+ except Exception as exc: # noqa: BLE001 — model not staged in this env → skip
+ pytest.skip(f"model {_MODEL_ID!r} not loadable on this box: {exc}")
+ return a
+
+
+def test_guard_lifted_flash_path_active(adapter: SPLADEFlashAdapter) -> None:
+ """The RoBERTa packed flash path must actually be enabled (guard lifted)."""
+ assert adapter._use_flash is True, "packed flash path is not active — guard not lifted?"
+
+
[email protected]("i", range(len(_TEXTS)), ids=[f"text{i}" for i in range(len(_TEXTS))])
+def test_single_item_parity(adapter: SPLADEFlashAdapter, i: int) -> None:
+ """Each text alone: packed forward == padded forward."""
+ dim = adapter._vocab_size
+ flash = adapter._encode_flash([_TEXTS[i]])[0]
+ native = adapter._encode_native([_TEXTS[i]])[0]
+ cos = _cosine(_densify(flash, dim), _densify(native, dim))
+ max_abs = float(np.max(np.abs(_densify(flash, dim) - _densify(native, dim))))
+ print(
+ f"[text{i}] cosine={cos:.6f} max_abs_diff={max_abs:.4e} nnz_flash={len(flash.indices)} nnz_native={len(native.indices)}"
+ )
+ assert cos >= 0.9999, f"text{i} cosine {cos} < 0.9999"
+
+
+def test_mixed_batch_parity(adapter: SPLADEFlashAdapter) -> None:
+ """One packed batch of varied lengths: every item matches the padded path."""
+ dim = adapter._vocab_size
+ flash = adapter._encode_flash(_TEXTS)
+ native = adapter._encode_native(_TEXTS)
+ assert len(flash) == len(native) == len(_TEXTS)
+ worst = 1.0
+ for j, (f, n) in enumerate(zip(flash, native, strict=True)):
+ cos = _cosine(_densify(f, dim), _densify(n, dim))
+ worst = min(worst, cos)
+ print(f"[mixed item{j}] cosine={cos:.6f}")
+ assert cos >= 0.9999, f"mixed batch item{j} cosine {cos} < 0.9999"
+ print(f"[mixed batch] worst cosine={worst:.6f}")
diff --git a/packages/sie_server/tests/adapters/test_splade_roberta_position_ids.py b/packages/sie_server/tests/adapters/test_splade_roberta_position_ids.py
new file mode 100644
index 000000000..703286f9a
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_splade_roberta_position_ids.py
@@ -0,0 +1,101 @@
+"""Position-id parity for the SPLADE packed flash path across architectures.
+
+The SPLADE flash adapter packs a batch of sequences into one flat token stream
+and drives ``flash_attn_varlen_func`` with ``cu_seqlens``. Each packed sequence
+needs position ids restarting at the model's base offset: 0-based for
+BERT/DistilBERT, ``padding_idx + 1`` for RoBERTa. These CPU tests pin that the
+packed builder is bit-identical to HuggingFace's own position-id construction
+(``create_position_ids_from_input_ids``) — the correctness gate that let the
+RoBERTa packed path be enabled (granite-embedding-30m-sparse) without a GPU.
+
+The end-to-end packed-vs-padded output-equivalence test (real model, flash-attn)
+lives in ``test_splade_packed_parity.py`` and is GPU-gated.
+"""
+
+from __future__ import annotations
+
+import torch
+from sie_server.adapters._flash_pack import build_position_ids
+from sie_server.adapters.splade_flash import SPLADEFlashAdapter
+
+
+def _cu_seqlens(seq_lengths: list[int]) -> torch.Tensor:
+ cu = torch.zeros(len(seq_lengths) + 1, dtype=torch.int32)
+ cu[1:] = torch.tensor(seq_lengths, dtype=torch.int32).cumsum(0)
+ return cu
+
+
+class _StubEmbeddings:
+ def __init__(self, padding_idx: int) -> None:
+ self.padding_idx = padding_idx
+
+
+class _StubBaseModel:
+ def __init__(self, padding_idx: int) -> None:
+ self.embeddings = _StubEmbeddings(padding_idx)
+
+
+def test_packed_roberta_position_ids_match_hf_reference() -> None:
+ """Packed per-sequence RoBERTa position ids == HF create_position_ids_from_input_ids.
+
+ HF builds RoBERTa position ids from the input_ids + attention mask
+ (padding_idx + cumsum(non_pad)). For unpadded input — which is exactly what
+ varlen packing feeds — that reduces to ``[pad+1, pad+2, ...]`` per sequence.
+ Varied lengths incl. the len-1 boundary and the 512 max-seq boundary.
+ """
+ from transformers.models.roberta.modeling_roberta import create_position_ids_from_input_ids
+
+ padding_idx = 1
+ seq_lengths = [1, 5, 12, 3, 512]
+ cu = _cu_seqlens(seq_lengths)
+
+ got = build_position_ids(cu, offset=padding_idx + 1)
+
+ expected_parts = []
+ for length in seq_lengths:
+ # Any non-pad token id works; the mask is all-ones for unpadded input.
+ ids = torch.full((1, length), fill_value=padding_idx + 100, dtype=torch.long)
+ expected_parts.append(create_position_ids_from_input_ids(ids, padding_idx).squeeze(0))
+ expected = torch.cat(expected_parts)
+
+ assert got.dtype == torch.int64
+ assert torch.equal(got, expected)
+
+
+def test_adapter_build_position_ids_roberta_uses_padding_offset() -> None:
+ adapter = SPLADEFlashAdapter("stub-roberta", max_seq_length=128)
+ adapter._arch = "roberta"
+ adapter._device = "cpu"
+ adapter._get_base_model = lambda: _StubBaseModel(padding_idx=1) # type: ignore[method-assign]
+
+ cu = _cu_seqlens([3, 1, 7])
+ got = adapter._build_position_ids(cu)
+
+ # per-seq (offset pad+1=2): [2,3,4] · [2] · [2,3,4,5,6,7,8]
+ expected = torch.tensor([2, 3, 4, 2, 2, 3, 4, 5, 6, 7, 8])
+ assert torch.equal(got, expected)
+
+
+def test_adapter_build_position_ids_bert_is_zero_based() -> None:
+ adapter = SPLADEFlashAdapter("stub-bert", max_seq_length=128)
+ adapter._arch = "bert"
+ adapter._device = "cpu"
+
+ cu = _cu_seqlens([3, 1, 4])
+ got = adapter._build_position_ids(cu)
+
+ # per-seq (offset 0): [0,1,2] · [0] · [0,1,2,3]
+ expected = torch.tensor([0, 1, 2, 0, 0, 1, 2, 3])
+ assert torch.equal(got, expected)
+
+
+def test_adapter_build_position_ids_distilbert_is_zero_based() -> None:
+ adapter = SPLADEFlashAdapter("stub-distilbert", max_seq_length=128)
+ adapter._arch = "distilbert"
+ adapter._device = "cpu"
+
+ cu = _cu_seqlens([2, 5])
+ got = adapter._build_position_ids(cu)
+
+ expected = torch.tensor([0, 1, 0, 1, 2, 3, 4])
+ assert torch.equal(got, expected)
diff --git a/packages/sie_server/tests/adapters/test_visual_document.py b/packages/sie_server/tests/adapters/test_visual_document.py
index bd0d41569..62512c712 100644
--- a/packages/sie_server/tests/adapters/test_visual_document.py
+++ b/packages/sie_server/tests/adapters/test_visual_document.py
@@ -12,6 +12,7 @@ import pytest
from sie_server.adapters.colpali import ColPaliAdapter
from sie_server.adapters.colqwen2 import ColQwen2Adapter
from sie_server.adapters.colqwen3 import ColQwen3Adapter
+from sie_server.adapters.colsmol import ColSmolAdapter
from sie_server.adapters.nemo_colembed import NemoColEmbedAdapter
from sie_server.types.inputs import Item
@@ -239,6 +240,92 @@ class TestColQwen3Adapter:
assert mv[8, 0] == 3.0
+class TestColSmolAdapter:
+ """Tests for ColSmolAdapter with mocked model (small permissive visual-MV)."""
+
+ @pytest.fixture
+ def adapter(self) -> ColSmolAdapter:
+ """Create an adapter instance."""
+ return ColSmolAdapter(
+ "vidore/colSmol-256M",
+ normalize=True,
+ compute_precision="bfloat16",
+ )
+
+ def test_capabilities(self, adapter: ColSmolAdapter) -> None:
+ """Adapter reports correct capabilities."""
+ caps = adapter.capabilities
+ assert caps.inputs == ["text", "image"]
+ assert caps.outputs == ["multivector", "score"]
+
+ def test_dims_before_load_has_default(self, adapter: ColSmolAdapter) -> None:
+ """Dims returns default value before load."""
+ dims = adapter.dims
+ assert dims.multivector == 128 # ColSmol default
+
+ def test_encode_before_load_raises(self, adapter: ColSmolAdapter) -> None:
+ """Encode before load raises error."""
+ items = [Item(text="hello")]
+ with pytest.raises(RuntimeError, match="Model not loaded"):
+ adapter.encode(items, output_types=["multivector"])
+
+ def test_encode_without_input_raises(self, adapter: ColSmolAdapter) -> None:
+ """Encode raises if item has no text or images."""
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ adapter._device = "cpu"
+
+ items = [Item()] # No text or images
+ with pytest.raises(ValueError, match="requires either text or images"):
+ adapter.encode(items, output_types=["multivector"])
+
+ def test_validate_output_types(self, adapter: ColSmolAdapter) -> None:
+ """Only multivector output type is supported."""
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ adapter._device = "cpu"
+
+ items = [Item(text="test")]
+ with pytest.raises(ValueError, match="Unsupported output types"):
+ adapter.encode(items, output_types=["dense"])
+
+ with pytest.raises(ValueError, match="Unsupported output types"):
+ adapter.encode(items, output_types=["sparse"])
+
+ def test_encode_mixed_batch_preserves_order(self, adapter: ColSmolAdapter) -> None:
+ """Mixed text/image items round-trip in input order with one mv per item."""
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ adapter._device = "cpu"
+ adapter._multivector_dim = 4
+
+ adapter._load_images = lambda item: ["img"] * (1 if item.images else 0) # type: ignore[method-assign]
+
+ def fake_encode_images(images: list[Any]) -> list[np.ndarray]:
+ return [np.full((2, 4), float(i + 100), dtype=np.float32) for i, _ in enumerate(images)]
+
+ def fake_encode_text(text: str) -> np.ndarray:
+ return np.full((1, 4), float(hash(text) % 1000), dtype=np.float32)
+
+ adapter._encode_images = fake_encode_images # type: ignore[method-assign]
+ adapter._encode_text = fake_encode_text # type: ignore[method-assign]
+
+ items = [
+ Item(text="a", images=[{"data": b"x", "format": "png"}]),
+ Item(text="b"),
+ Item(text="c", images=[{"data": b"y", "format": "png"}]),
+ Item(text="d"),
+ ]
+ out = adapter.encode(items, output_types=["multivector"])
+ assert out.batch_size == len(items)
+ assert out.multivector is not None
+ assert len(out.multivector) == len(items)
+ assert out.multivector[0][0, 0] == 100.0
+ assert out.multivector[1][0, 0] == float(hash("b") % 1000)
+ assert out.multivector[2][0, 0] == 101.0
+ assert out.multivector[3][0, 0] == float(hash("d") % 1000)
+
+
class TestNemoColEmbedV2Config:
"""Tests for NemoColEmbedAdapter v2 configuration (Qwen3-VL backbone, token_dim=2560)."""
@@ -396,6 +483,15 @@ class TestVLMCudaCacheClearing:
"ColQwen2._encode_images_batched must call torch.cuda.empty_cache() to prevent OOM"
)
+ def test_colsmol_encode_images_has_empty_cache(self) -> None:
+ """ColSmol _encode_images source contains empty_cache call."""
+ import inspect
+
+ source = inspect.getsource(ColSmolAdapter._encode_images)
+ assert "torch.cuda.empty_cache()" in source, (
+ "ColSmol._encode_images must call torch.cuda.empty_cache() to prevent OOM"
+ )
+
def test_nemo_colembed_encode_images_has_empty_cache(self) -> None:
"""NemoColEmbed _encode_images source contains empty_cache call."""
import inspect
diff --git a/packages/sie_server/tests/api/test_encode_endpoint.py b/packages/sie_server/tests/api/test_encode_endpoint.py
index 346ae13a3..5b57bc88b 100644
--- a/packages/sie_server/tests/api/test_encode_endpoint.py
+++ b/packages/sie_server/tests/api/test_encode_endpoint.py
@@ -783,3 +783,40 @@ class TestEncodeLoraRouting:
assert response.headers.get("Retry-After") != "1"
registry.ensure_lora_loaded_async.assert_called_once_with("test-model", "org/test-lora")
mock_adapter.encode.assert_not_called()
+
+ def test_lora_on_non_supporting_model_returns_typed_400(self, mock_adapter: MagicMock) -> None:
+ """A lora_id aimed at a non-LoRA model must be a typed 400, never a silent serve.
+
+ Negative control for the LoRA capability audit: adapters whose forward
+ cannot honor a LoRA (e.g. ``bert_flash`` fused-QKV, ``nomic_flash`` raw
+ safetensors) report ``supports_lora() == False``, which makes
+ ``ModelRegistry.ensure_lora_loaded_async`` raise ``ValueError`` (the
+ exact raise is locked by
+ ``tests/adapters/test_lora.py::TestLoraRejectionOnNonSupportingAdapters``).
+ The endpoint must translate that into 400 INVALID_INPUT and must NOT
+ fall through to serving base weights as if the LoRA were applied.
+ """
+ registry = self._make_lora_registry(mock_adapter)
+ registry.ensure_lora_loaded_async = AsyncMock(
+ side_effect=ValueError("Model 'test-model' does not support LoRA"),
+ )
+ app = FastAPI()
+ app.include_router(encode_router)
+ app.state.registry = registry
+ client = TestClient(app)
+
+ response = client.post(
+ "/v1/encode/test-model",
+ json={
+ "items": [{"text": "Hello"}],
+ "params": {"options": {"lora_id": "org/customer-lora"}},
+ },
+ headers=JSON_HEADERS,
+ )
+ assert response.status_code == 400
+ detail = response.json()["detail"]
+ assert detail["code"] == "INVALID_INPUT"
+ assert "does not support LoRA" in detail["message"]
+ # The worst-case failure mode is silent mis-serving: the request must
+ # not reach the adapter at all.
+ mock_adapter.encode.assert_not_called()
diff --git a/packages/sie_server/tests/api/test_models.py b/packages/sie_server/tests/api/test_models.py
index c127a5caa..3525a0fc0 100644
--- a/packages/sie_server/tests/api/test_models.py
+++ b/packages/sie_server/tests/api/test_models.py
@@ -336,3 +336,49 @@ class TestModelCapabilitiesField:
by_name = {m["name"]: m for m in response.json()["models"]}
assert by_name["gen-model"]["capabilities"]["code"] is True
assert by_name["enc-model"]["capabilities"] is None
+
+
+class TestModelRevisionField:
+ """Coverage for the additive ``revision`` field on ``ModelInfo`` (design §6.6)."""
+
+ _SHA = "5617a9f61b028005a4858fdac845db406aefb181"
+
+ @pytest.fixture
+ def rev_client(self) -> TestClient:
+ registry = MagicMock(spec=ModelRegistry)
+ registry.model_names = ["pinned", "unpinned"]
+ configs = {
+ "pinned": ModelConfig(
+ sie_id="pinned",
+ hf_id="org/pinned",
+ hf_revision=self._SHA,
+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),
+ profiles={"default": ProfileConfig(adapter_path="test:Adapter", max_batch_tokens=8192)},
+ ),
+ "unpinned": _make_config("unpinned", "org/unpinned", dense_dim=768),
+ }
+ registry.get_config = lambda name: configs[name]
+ registry.has_model = lambda name: name in configs
+ registry.is_loaded = lambda _name: False
+ registry.is_loading = lambda _name: False
+ registry.is_unloading = lambda _name: False
+ registry.is_failed = lambda _name: False
+ registry.get_failure = lambda _name: None
+
+ app = FastAPI()
+ app.include_router(models_router)
+ app.state.registry = registry
+ return TestClient(app)
+
+ def test_get_model_surfaces_pinned_revision(self, rev_client: TestClient) -> None:
+ data = rev_client.get("/v1/models/pinned").json()
+ assert data["revision"] == self._SHA
+
+ def test_unpinned_model_revision_is_null(self, rev_client: TestClient) -> None:
+ data = rev_client.get("/v1/models/unpinned").json()
+ assert data["revision"] is None
+
+ def test_list_models_carries_revision(self, rev_client: TestClient) -> None:
+ by_name = {m["name"]: m for m in rev_client.get("/v1/models").json()["models"]}
+ assert by_name["pinned"]["revision"] == self._SHA
+ assert by_name["unpinned"]["revision"] is None
diff --git a/packages/sie_server/tests/app/test_app_factory.py b/packages/sie_server/tests/app/test_app_factory.py
index b0821d634..522d65138 100644
--- a/packages/sie_server/tests/app/test_app_factory.py
+++ b/packages/sie_server/tests/app/test_app_factory.py
@@ -385,6 +385,7 @@ class TestPreloadModelsEnvRoundTrip:
monkeypatch.delenv("SIE_MODELS_DIR", raising=False)
monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)
monkeypatch.delenv("SIE_DEVICE", raising=False)
+ monkeypatch.delenv("SIE_DEVICES", raising=False)
monkeypatch.delenv("SIE_POOL", raising=False)
monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)
@@ -392,36 +393,73 @@ class TestPreloadModelsEnvRoundTrip:
config.save_to_env_vars()
restored = AppStateConfig.from_env_vars()
assert restored.preload_models == ["model-a", "model-b"]
+ assert restored.devices is None
- def test_preload_models_none_round_trip(self, monkeypatch) -> None:
- """preload_models=None survives env round-trip."""
+ def test_devices_env_round_trip(self, monkeypatch) -> None:
+ """Devices survives save_to_env_vars / from_env_vars cycle."""
monkeypatch.delenv("SIE_PRELOAD_MODELS", raising=False)
monkeypatch.delenv("SIE_MODELS_DIR", raising=False)
monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)
monkeypatch.delenv("SIE_DEVICE", raising=False)
+ monkeypatch.delenv("SIE_DEVICES", raising=False)
monkeypatch.delenv("SIE_POOL", raising=False)
- monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)
- config = AppStateConfig(preload_models=None)
+ config = AppStateConfig(device="cuda", devices=["cuda:0", "cuda:1"])
config.save_to_env_vars()
restored = AppStateConfig.from_env_vars()
- assert restored.preload_models is None
+ assert restored.device == "cuda"
+ assert restored.devices == ["cuda:0", "cuda:1"]
assert restored.pool_name is None
+ def test_devices_env_derives_default_device_family(self, monkeypatch) -> None:
+ """SIE_DEVICES alone turns the default CPU family into the concrete device family."""
+ monkeypatch.delenv("SIE_DEVICE", raising=False)
+ monkeypatch.setenv("SIE_DEVICES", "cuda:0,cuda:1")
+
+ restored = AppStateConfig.from_env_vars()
+
+ assert restored.device == "cuda"
+ assert restored.devices == ["cuda:0", "cuda:1"]
+
+ def test_devices_reject_mismatched_device_family(self) -> None:
+ with pytest.raises(ValueError, match="must match SIE_DEVICES"):
+ AppStateConfig(device="mps", devices=["cuda:0"])
+
+ def test_devices_reject_mixed_families_with_default_device(self) -> None:
+ with pytest.raises(ValueError, match="must match SIE_DEVICES"):
+ AppStateConfig(devices=["cuda:0", "mps:0"])
+
def test_pool_name_env_round_trip(self, monkeypatch) -> None:
"""SIE_POOL survives save_to_env_vars / from_env_vars cycle."""
monkeypatch.delenv("SIE_PRELOAD_MODELS", raising=False)
monkeypatch.delenv("SIE_MODELS_DIR", raising=False)
monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)
monkeypatch.delenv("SIE_DEVICE", raising=False)
+ monkeypatch.delenv("SIE_DEVICES", raising=False)
monkeypatch.delenv("SIE_POOL", raising=False)
- monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)
config = AppStateConfig(pool_name="customer-a")
config.save_to_env_vars()
restored = AppStateConfig.from_env_vars()
assert restored.pool_name == "customer-a"
+ def test_preload_models_none_round_trip(self, monkeypatch) -> None:
+ """preload_models=None survives env round-trip."""
+ monkeypatch.delenv("SIE_PRELOAD_MODELS", raising=False)
+ monkeypatch.delenv("SIE_MODELS_DIR", raising=False)
+ monkeypatch.delenv("SIE_MODEL_FILTER", raising=False)
+ monkeypatch.delenv("SIE_DEVICE", raising=False)
+ monkeypatch.delenv("SIE_DEVICES", raising=False)
+ monkeypatch.delenv("SIE_POOL", raising=False)
+ monkeypatch.delenv("SIE_PINNED_MODELS", raising=False)
+
+ config = AppStateConfig(preload_models=None)
+ config.save_to_env_vars()
+ restored = AppStateConfig.from_env_vars()
+ assert restored.preload_models is None
+ assert restored.pool_name is None
+ assert restored.devices is None
+
def test_pinned_models_env_round_trip(self, monkeypatch) -> None:
"""SIE_PINNED_MODELS='a,b' round-trips to pinned_models == ['a', 'b']."""
monkeypatch.delenv("SIE_PRELOAD_MODELS", raising=False)
diff --git a/packages/sie_server/tests/config/test_bundle_coverage.py b/packages/sie_server/tests/config/test_bundle_coverage.py
index 0e906ff33..3cff32962 100644
--- a/packages/sie_server/tests/config/test_bundle_coverage.py
+++ b/packages/sie_server/tests/config/test_bundle_coverage.py
@@ -124,6 +124,24 @@ def test_candle_bundle_only_exposes_profile_variants() -> None:
)
+def test_gte_multilingual_candle_profile_targets_rust_fp16() -> None:
+ model_yaml = MODELS_DIR / "Alibaba-NLP__gte-multilingual-base.yaml"
+ data = yaml.safe_load(model_yaml.read_text()) or {}
+ profiles = data["profiles"]
+
+ default = profiles["default"]
+ candle = profiles["candle"]
+
+ assert default["adapter_path"] == "sie_server.adapters.rope_flash:RoPEFlashAdapter"
+ assert candle["extends"] == "default"
+ assert candle["adapter_path"] == "sie_server_rust.adapters.candle:CandleEmbeddingAdapter"
+ assert candle["compute_precision"] == "float16"
+ assert "Alibaba-NLP/gte-multilingual-base:candle" in match_bundle_models(
+ BUNDLES_DIR / "candle.yaml",
+ MODELS_DIR,
+ )
+
+
@pytest.mark.parametrize("bundle_yaml", sorted(BUNDLES_DIR.glob("*.yaml")))
def test_bundle_yaml_has_required_fields(bundle_yaml: Path) -> None:
data = yaml.safe_load(bundle_yaml.read_text()) or {}
diff --git a/packages/sie_server/tests/config/test_config.py b/packages/sie_server/tests/config/test_config.py
index c9fec25b8..0bd971aac 100644
--- a/packages/sie_server/tests/config/test_config.py
+++ b/packages/sie_server/tests/config/test_config.py
@@ -55,6 +55,17 @@ class TestEngineConfig:
assert config.attention_backend == "flash_attention_2"
assert config.default_compute_precision == "bfloat16"
+ def test_max_batch_requests_from_env(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """SIE_MAX_BATCH_REQUESTS overrides the batch-depth cap (the sglang-embed deep-batch lane knob).
+
+ The managed embed lane bakes this env into the container image so the
+ engine's batcher packs deeper forwards; proves the env-wiring the deploy
+ relies on (default 64 -> 128).
+ """
+ assert EngineConfig().max_batch_requests == 64
+ monkeypatch.setenv("SIE_MAX_BATCH_REQUESTS", "128")
+ assert EngineConfig().max_batch_requests == 128
+
def test_invalid_attention_backend(self) -> None:
"""Invalid attention backend is rejected."""
with pytest.raises(ValidationError):
diff --git a/packages/sie_server/tests/core/test_registry_async.py b/packages/sie_server/tests/core/test_registry_async.py
index ec734bed9..fd8e6b338 100644
--- a/packages/sie_server/tests/core/test_registry_async.py
+++ b/packages/sie_server/tests/core/test_registry_async.py
@@ -1,4 +1,6 @@
import asyncio
+from collections.abc import Callable, Iterator
+from contextlib import ExitStack
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
@@ -6,6 +8,7 @@ import pytest
from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks
from sie_server.core.memory import MemoryConfig, MemoryStats
from sie_server.core.registry import ModelRegistry
+from sie_server.core.residency import EvictionResult
def _make_config(
@@ -297,14 +300,159 @@ class TestAsyncLoading:
await registry_with_model.load_async("test-model", "cpu")
+class TestMultiDevicePlacement:
+ """Tests for whole-model placement across multiple configured devices."""
+
+ @pytest.fixture
+ def registry_with_three_models(self) -> Iterator[ModelRegistry]:
+ with ExitStack() as stack:
+ registry = ModelRegistry(device="cuda", devices=["cuda:0", "cuda:1"])
+ for name in ["model-a", "model-b", "model-c"]:
+ registry.add_config(_make_config(name=name, hf_id=f"org/{name}"))
+ for manager in registry.memory_managers.values():
+ stack.enter_context(patch.object(manager, "check_pressure", return_value=False))
+ yield registry
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_load_async_places_models_across_devices(
+ self,
+ mock_load_adapter: MagicMock,
+ registry_with_three_models: ModelRegistry,
+ ) -> None:
+ """Lazy loads distribute whole models across configured devices."""
+ adapters = [MagicMock() for _ in range(3)]
+ for adapter in adapters:
+ adapter.capabilities.outputs = ["dense"]
+ adapter.memory_footprint.return_value = 1000
+ mock_load_adapter.side_effect = adapters
+
+ await registry_with_three_models.load_async("model-a", "cuda")
+ await registry_with_three_models.load_async("model-b", "cuda")
+ await registry_with_three_models.load_async("model-c", "cuda")
+
+ assert registry_with_three_models._loaded["model-a"].device == "cuda:0"
+ assert registry_with_three_models._loaded["model-b"].device == "cuda:1"
+ assert registry_with_three_models._loaded["model-c"].device == "cuda:0"
+ adapters[0].load.assert_called_once_with("cuda:0")
+ adapters[1].load.assert_called_once_with("cuda:1")
+ adapters[2].load.assert_called_once_with("cuda:0")
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_family_request_only_scores_matching_devices(self, mock_load_adapter: MagicMock) -> None:
+ """A cuda family request must not select another configured device family."""
+ registry = ModelRegistry(device="cuda", devices=["cuda:0", "mps:0"])
+ registry.add_config(_make_config(name="model-a", hf_id="org/model-a"))
+ for manager in registry.memory_managers.values():
+ manager.check_pressure = MagicMock(return_value=False) # type: ignore[method-assign]
+ registry.memory_managers["cuda:0"].register_model("already-loaded")
+
+ adapter = MagicMock()
+ adapter.capabilities.outputs = ["dense"]
+ adapter.memory_footprint.return_value = 1000
+ mock_load_adapter.return_value = adapter
+
+ await registry.load_async("model-a", "cuda")
+
+ assert registry._loaded["model-a"].device == "cuda:0"
+ adapter.load.assert_called_once_with("cuda:0")
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_oom_recovery_evicts_only_same_device_siblings(
+ self,
+ mock_load_adapter: MagicMock,
+ registry_with_three_models: ModelRegistry,
+ ) -> None:
+ """Worker OOM recovery frees memory on the caller's device only."""
+ adapters = [MagicMock() for _ in range(3)]
+ for adapter in adapters:
+ adapter.capabilities.outputs = ["dense"]
+ adapter.memory_footprint.return_value = 1000
+ mock_load_adapter.side_effect = adapters
+
+ await registry_with_three_models.load_async("model-a", "cuda:0")
+ await registry_with_three_models.load_async("model-b", "cuda:1")
+
+ assert (
+ await registry_with_three_models.evict_lru_excluding("model-b", timeout_s=1.0)
+ == EvictionResult.NO_CANDIDATE
+ )
+ assert registry_with_three_models.is_loaded("model-a")
+ assert registry_with_three_models.is_loaded("model-b")
+
+ await registry_with_three_models.load_async("model-c", "cuda:1")
+ assert await registry_with_three_models.evict_lru_excluding("model-b", timeout_s=1.0) == EvictionResult.EVICTED
+ assert registry_with_three_models.is_loaded("model-a")
+ assert registry_with_three_models.is_loaded("model-b")
+ assert not registry_with_three_models.is_loaded("model-c")
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_lru_touch_uses_loaded_model_device_manager(
+ self,
+ mock_load_adapter: MagicMock,
+ registry_with_three_models: ModelRegistry,
+ ) -> None:
+ """Hot-path LRU touches update the concrete device a model loaded on."""
+ adapters = [MagicMock() for _ in range(2)]
+ for adapter in adapters:
+ adapter.capabilities.outputs = ["dense"]
+ adapter.memory_footprint.return_value = 1000
+ mock_load_adapter.side_effect = adapters
+
+ await registry_with_three_models.load_async("model-a", "cuda:1")
+ await registry_with_three_models.load_async("model-b", "cuda:1")
+ manager = registry_with_three_models.memory_managers["cuda:1"]
+ assert manager.get_lru_model() == "model-a"
+
+ worker = MagicMock()
+ worker.is_running = True
+ worker.start = AsyncMock()
+ registry_with_three_models._loaded["model-a"].worker = worker
+ assert await registry_with_three_models.start_worker("model-a") is worker
+ worker.start.assert_not_awaited()
+ assert manager.get_lru_model() == "model-b"
+
+ registry_with_three_models.touch_lru("model-b")
+ assert manager.get_lru_model() == "model-a"
+
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_replace_configs_unloads_from_concrete_device_manager(
+ self,
+ mock_load_adapter: MagicMock,
+ registry_with_three_models: ModelRegistry,
+ ) -> None:
+ """Authoritative config replacement cleans up the loaded model's device LRU."""
+ adapter = MagicMock()
+ adapter.aclose_client = None
+ adapter.capabilities.outputs = ["dense"]
+ adapter.memory_footprint.return_value = 1000
+ adapter.requires_main_thread = False
+ mock_load_adapter.return_value = adapter
+
+ await registry_with_three_models.load_async("model-a", "cuda:1")
+ assert registry_with_three_models.memory_managers["cuda:1"].loaded_models == ["model-a"]
+
+ current_configs = registry_with_three_models.get_configs_snapshot()
+ invalidated = await registry_with_three_models.replace_configs_async(
+ [
+ _make_config(name="model-a", hf_id="org/model-a", dense_dim=1024),
+ current_configs["model-b"],
+ current_configs["model-c"],
+ ]
+ )
+
+ assert invalidated == {"model-a"}
+ assert not registry_with_three_models.is_loaded("model-a")
+ assert registry_with_three_models.memory_managers["cuda:1"].loaded_models == []
+
+
class TestProactiveEviction:
"""Tests for proactive memory eviction (pre-load and background monitor)."""
@pytest.fixture
- def mock_adapter_factory(self) -> MagicMock:
+ def mock_adapter_factory(self) -> Callable[[], MagicMock]:
"""Create a factory that returns fresh mock adapters."""
- def make_mock():
+ def make_mock() -> MagicMock:
mock = MagicMock()
mock.capabilities.outputs = ["dense"]
mock.memory_footprint.return_value = 1000
@@ -313,7 +461,7 @@ class TestProactiveEviction:
return make_mock
@pytest.fixture
- def registry_with_models(self, mock_adapter_factory: MagicMock) -> ModelRegistry:
+ def registry_with_models(self, mock_adapter_factory: Callable[[], MagicMock]) -> ModelRegistry:
"""Create registry with 3 model configs."""
from sie_server.core.memory import MemoryConfig
@@ -329,7 +477,10 @@ class TestProactiveEviction:
@patch("sie_server.core.model_loader.load_adapter")
async def test_pre_load_eviction_triggers_when_above_threshold(
- self, mock_load_adapter: MagicMock, registry_with_models: ModelRegistry, mock_adapter_factory: MagicMock
+ self,
+ mock_load_adapter: MagicMock,
+ registry_with_models: ModelRegistry,
+ mock_adapter_factory: Callable[[], MagicMock],
) -> None:
"""Pre-load eviction evicts LRU when memory is above threshold."""
adapters = [mock_adapter_factory() for _ in range(3)]
@@ -354,7 +505,10 @@ class TestProactiveEviction:
@patch("sie_server.core.model_loader.load_adapter")
async def test_pre_load_eviction_loop_evicts_multiple(
- self, mock_load_adapter: MagicMock, registry_with_models: ModelRegistry, mock_adapter_factory: MagicMock
+ self,
+ mock_load_adapter: MagicMock,
+ registry_with_models: ModelRegistry,
+ mock_adapter_factory: Callable[[], MagicMock],
) -> None:
"""Pre-load eviction can evict multiple models until below threshold."""
adapters = [mock_adapter_factory() for _ in range(3)]
@@ -455,16 +609,15 @@ class TestProactiveEviction:
check_count += 1
return False # No pressure, so no eviction needed
- registry._memory_manager.check_pressure = counting_check
-
- await registry.start_memory_monitor()
- try:
- # Wait for a few check cycles
- await asyncio.sleep(0.02)
- # Should have been called multiple times
- assert check_count >= 2
- finally:
- await registry.stop_memory_monitor()
+ with patch.object(registry._memory_manager, "check_pressure", side_effect=counting_check):
+ await registry.start_memory_monitor()
+ try:
+ # Wait for a few check cycles
+ await asyncio.sleep(0.02)
+ # Should have been called multiple times
+ assert check_count >= 2
+ finally:
+ await registry.stop_memory_monitor()
@patch("sie_server.core.model_loader.load_adapter")
async def test_memory_monitor_does_not_evict_only_loaded_model(
@@ -493,6 +646,39 @@ class TestProactiveEviction:
assert registry.is_loaded("model-a")
mock_adapter.unload.assert_not_called()
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_memory_monitor_skips_pinned_lru_model(
+ self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock
+ ) -> None:
+ """Pressure monitor evicts the oldest non-pinned model, never a pinned LRU."""
+ registry = ModelRegistry(
+ pinned_models=["model-pinned"],
+ memory_config=MemoryConfig(
+ pressure_threshold=0.95,
+ memory_check_interval_s=0.005,
+ ),
+ )
+ registry.add_config(_make_config(name="model-pinned", hf_id="org/model-pinned"))
+ registry.add_config(_make_config(name="model-other", hf_id="org/model-other"))
+ adapter_pinned = mock_adapter_factory()
+ adapter_other = mock_adapter_factory()
+ mock_load_adapter.side_effect = [adapter_pinned, adapter_other]
+
+ await registry.load_async("model-pinned", "cpu")
+ await registry.load_async("model-other", "cpu")
+ registry._memory_manager.check_pressure = MagicMock(return_value=True)
+
+ await registry.start_memory_monitor()
+ try:
+ await asyncio.sleep(0.02)
+ finally:
+ await registry.stop_memory_monitor()
+
+ assert registry.is_loaded("model-pinned")
+ assert not registry.is_loaded("model-other")
+ adapter_pinned.unload.assert_not_called()
+ adapter_other.unload.assert_called_once()
+
async def test_memory_monitor_starts_and_stops(self) -> None:
"""Memory monitor can be started and stopped cleanly."""
from sie_server.core.memory import MemoryConfig
diff --git a/packages/sie_server/tests/core/test_residency.py b/packages/sie_server/tests/core/test_residency.py
new file mode 100644
index 000000000..135745f5b
--- /dev/null
+++ b/packages/sie_server/tests/core/test_residency.py
@@ -0,0 +1,49 @@
+# Tests for the pure eviction-decision helper in core/residency.py.
+#
+# ``select_eviction_candidate`` is the *policy* half of
+# ``ModelRegistry.evict_lru_excluding`` (the registry keeps the I/O half).
+# Exercising it directly locks the LRU-walk skip rules without standing up a
+# registry — the worker's OOM-recovery path must not import the registry.
+
+from __future__ import annotations
+
+from sie_server.core.residency import select_eviction_candidate
+
+
+def _never_pinned(_name: str) -> bool:
+ return False
+
+
+def test_selects_first_eligible_in_lru_order() -> None:
+ got = select_eviction_candidate(
+ ["a", "b", "c"],
+ exclude_name="z",
+ is_pinned=_never_pinned,
+ loaded={"a", "b", "c"},
+ unloading=set(),
+ )
+ assert got == "a"
+
+
+def test_skips_exclude_pinned_ghost_and_unloading() -> None:
+ # a == exclude, b pinned, c is a ghost (in LRU order but not loaded),
+ # d is already unloading, e is the first eligible sibling.
+ got = select_eviction_candidate(
+ ["a", "b", "c", "d", "e"],
+ exclude_name="a",
+ is_pinned=lambda n: n == "b",
+ loaded={"a", "b", "d", "e"}, # c absent -> ghost, skipped
+ unloading={"d"},
+ )
+ assert got == "e"
+
+
+def test_returns_none_when_nothing_eligible() -> None:
+ got = select_eviction_candidate(
+ ["only-self"],
+ exclude_name="only-self",
+ is_pinned=_never_pinned,
+ loaded={"only-self"},
+ unloading=set(),
+ )
+ assert got is None
diff --git a/packages/sie_server/tests/core/test_revision_identity.py b/packages/sie_server/tests/core/test_revision_identity.py
new file mode 100644
index 000000000..96f205bbb
--- /dev/null
+++ b/packages/sie_server/tests/core/test_revision_identity.py
@@ -0,0 +1,119 @@
+"""Served-model version-identity validation (design §6.6).
+
+A promoted/served HF-backed model must pin ``hf_revision`` to an immutable
+commit SHA so its ``sie_id`` maps to identical weights forever; a weights
+change becomes a NEW versioned id. ``weights_path`` / ``package_backed`` models
+are exempt (no Hub revision to drift).
+"""
+
+from pathlib import Path
+
+import pytest
+from sie_server.config.model import (
+ EmbeddingDim,
+ EncodeTask,
+ ExtractTask,
+ ModelConfig,
+ ProfileConfig,
+ Tasks,
+)
+from sie_server.core.loader import (
+ is_immutable_revision,
+ load_model_configs,
+ require_pinned_revisions,
+ validate_pinned_revision,
+)
+
+_SHA = "5617a9f61b028005a4858fdac845db406aefb181" # a real 40-hex commit SHA shape
+
+
+def _encode_config(
+ *,
+ hf_id: str | None = "org/model",
+ hf_revision: str | None = None,
+ weights_path: Path | None = None,
+ package_backed: bool = False,
+) -> ModelConfig:
+ kwargs: dict = {
+ "sie_id": "org/model",
+ "package_backed": package_backed,
+ "tasks": Tasks(extract=ExtractTask())
+ if package_backed
+ else Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),
+ "profiles": {"default": ProfileConfig(adapter_path="test:Adapter", max_batch_tokens=8192)},
+ }
+ if not package_backed:
+ kwargs["hf_id"] = hf_id
+ kwargs["hf_revision"] = hf_revision
+ kwargs["weights_path"] = weights_path
+ return ModelConfig(**kwargs)
+
+
+class TestIsImmutableRevision:
+ @pytest.mark.parametrize("rev", [_SHA, "0" * 40, "abcdef0123456789abcdef0123456789abcdef01"])
+ def test_accepts_40_hex_sha(self, rev: str) -> None:
+ assert is_immutable_revision(rev) is True
+
+ @pytest.mark.parametrize("rev", [None, "main", "v1.0", _SHA[:12], _SHA + "aa", _SHA.upper()])
+ def test_rejects_non_immutable(self, rev: str | None) -> None:
+ assert is_immutable_revision(rev) is False
+
+
+class TestValidatePinnedRevision:
+ def test_rejects_unpinned_hf_model(self) -> None:
+ with pytest.raises(ValueError, match="has no 'hf_revision'"):
+ validate_pinned_revision(_encode_config(hf_revision=None))
+
+ def test_rejects_branch_pin(self) -> None:
+ with pytest.raises(ValueError, match="immutable 40-char commit SHA"):
+ validate_pinned_revision(_encode_config(hf_revision="main"))
+
+ def test_accepts_immutable_sha(self) -> None:
+ validate_pinned_revision(_encode_config(hf_revision=_SHA)) # no raise
+
+ def test_weights_path_model_is_exempt(self) -> None:
+ validate_pinned_revision(_encode_config(hf_id=None, weights_path=Path("/w/model")))
+
+ def test_package_backed_model_is_exempt(self) -> None:
+ validate_pinned_revision(_encode_config(package_backed=True))
+
+
+_MODEL_YAML = """\
+sie_id: {sie_id}
+hf_id: {hf_id}
+{rev_line}tasks:
+ encode:
+ dense:
+ dim: 768
+profiles:
+ default:
+ adapter_path: test:Adapter
+ max_batch_tokens: 8192
+"""
+
+
+def _write_yaml(models_dir: Path, name: str, *, revision: str | None) -> None:
+ rev_line = f"hf_revision: {revision}\n" if revision is not None else ""
+ (models_dir / f"{name}.yaml").write_text(
+ _MODEL_YAML.format(sie_id=f"org/{name}", hf_id=f"org/{name}", rev_line=rev_line)
+ )
+
+
+class TestRequirePinnedRevisionsAtLoad:
+ def test_strict_load_rejects_unpinned(self, tmp_path: Path) -> None:
+ _write_yaml(tmp_path, "pinned", revision=_SHA)
+ _write_yaml(tmp_path, "unpinned", revision=None)
+ with pytest.raises(ValueError, match="hf_revision"):
+ load_model_configs(tmp_path, require_pinned_revision=True)
+
+ def test_non_strict_load_accepts_unpinned(self, tmp_path: Path) -> None:
+ _write_yaml(tmp_path, "unpinned", revision=None)
+ configs = load_model_configs(tmp_path) # default: not strict
+ assert "org/unpinned" in configs
+
+ def test_strict_load_accepts_all_pinned(self, tmp_path: Path) -> None:
+ _write_yaml(tmp_path, "a", revision=_SHA)
+ _write_yaml(tmp_path, "b", revision="cdbee75f17c01a7cc42f958dc650907174af0554")
+ configs = load_model_configs(tmp_path, require_pinned_revision=True)
+ assert {"org/a", "org/b"} <= set(configs)
+ require_pinned_revisions(configs) # idempotent, no raise
diff --git a/packages/sie_server/tests/test_cli_devices.py b/packages/sie_server/tests/test_cli_devices.py
new file mode 100644
index 000000000..39df779fe
--- /dev/null
+++ b/packages/sie_server/tests/test_cli_devices.py
@@ -0,0 +1,33 @@
+from __future__ import annotations
+
+from typing import Any
+
+from sie_server import cli
+from sie_server.app.app_state_config import AppStateConfig
+from typer.testing import CliRunner
+
+
+def test_serve_threads_sie_devices_env_to_app_config(monkeypatch, tmp_path) -> None:
+ """Helm-rendered SIE_DEVICES reaches AppStateConfig through the CLI path."""
+ captured: dict[str, AppStateConfig] = {}
+
+ def fake_run_server(**kwargs: Any) -> None:
+ captured["config"] = kwargs["config"]
+
+ monkeypatch.setenv("SIE_DEVICES", "cuda:0, cuda:1,,")
+ monkeypatch.setattr(cli, "run_server", fake_run_server)
+
+ result = CliRunner().invoke(
+ cli.app,
+ [
+ "serve",
+ "--device",
+ "cuda",
+ "--models-dir",
+ str(tmp_path),
+ ],
+ )
+
+ assert result.exit_code == 0, result.output
+ assert captured["config"].device == "cuda"
+ assert captured["config"].devices == ["cuda:0", "cuda:1"]
diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.py
index 0753dd1d8..9fb30f5f2 100644
--- a/packages/sie_server/tests/test_ipc_server.py
+++ b/packages/sie_server/tests/test_ipc_server.py
@@ -7,6 +7,7 @@ import struct
import tempfile
import time
import uuid
+from collections.abc import Iterator
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
@@ -19,6 +20,7 @@ from sie_sdk.bundle_utils import match_bundle_models
from sie_server.api.ws import compute_bundle_config_hash_cached
from sie_server.config.model import ModelConfig
from sie_server.core.inference_output import ExtractOutput, ScoreOutput
+from sie_server.core.readiness import mark_not_ready, mark_ready, register_liveness_probe
from sie_server.core.registry import ModelRegistry
from sie_server.core.timing import RequestTiming
from sie_server.core.worker.types import WorkerResult
@@ -133,6 +135,15 @@ def _make_executor() -> tuple[QueueExecutor, MagicMock]:
return QueueExecutor(reg), reg
[email protected](autouse=True)
+def _reset_readiness_state() -> Iterator[None]:
+ register_liveness_probe(None)
+ mark_not_ready()
+ yield
+ register_liveness_probe(None)
+ mark_not_ready()
+
+
def _qwen_profile_variant_yaml() -> str:
return """
sie_id: Qwen/Qwen3.6-27B
@@ -243,12 +254,65 @@ class TestFraming:
assert resp["request_id"] == "r1"
assert resp["body"]["timestamp_ms"] == 123.0
assert resp["body"]["worker_id"] == "worker-test"
+ assert resp["body"]["ready"] is False
assert resp["body"]["bundle_config_hash"] == ""
assert resp["body"]["loaded_models"] == ["test/model"]
assert srv.is_heartbeat_fresh()
finally:
await client.close()
+ @pytest.mark.asyncio
+ async def test_ping_reports_ready_after_worker_ready(self, server_and_path) -> None:
+ _srv, sock = server_and_path
+ mark_ready()
+ client = await _Client.connect(sock)
+ try:
+ with patch(
+ "sie_server.ipc_server.gpu_is_healthy_async",
+ new=AsyncMock(return_value=True),
+ ) as health:
+ resp = await client.rpc("Ping", {"timestamp_ms": 123.0})
+ assert resp["ok"] is True
+ assert resp["body"]["ready"] is True
+ health.assert_awaited_once_with()
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_ping_reports_not_ready_when_gpu_health_fails(self, server_and_path) -> None:
+ _srv, sock = server_and_path
+ mark_ready()
+ client = await _Client.connect(sock)
+ try:
+ with patch(
+ "sie_server.ipc_server.gpu_is_healthy_async",
+ new=AsyncMock(return_value=False),
+ ) as health:
+ resp = await client.rpc("Ping", {"timestamp_ms": 123.0})
+ assert resp["ok"] is True
+ assert resp["body"]["ready"] is False
+ health.assert_awaited_once_with()
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_ping_reports_not_ready_when_gpu_health_raises(self, server_and_path) -> None:
+ _srv, sock = server_and_path
+ mark_ready()
+ client = await _Client.connect(sock)
+ try:
+ with patch(
+ "sie_server.ipc_server.gpu_is_healthy_async",
+ new=AsyncMock(side_effect=RuntimeError("nvml unavailable")),
+ ) as health:
+ resp = await client.rpc("Ping", {"timestamp_ms": 123.0})
+ assert resp["ok"] is True
+ assert resp["body"]["ready"] is False
+ assert resp["body"]["loaded_models"] == ["test/model"]
+ health.assert_awaited_once_with()
+ finally:
+ await client.close()
+
@pytest.mark.asyncio
async def test_multiple_requests_on_one_connection(self, server_and_path) -> None:
_srv, sock = server_and_path
diff --git a/packages/sie_server/tests/test_metering_units.py b/packages/sie_server/tests/test_metering_units.py
new file mode 100644
index 000000000..a2f843331
--- /dev/null
+++ b/packages/sie_server/tests/test_metering_units.py
@@ -0,0 +1,866 @@
+"""Unit-meter token-count generalization (§7.3).
+
+Covers the shared metering seam that lets EVERY encode/score adapter surface
+authoritative per-item / per-pair input-token counts without per-adapter code:
+
+* ``BaseAdapter.count_input_tokens`` — encode ground truth (bert_flash/e5,
+ ColBERT, and every flash text encoder inherit it).
+* ``BaseAdapter.count_pair_input_tokens`` — reranker ground truth (flash
+ cross-encoders inherit it).
+* ``EncodePipeline.run_encode`` fallback wiring the encode seam.
+* ``QueueExecutor.process_score_batch`` backfilling the score seam.
+
+Ground-truth assertions mirror G2: the emitted count must equal the adapter
+tokenizer's own ``len(input_ids)`` for the item/pair. Regression assertions
+prove the fallbacks never override counts an adapter already produced (so
+bge-m3 / GLiNER / cross_encoder keep their exact values).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import numpy as np
+import pytest
+from sie_server.adapters._base_adapter import BaseAdapter
+from sie_server.adapters._spec import AdapterSpec
+from sie_server.adapters.bert_flash import BertFlashAdapter
+from sie_server.adapters.clip import CLIPAdapter
+from sie_server.adapters.colbert import ColBERTAdapter
+from sie_server.adapters.jina_flash_cross_encoder import JinaFlashCrossEncoderAdapter
+from sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter
+from sie_server.adapters.siglip import SiglipAdapter
+from sie_server.core.encode_pipeline import EncodePipeline
+from sie_server.core.inference_output import EncodeOutput, ExtractOutput, ScoreOutput
+from sie_server.core.timing import RequestTiming
+from sie_server.core.worker.types import WorkerResult
+from sie_server.ipc_types import (
+ EncodeBatchItem,
+ ExtractBatchItem,
+ ProcessEncodeBatchRequest,
+ ProcessExtractBatchRequest,
+ ProcessScoreBatchRequest,
+ ScoreBatchItem,
+)
+from sie_server.queue_executor import QueueExecutor
+from sie_server.types.inputs import Item
+
+
+class _FakeTokenizer:
+ """Deterministic HF-shaped tokenizer for ground-truth assertions.
+
+ A single text encodes to ``len(text.split()) + 2`` ids (words + CLS/SEP);
+ a joint ``(query, doc)`` pair encodes to ``words(q) + words(d) + 3`` ids
+ (the shared separators of a cross-encoder). Honors ``truncation`` /
+ ``max_length`` so the truncation cap is exercised. Returns ``input_ids`` as
+ a list of lists, exactly like a real fast tokenizer called without
+ ``return_tensors``.
+ """
+
+ def __init__(self, model_max_length: int = 512) -> None:
+ self.model_max_length = model_max_length
+
+ def __call__(
+ self,
+ text: list[str],
+ text_pair: list[str] | None = None,
+ *,
+ truncation: bool = False,
+ max_length: int | None = None,
+ **_: Any,
+ ) -> dict[str, list[list[int]]]:
+ if text_pair is not None:
+ lengths = [len(a.split()) + len(b.split()) + 3 for a, b in zip(text, text_pair, strict=True)]
+ else:
+ lengths = [len(t.split()) + 2 for t in text]
+ if truncation and max_length is not None:
+ lengths = [min(n, max_length) for n in lengths]
+ return {"input_ids": [[0] * n for n in lengths]}
+
+
+# ---------------------------------------------------------------------------
+# count_input_tokens — encode ground truth
+# ---------------------------------------------------------------------------
+
+
+class TestCountInputTokens:
+ def test_bert_flash_matches_tokenizer_ground_truth(self) -> None:
+ adapter = BertFlashAdapter(model_name_or_path="stub/model")
+ adapter._tokenizer = _FakeTokenizer() # type: ignore[assignment]
+ items = [Item(text="alpha beta"), Item(text="one two three four")]
+ # Ground truth mirrors the tokenizer: words + 2 special tokens.
+ assert adapter.count_input_tokens(items) == [4, 6]
+
+ def test_colbert_matches_tokenizer_ground_truth(self) -> None:
+ adapter = ColBERTAdapter(model_name_or_path="stub/model")
+ adapter._tokenizer = _FakeTokenizer() # type: ignore[assignment]
+ items = [Item(text="a b c"), Item(text="single")]
+ assert adapter.count_input_tokens(items) == [5, 3]
+
+ def test_truncation_cap_applied(self) -> None:
+ adapter = BertFlashAdapter(model_name_or_path="stub/model", max_seq_length=4)
+ adapter._tokenizer = _FakeTokenizer() # type: ignore[assignment]
+ # "one two three four five" -> 5 words + 2 = 7, capped at 4.
+ assert adapter.count_input_tokens([Item(text="one two three four five")]) == [4]
+
+ def test_no_tokenizer_returns_none(self) -> None:
+ # Server-backed / image adapters have no in-process tokenizer -> reserve
+ # fallback rather than an approximation billed as a count.
+ adapter = BertFlashAdapter(model_name_or_path="stub/model")
+ adapter._tokenizer = None
+ assert adapter.count_input_tokens([Item(text="hello")]) is None
+
+ def test_non_text_item_returns_none(self) -> None:
+ adapter = BertFlashAdapter(model_name_or_path="stub/model")
+ adapter._tokenizer = _FakeTokenizer() # type: ignore[assignment]
+ assert adapter.count_input_tokens([Item(images=[{"data": b"fake"}])]) is None
+
+ def test_empty_items_returns_empty(self) -> None:
+ adapter = BertFlashAdapter(model_name_or_path="stub/model")
+ adapter._tokenizer = _FakeTokenizer() # type: ignore[assignment]
+ assert adapter.count_input_tokens([]) == []
+
+
+# ---------------------------------------------------------------------------
+# count_pair_input_tokens — reranker ground truth
+# ---------------------------------------------------------------------------
+
+
+class TestCountPairInputTokens:
+ def _adapter(self, *, max_seq_length: int = 512) -> JinaFlashCrossEncoderAdapter:
+ adapter = JinaFlashCrossEncoderAdapter(model_name_or_path="stub/model", max_seq_length=max_seq_length)
+ adapter._tokenizer = _FakeTokenizer() # type: ignore[assignment]
+ return adapter
+
+ def test_flash_cross_encoder_matches_joint_ground_truth(self) -> None:
+ adapter = self._adapter()
+ counts = adapter.count_pair_input_tokens(
+ Item(text="query terms"),
+ [Item(text="doc one"), Item(text="a longer document body")],
+ )
+ # Joint: words(q) + words(d) + 3 separators.
+ assert counts == [2 + 2 + 3, 2 + 4 + 3]
+
+ def test_instruction_is_counted_on_the_query(self) -> None:
+ adapter = self._adapter()
+ base = adapter.count_pair_input_tokens(Item(text="q"), [Item(text="d")])
+ with_instr = adapter.count_pair_input_tokens(Item(text="q"), [Item(text="d")], instruction="please rank")
+ assert base == [1 + 1 + 3]
+ # "please rank q" -> 3 query words instead of 1 -> +2 tokens.
+ assert with_instr == [3 + 1 + 3]
+
+ def test_no_tokenizer_returns_none(self) -> None:
+ adapter = self._adapter()
+ adapter._tokenizer = None
+ assert adapter.count_pair_input_tokens(Item(text="q"), [Item(text="d")]) is None
+
+
+# ---------------------------------------------------------------------------
+# EncodePipeline.run_encode — encode seam wiring
+# ---------------------------------------------------------------------------
+
+
+class _FakeEncodeAdapter(BaseAdapter):
+ """Minimal dense encoder that (optionally) owns its token counts."""
+
+ spec = AdapterSpec(inputs=("text",), outputs=("dense",), unload_fields=("_model",))
+
+ def __init__(self, *, tokenizer: Any = None, stamp_extra: bool = False) -> None:
+ self._model = object()
+ self._tokenizer = tokenizer
+ self._max_seq_length = 512
+ self._stamp_extra = stamp_extra
+ self._device = "cpu"
+
+ def load(self, device: str) -> None: # pragma: no cover - not exercised
+ _ = device
+
+ def encode(
+ self,
+ items: list[Item],
+ output_types: list[str],
+ *,
+ instruction: str | None = None,
+ is_query: bool = False,
+ prepared_items: Any = None,
+ options: dict[str, Any] | None = None,
+ ) -> EncodeOutput:
+ _ = (output_types, instruction, is_query, prepared_items, options)
+ out = EncodeOutput(dense=np.zeros((len(items), 4), dtype=np.float32), batch_size=len(items))
+ if self._stamp_extra:
+ out.extra["input_token_counts"] = [999 for _ in items]
+ return out
+
+
+def _registry_for(adapter: _FakeEncodeAdapter) -> MagicMock:
+ reg = MagicMock()
+ # No text/image preprocessor -> _prepare_batch returns None -> direct path.
+ reg.preprocessor_registry.has_preprocessor.return_value = False
+ reg.postprocessor_registry.transform_sync.return_value = 0.0
+ reg.get.return_value = adapter
+ return reg
+
+
+class TestEncodePipelineFallback:
+ @pytest.mark.asyncio
+ async def test_fallback_populates_units_from_tokenizer(self) -> None:
+ adapter = _FakeEncodeAdapter(tokenizer=_FakeTokenizer())
+ reg = _registry_for(adapter)
+ _formatted, timing = await EncodePipeline.run_encode(
+ registry=reg,
+ model="m",
+ items=[Item(text="alpha beta"), Item(text="one two three four")],
+ output_types=["dense"],
+ instruction=None,
+ config=MagicMock(),
+ is_query=False,
+ options={},
+ )
+ assert timing.input_token_counts == [4, 6]
+
+ @pytest.mark.asyncio
+ async def test_extra_counts_win_over_fallback(self) -> None:
+ # Adapter that pre-stamps extra (like bge-m3) must keep its own counts;
+ # the fallback must not re-tokenize over them.
+ adapter = _FakeEncodeAdapter(tokenizer=_FakeTokenizer(), stamp_extra=True)
+ reg = _registry_for(adapter)
+ _formatted, timing = await EncodePipeline.run_encode(
+ registry=reg,
+ model="m",
+ items=[Item(text="alpha beta"), Item(text="x")],
+ output_types=["dense"],
+ instruction=None,
+ config=MagicMock(),
+ is_query=False,
+ options={},
+ )
+ assert timing.input_token_counts == [999, 999]
+
+ @pytest.mark.asyncio
+ async def test_no_tokenizer_leaves_counts_unset(self) -> None:
+ adapter = _FakeEncodeAdapter(tokenizer=None)
+ reg = _registry_for(adapter)
+ _formatted, timing = await EncodePipeline.run_encode(
+ registry=reg,
+ model="m",
+ items=[Item(text="alpha beta")],
+ output_types=["dense"],
+ instruction=None,
+ config=MagicMock(),
+ is_query=False,
+ options={},
+ )
+ assert timing.input_token_counts is None
+
+
+# ---------------------------------------------------------------------------
+# QueueExecutor.process_score_batch — score seam backfill
+# ---------------------------------------------------------------------------
+
+
+def _score_registry() -> MagicMock:
+ reg = MagicMock()
+ reg.device = "cpu"
+ reg.get_config.return_value = MagicMock()
+ return reg
+
+
+def _score_worker(score_output: ScoreOutput) -> AsyncMock:
+ worker = AsyncMock()
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_result(WorkerResult(output=score_output, timing=RequestTiming()))
+ worker.submit_score_preformed_batch = AsyncMock(return_value=[fut])
+ return worker
+
+
+def _score_request() -> ProcessScoreBatchRequest:
+ return ProcessScoreBatchRequest(
+ model_id="test/model",
+ items=[
+ ScoreBatchItem(
+ work_item_id="req-1.0",
+ request_id="req-1",
+ item_index=0,
+ total_items=1,
+ timestamp=time.time(),
+ query_item={"text": "q"},
+ score_items=[{"text": "a", "id": "doc-a"}, {"text": "b", "id": "doc-b"}],
+ )
+ ],
+ )
+
+
+class TestScoreBackfill:
+ @pytest.mark.asyncio
+ async def test_backfills_units_for_flash_cross_encoder(self) -> None:
+ adapter = JinaFlashCrossEncoderAdapter(model_name_or_path="stub/model", max_seq_length=512)
+ adapter._tokenizer = _FakeTokenizer() # type: ignore[assignment]
+ # Reranker did not surface counts (flash cross-encoder gap).
+ score_output = ScoreOutput(scores=np.array([0.9, 0.1], dtype=np.float32))
+ reg = _score_registry()
+ reg.get.return_value = adapter
+ reg.start_worker = AsyncMock(return_value=_score_worker(score_output))
+
+ ex = QueueExecutor(reg)
+ outcome = await ex.process_score_batch(_score_request())
+
+ o = outcome.outcomes[0]
+ assert o.units is not None
+ # Two pairs, joint count 1 + 1 + 3 = 5 each -> summed billable = 10.
+ assert o.units.input_tokens == 10
+
+ @pytest.mark.asyncio
+ async def test_existing_counts_are_not_overwritten(self) -> None:
+ # An adapter that already surfaced counts (cross_encoder / bge-m3) keeps
+ # them; the backfill is a pure fallback.
+ adapter = JinaFlashCrossEncoderAdapter(model_name_or_path="stub/model", max_seq_length=512)
+ adapter._tokenizer = _FakeTokenizer() # type: ignore[assignment]
+ score_output = ScoreOutput(
+ scores=np.array([0.9, 0.1], dtype=np.float32),
+ input_token_counts=[7, 7],
+ )
+ reg = _score_registry()
+ reg.get.return_value = adapter
+ reg.start_worker = AsyncMock(return_value=_score_worker(score_output))
+
+ ex = QueueExecutor(reg)
+ outcome = await ex.process_score_batch(_score_request())
+
+ o = outcome.outcomes[0]
+ assert o.units is not None
+ assert o.units.input_tokens == 14 # 7 + 7, not the fallback 10
+
+
+# ---------------------------------------------------------------------------
+# Per-image metering (§7 "$ per image")
+# ---------------------------------------------------------------------------
+#
+# The vision analogue of the per-token seam above: any vision adapter inherits
+# authoritative per-image counts from the base ``count_input_images`` hook, the
+# encode/extract result seam stamps ``UnitCounts.images``, and CLIP/SigLIP TEXT
+# (whose tokenizer lives inside the processor, not ``_tokenizer``) now surfaces
+# real token counts through the enhanced ``_metering_tokenizer`` fallback.
+
+
+class _FakeProcessor:
+ """Minimal CLIP/SigLIP-style processor exposing a ``.tokenizer`` (the base
+ ``_metering_tokenizer`` fallback reads it for text-token metering).
+ """
+
+ def __init__(self, tokenizer: Any) -> None:
+ self.tokenizer = tokenizer
+
+
+class _FakeVisionEncodeAdapter(BaseAdapter):
+ """Dual (text+image) dense encoder: inherits ``count_input_images`` and,
+ when given a processor tokenizer, ``count_input_tokens`` for text.
+ """
+
+ spec = AdapterSpec(inputs=("text", "image"), outputs=("dense",), unload_fields=("_model",))
+
+ def __init__(self, *, tokenizer: Any = None) -> None:
+ self._model = object()
+ self._processor = _FakeProcessor(tokenizer) if tokenizer is not None else None
+ self._device = "cpu"
+
+ def load(self, device: str) -> None: # pragma: no cover - not exercised
+ _ = device
+
+ def encode(self, items: list[Item], output_types: list[str], **_: Any) -> EncodeOutput:
+ return EncodeOutput(dense=np.zeros((len(items), 4), dtype=np.float32), batch_size=len(items))
+
+
+class _FakeVisionExtractAdapter(BaseAdapter):
+ """Image-input extractor (Florence-2 shape): inherits ``count_input_images``
+ and surfaces no token counts.
+ """
+
+ spec = AdapterSpec(inputs=("image",), outputs=("json",), unload_fields=("_model",))
+
+ def __init__(self) -> None:
+ self._model = object()
+ self._device = "cpu"
+
+ def load(self, device: str) -> None: # pragma: no cover - not exercised
+ _ = device
+
+ def extract(self, items: list[Item], **_: Any) -> ExtractOutput: # pragma: no cover - worker mocked
+ return ExtractOutput(entities=[[] for _ in items])
+
+
+class _FakeTextExtractAdapter(BaseAdapter):
+ """Text-input extractor (GLiNER shape): no images."""
+
+ spec = AdapterSpec(inputs=("text",), outputs=("json",), unload_fields=("_model",))
+
+ def __init__(self) -> None:
+ self._model = object()
+ self._device = "cpu"
+
+ def load(self, device: str) -> None: # pragma: no cover - not exercised
+ _ = device
+
+ def extract(self, items: list[Item], **_: Any) -> ExtractOutput: # pragma: no cover - worker mocked
+ return ExtractOutput(entities=[[] for _ in items])
+
+
+def _img(fmt: str = "png") -> dict[str, Any]:
+ return {"data": b"fake-image-bytes", "format": fmt}
+
+
+# ---------------------------------------------------------------------------
+# count_input_images — vision ground truth (base hook)
+# ---------------------------------------------------------------------------
+
+
+class TestCountInputImages:
+ def test_counts_images_per_item(self) -> None:
+ adapter = _FakeVisionEncodeAdapter()
+ items = [
+ Item(images=[{"data": b"a"}]),
+ Item(images=[{"data": b"b"}, {"data": b"c"}]),
+ ]
+ assert adapter.count_input_images(items) == [1, 2]
+
+ def test_text_only_items_count_zero(self) -> None:
+ adapter = _FakeVisionEncodeAdapter()
+ assert adapter.count_input_images([Item(text="alpha"), Item(text="beta")]) == [0, 0]
+
+ def test_mixed_batch(self) -> None:
+ adapter = _FakeVisionEncodeAdapter()
+ assert adapter.count_input_images([Item(text="a caption"), Item(images=[{"data": b"x"}])]) == [0, 1]
+
+ def test_empty_items(self) -> None:
+ assert _FakeVisionEncodeAdapter().count_input_images([]) == []
+
+
+# ---------------------------------------------------------------------------
+# CLIP/SigLIP TEXT — processor-tokenizer metering fallback
+# ---------------------------------------------------------------------------
+
+
+class TestProcessorTokenizerMetering:
+ def test_clip_text_counts_via_processor_tokenizer(self) -> None:
+ # CLIP keeps its tokenizer inside _processor, not _tokenizer, so the
+ # base hook must reach it — otherwise CLIP TEXT bills nothing.
+ adapter = CLIPAdapter(model_name_or_path="stub/clip")
+ adapter._processor = _FakeProcessor(_FakeTokenizer()) # type: ignore[assignment]
+ assert adapter.count_input_tokens([Item(text="alpha beta"), Item(text="one two three")]) == [4, 5]
+
+ def test_siglip_text_counts_via_processor_tokenizer(self) -> None:
+ adapter = SiglipAdapter(model_name_or_path="stub/siglip")
+ adapter._processor = _FakeProcessor(_FakeTokenizer()) # type: ignore[assignment]
+ assert adapter.count_input_tokens([Item(text="a b c")]) == [5]
+
+ def test_processor_model_max_length_caps_the_count(self) -> None:
+ # A long text truncates at the tokenizer's model_max_length (the CLIP
+ # 77 / SigLIP 64 context window) rather than over-billing.
+ adapter = CLIPAdapter(model_name_or_path="stub/clip")
+ adapter._processor = _FakeProcessor(_FakeTokenizer(model_max_length=4)) # type: ignore[assignment]
+ # "one two three four five" -> 5 words + 2 specials = 7, capped at 4.
+ assert adapter.count_input_tokens([Item(text="one two three four five")]) == [4]
+
+ def test_image_only_item_returns_none(self) -> None:
+ # No text -> no token count (the image dimension meters it instead).
+ adapter = CLIPAdapter(model_name_or_path="stub/clip")
+ adapter._processor = _FakeProcessor(_FakeTokenizer()) # type: ignore[assignment]
+ assert adapter.count_input_tokens([Item(images=[{"data": b"x"}])]) is None
+
+ def test_no_processor_returns_none(self) -> None:
+ adapter = CLIPAdapter(model_name_or_path="stub/clip")
+ adapter._processor = None
+ assert adapter.count_input_tokens([Item(text="hello")]) is None
+
+
+# ---------------------------------------------------------------------------
+# SGLangEmbeddingAdapter — server-backed self-metering (§7.3)
+# ---------------------------------------------------------------------------
+#
+# SGLang runs the model in a subprocess, so the base ``count_input_tokens``
+# seam has no in-process tokenizer and ``units.input_tokens`` would stay 0 (the
+# meter's reserve fallback) for the promoted dense-SMARTEST tier. The adapter
+# now stamps exact per-item counts onto ``EncodeOutput.extra`` from a lazy,
+# weights-free metering tokenizer, counting the EXACT (template/EOS-formatted,
+# truncated) strings it POSTs to sglang. These tests inject the deterministic
+# ``_FakeTokenizer`` and stub the HTTP POST so no server / weights are needed.
+
+
+class TestSGLangEmbeddingMetering:
+ def _adapter(self, **kwargs: Any) -> SGLangEmbeddingAdapter:
+ adapter = SGLangEmbeddingAdapter(model_name_or_path="stub/qwen3-emb", **kwargs)
+ adapter._server_url = "http://localhost:0" # satisfy _check_loaded
+ adapter._dense_dim = 4
+ adapter._configured_dense_dim = 4
+ # Inject the deterministic metering tokenizer (words + 2 specials),
+ # bypassing the lazy HF load.
+ adapter._metering_tokenizer_obj = _FakeTokenizer() # type: ignore[assignment]
+ adapter._metering_tokenizer_loaded = True
+ return adapter
+
+ @staticmethod
+ def _stub_embed(adapter: SGLangEmbeddingAdapter, dim: int = 4) -> None:
+ # Replace the sglang HTTP POST with a deterministic embedding of the
+ # right shape so encode() runs without a live server.
+ def fake_embed(texts: list[str], model_name: str) -> np.ndarray:
+ _ = model_name
+ return np.ones((len(texts), dim), dtype=np.float32)
+
+ adapter._embed_texts = fake_embed # type: ignore[method-assign]
+
+ def test_doc_side_counts_raw_text(self) -> None:
+ # No doc_template -> the posted text == the raw item text -> words + 2.
+ adapter = self._adapter()
+ self._stub_embed(adapter)
+ items = [Item(text="alpha beta"), Item(text="one two three")]
+ out = adapter.encode(items, ["dense"], is_query=False)
+ assert out.extra["input_token_counts"] == [4, 5]
+
+ def test_query_side_counts_post_template(self) -> None:
+ # Qwen3-Embedding-4B applies an Instruct/Query template to queries; the
+ # count must reflect the FORMATTED string that is actually sent, not the
+ # raw text (that is exactly the metering gap this fixes).
+ adapter = self._adapter(
+ query_template="Instruct: {instruction}\nQuery: {text}",
+ default_instruction="find it",
+ )
+ self._stub_embed(adapter)
+ items = [Item(text="alpha beta")]
+ formatted = adapter._format_texts(items, None, is_query=True)
+ out = adapter.encode(items, ["dense"], is_query=True)
+ assert out.extra["input_token_counts"] == [len(formatted[0].split()) + 2]
+ # Strictly MORE than the raw-text count — the template adds tokens.
+ assert out.extra["input_token_counts"][0] > len(["alpha", "beta"]) + 2
+
+ def test_empty_items_bill_zero_and_scatter(self) -> None:
+ # Whitespace-only items take the zero-vector fallback (not posted) and
+ # must bill 0 while the sent items keep their exact counts, aligned 1:1.
+ adapter = self._adapter()
+ self._stub_embed(adapter)
+ items = [Item(text="alpha beta"), Item(text=" "), Item(text="x y z")]
+ out = adapter.encode(items, ["dense"], is_query=False)
+ assert out.extra["input_token_counts"] == [4, 0, 5]
+
+ def test_all_empty_bills_zero(self) -> None:
+ # All-empty batch short-circuits to zero vectors with no POST -> all 0.
+ adapter = self._adapter()
+ items = [Item(text=""), Item(text=" ")]
+ out = adapter.encode(items, ["dense"], is_query=False)
+ assert out.extra["input_token_counts"] == [0, 0]
+
+ def test_truncation_cap_applied(self) -> None:
+ # A text longer than max_seq_length counts at the cap (sglang truncates
+ # at --context-length), not the untruncated length.
+ adapter = self._adapter(max_seq_length=4)
+ self._stub_embed(adapter)
+ out = adapter.encode([Item(text="one two three four five")], ["dense"], is_query=False)
+ # 5 words + 2 specials = 7, capped at 4.
+ assert out.extra["input_token_counts"] == [4]
+
+ def test_no_tokenizer_leaves_counts_unstamped(self) -> None:
+ # A tokenizer load failure degrades to the meter's reserve estimate
+ # (no counts) rather than billing an approximation or raising.
+ adapter = self._adapter()
+ adapter._metering_tokenizer_obj = None # simulate load failure
+ self._stub_embed(adapter)
+ out = adapter.encode([Item(text="alpha beta")], ["dense"], is_query=False)
+ assert "input_token_counts" not in out.extra
+
+
+# ---------------------------------------------------------------------------
+# QueueExecutor.process_encode_batch — encode seam stamps images
+# ---------------------------------------------------------------------------
+
+
+def _encode_registry(adapter: BaseAdapter) -> MagicMock:
+ reg = MagicMock()
+ reg.device = "cpu"
+ reg.get_config.return_value = MagicMock()
+ reg.get.return_value = adapter
+ return reg
+
+
+def _encode_request(items: list[dict[str, Any]]) -> ProcessEncodeBatchRequest:
+ return ProcessEncodeBatchRequest(
+ model_id="test/model",
+ items=[
+ EncodeBatchItem(
+ work_item_id=f"req-1.{i}",
+ request_id="req-1",
+ item_index=i,
+ total_items=len(items),
+ timestamp=time.time(),
+ item=item,
+ )
+ for i, item in enumerate(items)
+ ],
+ )
+
+
+class TestEncodeSeamImages:
+ @pytest.mark.asyncio
+ async def test_image_encode_stamps_images(self) -> None:
+ adapter = _FakeVisionEncodeAdapter()
+ reg = _encode_registry(adapter)
+ ex = QueueExecutor(reg)
+
+ # Image path: the pipeline records no token counts (image input).
+ async def fake_run_encode(**kwargs: Any) -> tuple[list[dict[str, Any]], RequestTiming]:
+ return [{"dense": [0.0]} for _ in kwargs["items"]], RequestTiming()
+
+ with patch.object(EncodePipeline, "run_encode", new=AsyncMock(side_effect=fake_run_encode)):
+ outcome = await ex.process_encode_batch(_encode_request([{"images": [_img(), _img()]}]))
+
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_and_ack"
+ assert o.units is not None
+ assert o.units.images == 2 # two images in the item
+ assert o.units.input_tokens is None # image path bills no tokens
+
+ @pytest.mark.asyncio
+ async def test_text_encode_stamps_tokens_not_images(self) -> None:
+ adapter = _FakeVisionEncodeAdapter(tokenizer=_FakeTokenizer())
+ reg = _encode_registry(adapter)
+ ex = QueueExecutor(reg)
+
+ async def fake_run_encode(**kwargs: Any) -> tuple[list[dict[str, Any]], RequestTiming]:
+ timing = RequestTiming()
+ timing.input_token_counts = [4] # pipeline recorded a real token count
+ return [{"dense": [0.0]} for _ in kwargs["items"]], timing
+
+ with patch.object(EncodePipeline, "run_encode", new=AsyncMock(side_effect=fake_run_encode)):
+ outcome = await ex.process_encode_batch(_encode_request([{"text": "alpha beta"}]))
+
+ o = outcome.outcomes[0]
+ assert o.units is not None
+ assert o.units.input_tokens == 4
+ assert o.units.images is None # text-only item never emits images=0
+
+ @pytest.mark.asyncio
+ async def test_no_units_when_neither_dimension_present(self) -> None:
+ # A vision adapter with no tokenizer on a text item (no token count) and
+ # no images leaves units unset -> the meter falls back to the reserve.
+ adapter = _FakeVisionEncodeAdapter()
+ reg = _encode_registry(adapter)
+ ex = QueueExecutor(reg)
+
+ async def fake_run_encode(**kwargs: Any) -> tuple[list[dict[str, Any]], RequestTiming]:
+ return [{"dense": [0.0]} for _ in kwargs["items"]], RequestTiming()
+
+ with patch.object(EncodePipeline, "run_encode", new=AsyncMock(side_effect=fake_run_encode)):
+ outcome = await ex.process_encode_batch(_encode_request([{"text": "alpha beta"}]))
+
+ assert outcome.outcomes[0].units is None
+
+
+# ---------------------------------------------------------------------------
+# QueueExecutor.process_extract_batch — extract seam stamps images
+# ---------------------------------------------------------------------------
+
+
+def _extract_worker(extract_output: ExtractOutput) -> AsyncMock:
+ worker = AsyncMock()
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_result(WorkerResult(output=extract_output, timing=RequestTiming()))
+ worker.submit_extract_preformed_batch = AsyncMock(return_value=[fut])
+ return worker
+
+
+def _extract_registry(adapter: BaseAdapter, worker: AsyncMock) -> MagicMock:
+ reg = MagicMock()
+ reg.device = "cpu"
+ reg.get_config.return_value = MagicMock()
+ reg.get.return_value = adapter
+ reg.start_worker = AsyncMock(return_value=worker)
+ return reg
+
+
+def _extract_request(item: dict[str, Any]) -> ProcessExtractBatchRequest:
+ return ProcessExtractBatchRequest(
+ model_id="test/model",
+ items=[
+ ExtractBatchItem(
+ work_item_id="req-1.0",
+ request_id="req-1",
+ item_index=0,
+ total_items=1,
+ timestamp=time.time(),
+ item=item,
+ )
+ ],
+ )
+
+
+class TestExtractSeamImages:
+ @pytest.mark.asyncio
+ async def test_florence2_image_extract_stamps_images(self) -> None:
+ adapter = _FakeVisionExtractAdapter()
+ # Florence-2 surfaces no input_token_counts on its ExtractOutput.
+ extract_output = ExtractOutput(entities=[[{"text": "a red circle", "label": "caption", "score": 1.0}]])
+ reg = _extract_registry(adapter, _extract_worker(extract_output))
+ ex = QueueExecutor(reg)
+
+ outcome = await ex.process_extract_batch(_extract_request({"images": [_img()]}))
+
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_and_ack"
+ assert o.units is not None
+ assert o.units.images == 1
+ assert o.units.input_tokens is None # no tokenizer count on the VLM path
+
+ @pytest.mark.asyncio
+ async def test_text_extract_keeps_tokens_no_images(self) -> None:
+ # Regression: GLiNER-style text extract still bills per token and emits
+ # no images (the image fold is a pure no-op for text-only docs).
+ adapter = _FakeTextExtractAdapter()
+ extract_output = ExtractOutput(
+ entities=[[{"text": "Alice", "label": "person", "score": 0.99, "start": 0, "end": 5}]],
+ input_token_counts=[6],
+ )
+ reg = _extract_registry(adapter, _extract_worker(extract_output))
+ ex = QueueExecutor(reg)
+
+ outcome = await ex.process_extract_batch(_extract_request({"text": "Alice works at Acme."}))
+
+ o = outcome.outcomes[0]
+ assert o.units is not None
+ assert o.units.input_tokens == 6
+ assert o.units.images is None
+
+
+# ---------------------------------------------------------------------------
+# QueueExecutor.process_extract_batch — parse/OCR page dimension (§7)
+# ---------------------------------------------------------------------------
+#
+# The canonical parse/OCR billing unit is PAGES ("$ per 1k pages", design §7).
+# Document-model parsers (docling) surface the real page count on
+# ``ExtractOutput.pages``; the extract result seam folds it into
+# ``UnitCounts.pages`` — the third independent §7 dimension alongside tokens
+# and images.
+
+
+class _FakeParseExtractAdapter(BaseAdapter):
+ """Document parser (docling shape): surfaces per-item page counts and no
+ token counts. Input is a document, so it consumes no images.
+ """
+
+ spec = AdapterSpec(inputs=("document", "image"), outputs=("json",), unload_fields=("_model",))
+
+ def __init__(self) -> None:
+ self._model = object()
+ self._device = "cpu"
+
+ def load(self, device: str) -> None: # pragma: no cover - not exercised
+ _ = device
+
+ def extract(self, items: list[Item], **_: Any) -> ExtractOutput: # pragma: no cover - worker mocked
+ return ExtractOutput(entities=[[] for _ in items])
+
+
+class TestExtractSeamPages:
+ @pytest.mark.asyncio
+ async def test_docling_parse_extract_stamps_pages(self) -> None:
+ adapter = _FakeParseExtractAdapter()
+ # Docling surfaces the real page count on ExtractOutput.pages and no
+ # token counts (package-backed parser).
+ extract_output = ExtractOutput(
+ entities=[[]],
+ data=[{"text": "parsed", "markdown": "# parsed", "document": {}}],
+ pages=[7],
+ )
+ reg = _extract_registry(adapter, _extract_worker(extract_output))
+ ex = QueueExecutor(reg)
+
+ outcome = await ex.process_extract_batch(
+ _extract_request({"document": {"data": b"%PDF-1.4 ...", "format": "pdf"}})
+ )
+
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_and_ack"
+ assert o.units is not None
+ assert o.units.pages == 7 # the §7 parse dimension
+ assert o.units.input_tokens is None # package-backed parse bills no tokens
+ assert o.units.images is None # document input consumes no images
+
+ @pytest.mark.asyncio
+ async def test_parse_extract_without_pages_leaves_units_unset(self) -> None:
+ # An all-error parse (0 pages) surfaces no pages → the meter falls back
+ # to its reserve estimate rather than billing zero.
+ adapter = _FakeParseExtractAdapter()
+ extract_output = ExtractOutput(entities=[[]], data=[{"error": "bad pdf"}], pages=None)
+ reg = _extract_registry(adapter, _extract_worker(extract_output))
+ ex = QueueExecutor(reg)
+
+ outcome = await ex.process_extract_batch(_extract_request({"document": {"data": b"garbage", "format": "pdf"}}))
+
+ assert outcome.outcomes[0].units is None
+
+
+# ---------------------------------------------------------------------------
+# CLIP / SigLIP TEXT tower — exact per-item token-count stamp (§7.3)
+# ---------------------------------------------------------------------------
+#
+# The image towers meter per image (``count_input_images``); the TEXT towers
+# tokenize in-process, so they stamp the exact per-item token counts they
+# encoded onto ``EncodeOutput.extra`` (scattered to item positions, 0 for image
+# items, unstamped for a pure-image batch so it stays on the image dimension).
+
+
+class TestVisionTextTokenStamp:
+ def _clip(self) -> CLIPAdapter:
+ adapter = CLIPAdapter(model_name_or_path="stub/clip")
+ adapter._model = object() # type: ignore[assignment]
+ adapter._processor = _FakeProcessor(_FakeTokenizer()) # type: ignore[assignment]
+ adapter._dense_dim = 4
+ adapter._device = "cpu"
+ # Stub the tower forwards so no real weights are needed. The text tower
+ # still derives its per-text counts from the shared base counter over
+ # the processor tokenizer (the real metering path), returning matching
+ # zero vectors; the image tower returns zero vectors.
+ adapter._encode_image_items = lambda items: np.zeros((len(items), 4), dtype=np.float32) # type: ignore[method-assign]
+
+ def fake_encode_texts(texts: list[str]) -> tuple[Any, list[int] | None]:
+ counts = adapter._token_counts_or_none(adapter._processor.tokenizer, list(texts), expected_len=len(texts))
+ return np.zeros((len(texts), 4), dtype=np.float32), counts
+
+ adapter._encode_texts = fake_encode_texts # type: ignore[method-assign]
+ return adapter
+
+ def test_clip_text_encode_stamps_exact_counts(self) -> None:
+ adapter = self._clip()
+ out = adapter.encode([Item(text="alpha beta"), Item(text="one two three")], ["dense"])
+ # _FakeTokenizer: words + 2 specials.
+ assert out.extra["input_token_counts"] == [4, 5]
+
+ def test_clip_mixed_batch_scatters_zero_for_image_items(self) -> None:
+ adapter = self._clip()
+ items = [Item(text="alpha beta"), Item(images=[{"data": b"x"}]), Item(text="one two three")]
+ out = adapter.encode(items, ["dense"])
+ # Text items keep their real counts; the image item contributes 0 text
+ # tokens (it is metered per image instead).
+ assert out.extra["input_token_counts"] == [4, 0, 5]
+
+ def test_clip_pure_image_batch_leaves_extra_unstamped(self) -> None:
+ adapter = self._clip()
+ out = adapter.encode([Item(images=[{"data": b"x"}])], ["dense"])
+ assert "input_token_counts" not in out.extra
+
+ def test_siglip_text_encode_stamps_exact_counts(self) -> None:
+ adapter = SiglipAdapter(model_name_or_path="stub/siglip")
+ adapter._model = object() # type: ignore[assignment]
+ adapter._processor = _FakeProcessor(_FakeTokenizer()) # type: ignore[assignment]
+ adapter._dense_dim = 4
+ adapter._device = "cpu"
+ adapter._backend = "transformers" # type: ignore[assignment]
+
+ # Stub the text forward: real counts come from the shared base counter
+ # over the processor tokenizer; return matching zero vectors.
+ def fake_encode_texts(texts: list[str]) -> tuple[Any, list[int] | None]:
+ counts = adapter._token_counts_or_none(adapter._processor.tokenizer, list(texts), expected_len=len(texts))
+ return np.zeros((len(texts), 4), dtype=np.float32), counts
+
+ adapter._encode_texts = fake_encode_texts # type: ignore[method-assign]
+ out = adapter.encode([Item(text="a b c")], ["dense"])
+ assert out.extra["input_token_counts"] == [5]
diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.py
index 86e33d57c..f73ea2b0f 100644
--- a/packages/sie_server/tests/test_queue_executor.py
+++ b/packages/sie_server/tests/test_queue_executor.py
@@ -2,13 +2,15 @@ from __future__ import annotations
import asyncio
import time
+from contextlib import ExitStack
from unittest.mock import AsyncMock, MagicMock, patch
import msgpack
import numpy as np
import pytest
-from sie_server.config.model import ModelConfig
+from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks
from sie_server.core.inference_output import ExtractOutput, ScoreOutput
+from sie_server.core.registry import ModelRegistry
from sie_server.core.timing import RequestTiming
from sie_server.core.worker.types import WorkerResult
from sie_server.ipc_types import (
@@ -33,6 +35,32 @@ def _make_registry(*, loaded: bool = True, loading: bool = False) -> MagicMock:
return reg
+def _make_config(name: str) -> ModelConfig:
+ return ModelConfig(
+ sie_id=name,
+ package_backed=True,
+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),
+ profiles={
+ "default": ProfileConfig(
+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",
+ max_batch_tokens=8192,
+ )
+ },
+ )
+
+
+async def _wait_until_loaded(registry: ModelRegistry, *model_ids: str, timeout_s: float = 2.0) -> None:
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ if all(registry.is_loaded(model_id) for model_id in model_ids):
+ return
+ await asyncio.sleep(0.01)
+ if all(registry.is_loaded(model_id) for model_id in model_ids):
+ return
+ missing = [model_id for model_id in model_ids if not registry.is_loaded(model_id)]
+ raise AssertionError(f"timed out waiting for models to load: {missing}")
+
+
def _encode_item(
*,
wiid: str = "req-1.0",
@@ -131,6 +159,42 @@ class TestEnsureModelReady:
ex = QueueExecutor(reg)
assert await ex.ensure_model_ready("test/model") == "retry_later"
+ @pytest.mark.asyncio
+ @patch("sie_server.core.model_loader.load_adapter")
+ async def test_concurrent_sidecar_ready_loads_use_distinct_configured_devices(
+ self,
+ mock_load_adapter: MagicMock,
+ ) -> None:
+ """Concurrent sidecar-triggered loads serialize placement through the registry lock."""
+ registry = ModelRegistry(device="cuda", devices=["cuda:0", "cuda:1"])
+ registry.add_config(_make_config("model-a"))
+ registry.add_config(_make_config("model-b"))
+
+ adapters = [MagicMock(), MagicMock()]
+ for adapter in adapters:
+ adapter.aclose_client = None
+ adapter.capabilities.outputs = ["dense"]
+ adapter.memory_footprint.return_value = 1000
+ adapter.requires_main_thread = False
+ mock_load_adapter.side_effect = adapters
+
+ with ExitStack() as stack:
+ for manager in registry.memory_managers.values():
+ stack.enter_context(patch.object(manager, "check_pressure", return_value=False))
+
+ executor = QueueExecutor(registry)
+ states = await asyncio.gather(
+ executor.ensure_model_ready("model-a"),
+ executor.ensure_model_ready("model-b"),
+ )
+ await _wait_until_loaded(registry, "model-a", "model-b")
+
+ assert states == ["loading_started", "loading_started"]
+ assert registry._loaded["model-a"].device == "cuda:0"
+ assert registry._loaded["model-b"].device == "cuda:1"
+ adapters[0].load.assert_called_once_with("cuda:0")
+ adapters[1].load.assert_called_once_with("cuda:1")
+
class TestGetBatchBudget:
"""Per-model batch budget advertised to the Rust queue consumer via
@@ -363,6 +427,121 @@ class TestProcessEncodeBatch:
assert captured["query_template"] == "fast: {text}"
assert "profile" not in captured
+ @pytest.mark.asyncio
+ async def test_profile_default_output_types_applied(self) -> None:
+ """Regression for dade77d64: a profile whose runtime declares an
+ ``output_types`` default must resolve on the managed path exactly as
+ OSS ``api.encode`` does (profile > request > default).
+
+ Mirrors the ``bge-m3:sparse`` synthetic variant — its promoted
+ "default" profile carries ``output_types: [sparse]``. A queued request
+ with NO request-level output_types must reach the engine as
+ ``["sparse"]`` and be served as sparse, not silently fall back to
+ dense-only (the managed path dropped the profile default).
+ """
+ config = ModelConfig.model_validate(
+ {
+ "sie_id": "test/bge-m3:sparse",
+ "hf_id": "test/bge-m3",
+ "inputs": {"text": True},
+ "tasks": {"encode": {"dense": {"dim": 8}, "sparse": {"dim": 250002}}},
+ "max_sequence_length": 512,
+ "profiles": {
+ "default": {
+ "max_batch_tokens": 8192,
+ "adapter_path": "sie_server.adapters.bge_m3_flash:BGEM3FlashAdapter",
+ "adapter_options": {
+ "runtime": {"pooling": "cls", "normalize": True, "output_types": ["sparse"]},
+ },
+ },
+ },
+ }
+ )
+ reg = _make_registry()
+ reg.get_config.return_value = config
+ ex = QueueExecutor(reg)
+
+ observed: list[list[str]] = []
+
+ async def fake_run_encode(**kwargs):
+ observed.append(kwargs["output_types"])
+ sparse = {
+ "sparse": {
+ "indices": np.array([1, 2], dtype=np.int32),
+ "values": np.array([0.5, 0.25], dtype=np.float32),
+ }
+ }
+ return [sparse for _ in kwargs["items"]], RequestTiming()
+
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new=AsyncMock(side_effect=fake_run_encode),
+ ):
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id="test/bge-m3:sparse",
+ items=[_encode_item(options=None)], # no request-level output_types
+ )
+ )
+
+ # Engine received the profile's head, not the ["dense"] fallback...
+ assert observed == [["sparse"]]
+ # ...and the item is served as sparse.
+ assert outcome.outcomes[0].disposition == "publish_and_ack"
+ assert outcome.outcomes[0].raw_output is not None
+ assert outcome.outcomes[0].raw_output.sparse is not None
+
+ @pytest.mark.asyncio
+ async def test_request_output_types_and_base_default_unchanged(self) -> None:
+ """The profile-default fix must not over-reach: with NO profile-level
+ ``output_types`` default, the managed path keeps OSS ``request >
+ default`` — an explicit request output_types is honoured, an absent one
+ falls back to ``["dense"]``.
+ """
+ config = ModelConfig.model_validate(
+ {
+ "sie_id": "test/plain-embedder",
+ "hf_id": "test/plain-embedder",
+ "inputs": {"text": True},
+ "tasks": {"encode": {"dense": {"dim": 8}, "multivector": {"dim": 8}}},
+ "max_sequence_length": 512,
+ "profiles": {
+ "default": {
+ "max_batch_tokens": 8192,
+ "adapter_path": "sie_server.adapters.bge_m3_flash:BGEM3FlashAdapter",
+ "adapter_options": {"runtime": {"pooling": "cls", "normalize": True}},
+ },
+ },
+ }
+ )
+ reg = _make_registry()
+ reg.get_config.return_value = config
+ ex = QueueExecutor(reg)
+
+ observed: list[tuple[str, ...]] = []
+
+ async def fake_run_encode(**kwargs):
+ observed.append(tuple(kwargs["output_types"]))
+ return [{"dense": [0.0]} for _ in kwargs["items"]], RequestTiming()
+
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new=AsyncMock(side_effect=fake_run_encode),
+ ):
+ await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id="test/plain-embedder",
+ items=[
+ # Explicit request output_types -> honoured (not clobbered).
+ _encode_item(wiid="a.0", output_types=["multivector"], item_index=0),
+ # No request output_types -> base ["dense"] default.
+ _encode_item(wiid="b.0", output_types=None, item_index=1),
+ ],
+ )
+ )
+
+ assert sorted(observed) == [("dense",), ("multivector",)]
+
@pytest.mark.asyncio
async def test_model_evicted_naks_all(self) -> None:
reg = _make_registry()
@@ -1021,3 +1200,28 @@ class TestWrapEncodeOutput:
assert mv["token_dims"] == 128
assert mv["num_tokens"] == 7
assert mv["dtype"] == "binary"
+
+ def test_full_width_uint8_dense_stays_uint8(self) -> None:
+ """A full-width uint8 dense vector (NOT bit-packed) must keep the
+ ``uint8`` label — only the shape-based binary check may emit ``binary``,
+ else the SDK would bit-unpack values that were never packed.
+ """
+ from sie_server.queue_executor import _wrap_encode_output
+
+ arr = np.zeros(128, dtype=np.uint8) # full width == dense_dim, not packed
+ wrapped = _wrap_encode_output({"dense": arr}, self._config(dense_dim=128))
+ assert wrapped["dense"]["dims"] == 128
+ assert wrapped["dense"]["dtype"] == "uint8"
+
+ def test_full_width_uint8_multivector_stays_uint8(self) -> None:
+ """A full-width uint8 multivector (shape[1] == mv_dim) is not bit-packed,
+ so it must keep the ``uint8`` label rather than fall through to binary.
+ """
+ from sie_server.queue_executor import _wrap_encode_output
+
+ arr = np.zeros((5, 128), dtype=np.uint8) # full width == mv_dim, not packed
+ wrapped = _wrap_encode_output({"multivector": arr}, self._config(multivector_dim=128))
+ mv = wrapped["multivector"]
+ assert mv["token_dims"] == 128
+ assert mv["num_tokens"] == 5
+ assert mv["dtype"] == "uint8"
diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lock
index 759cbb647..005c46644 100644
--- a/packages/sie_server_sidecar/Cargo.lock
+++ b/packages/sie_server_sidecar/Cargo.lock
@@ -2463,7 +2463,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "sie-server-sidecar"
-version = "0.6.16"
+version = "0.6.17"
dependencies = [
"anyhow",
"async-nats",
diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.toml
index e5e6460b8..905b91457 100644
--- a/packages/sie_server_sidecar/Cargo.toml
+++ b/packages/sie_server_sidecar/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-server-sidecar"
-version = "0.6.16"
+version = "0.6.17"
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/src/backend/adapter_pool.rs b/packages/sie_server_sidecar/src/backend/adapter_pool.rs
new file mode 100644
index 000000000..cd04a0711
--- /dev/null
+++ b/packages/sie_server_sidecar/src/backend/adapter_pool.rs
@@ -0,0 +1,1296 @@
+//! Adapter worker pool backend.
+//!
+//! This backend owns one IPC client per adapter worker child and keeps
+//! model-to-child placement inside the sidecar. The dispatcher still sees a
+//! single [`InferenceBackend`]; routing to a concrete adapter process happens
+//! here on `EnsureModelReady` and is reused for subsequent batches.
+
+use std::collections::{BTreeSet, HashMap, HashSet};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use futures_util::future::join_all;
+use tracing::{debug, info, warn};
+
+use crate::backend::python_ipc::map_ipc_error;
+use crate::backend::{BackendError, InferenceBackend};
+use crate::ipc_client::{IpcClient, IpcError};
+use crate::ipc_types::{
+ ApplyModelConfigRequest, ApplyModelConfigResponse, BatchOutcome, DrainResponse,
+ EnsureModelReadyResponse, GenerateEvent, PingResponse, ProcessEncodeBatchRequest,
+ ProcessExtractBatchRequest, ProcessGenerateRequest, ProcessScoreBatchRequest,
+ ReplaceModelConfigsRequest, ReplaceModelConfigsResponse, RunBatchRequest,
+ SetPinnedModelsResponse, SignalGenerateCancelResponse, WorkerCapabilitiesResponse,
+};
+use crate::metrics::MetricsRegistry;
+
+struct AdapterWorkerChild {
+ index: usize,
+ socket_path: PathBuf,
+ ipc: Arc<IpcClient>,
+ ready: AtomicBool,
+ inflight_batches: AtomicI64,
+ pending_items: AtomicI64,
+ pending_cost: AtomicI64,
+ models: Mutex<HashSet<String>>,
+}
+
+impl AdapterWorkerChild {
+ fn model_count(&self) -> usize {
+ self.models
+ .lock()
+ .expect("adapter worker child model set poisoned")
+ .len()
+ }
+}
+
+/// Shared pool state used by the backend, heartbeat, config fanout, and
+/// generation cancel fanout.
+pub struct AdapterWorkerPool {
+ children: Vec<Arc<AdapterWorkerChild>>,
+ placements: Mutex<HashMap<String, usize>>,
+ pinned_models: Mutex<HashSet<String>>,
+ pinned_assignment_revision: AtomicU64,
+ config_quarantined: AtomicBool,
+ config_fanout_generation: AtomicU64,
+ metrics: Arc<MetricsRegistry>,
+}
+
+impl AdapterWorkerPool {
+ pub fn new(
+ socket_paths: &[PathBuf],
+ ipc_pool_size: usize,
+ ipc_request_timeout_s: u64,
+ model_ready_timeout_s: u64,
+ metrics: Arc<MetricsRegistry>,
+ ) -> Arc<Self> {
+ let mut children = Vec::with_capacity(socket_paths.len().max(1));
+ for (index, socket_path) in socket_paths.iter().enumerate() {
+ let ipc = Arc::new(
+ IpcClient::new_pool(socket_path, ipc_pool_size)
+ .with_timeout(Duration::from_secs(ipc_request_timeout_s))
+ .with_model_ready_timeout(Duration::from_secs(model_ready_timeout_s))
+ .with_metrics(Arc::clone(&metrics)),
+ );
+ children.push(Arc::new(AdapterWorkerChild {
+ index,
+ socket_path: socket_path.clone(),
+ ipc,
+ ready: AtomicBool::new(false),
+ inflight_batches: AtomicI64::new(0),
+ pending_items: AtomicI64::new(0),
+ pending_cost: AtomicI64::new(0),
+ models: Mutex::new(HashSet::new()),
+ }));
+ }
+ assert!(
+ !children.is_empty(),
+ "AdapterWorkerPool requires at least one IPC socket"
+ );
+ let pool = Arc::new(Self {
+ children,
+ placements: Mutex::new(HashMap::new()),
+ pinned_models: Mutex::new(HashSet::new()),
+ pinned_assignment_revision: AtomicU64::new(0),
+ config_quarantined: AtomicBool::new(false),
+ config_fanout_generation: AtomicU64::new(0),
+ metrics,
+ });
+ pool.metrics
+ .worker_gpu_slots_total
+ .set(pool.children.len() as i64);
+ pool.metrics.worker_gpu_slots_ready.set(0);
+ pool.refresh_all_child_metrics();
+ pool
+ }
+
+ pub fn primary_ipc(&self) -> Arc<IpcClient> {
+ Arc::clone(&self.children[0].ipc)
+ }
+
+ pub fn child_count(&self) -> usize {
+ self.children.len()
+ }
+
+ pub fn pinned_assignment_revision(&self) -> u64 {
+ self.pinned_assignment_revision.load(Ordering::Acquire)
+ }
+
+ pub fn ready_child_count(&self) -> usize {
+ self.children
+ .iter()
+ .filter(|child| child.ready.load(Ordering::Acquire))
+ .count()
+ }
+
+ pub async fn ping_all(
+ &self,
+ timestamp_ms: f64,
+ ) -> Vec<(usize, Result<PingResponse, IpcError>)> {
+ let out = join_all(self.children.iter().map(|child| async move {
+ let result = child.ipc.ping(timestamp_ms).await;
+ if result.as_ref().is_ok_and(|resp| resp.ready) {
+ self.mark_child_ready_from_health_success(child);
+ } else {
+ child.ready.store(false, Ordering::Release);
+ }
+ (child.index, result)
+ }))
+ .await;
+ self.metrics
+ .worker_gpu_slots_ready
+ .set(self.ready_child_count() as i64);
+ self.refresh_all_child_metrics();
+ out
+ }
+
+ pub async fn worker_capabilities(&self) -> Result<WorkerCapabilitiesResponse, IpcError> {
+ let mut combined = WorkerCapabilitiesResponse::default();
+ let mut any_success = false;
+ let mut last_err = None;
+ for child in &self.children {
+ match child.ipc.worker_capabilities().await {
+ Ok(resp) => {
+ any_success = true;
+ self.mark_child_ready_from_health_success(child);
+ self.refresh_child_metrics(child);
+ combined.has_generation_models |= resp.has_generation_models;
+ for model in resp.generation_models {
+ if !combined.generation_models.contains(&model) {
+ combined.generation_models.push(model);
+ }
+ }
+ }
+ Err(e) => {
+ child.ready.store(false, Ordering::Release);
+ self.refresh_child_metrics(child);
+ last_err = Some(e);
+ }
+ }
+ }
+ self.metrics
+ .worker_gpu_slots_ready
+ .set(self.ready_child_count() as i64);
+ if any_success {
+ combined.generation_models.sort();
+ Ok(combined)
+ } else {
+ Err(last_err.expect("last_err set when every capabilities probe failed"))
+ }
+ }
+
+ pub async fn apply_model_config(
+ &self,
+ req: ApplyModelConfigRequest,
+ ) -> Result<ApplyModelConfigResponse, IpcError> {
+ let generation = self.begin_config_fanout("apply_model_config");
+ let mut combined = None;
+ let mut last_err = None;
+ for child in &self.children {
+ match child.ipc.apply_model_config(req.clone()).await {
+ Ok(resp) => {
+ if !resp.applied {
+ warn!(
+ child_index = child.index,
+ "adapter-worker-pool: child rejected config apply"
+ );
+ }
+ self.refresh_child_metrics(child);
+ merge_apply_model_config_response(&mut combined, resp);
+ }
+ Err(e) => {
+ child.ready.store(false, Ordering::Release);
+ self.refresh_child_metrics(child);
+ last_err = Some(e);
+ }
+ }
+ }
+ if let Some(e) = last_err {
+ self.quarantine_config_fanout("apply_model_config IPC failure", generation);
+ return Err(e);
+ }
+ let resp = combined.expect("at least one child exists");
+ if resp.applied {
+ self.clear_config_quarantine_after_success("apply_model_config", generation);
+ } else {
+ self.quarantine_config_fanout("apply_model_config rejected or diverged", generation);
+ }
+ Ok(resp)
+ }
+
+ pub async fn replace_model_configs(
+ &self,
+ req: ReplaceModelConfigsRequest,
+ ) -> Result<ReplaceModelConfigsResponse, IpcError> {
+ let generation = self.begin_config_fanout("replace_model_configs");
+ let mut combined = None;
+ let mut last_err = None;
+ for child in &self.children {
+ match child.ipc.replace_model_configs(req.clone()).await {
+ Ok(resp) => {
+ if !resp.applied {
+ warn!(
+ child_index = child.index,
+ "adapter-worker-pool: child rejected config replace"
+ );
+ }
+ self.refresh_child_metrics(child);
+ merge_replace_model_configs_response(&mut combined, resp);
+ }
+ Err(e) => {
+ child.ready.store(false, Ordering::Release);
+ self.refresh_child_metrics(child);
+ last_err = Some(e);
+ }
+ }
+ }
+ if let Some(e) = last_err {
+ self.quarantine_config_fanout("replace_model_configs IPC failure", generation);
+ return Err(e);
+ }
+ let resp = combined.expect("at least one child exists");
+ if resp.applied {
+ self.clear_config_quarantine_after_success("replace_model_configs", generation);
+ } else {
+ self.quarantine_config_fanout("replace_model_configs rejected or diverged", generation);
+ }
+ Ok(resp)
+ }
+
+ pub async fn signal_generate_cancel(
+ &self,
+ request_id: String,
+ ) -> Result<SignalGenerateCancelResponse, IpcError> {
+ let mut matched = false;
+ let mut any_success = false;
+ let mut last_err = None;
+ for child in &self.children {
+ match child.ipc.signal_generate_cancel(request_id.clone()).await {
+ Ok(resp) => {
+ any_success = true;
+ matched |= resp.matched;
+ }
+ Err(e) => {
+ self.mark_child_call_failed(child);
+ last_err = Some(e);
+ }
+ }
+ }
+ if any_success {
+ Ok(SignalGenerateCancelResponse { matched })
+ } else {
+ Err(last_err.expect("last_err set when every cancel fanout failed"))
+ }
+ }
+
+ pub async fn set_pinned_models(
+ &self,
+ models: Vec<String>,
+ ) -> Result<SetPinnedModelsResponse, IpcError> {
+ let models = normalize_pinned_models(models);
+ self.update_pinned_model_set(&models);
+ let models_by_child = self.pinned_models_by_child(models);
+ let mut applied = true;
+ let mut pinned_count = 0u32;
+ for child in &self.children {
+ let child_models = models_by_child
+ .get(child.index)
+ .cloned()
+ .unwrap_or_default();
+ match child.ipc.set_pinned_models(child_models).await {
+ Ok(resp) => {
+ self.mark_child_ready_from_health_success(child);
+ self.refresh_child_metrics(child);
+ applied &= resp.applied;
+ pinned_count = pinned_count.saturating_add(resp.pinned_count);
+ }
+ Err(e) => {
+ self.mark_child_call_failed(child);
+ return Err(e);
+ }
+ }
+ }
+ self.metrics
+ .worker_gpu_slots_ready
+ .set(self.ready_child_count() as i64);
+ Ok(SetPinnedModelsResponse {
+ applied,
+ pinned_count,
+ })
+ }
+
+ fn pinned_models_by_child(&self, models: Vec<String>) -> Vec<Vec<String>> {
+ let mut assigned = vec![BTreeSet::new(); self.children.len()];
+ for model in normalize_pinned_models(models) {
+ let child = self.child_for_model(&model);
+ assigned[child.index].insert(model);
+ }
+ assigned
+ .into_iter()
+ .map(|models| models.into_iter().collect())
+ .collect()
+ }
+
+ pub async fn process_generate<F, Fut>(
+ &self,
+ req: ProcessGenerateRequest,
+ on_event: F,
+ ) -> Result<(), IpcError>
+ where
+ F: FnMut(GenerateEvent) -> Fut,
+ Fut: std::future::Future<Output = Result<(), IpcError>>,
+ {
+ self.ensure_not_config_quarantined()?;
+ let model_id = req.model_id.clone();
+ let child = self.child_for_model(&model_id);
+ child.inflight_batches.fetch_add(1, Ordering::AcqRel);
+ self.refresh_child_metrics(&child);
+ let result = child.ipc.process_generate(req, on_event).await;
+ child.inflight_batches.fetch_sub(1, Ordering::AcqRel);
+ self.refresh_child_metrics(&child);
+ match &result {
+ Ok(()) => self.mark_child_call_succeeded(&child),
+ Err(_) => {
+ self.mark_child_call_failed(&child);
+ self.clear_model_if_on_child(&model_id, child.index);
+ }
+ }
+ result
+ }
+
+ pub fn record_model_pending_enqueue(&self, model_id: &str, cost: u64) -> usize {
+ let child = self.child_for_model(model_id);
+ child.pending_items.fetch_add(1, Ordering::AcqRel);
+ child
+ .pending_cost
+ .fetch_add(clamp_u64_to_i64(cost), Ordering::AcqRel);
+ self.refresh_child_metrics(&child);
+ child.index
+ }
+
+ pub fn record_child_pending_dequeue(&self, child_index: usize, item_count: usize, cost: u64) {
+ let Some(child) = self.children.get(child_index).cloned() else {
+ warn!(
+ child_index,
+ "adapter-worker-pool: ignoring pending dequeue for unknown child"
+ );
+ return;
+ };
+ atomic_add_floor_zero(&child.pending_items, -(item_count as i64));
+ atomic_add_floor_zero(&child.pending_cost, -clamp_u64_to_i64(cost));
+ self.refresh_child_metrics(&child);
+ }
+
+ pub fn record_model_pending_dequeue(&self, model_id: &str, item_count: usize, cost: u64) {
+ let index = self
+ .placements
+ .lock()
+ .expect("adapter worker placement map poisoned")
+ .get(model_id)
+ .copied();
+ let Some(index) = index else {
+ return;
+ };
+ let child = Arc::clone(&self.children[index]);
+ atomic_add_floor_zero(&child.pending_items, -(item_count as i64));
+ atomic_add_floor_zero(&child.pending_cost, -clamp_u64_to_i64(cost));
+ self.refresh_child_metrics(&child);
+ }
+
+ pub async fn drain_all(
+ &self,
+ deadline_ms: u64,
+ ) -> Vec<(usize, Result<DrainResponse, IpcError>)> {
+ let mut out = Vec::with_capacity(self.children.len());
+ for child in &self.children {
+ out.push((child.index, child.ipc.drain(deadline_ms).await));
+ }
+ out
+ }
+
+ fn child_for_model(&self, model_id: &str) -> Arc<AdapterWorkerChild> {
+ let mut placements = self
+ .placements
+ .lock()
+ .expect("adapter worker placement map poisoned");
+ if let Some(&index) = placements.get(model_id) {
+ let child = Arc::clone(&self.children[index]);
+ if child.ready.load(Ordering::Acquire) || self.ready_child_count() == 0 {
+ return child;
+ }
+ placements.remove(model_id);
+ self.mark_pinned_assignment_changed_if_needed(model_id);
+ child
+ .models
+ .lock()
+ .expect("adapter worker child model set poisoned")
+ .remove(model_id);
+ self.refresh_child_metrics(&child);
+ }
+
+ let index = self.choose_child_index();
+ placements.insert(model_id.to_string(), index);
+ self.mark_pinned_assignment_changed_if_needed(model_id);
+ let child = Arc::clone(&self.children[index]);
+ child
+ .models
+ .lock()
+ .expect("adapter worker child model set poisoned")
+ .insert(model_id.to_string());
+ self.refresh_child_metrics(&child);
+ info!(
+ model = %model_id,
+ child_index = index,
+ socket = %child.socket_path.display(),
+ "adapter-worker-pool: model placed on child"
+ );
+ child
+ }
+
+ fn update_pinned_model_set(&self, models: &[String]) {
+ let next: HashSet<String> = models.iter().cloned().collect();
+ let mut pinned_models = self
+ .pinned_models
+ .lock()
+ .expect("adapter worker pinned model set poisoned");
+ if *pinned_models != next {
+ *pinned_models = next;
+ self.pinned_assignment_revision
+ .fetch_add(1, Ordering::AcqRel);
+ }
+ }
+
+ fn mark_pinned_assignment_changed_if_needed(&self, model_id: &str) {
+ let pinned = self
+ .pinned_models
+ .lock()
+ .expect("adapter worker pinned model set poisoned")
+ .contains(model_id);
+ if pinned {
+ self.pinned_assignment_revision
+ .fetch_add(1, Ordering::AcqRel);
+ }
+ }
+
+ fn choose_child_index(&self) -> usize {
+ let any_ready = self.ready_child_count() > 0;
+ self.children
+ .iter()
+ .min_by_key(|child| {
+ let unready_penalty =
+ usize::from(any_ready && !child.ready.load(Ordering::Acquire));
+ (
+ unready_penalty,
+ child.model_count(),
+ child.pending_cost.load(Ordering::Relaxed),
+ child.pending_items.load(Ordering::Relaxed),
+ child.inflight_batches.load(Ordering::Relaxed),
+ child.index,
+ )
+ })
+ .expect("at least one child exists")
+ .index
+ }
+
+ fn clear_model_if_on_child(&self, model_id: &str, child_index: usize) {
+ let mut placements = self
+ .placements
+ .lock()
+ .expect("adapter worker placement map poisoned");
+ if placements.get(model_id).copied() == Some(child_index) {
+ placements.remove(model_id);
+ self.mark_pinned_assignment_changed_if_needed(model_id);
+ self.children[child_index]
+ .models
+ .lock()
+ .expect("adapter worker child model set poisoned")
+ .remove(model_id);
+ self.refresh_child_metrics(&self.children[child_index]);
+ debug!(
+ model = %model_id,
+ child_index,
+ "adapter-worker-pool: placement cleared after child failure"
+ );
+ }
+ }
+
+ fn mark_child_call_failed(&self, child: &AdapterWorkerChild) {
+ child.ready.store(false, Ordering::Release);
+ self.metrics
+ .worker_gpu_slots_ready
+ .set(self.ready_child_count() as i64);
+ self.refresh_child_metrics(child);
+ }
+
+ fn mark_child_call_succeeded(&self, child: &AdapterWorkerChild) {
+ self.mark_child_ready_from_health_success(child);
+ self.metrics
+ .worker_gpu_slots_ready
+ .set(self.ready_child_count() as i64);
+ self.refresh_child_metrics(child);
+ }
+
+ fn mark_child_ready_from_health_success(&self, child: &AdapterWorkerChild) {
+ if self.config_quarantined.load(Ordering::Acquire) {
+ child.ready.store(false, Ordering::Release);
+ return;
+ }
+ child.ready.store(true, Ordering::Release);
+ if self.config_quarantined.load(Ordering::Acquire) {
+ child.ready.store(false, Ordering::Release);
+ }
+ }
+
+ fn ensure_not_config_quarantined(&self) -> Result<(), IpcError> {
+ if self.config_quarantined.load(Ordering::Acquire) {
+ Err(IpcError::Server(
+ "adapter worker pool config fanout incomplete; pool quarantined".to_string(),
+ ))
+ } else {
+ Ok(())
+ }
+ }
+
+ fn begin_config_fanout(&self, operation: &'static str) -> u64 {
+ let generation = self.config_fanout_generation.fetch_add(1, Ordering::AcqRel) + 1;
+ self.config_quarantined.store(true, Ordering::Release);
+ for child in &self.children {
+ child.ready.store(false, Ordering::Release);
+ self.refresh_child_metrics(child);
+ }
+ self.metrics.worker_gpu_slots_ready.set(0);
+ debug!(
+ operation,
+ generation,
+ "adapter-worker-pool: config fanout started; children temporarily quarantined"
+ );
+ generation
+ }
+
+ fn quarantine_config_fanout(&self, reason: &'static str, generation: u64) {
+ if self.config_fanout_generation.load(Ordering::Acquire) != generation {
+ debug!(
+ reason,
+ generation, "adapter-worker-pool: ignoring stale config fanout failure"
+ );
+ return;
+ }
+ let was_quarantined = self.config_quarantined.swap(true, Ordering::AcqRel);
+ if was_quarantined {
+ warn!(
+ reason,
+ "adapter-worker-pool: keeping all children quarantined after config fanout failure"
+ );
+ } else {
+ warn!(
+ reason,
+ "adapter-worker-pool: quarantining all children after config fanout failure"
+ );
+ }
+ for child in &self.children {
+ child.ready.store(false, Ordering::Release);
+ self.refresh_child_metrics(child);
+ }
+ self.metrics.worker_gpu_slots_ready.set(0);
+ }
+
+ fn clear_config_quarantine_after_success(&self, operation: &'static str, generation: u64) {
+ if self.config_fanout_generation.load(Ordering::Acquire) != generation {
+ debug!(
+ operation,
+ generation, "adapter-worker-pool: ignoring stale config fanout success"
+ );
+ return;
+ }
+ let was_quarantined = self.config_quarantined.swap(false, Ordering::AcqRel);
+ if was_quarantined {
+ info!(
+ operation,
+ "adapter-worker-pool: config fanout succeeded; clearing child quarantine"
+ );
+ }
+ for child in &self.children {
+ child.ready.store(true, Ordering::Release);
+ self.refresh_child_metrics(child);
+ }
+ self.metrics
+ .worker_gpu_slots_ready
+ .set(self.ready_child_count() as i64);
+ }
+
+ fn refresh_all_child_metrics(&self) {
+ for child in &self.children {
+ self.refresh_child_metrics(child);
+ }
+ }
+
+ fn refresh_child_metrics(&self, child: &AdapterWorkerChild) {
+ let child_label = child.index.to_string();
+ let labels = &[child_label.as_str()];
+ self.metrics
+ .worker_child_ready
+ .with_label_values(labels)
+ .set(i64::from(child.ready.load(Ordering::Acquire)));
+ self.metrics
+ .worker_child_models
+ .with_label_values(labels)
+ .set(child.model_count() as i64);
+ self.metrics
+ .worker_child_queue_depth
+ .with_label_values(labels)
+ .set(child.pending_items.load(Ordering::Acquire));
+ self.metrics
+ .worker_child_pending_cost
+ .with_label_values(labels)
+ .set(child.pending_cost.load(Ordering::Acquire));
+ self.metrics
+ .worker_child_inflight_batches
+ .with_label_values(labels)
+ .set(child.inflight_batches.load(Ordering::Acquire));
+ }
+
+ async fn run_child_batch<F, Fut>(
+ &self,
+ model_id: String,
+ child: Arc<AdapterWorkerChild>,
+ call: F,
+ ) -> Result<BatchOutcome, IpcError>
+ where
+ F: FnOnce(Arc<IpcClient>) -> Fut,
+ Fut: std::future::Future<Output = Result<BatchOutcome, IpcError>>,
+ {
+ self.ensure_not_config_quarantined()?;
+ child.inflight_batches.fetch_add(1, Ordering::AcqRel);
+ self.refresh_child_metrics(&child);
+ let result = call(Arc::clone(&child.ipc)).await;
+ child.inflight_batches.fetch_sub(1, Ordering::AcqRel);
+ self.refresh_child_metrics(&child);
+ match &result {
+ Ok(_) => self.mark_child_call_succeeded(&child),
+ Err(_) => {
+ self.mark_child_call_failed(&child);
+ self.clear_model_if_on_child(&model_id, child.index);
+ }
+ }
+ result
+ }
+
+ pub async fn ensure_model_ready_on_placed_child(
+ &self,
+ model_id: &str,
+ ) -> Result<EnsureModelReadyResponse, IpcError> {
+ self.ensure_not_config_quarantined()?;
+ let child = self.child_for_model(model_id);
+ match child.ipc.ensure_model_ready(model_id).await {
+ Ok(resp) => {
+ self.mark_child_call_succeeded(&child);
+ Ok(resp)
+ }
+ Err(e) => {
+ self.mark_child_call_failed(&child);
+ self.clear_model_if_on_child(model_id, child.index);
+ Err(e)
+ }
+ }
+ }
+}
+
+fn clamp_u64_to_i64(value: u64) -> i64 {
+ i64::try_from(value).unwrap_or(i64::MAX)
+}
+
+fn atomic_add_floor_zero(value: &AtomicI64, delta: i64) {
+ if delta >= 0 {
+ value.fetch_add(delta, Ordering::AcqRel);
+ return;
+ }
+ let _ = value.fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
+ Some(current.saturating_add(delta).max(0))
+ });
+}
+
+fn normalize_pinned_models(models: Vec<String>) -> Vec<String> {
+ models
+ .into_iter()
+ .map(|model| model.trim().to_string())
+ .filter(|model| !model.is_empty())
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect()
+}
+
+fn merge_apply_model_config_response(
+ combined: &mut Option<ApplyModelConfigResponse>,
+ resp: ApplyModelConfigResponse,
+) {
+ let Some(existing) = combined.as_mut() else {
+ *combined = Some(resp);
+ return;
+ };
+ existing.applied &= resp.applied;
+ merge_bundle_hash(
+ &mut existing.applied,
+ &mut existing.bundle_config_hash,
+ resp.bundle_config_hash,
+ );
+ existing.config_version = existing.config_version.max(resp.config_version);
+}
+
+fn merge_replace_model_configs_response(
+ combined: &mut Option<ReplaceModelConfigsResponse>,
+ resp: ReplaceModelConfigsResponse,
+) {
+ let Some(existing) = combined.as_mut() else {
+ *combined = Some(resp);
+ return;
+ };
+ existing.applied &= resp.applied;
+ merge_bundle_hash(
+ &mut existing.applied,
+ &mut existing.bundle_config_hash,
+ resp.bundle_config_hash,
+ );
+ existing.config_version = existing.config_version.max(resp.config_version);
+
+ let mut existing_models = existing.applied_models.clone();
+ let mut new_models = resp.applied_models;
+ existing_models.sort();
+ new_models.sort();
+ if existing_models != new_models {
+ existing.applied = false;
+ existing.applied_models = existing_models
+ .into_iter()
+ .chain(new_models)
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+ existing.applied_models.sort();
+ }
+}
+
+fn merge_bundle_hash(applied: &mut bool, existing_hash: &mut String, next_hash: String) {
+ if existing_hash.is_empty() {
+ *existing_hash = next_hash;
+ } else if !next_hash.is_empty() && *existing_hash != next_hash {
+ *applied = false;
+ }
+}
+
+#[async_trait]
+impl InferenceBackend for AdapterWorkerPool {
+ fn name(&self) -> &'static str {
+ "adapter-worker-pool"
+ }
+
+ fn supports(&self, _model_id: &str) -> bool {
+ true
+ }
+
+ async fn ensure_model_ready(
+ &self,
+ model_id: &str,
+ ) -> Result<EnsureModelReadyResponse, BackendError> {
+ self.ensure_model_ready_on_placed_child(model_id)
+ .await
+ .map_err(map_ipc_error)
+ }
+
+ async fn process_encode_batch(
+ &self,
+ req: ProcessEncodeBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ let model_id = req.model_id.clone();
+ let child = self.child_for_model(&model_id);
+ self.run_child_batch(model_id, child, |ipc| async move {
+ ipc.process_encode_batch(req).await
+ })
+ .await
+ .map_err(map_ipc_error)
+ }
+
+ async fn process_score_batch(
+ &self,
+ req: ProcessScoreBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ let model_id = req.model_id.clone();
+ let child = self.child_for_model(&model_id);
+ self.run_child_batch(model_id, child, |ipc| async move {
+ ipc.process_score_batch(req).await
+ })
+ .await
+ .map_err(map_ipc_error)
+ }
+
+ async fn process_extract_batch(
+ &self,
+ req: ProcessExtractBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ let model_id = req.model_id.clone();
+ let child = self.child_for_model(&model_id);
+ self.run_child_batch(model_id, child, |ipc| async move {
+ ipc.process_extract_batch(req).await
+ })
+ .await
+ .map_err(map_ipc_error)
+ }
+
+ async fn run_batch(&self, req: RunBatchRequest) -> Result<BatchOutcome, BackendError> {
+ let model_id = req.model_id.clone();
+ let child = self.child_for_model(&model_id);
+ self.run_child_batch(
+ model_id,
+ child,
+ |ipc| async move { ipc.run_batch(req).await },
+ )
+ .await
+ .map_err(map_ipc_error)
+ }
+
+ async fn drain(&self, deadline_ms: u64) {
+ for (index, result) in self.drain_all(deadline_ms).await {
+ match result {
+ Ok(resp) => debug!(
+ child_index = index,
+ acknowledged = resp.acknowledged,
+ "adapter-worker-pool drain acknowledged"
+ ),
+ Err(e) => warn!(
+ child_index = index,
+ error = %e,
+ "adapter-worker-pool drain RPC failed"
+ ),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::net::UnixListener;
+
+ async fn spawn_cancel_ok(path: PathBuf) -> tokio::task::JoinHandle<()> {
+ let listener = UnixListener::bind(path).expect("bind cancel test socket");
+ tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(pair) => pair,
+ Err(_) => return,
+ };
+ tokio::spawn(async move {
+ loop {
+ let mut len_buf = [0_u8; 4];
+ if sock.read_exact(&mut len_buf).await.is_err() {
+ return;
+ }
+ let n = u32::from_be_bytes(len_buf) as usize;
+ let mut buf = vec![0_u8; n];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ let resp = crate::ipc_types::ResponseEnvelope {
+ version: crate::ipc_types::IPC_VERSION,
+ request_id: "req-cancel".to_string(),
+ ok: true,
+ body: Some(SignalGenerateCancelResponse { matched: true }),
+ error: None,
+ };
+ let resp = rmp_serde::to_vec_named(&resp).expect("encode cancel response");
+ let len = (resp.len() as u32).to_be_bytes();
+ if sock.write_all(&len).await.is_err() {
+ return;
+ }
+ if sock.write_all(&resp).await.is_err() {
+ return;
+ }
+ if sock.flush().await.is_err() {
+ return;
+ }
+ }
+ });
+ }
+ })
+ }
+
+ fn pool_with_children(count: usize) -> Arc<AdapterWorkerPool> {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let paths: Vec<PathBuf> = (0..count)
+ .map(|i| dir.path().join(format!("ipc-{i}.sock")))
+ .collect();
+ let pool = AdapterWorkerPool::new(
+ &paths,
+ 1,
+ 60,
+ 900,
+ Arc::new(MetricsRegistry::new().unwrap()),
+ );
+ for child in &pool.children {
+ child.ready.store(true, Ordering::Release);
+ }
+ pool.metrics
+ .worker_gpu_slots_ready
+ .set(pool.ready_child_count() as i64);
+ pool.refresh_all_child_metrics();
+ pool
+ }
+
+ fn pool_with_paths(paths: &[PathBuf]) -> Arc<AdapterWorkerPool> {
+ let pool =
+ AdapterWorkerPool::new(paths, 1, 1, 900, Arc::new(MetricsRegistry::new().unwrap()));
+ for child in &pool.children {
+ child.ready.store(true, Ordering::Release);
+ }
+ pool.metrics
+ .worker_gpu_slots_ready
+ .set(pool.ready_child_count() as i64);
+ pool.refresh_all_child_metrics();
+ pool
+ }
+
+ fn placement(pool: &AdapterWorkerPool, model_id: &str) -> Option<usize> {
+ pool.placements
+ .lock()
+ .expect("placement map")
+ .get(model_id)
+ .copied()
+ }
+
+ #[test]
+ fn keeps_existing_model_on_same_ready_child() {
+ let pool = pool_with_children(2);
+
+ let first = pool.child_for_model("model-a").index;
+ let second = pool.child_for_model("model-a").index;
+
+ assert_eq!(first, second);
+ assert_eq!(placement(&pool, "model-a"), Some(first));
+ }
+
+ #[test]
+ fn spreads_new_models_by_child_model_count() {
+ let pool = pool_with_children(4);
+
+ let placements: Vec<usize> = ["model-a", "model-b", "model-c", "model-d"]
+ .into_iter()
+ .map(|model| pool.child_for_model(model).index)
+ .collect();
+
+ assert_eq!(placements, vec![0, 1, 2, 3]);
+ }
+
+ #[test]
+ fn partitions_pinned_models_by_placed_child_without_replication() {
+ let pool = pool_with_children(3);
+
+ let assigned = pool.pinned_models_by_child(vec![
+ "model-a".to_string(),
+ "model-b".to_string(),
+ "model-c".to_string(),
+ "model-a".to_string(),
+ " ".to_string(),
+ ]);
+
+ assert_eq!(
+ assigned,
+ vec![
+ vec!["model-a".to_string()],
+ vec!["model-b".to_string()],
+ vec!["model-c".to_string()],
+ ]
+ );
+ assert_eq!(placement(&pool, "model-a"), Some(0));
+ assert_eq!(placement(&pool, "model-b"), Some(1));
+ assert_eq!(placement(&pool, "model-c"), Some(2));
+ }
+
+ #[test]
+ fn pinned_assignment_revision_tracks_pinned_model_moves_only() {
+ let pool = pool_with_children(2);
+ pool.update_pinned_model_set(&["model-a".to_string()]);
+ let initial_revision = pool.pinned_assignment_revision();
+
+ let first = pool.child_for_model("model-a").index;
+ assert_eq!(first, 0);
+ let after_initial_place = pool.pinned_assignment_revision();
+ assert!(after_initial_place > initial_revision);
+
+ pool.children[first].ready.store(false, Ordering::Release);
+ let moved = pool.child_for_model("model-a").index;
+ assert_eq!(moved, 1);
+ let after_move = pool.pinned_assignment_revision();
+ assert!(after_move > after_initial_place);
+
+ let non_pinned_revision = pool.pinned_assignment_revision();
+ let non_pinned_first = pool.child_for_model("model-b").index;
+ pool.children[non_pinned_first]
+ .ready
+ .store(false, Ordering::Release);
+ let _ = pool.child_for_model("model-b");
+ assert_eq!(pool.pinned_assignment_revision(), non_pinned_revision);
+ }
+
+ #[test]
+ fn moves_model_when_placed_child_is_unready() {
+ let pool = pool_with_children(2);
+
+ let first = pool.child_for_model("model-a").index;
+ pool.children[first].ready.store(false, Ordering::Release);
+ pool.metrics
+ .worker_gpu_slots_ready
+ .set(pool.ready_child_count() as i64);
+ let second = pool.child_for_model("model-a").index;
+
+ assert_ne!(first, second);
+ assert_eq!(placement(&pool, "model-a"), Some(second));
+ assert!(!pool.children[first]
+ .models
+ .lock()
+ .expect("model set")
+ .contains("model-a"));
+ }
+
+ #[test]
+ fn chooses_least_inflight_child_when_model_counts_match() {
+ let pool = pool_with_children(2);
+ pool.children[0]
+ .inflight_batches
+ .store(8, Ordering::Release);
+
+ let chosen = pool.child_for_model("model-a").index;
+
+ assert_eq!(chosen, 1);
+ }
+
+ #[test]
+ fn chooses_least_pending_cost_when_model_counts_match() {
+ let pool = pool_with_children(2);
+ pool.children[0]
+ .models
+ .lock()
+ .expect("model set")
+ .insert("existing-a".to_string());
+ pool.children[1]
+ .models
+ .lock()
+ .expect("model set")
+ .insert("existing-b".to_string());
+ pool.children[0].pending_cost.store(128, Ordering::Release);
+ pool.children[1].pending_cost.store(8, Ordering::Release);
+
+ let chosen = pool.child_for_model("model-a").index;
+
+ assert_eq!(chosen, 1);
+ }
+
+ #[test]
+ fn records_pending_work_against_placed_child() {
+ let pool = pool_with_children(2);
+
+ let child_index = pool.record_model_pending_enqueue("model-a", 10);
+ let child = pool.child_for_model("model-a");
+
+ assert_eq!(child_index, child.index);
+ assert_eq!(child.pending_items.load(Ordering::Acquire), 1);
+ assert_eq!(child.pending_cost.load(Ordering::Acquire), 10);
+
+ pool.record_child_pending_dequeue(child_index, 1, 10);
+
+ assert_eq!(child.pending_items.load(Ordering::Acquire), 0);
+ assert_eq!(child.pending_cost.load(Ordering::Acquire), 0);
+ }
+
+ #[test]
+ fn pending_dequeue_uses_original_child_after_model_moves() {
+ let pool = pool_with_children(2);
+
+ let original_child = pool.record_model_pending_enqueue("model-a", 10);
+ assert_eq!(original_child, 0);
+
+ pool.children[0].ready.store(false, Ordering::Release);
+ let moved_child = pool.child_for_model("model-a");
+ assert_eq!(moved_child.index, 1);
+
+ pool.record_child_pending_dequeue(original_child, 1, 10);
+
+ assert_eq!(pool.children[0].pending_items.load(Ordering::Acquire), 0);
+ assert_eq!(pool.children[0].pending_cost.load(Ordering::Acquire), 0);
+ assert_eq!(pool.children[1].pending_items.load(Ordering::Acquire), 0);
+ assert_eq!(pool.children[1].pending_cost.load(Ordering::Acquire), 0);
+ }
+
+ #[tokio::test]
+ async fn cancel_fanout_failure_refreshes_aggregate_ready_slots() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let healthy_path = dir.path().join("healthy.sock");
+ let missing_path = dir.path().join("missing.sock");
+ let server = spawn_cancel_ok(healthy_path.clone()).await;
+ let pool = pool_with_paths(&[healthy_path, missing_path]);
+
+ assert_eq!(pool.metrics.worker_gpu_slots_ready.get(), 2);
+
+ let resp = pool
+ .signal_generate_cancel("req-cancel".to_string())
+ .await
+ .expect("one child should accept cancel");
+
+ assert!(resp.matched);
+ assert!(pool.children[0].ready.load(Ordering::Acquire));
+ assert!(!pool.children[1].ready.load(Ordering::Acquire));
+ assert_eq!(pool.metrics.worker_gpu_slots_ready.get(), 1);
+
+ server.abort();
+ }
+
+ #[test]
+ fn config_quarantine_blocks_child_readiness_until_full_success() {
+ let pool = pool_with_children(2);
+
+ let generation = pool.begin_config_fanout("test apply");
+
+ assert!(pool.config_quarantined.load(Ordering::Acquire));
+ assert_eq!(pool.ready_child_count(), 0);
+ assert!(pool.ensure_not_config_quarantined().is_err());
+
+ pool.mark_child_call_succeeded(&pool.children[0]);
+
+ assert_eq!(pool.ready_child_count(), 0);
+ assert!(!pool.children[0].ready.load(Ordering::Acquire));
+
+ pool.clear_config_quarantine_after_success("test success", generation);
+
+ assert!(!pool.config_quarantined.load(Ordering::Acquire));
+ assert_eq!(pool.ready_child_count(), 2);
+ pool.ensure_not_config_quarantined().unwrap();
+ }
+
+ #[test]
+ fn stale_config_fanout_cannot_clear_newer_quarantine() {
+ let pool = pool_with_children(2);
+
+ let stale_generation = pool.begin_config_fanout("stale apply");
+ let current_generation = pool.begin_config_fanout("current apply");
+
+ pool.clear_config_quarantine_after_success("stale success", stale_generation);
+
+ assert!(pool.config_quarantined.load(Ordering::Acquire));
+ assert_eq!(pool.ready_child_count(), 0);
+
+ pool.clear_config_quarantine_after_success("current success", current_generation);
+
+ assert!(!pool.config_quarantined.load(Ordering::Acquire));
+ assert_eq!(pool.ready_child_count(), 2);
+ }
+
+ #[test]
+ fn stale_config_fanout_failure_cannot_requarantine_after_newer_success() {
+ let pool = pool_with_children(2);
+
+ let stale_generation = pool.begin_config_fanout("stale apply");
+ let current_generation = pool.begin_config_fanout("current apply");
+ pool.clear_config_quarantine_after_success("current success", current_generation);
+
+ pool.quarantine_config_fanout("stale failure", stale_generation);
+
+ assert!(!pool.config_quarantined.load(Ordering::Acquire));
+ assert_eq!(pool.ready_child_count(), 2);
+ }
+
+ #[test]
+ fn clearing_failed_pinned_placement_advances_assignment_revision() {
+ let pool = pool_with_children(2);
+ pool.update_pinned_model_set(&["model-a".to_string()]);
+ let child = pool.child_for_model("model-a");
+ let before_clear = pool.pinned_assignment_revision();
+
+ pool.clear_model_if_on_child("model-a", child.index);
+
+ assert!(pool.pinned_assignment_revision() > before_clear);
+ assert_eq!(placement(&pool, "model-a"), None);
+ }
+
+ #[test]
+ fn apply_config_merge_preserves_any_child_rejection() {
+ let mut combined = None;
+
+ merge_apply_model_config_response(
+ &mut combined,
+ ApplyModelConfigResponse {
+ applied: false,
+ bundle_config_hash: "h1".into(),
+ config_version: 1,
+ },
+ );
+ merge_apply_model_config_response(
+ &mut combined,
+ ApplyModelConfigResponse {
+ applied: true,
+ bundle_config_hash: "h1".into(),
+ config_version: 2,
+ },
+ );
+
+ let resp = combined.expect("combined response");
+ assert!(!resp.applied);
+ assert_eq!(resp.bundle_config_hash, "h1");
+ assert_eq!(resp.config_version, 2);
+ }
+
+ #[test]
+ fn apply_config_merge_rejects_child_hash_divergence() {
+ let mut combined = None;
+
+ merge_apply_model_config_response(
+ &mut combined,
+ ApplyModelConfigResponse {
+ applied: true,
+ bundle_config_hash: "h1".into(),
+ config_version: 1,
+ },
+ );
+ merge_apply_model_config_response(
+ &mut combined,
+ ApplyModelConfigResponse {
+ applied: true,
+ bundle_config_hash: "h2".into(),
+ config_version: 1,
+ },
+ );
+
+ assert!(!combined.expect("combined response").applied);
+ }
+
+ #[test]
+ fn replace_config_merge_rejects_child_model_divergence() {
+ let mut combined = None;
+
+ merge_replace_model_configs_response(
+ &mut combined,
+ ReplaceModelConfigsResponse {
+ applied: true,
+ bundle_config_hash: "h1".into(),
+ config_version: 1,
+ applied_models: vec!["model-a".into()],
+ },
+ );
+ merge_replace_model_configs_response(
+ &mut combined,
+ ReplaceModelConfigsResponse {
+ applied: true,
+ bundle_config_hash: "h1".into(),
+ config_version: 1,
+ applied_models: vec!["model-b".into()],
+ },
+ );
+
+ let resp = combined.expect("combined response");
+ assert!(!resp.applied);
+ assert_eq!(
+ resp.applied_models,
+ vec!["model-a".to_string(), "model-b".to_string()]
+ );
+ }
+}
diff --git a/packages/sie_server_sidecar/src/backend/mod.rs b/packages/sie_server_sidecar/src/backend/mod.rs
index 347bffcc3..0d5a91c3e 100644
--- a/packages/sie_server_sidecar/src/backend/mod.rs
+++ b/packages/sie_server_sidecar/src/backend/mod.rs
@@ -1,17 +1,17 @@
//! Inference backend abstraction.
//!
//! A [`InferenceBackend`] is the thing the dispatcher calls to turn a
-//! batch of `WorkItem`s into results. The default implementation is
-//! [`PythonIpcBackend`] — a thin adapter around [`crate::ipc_client::IpcClient`]
-//! that preserves the exact contract the Python `sie-server` expects.
+//! batch of `WorkItem`s into results. The queue-mode default is
+//! [`AdapterWorkerPool`], which owns one IPC client per colocated adapter
+//! child. [`PythonIpcBackend`] remains the single-socket IPC backend used by
+//! tests and specialised call sites.
//!
//! # Why this exists
//!
-//! The worker-sidecar owns NATS consumption, scheduling, and dispatch
-//! while Python remains the default inference engine (via UDS + msgpack
-//! RPC). This trait is the extension point for additional engines: a
-//! native backend can claim select models without touching the NATS or
-//! dispatcher code paths.
+//! The worker-sidecar owns NATS consumption, scheduling, and dispatch while
+//! adapter processes own model execution over UDS + msgpack RPC. This trait
+//! keeps those concerns separated: Python/PyTorch and Rust/Candle children can
+//! share the dispatcher, IPC protocol, metrics, and config fanout paths.
//!
//! # Not a runtime fallback
//!
@@ -79,14 +79,15 @@ use crate::ipc_types::{
ProcessScoreBatchRequest, RunBatchRequest,
};
+pub mod adapter_pool;
pub mod python_ipc;
pub mod router;
-// The sidecar talks to whichever adapter is co-deployed over IPC; today
-// that is the Python `sie_server` adapter. GPU-independent pieces
-// (tokenize, text prep, IPC types, output formatting) live in this crate
+// The sidecar talks to colocated adapter children over IPC. GPU-independent
+// pieces (tokenize, text prep, IPC types, output formatting) live in this crate
// under `prep` and `protocol`.
+pub use adapter_pool::AdapterWorkerPool;
pub use python_ipc::PythonIpcBackend;
pub use router::BackendRouter;
diff --git a/packages/sie_server_sidecar/src/backend/python_ipc.rs b/packages/sie_server_sidecar/src/backend/python_ipc.rs
index 77342bdfd..3c2c50a36 100644
--- a/packages/sie_server_sidecar/src/backend/python_ipc.rs
+++ b/packages/sie_server_sidecar/src/backend/python_ipc.rs
@@ -48,7 +48,7 @@ impl PythonIpcBackend {
/// this channel — the Python server always responds with a readiness
/// state (`RetryLater`) when a model is unknown, which the dispatcher
/// handles separately via [`EnsureModelReadyResponse`].
-fn map_ipc_error(e: IpcError) -> BackendError {
+pub(crate) fn map_ipc_error(e: IpcError) -> BackendError {
// Log at debug — the dispatcher already logs warn on NAK decisions.
debug!(error = %e, "python-ipc backend: IPC call failed");
BackendError::Transient(e.to_string())
diff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rs
index a8b89fb6d..7e28aaf95 100644
--- a/packages/sie_server_sidecar/src/config.rs
+++ b/packages/sie_server_sidecar/src/config.rs
@@ -7,8 +7,15 @@ use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct WorkerConfig {
- /// NATS server URL (e.g. `nats://localhost:4222`).
- pub nats_url: String,
+ /// NATS server URL (e.g. `nats://localhost:4222`). Required for the
+ /// default NATS ingest (`run()`); `None` is valid only for the
+ /// local-ingest mode (`run_local()`, P2.10 §4.6) which never
+ /// touches NATS.
+ pub nats_url: Option<String>,
+
+ /// UDS path for the local-ingest listener (`SIE_SIDECAR_LOCAL_SOCKET`).
+ /// Only read by `run_local()`; `None` on NATS deployments.
+ pub local_socket_path: Option<PathBuf>,
/// Pool name — drives the stream (`WORK_POOL_{pool}`), durable consumer
/// (`{pool}_{machine_profile}_{bundle}`), and subject filters.
@@ -18,10 +25,14 @@ pub struct WorkerConfig {
/// so multiple bundles on the same pool don't step on each other.
pub bundle: String,
- /// Unix domain socket used to talk to the colocated backend IPC server.
+ /// Primary Unix domain socket used to talk to the colocated adapter worker.
pub ipc_socket_path: PathBuf,
- /// Number of concurrent IPC connections to the backend process. `1`
+ /// Unix domain sockets used to talk to adapter worker children. Defaults to
+ /// [`Self::ipc_socket_path`] for the single-worker baseline.
+ pub ipc_socket_paths: Vec<PathBuf>,
+
+ /// Number of concurrent IPC connections to each adapter worker process. `1`
/// preserves the legacy single-socket behaviour; higher values let
/// the dispatcher's `SIE_MAX_CONCURRENT_BATCHES` actually drive
/// parallel backend-side batches. Sourced from `SIE_IPC_POOL_SIZE`
@@ -29,11 +40,11 @@ pub struct WorkerConfig {
/// `SIE_MAX_CONCURRENT_BATCHES`'s default (4).
pub ipc_pool_size: usize,
- /// Per-RPC timeout for ordinary sidecar-to-backend IPC calls. Sourced from
+ /// Per-RPC timeout for ordinary sidecar → adapter IPC calls. Sourced from
/// `SIE_IPC_REQUEST_TIMEOUT_S`.
pub ipc_request_timeout_s: u64,
- /// Timeout for sidecar-to-backend `EnsureModelReady` calls. Must be at least
+ /// Timeout for sidecar → adapter `EnsureModelReady` calls. Must be at least
/// as long as the slowest expected cold start; SGLang adapters may
/// legitimately spend many minutes loading large models before they can
/// answer the readiness handshake. Sourced from
@@ -78,7 +89,7 @@ pub struct WorkerConfig {
/// IPC `Ping`.
pub worker_id: String,
- /// How often to send `Ping` RPCs to the backend process.
+ /// How often to send `Ping` RPCs to adapter worker processes.
pub ping_interval_ms: u64,
/// Multiplier applied to `ping_interval_ms` to compute the
@@ -88,7 +99,7 @@ pub struct WorkerConfig {
///
/// Default `3`. Override with `SIE_WORKER_READYZ_STALE_MULT`
/// when ops want a looser bound (e.g. `5` to roughly match the
- /// Python adapter's historical 10 s window with a 2 s ping).
+ /// adapter worker's historical 10 s window with a 2 s ping).
/// `0` falls back to the default at construction time so a
/// misconfigured env var doesn't make the pod look unready on
/// the very tick after a successful ping.
@@ -202,10 +213,12 @@ mod tests {
fn sample() -> WorkerConfig {
WorkerConfig {
- nats_url: "nats://localhost:4222".into(),
+ nats_url: Some("nats://localhost:4222".into()),
+ local_socket_path: None,
pool: "l4".into(),
bundle: "default".into(),
ipc_socket_path: PathBuf::from("/tmp/sie-ipc.sock"),
+ ipc_socket_paths: vec![PathBuf::from("/tmp/sie-ipc.sock")],
ipc_pool_size: 1,
ipc_request_timeout_s: 60,
model_ready_timeout_s: 900,
diff --git a/packages/sie_server_sidecar/src/config_reconciler.rs b/packages/sie_server_sidecar/src/config_reconciler.rs
index 23391cca0..b9a94c9c7 100644
--- a/packages/sie_server_sidecar/src/config_reconciler.rs
+++ b/packages/sie_server_sidecar/src/config_reconciler.rs
@@ -18,10 +18,11 @@ use tokio::task::JoinHandle;
use tokio::time::interval;
use tracing::{debug, info, warn};
+use crate::backend::AdapterWorkerPool;
use crate::config_subscriber::{
advertised_bundle_hash, replace_via_ipc_with_retry, ConfigApplyState, MAX_MODEL_CONFIG_BYTES,
};
-use crate::ipc_client::{IpcClient, IpcError};
+use crate::ipc_client::IpcError;
use crate::ipc_types::{
ReplaceModelConfigEntry, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,
};
@@ -152,7 +153,7 @@ struct ReconcileRuntime<'a> {
client: &'a ReconcileClient,
bundle: &'a str,
pool: &'a str,
- ipc: Arc<IpcClient>,
+ ipc: Arc<AdapterWorkerPool>,
state: Arc<ConfigApplyState>,
metrics: Arc<MetricsRegistry>,
shutdown: Arc<Shutdown>,
@@ -286,7 +287,7 @@ fn compute_export_signature(
/// and health publisher lifecycle.
pub fn spawn(
config: Option<ReconcilerConfig>,
- ipc: Arc<IpcClient>,
+ ipc: Arc<AdapterWorkerPool>,
state: Arc<ConfigApplyState>,
metrics: Arc<MetricsRegistry>,
shutdown: Arc<Shutdown>,
diff --git a/packages/sie_server_sidecar/src/config_subscriber.rs b/packages/sie_server_sidecar/src/config_subscriber.rs
index f387da426..c6b6cccaf 100644
--- a/packages/sie_server_sidecar/src/config_subscriber.rs
+++ b/packages/sie_server_sidecar/src/config_subscriber.rs
@@ -19,10 +19,12 @@ use tokio::task::JoinHandle;
use tokio::time::{sleep, Duration};
use tracing::{debug, info, warn};
+use crate::backend::AdapterWorkerPool;
use crate::health_publisher::{SharedBundleConfigHash, SharedLoadedModels};
-use crate::ipc_client::{IpcClient, IpcError};
+use crate::ipc_client::IpcError;
use crate::ipc_types::{
- ApplyModelConfigRequest, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,
+ ApplyModelConfigRequest, ReadinessState, ReplaceModelConfigsRequest,
+ ReplaceModelConfigsResponse,
};
use crate::metrics::MetricsRegistry;
use crate::shutdown::Shutdown;
@@ -145,6 +147,22 @@ impl ConfigApplyState {
*guard = deduped;
}
+ pub fn record_loaded_model(&self, model_id: &str) {
+ let model_id = model_id.trim();
+ if model_id.is_empty() {
+ return;
+ }
+ let mut guard = self
+ .loaded_models
+ .write()
+ .expect("loaded models lock poisoned");
+ if guard.iter().any(|known| known == model_id) {
+ return;
+ }
+ guard.push(model_id.to_string());
+ guard.sort();
+ }
+
fn remember_bundle_hash(&self, hash: &str) {
if hash.is_empty() {
return;
@@ -268,7 +286,7 @@ struct SubscriberRuntime {
bundle: String,
pool: String,
trusted_producers: Vec<String>,
- ipc: Arc<IpcClient>,
+ ipc: Arc<AdapterWorkerPool>,
state: Arc<ConfigApplyState>,
metrics: Arc<MetricsRegistry>,
shutdown: Arc<Shutdown>,
@@ -373,6 +391,60 @@ fn retryable_ipc_error(e: &IpcError) -> bool {
}
}
+fn requires_eager_model_ready(bundle_id: &str) -> bool {
+ bundle_id.trim() == "candle"
+}
+
+async fn ensure_candle_model_ready_if_needed(
+ ipc: &Arc<AdapterWorkerPool>,
+ bundle_id: &str,
+ model_id: &str,
+ epoch: u64,
+) -> Result<(), IpcError> {
+ if !requires_eager_model_ready(bundle_id) {
+ return Ok(());
+ }
+
+ match ipc.ensure_model_ready_on_placed_child(model_id).await {
+ Ok(resp) if resp.state == ReadinessState::Ready => {
+ info!(
+ model = %model_id,
+ epoch,
+ "worker-config: Candle model ready after config apply"
+ );
+ Ok(())
+ }
+ Ok(resp) => {
+ warn!(
+ model = %model_id,
+ epoch,
+ state = ?resp.state,
+ "worker-config: Candle model not ready after config apply; retrying"
+ );
+ Err(IpcError::Timeout)
+ }
+ Err(e) => Err(e),
+ }
+}
+
+async fn ensure_candle_models_ready_if_needed(
+ ipc: &Arc<AdapterWorkerPool>,
+ bundle_id: &str,
+ model_ids: &[String],
+ epoch: u64,
+) -> Result<Vec<String>, IpcError> {
+ if !requires_eager_model_ready(bundle_id) {
+ return Ok(model_ids.to_vec());
+ }
+
+ let mut ready_models = Vec::with_capacity(model_ids.len());
+ for model_id in model_ids {
+ ensure_candle_model_ready_if_needed(ipc, bundle_id, model_id, epoch).await?;
+ ready_models.push(model_id.clone());
+ }
+ Ok(ready_models)
+}
+
fn next_retry_delay(current: Duration) -> Duration {
std::cmp::min(current.saturating_mul(2), RETRY_MAX_DELAY)
}
@@ -391,7 +463,7 @@ async fn wait_retry_or_shutdown(shutdown: &Shutdown, delay: Duration) -> bool {
pub fn spawn(
nats: Client,
bundle: String,
- ipc: Arc<IpcClient>,
+ ipc: Arc<AdapterWorkerPool>,
state: Arc<ConfigApplyState>,
metrics: Arc<MetricsRegistry>,
shutdown: Arc<Shutdown>,
@@ -494,7 +566,7 @@ pub fn spawn(
}
pub(crate) async fn apply_via_ipc_with_retry(
- ipc: Arc<IpcClient>,
+ ipc: Arc<AdapterWorkerPool>,
shutdown: Arc<Shutdown>,
req: ApplyModelConfigRequest,
model_id: &str,
@@ -504,7 +576,43 @@ pub(crate) async fn apply_via_ipc_with_retry(
let mut attempt = 0_u64;
loop {
match ipc.apply_model_config(req.clone()).await {
- Ok(resp) => return Ok(Some(resp)),
+ Ok(resp) => {
+ match ensure_candle_model_ready_if_needed(&ipc, &req.bundle_id, model_id, epoch)
+ .await
+ {
+ Ok(()) => return Ok(Some(resp)),
+ Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {
+ attempt = attempt.saturating_add(1);
+ if attempt == 1
+ || attempt == 5
+ || attempt == 30
+ || attempt.is_multiple_of(120)
+ {
+ warn!(
+ model = %model_id,
+ epoch,
+ attempt,
+ retry_delay_ms = retry_delay.as_millis() as u64,
+ error = %e,
+ "worker-config: Candle model readiness still waiting after apply; retrying"
+ );
+ } else {
+ debug!(
+ model = %model_id,
+ epoch,
+ attempt,
+ error = %e,
+ "worker-config: Candle model readiness still waiting"
+ );
+ }
+ if wait_retry_or_shutdown(&shutdown, retry_delay).await {
+ return Ok(None);
+ }
+ retry_delay = next_retry_delay(retry_delay);
+ }
+ Err(e) => return Err(e),
+ }
+ }
Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {
attempt = attempt.saturating_add(1);
if attempt == 1 || attempt == 5 || attempt == 30 || attempt.is_multiple_of(120) {
@@ -536,7 +644,7 @@ pub(crate) async fn apply_via_ipc_with_retry(
}
pub(crate) async fn replace_via_ipc_with_retry(
- ipc: Arc<IpcClient>,
+ ipc: Arc<AdapterWorkerPool>,
shutdown: Arc<Shutdown>,
req: ReplaceModelConfigsRequest,
epoch: u64,
@@ -545,7 +653,49 @@ pub(crate) async fn replace_via_ipc_with_retry(
let mut attempt = 0_u64;
loop {
match ipc.replace_model_configs(req.clone()).await {
- Ok(resp) => return Ok(Some(resp)),
+ Ok(mut resp) => {
+ match ensure_candle_models_ready_if_needed(
+ &ipc,
+ &req.bundle_id,
+ &resp.applied_models,
+ epoch,
+ )
+ .await
+ {
+ Ok(ready_models) => {
+ resp.applied_models = ready_models;
+ return Ok(Some(resp));
+ }
+ Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {
+ attempt = attempt.saturating_add(1);
+ if attempt == 1
+ || attempt == 5
+ || attempt == 30
+ || attempt.is_multiple_of(120)
+ {
+ warn!(
+ epoch,
+ attempt,
+ retry_delay_ms = retry_delay.as_millis() as u64,
+ error = %e,
+ "worker-config: Candle model readiness still waiting after replace; retrying"
+ );
+ } else {
+ debug!(
+ epoch,
+ attempt,
+ error = %e,
+ "worker-config: Candle model readiness still waiting after replace"
+ );
+ }
+ if wait_retry_or_shutdown(&shutdown, retry_delay).await {
+ return Ok(None);
+ }
+ retry_delay = next_retry_delay(retry_delay);
+ }
+ Err(e) => return Err(e),
+ }
+ }
Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {
attempt = attempt.saturating_add(1);
if attempt == 1 || attempt == 5 || attempt == 30 || attempt.is_multiple_of(120) {
@@ -754,6 +904,9 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNot
}
state.mark_applied(notification.epoch, advertised_hash);
+ if requires_eager_model_ready(&notification.bundle_id) {
+ state.record_loaded_model(&notification.model_id);
+ }
metrics.config_epoch.set(notification.epoch as i64);
}
diff --git a/packages/sie_server_sidecar/src/delivery.rs b/packages/sie_server_sidecar/src/delivery.rs
new file mode 100644
index 000000000..c6fa3083f
--- /dev/null
+++ b/packages/sie_server_sidecar/src/delivery.rs
@@ -0,0 +1,273 @@
+//! Delivery abstraction: where a `WorkItem` came from and where its
+//! settlement (result publish / ACK / redelivery request) must go.
+//!
+//! Added for the local-ingest mode: in a broker-less sidecar lane there
+//! is no NATS, so the dispatcher cannot settle
+//! work by ACK/NAK-ing a JetStream [`Message`] or publishing to a reply
+//! subject. Instead of forking the dispatch pipeline, the pipeline becomes
+//! generic over this small enum:
+//!
+//! * [`Delivery::Nats`] — the existing JetStream message. ACK/NAK/progress
+//! map 1:1 onto the underlying [`Message`]; results still publish to
+//! `WorkItem.reply_subject` via [`crate::publisher::WorkPublisher`].
+//! **Zero behaviour change** for the NATS path.
+//! * [`Delivery::Local`] — one slot of an in-flight local-ingest
+//! `publish_work` call (`crate::local_ingest`). Results are sent back to
+//! the ingest connection as [`LocalDeliveryEvent::Result`]; a NAK becomes
+//! [`LocalDeliveryEvent::Retry`] (there is no broker to redeliver, so the
+//! ingest layer re-dispatches with a bounded attempt budget — the same
+//! proportional stand-in the reference Python lane uses); ACK and progress
+//! are no-ops because the terminal `Result` event *is* the settlement.
+
+use std::time::Duration;
+
+use async_nats::jetstream::Message;
+use tokio::sync::mpsc;
+use tokio::sync::OwnedSemaphorePermit;
+
+use crate::work_types::WorkResult;
+
+/// Event emitted by the dispatcher for one local-ingest slot.
+#[derive(Debug)]
+pub enum LocalDeliveryEvent {
+ /// Terminal settlement: a `WorkResult` (success or typed error) for
+ /// `slot`. Exactly one per slot reaches the ingest response. Boxed:
+ /// `WorkResult` dwarfs `Retry`, and the event only crosses a channel
+ /// once per item, so the indirection is free.
+ Result {
+ slot: usize,
+ result: Box<WorkResult>,
+ },
+ /// The worker requested redelivery (the NATS NAK analogue). The
+ /// ingest layer re-dispatches the original `WorkItem` after
+ /// `delay_ms`, or synthesises a typed error once the attempt budget
+ /// is exhausted. `attempt` is the attempt that just NAKed (0-based).
+ Retry {
+ slot: usize,
+ attempt: u32,
+ delay_ms: u64,
+ },
+}
+
+/// Settlement handle for one item of a local-ingest `publish_work` call.
+#[derive(Debug, Clone)]
+pub struct LocalDelivery {
+ slot: usize,
+ attempt: u32,
+ tx: mpsc::UnboundedSender<LocalDeliveryEvent>,
+}
+
+impl LocalDelivery {
+ pub fn new(slot: usize, attempt: u32, tx: mpsc::UnboundedSender<LocalDeliveryEvent>) -> Self {
+ Self { slot, attempt, tx }
+ }
+
+ pub fn slot(&self) -> usize {
+ self.slot
+ }
+
+ pub fn attempt(&self) -> u32 {
+ self.attempt
+ }
+
+ /// Send the terminal result. `false` means the ingest caller is gone
+ /// (connection closed / call timed out) — there is nowhere left to
+ /// deliver, so callers just log and move on.
+ pub fn send_result(&self, result: WorkResult) -> bool {
+ self.tx
+ .send(LocalDeliveryEvent::Result {
+ slot: self.slot,
+ result: Box::new(result),
+ })
+ .is_ok()
+ }
+
+ fn send_retry(&self, delay_ms: u64) -> bool {
+ self.tx
+ .send(LocalDeliveryEvent::Retry {
+ slot: self.slot,
+ attempt: self.attempt,
+ delay_ms,
+ })
+ .is_ok()
+ }
+}
+
+/// The dispatcher-facing settlement token. Not `Clone` on the NATS arm:
+/// the JetStream [`Message`] owns the ACK/NAK token, which must not be
+/// duplicated (same single-ownership rule `SchedulerMeta` documents).
+///
+/// Variant sizes are lopsided (`Message` ≈ 400 B vs 24 B), but this enum
+/// occupies exactly the slots that held a bare `Message` before the
+/// local-ingest refactor — boxing it would add a heap hop to every NATS
+/// settlement to save memory the pipeline was already spending. Scoped
+/// allow, same policy as `publisher::ShapeOutcome`.
+#[allow(clippy::large_enum_variant)]
+pub enum Delivery {
+ Nats(
+ Message,
+ /// Pull-loop admission permit: intake capacity stays occupied until
+ /// this delivery settles (ACK / NAK / drop) — exactly the
+ /// queue-admission bound. Local-ingest deliveries carry no permit.
+ Option<OwnedSemaphorePermit>,
+ ),
+ Local(LocalDelivery),
+}
+
+impl Delivery {
+ /// True when this delivery arrived worker-directly rather than via the
+ /// pool subject: a NATS message on a worker-specific direct-dispatch
+ /// subject, or any local-ingest delivery (the caller addressed THIS
+ /// worker's socket). Feeds `WorkResult.worker_direct` /
+ /// `SchedulerMeta.worker_direct` so the gateway's direct-fallback
+ /// cancellation bookkeeping (main's NAK/stale-republish hardening) sees
+ /// the same signal on every path.
+ pub fn worker_direct(&self) -> bool {
+ match self {
+ Self::Nats(msg, _) => crate::subject::is_worker_direct_work_subject(&msg.subject),
+ Self::Local(_) => true,
+ }
+ }
+
+ /// ACK — "settled, never redeliver". Local deliveries settle via
+ /// their terminal [`LocalDeliveryEvent::Result`], so this is a no-op.
+ pub async fn ack(&self) -> Result<(), String> {
+ match self {
+ Self::Nats(msg, _) => msg.ack().await.map_err(|e| e.to_string()),
+ Self::Local(_) => Ok(()),
+ }
+ }
+
+ /// NAK — "not settled, redeliver after `delay_ms`". Local deliveries
+ /// route this to the ingest layer's bounded re-dispatch.
+ pub async fn nak(&self, delay_ms: u64) -> Result<(), String> {
+ match self {
+ Self::Nats(msg, _) => msg
+ .ack_with(async_nats::jetstream::AckKind::Nak(Some(
+ Duration::from_millis(delay_ms),
+ )))
+ .await
+ .map_err(|e| e.to_string()),
+ Self::Local(local) => {
+ if local.send_retry(delay_ms) {
+ Ok(())
+ } else {
+ Err("local ingest caller gone — retry event dropped".to_string())
+ }
+ }
+ }
+ }
+
+ /// Progress ACK — "still working, reset the redelivery clock". The
+ /// local ingest caller holds one synchronous call open with no
+ /// ack-wait clock, so this is a no-op there.
+ pub async fn progress(&self) -> Result<(), String> {
+ match self {
+ Self::Nats(msg, _) => msg
+ .ack_with(async_nats::jetstream::AckKind::Progress)
+ .await
+ .map_err(|e| e.to_string()),
+ Self::Local(_) => Ok(()),
+ }
+ }
+
+ /// Log-friendly origin reference (NATS subject / local slot).
+ pub fn log_ref(&self) -> String {
+ match self {
+ Self::Nats(msg, _) => msg.subject.to_string(),
+ Self::Local(local) => format!("local[slot={},attempt={}]", local.slot, local.attempt),
+ }
+ }
+}
+
+impl std::fmt::Debug for Delivery {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ // `Message` intentionally has no useful Debug; print the origin ref.
+ f.debug_tuple("Delivery").field(&self.log_ref()).finish()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn result(slot: usize) -> WorkResult {
+ WorkResult {
+ work_item_id: format!("r.{slot}"),
+ request_id: "r".into(),
+ item_index: slot as u32,
+ success: true,
+ result_msgpack: vec![1, 2, 3],
+ error: None,
+ error_code: None,
+ worker_direct: true,
+ inference_ms: None,
+ queue_ms: None,
+ processing_ms: None,
+ worker_id: Some("w".into()),
+ tokenization_ms: None,
+ postprocessing_ms: None,
+ payload_fetch_ms: None,
+ units: None,
+ }
+ }
+
+ #[tokio::test]
+ async fn local_ack_and_progress_are_noops() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let d = Delivery::Local(LocalDelivery::new(0, 0, tx));
+ d.ack().await.expect("local ack is Ok");
+ d.progress().await.expect("local progress is Ok");
+ // Neither emits an event.
+ assert!(rx.try_recv().is_err());
+ }
+
+ #[tokio::test]
+ async fn local_nak_emits_retry_with_attempt_and_delay() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let d = Delivery::Local(LocalDelivery::new(3, 1, tx));
+ d.nak(250).await.expect("retry event sent");
+ match rx.try_recv().expect("event present") {
+ LocalDeliveryEvent::Retry {
+ slot,
+ attempt,
+ delay_ms,
+ } => {
+ assert_eq!(slot, 3);
+ assert_eq!(attempt, 1);
+ assert_eq!(delay_ms, 250);
+ }
+ other => panic!("expected Retry, got {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn local_nak_after_caller_gone_is_error() {
+ let (tx, rx) = mpsc::unbounded_channel();
+ drop(rx);
+ let d = Delivery::Local(LocalDelivery::new(0, 0, tx));
+ assert!(d.nak(100).await.is_err());
+ }
+
+ #[tokio::test]
+ async fn local_send_result_round_trips() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let local = LocalDelivery::new(2, 0, tx);
+ assert!(local.send_result(result(2)));
+ match rx.try_recv().expect("event present") {
+ LocalDeliveryEvent::Result { slot, result } => {
+ assert_eq!(slot, 2);
+ assert!(result.success);
+ assert_eq!(result.work_item_id, "r.2");
+ }
+ other @ LocalDeliveryEvent::Retry { .. } => panic!("expected Result, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn log_ref_identifies_local_slot() {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let d = Delivery::Local(LocalDelivery::new(7, 2, tx));
+ assert_eq!(d.log_ref(), "local[slot=7,attempt=2]");
+ }
+}
diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rs
index d06211d84..0330272da 100644
--- a/packages/sie_server_sidecar/src/dispatcher.rs
+++ b/packages/sie_server_sidecar/src/dispatcher.rs
@@ -14,6 +14,7 @@
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
+use std::sync::OnceLock;
use std::time::{Duration, Instant};
use async_nats::jetstream::Message;
@@ -21,14 +22,15 @@ use futures_util::future::join_all;
use rmpv::Value as MsgValue;
use serde_json::Value as Json;
use thiserror::Error;
-use tokio::sync::{Mutex, Semaphore};
+use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};
-use crate::backend::{BackendError, SharedBackend};
+use crate::backend::{AdapterWorkerPool, BackendError, SharedBackend};
use crate::batch_cancel::BatchCancelState;
use crate::config_subscriber::ConfigApplyState;
-use crate::ipc_client::{IpcClient, IpcError};
+use crate::delivery::Delivery;
+use crate::ipc_client::IpcError;
use crate::ipc_types::{
BatchOutcome, Disposition, EncodeBatchItem, ExtractBatchItem, GenerateEvent, ItemOutcome,
PreparedTokens, ProcessEncodeBatchRequest, ProcessExtractBatchRequest, ProcessGenerateRequest,
@@ -39,10 +41,10 @@ use crate::log_util::ErrChain;
use crate::metrics::MetricsRegistry;
use crate::payload_store::{PayloadError, PayloadStore};
use crate::pool_admission::PoolAdmissionGate;
-use crate::publisher::{should_publish, Timings, WorkPublisher};
+use crate::publisher::{shape_and_build_work_result, should_publish, Timings, WorkPublisher};
use crate::scheduler::{
- lora_from_options, HasCost, Op as SchedOp, ProductionScheduler, ProductionSchedulerRegistry,
- SchedulerItem, SchedulerMeta,
+ lora_from_options, HasCost, LoraKey, Op as SchedOp, ProductionScheduler,
+ ProductionSchedulerRegistry, SchedulerItem, SchedulerMeta,
};
use crate::shutdown::Shutdown;
use crate::subject::{extract_model_id, is_worker_direct_work_subject};
@@ -288,6 +290,48 @@ pub enum DispatchError {
Ack(String),
}
+/// A JetStream message plus an optional pull-loop admission permit — the
+/// pull-loop intake type consumed by [`Dispatcher::handle_batch`].
+///
+/// The permit is intentionally carried with the message until the request
+/// settles. This makes the sidecar's queue intake behave like the Python
+/// worker queue: a pulled item occupies capacity until the scheduler/backend
+/// path has actually finished with it, not merely until it was enqueued.
+/// At decode time `handle_batch` moves the permit into the item's
+/// [`Delivery`], which owns it for the rest of the pipeline.
+pub(crate) struct QueuedMessage {
+ msg: Message,
+ admission_permit: Option<OwnedSemaphorePermit>,
+}
+
+impl QueuedMessage {
+ #[must_use]
+ pub(crate) fn new(msg: Message, admission_permit: Option<OwnedSemaphorePermit>) -> Self {
+ Self {
+ msg,
+ admission_permit,
+ }
+ }
+
+ fn into_parts(self) -> (Message, Option<OwnedSemaphorePermit>) {
+ (self.msg, self.admission_permit)
+ }
+}
+
+impl From<Message> for QueuedMessage {
+ fn from(msg: Message) -> Self {
+ Self::new(msg, None)
+ }
+}
+
+impl std::ops::Deref for QueuedMessage {
+ type Target = Message;
+
+ fn deref(&self) -> &Self::Target {
+ &self.msg
+ }
+}
+
/// Pre-bundled handles the dispatcher needs — avoids a giant fn signature.
pub struct Dispatcher {
/// Inference backend — typically a [`crate::backend::BackendRouter`]
@@ -295,12 +339,20 @@ pub struct Dispatcher {
/// Held behind a trait object so the dispatcher doesn't care which
/// backend runs which model.
pub backend: SharedBackend,
- /// Direct IPC client used for streaming generation. The batch backend
+ /// Adapter worker pool used for streaming generation. The batch backend
/// trait remains outcome-oriented; generation is event-streaming, so
- /// the dispatcher talks to Python's `ProcessGenerate` RPC directly.
- pub ipc: Arc<IpcClient>,
+ /// the dispatcher asks the pool to pick the concrete child socket.
+ pub worker_pool: Arc<AdapterWorkerPool>,
pub payload_store: Arc<dyn PayloadStore>,
- pub publisher: Arc<WorkPublisher>,
+ /// NATS result publisher. `None` in local-ingest mode (P2.10, §4.6)
+ /// where results ride each [`Delivery::Local`]'s event channel instead
+ /// — the invariant "a [`Delivery::Nats`] item implies `Some`" holds by
+ /// construction (`run()` wires both NATS and the publisher; `run_local()`
+ /// wires neither).
+ pub publisher: Option<Arc<WorkPublisher>>,
+ /// Stable worker id stamped on locally-delivered `WorkResult`s. Same
+ /// value the NATS `WorkPublisher` stamps on its results.
+ pub worker_id: String,
pub metrics: Arc<MetricsRegistry>,
/// Rolling latency tracker shared with the pull loop. On every
/// successful publish we record `inference_ms + postprocess_ms`
@@ -368,9 +420,10 @@ impl Dispatcher {
#[allow(clippy::too_many_arguments)] // each arg is a distinct dependency
pub fn new(
backend: SharedBackend,
- ipc: Arc<IpcClient>,
+ worker_pool: Arc<AdapterWorkerPool>,
payload_store: Arc<dyn PayloadStore>,
- publisher: Arc<WorkPublisher>,
+ publisher: Option<Arc<WorkPublisher>>,
+ worker_id: String,
metrics: Arc<MetricsRegistry>,
latency_tracker: Arc<Mutex<LatencyTracker>>,
tokenizer_registry: Arc<TokenizerRegistry>,
@@ -387,9 +440,10 @@ impl Dispatcher {
);
Self {
backend,
- ipc,
+ worker_pool,
payload_store,
publisher,
+ worker_id,
metrics,
latency_tracker,
batch_semaphore: Arc::new(Semaphore::new(default_max_concurrent_batches())),
@@ -421,15 +475,15 @@ impl Dispatcher {
worker_direct && operation != "generate" && self.batch_cancel_state.is_cancelled(request_id)
}
- async fn ack_cancelled_worker_direct_batch(&self, wi: &WorkItem, msg: &Message) {
+ async fn ack_cancelled_worker_direct_batch(&self, wi: &WorkItem, delivery: &Delivery) {
debug!(
request_id = %wi.request_id,
work_item_id = %wi.work_item_id,
operation = %wi.operation,
- subject = %msg.subject,
+ origin = %delivery.log_ref(),
"batch-direct: ACKing cancelled worker-direct item"
);
- match ack(msg).await {
+ match ack(delivery).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(error = %e, "ack failed on cancelled worker-direct batch item");
@@ -460,8 +514,11 @@ fn unknown_bundle_config_hash<'a>(
impl Dispatcher {
/// Process a full fetched batch.
///
- /// Returns after every message has either been ACKed (we published a
- /// result) or NAKed (we'll see it again).
+ /// Legacy op handlers return after every message has either been ACKed
+ /// (we published a result) or NAKed (we'll see it again). Scheduler-routed
+ /// handlers return after enqueue, but any pull-loop admission permit
+ /// rides the item's [`Delivery`] (inside [`SchedulerMeta`]) until the
+ /// scheduler/backend path settles it.
///
/// Model-id routing: derived from the NATS **subject**, falling back
/// to `WorkItem.model_id` when the subject is malformed. On
@@ -474,7 +531,7 @@ impl Dispatcher {
/// avoid ACK-timeout storms.
/// * within a model, encode/score/extract run concurrently via
/// `tokio::join!` so slow payload fetches don't block other ops.
- pub async fn handle_batch(self: &Arc<Self>, messages: Vec<Message>) {
+ pub(crate) async fn handle_batch(self: &Arc<Self>, messages: Vec<QueuedMessage>) {
let batch_started = Instant::now();
let batch_size = messages.len();
self.metrics
@@ -483,8 +540,12 @@ impl Dispatcher {
info!(batch_size, "handle_batch: start");
let base_delay_ms = base_nak_delay_ms();
- let mut decoded: Vec<(WorkItem, Message)> = Vec::with_capacity(batch_size);
- for msg in messages {
+ let mut decoded: Vec<(WorkItem, Delivery)> = Vec::with_capacity(batch_size);
+ for queued in messages {
+ // The admission permit moves into the [`Delivery`] here: every
+ // reject path below settles (ACK/NAK) and drops it immediately,
+ // and successful decodes carry it until downstream settlement.
+ let (msg, admission_permit) = queued.into_parts();
// Record JetStream delivery count so operators can spot hot
// redelivery (which usually means a worker is hitting ack_wait).
// `info()` returns Ok for pull-based messages; core NATS messages
@@ -512,7 +573,12 @@ impl Dispatcher {
subject = %msg.subject,
"could not extract model_id from subject — NAKing for redelivery",
);
- nak_one(&msg, base_delay_ms, &self.metrics).await;
+ nak_one(
+ &Delivery::Nats(msg, admission_permit),
+ base_delay_ms,
+ &self.metrics,
+ )
+ .await;
continue;
}
};
@@ -526,7 +592,7 @@ impl Dispatcher {
reply_subject = %truncate(&wi.reply_subject, 60),
"rejecting WorkItem with suspicious reply_subject — ACKing to drop",
);
- match ack(&msg).await {
+ match ack(&Delivery::Nats(msg, admission_permit)).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(error = %e, "ack failed on drop");
@@ -541,7 +607,11 @@ impl Dispatcher {
&wi.operation,
worker_direct,
) {
- self.ack_cancelled_worker_direct_batch(&wi, &msg).await;
+ self.ack_cancelled_worker_direct_batch(
+ &wi,
+ &Delivery::Nats(msg, admission_permit),
+ )
+ .await;
continue;
}
if let Some(gate) = self.pool_admission.as_ref() {
@@ -558,7 +628,12 @@ impl Dispatcher {
.pool_admission_naks_total
.with_label_values(&["logical_pool_not_assigned"])
.inc();
- nak_one(&msg, base_delay_ms, &self.metrics).await;
+ nak_one(
+ &Delivery::Nats(msg, admission_permit),
+ base_delay_ms,
+ &self.metrics,
+ )
+ .await;
continue;
}
}
@@ -572,7 +647,7 @@ impl Dispatcher {
);
wi.model_id = subject_model;
}
- decoded.push((wi, msg));
+ decoded.push((wi, Delivery::Nats(msg, admission_permit)));
}
Err(e) => {
// NAK so JetStream redelivers (possibly to a worker on a
@@ -580,7 +655,12 @@ impl Dispatcher {
// max_deliver. ACK-dropping would silently discard the
// item on a transient msgpack glitch.
warn!(error = %e, subject = %msg.subject, "failed to decode WorkItem — NAKing for redelivery");
- nak_one(&msg, base_delay_ms, &self.metrics).await;
+ nak_one(
+ &Delivery::Nats(msg, admission_permit),
+ base_delay_ms,
+ &self.metrics,
+ )
+ .await;
}
}
}
@@ -592,14 +672,50 @@ impl Dispatcher {
);
return;
}
+ self.dispatch_decoded(decoded, batch_size, batch_started)
+ .await;
+ }
+ /// Dispatch already-decoded `(WorkItem, Delivery)` pairs — the shared
+ /// tail of [`Self::handle_batch`], also fed directly by the local-ingest
+ /// server (P2.10, §4.6) whose items arrive pre-decoded over the UDS
+ /// rather than as NATS messages. Both ingest paths coalesce in the same
+ /// per-model scheduler batch assembly downstream.
+ pub async fn dispatch_decoded(
+ self: &Arc<Self>,
+ decoded: Vec<(WorkItem, Delivery)>,
+ batch_size: usize,
+ batch_started: Instant,
+ ) {
let mut generate_items = Vec::new();
let mut regular_items = Vec::with_capacity(decoded.len());
- for (wi, msg) in decoded {
+ for (wi, delivery) in decoded {
if wi.operation == "generate" {
- generate_items.push((wi, msg));
+ match delivery {
+ // Generation bypasses the scheduler; re-bundle the permit
+ // with the message so intake capacity stays held until
+ // the generate task settles the delivery.
+ Delivery::Nats(msg, permit) => {
+ generate_items.push((wi, QueuedMessage::new(msg, permit)))
+ }
+ delivery @ Delivery::Local(_) => {
+ // Generation streams chunk envelopes over NATS reply
+ // subjects; the local-ingest publish_work op is
+ // one-shot (PROTOCOL.md v0.1 — streaming ops land
+ // with P2.6). Answer a typed error instead of
+ // silently sinking the item.
+ let _ = self
+ .publish_error(
+ &wi,
+ &delivery,
+ "bad_operation",
+ "generate is not supported on the local-ingest lane (P2.6)",
+ )
+ .await;
+ }
+ }
} else {
- regular_items.push((wi, msg));
+ regular_items.push((wi, delivery));
}
}
let generate_count = generate_items.len();
@@ -629,9 +745,14 @@ impl Dispatcher {
return;
}
};
- this.metrics.inflight_batches.inc();
+ let count_model_group_inflight = this.scheduler_registry.is_none();
+ if count_model_group_inflight {
+ this.metrics.inflight_batches.inc();
+ }
let result = this.handle_model_group(&model_id, items).await;
- this.metrics.inflight_batches.dec();
+ if count_model_group_inflight {
+ this.metrics.inflight_batches.dec();
+ }
drop(permit);
if let Err(e) = result {
warn!(model = %model_id, error = %ErrChain(&e), "model group handling failed");
@@ -647,7 +768,7 @@ impl Dispatcher {
);
}
- async fn spawn_generate_items(self: &Arc<Self>, items: Vec<(WorkItem, Message)>) {
+ async fn spawn_generate_items(self: &Arc<Self>, items: Vec<(WorkItem, QueuedMessage)>) {
let mut handles = self.generation_handles.lock().await;
handles.retain(|h| !h.is_finished());
for (wi, msg) in items {
@@ -658,7 +779,7 @@ impl Dispatcher {
}
}
- async fn handle_generate_item(self: Arc<Self>, mut wi: WorkItem, msg: Message) {
+ async fn handle_generate_item(self: Arc<Self>, mut wi: WorkItem, msg: QueuedMessage) {
let model_id = wi.model_id.clone();
let delivery = DeliveryContext::from_message(&msg);
let model_lbl = self.metrics.model_label(&model_id).into_owned();
@@ -700,7 +821,7 @@ impl Dispatcher {
error = %ErrChain(&e),
"EnsureModelReady failed for generate — NAKing"
);
- nak_one(&msg, nak_delay_for_backend_error(&e), &self.metrics).await;
+ nak_msg(&msg, nak_delay_for_backend_error(&e), &self.metrics).await;
return;
}
};
@@ -727,7 +848,7 @@ impl Dispatcher {
.publish_generate_terminal_error(&wi, MODEL_LOADING_ERROR_CODE, &message)
.await
{
- Ok(_) => match ack(&msg).await {
+ Ok(_) => match ack_msg(&msg).await {
Ok(()) => {
self.metrics.messages_acked_total.inc();
self.metrics
@@ -765,7 +886,7 @@ impl Dispatcher {
.generate_model_loading_responses_total
.with_label_values(&[&model_lbl, "loading_started", "publish_failed"])
.inc();
- nak_one(&msg, base_delay_ms, &self.metrics).await;
+ nak_msg(&msg, base_delay_ms, &self.metrics).await;
}
}
return;
@@ -786,7 +907,7 @@ impl Dispatcher {
pending = delivery.pending,
"generate model retry requested — NAKing"
);
- nak_one(&msg, base_delay_ms, &self.metrics).await;
+ nak_msg(&msg, base_delay_ms, &self.metrics).await;
return;
}
ReadinessState::LoadingInProgress => {
@@ -812,7 +933,7 @@ impl Dispatcher {
.publish_generate_terminal_error(&wi, MODEL_LOADING_ERROR_CODE, &message)
.await
{
- Ok(_) => match ack(&msg).await {
+ Ok(_) => match ack_msg(&msg).await {
Ok(()) => {
self.metrics.messages_acked_total.inc();
self.metrics
@@ -854,7 +975,7 @@ impl Dispatcher {
"publish_failed",
])
.inc();
- nak_one(&msg, delay_ms, &self.metrics).await;
+ nak_msg(&msg, delay_ms, &self.metrics).await;
}
}
return;
@@ -863,7 +984,7 @@ impl Dispatcher {
// Resolve an offloaded generate payload. The gateway offloads large
// vision work items to the object store (``payload_ref`` set,
- // ``generate`` blanked); fetch + inline so the Python worker — which
+ // ``generate`` blanked); fetch + inline so the adapter worker — which
// has no object-store access — receives a self-contained WorkItem. The
// blob is base64-string image data, so it decodes cleanly as
// ``serde_json::Value`` (msgpack ``bin`` would not).
@@ -890,7 +1011,7 @@ impl Dispatcher {
"failed to decode offloaded generate payload — publishing error + ACK"
);
match self
- .publish_error(
+ .publish_error_generate(
&wi,
"internal_error",
"failed to decode offloaded generate payload",
@@ -898,7 +1019,7 @@ impl Dispatcher {
)
.await
{
- Ok(_) => match ack(&msg).await {
+ Ok(_) => match ack_msg(&msg).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(
@@ -913,7 +1034,7 @@ impl Dispatcher {
self.metrics.jetstream_ack_failures_total.inc();
}
},
- Err(_) => nak_one(&msg, base_delay_ms, &self.metrics).await,
+ Err(_) => nak_msg(&msg, base_delay_ms, &self.metrics).await,
}
return;
}
@@ -933,7 +1054,7 @@ impl Dispatcher {
error = %e,
"failed to resolve offloaded generate payload — NAKing"
);
- nak_one(&msg, base_delay_ms, &self.metrics).await;
+ nak_msg(&msg, base_delay_ms, &self.metrics).await;
return;
}
}
@@ -957,7 +1078,7 @@ impl Dispatcher {
"failed to re-encode generate WorkItem — publishing error + ACK"
);
match self
- .publish_error(
+ .publish_error_generate(
&wi,
"internal_error",
"failed to encode generate work item",
@@ -965,7 +1086,7 @@ impl Dispatcher {
)
.await
{
- Ok(_) => match ack(&msg).await {
+ Ok(_) => match ack_msg(&msg).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(
@@ -980,12 +1101,22 @@ impl Dispatcher {
self.metrics.jetstream_ack_failures_total.inc();
}
},
- Err(_) => nak_one(&msg, base_delay_ms, &self.metrics).await,
+ Err(_) => nak_msg(&msg, base_delay_ms, &self.metrics).await,
}
return;
}
};
+ let Some(publisher) = self.publisher.clone() else {
+ // Unreachable by construction: generate items only arrive here
+ // as NATS deliveries, and `run()` always wires the publisher.
+ warn!(
+ work_item_id = %wi.work_item_id,
+ "generate item without a NATS publisher — NAKing"
+ );
+ nak_msg(&msg, base_delay_ms, &self.metrics).await;
+ return;
+ };
let settled = Arc::new(AtomicBool::new(false));
let msg = Arc::new(msg);
let delivery_log = Arc::new(GenerateDeliveryLogContext {
@@ -994,13 +1125,13 @@ impl Dispatcher {
model_id: model_id.clone(),
delivery,
});
- let publisher = Arc::clone(&self.publisher);
let metrics = Arc::clone(&self.metrics);
let settled_for_events = Arc::clone(&settled);
let msg_for_events = Arc::clone(&msg);
let delivery_log_for_events = Arc::clone(&delivery_log);
+ self.metrics.inflight_batches.inc();
let result = self
- .ipc
+ .worker_pool
.process_generate(
ProcessGenerateRequest {
model_id: model_id.clone(),
@@ -1020,6 +1151,7 @@ impl Dispatcher {
},
)
.await;
+ decrement_gauge(&self.metrics.inflight_batches, 1);
match result {
Ok(()) => {
@@ -1037,7 +1169,7 @@ impl Dispatcher {
pending = delivery_log.delivery.pending,
"ProcessGenerate ended without ACK/NAK event — NAKing"
);
- nak_one(&msg, base_delay_ms, &self.metrics).await;
+ nak_msg(&msg, base_delay_ms, &self.metrics).await;
}
}
Err(e) => {
@@ -1056,7 +1188,7 @@ impl Dispatcher {
"ProcessGenerate failed — NAKing if unsettled"
);
if !settled.swap(true, Ordering::SeqCst) {
- nak_one(&msg, base_delay_ms, &self.metrics).await;
+ nak_msg(&msg, base_delay_ms, &self.metrics).await;
}
}
}
@@ -1065,7 +1197,7 @@ impl Dispatcher {
async fn handle_model_group(
self: &Arc<Self>,
model_id: &str,
- items: Vec<(WorkItem, Message)>,
+ items: Vec<(WorkItem, Delivery)>,
) -> Result<(), DispatchError> {
let group_started = Instant::now();
let group_size = items.len();
@@ -1201,28 +1333,23 @@ impl Dispatcher {
let mut encode_items = Vec::new();
let mut score_items = Vec::new();
let mut extract_items = Vec::new();
- let mut unknown_items: Vec<(WorkItem, Message)> = Vec::new();
- for (wi, msg) in dispatch {
+ let mut unknown_items: Vec<(WorkItem, Delivery)> = Vec::new();
+ for (wi, delivery) in dispatch {
match wi.operation.as_str() {
- "encode" => encode_items.push((wi, msg)),
- "score" => score_items.push((wi, msg)),
- "extract" => extract_items.push((wi, msg)),
- _ => unknown_items.push((wi, msg)),
+ "encode" => encode_items.push((wi, delivery)),
+ "score" => score_items.push((wi, delivery)),
+ "extract" => extract_items.push((wi, delivery)),
+ _ => unknown_items.push((wi, delivery)),
}
}
- for (wi, msg) in &unknown_items {
+ for (wi, delivery) in &unknown_items {
warn!(op = %wi.operation, "unknown operation — publishing error + ACK");
match self
- .publish_error(
- wi,
- "bad_operation",
- "unknown operation",
- is_worker_direct_work_subject(&msg.subject),
- )
+ .publish_error(wi, delivery, "bad_operation", "unknown operation")
.await
{
- Ok(_) => match ack(msg).await {
+ Ok(_) => match ack(delivery).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(error = %e, "ack after bad_operation error-publish failed");
@@ -1234,7 +1361,7 @@ impl Dispatcher {
// and we get another chance to either succeed or hit
// max_deliver → DLQ (preserves the failure rather
// than silently dropping it).
- nak_one(msg, base_nak_delay_ms(), &self.metrics).await;
+ nak_one(delivery, base_nak_delay_ms(), &self.metrics).await;
}
}
}
@@ -1319,7 +1446,7 @@ impl Dispatcher {
async fn handle_encode(
&self,
model_id: &str,
- items: Vec<(WorkItem, Message)>,
+ items: Vec<(WorkItem, Delivery)>,
) -> Result<(), DispatchError> {
let model_lbl = self.metrics.model_label(model_id);
let _timer = self
@@ -1327,8 +1454,9 @@ impl Dispatcher {
.pull_batch_process_seconds
.with_label_values(&[&model_lbl, "encode"])
.start_timer();
- let mut resolved: Vec<(WorkItem, Message, MsgValue, f64)> = Vec::with_capacity(items.len());
- for (wi, msg) in items {
+ let mut resolved: Vec<(WorkItem, Delivery, MsgValue, f64)> =
+ Vec::with_capacity(items.len());
+ for (wi, delivery) in items {
let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
Ok(v) => v,
Err(e) => {
@@ -1340,15 +1468,10 @@ impl Dispatcher {
"failed to resolve encode item"
);
match self
- .publish_error(
- &wi,
- "payload_error",
- "failed to resolve item",
- is_worker_direct_work_subject(&msg.subject),
- )
+ .publish_error(&wi, &delivery, "payload_error", "failed to resolve item")
.await
{
- Ok(_) => match ack(&msg).await {
+ Ok(_) => match ack(&delivery).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(error = %e, "ack after error-publish failed");
@@ -1360,13 +1483,13 @@ impl Dispatcher {
// gives another attempt (or surfaces the
// error later). Swallowed publish errors
// would otherwise silently drop the item.
- nak_one(&msg, base_nak_delay_ms(), &self.metrics).await;
+ nak_one(&delivery, base_nak_delay_ms(), &self.metrics).await;
}
}
continue;
}
};
- resolved.push((wi, msg, item_json, fetch_ms));
+ resolved.push((wi, delivery, item_json, fetch_ms));
}
if resolved.is_empty() {
return Ok(());
@@ -1415,7 +1538,7 @@ impl Dispatcher {
batch_size = resolved.len(),
"ProcessEncodeBatch failed — NAKing group"
);
- let msgs_only: Vec<(WorkItem, Message)> =
+ let msgs_only: Vec<(WorkItem, Delivery)> =
resolved.into_iter().map(|(wi, m, _, _)| (wi, m)).collect();
nak_all(&msgs_only, delay, &self.metrics).await;
return Err(e.into());
@@ -1438,7 +1561,7 @@ impl Dispatcher {
async fn handle_score(
&self,
model_id: &str,
- items: Vec<(WorkItem, Message)>,
+ items: Vec<(WorkItem, Delivery)>,
) -> Result<(), DispatchError> {
let model_lbl = self.metrics.model_label(model_id);
let _timer = self
@@ -1446,9 +1569,9 @@ impl Dispatcher {
.pull_batch_process_seconds
.with_label_values(&[&model_lbl, "score"])
.start_timer();
- let mut prepared: Vec<(WorkItem, Message, MsgValue, Vec<MsgValue>, f64)> =
+ let mut prepared: Vec<(WorkItem, Delivery, MsgValue, Vec<MsgValue>, f64)> =
Vec::with_capacity(items.len());
- for (wi, msg) in items {
+ for (wi, delivery) in items {
let (query, score_items, fetch_ms) = match self.resolve_score(&wi).await {
Ok(v) => v,
Err(e) => {
@@ -1462,13 +1585,13 @@ impl Dispatcher {
match self
.publish_error(
&wi,
+ &delivery,
"payload_error",
"failed to resolve score payload",
- is_worker_direct_work_subject(&msg.subject),
)
.await
{
- Ok(_) => match ack(&msg).await {
+ Ok(_) => match ack(&delivery).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(error = %e, "ack after error-publish failed");
@@ -1476,13 +1599,13 @@ impl Dispatcher {
}
},
Err(_) => {
- nak_one(&msg, base_nak_delay_ms(), &self.metrics).await;
+ nak_one(&delivery, base_nak_delay_ms(), &self.metrics).await;
}
}
continue;
}
};
- prepared.push((wi, msg, query, score_items, fetch_ms));
+ prepared.push((wi, delivery, query, score_items, fetch_ms));
}
if prepared.is_empty() {
return Ok(());
@@ -1534,7 +1657,7 @@ impl Dispatcher {
batch_size = prepared.len(),
"ProcessScoreBatch failed — NAKing group"
);
- let msgs_only: Vec<(WorkItem, Message)> = prepared
+ let msgs_only: Vec<(WorkItem, Delivery)> = prepared
.into_iter()
.map(|(wi, m, _, _, _)| (wi, m))
.collect();
@@ -1559,7 +1682,7 @@ impl Dispatcher {
async fn handle_extract(
&self,
model_id: &str,
- items: Vec<(WorkItem, Message)>,
+ items: Vec<(WorkItem, Delivery)>,
) -> Result<(), DispatchError> {
let model_lbl = self.metrics.model_label(model_id);
let _timer = self
@@ -1567,8 +1690,9 @@ impl Dispatcher {
.pull_batch_process_seconds
.with_label_values(&[&model_lbl, "extract"])
.start_timer();
- let mut resolved: Vec<(WorkItem, Message, MsgValue, f64)> = Vec::with_capacity(items.len());
- for (wi, msg) in items {
+ let mut resolved: Vec<(WorkItem, Delivery, MsgValue, f64)> =
+ Vec::with_capacity(items.len());
+ for (wi, delivery) in items {
let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
Ok(v) => v,
Err(e) => {
@@ -1580,15 +1704,10 @@ impl Dispatcher {
"failed to resolve extract item"
);
match self
- .publish_error(
- &wi,
- "payload_error",
- "failed to resolve item",
- is_worker_direct_work_subject(&msg.subject),
- )
+ .publish_error(&wi, &delivery, "payload_error", "failed to resolve item")
.await
{
- Ok(_) => match ack(&msg).await {
+ Ok(_) => match ack(&delivery).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(error = %e, "ack after error-publish failed");
@@ -1596,13 +1715,13 @@ impl Dispatcher {
}
},
Err(_) => {
- nak_one(&msg, base_nak_delay_ms(), &self.metrics).await;
+ nak_one(&delivery, base_nak_delay_ms(), &self.metrics).await;
}
}
continue;
}
};
- resolved.push((wi, msg, item_json, fetch_ms));
+ resolved.push((wi, delivery, item_json, fetch_ms));
}
if resolved.is_empty() {
return Ok(());
@@ -1647,7 +1766,7 @@ impl Dispatcher {
batch_size = resolved.len(),
"ProcessExtractBatch failed — NAKing group"
);
- let msgs_only: Vec<(WorkItem, Message)> =
+ let msgs_only: Vec<(WorkItem, Delivery)> =
resolved.into_iter().map(|(wi, m, _, _)| (wi, m)).collect();
nak_all(&msgs_only, delay, &self.metrics).await;
return Err(e.into());
@@ -1679,7 +1798,11 @@ impl Dispatcher {
// -- outcome / publish helpers ---------------------------------------
- async fn apply_outcomes(&self, outcome: BatchOutcome, resolved: Vec<(WorkItem, Message, f64)>) {
+ async fn apply_outcomes(
+ &self,
+ outcome: BatchOutcome,
+ resolved: Vec<(WorkItem, Delivery, f64)>,
+ ) {
// Decide which index (if any) each outcome binds to, using the
// pure `resolve_outcome_indices` helper. Indices are into
// `resolved`; `None` means "ghost outcome, no matching item".
@@ -1692,7 +1815,7 @@ impl Dispatcher {
outcome.outcomes.iter().map(|o| o.work_item_id.as_str()),
);
- let mut resolved: Vec<Option<(WorkItem, Message, f64)>> =
+ let mut resolved: Vec<Option<(WorkItem, Delivery, f64)>> =
resolved.into_iter().map(Some).collect();
for (outcome_idx, item_outcome) in outcome.outcomes.into_iter().enumerate() {
@@ -1703,40 +1826,31 @@ impl Dispatcher {
);
continue;
};
- let Some((wi, msg, fetch_ms)) = resolved[idx].take() else {
+ let Some((wi, delivery, fetch_ms)) = resolved[idx].take() else {
continue;
};
- self.apply_outcome(&wi, &msg, &item_outcome, fetch_ms).await;
+ self.apply_outcome(&wi, &delivery, &item_outcome, fetch_ms)
+ .await;
}
// Any messages left without a corresponding outcome: the executor
// dropped them. NAK so they get redelivered.
for slot in resolved.iter_mut() {
- let Some((_wi, msg, _fm)) = slot.take() else {
+ let Some((_wi, delivery, _fm)) = slot.take() else {
continue;
};
warn!(
- subject = %msg.subject,
+ origin = %delivery.log_ref(),
"no outcome from executor — NAKing"
);
- if let Err(e) = msg
- .ack_with(async_nats::jetstream::AckKind::Nak(Some(
- std::time::Duration::from_millis(base_nak_delay_ms()),
- )))
- .await
- {
- warn!(error = %e, "NAK failed");
- self.metrics.jetstream_nak_failures_total.inc();
- } else {
- self.metrics.messages_naked_total.inc();
- }
+ nak_one(&delivery, base_nak_delay_ms(), &self.metrics).await;
}
}
async fn apply_outcome(
&self,
wi: &WorkItem,
- msg: &Message,
+ delivery: &Delivery,
outcome: &ItemOutcome,
payload_fetch_ms: f64,
) {
@@ -1748,16 +1862,7 @@ impl Dispatcher {
queue_ms,
payload_fetch_ms,
});
- match self
- .publisher
- .publish_result(
- &wi.reply_subject,
- outcome,
- timings,
- is_worker_direct_work_subject(&msg.subject),
- )
- .await
- {
+ match self.deliver_result(wi, delivery, outcome, timings).await {
Ok(()) => {
// Record latency only on the success path —
// sampling error-path latency would bias the
@@ -1855,7 +1960,7 @@ impl Dispatcher {
}
}
}
- match ack(msg).await {
+ match ack(delivery).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(error = %e, "ack failed");
@@ -1864,24 +1969,74 @@ impl Dispatcher {
}
}
Disposition::NakRetry => {
- let delay = std::time::Duration::from_millis(
+ nak_one(
+ delivery,
outcome.nak_delay_ms.unwrap_or_else(base_nak_delay_ms),
- );
- match msg
- .ack_with(async_nats::jetstream::AckKind::Nak(Some(delay)))
+ &self.metrics,
+ )
+ .await;
+ }
+ }
+ }
+
+ /// Route one publishable outcome to its delivery-appropriate result
+ /// sink: NATS reply-subject publish for [`Delivery::Nats`] (verbatim
+ /// legacy behaviour, including the fire-and-forget empty-reply-subject
+ /// contract), or an in-process [`crate::delivery::LocalDeliveryEvent`]
+ /// for [`Delivery::Local`] — same `WorkResult` bytes either way via
+ /// [`shape_and_build_work_result`].
+ async fn deliver_result(
+ &self,
+ wi: &WorkItem,
+ delivery: &Delivery,
+ outcome: &ItemOutcome,
+ timings: Option<Timings>,
+ ) -> Result<(), crate::publisher::PublishError> {
+ match delivery {
+ Delivery::Nats(..) => {
+ let Some(publisher) = self.publisher.as_ref() else {
+ // Unreachable by construction (`run()` wires NATS +
+ // publisher together); keep the item redeliverable
+ // rather than sinking it if the invariant ever breaks.
+ warn!(
+ work_item_id = %wi.work_item_id,
+ "NATS delivery without a publisher — skipping publish"
+ );
+ return Err(crate::publisher::PublishError::NoPublisher);
+ };
+ publisher
+ .publish_result(
+ &wi.reply_subject,
+ outcome,
+ timings,
+ delivery.worker_direct(),
+ )
.await
- {
- Ok(()) => self.metrics.messages_naked_total.inc(),
- Err(e) => {
- warn!(error = %e, "nak failed");
- self.metrics.jetstream_nak_failures_total.inc();
- }
+ }
+ Delivery::Local(local) => {
+ // reply_subject is NATS-only; local results always ride the
+ // ingest socket back to the caller that is awaiting them.
+ let result = shape_and_build_work_result(
+ outcome,
+ &self.worker_id,
+ timings,
+ delivery.worker_direct(),
+ );
+ if !local.send_result(result) {
+ debug!(
+ work_item_id = %wi.work_item_id,
+ origin = %delivery.log_ref(),
+ "local ingest caller gone — dropping WorkResult"
+ );
}
+ Ok(())
}
}
}
- /// Publish a synthetic error `WorkResult` on `wi.reply_subject`.
+ /// Publish a synthetic error `WorkResult` on `wi.reply_subject`
+ /// ([`Delivery::Nats`]) or straight to the local ingest caller
+ /// ([`Delivery::Local`]).
///
/// Returns:
/// * `Ok(true)` — published (or fire-and-forget: empty reply_subject).
@@ -1893,38 +2048,55 @@ impl Dispatcher {
/// to give another worker (or this one, later) a chance to surface
/// the failure.
async fn publish_error(
+ &self,
+ wi: &WorkItem,
+ delivery: &Delivery,
+ code: &str,
+ message: &str,
+ ) -> Result<bool, crate::publisher::PublishError> {
+ let outcome = synthetic_error_outcome(wi, code, message);
+ match self.deliver_result(wi, delivery, &outcome, None).await {
+ Ok(()) => Ok(true),
+ Err(crate::publisher::PublishError::EmptyReplySubject) => {
+ // Fire-and-forget work item. No one is waiting for the
+ // error; ACKing lets JetStream drop it on the floor,
+ // which is the right behaviour.
+ debug!(work_item_id = %wi.work_item_id, "skipping error publish — empty reply_subject");
+ Ok(true)
+ }
+ Err(e) => {
+ warn!(
+ work_item_id = %wi.work_item_id,
+ error = %e,
+ "failed to publish error WorkResult"
+ );
+ Err(e)
+ }
+ }
+ }
+
+ /// Generate-path twin of [`Self::publish_error`]. The generate flow is
+ /// NATS-only (local-ingest generate items are rejected before reaching
+ /// it, see [`Self::dispatch_decoded`]) and holds its [`Message`] in an
+ /// `Arc` for the event stream, so it cannot wrap one into a
+ /// [`Delivery`]; publish straight through the NATS publisher.
+ async fn publish_error_generate(
&self,
wi: &WorkItem,
code: &str,
message: &str,
worker_direct: bool,
) -> Result<bool, crate::publisher::PublishError> {
- // Synthetic outcome so we reuse the publisher encoder. No timings:
- // error-only publishes omit queue_ms / processing_ms / payload_fetch_ms.
- let outcome = ItemOutcome {
- work_item_id: wi.work_item_id.clone(),
- request_id: wi.request_id.clone(),
- item_index: wi.item_index,
- disposition: Disposition::PublishErrorAndAck,
- nak_delay_ms: None,
- result_msgpack: Vec::new(),
- error: Some(message.to_string()),
- error_code: Some(code.to_string()),
- inference_ms: None,
- tokenization_ms: None,
- postprocessing_ms: None,
- raw_output: None,
+ let Some(publisher) = self.publisher.as_ref() else {
+ return Err(crate::publisher::PublishError::NoPublisher);
};
- match self
- .publisher
+ let outcome = synthetic_error_outcome(wi, code, message);
+ match publisher
.publish_result(&wi.reply_subject, &outcome, None, worker_direct)
.await
{
Ok(()) => Ok(true),
Err(crate::publisher::PublishError::EmptyReplySubject) => {
- // Fire-and-forget work item. No one is waiting for the
- // error; ACKing lets JetStream drop it on the floor,
- // which is the right behaviour.
debug!(work_item_id = %wi.work_item_id, "skipping error publish — empty reply_subject");
Ok(true)
}
@@ -1958,8 +2130,11 @@ impl Dispatcher {
);
return Ok(true);
}
+ let Some(publisher) = self.publisher.as_ref() else {
+ return Err(crate::publisher::PublishError::NoPublisher);
+ };
let payload = encode_generate_terminal_error_chunk(wi, code, message)?;
- match self.publisher.publish_raw(&wi.reply_subject, payload).await {
+ match publisher.publish_raw(&wi.reply_subject, payload).await {
Ok(()) => Ok(true),
Err(crate::publisher::PublishError::EmptyReplySubject) => {
debug!(
@@ -2060,18 +2235,14 @@ impl Dispatcher {
&self,
model_id: &str,
scheduler: &Arc<ProductionScheduler>,
- items: Vec<(WorkItem, Message)>,
+ items: Vec<(WorkItem, Delivery)>,
) {
- self.metrics
- .scheduler
- .enqueued_items_total
- .with_label_values(&[&self.metrics.model_label(model_id), "encode"])
- .inc_by(items.len() as u64);
- for (wi, msg) in items {
+ let mut grouped: HashMap<LoraKey, Vec<(SchedulerItem, SchedulerMeta)>> = HashMap::new();
+ for (wi, delivery) in items {
let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
Ok(v) => v,
Err(e) => {
- self.fail_resolve(&wi, &msg, &e, "failed to resolve encode item")
+ self.fail_resolve(&wi, &delivery, &e, "failed to resolve encode item")
.await;
continue;
}
@@ -2094,10 +2265,24 @@ impl Dispatcher {
payload_fetch_ms: fetch_ms,
prepared_tokens,
};
- let worker_direct = is_worker_direct_work_subject(&msg.subject);
- let meta = SchedulerMeta::new_with_worker_direct(wi, msg, fetch_ms, worker_direct);
+ let item = SchedulerItem::Encode(ebi);
+ let child_index = self.record_scheduler_enqueue(model_id, &item);
+ let worker_direct = delivery.worker_direct();
+ let meta = SchedulerMeta::new_with_worker_direct(wi, delivery, fetch_ms, worker_direct)
+ .with_worker_child_index(child_index);
+ grouped.entry(lora).or_default().push((item, meta));
+ }
+ let enqueued = grouped.values().map(Vec::len).sum::<usize>();
+ if enqueued > 0 {
+ self.metrics
+ .scheduler
+ .enqueued_items_total
+ .with_label_values(&[&self.metrics.model_label(model_id), "encode"])
+ .inc_by(enqueued as u64);
+ }
+ for (lora, grouped_items) in grouped {
scheduler
- .submit(SchedOp::Encode, lora, SchedulerItem::Encode(ebi), meta)
+ .submit_many(SchedOp::Encode, lora, grouped_items)
.await;
}
}
@@ -2115,23 +2300,18 @@ impl Dispatcher {
&self,
model_id: &str,
scheduler: &Arc<ProductionScheduler>,
- items: Vec<(WorkItem, Message)>,
+ items: Vec<(WorkItem, Delivery)>,
) {
- self.metrics
- .scheduler
- .enqueued_items_total
- .with_label_values(&[&self.metrics.model_label(model_id), "score"])
- .inc_by(items.len() as u64);
- for (wi, msg) in items {
+ let mut grouped: Vec<(SchedulerItem, SchedulerMeta)> = Vec::new();
+ for (wi, delivery) in items {
let (query, score_items, fetch_ms) = match self.resolve_score(&wi).await {
Ok(v) => v,
Err(e) => {
- self.fail_resolve(&wi, &msg, &e, "failed to resolve score payload")
+ self.fail_resolve(&wi, &delivery, &e, "failed to resolve score payload")
.await;
continue;
}
};
- let lora = lora_from_options(&wi.options);
let sbi = ScoreBatchItem {
work_item_id: wi.work_item_id.clone(),
request_id: wi.request_id.clone(),
@@ -2146,10 +2326,21 @@ impl Dispatcher {
payload_fetch_ms: fetch_ms,
prepared_tokens: None,
};
- let worker_direct = is_worker_direct_work_subject(&msg.subject);
- let meta = SchedulerMeta::new_with_worker_direct(wi, msg, fetch_ms, worker_direct);
+ let item = SchedulerItem::Score(sbi);
+ let child_index = self.record_scheduler_enqueue(model_id, &item);
+ let worker_direct = delivery.worker_direct();
+ let meta = SchedulerMeta::new_with_worker_direct(wi, delivery, fetch_ms, worker_direct)
+ .with_worker_child_index(child_index);
+ grouped.push((item, meta));
+ }
+ if !grouped.is_empty() {
+ self.metrics
+ .scheduler
+ .enqueued_items_total
+ .with_label_values(&[&self.metrics.model_label(model_id), "score"])
+ .inc_by(grouped.len() as u64);
scheduler
- .submit(SchedOp::Score, lora, SchedulerItem::Score(sbi), meta)
+ .submit_many(SchedOp::Score, LoraKey::base(), grouped)
.await;
}
}
@@ -2163,18 +2354,14 @@ impl Dispatcher {
&self,
model_id: &str,
scheduler: &Arc<ProductionScheduler>,
- items: Vec<(WorkItem, Message)>,
+ items: Vec<(WorkItem, Delivery)>,
) {
- self.metrics
- .scheduler
- .enqueued_items_total
- .with_label_values(&[&self.metrics.model_label(model_id), "extract"])
- .inc_by(items.len() as u64);
- for (wi, msg) in items {
+ let mut grouped: HashMap<LoraKey, Vec<(SchedulerItem, SchedulerMeta)>> = HashMap::new();
+ for (wi, delivery) in items {
let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
Ok(v) => v,
Err(e) => {
- self.fail_resolve(&wi, &msg, &e, "failed to resolve extract item")
+ self.fail_resolve(&wi, &delivery, &e, "failed to resolve extract item")
.await;
continue;
}
@@ -2195,21 +2382,49 @@ impl Dispatcher {
bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
payload_fetch_ms: fetch_ms,
};
- let worker_direct = is_worker_direct_work_subject(&msg.subject);
- let meta = SchedulerMeta::new_with_worker_direct(wi, msg, fetch_ms, worker_direct);
+ let item = SchedulerItem::Extract(xbi);
+ let child_index = self.record_scheduler_enqueue(model_id, &item);
+ let worker_direct = delivery.worker_direct();
+ let meta = SchedulerMeta::new_with_worker_direct(wi, delivery, fetch_ms, worker_direct)
+ .with_worker_child_index(child_index);
+ grouped.entry(lora).or_default().push((item, meta));
+ }
+ let enqueued = grouped.values().map(Vec::len).sum::<usize>();
+ if enqueued > 0 {
+ self.metrics
+ .scheduler
+ .enqueued_items_total
+ .with_label_values(&[&self.metrics.model_label(model_id), "extract"])
+ .inc_by(enqueued as u64);
+ }
+ for (lora, grouped_items) in grouped {
scheduler
- .submit(SchedOp::Extract, lora, SchedulerItem::Extract(xbi), meta)
+ .submit_many(SchedOp::Extract, lora, grouped_items)
.await;
}
}
+ fn record_scheduler_enqueue(&self, model_id: &str, item: &SchedulerItem) -> usize {
+ let cost = item.cost();
+ self.metrics.worker_queue_depth.inc();
+ self.metrics.worker_pending_cost.add(clamp_u64_to_i64(cost));
+ self.worker_pool
+ .record_model_pending_enqueue(model_id, cost)
+ }
+
/// Shared failure tail for the three scheduler-enqueue paths.
/// Mirrors the payload-resolve error branch in the legacy
/// [`Self::handle_encode`] / [`Self::handle_score`] /
/// [`Self::handle_extract`] flows: publish a synthetic
/// `payload_error` WorkResult then ACK; if the publish itself
/// fails, NAK so JetStream redelivers.
- async fn fail_resolve(&self, wi: &WorkItem, msg: &Message, err: &PayloadError, log_msg: &str) {
+ async fn fail_resolve(
+ &self,
+ wi: &WorkItem,
+ delivery: &Delivery,
+ err: &PayloadError,
+ log_msg: &str,
+ ) {
warn!(
error = %ErrChain(err),
work_item_id = %wi.work_item_id,
@@ -2218,15 +2433,10 @@ impl Dispatcher {
"{log_msg}"
);
match self
- .publish_error(
- wi,
- "payload_error",
- "failed to resolve item",
- is_worker_direct_work_subject(&msg.subject),
- )
+ .publish_error(wi, delivery, "payload_error", "failed to resolve item")
.await
{
- Ok(_) => match ack(msg).await {
+ Ok(_) => match ack(delivery).await {
Ok(()) => self.metrics.messages_acked_total.inc(),
Err(e) => {
warn!(error = %e, "ack after error-publish failed");
@@ -2234,7 +2444,7 @@ impl Dispatcher {
}
},
Err(_) => {
- nak_one(msg, base_nak_delay_ms(), &self.metrics).await;
+ nak_one(delivery, base_nak_delay_ms(), &self.metrics).await;
}
}
}
@@ -2534,6 +2744,29 @@ fn rag_to_wire(
}
}
+/// Synthetic error `ItemOutcome` for pre-execution failures (payload
+/// resolution, bad operation, offload decode). Shared by the NATS and
+/// local delivery error paths so both emit the identical wire shape.
+/// No timings: error-only publishes omit queue_ms / processing_ms /
+/// payload_fetch_ms.
+fn synthetic_error_outcome(wi: &WorkItem, code: &str, message: &str) -> ItemOutcome {
+ ItemOutcome {
+ work_item_id: wi.work_item_id.clone(),
+ request_id: wi.request_id.clone(),
+ item_index: wi.item_index,
+ disposition: Disposition::PublishErrorAndAck,
+ nak_delay_ms: None,
+ result_msgpack: Vec::new(),
+ error: Some(message.to_string()),
+ error_code: Some(code.to_string()),
+ inference_ms: None,
+ tokenization_ms: None,
+ postprocessing_ms: None,
+ raw_output: None,
+ units: None,
+ }
+}
+
fn opt_non_empty(s: &str) -> Option<String> {
if s.is_empty() {
None
@@ -2572,7 +2805,7 @@ async fn handle_generate_event(
publisher: Arc<WorkPublisher>,
metrics: Arc<MetricsRegistry>,
settled: Arc<AtomicBool>,
- msg: Arc<Message>,
+ msg: Arc<QueuedMessage>,
delivery_log: Arc<GenerateDeliveryLogContext>,
) -> Result<(), DispatchError> {
match event.kind.as_str() {
@@ -2583,7 +2816,7 @@ async fn handle_generate_event(
}
"ack" => {
if !settled.swap(true, Ordering::SeqCst) {
- match ack(&msg).await {
+ match ack_msg(&msg).await {
Ok(()) => {
info!(
work_item_id = %delivery_log.work_item_id,
@@ -2637,7 +2870,7 @@ async fn handle_generate_event(
pending = delivery_log.delivery.pending,
"generate delivery NAKed by Python"
);
- nak_one(&msg, delay_ms, &metrics).await;
+ nak_msg(&msg, delay_ms, &metrics).await;
}
}
"in_progress" => {
@@ -2685,35 +2918,19 @@ async fn handle_generate_event(
Ok(())
}
-async fn ack(msg: &Message) -> Result<(), DispatchError> {
- msg.ack()
- .await
- .map_err(|e| DispatchError::Ack(e.to_string()))
+async fn ack(delivery: &Delivery) -> Result<(), DispatchError> {
+ delivery.ack().await.map_err(DispatchError::Ack)
}
-async fn nak_all(items: &[(WorkItem, Message)], delay_ms: u64, metrics: &MetricsRegistry) {
- let delay = std::time::Duration::from_millis(delay_ms);
- for (_, m) in items {
- match m
- .ack_with(async_nats::jetstream::AckKind::Nak(Some(delay)))
- .await
- {
- Ok(()) => metrics.messages_naked_total.inc(),
- Err(e) => {
- warn!(error = %e, "nak failed");
- metrics.jetstream_nak_failures_total.inc();
- }
- }
+async fn nak_all(items: &[(WorkItem, Delivery)], delay_ms: u64, metrics: &MetricsRegistry) {
+ for (_, d) in items {
+ nak_one(d, delay_ms, metrics).await;
}
debug!(count = items.len(), delay_ms, "NAKed group");
}
-async fn nak_one(msg: &Message, delay_ms: u64, metrics: &MetricsRegistry) {
- let delay = std::time::Duration::from_millis(delay_ms);
- match msg
- .ack_with(async_nats::jetstream::AckKind::Nak(Some(delay)))
- .await
- {
+async fn nak_one(delivery: &Delivery, delay_ms: u64, metrics: &MetricsRegistry) {
+ match delivery.nak(delay_ms).await {
Ok(()) => metrics.messages_naked_total.inc(),
Err(e) => {
warn!(error = %e, "nak failed");
@@ -2722,10 +2939,10 @@ async fn nak_one(msg: &Message, delay_ms: u64, metrics: &MetricsRegistry) {
}
}
-async fn progress_all(items: &[(WorkItem, Message)], metrics: &MetricsRegistry) -> bool {
+async fn progress_all(items: &[(WorkItem, Delivery)], metrics: &MetricsRegistry) -> bool {
let mut all_ok = true;
- for (_, m) in items {
- if !progress_one(m, metrics).await {
+ for (_, d) in items {
+ if !progress_one(d, metrics).await {
all_ok = false;
}
}
@@ -2735,8 +2952,8 @@ async fn progress_all(items: &[(WorkItem, Message)], metrics: &MetricsRegistry)
all_ok
}
-async fn progress_one(msg: &Message, metrics: &MetricsRegistry) -> bool {
- match msg.ack_with(async_nats::jetstream::AckKind::Progress).await {
+async fn progress_one(delivery: &Delivery, metrics: &MetricsRegistry) -> bool {
+ match delivery.progress().await {
Ok(()) => true,
Err(e) => {
warn!(error = %e, "progress ack failed");
@@ -2746,6 +2963,30 @@ async fn progress_one(msg: &Message, metrics: &MetricsRegistry) -> bool {
}
}
+// Generate-path (NATS-only) settlement helpers. The generation flow shares
+// its `Message` behind an `Arc` with the streaming-event callback, so it
+// cannot move it into a [`Delivery`]; these mirror `ack`/`nak_one` exactly.
+
+async fn ack_msg(msg: &Message) -> Result<(), DispatchError> {
+ msg.ack()
+ .await
+ .map_err(|e| DispatchError::Ack(e.to_string()))
+}
+
+async fn nak_msg(msg: &Message, delay_ms: u64, metrics: &MetricsRegistry) {
+ let delay = std::time::Duration::from_millis(delay_ms);
+ match msg
+ .ack_with(async_nats::jetstream::AckKind::Nak(Some(delay)))
+ .await
+ {
+ Ok(()) => metrics.messages_naked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "nak failed");
+ metrics.jetstream_nak_failures_total.inc();
+ }
+ }
+}
+
// -----------------------------------------------------------------------------
// Scheduler drain loop
// -----------------------------------------------------------------------------
@@ -2806,6 +3047,50 @@ pub(crate) enum WaveRole {
Drain,
}
+fn release_scheduler_pressure(
+ metrics: &MetricsRegistry,
+ worker_pool: &AdapterWorkerPool,
+ model_id: &str,
+ items: &[SchedulerItem],
+ metadata: &[SchedulerMeta],
+) {
+ if items.is_empty() {
+ return;
+ }
+ assert_eq!(
+ items.len(),
+ metadata.len(),
+ "FormattedBatch items and metadata must stay aligned",
+ );
+
+ let mut total_cost = 0_u64;
+ let mut child_pending: BTreeMap<usize, (usize, u64)> = BTreeMap::new();
+ let mut unattributed_count = 0_usize;
+ let mut unattributed_cost = 0_u64;
+
+ for (item, meta) in items.iter().zip(metadata.iter()) {
+ let item_cost = item.cost();
+ total_cost = total_cost.saturating_add(item_cost);
+ if let Some(child_index) = meta.worker_child_index {
+ let entry = child_pending.entry(child_index).or_insert((0, 0));
+ entry.0 += 1;
+ entry.1 = entry.1.saturating_add(item_cost);
+ } else {
+ unattributed_count += 1;
+ unattributed_cost = unattributed_cost.saturating_add(item_cost);
+ }
+ }
+
+ decrement_gauge(&metrics.worker_queue_depth, items.len() as i64);
+ decrement_gauge(&metrics.worker_pending_cost, clamp_u64_to_i64(total_cost));
+ for (child_index, (item_count, cost)) in child_pending {
+ worker_pool.record_child_pending_dequeue(child_index, item_count, cost);
+ }
+ if unattributed_count > 0 {
+ worker_pool.record_model_pending_dequeue(model_id, unattributed_count, unattributed_cost);
+ }
+}
+
/// Per-batch scheduler-tick: pack the flushed batch into a
/// [`RunBatchRequest`], hand it to the backend, apply outcomes
/// through the existing dispatcher publish/ACK/NAK path, and feed
@@ -2839,6 +3124,7 @@ async fn process_scheduler_batch(
items,
metadata,
total_cost: _,
+ flush_reason,
} = batch;
let mut kept_items = Vec::with_capacity(items.len());
let mut kept_metadata = Vec::with_capacity(metadata.len());
@@ -2850,8 +3136,15 @@ async fn process_scheduler_batch(
&meta.wi.operation,
meta.worker_direct,
) {
+ release_scheduler_pressure(
+ &dispatcher.metrics,
+ &dispatcher.worker_pool,
+ model_id,
+ std::slice::from_ref(&item),
+ std::slice::from_ref(&meta),
+ );
dispatcher
- .ack_cancelled_worker_direct_batch(&meta.wi, &meta.msg)
+ .ack_cancelled_worker_direct_batch(&meta.wi, &meta.delivery)
.await;
cancelled += 1;
continue;
@@ -2871,12 +3164,21 @@ async fn process_scheduler_batch(
items: kept_items,
metadata: kept_metadata,
total_cost: kept_cost,
+ flush_reason,
};
if batch.items.is_empty() {
return;
}
let batch_size = batch.items.len();
let total_cost = batch.total_cost;
+ let flush_reason = batch.flush_reason.as_label();
+ release_scheduler_pressure(
+ &dispatcher.metrics,
+ &dispatcher.worker_pool,
+ model_id,
+ &batch.items,
+ &batch.metadata,
+ );
let op_label = match op {
SchedOp::Encode => "encode",
SchedOp::Score => "score",
@@ -3023,6 +3325,12 @@ async fn process_scheduler_batch(
.batch_cost
.with_label_values(&[&model_lbl, op_label, lora_metric_label])
.observe(total_cost as f64);
+ dispatcher
+ .metrics
+ .scheduler
+ .flush_reason_total
+ .with_label_values(&[&model_lbl, op_label, lora_metric_label, flush_reason])
+ .inc();
let _timer = dispatcher
.metrics
.pull_batch_process_seconds
@@ -3030,10 +3338,12 @@ async fn process_scheduler_batch(
.start_timer();
let started = Instant::now();
dispatcher.metrics.ipc_requests_total.inc();
+ dispatcher.metrics.inflight_batches.inc();
let outcome = match dispatcher.backend.run_batch(req).await {
Ok(o) => o,
Err(e) => {
+ dispatcher.metrics.inflight_batches.dec();
dispatcher.metrics.ipc_failures_total.inc();
let delay = nak_delay_for_backend_error(&e);
warn!(
@@ -3044,12 +3354,16 @@ async fn process_scheduler_batch(
batch_size,
"scheduler RunBatch failed — NAKing batch",
);
- let msgs_only: Vec<(WorkItem, Message)> =
- batch.metadata.into_iter().map(|m| (m.wi, m.msg)).collect();
+ let msgs_only: Vec<(WorkItem, Delivery)> = batch
+ .metadata
+ .into_iter()
+ .map(|m| (m.wi, m.delivery))
+ .collect();
nak_all(&msgs_only, delay, &dispatcher.metrics).await;
return;
}
};
+ dispatcher.metrics.inflight_batches.dec();
// Collect per-item timings BEFORE we move the metadata into
// `apply_outcomes`. Two telemetry flows out of this loop:
@@ -3114,10 +3428,10 @@ async fn process_scheduler_batch(
now,
);
- let resolved: Vec<(WorkItem, Message, f64)> = batch
+ let resolved: Vec<(WorkItem, Delivery, f64)> = batch
.metadata
.into_iter()
- .map(|m| (m.wi, m.msg, m.fetch_ms))
+ .map(|m| (m.wi, m.delivery, m.fetch_ms))
.collect();
dispatcher.apply_outcomes(outcome, resolved).await;
@@ -3202,12 +3516,24 @@ async fn process_scheduler_batch(
batch_id,
batch_size,
total_cost,
+ flush_reason,
role = ?role,
elapsed_ms = started.elapsed().as_millis() as u64,
"scheduler batch complete",
);
}
+fn clamp_u64_to_i64(value: u64) -> i64 {
+ i64::try_from(value).unwrap_or(i64::MAX)
+}
+
+fn decrement_gauge(gauge: &prometheus::IntGauge, value: i64) {
+ if value <= 0 {
+ return;
+ }
+ gauge.sub(value);
+}
+
/// Per-model background task: consume flushed batches from the
/// model's [`ProductionScheduler`], run them, and cycle back. Exits
/// on the shared [`Shutdown`] signal after a bounded final-drain
@@ -3242,6 +3568,29 @@ fn pipeline_depth() -> usize {
.unwrap_or(2)
}
+/// Whether the scheduler may flush the first item after an idle gap
+/// immediately instead of waiting for the coalesce window.
+///
+/// Default true preserves the current low-load latency behavior.
+/// Operators can set `SIE_BATCHER_IDLE_BYPASS_ENABLED=false` for
+/// passthrough runtimes such as Candle when multi-worker fanout makes
+/// each worker see a thinner local stream and early singleton flushes
+/// under-fill GPU forwards.
+fn scheduler_idle_bypass_enabled() -> bool {
+ static ENABLED: OnceLock<bool> = OnceLock::new();
+ *ENABLED.get_or_init(|| {
+ std::env::var("SIE_BATCHER_IDLE_BYPASS_ENABLED")
+ .ok()
+ .map(|raw| {
+ !matches!(
+ raw.trim().to_ascii_lowercase().as_str(),
+ "0" | "false" | "no" | "off"
+ )
+ })
+ .unwrap_or(true)
+ })
+}
+
/// Acquire one permit from `pipeline_sem` (blocking the consume loop
/// once the active depth — `ceiling` minus any autotune-parked
/// permits — batches are in flight) then spawn the dispatch as an
@@ -3304,9 +3653,11 @@ pub(crate) async fn scheduler_drain_loop(
shutdown: Arc<Shutdown>,
) {
let depth = pipeline_depth();
+ let idle_bypass_enabled = scheduler_idle_bypass_enabled();
info!(
model = %model_id,
pipeline_depth = depth,
+ idle_bypass_enabled,
"rust-scheduler: drain loop started",
);
@@ -3341,12 +3692,16 @@ pub(crate) async fn scheduler_drain_loop(
// stands alone:
//
// * `was_idle` starts true and is forwarded to `consume_next`
- // as the `immediate` flag. When the worker just polled an
- // empty queue, the next item to arrive should flush at once
- // instead of paying the full `max_batch_wait_ms` (50 ms in
- // the auto-calibrated regime). Without this, low-concurrency
- // traffic eats one full wait window per batch and p50 ends
- // up dominated by the controller's wait knob.
+ // as the `immediate` flag when idle-bypass is enabled. When
+ // the worker just polled an empty queue, the next item to
+ // arrive can flush at once instead of paying the full
+ // `max_batch_wait_ms` (50 ms in the auto-calibrated regime).
+ // Without this, low-concurrency traffic eats one full wait
+ // window per batch and p50 ends up dominated by the
+ // controller's wait knob. Operators can disable this via
+ // `SIE_BATCHER_IDLE_BYPASS_ENABLED=false` for passthrough GPU
+ // runtimes whose per-worker stream gets too thin under
+ // multi-worker fanout.
//
// * After every consumed batch we loop on `try_drain_same` for
// the same `(op, lora)` until it returns `None`. With
@@ -3366,7 +3721,7 @@ pub(crate) async fn scheduler_drain_loop(
let mut was_idle = true;
loop {
tokio::select! {
- (op, lora, batch) = scheduler.consume_next(was_idle) => {
+ (op, lora, batch) = scheduler.consume_next(was_idle && idle_bypass_enabled) => {
let initial_batch_size = batch.items.len();
// First batch in the wave drives the controller step.
spawn_pipelined_batch(
@@ -3490,11 +3845,19 @@ fn decode_offloaded_generate(bytes: &[u8]) -> Result<Json, rmp_serde::decode::Er
#[cfg(test)]
mod tests {
use super::*;
+ use std::path::PathBuf;
+
+ use crate::delivery::LocalDelivery;
fn text_item(text: &str) -> MsgValue {
MsgValue::Map(vec![(MsgValue::from("text"), MsgValue::from(text))])
}
+ fn adapter_pool_with_metrics(metrics: Arc<MetricsRegistry>) -> Arc<AdapterWorkerPool> {
+ let paths = [PathBuf::from("/tmp/sie-test-ipc-0.sock")];
+ AdapterWorkerPool::new(&paths, 1, 60, 900, metrics)
+ }
+
fn wi(request: &str, idx: u32, model: &str, op: &str) -> WorkItem {
WorkItem {
work_item_id: format!("{}.{}", request, idx),
@@ -3531,6 +3894,73 @@ mod tests {
}
}
+ fn encode_scheduler_item(work: &WorkItem) -> SchedulerItem {
+ SchedulerItem::Encode(EncodeBatchItem {
+ work_item_id: work.work_item_id.clone(),
+ request_id: work.request_id.clone(),
+ item_index: work.item_index,
+ total_items: work.total_items,
+ timestamp: work.timestamp,
+ item: work.item.clone().expect("test item"),
+ output_types: work.output_types.clone(),
+ instruction: work.instruction.clone(),
+ is_query: work.is_query,
+ options: work.options.clone(),
+ profile_id: Some(work.profile_id.clone()),
+ bundle_config_hash: Some(work.bundle_config_hash.clone()),
+ payload_fetch_ms: 0.0,
+ prepared_tokens: None,
+ })
+ }
+
+ #[test]
+ fn releasing_cancelled_scheduled_item_clears_global_and_child_pressure() {
+ let metrics = Arc::new(MetricsRegistry::new().unwrap());
+ let worker_pool = adapter_pool_with_metrics(Arc::clone(&metrics));
+ let work = wi("req-cancel", 0, "model-a", "encode");
+ let item = encode_scheduler_item(&work);
+ let child_index = worker_pool.record_model_pending_enqueue(&work.model_id, item.cost());
+ metrics.worker_queue_depth.inc();
+ metrics
+ .worker_pending_cost
+ .add(clamp_u64_to_i64(item.cost()));
+
+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
+ let meta = SchedulerMeta::new_with_worker_direct(
+ work.clone(),
+ Delivery::Local(LocalDelivery::new(0, 0, tx)),
+ 0.0,
+ true,
+ )
+ .with_worker_child_index(child_index);
+
+ release_scheduler_pressure(
+ &metrics,
+ &worker_pool,
+ &work.model_id,
+ std::slice::from_ref(&item),
+ std::slice::from_ref(&meta),
+ );
+
+ assert_eq!(metrics.worker_queue_depth.get(), 0);
+ assert_eq!(metrics.worker_pending_cost.get(), 0);
+ let child_label = child_index.to_string();
+ assert_eq!(
+ metrics
+ .worker_child_queue_depth
+ .with_label_values(&[child_label.as_str()])
+ .get(),
+ 0
+ );
+ assert_eq!(
+ metrics
+ .worker_child_pending_cost
+ .with_label_values(&[child_label.as_str()])
+ .get(),
+ 0
+ );
+ }
+
#[test]
fn generate_terminal_error_chunk_uses_streaming_wire_shape() {
#[derive(serde::Deserialize)]
@@ -3795,6 +4225,18 @@ mod tests {
}
}
+ #[test]
+ fn scheduler_idle_bypass_enabled_default_is_true() {
+ // Env-free assertion only. The function caches its first
+ // result, so tests must not mutate the env var in-process.
+ if std::env::var("SIE_BATCHER_IDLE_BYPASS_ENABLED").is_err() {
+ assert!(
+ scheduler_idle_bypass_enabled(),
+ "idle bypass must default on for low-load latency parity"
+ );
+ }
+ }
+
#[test]
fn queue_ms_from_future_timestamp_clamps_to_zero() {
let in_the_future = std::time::SystemTime::now()
@@ -3977,6 +4419,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: post_ms,
raw_output: None,
+ units: None,
}
}
diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rs
index abfce4260..d5d1ecef6 100644
--- a/packages/sie_server_sidecar/src/health_publisher.rs
+++ b/packages/sie_server_sidecar/src/health_publisher.rs
@@ -46,6 +46,7 @@ use tokio::task::JoinHandle;
use tokio::time::interval;
use tracing::{debug, info, warn};
+use crate::metrics::MetricsRegistry;
use crate::readiness::Readiness;
use crate::shutdown::Shutdown;
@@ -64,13 +65,15 @@ pub const HEALTH_SUBJECT_PREFIX: &str = "sie.health";
/// gateway flipping the worker unhealthy via `check_heartbeats`
/// (default `heartbeat_timeout` is 30 s, so 5 s gives a 6× margin).
pub const DEFAULT_PUBLISH_INTERVAL: Duration = Duration::from_secs(5);
+const SATURATION_SET_PERCENT: i64 = 90;
+const SATURATION_CLEAR_PERCENT: i64 = 70;
/// Static config for the heartbeat publisher.
///
/// Most fields are captured at startup. The ready flag comes from
/// [`Readiness`], and `bundle_config_hash` is shared with the live config
/// subscriber so gateway readiness can observe successful worker-side apply.
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub struct HealthPublisherConfig {
/// Stable identifier used as the subject leaf and as the
/// fallback URL the gateway constructs. Should match
@@ -101,6 +104,8 @@ pub struct HealthPublisherConfig {
/// Models the colocated backend reports as loaded. Updated by the IPC
/// heartbeat, not by config apply.
pub loaded_models: SharedLoadedModels,
+ /// Runtime pressure/capacity gauges mirrored into the heartbeat payload.
+ pub metrics: Arc<MetricsRegistry>,
/// How often to publish. Defaults to [`DEFAULT_PUBLISH_INTERVAL`].
pub interval: Duration,
}
@@ -131,11 +136,17 @@ struct WorkerStatusPayload<'a> {
ready: bool,
terminated: bool,
gpu_count: i32,
+ total_gpu_slots: i32,
+ ready_gpu_slots: i32,
machine_profile: &'a str,
pool_name: &'a str,
bundle: &'a str,
bundle_config_hash: &'a str,
loaded_models: &'a [String],
+ queue_depth: i32,
+ pending_cost: i64,
+ inflight_batches: i32,
+ saturated: bool,
}
fn encode_payload(
@@ -158,20 +169,86 @@ fn encode_payload(
Some(guard) => guard.as_slice(),
None => &[],
};
+ let configured_slots = config.gpu_count.max(1);
+ let total_gpu_slots = clamp_i64_to_i32(
+ config
+ .metrics
+ .worker_gpu_slots_total
+ .get()
+ .max(configured_slots.into()),
+ );
+ let ready_gpu_slots = if ready {
+ clamp_i64_to_i32(
+ config
+ .metrics
+ .worker_gpu_slots_ready
+ .get()
+ .clamp(0, total_gpu_slots.into()),
+ )
+ } else {
+ 0
+ };
+ config
+ .metrics
+ .worker_gpu_slots_total
+ .set(total_gpu_slots.into());
+ config
+ .metrics
+ .worker_gpu_slots_ready
+ .set(ready_gpu_slots.into());
+ let queue_depth = clamp_i64_to_i32(config.metrics.worker_queue_depth.get().max(0));
+ let pending_cost = config.metrics.worker_pending_cost.get().max(0);
+ let inflight_batches = clamp_i64_to_i32(config.metrics.inflight_batches.get().max(0));
+ refresh_worker_saturation(&config.metrics);
+ let saturated = config.metrics.worker_saturated.get() > 0;
let payload = WorkerStatusPayload {
name: &config.worker_id,
ready,
terminated,
gpu_count: config.gpu_count,
+ total_gpu_slots,
+ ready_gpu_slots,
machine_profile: &config.machine_profile,
pool_name: &config.pool_name,
bundle: &config.bundle,
bundle_config_hash: hash.as_str(),
loaded_models,
+ queue_depth,
+ pending_cost,
+ inflight_batches,
+ saturated,
};
serde_json::to_vec(&payload)
}
+fn clamp_i64_to_i32(value: i64) -> i32 {
+ i32::try_from(value).unwrap_or_else(|_| if value.is_negative() { 0 } else { i32::MAX })
+}
+
+fn refresh_worker_saturation(metrics: &MetricsRegistry) {
+ let ready_slots = metrics.worker_gpu_slots_ready.get().max(0);
+ if ready_slots == 0 {
+ metrics.worker_saturated.set(0);
+ return;
+ }
+
+ let capacity = ready_slots
+ .saturating_mul(crate::dispatcher::default_max_concurrent_batches().max(1) as i64)
+ .max(1);
+ let load = metrics
+ .worker_queue_depth
+ .get()
+ .max(0)
+ .saturating_add(metrics.inflight_batches.get().max(0));
+ let threshold = if metrics.worker_saturated.get() > 0 {
+ SATURATION_CLEAR_PERCENT
+ } else {
+ SATURATION_SET_PERCENT
+ };
+ let saturated = load.saturating_mul(100) >= capacity.saturating_mul(threshold);
+ metrics.worker_saturated.set(i64::from(saturated));
+}
+
pub async fn publish_tombstone(
nats: &Client,
config: &HealthPublisherConfig,
@@ -303,6 +380,7 @@ mod tests {
gpu_count: 1,
bundle_config_hash: Arc::new(RwLock::new("hash-abc".into())),
loaded_models: Arc::new(RwLock::new(Vec::new())),
+ metrics: Arc::new(MetricsRegistry::new().unwrap()),
interval: DEFAULT_PUBLISH_INTERVAL,
}
}
@@ -329,10 +407,16 @@ mod tests {
ready: true,
terminated: false,
gpu_count: c.gpu_count,
+ total_gpu_slots: 1,
+ ready_gpu_slots: 1,
machine_profile: &c.machine_profile,
pool_name: &c.pool_name,
bundle: &c.bundle,
bundle_config_hash: hash.as_str(),
+ queue_depth: 0,
+ pending_cost: 0,
+ inflight_batches: 0,
+ saturated: false,
loaded_models: &[],
};
serde_json::to_value(&payload).unwrap()
@@ -341,6 +425,12 @@ mod tests {
assert_eq!(json["ready"], true);
assert_eq!(json["terminated"], false);
assert_eq!(json["gpu_count"], 1);
+ assert_eq!(json["total_gpu_slots"], 1);
+ assert_eq!(json["ready_gpu_slots"], 1);
+ assert_eq!(json["queue_depth"], 0);
+ assert_eq!(json["pending_cost"], 0);
+ assert_eq!(json["inflight_batches"], 0);
+ assert_eq!(json["saturated"], false);
assert_eq!(json["machine_profile"], "l4");
assert_eq!(json["pool_name"], "l4");
assert_eq!(json["bundle"], "default");
@@ -362,10 +452,16 @@ mod tests {
ready: true,
terminated: false,
gpu_count: c.gpu_count,
+ total_gpu_slots: 1,
+ ready_gpu_slots: 1,
machine_profile: &c.machine_profile,
pool_name: &c.pool_name,
bundle: &c.bundle,
bundle_config_hash: hash.as_str(),
+ queue_depth: 0,
+ pending_cost: 0,
+ inflight_batches: 0,
+ saturated: false,
loaded_models: &[],
};
serde_json::to_value(&payload).unwrap()
@@ -398,6 +494,8 @@ mod tests {
assert_eq!(json["ready"], false);
assert_eq!(json["terminated"], true);
assert_eq!(json["gpu_count"], 1);
+ assert_eq!(json["total_gpu_slots"], 1);
+ assert_eq!(json["ready_gpu_slots"], 0);
assert_eq!(json["machine_profile"], "l4");
assert_eq!(json["pool_name"], "l4");
assert_eq!(json["bundle"], "default");
@@ -405,6 +503,39 @@ mod tests {
assert_eq!(json["loaded_models"], serde_json::json!([]));
}
+ #[test]
+ fn payload_includes_runtime_pressure_metrics() {
+ let c = cfg();
+ c.metrics.worker_gpu_slots_ready.set(1);
+ c.metrics.worker_queue_depth.set(1_000_000);
+ c.metrics.worker_pending_cost.set(1234);
+ c.metrics.inflight_batches.set(2);
+
+ let json: serde_json::Value =
+ serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();
+
+ assert_eq!(json["queue_depth"], 1_000_000);
+ assert_eq!(json["pending_cost"], 1234);
+ assert_eq!(json["inflight_batches"], 2);
+ assert_eq!(json["saturated"], true);
+ }
+
+ #[test]
+ fn payload_derives_saturation_from_worker_pressure() {
+ let c = cfg();
+ c.metrics.worker_gpu_slots_ready.set(1);
+ c.metrics.worker_queue_depth.set(1_000_000);
+
+ let saturated: serde_json::Value =
+ serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();
+ assert_eq!(saturated["saturated"], true);
+
+ c.metrics.worker_queue_depth.set(0);
+ let cleared: serde_json::Value =
+ serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();
+ assert_eq!(cleared["saturated"], false);
+ }
+
#[test]
fn payload_uses_local_readiness_for_ready_flag() {
// Heartbeat must reflect /readyz state — once draining
diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rs
index 0d3469f4d..d0b13cf15 100644
--- a/packages/sie_server_sidecar/src/lib.rs
+++ b/packages/sie_server_sidecar/src/lib.rs
@@ -11,12 +11,14 @@ pub mod batch_cancel;
pub mod config;
pub mod config_reconciler;
pub mod config_subscriber;
+pub mod delivery;
pub mod dispatcher;
pub mod health_publisher;
pub mod ipc_client;
pub mod ipc_mux;
pub mod ipc_types;
pub mod latency;
+pub mod local_ingest;
pub mod log_util;
pub mod metrics;
pub mod nats_consumer;
@@ -41,17 +43,16 @@ use std::time::{Duration, Instant};
use anyhow::Context;
use futures_util::StreamExt;
-use tokio::sync::{Mutex, Semaphore};
+use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinHandle;
use tokio::time::{interval, sleep, timeout};
use tracing::{debug, info, warn};
-use crate::backend::{BackendRouter, PythonIpcBackend, SharedBackend};
+use crate::backend::{AdapterWorkerPool, BackendRouter, SharedBackend};
use crate::batch_cancel::{request_id_from_batch_cancel_subject, BatchCancelState};
use crate::config::WorkerConfig;
use crate::config_subscriber::ConfigApplyState;
-use crate::dispatcher::Dispatcher;
-use crate::ipc_client::IpcClient;
+use crate::dispatcher::{Dispatcher, QueuedMessage};
use crate::latency::{FetchExpiryController, LatencyTracker};
use crate::log_util::ErrChain;
use crate::metrics::MetricsRegistry;
@@ -126,7 +127,7 @@ fn nats_consumer_reconcile_interval() -> Option<Duration> {
.map(Duration::from_millis)
}
-/// Drain deadline sent to the backend IPC on shutdown.
+/// Drain deadline sent to adapter IPC on shutdown.
const DRAIN_DEADLINE_MS: u64 = 15_000;
/// Whether the pull-loop quantum's [`LatencyTracker`] should observe
@@ -248,6 +249,29 @@ pub(crate) fn pull_loop_inflight() -> usize {
.max(1)
}
+/// Max number of queue messages this sidecar may have admitted locally but
+/// not yet finished through the scheduler/backend path.
+///
+/// Python workers have an explicit pending-queue capacity check before
+/// accepting work. The Rust sidecar owns NATS pulling in queue mode, so this
+/// cap is the equivalent local admission guard. Defaulting to one fetch keeps
+/// enough work to form full batches while preventing a single worker from
+/// hoarding the shared durable consumer when its local scheduler backs up.
+pub(crate) fn pull_loop_max_outstanding(fetch_batch: usize, inflight_cap: usize) -> usize {
+ let raw = std::env::var("SIE_PULL_LOOP_MAX_OUTSTANDING").ok();
+ parse_pull_loop_max_outstanding(raw.as_deref(), fetch_batch, inflight_cap)
+}
+
+fn parse_pull_loop_max_outstanding(
+ raw: Option<&str>,
+ fetch_batch: usize,
+ inflight_cap: usize,
+) -> usize {
+ raw.and_then(|s| s.parse::<usize>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or_else(|| fetch_batch.max(inflight_cap).max(1))
+}
+
/// How long we wait at shutdown for already-spawned pull-loop dispatch
/// tasks to finish before logging and moving on to backend drain. Kept
/// generous (one Python GPU forward pass + ack round-trip is a few
@@ -285,6 +309,10 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
// payload store, dispatcher, and backend router. Construct first so every
// downstream component observes its own RPCs into the same registry.
let metrics_registry = Arc::new(MetricsRegistry::new().context("construct metrics registry")?);
+ metrics_registry
+ .worker_gpu_slots_total
+ .set(config.gpu_count.max(1).into());
+ metrics_registry.worker_gpu_slots_ready.set(0);
let metrics_handle = metrics::spawn_metrics_server(
config.metrics_port,
Arc::clone(&metrics_registry),
@@ -293,25 +321,30 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
)
.context("spawn metrics server")?;
- // --- IPC client (connect lazily on first call). Wrapped in a
- // `PythonIpcBackend` below; the dispatcher itself never sees the
- // raw IPC client, only the backend trait object.
- let ipc = Arc::new(
- IpcClient::new_pool(&config.ipc_socket_path, config.ipc_pool_size)
- .with_timeout(Duration::from_secs(config.ipc_request_timeout_s))
- .with_model_ready_timeout(Duration::from_secs(config.model_ready_timeout_s))
- .with_metrics(Arc::clone(&metrics_registry)),
+ // --- Adapter worker pool (connects lazily per child socket).
+ let worker_pool = AdapterWorkerPool::new(
+ &config.ipc_socket_paths,
+ config.ipc_pool_size,
+ config.ipc_request_timeout_s,
+ config.model_ready_timeout_s,
+ Arc::clone(&metrics_registry),
);
info!(
- socket = %config.ipc_socket_path.display(),
+ primary_socket = %config.ipc_socket_path.display(),
+ socket_count = worker_pool.child_count(),
ipc_pool_size = config.ipc_pool_size,
ipc_request_timeout_s = config.ipc_request_timeout_s,
model_ready_timeout_s = config.model_ready_timeout_s,
- "IPC client initialized with connection pool"
+ "Adapter worker pool initialized"
);
+
// --- NATS
- let (nats_client, jetstream) = connect(&config.nats_url).await.context("connect NATS")?;
- info!(nats = %config.nats_url, "NATS connected");
+ let nats_url = config
+ .nats_url
+ .as_deref()
+ .context("SIE_NATS_URL is required for the NATS ingest mode")?;
+ let (nats_client, jetstream) = connect(nats_url).await.context("connect NATS")?;
+ info!(nats = %nats_url, "NATS connected");
let consumer = ensure_stream_and_consumer(&jetstream, &config)
.await
.context("ensure NATS stream/consumer")?;
@@ -352,20 +385,18 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
});
// Pinned-model reconciler: polls the pool's PoolSpec.pinned_models and pushes
- // it to the backend over IPC. Decoupled from admission so pinned models
+ // it to the adapter worker over IPC. Decoupled from admission so pinned models
// work even when the admission gate is disabled or fails open.
let pinned_reconciler_handle =
- crate::pinned_reconciler::spawn(&config, Arc::clone(&ipc), Arc::clone(&shutdown))
+ crate::pinned_reconciler::spawn(&config, Arc::clone(&worker_pool), Arc::clone(&shutdown))
.context("spawn pinned reconciler")?;
// --- Backend router
//
- // The sidecar talks to whichever backend is co-deployed over IPC.
- // There is exactly one backend in the current deployment. `BackendRouter`
- // is kept as the single integration point so the multi-backend fall-through
- // plumbing stays available if we ever co-resident two adapters again.
- let python_backend: SharedBackend = Arc::new(PythonIpcBackend::new(Arc::clone(&ipc)));
- let backends: Vec<SharedBackend> = vec![Arc::clone(&python_backend)];
+ // The sidecar talks to the co-deployed adapter workers
+ // through a pool that owns child placement and per-socket health.
+ let adapter_backend: SharedBackend = worker_pool.clone();
+ let backends: Vec<SharedBackend> = vec![Arc::clone(&adapter_backend)];
let router =
BackendRouter::from_backends_with_metrics(backends, Some(Arc::clone(&metrics_registry)));
@@ -414,9 +445,10 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
let dispatcher = Arc::new(Dispatcher::new(
Arc::clone(&backend),
- Arc::clone(&ipc),
+ Arc::clone(&worker_pool),
payload_store,
- Arc::clone(&publisher),
+ Some(Arc::clone(&publisher)),
+ config.worker_id.clone(),
Arc::clone(&metrics_registry),
Arc::clone(&latency_tracker),
tokenizer_registry,
@@ -436,7 +468,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
fetch_ctrl.clone(),
Arc::clone(&latency_tracker),
pool_admission.clone(),
- Arc::clone(&ipc),
+ Arc::clone(&worker_pool),
Arc::clone(&nats_direct_active),
batch_cancel_state,
));
@@ -448,7 +480,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
let config_subscriber_handle = crate::config_subscriber::spawn(
nats_client.clone(),
config.bundle.clone(),
- Arc::clone(&ipc),
+ Arc::clone(&worker_pool),
Arc::clone(&config_apply_state),
Arc::clone(&metrics_registry),
shutdown.clone(),
@@ -472,7 +504,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
},
}
}),
- Arc::clone(&ipc),
+ Arc::clone(&worker_pool),
Arc::clone(&config_apply_state),
Arc::clone(&metrics_registry),
shutdown.clone(),
@@ -480,7 +512,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
// --- Background: heartbeat pings into IPC so /readyz reflects liveness
let heartbeat_handle = spawn_heartbeat(
- Arc::clone(&ipc),
+ Arc::clone(&worker_pool),
Duration::from_millis(config.ping_interval_ms),
Arc::clone(&readiness),
Arc::clone(&config_apply_state),
@@ -510,6 +542,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
gpu_count: config.gpu_count,
bundle_config_hash: config_apply_state.bundle_config_hash(),
loaded_models: Arc::clone(&loaded_models),
+ metrics: Arc::clone(&metrics_registry),
interval: Duration::from_millis(config.health_publish_interval_ms),
})
} else {
@@ -687,6 +720,203 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
Ok(())
}
+/// Local-ingest entrypoint: the broker-less sidecar lane. Selected with
+/// `SIE_SIDECAR_INGEST=local`.
+///
+/// Wires the exact dispatcher/prep/scheduler/backend pipeline [`run`]
+/// wires, but the work feed is the [`crate::local_ingest`] UDS server
+/// instead of the NATS pull loop, and every NATS-coupled subsystem is
+/// skipped by construction:
+///
+/// * no NATS connection / streams / consumers / reconciler — the ingest
+/// socket is the only work source;
+/// * no [`WorkPublisher`] — results ride each local delivery's channel
+/// back to the ingest caller (`Dispatcher.publisher = None`);
+/// * no NATS health publisher — the platform autoscaler owns worker health;
+/// the co-located shim watches this process + `/readyz`;
+/// * no NATS config subscriber — config freshness is the HTTP epoch-poll
+/// reconciler alone (`SIE_CONFIG_SERVICE_URL`, optional), which is
+/// transport-independent;
+/// * no gateway pool-admission gate / pinned reconciler — the lane has a
+/// fixed pool identity enforced by the ingest-side re-check, and model
+/// pinning is done by the lane's engine at snapshot time.
+///
+/// The IPC heartbeat stays: it drives `/readyz` freshness and the
+/// bundle-config hash exactly as on Kubernetes.
+pub async fn run_local(config: WorkerConfig) -> anyhow::Result<()> {
+ let shutdown = Arc::new(Shutdown::new());
+ shutdown::install_signal_handlers(shutdown.clone());
+
+ let local_socket = config
+ .local_socket_path
+ .clone()
+ .context("SIE_SIDECAR_LOCAL_SOCKET is required for the local ingest mode")?;
+
+ if config.ready_stale_mult == 0 {
+ warn!(
+ "SIE_WORKER_READYZ_STALE_MULT=0; falling back to readiness::DEFAULT_STALE_MULT ({})",
+ crate::readiness::DEFAULT_STALE_MULT
+ );
+ }
+ let readiness = Arc::new(Readiness::new(
+ config.ping_interval_ms,
+ config.ready_stale_mult,
+ ));
+
+ let metrics_registry = Arc::new(MetricsRegistry::new().context("construct metrics registry")?);
+ metrics_registry
+ .worker_gpu_slots_total
+ .set(config.gpu_count.max(1).into());
+ metrics_registry.worker_gpu_slots_ready.set(0);
+ let metrics_handle = metrics::spawn_metrics_server(
+ config.metrics_port,
+ Arc::clone(&metrics_registry),
+ Arc::clone(&readiness),
+ shutdown.clone(),
+ )
+ .context("spawn metrics server")?;
+
+ let worker_pool = AdapterWorkerPool::new(
+ &config.ipc_socket_paths,
+ config.ipc_pool_size,
+ config.ipc_request_timeout_s,
+ config.model_ready_timeout_s,
+ Arc::clone(&metrics_registry),
+ );
+ info!(
+ primary_socket = %config.ipc_socket_path.display(),
+ socket_count = worker_pool.child_count(),
+ ipc_pool_size = config.ipc_pool_size,
+ ipc_request_timeout_s = config.ipc_request_timeout_s,
+ model_ready_timeout_s = config.model_ready_timeout_s,
+ "local-ingest: adapter worker pool initialized"
+ );
+
+ let raw_payload_store = create_payload_store(config.payload_store_url.as_deref())
+ .await
+ .context("create payload store")?;
+ let payload_store: Arc<dyn payload_store::PayloadStore> = Arc::new(MeteredPayloadStore::new(
+ raw_payload_store,
+ Arc::clone(&metrics_registry),
+ ));
+
+ let adapter_backend: SharedBackend = worker_pool.clone();
+ let backend: SharedBackend = BackendRouter::from_backends_with_metrics(
+ vec![Arc::clone(&adapter_backend)],
+ Some(Arc::clone(&metrics_registry)),
+ );
+
+ // Tokenizer registry fills from `EnsureModelReady` descriptors exactly
+ // like the NATS path — the engine (which carries the image-baked model
+ // configs) is the config source; no sie-config dependency needed for
+ // Rust-side tokenisation.
+ let tokenizer_registry = TokenizerRegistry::empty();
+
+ let scheduler_registry: Arc<crate::scheduler::ProductionSchedulerRegistry> =
+ Arc::new(crate::scheduler::ProductionSchedulerRegistry::new(
+ crate::scheduler::BatchConfig::from_env_or_default(),
+ ));
+ let config_apply_state = Arc::new(ConfigApplyState::new(config.bundle_config_hash.clone()));
+ let loaded_models = config_apply_state.loaded_models();
+ let latency_tracker = Arc::new(Mutex::new(LatencyTracker::new(200, 10)));
+
+ let dispatcher = Arc::new(Dispatcher::new(
+ Arc::clone(&backend),
+ Arc::clone(&worker_pool),
+ payload_store,
+ None, // no NATS publisher: results ride the local delivery channels
+ config.worker_id.clone(),
+ Arc::clone(&metrics_registry),
+ Arc::clone(&latency_tracker),
+ tokenizer_registry,
+ Some(Arc::clone(&scheduler_registry)),
+ Some(shutdown.clone()),
+ Some(Arc::clone(&config_apply_state)),
+ None, // admission is the ingest-side re-check (fixed pool identity)
+ // Batch-cancel rides the NATS cancel subject; local ingest has no
+ // such feed, so a default (empty) state means "nothing cancelled".
+ BatchCancelState::default(),
+ ));
+
+ let heartbeat_handle = spawn_heartbeat(
+ Arc::clone(&worker_pool),
+ Duration::from_millis(config.ping_interval_ms),
+ Arc::clone(&readiness),
+ Arc::clone(&config_apply_state),
+ Arc::clone(&loaded_models),
+ shutdown.clone(),
+ );
+
+ let config_reconciler_handle = crate::config_reconciler::spawn(
+ config.config_service_url.as_ref().map(|base_url| {
+ crate::config_reconciler::ReconcilerConfig {
+ base_url: base_url.clone(),
+ admin_token: config.config_service_token.clone(),
+ bundle: config.bundle.clone(),
+ pool: config.pool.clone(),
+ poll_interval: Duration::from_millis(config.config_poll_interval_ms),
+ full_export_interval: if config.config_full_export_interval_ms == 0 {
+ None
+ } else {
+ Some(Duration::from_millis(config.config_full_export_interval_ms))
+ },
+ }
+ }),
+ Arc::clone(&worker_pool),
+ Arc::clone(&config_apply_state),
+ Arc::clone(&metrics_registry),
+ shutdown.clone(),
+ );
+
+ // --- Main ingest server: serves until shutdown. A bind failure is
+ // fatal — main exits non-zero and the co-located shim replaces the
+ // container (fail-fast supervision).
+ let ingest_result = crate::local_ingest::run_local_ingest(
+ &local_socket,
+ Arc::clone(&dispatcher),
+ &config.pool,
+ &config.worker_id,
+ Arc::clone(&shutdown),
+ )
+ .await;
+
+ info!("local ingest exited; stopping heartbeat before drain");
+ readiness.mark_draining();
+ heartbeat_handle.abort();
+ let _ = heartbeat_handle.await;
+ if let Some(h) = config_reconciler_handle {
+ h.abort();
+ let _ = h.await;
+ }
+
+ // Same scheduler final-drain contract as `run()` — residual items
+ // surface to the ingest callers as shutdown "cancelled" errors instead
+ // of JetStream redelivery.
+ let scheduler_drain_handles = dispatcher.take_scheduler_drain_handles().await;
+ if !scheduler_drain_handles.is_empty() {
+ let scheduler_drain_start = Instant::now();
+ info!(
+ drain_loop_count = scheduler_drain_handles.len(),
+ "rust-scheduler: awaiting per-model drain loops"
+ );
+ for h in scheduler_drain_handles {
+ if let Err(e) = h.await {
+ warn!(error = %e, "scheduler drain task join error");
+ }
+ }
+ info!(
+ elapsed_ms = scheduler_drain_start.elapsed().as_millis() as u64,
+ "rust-scheduler: drain loops exited"
+ );
+ }
+
+ info!("draining backends");
+ backend.drain(DRAIN_DEADLINE_MS).await;
+ metrics_handle.abort();
+ info!("sie-server-sidecar (local ingest) shutdown complete");
+ ingest_result
+}
+
#[derive(Default)]
struct GenerationDirectHandles {
pull: Option<JoinHandle<()>>,
@@ -708,7 +938,7 @@ struct GenerationDirectDispatch {
fetch_ctrl: FetchExpiryController,
latency_tracker: Arc<Mutex<LatencyTracker>>,
pool_admission: Option<Arc<PoolAdmissionGate>>,
- ipc: Arc<IpcClient>,
+ worker_pool: Arc<AdapterWorkerPool>,
active: Arc<AtomicBool>,
batch_cancel_state: BatchCancelState,
handles: Mutex<GenerationDirectHandles>,
@@ -725,7 +955,7 @@ impl GenerationDirectDispatch {
fetch_ctrl: FetchExpiryController,
latency_tracker: Arc<Mutex<LatencyTracker>>,
pool_admission: Option<Arc<PoolAdmissionGate>>,
- ipc: Arc<IpcClient>,
+ worker_pool: Arc<AdapterWorkerPool>,
active: Arc<AtomicBool>,
batch_cancel_state: BatchCancelState,
) -> Self {
@@ -738,7 +968,7 @@ impl GenerationDirectDispatch {
fetch_ctrl,
latency_tracker,
pool_admission,
- ipc,
+ worker_pool,
active,
batch_cancel_state,
handles: Mutex::new(GenerationDirectHandles::default()),
@@ -800,7 +1030,7 @@ impl GenerationDirectDispatch {
});
let generation_cancel = spawn_generation_cancel_subscriber(
self.nats_client.clone(),
- Arc::clone(&self.ipc),
+ Arc::clone(&self.worker_pool),
Arc::clone(&self.shutdown),
);
@@ -880,7 +1110,7 @@ fn spawn_nats_consumer_reconciler(
fn spawn_generation_cancel_subscriber(
nats_client: async_nats::Client,
- ipc: Arc<IpcClient>,
+ worker_pool: Arc<AdapterWorkerPool>,
shutdown: Arc<Shutdown>,
) -> JoinHandle<()> {
tokio::spawn(async move {
@@ -906,7 +1136,7 @@ fn spawn_generation_cancel_subscriber(
debug!(subject = %subject, "generation: ignoring malformed cancel subject");
continue;
};
- match ipc.signal_generate_cancel(request_id.clone()).await {
+ match worker_pool.signal_generate_cancel(request_id.clone()).await {
Ok(resp) => {
debug!(
request_id = %request_id,
@@ -997,13 +1227,13 @@ fn request_id_from_cancel_subject(subject: &str) -> Option<String> {
}
}
-/// Ping the backend IPC server on a ticker. A failure is logged but
+/// Ping every adapter IPC server on a ticker. A failure is logged but
/// non-fatal — the consumer loop will surface real problems via
/// EnsureModelReady / Process* errors.
///
-/// Each successful ping refreshes the [`Readiness`] heartbeat timestamp.
+/// Each successful ready ping refreshes the [`Readiness`] heartbeat timestamp.
fn spawn_heartbeat(
- ipc: Arc<IpcClient>,
+ worker_pool: Arc<AdapterWorkerPool>,
every: Duration,
readiness: Arc<Readiness>,
config_apply_state: Arc<ConfigApplyState>,
@@ -1027,53 +1257,74 @@ fn spawn_heartbeat(
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64() * 1000.0;
- match ipc.ping(ts).await {
- Ok(resp) => {
- if config_apply_state.current_bundle_config_hash().is_empty()
- && !resp.bundle_config_hash.is_empty()
- {
- config_apply_state.set_bundle_hash(resp.bundle_config_hash.clone());
- }
- match loaded_models.write() {
- Ok(mut guard) => {
- *guard = resp.loaded_models;
- }
- Err(_) => {
- warn!("loaded_models lock poisoned; NATS health will keep the previous model list");
- }
+ let ping_results = worker_pool.ping_all(ts).await;
+ let ready_children = worker_pool.ready_child_count();
+ let successful_ready: Vec<_> = ping_results
+ .iter()
+ .filter_map(|(_index, result)| result.as_ref().ok())
+ .filter(|resp| resp.ready)
+ .collect();
+ if let Some(resp) = (ready_children > 0).then(|| successful_ready.first()).flatten() {
+ if config_apply_state.current_bundle_config_hash().is_empty()
+ && !resp.bundle_config_hash.is_empty()
+ {
+ config_apply_state.set_bundle_hash(resp.bundle_config_hash.clone());
+ }
+ let mut merged_loaded_models = Vec::new();
+ for resp in &successful_ready {
+ merged_loaded_models.extend(resp.loaded_models.iter().cloned());
+ }
+ merged_loaded_models.sort();
+ merged_loaded_models.dedup();
+ match loaded_models.write() {
+ Ok(mut guard) => {
+ *guard = merged_loaded_models;
}
- readiness.record_ping_success();
- if consecutive_failures > 0 {
- info!(
- consecutive_failures,
- "IPC heartbeat recovered — /readyz will flip green"
- );
+ Err(_) => {
+ warn!("loaded_models lock poisoned; NATS health will keep the previous model list");
}
- consecutive_failures = 0;
}
- Err(e) => {
- consecutive_failures = consecutive_failures.saturating_add(1);
- // First failure and "big milestones" warn;
- // in between, stay quiet (the
- // `ipc_request_seconds` metric still
- // records everything for Grafana).
- if consecutive_failures == 1
- || consecutive_failures == 5
- || consecutive_failures == 30
- || consecutive_failures.is_multiple_of(120)
- {
- warn!(
- consecutive_failures,
- error = %ErrChain(&e),
- "IPC heartbeat failed — /readyz will flip red shortly"
- );
- } else {
- debug!(
- consecutive_failures,
- error = %ErrChain(&e),
- "IPC heartbeat still failing"
- );
- }
+ readiness.record_ping_success();
+ if consecutive_failures > 0 {
+ info!(
+ consecutive_failures,
+ ready_children,
+ total_children = worker_pool.child_count(),
+ "IPC heartbeat recovered"
+ );
+ }
+ consecutive_failures = 0;
+ } else {
+ let error = ping_results
+ .iter()
+ .find_map(|(_index, result)| result.as_ref().err())
+ .map(|e| ErrChain(e).to_string())
+ .unwrap_or_else(|| "all adapter children reported not ready".to_string());
+ consecutive_failures = consecutive_failures.saturating_add(1);
+ // First failure and "big milestones" warn;
+ // in between, stay quiet (the
+ // `ipc_request_seconds` metric still
+ // records everything for Grafana).
+ if consecutive_failures == 1
+ || consecutive_failures == 5
+ || consecutive_failures == 30
+ || consecutive_failures.is_multiple_of(120)
+ {
+ warn!(
+ consecutive_failures,
+ ready_children,
+ total_children = worker_pool.child_count(),
+ error = %error,
+ "IPC heartbeat failed"
+ );
+ } else {
+ debug!(
+ consecutive_failures,
+ ready_children,
+ total_children = worker_pool.child_count(),
+ error = %error,
+ "IPC heartbeat still failing"
+ );
}
}
}
@@ -1123,6 +1374,23 @@ async fn build_pull_stream(
}
}
+async fn acquire_pull_admission_permit(
+ permits: &Arc<Semaphore>,
+ shutdown: &Arc<Shutdown>,
+) -> Option<OwnedSemaphorePermit> {
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => None,
+ permit = permits.clone().acquire_owned() => match permit {
+ Ok(permit) => Some(permit),
+ Err(_) => {
+ warn!("pull-loop admission semaphore closed — exiting loop");
+ None
+ }
+ },
+ }
+}
+
/// Pull messages in a loop and dispatch each batch through the Dispatcher.
///
/// # Why one long-lived [`async_nats::jetstream::consumer::pull::Stream`]
@@ -1175,6 +1443,8 @@ async fn run_pull_loop(
let rebuild_backoff = Duration::from_millis(500);
let inflight_cap = pull_loop_inflight();
let dispatch_permits = Arc::new(Semaphore::new(inflight_cap));
+ let outstanding_cap = pull_loop_max_outstanding(fetch_batch, inflight_cap);
+ let admission_permits = Arc::new(Semaphore::new(outstanding_cap));
let mut inflight_tasks: Vec<JoinHandle<()>> = Vec::new();
info!(
@@ -1183,6 +1453,7 @@ async fn run_pull_loop(
quantum_min_ms = fetch_ctrl.min.as_millis() as u64,
quantum_max_ms = fetch_ctrl.max.as_millis() as u64,
inflight_cap,
+ outstanding_cap,
"pull loop starting",
);
@@ -1221,14 +1492,21 @@ async fn run_pull_loop(
};
}
- // Step 1: block for the first message of the next batch.
+ // Step 1: acquire local admission capacity, then block for the first
+ // message of the next batch. The permit travels with the message until
+ // the scheduler/backend path completes, which prevents one sidecar from
+ // draining the shared durable into an unbounded local scheduler backlog.
+ let Some(first_permit) = acquire_pull_admission_permit(&admission_permits, &shutdown).await
+ else {
+ break 'outer;
+ };
let first = tokio::select! {
biased;
_ = shutdown.wait() => break 'outer,
next = stream.as_mut().expect("pull stream is initialized").next() => next,
};
let first_msg = match first {
- Some(Ok(msg)) => msg,
+ Some(Ok(msg)) => QueuedMessage::new(msg, Some(first_permit)),
Some(Err(e)) => {
// Recoverable per-poll errors (server TIMEOUT 408, missed
// heartbeat, etc.) surface here. The underlying Stream is
@@ -1236,6 +1514,7 @@ async fn run_pull_loop(
// internally. Log, count, and keep going.
debug!(error = %e, "pull stream poll error; continuing");
dispatcher.metrics.nats_stream_errors_total.inc();
+ drop(first_permit);
continue 'outer;
}
None => {
@@ -1247,6 +1526,7 @@ async fn run_pull_loop(
warn!("pull stream returned None (terminal); rebuilding");
dispatcher.metrics.nats_stream_errors_total.inc();
stream = None;
+ drop(first_permit);
continue 'outer;
}
};
@@ -1267,19 +1547,23 @@ async fn run_pull_loop(
if remaining.is_zero() {
break;
}
+ let Ok(next_permit) = admission_permits.clone().try_acquire_owned() else {
+ break;
+ };
tokio::select! {
biased;
_ = shutdown.wait() => break,
_ = sleep(remaining) => break,
next = stream.as_mut().expect("pull stream is initialized").next() => {
match next {
- Some(Ok(msg)) => batch.push(msg),
+ Some(Ok(msg)) => batch.push(QueuedMessage::new(msg, Some(next_permit))),
Some(Err(e)) => {
// Mid-batch recoverable error — yield what we
// have; the next iteration's block-on-first
// will resynchronise with the stream.
debug!(error = %e, "pull stream error mid-batch; flushing partial batch");
dispatcher.metrics.nats_stream_errors_total.inc();
+ drop(next_permit);
break;
}
None => {
@@ -1288,6 +1572,7 @@ async fn run_pull_loop(
warn!("pull stream ended mid-batch; flushing partial batch");
dispatcher.metrics.nats_stream_errors_total.inc();
stream = None;
+ drop(next_permit);
break;
}
}
@@ -1380,6 +1665,14 @@ mod tests {
);
}
+ #[test]
+ fn pull_loop_max_outstanding_defaults_to_one_fetch_floor() {
+ assert_eq!(parse_pull_loop_max_outstanding(None, 64, 4), 64);
+ assert_eq!(parse_pull_loop_max_outstanding(None, 1, 4), 4);
+ assert_eq!(parse_pull_loop_max_outstanding(Some("0"), 64, 4), 64);
+ assert_eq!(parse_pull_loop_max_outstanding(Some("17"), 64, 4), 17);
+ }
+
#[test]
fn nats_consumer_reconcile_interval_defaults_and_disables() {
assert_eq!(
diff --git a/packages/sie_server_sidecar/src/local_ingest.rs b/packages/sie_server_sidecar/src/local_ingest.rs
new file mode 100644
index 000000000..5bea4c871
--- /dev/null
+++ b/packages/sie_server_sidecar/src/local_ingest.rs
@@ -0,0 +1,573 @@
+//! Local-ingest server: a UDS listener speaking the sidecar dispatch
+//! protocol, feeding the same dispatcher/prep/backend pipeline the NATS
+//! pull loop feeds.
+//!
+//! Added for the broker-less sidecar lane. In this mode there is no NATS:
+//! a thin handler shim forwards each `run_batch` call over this socket as
+//! one `publish_work` op, and the sidecar answers with the msgpack
+//! `WorkResult` array. Concurrent `publish_work` calls coalesce in the
+//! sidecar's per-model scheduler exactly like concurrent NATS fetches do.
+//!
+//! ## Wire contract (v0.1)
+//!
+//! * Frame: `u32` little-endian length + msgpack map. 64 MiB cap.
+//! * Request: `{"id": u64, "op": str, "body": map}`; response
+//! `{"id": u64, "ok": bool, "error": str|nil, "body": map}`.
+//! * Ops: `ping` → `{}`; `publish_work` → `{results: bin}`; `cancel` →
+//! `{}` (accepted but a no-op here: the lane's one-shot batch calls
+//! are dropped by the caller side on cancel, and the gateway already
+//! discards late results — real in-flight cancellation lands with the
+//! streaming ops later).
+//! * Errors are `"ExceptionType: message"` strings; a decodable request
+//! with an unknown op or bad body answers `ok=false` and keeps the
+//! connection open; an undecodable frame closes the connection.
+//!
+//! ## Divergences from the NATS ingest, by design
+//!
+//! * **No `reply_subject` enforcement** — results never touch a NATS
+//! subject; every result rides this socket back to the caller, so the
+//! `_INBOX.` anti-injection check is meaningless here.
+//! * **No broker redelivery** — a dispatcher NAK surfaces as a
+//! [`LocalDeliveryEvent::Retry`] and is re-dispatched in-process with a
+//! bounded attempt budget, after which it becomes a typed error result.
+//! Same proportional stand-in the reference Python lane uses
+//! (`_NAK_MAX_ATTEMPTS`).
+//! * **Worker-side admission re-check** happens here (the lane has
+//! one pool identity), mirroring the reference lane engine's
+//! `_admission_error`: rejections are typed errors, not NAKs — there is
+//! no differently-assigned worker to redeliver to.
+
+use std::os::unix::fs::PermissionsExt;
+use std::path::Path;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use anyhow::Context;
+use serde::Deserialize;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::{UnixListener, UnixStream};
+use tokio::sync::{mpsc, Mutex};
+use tracing::{debug, info, warn};
+
+use crate::delivery::{Delivery, LocalDelivery, LocalDeliveryEvent};
+use crate::dispatcher::Dispatcher;
+use crate::shutdown::Shutdown;
+use crate::work_types::{WorkItem, WorkResult};
+
+/// Defensive ceiling on a single frame — matches the reference dispatcher
+/// server's `DEFAULT_MAX_FRAME_BYTES` (over-length = protocol error →
+/// connection closed).
+const MAX_FRAME_BYTES: u32 = 64 * 1024 * 1024;
+
+/// Default liveness deadline for a `publish_work` op when the request omits
+/// `timeout_ms` (or sends `0`). A missing/zero value must NOT disable the
+/// deadline: an unbounded wait pins the connection and leaks the detached
+/// dispatch forever if a slot never settles. It therefore falls back to this
+/// bounded ceiling; callers that need longer set an explicit positive
+/// `timeout_ms`.
+const DEFAULT_PUBLISH_WORK_TIMEOUT_MS: u64 = 300_000;
+
+/// Redelivery budget per item: how many NAK-triggered re-dispatches one
+/// item gets before its NAK becomes a typed error result. Matches the
+/// Python lane's `_NAK_MAX_ATTEMPTS`.
+const LOCAL_REDELIVERY_MAX_ATTEMPTS: u32 = 3;
+
+/// Ceiling on one local retry backoff. NATS NAK delays reach 5s
+/// (`SIE_NAK_DELAY_S` default); with a caller synchronously awaiting the
+/// batch there is no reason to wait longer per hop. Matches the Python
+/// lane's `_NAK_MAX_DELAY_S`.
+const LOCAL_RETRY_MAX_DELAY_MS: u64 = 5_000;
+
+/// Error code for the worker-side admission re-check — same string
+/// the reference Python lane emits.
+const POOL_ADMISSION_ERROR_CODE: &str = "pool_admission_rejected";
+
+const OP_PING: &str = "ping";
+const OP_PUBLISH_WORK: &str = "publish_work";
+const OP_CANCEL: &str = "cancel";
+
+// ---------------------------------------------------------------------------
+// Wire envelopes
+// ---------------------------------------------------------------------------
+
+/// One-shot body decode covering every v0.1 op: unknown fields are
+/// ignored, absent fields default, so `ping`'s `{}` and `publish_work`'s
+/// full body both land here without a second msgpack pass over the
+/// (potentially large) `items` bytes.
+#[derive(Debug, Default, Deserialize)]
+#[serde(default)]
+struct RequestBody {
+ lane: String,
+ #[allow(dead_code)] // wire field; op routing uses WorkItem.operation
+ endpoint: String,
+ #[allow(dead_code)] // wire field; the engine resolves per-item model_id
+ model: String,
+ #[allow(dead_code)] // wire field; engine routing is per-item
+ engine: String,
+ admission_pool: String,
+ #[allow(dead_code)] // per-item hashes are checked by the dispatcher
+ bundle_config_hash: String,
+ #[allow(dead_code)] // cancel correlation — no-op in v0.1 (see module doc)
+ request_id: String,
+ /// Opaque `WorkParams` bytes. Every executor-relevant field is also
+ /// serialized per-item on the WorkItem maps (gateway `WorkItemRef`
+ /// contract), so the lane never decodes it — same as the Python lane.
+ #[allow(dead_code)]
+ params: serde_bytes::ByteBuf,
+ items: serde_bytes::ByteBuf,
+ timeout_ms: i64,
+}
+
+#[derive(Debug, Deserialize)]
+struct RequestEnvelope {
+ id: u64,
+ op: String,
+ #[serde(default)]
+ body: RequestBody,
+}
+
+fn encode_response(id: u64, ok: bool, error: Option<&str>, body: rmpv::Value) -> Vec<u8> {
+ let map = rmpv::Value::Map(vec![
+ (rmpv::Value::from("id"), rmpv::Value::from(id)),
+ (rmpv::Value::from("ok"), rmpv::Value::from(ok)),
+ (
+ rmpv::Value::from("error"),
+ match error {
+ Some(e) => rmpv::Value::from(e),
+ None => rmpv::Value::Nil,
+ },
+ ),
+ (rmpv::Value::from("body"), body),
+ ]);
+ let mut payload = Vec::new();
+ rmpv::encode::write_value(&mut payload, &map).expect("msgpack encode to Vec cannot fail");
+ let mut frame = Vec::with_capacity(4 + payload.len());
+ frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());
+ frame.extend_from_slice(&payload);
+ frame
+}
+
+fn empty_body() -> rmpv::Value {
+ rmpv::Value::Map(Vec::new())
+}
+
+fn results_body(results_bytes: Vec<u8>) -> rmpv::Value {
+ rmpv::Value::Map(vec![(
+ rmpv::Value::from("results"),
+ rmpv::Value::Binary(results_bytes),
+ )])
+}
+
+/// Read one length-prefixed frame; `Ok(None)` on clean EOF between frames.
+async fn read_frame<R: AsyncReadExt + Unpin>(reader: &mut R) -> std::io::Result<Option<Vec<u8>>> {
+ let mut header = [0u8; 4];
+ match reader.read_exact(&mut header).await {
+ Ok(_) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
+ Err(e) => return Err(e),
+ }
+ let len = u32::from_le_bytes(header);
+ if len > MAX_FRAME_BYTES {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ format!("frame length {len} exceeds max {MAX_FRAME_BYTES}"),
+ ));
+ }
+ // Grow the buffer as bytes actually arrive rather than pre-allocating the
+ // full declared length: a client can cheaply declare up to the 64 MiB cap,
+ // so an eager `vec![0u8; len]` would let a 4-byte header pin 64 MiB before
+ // any body arrives (local memory amplification). `take` bounds the read to
+ // the declared length; a short/truncated frame is a protocol error.
+ let mut payload = Vec::new();
+ let read = reader
+ .take(u64::from(len))
+ .read_to_end(&mut payload)
+ .await?;
+ if read != len as usize {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::UnexpectedEof,
+ format!("frame truncated: read {read} of {len} declared bytes"),
+ ));
+ }
+ Ok(Some(payload))
+}
+
+// ---------------------------------------------------------------------------
+// Server
+// ---------------------------------------------------------------------------
+
+/// Lane identity + shared handles one connection task needs.
+struct IngestShared {
+ dispatcher: Arc<Dispatcher>,
+ shutdown: Arc<Shutdown>,
+ /// Physical pool this lane serves (`SIE_POOL`), pre-normalized.
+ lane_pool: String,
+ worker_id: String,
+}
+
+/// Bind the local-ingest UDS and serve until shutdown. Consumes the
+/// listener task; callers spawn it.
+pub async fn run_local_ingest(
+ socket_path: &Path,
+ dispatcher: Arc<Dispatcher>,
+ pool: &str,
+ worker_id: &str,
+ shutdown: Arc<Shutdown>,
+) -> anyhow::Result<()> {
+ // Unlink a stale socket file (crash leftovers) before binding — same
+ // bind-time cleanup as the Python IPC/dispatcher servers.
+ if socket_path.exists() {
+ std::fs::remove_file(socket_path)
+ .with_context(|| format!("unlink stale local socket {}", socket_path.display()))?;
+ }
+ if let Some(parent) = socket_path.parent() {
+ let parent_existed = parent.exists();
+ std::fs::create_dir_all(parent)
+ .with_context(|| format!("create socket dir {}", parent.display()))?;
+ // Only tighten a directory we created — never clobber the mode of a
+ // pre-existing (possibly shared, e.g. `/tmp`) parent. A dedicated
+ // socket dir at 0700 denies traversal to non-owners regardless of the
+ // socket node's own mode.
+ if !parent_existed {
+ std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))
+ .with_context(|| format!("restrict socket dir {}", parent.display()))?;
+ }
+ }
+ let listener = UnixListener::bind(socket_path)
+ .with_context(|| format!("bind local ingest socket {}", socket_path.display()))?;
+ // Restrict the socket node to the owner. It is bound with the process
+ // umask default (`0o777 & !umask`), so under a permissive container umask
+ // (0000/0002) it would be group/world-connectable and any local process
+ // could inject WorkItems onto this worker's GPU (compute theft / DoS).
+ // connect(2) checks write permission on the node, so 0600 gates it.
+ std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o600))
+ .with_context(|| format!("restrict local ingest socket {}", socket_path.display()))?;
+ info!(socket = %socket_path.display(), pool, "local-ingest: listening");
+
+ let shared = Arc::new(IngestShared {
+ dispatcher,
+ shutdown: Arc::clone(&shutdown),
+ lane_pool: normalize_pool(pool),
+ worker_id: worker_id.to_string(),
+ });
+
+ loop {
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => break,
+ accepted = listener.accept() => {
+ match accepted {
+ Ok((stream, _)) => {
+ let shared = Arc::clone(&shared);
+ tokio::spawn(async move {
+ handle_connection(stream, shared).await;
+ });
+ }
+ Err(e) => {
+ warn!(error = %e, "local-ingest: accept failed");
+ }
+ }
+ }
+ }
+ }
+ let _ = std::fs::remove_file(socket_path);
+ info!("local-ingest: listener stopped");
+ Ok(())
+}
+
+async fn handle_connection(stream: UnixStream, shared: Arc<IngestShared>) {
+ let (mut reader, writer) = stream.into_split();
+ let writer = Arc::new(Mutex::new(writer));
+ loop {
+ let payload = tokio::select! {
+ biased;
+ _ = shared.shutdown.wait() => break,
+ frame = read_frame(&mut reader) => match frame {
+ Ok(Some(p)) => p,
+ Ok(None) => break, // clean EOF
+ Err(e) => {
+ warn!(error = %e, "local-ingest: closing connection on malformed frame");
+ break;
+ }
+ },
+ };
+ let request: RequestEnvelope = match rmp_serde::from_slice(&payload) {
+ Ok(r) => r,
+ Err(e) => {
+ // No usable `id` to correlate an error response — close,
+ // per the protocol contract.
+ warn!(error = %e, "local-ingest: closing connection on malformed request envelope");
+ break;
+ }
+ };
+ // Each op runs as its own task; responses may interleave and are
+ // correlated by `id` (same shape as the Python dispatcher server).
+ let shared_op = Arc::clone(&shared);
+ let writer_op = Arc::clone(&writer);
+ tokio::spawn(async move {
+ let frame = run_op(request, &shared_op).await;
+ let mut w = writer_op.lock().await;
+ if let Err(e) = w.write_all(&frame).await {
+ debug!(error = %e, "local-ingest: response write failed (caller gone)");
+ }
+ });
+ }
+}
+
+async fn run_op(request: RequestEnvelope, shared: &IngestShared) -> Vec<u8> {
+ match request.op.as_str() {
+ OP_PING => encode_response(request.id, true, None, empty_body()),
+ OP_CANCEL => encode_response(request.id, true, None, empty_body()),
+ OP_PUBLISH_WORK => match publish_work(request.body, shared).await {
+ Ok(results_bytes) => {
+ encode_response(request.id, true, None, results_body(results_bytes))
+ }
+ Err(e) => encode_response(request.id, false, Some(&e), empty_body()),
+ },
+ other => encode_response(
+ request.id,
+ false,
+ Some(&format!("ValueError: unknown op: {other:?}")),
+ empty_body(),
+ ),
+ }
+}
+
+// ---------------------------------------------------------------------------
+// publish_work
+// ---------------------------------------------------------------------------
+
+fn normalize_pool(raw: &str) -> String {
+ raw.trim().to_ascii_lowercase()
+}
+
+/// Worker-side admission re-check — the local-mode mirror of the
+/// NATS decode-path `PoolAdmissionGate` check, reduced exactly like the
+/// reference lane's `_admission_error`: one pool identity, no
+/// assigned-logical-pool list, so "requested pool must be empty or equal
+/// the lane pool" with batch meta and per-item fields required to agree.
+fn admission_error(lane_pool: &str, meta_pool: &str, item_pool: &str) -> Option<String> {
+ if !meta_pool.is_empty() && !item_pool.is_empty() && meta_pool != item_pool {
+ return Some(format!(
+ "admission_pool mismatch: batch meta={meta_pool:?} item={item_pool:?}"
+ ));
+ }
+ for requested in [meta_pool, item_pool] {
+ if !requested.is_empty() && requested != lane_pool {
+ return Some(format!(
+ "lane pool {lane_pool:?} does not serve admission_pool {requested:?}"
+ ));
+ }
+ }
+ None
+}
+
+fn error_result(wi: &WorkItem, worker_id: &str, code: &str, message: &str) -> WorkResult {
+ WorkResult {
+ work_item_id: wi.work_item_id.clone(),
+ request_id: wi.request_id.clone(),
+ item_index: wi.item_index,
+ success: false,
+ result_msgpack: Vec::new(),
+ error: Some(message.to_string()),
+ error_code: Some(code.to_string()),
+ inference_ms: None,
+ queue_ms: None,
+ processing_ms: None,
+ worker_id: Some(worker_id.to_string()),
+ tokenization_ms: None,
+ postprocessing_ms: None,
+ payload_fetch_ms: None,
+ units: None,
+ // Local-ingest deliveries are worker-direct by construction: the
+ // caller addressed this worker's socket, not a pool subject.
+ worker_direct: true,
+ }
+}
+
+async fn publish_work(body: RequestBody, shared: &IngestShared) -> Result<Vec<u8>, String> {
+ let items: Vec<WorkItem> = rmp_serde::from_slice(&body.items)
+ .map_err(|e| format!("DecodeError: items is not a msgpack WorkItem array: {e}"))?;
+ let n = items.len();
+ shared
+ .dispatcher
+ .metrics
+ .messages_received_total
+ .inc_by(n as u64);
+ let mut results: Vec<Option<WorkResult>> = Vec::with_capacity(n);
+ results.resize_with(n, || None);
+
+ let (tx, mut rx) = mpsc::unbounded_channel::<LocalDeliveryEvent>();
+ let meta_pool = normalize_pool(&body.admission_pool);
+ let mut dispatchable: Vec<(WorkItem, Delivery)> = Vec::with_capacity(n);
+ for (slot, wi) in items.iter().enumerate() {
+ let item_pool = normalize_pool(&wi.admission_pool);
+ if let Some(reason) = admission_error(&shared.lane_pool, &meta_pool, &item_pool) {
+ results[slot] = Some(error_result(
+ wi,
+ &shared.worker_id,
+ POOL_ADMISSION_ERROR_CODE,
+ &reason,
+ ));
+ continue;
+ }
+ dispatchable.push((
+ wi.clone(),
+ Delivery::Local(LocalDelivery::new(slot, 0, tx.clone())),
+ ));
+ }
+ // `tx` stays alive for the whole collect loop so NAK-triggered
+ // re-dispatches can mint fresh senders. Loop termination is driven by
+ // the `pending` count (every delivery settles as Result or Retry — the
+ // dispatcher's settlement invariant, the same one the NATS path
+ // ultimately backstops with ack_wait), plus timeout/shutdown.
+
+ let mut pending = results.iter().filter(|r| r.is_none()).count();
+ if pending > 0 {
+ let dispatcher = Arc::clone(&shared.dispatcher);
+ let batch_size = dispatchable.len();
+ tokio::spawn(async move {
+ dispatcher
+ .dispatch_decoded(dispatchable, batch_size, Instant::now())
+ .await;
+ });
+ }
+
+ // A missing or non-positive `timeout_ms` must NOT disable the deadline:
+ // that turns the timeout arm into `pending()` forever, pinning the
+ // connection and leaking the detached dispatch if a slot never settles.
+ // Fall back to a bounded default so every op is guaranteed to settle.
+ let timeout_ms = if body.timeout_ms > 0 {
+ body.timeout_ms as u64
+ } else {
+ DEFAULT_PUBLISH_WORK_TIMEOUT_MS
+ };
+ let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms);
+ while pending > 0 {
+ let event = tokio::select! {
+ biased;
+ _ = shared.shutdown.wait() => {
+ // Wire lifecycle: in-flight ops answer the exact
+ // string "cancelled" on shutdown.
+ return Err("cancelled".to_string());
+ }
+ _ = tokio::time::sleep_until(deadline) => {
+ return Err(format!(
+ "TimeoutError: publish_work timed out after {timeout_ms}ms (lane '{}')",
+ body.lane
+ ));
+ }
+ event = rx.recv() => match event {
+ Some(e) => e,
+ // Unreachable while our own `tx` is alive; defensive break.
+ None => break,
+ },
+ };
+ match event {
+ LocalDeliveryEvent::Result { slot, result } => {
+ if slot < results.len() && results[slot].is_none() {
+ results[slot] = Some(*result);
+ pending -= 1;
+ } else {
+ debug!(slot, "local-ingest: duplicate/out-of-range result ignored");
+ }
+ }
+ LocalDeliveryEvent::Retry {
+ slot,
+ attempt,
+ delay_ms,
+ } => {
+ if slot >= results.len() || results[slot].is_some() {
+ debug!(slot, "local-ingest: retry for settled slot ignored");
+ continue;
+ }
+ if attempt >= LOCAL_REDELIVERY_MAX_ATTEMPTS {
+ let wi = &items[slot];
+ warn!(
+ work_item_id = %wi.work_item_id,
+ attempts = attempt + 1,
+ "local-ingest: redelivery budget exhausted — typed error"
+ );
+ results[slot] = Some(error_result(
+ wi,
+ &shared.worker_id,
+ "inference_error",
+ &format!(
+ "worker requested redelivery (nak) for {:?} but the local-ingest \
+ lane has no broker redelivery; exhausted {LOCAL_REDELIVERY_MAX_ATTEMPTS} \
+ in-lane retries",
+ wi.work_item_id
+ ),
+ ));
+ pending -= 1;
+ continue;
+ }
+ // Bounded in-process redelivery: re-dispatch this single
+ // item after the NAK delay (capped — the caller is
+ // synchronously waiting).
+ let delay = Duration::from_millis(delay_ms.min(LOCAL_RETRY_MAX_DELAY_MS));
+ let wi = items[slot].clone();
+ let delivery = Delivery::Local(LocalDelivery::new(slot, attempt + 1, tx.clone()));
+ let dispatcher = Arc::clone(&shared.dispatcher);
+ debug!(
+ work_item_id = %wi.work_item_id,
+ attempt = attempt + 1,
+ delay_ms = delay.as_millis() as u64,
+ "local-ingest: re-dispatching NAKed item"
+ );
+ tokio::spawn(async move {
+ tokio::time::sleep(delay).await;
+ dispatcher
+ .dispatch_decoded(vec![(wi, delivery)], 1, Instant::now())
+ .await;
+ });
+ }
+ }
+ }
+
+ drop(tx);
+ let final_results: Vec<WorkResult> = results
+ .into_iter()
+ .enumerate()
+ .map(|(slot, r)| {
+ r.unwrap_or_else(|| {
+ // A delivery was dropped without settling (should not
+ // happen; the dispatcher always answers). Fail typed
+ // rather than hanging or omitting the slot.
+ error_result(
+ &items[slot],
+ &shared.worker_id,
+ "inference_error",
+ "work item was dropped without an outcome",
+ )
+ })
+ })
+ .collect();
+ rmp_serde::to_vec_named(&final_results)
+ .map_err(|e| format!("EncodeError: results encode failed: {e}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn admission_accepts_empty_and_matching_pools() {
+ assert_eq!(admission_error("default", "", ""), None);
+ assert_eq!(admission_error("default", "default", ""), None);
+ assert_eq!(admission_error("default", "", "default"), None);
+ assert_eq!(admission_error("default", "default", "default"), None);
+ }
+
+ #[test]
+ fn admission_rejects_mismatched_meta_and_item() {
+ let err = admission_error("default", "a", "b").expect("mismatch rejected");
+ assert!(err.contains("admission_pool mismatch"));
+ }
+
+ #[test]
+ fn admission_rejects_foreign_pool() {
+ let err = admission_error("default", "other", "").expect("foreign pool rejected");
+ assert!(err.contains("does not serve"));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/main.rs b/packages/sie_server_sidecar/src/main.rs
index 42d08d1f8..be4d4fcf2 100644
--- a/packages/sie_server_sidecar/src/main.rs
+++ b/packages/sie_server_sidecar/src/main.rs
@@ -3,6 +3,9 @@
//! See `docs/architecture-guide.md` for the design. This binary is the
//! entrypoint; the library modules live in `lib.rs`.
+use std::collections::HashSet;
+use std::path::PathBuf;
+
use anyhow::Context;
use clap::Parser;
use tracing::{error, info};
@@ -10,13 +13,25 @@ use tracing::{error, info};
use sie_server_sidecar::config::WorkerConfig;
use sie_server_sidecar::config_subscriber::trusted_producers_from_env;
use sie_server_sidecar::dispatcher::default_max_concurrent_batches;
-use sie_server_sidecar::run;
+use sie_server_sidecar::{run, run_local};
#[derive(Parser, Debug)]
#[command(author, version, about = "SIE server sidecar", long_about = None)]
struct Cli {
+ /// Work-ingest mode: `nats` (default; JetStream pull consumer) or
+ /// `local` (UDS `publish_work` listener for the broker-less sidecar
+ /// lane).
+ #[arg(long, env = "SIE_SIDECAR_INGEST", default_value = "nats")]
+ ingest: String,
+
+ /// UDS path for the local-ingest listener. Required (and only read)
+ /// when `--ingest local`.
+ #[arg(long, env = "SIE_SIDECAR_LOCAL_SOCKET")]
+ local_socket: Option<String>,
+
+ /// Required for `--ingest nats`; unused in local mode.
#[arg(long, env = "SIE_NATS_URL")]
- nats_url: String,
+ nats_url: Option<String>,
#[arg(long, env = "SIE_POOL")]
pool: String,
@@ -27,7 +42,12 @@ struct Cli {
#[arg(long, env = "SIE_IPC_SOCKET_PATH", default_value = "/tmp/sie-ipc.sock")]
ipc_socket_path: String,
- /// Number of concurrent IPC connections to the backend process.
+ /// Comma-separated IPC socket paths for per-GPU adapter worker children.
+ /// Defaults to `SIE_IPC_SOCKET_PATH` when unset.
+ #[arg(long, env = "SIE_IPC_SOCKET_PATHS")]
+ ipc_socket_paths: Option<String>,
+
+ /// Number of concurrent IPC connections to each adapter process.
/// Defaults to `SIE_MAX_CONCURRENT_BATCHES` when unset (falling
/// back to the dispatcher's own default of 4), so the IPC pool
/// never becomes the binding constraint on the dispatcher's
@@ -35,7 +55,7 @@ struct Cli {
#[arg(long, env = "SIE_IPC_POOL_SIZE")]
ipc_pool_size: Option<usize>,
- /// Timeout, in seconds, for ordinary sidecar-to-backend IPC calls.
+ /// Timeout, in seconds, for ordinary sidecar → adapter IPC calls.
#[arg(long, env = "SIE_IPC_REQUEST_TIMEOUT_S", default_value = "60")]
ipc_request_timeout_s: u64,
@@ -45,7 +65,7 @@ struct Cli {
#[arg(long, env = "SIE_MODEL_READY_TIMEOUT_S")]
model_ready_timeout_s: Option<u64>,
- /// Backend worker liveness budget in seconds. When set by Helm, the sidecar
+ /// Adapter worker liveness budget in seconds. When set by Helm, the sidecar
/// rejects an EnsureModelReady timeout kubelet would kill before completion.
#[arg(long, env = "SIE_WORKER_LIVENESS_BUDGET_S")]
worker_liveness_budget_s: Option<u64>,
@@ -162,16 +182,27 @@ async fn main() -> anyhow::Result<()> {
init_tracing();
let cli = Cli::parse();
+ let ingest = validate_ingest_mode(
+ &cli.ingest,
+ cli.nats_url.as_deref(),
+ cli.local_socket.as_deref(),
+ )?;
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 model_ready_timeout_s = cli.model_ready_timeout_s.unwrap_or(900).max(1);
validate_model_ready_liveness_budget(model_ready_timeout_s, cli.worker_liveness_budget_s)?;
+ let ipc_socket_path = PathBuf::from(cli.ipc_socket_path);
+ let ipc_socket_paths = parse_ipc_socket_paths(cli.ipc_socket_paths.as_deref())
+ .unwrap_or_else(|| vec![ipc_socket_path.clone()]);
+ validate_unique_ipc_socket_paths(&ipc_socket_paths)?;
let config = WorkerConfig {
nats_url: cli.nats_url,
+ local_socket_path: cli.local_socket.map(Into::into),
pool,
bundle,
- ipc_socket_path: cli.ipc_socket_path.into(),
+ ipc_socket_path,
+ ipc_socket_paths,
ipc_pool_size: cli
.ipc_pool_size
.filter(|&n| n > 0)
@@ -211,12 +242,20 @@ async fn main() -> anyhow::Result<()> {
pool = %config.pool,
bundle = %config.bundle,
ipc = %config.ipc_socket_path.display(),
+ ipc_sockets = config.ipc_socket_paths.len(),
ipc_pool_size = config.ipc_pool_size,
worker_id = %config.worker_id,
+ ingest = %ingest,
"sie-server-sidecar starting"
);
- if let Err(e) = run(config).await.context("server sidecar run loop") {
+ let result = match ingest {
+ IngestMode::Nats => run(config).await.context("server sidecar run loop"),
+ IngestMode::Local => run_local(config)
+ .await
+ .context("server sidecar local-ingest run loop"),
+ };
+ if let Err(e) = result {
error!(error = ?e, "sie-server-sidecar exited with error");
// Flush any pending OTLP spans before the hard exit.
sie_server_sidecar::observability::tracing::shutdown_tracing();
@@ -232,6 +271,48 @@ fn init_tracing() {
sie_server_sidecar::observability::tracing::init_tracing();
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum IngestMode {
+ Nats,
+ Local,
+}
+
+impl std::fmt::Display for IngestMode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ Self::Nats => "nats",
+ Self::Local => "local",
+ })
+ }
+}
+
+/// Validate the ingest mode + its per-mode required argument. Kept out of
+/// clap's value-parser so the error names the env vars operators actually
+/// set (`SIE_SIDECAR_INGEST` / `SIE_NATS_URL` / `SIE_SIDECAR_LOCAL_SOCKET`).
+fn validate_ingest_mode(
+ raw: &str,
+ nats_url: Option<&str>,
+ local_socket: Option<&str>,
+) -> anyhow::Result<IngestMode> {
+ match raw.trim().to_ascii_lowercase().as_str() {
+ "nats" | "" => {
+ if nats_url.is_none_or(|url| url.trim().is_empty()) {
+ anyhow::bail!(
+ "SIE_NATS_URL is required when SIE_SIDECAR_INGEST=nats (the default)"
+ );
+ }
+ Ok(IngestMode::Nats)
+ }
+ "local" => {
+ if local_socket.is_none_or(|path| path.trim().is_empty()) {
+ anyhow::bail!("SIE_SIDECAR_LOCAL_SOCKET is required when SIE_SIDECAR_INGEST=local");
+ }
+ Ok(IngestMode::Local)
+ }
+ other => anyhow::bail!("SIE_SIDECAR_INGEST must be 'nats' or 'local', got {other:?}"),
+ }
+}
+
fn validate_lane_segment(name: &str, raw: String) -> anyhow::Result<String> {
let value = raw.trim();
if value.is_empty() {
@@ -257,6 +338,34 @@ fn env_bool_value(raw: Option<&str>, default: bool) -> bool {
!matches!(trimmed.as_str(), "0" | "false" | "no" | "off")
}
+fn parse_ipc_socket_paths(raw: Option<&str>) -> Option<Vec<PathBuf>> {
+ let raw = raw?;
+ let paths: Vec<PathBuf> = raw
+ .split(',')
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(PathBuf::from)
+ .collect();
+ if paths.is_empty() {
+ None
+ } else {
+ Some(paths)
+ }
+}
+
+fn validate_unique_ipc_socket_paths(paths: &[PathBuf]) -> anyhow::Result<()> {
+ let mut seen = HashSet::with_capacity(paths.len());
+ for path in paths {
+ if !seen.insert(path) {
+ anyhow::bail!(
+ "SIE_IPC_SOCKET_PATHS must not contain duplicate path '{}'",
+ path.display()
+ );
+ }
+ }
+ Ok(())
+}
+
fn seconds_to_millis(seconds: f64, min_ms: u64) -> u64 {
if !seconds.is_finite() || seconds <= 0.0 {
return min_ms;
@@ -286,8 +395,39 @@ fn validate_model_ready_liveness_budget(
#[cfg(test)]
mod tests {
+ use std::path::PathBuf;
+
+ use super::parse_ipc_socket_paths;
+ use super::validate_ingest_mode;
use super::validate_lane_segment;
use super::validate_model_ready_liveness_budget;
+ use super::validate_unique_ipc_socket_paths;
+ use super::IngestMode;
+
+ #[test]
+ fn ingest_mode_nats_requires_nats_url() {
+ assert_eq!(
+ validate_ingest_mode("nats", Some("nats://x:4222"), None).unwrap(),
+ IngestMode::Nats
+ );
+ assert!(validate_ingest_mode("nats", None, None).is_err());
+ assert!(validate_ingest_mode("nats", Some(" "), None).is_err());
+ }
+
+ #[test]
+ fn ingest_mode_local_requires_socket() {
+ assert_eq!(
+ validate_ingest_mode("local", None, Some("/tmp/s.sock")).unwrap(),
+ IngestMode::Local
+ );
+ assert!(validate_ingest_mode("local", Some("nats://x"), None).is_err());
+ assert!(validate_ingest_mode("local", None, Some("")).is_err());
+ }
+
+ #[test]
+ fn ingest_mode_rejects_unknown_values() {
+ assert!(validate_ingest_mode("both", Some("nats://x"), Some("/tmp/s")).is_err());
+ }
#[test]
fn validate_lane_segment_trims_valid_values() {
@@ -316,4 +456,28 @@ mod tests {
assert!(validate_model_ready_liveness_budget(900, Some(900)).is_err());
assert!(validate_model_ready_liveness_budget(1200, Some(1080)).is_err());
}
+
+ #[test]
+ fn parse_ipc_socket_paths_ignores_empty_segments() {
+ let paths = parse_ipc_socket_paths(Some(" /a.sock, ,/b.sock ")).unwrap();
+ assert_eq!(
+ paths,
+ vec![PathBuf::from("/a.sock"), PathBuf::from("/b.sock")]
+ );
+ assert!(parse_ipc_socket_paths(Some(" , ")).is_none());
+ }
+
+ #[test]
+ fn validate_unique_ipc_socket_paths_rejects_duplicates() {
+ let paths = parse_ipc_socket_paths(Some("/a.sock,/b.sock,/a.sock")).unwrap();
+
+ assert!(validate_unique_ipc_socket_paths(&paths).is_err());
+ }
+
+ #[test]
+ fn validate_unique_ipc_socket_paths_accepts_distinct_paths() {
+ let paths = parse_ipc_socket_paths(Some("/a.sock,/b.sock")).unwrap();
+
+ validate_unique_ipc_socket_paths(&paths).unwrap();
+ }
}
diff --git a/packages/sie_server_sidecar/src/metrics.rs b/packages/sie_server_sidecar/src/metrics.rs
index 606af5842..752156e64 100644
--- a/packages/sie_server_sidecar/src/metrics.rs
+++ b/packages/sie_server_sidecar/src/metrics.rs
@@ -13,8 +13,8 @@ use hyper::service::service_fn;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use prometheus::{
- Encoder, Histogram, HistogramOpts, HistogramVec, IntCounter, IntCounterVec, IntGauge, Opts,
- Registry, TextEncoder,
+ Encoder, Histogram, HistogramOpts, HistogramVec, IntCounter, IntCounterVec, IntGauge,
+ IntGaugeVec, Opts, Registry, TextEncoder,
};
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
@@ -83,6 +83,16 @@ pub struct MetricsRegistry {
pub ipc_requests_total: IntCounter,
pub ipc_failures_total: IntCounter,
pub inflight_batches: IntGauge,
+ pub worker_gpu_slots_total: IntGauge,
+ pub worker_gpu_slots_ready: IntGauge,
+ pub worker_queue_depth: IntGauge,
+ pub worker_pending_cost: IntGauge,
+ pub worker_saturated: IntGauge,
+ pub worker_child_ready: IntGaugeVec,
+ pub worker_child_models: IntGaugeVec,
+ pub worker_child_queue_depth: IntGaugeVec,
+ pub worker_child_pending_cost: IntGaugeVec,
+ pub worker_child_inflight_batches: IntGaugeVec,
pub pull_items_fetched: HistogramVec,
pub pull_batch_process_seconds: HistogramVec,
@@ -104,7 +114,7 @@ pub struct MetricsRegistry {
/// `tokenization_ms` / `postprocessing_ms` fields on each
/// `ItemOutcome`.
///
- /// IPC backends report the backend sub-group wall time on every
+ /// Adapter IPC reports the backend sub-group wall time on every
/// item in that sub-group, so percentiles are request-volume
/// weighted backend times, not amortised per-item costs. Backends
/// may use different timing semantics; compare distributions
@@ -211,6 +221,61 @@ impl MetricsRegistry {
"sie_worker_inflight_batches",
"Number of batches currently in flight through IPC",
)?;
+ let worker_gpu_slots_total = IntGauge::new(
+ "sie_worker_gpu_slots_total",
+ "GPU slots assigned to this worker pod",
+ )?;
+ let worker_gpu_slots_ready = IntGauge::new(
+ "sie_worker_gpu_slots_ready",
+ "GPU slots currently ready to receive work in this worker pod",
+ )?;
+ let worker_queue_depth = IntGauge::new(
+ "sie_worker_queue_depth",
+ "Worker-local scheduler pending item count",
+ )?;
+ let worker_pending_cost = IntGauge::new(
+ "sie_worker_pending_cost",
+ "Worker-local scheduler pending cost across all models",
+ )?;
+ let worker_saturated = IntGauge::new(
+ "sie_worker_saturated",
+ "Worker admission saturation flag: 1 means the gateway should avoid direct dispatch",
+ )?;
+ let worker_child_ready = IntGaugeVec::new(
+ Opts::new(
+ "sie_worker_child_ready",
+ "Per-child GPU slot readiness inside this worker pod",
+ ),
+ &["child"],
+ )?;
+ let worker_child_models = IntGaugeVec::new(
+ Opts::new(
+ "sie_worker_child_models",
+ "Number of models placed on each adapter worker child",
+ ),
+ &["child"],
+ )?;
+ let worker_child_queue_depth = IntGaugeVec::new(
+ Opts::new(
+ "sie_worker_child_queue_depth",
+ "Pending scheduler item count attributed to each adapter worker child",
+ ),
+ &["child"],
+ )?;
+ let worker_child_pending_cost = IntGaugeVec::new(
+ Opts::new(
+ "sie_worker_child_pending_cost",
+ "Pending scheduler cost attributed to each adapter worker child",
+ ),
+ &["child"],
+ )?;
+ let worker_child_inflight_batches = IntGaugeVec::new(
+ Opts::new(
+ "sie_worker_child_inflight_batches",
+ "Batches currently in flight on each adapter worker child",
+ ),
+ &["child"],
+ )?;
let pull_items_fetched = HistogramVec::new(
HistogramOpts::new(
@@ -462,6 +527,16 @@ impl MetricsRegistry {
registry.register(Box::new(ipc_requests_total.clone()))?;
registry.register(Box::new(ipc_failures_total.clone()))?;
registry.register(Box::new(inflight_batches.clone()))?;
+ registry.register(Box::new(worker_gpu_slots_total.clone()))?;
+ registry.register(Box::new(worker_gpu_slots_ready.clone()))?;
+ registry.register(Box::new(worker_queue_depth.clone()))?;
+ registry.register(Box::new(worker_pending_cost.clone()))?;
+ registry.register(Box::new(worker_saturated.clone()))?;
+ registry.register(Box::new(worker_child_ready.clone()))?;
+ registry.register(Box::new(worker_child_models.clone()))?;
+ registry.register(Box::new(worker_child_queue_depth.clone()))?;
+ registry.register(Box::new(worker_child_pending_cost.clone()))?;
+ registry.register(Box::new(worker_child_inflight_batches.clone()))?;
registry.register(Box::new(pull_items_fetched.clone()))?;
registry.register(Box::new(pull_batch_process_seconds.clone()))?;
registry.register(Box::new(pull_nak_unloaded_total.clone()))?;
@@ -524,6 +599,16 @@ impl MetricsRegistry {
ipc_requests_total,
ipc_failures_total,
inflight_batches,
+ worker_gpu_slots_total,
+ worker_gpu_slots_ready,
+ worker_queue_depth,
+ worker_pending_cost,
+ worker_saturated,
+ worker_child_ready,
+ worker_child_models,
+ worker_child_queue_depth,
+ worker_child_pending_cost,
+ worker_child_inflight_batches,
pull_items_fetched,
pull_batch_process_seconds,
pull_nak_unloaded_total,
@@ -730,9 +815,26 @@ mod tests {
m.messages_received_total.inc();
m.messages_acked_total.inc_by(5);
m.inflight_batches.set(3);
+ m.worker_gpu_slots_total.set(4);
+ m.worker_gpu_slots_ready.set(2);
+ m.worker_queue_depth.set(7);
+ m.worker_pending_cost.set(128);
+ m.worker_child_ready.with_label_values(&["0"]).set(1);
+ m.worker_child_models.with_label_values(&["0"]).set(1);
+ m.worker_child_queue_depth.with_label_values(&["0"]).set(3);
+ m.worker_child_pending_cost
+ .with_label_values(&["0"])
+ .set(64);
+ m.worker_child_inflight_batches
+ .with_label_values(&["0"])
+ .set(2);
assert_eq!(m.messages_received_total.get(), 1);
assert_eq!(m.messages_acked_total.get(), 5);
assert_eq!(m.inflight_batches.get(), 3);
+ assert_eq!(m.worker_gpu_slots_total.get(), 4);
+ assert_eq!(m.worker_gpu_slots_ready.get(), 2);
+ assert_eq!(m.worker_queue_depth.get(), 7);
+ assert_eq!(m.worker_pending_cost.get(), 128);
m.pull_items_fetched.with_label_values(&["m1"]).observe(4.0);
m.pull_batch_process_seconds
@@ -750,6 +852,15 @@ mod tests {
let names: Vec<&str> = families.iter().map(|f| f.name()).collect();
for expected in [
"sie_worker_messages_received_total",
+ "sie_worker_gpu_slots_total",
+ "sie_worker_gpu_slots_ready",
+ "sie_worker_queue_depth",
+ "sie_worker_pending_cost",
+ "sie_worker_child_ready",
+ "sie_worker_child_models",
+ "sie_worker_child_queue_depth",
+ "sie_worker_child_pending_cost",
+ "sie_worker_child_inflight_batches",
"sie_pull_loop_items_fetched",
"sie_pull_loop_batch_process_seconds",
"sie_pull_loop_nak_unloaded_total",
diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rs
index 9e3375aef..f5259df16 100644
--- a/packages/sie_server_sidecar/src/nats_consumer.rs
+++ b/packages/sie_server_sidecar/src/nats_consumer.rs
@@ -716,10 +716,12 @@ mod tests {
#[test]
fn config_produces_expected_names() {
let cfg = WorkerConfig {
- nats_url: String::new(),
+ nats_url: Some(String::new()),
+ local_socket_path: None,
pool: "default".into(),
bundle: "b".into(),
ipc_socket_path: PathBuf::from("/tmp/s.sock"),
+ ipc_socket_paths: vec![PathBuf::from("/tmp/s.sock")],
ipc_pool_size: 1,
ipc_request_timeout_s: 60,
model_ready_timeout_s: 900,
diff --git a/packages/sie_server_sidecar/src/observability/mod.rs b/packages/sie_server_sidecar/src/observability/mod.rs
index 8ede5f7eb..5b1ed0f92 100644
--- a/packages/sie_server_sidecar/src/observability/mod.rs
+++ b/packages/sie_server_sidecar/src/observability/mod.rs
@@ -1,7 +1,7 @@
//! Sidecar-side observability: OTLP tracing + W3C Trace Context.
//!
//! The sidecar sits on the queue hop between the gateway and the
-//! backend worker. It owns the OpenTelemetry tracer-provider setup, the
+//! adapter worker. It owns the OpenTelemetry tracer-provider setup, the
//! global W3C propagator install, and the helpers for extracting the
//! inbound gateway context off the work envelope plus injecting the
//! `sidecar.dispatch` span's context onto the IPC `RunBatchItem`s.
diff --git a/packages/sie_server_sidecar/src/observability/propagation.rs b/packages/sie_server_sidecar/src/observability/propagation.rs
index 842be195a..ed79ec679 100644
--- a/packages/sie_server_sidecar/src/observability/propagation.rs
+++ b/packages/sie_server_sidecar/src/observability/propagation.rs
@@ -10,7 +10,7 @@
//! `sidecar.dispatch` span on the result.
//!
//! 2. **In-process Context → outbound IPC item**. Before sending the
-//! [`crate::ipc_types::RunBatchItem`] to the Python worker we
+//! [`crate::ipc_types::RunBatchItem`] to the adapter worker we
//! serialise the active `sidecar.dispatch` span back into the two
//! header strings and write them onto the wire item, so the
//! worker's `worker.run_batch` span nests under the sidecar span.
diff --git a/packages/sie_server_sidecar/src/observability/tracing.rs b/packages/sie_server_sidecar/src/observability/tracing.rs
index 1548dd172..c2272e815 100644
--- a/packages/sie_server_sidecar/src/observability/tracing.rs
+++ b/packages/sie_server_sidecar/src/observability/tracing.rs
@@ -7,7 +7,7 @@
//! The W3C [`TraceContextPropagator`] is installed globally regardless
//! of that exporter gate so that the inbound gateway
//! `traceparent` (carried on the work envelope) still propagates
-//! through to the backend worker. Without an exporter the sidecar
+//! through to the adapter worker. Without an exporter the sidecar
//! itself records no spans, but the IDs continue to flow — the
//! `into_run_batch_item_with_trace` fallback in the dispatcher copies
//! the gateway context onto the wire items unchanged.
diff --git a/packages/sie_server_sidecar/src/pinned_reconciler.rs b/packages/sie_server_sidecar/src/pinned_reconciler.rs
index a0ac2fe8d..73782f6dd 100644
--- a/packages/sie_server_sidecar/src/pinned_reconciler.rs
+++ b/packages/sie_server_sidecar/src/pinned_reconciler.rs
@@ -25,8 +25,8 @@ use tokio::task::JoinHandle;
use tokio::time::{interval, MissedTickBehavior};
use tracing::{debug, info, warn};
+use crate::backend::AdapterWorkerPool;
use crate::config::WorkerConfig;
-use crate::ipc_client::IpcClient;
use crate::shutdown::Shutdown;
const HTTP_TIMEOUT: Duration = Duration::from_secs(5);
@@ -38,12 +38,17 @@ struct PinnedReconciler {
api_key: Option<String>,
poll_interval: Duration,
http: reqwest::Client,
- ipc: Arc<IpcClient>,
+ worker_pool: Arc<AdapterWorkerPool>,
/// Last set pushed to the worker (sorted), or `None` before the first
/// successful push. Starts `None` so the first authoritative fetch always
/// pushes — even an empty set — replacing any deploy-time `SIE_PINNED_MODELS`
/// bootstrap baseline.
last_pushed: Option<Vec<String>>,
+ /// Pool-side child-placement revision observed on the last successful push.
+ /// The pinned set can stay identical while a pinned model moves to a new
+ /// child after a child failure; in that case the per-child pin assignment must
+ /// be pushed again.
+ last_pushed_assignment_revision: u64,
/// Whether the previous fetch failed, so we warn once on the transition into
/// a failing state (a wedged gateway URL / api key) instead of only emitting
/// debug logs that hide a never-converging reconciler.
@@ -53,7 +58,7 @@ struct PinnedReconciler {
impl PinnedReconciler {
fn from_worker_config(
config: &WorkerConfig,
- ipc: Arc<IpcClient>,
+ worker_pool: Arc<AdapterWorkerPool>,
) -> anyhow::Result<Option<Self>> {
let Some(gateway_url) = config.gateway_url.as_deref().map(str::trim) else {
debug!("pinned-reconciler: disabled because SIE_GATEWAY_URL is unset");
@@ -74,8 +79,9 @@ impl PinnedReconciler {
// own field only if the cadences ever need to diverge.
poll_interval: Duration::from_millis(config.pool_admission_check_interval_ms),
http,
- ipc,
+ worker_pool,
last_pushed: None,
+ last_pushed_assignment_revision: 0,
last_fetch_failed: false,
}))
}
@@ -134,12 +140,25 @@ impl PinnedReconciler {
);
}
}
- if self.last_pushed.as_ref() == Some(&current) {
+ let assignment_revision = self.worker_pool.pinned_assignment_revision();
+ if self.last_pushed.as_ref() == Some(&current)
+ && self.last_pushed_assignment_revision == assignment_revision
+ {
return;
}
- match self.ipc.set_pinned_models(current.clone()).await {
+ match self.worker_pool.set_pinned_models(current.clone()).await {
Ok(resp) => {
+ if !resp.applied {
+ warn!(
+ pool = %self.pool_name,
+ worker_id = %self.worker_id,
+ count = current.len(),
+ pinned_count = resp.pinned_count,
+ "pinned-reconciler: worker pool rejected pinned set; will retry"
+ );
+ return;
+ }
info!(
pool = %self.pool_name,
worker_id = %self.worker_id,
@@ -148,6 +167,7 @@ impl PinnedReconciler {
"pinned-reconciler: pushed pinned set to worker"
);
self.last_pushed = Some(current);
+ self.last_pushed_assignment_revision = assignment_revision;
}
Err(error) => {
// Leave `last_pushed` unchanged so the next tick retries.
@@ -268,10 +288,10 @@ fn parse_pinned_models(pool: &Value) -> Vec<String> {
/// where pinned models come only from the `SIE_PINNED_MODELS` env baseline.
pub fn spawn(
config: &WorkerConfig,
- ipc: Arc<IpcClient>,
+ worker_pool: Arc<AdapterWorkerPool>,
shutdown: Arc<Shutdown>,
) -> anyhow::Result<Option<JoinHandle<()>>> {
- let Some(reconciler) = PinnedReconciler::from_worker_config(config, ipc)? else {
+ let Some(reconciler) = PinnedReconciler::from_worker_config(config, worker_pool)? else {
return Ok(None);
};
Ok(Some(tokio::spawn(async move {
diff --git a/packages/sie_server_sidecar/src/pool_admission.rs b/packages/sie_server_sidecar/src/pool_admission.rs
index 8f78e8134..52029320a 100644
--- a/packages/sie_server_sidecar/src/pool_admission.rs
+++ b/packages/sie_server_sidecar/src/pool_admission.rs
@@ -3,7 +3,7 @@
//! The gateway owns pool assignment. The sidecar polls `/v1/pools`, opens its
//! physical JetStream consumer only when the physical pool or at least one
//! backed logical pool assigns this worker, then checks every work item's
-//! `admission_pool` before backend IPC so direct NATS publishes cannot bypass
+//! `admission_pool` before adapter IPC so direct NATS publishes cannot bypass
//! the gateway's admission decision.
use std::collections::HashSet;
diff --git a/packages/sie_server_sidecar/src/prep/outcome.rs b/packages/sie_server_sidecar/src/prep/outcome.rs
index b15a41b39..16282e190 100644
--- a/packages/sie_server_sidecar/src/prep/outcome.rs
+++ b/packages/sie_server_sidecar/src/prep/outcome.rs
@@ -46,6 +46,7 @@ impl EncodeItemHandle {
tokenization_ms: None,
postprocessing_ms: None,
raw_output: None,
+ units: None,
}
}
}
@@ -68,6 +69,7 @@ pub fn encode_error_outcome(item: &EncodeBatchItem, code: &str, message: String)
tokenization_ms: None,
postprocessing_ms: None,
raw_output: None,
+ units: None,
}
}
@@ -90,6 +92,7 @@ pub fn encode_error_outcome_score(
tokenization_ms: None,
postprocessing_ms: None,
raw_output: None,
+ units: None,
}
}
diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rs
index 00185dea5..7977f359d 100644
--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs
+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs
@@ -150,6 +150,8 @@ pub struct PingResponse {
#[serde(default)]
pub worker_id: String,
#[serde(default)]
+ pub ready: bool,
+ #[serde(default)]
pub bundle_config_hash: String,
#[serde(default)]
pub loaded_models: Vec<String>,
@@ -755,6 +757,24 @@ pub struct ItemOutcome {
/// results. See [`RawOutput`] for the wire-format fallback matrix.
#[serde(default)]
pub raw_output: Option<RawOutput>,
+ /// Authoritative billable-unit counts (P3.5, design §7.3): real
+ /// tokenizer counts emitted by the engine so metering edges never
+ /// re-derive units from estimates. Optional; passed through onto the
+ /// `WorkResult` wire unchanged.
+ #[serde(default)]
+ pub units: Option<UnitCounts>,
+}
+
+/// Mirror of `sie_server.ipc_types.UnitCounts` — a field is set only when
+/// the engine holds an authoritative count for it (§7.3).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UnitCounts {
+ #[serde(default)]
+ pub input_tokens: Option<u64>,
+ #[serde(default)]
+ pub pages: Option<u64>,
+ #[serde(default)]
+ pub images: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -966,6 +986,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
raw_output: None,
+ units: None,
};
let bytes = rmp_serde::to_vec_named(&outcome).unwrap();
let back: ItemOutcome = rmp_serde::from_slice(&bytes).unwrap();
@@ -1231,6 +1252,7 @@ mod tests {
let back: PingResponse = rmp_serde::from_slice(&bytes).unwrap();
assert_eq!(back.worker_id, "w-1");
assert_eq!(back.timestamp_ms, 123.0);
+ assert!(!back.ready);
assert_eq!(back.bundle_config_hash, "");
assert!(back.loaded_models.is_empty());
}
diff --git a/packages/sie_server_sidecar/src/publisher.rs b/packages/sie_server_sidecar/src/publisher.rs
index 8d4e1242f..4eb99d28f 100644
--- a/packages/sie_server_sidecar/src/publisher.rs
+++ b/packages/sie_server_sidecar/src/publisher.rs
@@ -20,6 +20,12 @@ pub enum PublishError {
Encode(#[from] rmp_serde::encode::Error),
#[error("empty reply_subject — cannot publish")]
EmptyReplySubject,
+ /// A NATS delivery reached a dispatcher wired without a
+ /// [`WorkPublisher`] (local-ingest mode, P2.10). Unreachable by
+ /// construction; mapped to the skip-ACK path so the item stays
+ /// redeliverable if the invariant ever breaks.
+ #[error("no NATS publisher configured (local-ingest mode)")]
+ NoPublisher,
}
/// Per-item timings stamped onto `WorkResult` by the worker.
@@ -63,20 +69,7 @@ impl WorkPublisher {
) -> Result<(), PublishError> {
check_reply_subject(reply_subject)?;
- // If Python emitted `raw_output` (deferring wire framing to Rust),
- // shape it into `result_msgpack` here. Any shape error becomes an
- // error `WorkResult` so a misconfigured model cannot silently drop
- // a request.
- let owned;
- let effective = match shape_raw_output_for_wire(outcome) {
- ShapeOutcome::Unchanged => outcome,
- ShapeOutcome::Shaped(o) => {
- owned = o;
- &owned
- }
- };
-
- let result = build_work_result(effective, &self.worker_id, timings, worker_direct);
+ let result = shape_and_build_work_result(outcome, &self.worker_id, timings, worker_direct);
let bytes = rmp_serde::to_vec_named(&result)?;
debug!(
reply = %reply_subject,
@@ -216,6 +209,33 @@ fn shape(raw: &RawOutput) -> Result<Vec<u8>, ShapeError> {
))
}
+/// Shape `raw_output` (if any) into `result_msgpack` bytes, then build the
+/// gateway-facing `WorkResult`. This is the full outcome→wire conversion
+/// [`WorkPublisher::publish_result`] performs before its NATS publish;
+/// exposed as a pure function so the local-ingest path (P2.10, §4.6) —
+/// which returns `WorkResult`s over a socket instead of publishing them —
+/// produces byte-identical results.
+pub fn shape_and_build_work_result(
+ outcome: &ItemOutcome,
+ worker_id: &str,
+ timings: Option<Timings>,
+ worker_direct: bool,
+) -> WorkResult {
+ // If Python emitted `raw_output` (deferring wire framing to Rust),
+ // shape it into `result_msgpack` here. Any shape error becomes an
+ // error `WorkResult` so a misconfigured model cannot silently drop
+ // a request.
+ let owned;
+ let effective = match shape_raw_output_for_wire(outcome) {
+ ShapeOutcome::Unchanged => outcome,
+ ShapeOutcome::Shaped(o) => {
+ owned = o;
+ &owned
+ }
+ };
+ build_work_result(effective, worker_id, timings, worker_direct)
+}
+
/// Convert an `ItemOutcome` into a `WorkResult` (gateway-facing wire
/// type). `NakRetry` should never reach this path — the caller filters.
/// `timings.is_some()` → queue / processing / payload_fetch are stamped;
@@ -274,6 +294,7 @@ pub fn build_work_result(
tokenization_ms: outcome.tokenization_ms,
postprocessing_ms: outcome.postprocessing_ms,
payload_fetch_ms,
+ units: outcome.units.clone(),
worker_direct,
}
}
@@ -315,6 +336,7 @@ mod tests {
tokenization_ms: Some(1.1),
postprocessing_ms: Some(0.3),
raw_output: None,
+ units: None,
}
}
diff --git a/packages/sie_server_sidecar/src/scheduler/batch_former.rs b/packages/sie_server_sidecar/src/scheduler/batch_former.rs
index c97a4226a..6fd6dd94b 100644
--- a/packages/sie_server_sidecar/src/scheduler/batch_former.rs
+++ b/packages/sie_server_sidecar/src/scheduler/batch_former.rs
@@ -65,6 +65,7 @@ pub struct FormattedBatch<I: HasCost, T> {
pub items: Vec<I>,
pub metadata: Vec<T>,
pub total_cost: u64,
+ pub flush_reason: FlushReason,
}
impl<I: HasCost, T> FormattedBatch<I, T> {
@@ -103,6 +104,34 @@ impl<I: HasCost, T> FormattedBatch<I, T> {
items,
metadata,
total_cost: self.total_cost,
+ flush_reason: self.flush_reason,
+ }
+ }
+}
+
+/// Reason a [`BatchFormer`] emitted a batch.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FlushReason {
+ CostCap,
+ CountCap,
+ Timeout,
+ Coalesce,
+ SingleOversize,
+ IdleBypass,
+ Drain,
+}
+
+impl FlushReason {
+ #[must_use]
+ pub const fn as_label(self) -> &'static str {
+ match self {
+ Self::CostCap => "cost_cap",
+ Self::CountCap => "count_cap",
+ Self::Timeout => "timeout",
+ Self::Coalesce => "coalesce",
+ Self::SingleOversize => "single_oversize",
+ Self::IdleBypass => "idle_bypass",
+ Self::Drain => "drain",
}
}
}
@@ -256,8 +285,8 @@ impl<I: HasCost, T> BatchFormer<I, T> {
let wait = {
let mut guard = self.inner.lock().await;
- if !guard.pending.is_empty() && (should_yield_batch(&guard) || immediate) {
- return extract_batch(&mut guard);
+ if let Some(reason) = flush_reason(&guard, immediate) {
+ return extract_batch(&mut guard, reason);
}
notified.as_mut().enable();
wait_timeout(&guard)
@@ -292,11 +321,8 @@ impl<I: HasCost, T> BatchFormer<I, T> {
/// hold, else return `None`. Matches Python's `try_get_batch`.
pub async fn try_get_batch(&self) -> Option<FormattedBatch<I, T>> {
let mut guard = self.inner.lock().await;
- if should_yield_batch(&guard) {
- Some(extract_batch(&mut guard))
- } else {
- None
- }
+ let reason = flush_reason(&guard, false)?;
+ Some(extract_batch(&mut guard, reason))
}
/// Drain whatever is pending right now, bypassing the flush
@@ -307,7 +333,7 @@ impl<I: HasCost, T> BatchFormer<I, T> {
if guard.pending.is_empty() {
None
} else {
- Some(extract_batch(&mut guard))
+ Some(extract_batch(&mut guard, FlushReason::Drain))
}
}
}
@@ -341,11 +367,6 @@ fn append_item<I: HasCost, T>(inner: &mut Inner<I, T>, item: I, metadata: T) ->
should_yield_batch(inner) || is_first
}
-fn batch_is_full<I: HasCost, T>(inner: &Inner<I, T>) -> bool {
- inner.total_cost >= inner.config.max_batch_cost
- || inner.pending.len() >= inner.config.max_batch_requests
-}
-
fn batch_timeout_expired<I: HasCost, T>(inner: &Inner<I, T>) -> bool {
let Some(first) = inner.first_request_time else {
return false;
@@ -366,10 +387,32 @@ fn coalesce_expired<I: HasCost, T>(inner: &Inner<I, T>) -> bool {
}
fn should_yield_batch<I: HasCost, T>(inner: &Inner<I, T>) -> bool {
+ flush_reason(inner, false).is_some()
+}
+
+fn flush_reason<I: HasCost, T>(inner: &Inner<I, T>, immediate: bool) -> Option<FlushReason> {
if inner.pending.is_empty() {
- return false;
+ return None;
+ }
+ if inner.pending.len() == 1 && inner.total_cost > inner.config.max_batch_cost {
+ return Some(FlushReason::SingleOversize);
+ }
+ if inner.total_cost >= inner.config.max_batch_cost {
+ return Some(FlushReason::CostCap);
}
- batch_is_full(inner) || batch_timeout_expired(inner) || coalesce_expired(inner)
+ if inner.pending.len() >= inner.config.max_batch_requests {
+ return Some(FlushReason::CountCap);
+ }
+ if batch_timeout_expired(inner) {
+ return Some(FlushReason::Timeout);
+ }
+ if coalesce_expired(inner) {
+ return Some(FlushReason::Coalesce);
+ }
+ if immediate {
+ return Some(FlushReason::IdleBypass);
+ }
+ None
}
/// Time remaining until the next guaranteed flush, given current
@@ -395,7 +438,10 @@ fn wait_timeout<I: HasCost, T>(inner: &Inner<I, T>) -> Option<Duration> {
Some(Duration::from_secs_f64(effective_ms.max(0.0) / 1000.0))
}
-fn extract_batch<I: HasCost, T>(inner: &mut Inner<I, T>) -> FormattedBatch<I, T> {
+fn extract_batch<I: HasCost, T>(
+ inner: &mut Inner<I, T>,
+ flush_reason: FlushReason,
+) -> FormattedBatch<I, T> {
// Cost-sort pending before slicing — keeps each sub-batch's
// items close in length, minimising padding waste on the adapter
// side. Stable sort preserves FIFO order within equal-cost items
@@ -448,6 +494,7 @@ fn extract_batch<I: HasCost, T>(inner: &mut Inner<I, T>) -> FormattedBatch<I, T>
items,
metadata,
total_cost: batch_cost,
+ flush_reason,
}
}
@@ -494,6 +541,7 @@ mod tests {
let batch = b.try_drain().await.expect("drain should succeed");
assert_eq!(batch.size(), 2);
assert_eq!(batch.total_cost, 30);
+ assert_eq!(batch.flush_reason, FlushReason::Drain);
assert_eq!(b.pending_count().await, 0);
assert_eq!(b.pending_cost().await, 0);
}
@@ -514,6 +562,7 @@ mod tests {
let batch = b.try_get_batch().await.expect("cost cap should trigger");
assert_eq!(batch.size(), 2);
assert_eq!(batch.total_cost, 30);
+ assert_eq!(batch.flush_reason, FlushReason::CostCap);
}
#[tokio::test]
@@ -531,6 +580,7 @@ mod tests {
b.submit(StubItem::new(1), 3).await;
let batch = b.try_get_batch().await.expect("count cap should trigger");
assert_eq!(batch.size(), 3);
+ assert_eq!(batch.flush_reason, FlushReason::CountCap);
}
#[tokio::test]
@@ -561,10 +611,13 @@ mod tests {
let b = BatchFormer::<StubItem, u32>::new(cfg);
b.submit(StubItem::new(500), 1).await; // cost >> cap
- // try_drain always returns, regardless of cap status.
- let batch = b.try_drain().await.expect("oversize should still flush");
+ let batch = b
+ .try_get_batch()
+ .await
+ .expect("oversize should still flush");
assert_eq!(batch.size(), 1);
assert_eq!(batch.total_cost, 500);
+ assert_eq!(batch.flush_reason, FlushReason::SingleOversize);
}
#[tokio::test]
@@ -609,6 +662,7 @@ mod tests {
// returns as soon as the single pending item is visible.
let batch = b.get_batch(true).await;
assert_eq!(batch.size(), 1);
+ assert_eq!(batch.flush_reason, FlushReason::IdleBypass);
}
#[tokio::test]
@@ -634,7 +688,7 @@ mod tests {
max_batch_requests: 1000,
max_batch_wait_ms: 20.0,
coalesce_ms: 1_000.0,
- coalesce_ratio: 0.99, // proportional ≈ 19.8 — fires at ~20 ms
+ coalesce_ratio: 1.0, // coalesce ties max-wait; timeout wins by priority
};
let b = BatchFormer::<StubItem, u32>::new(cfg);
b.submit(StubItem::new(1), 1).await;
@@ -647,6 +701,7 @@ mod tests {
.expect("must flush on timeout within 200 ms");
let elapsed_ms = start.elapsed().as_millis();
assert_eq!(batch.size(), 1);
+ assert_eq!(batch.flush_reason, FlushReason::Timeout);
assert!(
elapsed_ms >= 15,
"must wait at least ~max_batch_wait_ms before flushing (waited {elapsed_ms} ms)"
diff --git a/packages/sie_server_sidecar/src/scheduler/item.rs b/packages/sie_server_sidecar/src/scheduler/item.rs
index 5e0ac3465..930a664a7 100644
--- a/packages/sie_server_sidecar/src/scheduler/item.rs
+++ b/packages/sie_server_sidecar/src/scheduler/item.rs
@@ -45,8 +45,7 @@
use std::time::Instant;
-use async_nats::jetstream::Message;
-
+use crate::delivery::Delivery;
use crate::ipc_types::{
EncodeBatchItem, ExtractBatchItem, PreparedTokens, RunBatchItem, ScoreBatchItem,
};
@@ -157,20 +156,23 @@ impl HasCost for SchedulerItem {
/// through the scheduler to finish the request lifecycle on the
/// other side.
///
-/// Not `Clone`: the JetStream [`Message`] owns the ACK/NAK token,
-/// which must not be duplicated. The scheduler moves items by value
-/// (vec of `(item, metadata)` into the batcher, vec back out of the
-/// flushed [`crate::scheduler::batch_former::FormattedBatch`]), so
+/// Not `Clone`: on the NATS arm the JetStream `Message` inside
+/// [`Delivery`] owns the ACK/NAK token, which must not be duplicated.
+/// The scheduler moves items by value (vec of `(item, metadata)` into
+/// the batcher, vec back out of the flushed
+/// [`crate::scheduler::batch_former::FormattedBatch`]), so
/// single-ownership is preserved end-to-end.
pub struct SchedulerMeta {
/// The parsed work item — needed for `publish_result` / `publish_error`
/// (reply subject, request id, timings, output types, etc.).
pub wi: WorkItem,
- /// JetStream message — owns the ACK / NAK. Dropping it without
- /// either is safe but leaks: JetStream will redeliver after
- /// `ack_wait` expires. The drain loop is responsible for ACKing
- /// on success and NAKing on backend failure.
- pub msg: Message,
+ /// Settlement token (NATS message or local-ingest slot, P2.10 §4.6)
+ /// — owns the ACK / NAK. Dropping a NATS one without either is safe
+ /// but leaks: JetStream redelivers after `ack_wait` expires; a local
+ /// one surfaces at the ingest layer as a missing-result timeout. The
+ /// drain loop is responsible for ACKing on success and NAKing on
+ /// backend failure.
+ pub delivery: Delivery,
/// Payload-store fetch latency (ms). Surfaced on the published
/// [`crate::publisher::Timings`] and on the `payload_fetch_seconds`
/// histogram.
@@ -183,44 +185,56 @@ pub struct SchedulerMeta {
/// driven by its own `head_ns` atomic (see
/// [`super::engine::Scheduler`]).
pub submitted_at: Instant,
+ /// Adapter worker child selected by the sidecar when this item entered
+ /// the scheduler. Used to keep per-child queue-pressure metrics
+ /// balanced even if model placement changes before the batch flushes.
+ pub worker_child_index: Option<usize>,
}
impl SchedulerMeta {
/// Construct the standard triple stamped with `Instant::now`.
#[must_use]
- pub fn new(wi: WorkItem, msg: Message, fetch_ms: f64) -> Self {
- Self::new_with_worker_direct(wi, msg, fetch_ms, false)
+ pub fn new(wi: WorkItem, delivery: Delivery, fetch_ms: f64) -> Self {
+ Self::new_with_worker_direct(wi, delivery, fetch_ms, false)
}
/// Construct metadata with an explicit delivery-origin marker.
#[must_use]
pub fn new_with_worker_direct(
wi: WorkItem,
- msg: Message,
+ delivery: Delivery,
fetch_ms: f64,
worker_direct: bool,
) -> Self {
Self {
wi,
- msg,
+ delivery,
fetch_ms,
worker_direct,
submitted_at: Instant::now(),
+ worker_child_index: None,
}
}
+
+ #[must_use]
+ pub fn with_worker_child_index(mut self, child_index: usize) -> Self {
+ self.worker_child_index = Some(child_index);
+ self
+ }
}
impl std::fmt::Debug for SchedulerMeta {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- // `Message` intentionally doesn't implement Debug in a
- // useful way for our purposes — skip it. The rest is cheap
- // to print.
+ // The NATS `Message` inside `Delivery` intentionally doesn't
+ // implement Debug in a useful way for our purposes — skip it.
+ // The rest is cheap to print.
f.debug_struct("SchedulerMeta")
.field("wi_work_item_id", &self.wi.work_item_id)
.field("wi_request_id", &self.wi.request_id)
.field("fetch_ms", &self.fetch_ms)
.field("worker_direct", &self.worker_direct)
.field("submitted_at", &self.submitted_at)
+ .field("worker_child_index", &self.worker_child_index)
.finish_non_exhaustive()
}
}
diff --git a/packages/sie_server_sidecar/src/scheduler/metrics.rs b/packages/sie_server_sidecar/src/scheduler/metrics.rs
index f94ee8ac7..f45e467a6 100644
--- a/packages/sie_server_sidecar/src/scheduler/metrics.rs
+++ b/packages/sie_server_sidecar/src/scheduler/metrics.rs
@@ -15,12 +15,10 @@
//! * [`SchedulerMetrics::models_total`] — live IntGauge of models
//! that have had a scheduler materialised.
//!
-//! The adaptive-controller gauges, starvation counter,
-//! `flush_reason_total`, `active_batchers`, and `hol_wait_ms_mean`
-//! families are declared so the `/metrics` scrape shape stays stable
-//! across builds, but are not yet populated. They will be wired when
-//! we have a concrete operational need; keeping the surface declared
-//! means dashboards can be authored now without a second deploy.
+//! The adaptive-controller gauges, starvation counter, active-batcher,
+//! and head-of-line families are declared alongside the hot batch
+//! shape counters so the `/metrics` scrape shape stays stable across
+//! builds.
//!
//! ## Label cardinality
//!
@@ -59,7 +57,7 @@ pub const FLUSH_REASONS: &[&str] = &[
"timeout",
"coalesce",
"single_oversize",
- "update_tightened",
+ "idle_bypass",
"drain",
];
@@ -157,7 +155,7 @@ impl SchedulerMetrics {
let flush_reason_total = IntCounterVec::new(
Opts::new(
"sie_worker_scheduler_flush_reason_total",
- "Scheduler flush triggers. `reason` ∈ cost_cap | count_cap | timeout | coalesce | single_oversize | update_tightened | drain",
+ "Scheduler flush triggers. `reason` ∈ cost_cap | count_cap | timeout | coalesce | single_oversize | idle_bypass | drain",
),
&["model", "operation", "lora", "reason"],
)?;
@@ -282,8 +280,18 @@ mod tests {
for r in FLUSH_REASONS {
assert!(!r.is_empty());
}
+ let batcher_reasons = [
+ super::super::FlushReason::CostCap.as_label(),
+ super::super::FlushReason::CountCap.as_label(),
+ super::super::FlushReason::Timeout.as_label(),
+ super::super::FlushReason::Coalesce.as_label(),
+ super::super::FlushReason::SingleOversize.as_label(),
+ super::super::FlushReason::IdleBypass.as_label(),
+ super::super::FlushReason::Drain.as_label(),
+ ];
+ assert_eq!(FLUSH_REASONS, batcher_reasons.as_slice());
// 7 triggers today: cost_cap, count_cap, timeout, coalesce,
- // single_oversize, update_tightened, drain.
+ // single_oversize, idle_bypass, drain.
assert_eq!(FLUSH_REASONS.len(), 7);
}
diff --git a/packages/sie_server_sidecar/src/scheduler/mod.rs b/packages/sie_server_sidecar/src/scheduler/mod.rs
index 0a4ee47d9..ea8b866f5 100644
--- a/packages/sie_server_sidecar/src/scheduler/mod.rs
+++ b/packages/sie_server_sidecar/src/scheduler/mod.rs
@@ -48,7 +48,7 @@ pub mod trackers;
pub use adaptive::{AdaptiveBatchController, AdaptiveBatchControllerBuilder, AdaptiveBatchState};
pub use batch_config::BatchConfig;
-pub use batch_former::{BatchFormer, FormattedBatch, HasCost, PendingRequest};
+pub use batch_former::{BatchFormer, FlushReason, FormattedBatch, HasCost, PendingRequest};
pub use engine::{LoraKey, Op, RecordCompletionOutcome, Scheduler, SchedulerBuilder};
pub use item::{lora_from_options, SchedulerItem, SchedulerMeta};
pub use metrics::{SchedulerMetrics, FLUSH_REASONS};
diff --git a/packages/sie_server_sidecar/src/work_types.rs b/packages/sie_server_sidecar/src/work_types.rs
index b103a3157..8c5729820 100644
--- a/packages/sie_server_sidecar/src/work_types.rs
+++ b/packages/sie_server_sidecar/src/work_types.rs
@@ -109,6 +109,11 @@ pub struct WorkResult {
pub postprocessing_ms: Option<f64>,
#[serde(default)]
pub payload_fetch_ms: Option<f64>,
+ /// Authoritative billable-unit counts passed through from the engine's
+ /// `ItemOutcome.units` (P3.5, design §7.3). `skip_serializing_if` keeps
+ /// legacy consumers' maps unchanged when absent.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub units: Option<crate::ipc_types::UnitCounts>,
#[serde(default)]
pub worker_direct: bool,
}
@@ -254,6 +259,7 @@ mod tests {
tokenization_ms: None,
postprocessing_ms: None,
payload_fetch_ms: None,
+ units: None,
worker_direct: true,
};
let bytes = rmp_serde::to_vec_named(&result).unwrap();
diff --git a/packages/sie_server_sidecar/tests/local_ingest_loopback.rs b/packages/sie_server_sidecar/tests/local_ingest_loopback.rs
new file mode 100644
index 000000000..953705f7b
--- /dev/null
+++ b/packages/sie_server_sidecar/tests/local_ingest_loopback.rs
@@ -0,0 +1,539 @@
+//! Loopback test for the local-ingest mode.
+//!
+//! What this proves:
+//! * `sie-server-sidecar --ingest local` starts with **no NATS server**
+//! anywhere (the mode's whole point).
+//! * The UDS listener speaks the wire protocol v0.1: u32-LE frame + msgpack
+//! `{id, op, body}` envelopes; `ping`, `publish_work`, unknown-op
+//! error envelope.
+//! * `publish_work` WorkItem bytes flow through the real dispatcher →
+//! scheduler → IPC backend pipeline against the Python IPC harness
+//! (`sie_server._ipc_test_harness`) and come back as an ordered
+//! msgpack `WorkResult` array over the socket.
+//! * The admission re-check and the generate-op rejection answer
+//! typed error results instead of NAK-looping.
+//!
+//! Not proven here: real inference (the harness returns canned payloads)
+//! — that is covered by the E2E verify step.
+
+use std::path::PathBuf;
+use std::process::Stdio;
+use std::time::{Duration, Instant};
+
+use sie_server_sidecar::work_types::{WorkItem, WorkResult};
+use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
+use tokio::net::UnixStream;
+use tokio::process::{Child, Command};
+use tokio::time::{sleep, timeout};
+
+// ---------------------------------------------------------------------------
+// Tool / path helpers (self-contained twin of integration_smoke.rs — Rust
+// integration tests are separate crates, so no shared module without a
+// common-file refactor that isn't worth it for two files).
+// ---------------------------------------------------------------------------
+
+fn which(bin: &str) -> Option<PathBuf> {
+ std::env::var_os("PATH").and_then(|paths| {
+ std::env::split_paths(&paths).find_map(|dir| {
+ let p = dir.join(bin);
+ if p.is_file() {
+ Some(p)
+ } else {
+ None
+ }
+ })
+ })
+}
+
+fn skip_unless_tools_available() -> bool {
+ if which("mise").is_none() && which("uv").is_none() {
+ eprintln!("local_ingest_loopback: skipping — missing mise/uv on $PATH");
+ return true;
+ }
+ // The fake engine is `sie_server._ipc_test_harness` from the Python
+ // workspace. Rust-only CI jobs check out the repo without syncing the
+ // Python venv, so probe importability the same way the harness is
+ // spawned and skip (not fail) when the module cannot load.
+ let (program, base_args) = harness_launcher();
+ let importable = std::process::Command::new(program)
+ .current_dir(workspace_root())
+ .args(&base_args)
+ .args(["python", "-c", "import sie_server._ipc_test_harness"])
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()
+ .map(|s| s.success())
+ .unwrap_or(false);
+ if !importable {
+ eprintln!(
+ "local_ingest_loopback: skipping — sie_server._ipc_test_harness not \
+ importable (Python workspace not synced in this environment)"
+ );
+ return true;
+ }
+ false
+}
+
+/// Program + base args used to run workspace Python (mise-managed uv when
+/// available, bare uv otherwise) — shared by the skip probe and the harness.
+fn harness_launcher() -> (&'static str, Vec<String>) {
+ if which("mise").is_some() {
+ (
+ "mise",
+ vec![
+ "exec".to_string(),
+ "--".to_string(),
+ "uv".to_string(),
+ "run".to_string(),
+ "--no-sync".to_string(),
+ ],
+ )
+ } else {
+ ("uv", vec!["run".to_string(), "--no-sync".to_string()])
+ }
+}
+
+fn workspace_root() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("..")
+ .join("..")
+ .canonicalize()
+ .expect("canonicalize workspace root")
+}
+
+struct ShortSocket {
+ path: PathBuf,
+ _dir: tempfile::TempDir,
+}
+
+impl ShortSocket {
+ fn new(name: &str) -> Self {
+ let dir = tempfile::Builder::new()
+ .prefix("sieli-")
+ .tempdir_in("/tmp")
+ .expect("create short socket dir");
+ let path = dir.path().join(name);
+ Self { path, _dir: dir }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Python IPC harness (fake engine)
+// ---------------------------------------------------------------------------
+
+struct PythonHarness {
+ child: Child,
+ socket_path: PathBuf,
+}
+
+impl PythonHarness {
+ async fn start(socket_path: PathBuf) -> Self {
+ let (program, base_args) = harness_launcher();
+ let mut cmd = Command::new(program);
+ cmd.current_dir(workspace_root())
+ .args(&base_args)
+ .args([
+ "python",
+ "-m",
+ "sie_server._ipc_test_harness",
+ "--socket",
+ socket_path.to_str().unwrap(),
+ "--worker-id",
+ "loopback-harness",
+ "--log-level",
+ "INFO",
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true);
+ let mut child = cmd.spawn().expect("spawn python harness");
+
+ let stdout = child.stdout.take().expect("stdout");
+ let mut reader = BufReader::new(stdout).lines();
+ let ready_deadline = Instant::now() + Duration::from_secs(45);
+ let mut ready = false;
+ while Instant::now() < ready_deadline {
+ match timeout(Duration::from_millis(500), reader.next_line()).await {
+ Ok(Ok(Some(line))) => {
+ eprintln!("[python-harness] {line}");
+ if line.contains("HARNESS_READY") {
+ ready = true;
+ break;
+ }
+ }
+ Ok(Ok(None)) => break,
+ Ok(Err(e)) => panic!("read python stdout: {e}"),
+ Err(_) => {
+ if let Some(status) = child.try_wait().expect("try_wait") {
+ panic!("python harness exited early: status={status:?}");
+ }
+ }
+ }
+ }
+ assert!(ready, "python harness never printed HARNESS_READY");
+ tokio::spawn(async move {
+ while let Ok(Some(line)) = reader.next_line().await {
+ eprintln!("[python-harness] {line}");
+ }
+ });
+ if let Some(stderr) = child.stderr.take() {
+ let mut stderr_reader = BufReader::new(stderr).lines();
+ tokio::spawn(async move {
+ while let Ok(Some(line)) = stderr_reader.next_line().await {
+ eprintln!("[python-harness:stderr] {line}");
+ }
+ });
+ }
+ Self { child, socket_path }
+ }
+}
+
+impl Drop for PythonHarness {
+ fn drop(&mut self) {
+ let _ = self.child.start_kill();
+ let _ = std::fs::remove_file(&self.socket_path);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Sidecar in local-ingest mode
+// ---------------------------------------------------------------------------
+
+struct LocalWorkerHarness {
+ child: Child,
+}
+
+impl LocalWorkerHarness {
+ fn spawn(ipc_socket: &std::path::Path, local_socket: &std::path::Path) -> Self {
+ let exe = env!("CARGO_BIN_EXE_sie-server-sidecar");
+ let mut cmd = Command::new(exe);
+ cmd.env("SIE_SIDECAR_INGEST", "local")
+ .env("SIE_SIDECAR_LOCAL_SOCKET", local_socket)
+ .env("SIE_POOL", "default")
+ .env("SIE_MACHINE_PROFILE", "l4")
+ .env("SIE_BUNDLE", "default")
+ .env("SIE_IPC_SOCKET_PATH", ipc_socket)
+ .env("SIE_WORKER_METRICS_PORT", free_tcp_port().to_string())
+ .env("SIE_WORKER_ID", "loopback-worker")
+ .env("SIE_WORKER_PING_INTERVAL_MS", "500")
+ .env("RUST_LOG", "info,sie_server_sidecar=debug")
+ // Explicitly NO SIE_NATS_URL: local mode must not need it.
+ .env_remove("SIE_NATS_URL")
+ .stdout(Stdio::inherit())
+ .stderr(Stdio::inherit())
+ .kill_on_drop(true);
+ let child = cmd.spawn().expect("spawn sie-server-sidecar (local)");
+ Self { child }
+ }
+}
+
+impl Drop for LocalWorkerHarness {
+ fn drop(&mut self) {
+ let _ = self.child.start_kill();
+ }
+}
+
+fn free_tcp_port() -> u16 {
+ std::net::TcpListener::bind("127.0.0.1:0")
+ .expect("bind ephemeral port")
+ .local_addr()
+ .unwrap()
+ .port()
+}
+
+// ---------------------------------------------------------------------------
+// Wire protocol v0.1 client
+// ---------------------------------------------------------------------------
+
+async fn connect_with_retry(path: &std::path::Path, budget: Duration) -> UnixStream {
+ let deadline = Instant::now() + budget;
+ loop {
+ if let Ok(stream) = UnixStream::connect(path).await {
+ return stream;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "local ingest socket never came up: {}",
+ path.display()
+ );
+ sleep(Duration::from_millis(100)).await;
+ }
+}
+
+async fn send_request(stream: &mut UnixStream, id: u64, op: &str, body: rmpv::Value) {
+ let map = rmpv::Value::Map(vec![
+ (rmpv::Value::from("id"), rmpv::Value::from(id)),
+ (rmpv::Value::from("op"), rmpv::Value::from(op)),
+ (rmpv::Value::from("body"), body),
+ ]);
+ let mut payload = Vec::new();
+ rmpv::encode::write_value(&mut payload, &map).unwrap();
+ let mut frame = Vec::with_capacity(4 + payload.len());
+ frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());
+ frame.extend_from_slice(&payload);
+ stream.write_all(&frame).await.expect("write frame");
+}
+
+async fn read_response(stream: &mut UnixStream) -> rmpv::Value {
+ let mut header = [0u8; 4];
+ stream.read_exact(&mut header).await.expect("read header");
+ let len = u32::from_le_bytes(header) as usize;
+ let mut payload = vec![0u8; len];
+ stream.read_exact(&mut payload).await.expect("read payload");
+ rmpv::decode::read_value(&mut payload.as_slice()).expect("decode response")
+}
+
+fn map_get<'a>(value: &'a rmpv::Value, key: &str) -> Option<&'a rmpv::Value> {
+ let rmpv::Value::Map(entries) = value else {
+ return None;
+ };
+ entries
+ .iter()
+ .find(|(k, _)| matches!(k, rmpv::Value::String(s) if s.as_str() == Some(key)))
+ .map(|(_, v)| v)
+}
+
+fn work_item(request_id: &str, idx: u32, total: u32, op: &str, admission_pool: &str) -> WorkItem {
+ WorkItem {
+ work_item_id: format!("{request_id}.{idx}"),
+ request_id: request_id.to_string(),
+ item_index: idx,
+ total_items: total,
+ operation: op.into(),
+ model_id: "BAAI/bge-m3".into(),
+ profile_id: "default".into(),
+ engine: String::new(),
+ pool_name: "default".into(),
+ admission_pool: admission_pool.into(),
+ machine_profile: "l4".into(),
+ item: Some(rmpv::Value::Map(vec![(
+ rmpv::Value::from("text"),
+ rmpv::Value::from(format!("loopback text {idx}")),
+ )])),
+ payload_ref: None,
+ output_types: Some(vec!["dense".into()]),
+ instruction: None,
+ is_query: false,
+ options: None,
+ query_item: None,
+ query_payload_ref: None,
+ score_items: None,
+ labels: None,
+ output_schema: None,
+ generate: None,
+ routing_key: None,
+ prompt_cache_key: None,
+ bundle_config_hash: String::new(),
+ router_id: "loopback".into(),
+ reply_subject: String::new(), // NATS-only field; unused on this path
+ traceparent: None,
+ tracestate: None,
+ timestamp: 0.0,
+ }
+}
+
+fn publish_work_body(items: &[WorkItem], admission_pool: &str, timeout_ms: i64) -> rmpv::Value {
+ let items_bytes = rmp_serde::to_vec_named(items).expect("encode items");
+ rmpv::Value::Map(vec![
+ (
+ rmpv::Value::from("lane"),
+ rmpv::Value::from("default|l4|default"),
+ ),
+ (rmpv::Value::from("endpoint"), rmpv::Value::from("encode")),
+ (rmpv::Value::from("model"), rmpv::Value::from("BAAI/bge-m3")),
+ (rmpv::Value::from("engine"), rmpv::Value::from("")),
+ (
+ rmpv::Value::from("admission_pool"),
+ rmpv::Value::from(admission_pool),
+ ),
+ (
+ rmpv::Value::from("bundle_config_hash"),
+ rmpv::Value::from(""),
+ ),
+ (
+ rmpv::Value::from("request_id"),
+ rmpv::Value::from(items.first().map(|i| i.request_id.as_str()).unwrap_or("")),
+ ),
+ (
+ rmpv::Value::from("params"),
+ rmpv::Value::Binary(rmp_serde::to_vec_named(&serde_json::json!({})).unwrap()),
+ ),
+ (rmpv::Value::from("items"), rmpv::Value::Binary(items_bytes)),
+ (
+ rmpv::Value::from("timeout_ms"),
+ rmpv::Value::from(timeout_ms),
+ ),
+ ])
+}
+
+fn decode_results(response: &rmpv::Value) -> Vec<WorkResult> {
+ assert_eq!(
+ map_get(response, "ok").and_then(rmpv::Value::as_bool),
+ Some(true),
+ "publish_work not ok: {response:?}"
+ );
+ let body = map_get(response, "body").expect("body present");
+ let results = map_get(body, "results").expect("results present");
+ let rmpv::Value::Binary(bytes) = results else {
+ panic!("results should be msgpack bin, got {results:?}");
+ };
+ rmp_serde::from_slice(bytes).expect("decode WorkResult array")
+}
+
+// ---------------------------------------------------------------------------
+// The test
+// ---------------------------------------------------------------------------
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn local_ingest_round_trips_publish_work_without_nats() {
+ if skip_unless_tools_available() {
+ return;
+ }
+
+ let ipc_sock = ShortSocket::new("ipc.sock");
+ let ingest_sock = ShortSocket::new("ingest.sock");
+ let _python = PythonHarness::start(ipc_sock.path.clone()).await;
+ let _worker = LocalWorkerHarness::spawn(&ipc_sock.path, &ingest_sock.path);
+
+ let mut stream = connect_with_retry(&ingest_sock.path, Duration::from_secs(30)).await;
+
+ // 1. ping
+ send_request(&mut stream, 1, "ping", rmpv::Value::Map(vec![])).await;
+ let resp = read_response(&mut stream).await;
+ assert_eq!(map_get(&resp, "id").and_then(rmpv::Value::as_u64), Some(1));
+ assert_eq!(
+ map_get(&resp, "ok").and_then(rmpv::Value::as_bool),
+ Some(true)
+ );
+
+ // 2. publish_work: 3 encode items -> 3 ordered successful WorkResults.
+ let items: Vec<WorkItem> = (0..3)
+ .map(|i| work_item("li-req-1", i, 3, "encode", "default"))
+ .collect();
+ send_request(
+ &mut stream,
+ 2,
+ "publish_work",
+ publish_work_body(&items, "default", 60_000),
+ )
+ .await;
+ let resp = timeout(Duration::from_secs(60), read_response(&mut stream))
+ .await
+ .expect("publish_work answered within budget");
+ assert_eq!(map_get(&resp, "id").and_then(rmpv::Value::as_u64), Some(2));
+ let results = decode_results(&resp);
+ assert_eq!(results.len(), 3);
+ for (i, r) in results.iter().enumerate() {
+ assert!(
+ r.success,
+ "item {i} failed: {:?} {:?}",
+ r.error_code, r.error
+ );
+ assert_eq!(r.item_index, i as u32, "results must be in input order");
+ assert_eq!(r.work_item_id, format!("li-req-1.{i}"));
+ assert_eq!(r.worker_id.as_deref(), Some("loopback-worker"));
+ assert!(!r.result_msgpack.is_empty());
+ // The harness cans a msgpack map with smoke=ok.
+ let payload: rmpv::Value =
+ rmp_serde::from_slice(&r.result_msgpack).expect("payload decodes");
+ assert_eq!(
+ map_get(&payload, "smoke").and_then(|v| v.as_str().map(str::to_string)),
+ Some("ok".to_string())
+ );
+ }
+
+ // 3. Admission re-check: foreign pool -> typed errors, not a hang.
+ let foreign: Vec<WorkItem> = (0..2)
+ .map(|i| work_item("li-req-2", i, 2, "encode", "other-pool"))
+ .collect();
+ send_request(
+ &mut stream,
+ 3,
+ "publish_work",
+ publish_work_body(&foreign, "other-pool", 30_000),
+ )
+ .await;
+ let resp = timeout(Duration::from_secs(30), read_response(&mut stream))
+ .await
+ .expect("admission rejection answered");
+ let results = decode_results(&resp);
+ assert_eq!(results.len(), 2);
+ for r in &results {
+ assert!(!r.success);
+ assert_eq!(r.error_code.as_deref(), Some("pool_admission_rejected"));
+ }
+
+ // 4. generate op -> typed bad_operation error (streaming lands later).
+ let gen = vec![work_item("li-req-3", 0, 1, "generate", "default")];
+ send_request(
+ &mut stream,
+ 4,
+ "publish_work",
+ publish_work_body(&gen, "default", 30_000),
+ )
+ .await;
+ let resp = timeout(Duration::from_secs(30), read_response(&mut stream))
+ .await
+ .expect("generate rejection answered");
+ let results = decode_results(&resp);
+ assert_eq!(results.len(), 1);
+ assert!(!results[0].success);
+ assert_eq!(results[0].error_code.as_deref(), Some("bad_operation"));
+
+ // 5. unknown op -> ok=false envelope, connection stays usable.
+ send_request(&mut stream, 5, "warp", rmpv::Value::Map(vec![])).await;
+ let resp = read_response(&mut stream).await;
+ assert_eq!(
+ map_get(&resp, "ok").and_then(rmpv::Value::as_bool),
+ Some(false)
+ );
+ assert!(map_get(&resp, "error")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .contains("unknown op"));
+ send_request(&mut stream, 6, "ping", rmpv::Value::Map(vec![])).await;
+ let resp = read_response(&mut stream).await;
+ assert_eq!(
+ map_get(&resp, "ok").and_then(rmpv::Value::as_bool),
+ Some(true)
+ );
+
+ // 6. Concurrent publish_work calls on separate connections coalesce in
+ // the same scheduler without cross-talk.
+ let path_a = ingest_sock.path.clone();
+ let path_b = ingest_sock.path.clone();
+ let (ra, rb) = tokio::join!(
+ async move {
+ let mut s = connect_with_retry(&path_a, Duration::from_secs(5)).await;
+ let items: Vec<WorkItem> = (0..4)
+ .map(|i| work_item("li-conc-a", i, 4, "encode", "default"))
+ .collect();
+ send_request(
+ &mut s,
+ 10,
+ "publish_work",
+ publish_work_body(&items, "default", 60_000),
+ )
+ .await;
+ decode_results(&read_response(&mut s).await)
+ },
+ async move {
+ let mut s = connect_with_retry(&path_b, Duration::from_secs(5)).await;
+ let items: Vec<WorkItem> = (0..4)
+ .map(|i| work_item("li-conc-b", i, 4, "encode", "default"))
+ .collect();
+ send_request(
+ &mut s,
+ 11,
+ "publish_work",
+ publish_work_body(&items, "default", 60_000),
+ )
+ .await;
+ decode_results(&read_response(&mut s).await)
+ },
+ );
+ assert_eq!(ra.len(), 4);
+ assert_eq!(rb.len(), 4);
+ assert!(ra.iter().all(|r| r.success && r.request_id == "li-conc-a"));
+ assert!(rb.iter().all(|r| r.success && r.request_id == "li-conc-b"));
+}
diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.json
index 0fa59740b..f443fdb8f 100644
--- a/packages/sie_ts_sdk/package.json
+++ b/packages/sie_ts_sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-sdk",
- "version": "0.6.16",
+ "version": "0.6.17",
"description": "Official TypeScript SDK for SIE (Search Inference Engine)",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index 3c18131df..f6881b8d1 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -34,17 +34,23 @@ import {
PoolError,
ProvisioningError,
RequestError,
+ ResourceExhaustedError,
SIEConnectionError,
SIEStreamError,
+ ServerError,
} from "./errors.js";
import { toImageWireFormat } from "./images.js";
import type { ImageInput, ImageWireFormat } from "./images.js";
import {
+ DEFAULT_JOB_WAIT_POLL,
+ DEFAULT_JOB_WAIT_TIMEOUT,
DEFAULT_LEASE_RENEWAL_INTERVAL,
+ DEFAULT_LONG_RUNNING_TIMEOUT,
DEFAULT_PROVISION_TIMEOUT,
DEFAULT_RETRY_DELAY,
DEFAULT_TIMEOUT,
HTTP_CLIENT_ERROR_MIN,
+ HTTP_GATEWAY_TIMEOUT,
JSON_CONTENT_TYPE,
LORA_LOADING_DEFAULT_DELAY,
LORA_LOADING_ERROR_CODE,
@@ -53,6 +59,8 @@ import {
MODEL_LOADING_ERROR_CODE,
MSGPACK_CONTENT_TYPE,
PROVISIONING_ERROR_CODE,
+ RESOURCE_EXHAUSTED_ERROR_CODE,
+ RESOURCE_EXHAUSTED_MAX_RETRIES,
SDK_VERSION_HEADER,
SERVER_VERSION_HEADER,
} from "./internal/constants.js";
@@ -68,20 +76,37 @@ import {
throwIfInputTooLong,
throwIfModelLoadFailed,
} from "./internal/parsing.js";
-import { withProvisioningRetry } from "./internal/provisioning.js";
+import { nextOomRetryDelay, withProvisioningRetry } from "./internal/provisioning.js";
import { applyRetryJitter } from "./internal/retry.js";
+import {
+ type JobResultItem,
+ type JobResults,
+ type JobStatus,
+ type JobSubmitResult,
+ type SubmitJobOptions,
+ TERMINAL_JOB_STATES,
+ buildJobBody,
+ decodeChunkBytes,
+ jobChunks,
+} from "./jobs.js";
import { packMessage, unpackMessage } from "./msgpack.js";
import { parseSseStream } from "./sse.js";
import type {
+ Batch,
CapacityInfo,
ChatCompletion,
ChatCompletionChunk,
ChatCompletionOptions,
ChatCompletionRequest,
+ Connection,
+ ConnectionCreated,
+ ConnectionRevoked,
+ CreatePoolOptions,
EncodeOptions,
EncodeResult,
ExtractOptions,
ExtractResult,
+ FileDeleted,
GenerateChunk,
GenerateOptions,
GenerateResult,
@@ -90,17 +115,105 @@ import type {
PoolInfo,
PoolSpec,
SIEClientOptions,
+ File as SIEFile,
ScoreOptions,
ScoreResult,
StatusMessage,
} from "./types.js";
import { SDK_VERSION } from "./version.js";
+/** The `client.jobs` batch namespace. */
+export interface JobsNamespace {
+ /** Submit a batch job (`POST /v1/jobs`); returns the created-job envelope. */
+ submit(options: SubmitJobOptions): Promise<JobSubmitResult>;
+ /** Fetch a job's public status doc (`GET /v1/jobs/{id}`). */
+ get(jobId: string): Promise<JobStatus>;
+ /** List the org's jobs (`GET /v1/jobs`; scoped to the key's org). */
+ list(): Promise<JobStatus[]>;
+ /** Cancel a job (`POST /v1/jobs/{id}/cancel`); the hold's remainder releases. */
+ cancel(jobId: string): Promise<JobStatus>;
+ /** Retrieve a finished job's chunk refs and decode the per-item results. */
+ results(jobId: string): Promise<JobResults>;
+ /**
+ * Poll `get` until the job reaches a terminal state, then return its status.
+ * Throws a `job_wait_timeout` `RequestError` if `timeoutMs` elapses first.
+ * Mirrors the Python SDK's `jobs.wait` (default 600s timeout, 2s poll).
+ */
+ wait(jobId: string, options?: { timeoutMs?: number; pollMs?: number }): Promise<JobStatus>;
+}
+
+/** The `client.connections` namespace (org-scoped connector auth). */
+export interface ConnectionsNamespace {
+ /** Create an org-scoped connection (connector auth by name). */
+ add(name: string, type: string, secret: string): Promise<ConnectionCreated>;
+ /** List the org's active connections (secrets redacted). */
+ list(): Promise<Connection[]>;
+ /** Revoke (soft-delete) a connection; frees the name for reuse. */
+ revoke(name: string): Promise<ConnectionRevoked>;
+}
+
+/** Accepted upload payloads — the same shapes `fetch` sends as a body. */
+export type FileUploadInput = Uint8Array | ArrayBuffer | string | Blob;
+
+/**
+ * The `client.files` OpenAI-compatible Files namespace. Method
+ * names/args mirror `openai.files` so an `openai` → `sie-sdk` swap is mechanical.
+ */
+export interface FilesNamespace {
+ /** Upload a file (`POST /v1/files`); `purpose` defaults to `"batch"`. */
+ upload(
+ file: FileUploadInput,
+ options?: { purpose?: string; filename?: string },
+ ): Promise<SIEFile>;
+ /** OpenAI-exact alias for {@link upload} (`files.create({ file, purpose })`). */
+ create(options: { file: FileUploadInput; purpose?: string; filename?: string }): Promise<SIEFile>;
+ /** Fetch a file's metadata (`GET /v1/files/{id}`). */
+ retrieve(fileId: string): Promise<SIEFile>;
+ /** Download a file's raw bytes (`GET /v1/files/{id}/content`). */
+ content(fileId: string): Promise<Uint8Array>;
+ /** Delete a file (`DELETE /v1/files/{id}`; additive OpenAI-parity surface). */
+ delete(fileId: string): Promise<FileDeleted>;
+}
+
+/**
+ * The `client.batches` OpenAI-compatible Batch namespace. A
+ * batch is a job over an uploaded file's JSONL lines;
+ * `list` / `cancel` are the additive OpenAI-parity completion of the surface.
+ * Args are OpenAI's exact snake_case body keys, so an `openai` → `sie-sdk` swap
+ * is mechanical.
+ */
+export interface BatchesNamespace {
+ /** Create a batch (`POST /v1/batches`); returns the Batch object. */
+ create(options: {
+ input_file_id: string;
+ endpoint?: string;
+ completion_window?: string;
+ metadata?: Record<string, unknown>;
+ }): Promise<Batch>;
+ /** Fetch a batch's status (`GET /v1/batches/{id}`). */
+ retrieve(batchId: string): Promise<Batch>;
+ /** List the org's batches (`GET /v1/batches`; additive OpenAI-parity). */
+ list(): Promise<Batch[]>;
+ /** Cancel a batch (`POST /v1/batches/{id}/cancel`; additive OpenAI-parity). */
+ cancel(batchId: string): Promise<Batch>;
+}
+
/** Helper to sleep for a given number of milliseconds */
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+/** Derive an upload filename: an explicit override > a File/Blob `.name` > default. */
+function resolveUploadFilename(file: FileUploadInput, filename?: string): string {
+ if (filename) return filename;
+ const name = (file as { name?: unknown }).name;
+ if (typeof name === "string" && name.length > 0) {
+ // A File's `.name` may include a path; keep just the basename.
+ return name.split(/[/\\]/).pop() || "upload.jsonl";
+ }
+ return "upload.jsonl";
+}
+
/** Sleep that can be cancelled via AbortSignal. Returns true if aborted. */
function abortableSleep(ms: number, signal: AbortSignal): Promise<boolean> {
if (signal.aborted) return Promise.resolve(true);
@@ -203,6 +316,17 @@ export class SIEClient {
private readonly apiKey?: string;
private readonly defaultWaitForCapacity: boolean;
private readonly provisionTimeout: number;
+ private readonly controlPlaneUrl?: string;
+ private readonly org?: string;
+
+ /** Batch class — `POST/GET /v1/jobs` on the keyed gateway. */
+ readonly jobs: JobsNamespace;
+ /** Org-scoped connections (connector auth by name) on the control plane. */
+ readonly connections: ConnectionsNamespace;
+ /** OpenAI-compatible Files API — `POST/GET /v1/files`. */
+ readonly files: FilesNamespace;
+ /** OpenAI-compatible Batch API — `POST/GET /v1/batches`. */
+ readonly batches: BatchesNamespace;
// Pool state: track created pools and their lease renewal scheduling
private readonly pools: Map<
@@ -232,8 +356,44 @@ export class SIEClient {
this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
this.gpu = options.gpu;
this.apiKey = options.apiKey;
- this.defaultWaitForCapacity = options.waitForCapacity ?? false;
+ // BREAKING CHANGE (0.7): default flipped from `false` to `true` to match
+ // the Python SDK (`wait_for_capacity=True`). Callers that relied on
+ // fail-fast 503 PROVISIONING / connect-error behaviour must now pass
+ // `waitForCapacity: false` explicitly.
+ this.defaultWaitForCapacity = options.waitForCapacity ?? true;
this.provisionTimeout = options.provisionTimeout ?? DEFAULT_PROVISION_TIMEOUT;
+ this.controlPlaneUrl = options.controlPlaneUrl?.replace(/\/$/, "");
+ this.org = options.org;
+
+ // First-class batch + connector surface.
+ this.jobs = {
+ submit: (submitOptions) => this.jobSubmit(submitOptions),
+ get: (jobId) => this.jobGet(jobId),
+ list: () => this.jobList(),
+ cancel: (jobId) => this.jobCancel(jobId),
+ results: (jobId) => this.jobResults(jobId),
+ wait: (jobId, options) => this.jobWait(jobId, options),
+ };
+ this.connections = {
+ add: (name, type, secret) => this.connectionAdd(name, type, secret),
+ list: () => this.connectionList(),
+ revoke: (name) => this.connectionRevoke(name),
+ };
+ // OpenAI-compatible Files + Batches surface — a base_url
+ // swap makes an `openai` batch caller work unchanged.
+ this.files = {
+ upload: (file, options) => this.fileUpload(file, options),
+ create: (options) => this.fileUpload(options.file, options),
+ retrieve: (fileId) => this.fileRetrieve(fileId),
+ content: (fileId) => this.fileContent(fileId),
+ delete: (fileId) => this.fileDelete(fileId),
+ };
+ this.batches = {
+ create: (options) => this.batchCreate(options),
+ retrieve: (batchId) => this.batchRetrieve(batchId),
+ list: () => this.batchList(),
+ cancel: (batchId) => this.batchCancel(batchId),
+ };
}
/**
@@ -824,8 +984,10 @@ export class SIEClient {
* generator throws it instead of yielding the chunk.
*
* Retry policy mirrors {@link generate}: only explicit SAFE
- * pre-execution capacity signals — `503 PROVISIONING` and
- * `503 MODEL_LOADING` — are retried while the provision budget remains.
+ * pre-execution capacity signals — `503 PROVISIONING`,
+ * `503 MODEL_LOADING` and `503 RESOURCE_EXHAUSTED` (the latter only
+ * under `waitForCapacity`) — are retried while the provision budget
+ * remains; a `504` is post-publish and therefore terminal.
* Once the body opens we never retry (the call is non-idempotent; a
* mid-stream failure must not re-issue generation).
*
@@ -860,12 +1022,13 @@ export class SIEClient {
try {
const startTime = Date.now();
+ let oomRetries = 0;
let response: Response | undefined;
// Pre-stream provisioning retry loop. We re-fetch on explicit SAFE
- // pre-execution capacity signals only (503 PROVISIONING / MODEL_LOADING),
- // parallel to `generate()`. The loop terminates by `break`-ing on a
- // 200 (the only status that opens a body) or by throwing.
+ // pre-execution capacity signals only (503 PROVISIONING / MODEL_LOADING /
+ // RESOURCE_EXHAUSTED), parallel to `generate()`. The loop terminates by
+ // `break`-ing on a 200 (the only status that opens a body) or by throwing.
while (true) {
if (signal?.aborted) {
throw new SIEConnectionError("Stream aborted before request", "other");
@@ -954,6 +1117,43 @@ export class SIEClient {
}
continue;
}
+ if (errorCode === RESOURCE_EXHAUSTED_ERROR_CODE) {
+ // Pre-stream capacity signal. Mirrors the Python streaming
+ // surface (`next_stream_retry_delay`): retried only under
+ // `waitForCapacity`, bounded by the shared OOM budget.
+ if (!waitForCapacity) {
+ throw new ResourceExhaustedError(
+ `Server resource exhausted after ${oomRetries} retry attempt(s) for model '${model}'`,
+ { model, retries: oomRetries },
+ );
+ }
+ const delay = nextOomRetryDelay({
+ retryAfter: getRetryAfter(attemptResponse),
+ oomRetries,
+ maxOomRetries: RESOURCE_EXHAUSTED_MAX_RETRIES,
+ elapsedMs: Date.now() - startTime,
+ provisionTimeoutMs: this.provisionTimeout,
+ model,
+ });
+ oomRetries += 1;
+ if (await abortableSleep(delay, controller.signal)) {
+ throw new SIEConnectionError("Stream aborted while provisioning", "other");
+ }
+ continue;
+ }
+ }
+
+ // 504 is terminal on the streaming path: post-publish, a worker may
+ // already be generating, and generation is non-idempotent (Python
+ // SDK parity — see `next_stream_retry_delay`).
+ if (attemptResponse.status === HTTP_GATEWAY_TIMEOUT) {
+ throw new ServerError(
+ "Gateway timed out (504) after the request was published to the queue; " +
+ "a worker may already be generating. Not retried because generation is " +
+ "non-idempotent (retrying could double-bill).",
+ await getErrorCode(attemptResponse.clone()),
+ HTTP_GATEWAY_TIMEOUT,
+ );
}
// Any remaining non-200 is an error.
@@ -1169,12 +1369,21 @@ export class SIEClient {
* @param gpus - Optional machine profile requirements for pool readiness, e.g., { "l4": 2, "l4-spot": 1 }
* @param gpuCaps - Optional maximum assigned workers per machine profile
* @param queuePool - Optional Helm/NATS queue namespace backing this logical pool. Defaults to "default".
+ * @param options - Optional bundle filter, warm floor, and pinned models
+ * (Python SDK `create_pool` parity)
*
* @example
* ```typescript
* // Create or update a pool with 2 L4 GPUs
* await client.createPool("eval-bench", { l4: 2 });
*
+ * // With a bundle filter, warm floor, and pinned models
+ * await client.createPool("eval-bench", { l4: 2 }, undefined, undefined, {
+ * bundle: "default",
+ * minimumWorkerCount: 1,
+ * pinnedModels: ["bge-m3"],
+ * });
+ *
* // Use the pool for requests
* await client.encode("bge-m3", { text: "Hello" }, { gpu: "eval-bench/l4" });
*
@@ -1187,15 +1396,23 @@ export class SIEClient {
gpus?: Record<string, number>,
gpuCaps?: Record<string, number>,
queuePool?: string,
+ options: CreatePoolOptions = {},
): Promise<void> {
const alreadyTracking = this.pools.has(name);
+ if (options.minimumWorkerCount !== undefined && options.minimumWorkerCount < 0) {
+ throw new RangeError("minimumWorkerCount must be >= 0");
+ }
+
// Build pool creation request
const requestBody: {
name: string;
gpus?: Record<string, number>;
gpu_caps?: Record<string, number>;
queue_pool?: string;
+ bundle?: string;
+ minimum_worker_count?: number;
+ pinned_models?: string[];
} = {
name,
};
@@ -1208,6 +1425,15 @@ export class SIEClient {
if (queuePool) {
requestBody.queue_pool = queuePool;
}
+ if (options.bundle) {
+ requestBody.bundle = options.bundle;
+ }
+ if (options.minimumWorkerCount !== undefined) {
+ requestBody.minimum_worker_count = options.minimumWorkerCount;
+ }
+ if (options.pinnedModels !== undefined) {
+ requestBody.pinned_models = options.pinnedModels;
+ }
const url = `${this.baseUrl}/v1/pools`;
const headers: Record<string, string> = {
@@ -1589,6 +1815,11 @@ export class SIEClient {
* Retried (capped by `provisionTimeout`):
* - 503 `PROVISIONING` when `waitForCapacity: true`
* - 503 `MODEL_LOADING` / `LORA_LOADING`
+ * - 503 `RESOURCE_EXHAUSTED` regardless of `waitForCapacity` (bounded
+ * exponential backoff, at most `RESOURCE_EXHAUSTED_MAX_RETRIES`)
+ * - 504 gateway timeout when `waitForCapacity: true` — encode/score/
+ * extract are idempotent queue paths, so a post-publish retry is safe
+ * (unlike generate/chat, where a 504 is terminal)
* - `SIEConnectionError` with `kind === "connect"` (issue #95)
*
* `kind === "timeout"` is NOT retried — would extend the user-visible
@@ -1607,6 +1838,9 @@ export class SIEClient {
// Local retry counter for LoRA loading (uses retry count, not time-based)
// Model loading uses cumulative time check, not retry counter
let loraRetries = 0;
+ // Retry counter for server-side OOM (RESOURCE_EXHAUSTED). Bounded so a
+ // stuck-at-OOM server cannot cause unbounded blocking.
+ let oomRetries = 0;
while (true) {
let response: Response;
@@ -1704,6 +1938,38 @@ export class SIEClient {
await sleep(actualDelay);
continue;
}
+
+ if (errorCode === RESOURCE_EXHAUSTED_ERROR_CODE) {
+ // Server-side OOM. Retried regardless of `waitForCapacity`
+ // (bounded budget), matching the Python SDK: the worker already
+ // accepted the request and is recovering from transient capacity
+ // exhaustion.
+ const delay = nextOomRetryDelay({
+ retryAfter: getRetryAfter(response),
+ oomRetries,
+ maxOomRetries: RESOURCE_EXHAUSTED_MAX_RETRIES,
+ elapsedMs: Date.now() - startTime,
+ provisionTimeoutMs: this.provisionTimeout,
+ model,
+ });
+ oomRetries += 1;
+ await sleep(delay);
+ continue;
+ }
+ }
+
+ // Handle 504 (gateway timeout): queued work was published, but the
+ // gateway did not receive a worker result before its deadline.
+ // Encode/score/extract are idempotent, so callers that opted into
+ // waitForCapacity can retry within the provision budget (Python SDK
+ // parity). On budget exhaustion this falls through to handleError.
+ if (response.status === HTTP_GATEWAY_TIMEOUT && waitForCapacity) {
+ const elapsed = Date.now() - startTime;
+ if (elapsed < this.provisionTimeout) {
+ const delay = getRetryAfter(response) ?? MODEL_LOADING_DEFAULT_DELAY;
+ await sleep(Math.min(delay, this.provisionTimeout - elapsed));
+ continue;
+ }
}
// Handle other errors
@@ -1819,6 +2085,343 @@ export class SIEClient {
}
}
+ // ---------------------------------------------------------------------------
+ // Jobs + connections namespaces. Jobs ride the keyed gateway
+ // (`/v1/jobs`); connections ride the control plane (`/internal/orgs/{org}/…`).
+ // ---------------------------------------------------------------------------
+
+ /** One JSON request over `fetch` (bearer auth reused; absolute or base-relative URL). */
+ private async jsonRequest<T>(
+ target: string,
+ method: "GET" | "POST" | "DELETE",
+ body?: unknown,
+ timeoutMs: number = this.timeout,
+ ): Promise<T> {
+ const url = target.startsWith("http") ? target : `${this.baseUrl}${target}`;
+ const headers: Record<string, string> = {
+ Accept: JSON_CONTENT_TYPE,
+ [SDK_VERSION_HEADER]: SDK_VERSION,
+ };
+ if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
+ const init: RequestInit = { method, headers };
+ if (body !== undefined) {
+ headers["Content-Type"] = JSON_CONTENT_TYPE;
+ init.body = JSON.stringify(body);
+ }
+
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
+ init.signal = controller.signal;
+ try {
+ const response = await fetch(url, init);
+ if (!response.ok) {
+ await handleError(response);
+ }
+ this.checkServerVersion(response);
+ const text = await response.text();
+ return (text ? JSON.parse(text) : {}) as T;
+ } catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ throw new SIEConnectionError(`Request timeout after ${timeoutMs}ms`, "timeout");
+ }
+ if (error instanceof TypeError) {
+ throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ }
+
+ private async jobSubmit(options: SubmitJobOptions): Promise<JobSubmitResult> {
+ return this.jsonRequest<JobSubmitResult>(
+ "/v1/jobs",
+ "POST",
+ buildJobBody(options),
+ Math.max(this.timeout, DEFAULT_LONG_RUNNING_TIMEOUT),
+ );
+ }
+
+ private async jobGet(jobId: string): Promise<JobStatus> {
+ return this.jsonRequest<JobStatus>(`/v1/jobs/${encodeURIComponent(jobId)}`, "GET");
+ }
+
+ private async jobList(): Promise<JobStatus[]> {
+ const data = await this.jsonRequest<{ object?: string; data?: JobStatus[] }>("/v1/jobs", "GET");
+ return Array.isArray(data) ? data : (data.data ?? []);
+ }
+
+ private async jobCancel(jobId: string): Promise<JobStatus> {
+ return this.jsonRequest<JobStatus>(`/v1/jobs/${encodeURIComponent(jobId)}/cancel`, "POST");
+ }
+
+ private async jobResults(jobId: string): Promise<JobResults> {
+ const job = await this.jobGet(jobId);
+ const chunks = jobChunks(job);
+ const items: JobResultItem[] = [];
+ for (const chunk of chunks) {
+ if (chunk.state !== "succeeded" || !chunk.ref) continue;
+ const raw = await this.readRef(chunk.ref);
+ items.push(...decodeChunkBytes(raw));
+ }
+ const withDims = items.find((it) => it.dims != null);
+ return {
+ job_id: job.id ?? jobId,
+ state: job.state,
+ total_items: job.total_items,
+ settled_credits: job.settled_credits,
+ chunks,
+ retrieved: items.length,
+ dims: withDims ? withDims.dims : null,
+ items,
+ };
+ }
+
+ private async jobWait(
+ jobId: string,
+ options?: { timeoutMs?: number; pollMs?: number },
+ ): Promise<JobStatus> {
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_JOB_WAIT_TIMEOUT;
+ const pollMs = options?.pollMs ?? DEFAULT_JOB_WAIT_POLL;
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const job = await this.jobGet(jobId);
+ if (job.state && TERMINAL_JOB_STATES.has(job.state)) {
+ return job;
+ }
+ if (Date.now() >= deadline) {
+ throw new RequestError(
+ `job ${jobId} still ${JSON.stringify(job.state)} after ${timeoutMs}ms`,
+ "job_wait_timeout",
+ 504,
+ );
+ }
+ await sleep(pollMs);
+ }
+ }
+
+ /** Retrieve a chunk's payload-store ref (http(s) URL). */
+ private async readRef(ref: string): Promise<Uint8Array> {
+ if (!ref.startsWith("http://") && !ref.startsWith("https://")) {
+ throw new RequestError(
+ `cannot retrieve payload-store ref ${JSON.stringify(ref)} (the TS SDK reads http(s) refs)`,
+ "bad_ref",
+ 400,
+ );
+ }
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
+ try {
+ const response = await fetch(ref, {
+ headers: { Accept: "application/octet-stream" },
+ signal: controller.signal,
+ });
+ if (!response.ok) {
+ await handleError(response);
+ }
+ return new Uint8Array(await response.arrayBuffer());
+ } catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ throw new SIEConnectionError(`Request timeout after ${this.timeout}ms`, "timeout");
+ }
+ if (error instanceof TypeError) {
+ throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ }
+
+ private connectionsBase(): string {
+ if (!this.controlPlaneUrl) {
+ throw new RequestError(
+ "connections require controlPlaneUrl on the client: new SIEClient(url, { controlPlaneUrl, org })",
+ "missing_control_plane_url",
+ 400,
+ );
+ }
+ if (!this.org) {
+ throw new RequestError(
+ "connections require org on the client: new SIEClient(url, { controlPlaneUrl, org })",
+ "missing_org",
+ 400,
+ );
+ }
+ return `${this.controlPlaneUrl}/internal/orgs/${encodeURIComponent(this.org)}/connections`;
+ }
+
+ private async connectionAdd(
+ name: string,
+ type: string,
+ secret: string,
+ ): Promise<ConnectionCreated> {
+ return this.jsonRequest<ConnectionCreated>(this.connectionsBase(), "POST", {
+ type,
+ name,
+ secret,
+ });
+ }
+
+ private async connectionList(): Promise<Connection[]> {
+ const data = await this.jsonRequest<{ connections?: Connection[] }>(
+ this.connectionsBase(),
+ "GET",
+ );
+ return Array.isArray(data) ? data : (data.connections ?? []);
+ }
+
+ private async connectionRevoke(name: string): Promise<ConnectionRevoked> {
+ return this.jsonRequest<ConnectionRevoked>(
+ `${this.connectionsBase()}/${encodeURIComponent(name)}`,
+ "DELETE",
+ );
+ }
+
+ // ---------------------------------------------------------------------------
+ // Files + batches namespaces — the OpenAI-compatible file /
+ // batch surface on the keyed gateway. Method names/args mirror `openai.files`
+ // / `openai.batches` so switching an OpenAI-batch caller to the SDK is
+ // mechanical.
+ // ---------------------------------------------------------------------------
+
+ /** POST a raw body and parse the JSON response (bearer auth reused). */
+ private async rawPostJson<T>(
+ path: string,
+ body: FileUploadInput,
+ contentType: string,
+ timeoutMs: number = this.timeout,
+ ): Promise<T> {
+ const url = `${this.baseUrl}${path}`;
+ const headers: Record<string, string> = {
+ Accept: JSON_CONTENT_TYPE,
+ "Content-Type": contentType,
+ [SDK_VERSION_HEADER]: SDK_VERSION,
+ };
+ if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
+
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const response = await fetch(url, {
+ method: "POST",
+ headers,
+ body,
+ signal: controller.signal,
+ });
+ if (!response.ok) {
+ await handleError(response);
+ }
+ this.checkServerVersion(response);
+ const text = await response.text();
+ return (text ? JSON.parse(text) : {}) as T;
+ } catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ throw new SIEConnectionError(`Request timeout after ${timeoutMs}ms`, "timeout");
+ }
+ if (error instanceof TypeError) {
+ throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ }
+
+ /** GET raw bytes (bearer auth reused); used to download a file's content. */
+ private async rawGetBytes(path: string): Promise<Uint8Array> {
+ const url = `${this.baseUrl}${path}`;
+ const headers: Record<string, string> = {
+ Accept: "application/jsonl",
+ [SDK_VERSION_HEADER]: SDK_VERSION,
+ };
+ if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
+
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
+ try {
+ const response = await fetch(url, { method: "GET", headers, signal: controller.signal });
+ if (!response.ok) {
+ await handleError(response);
+ }
+ this.checkServerVersion(response);
+ return new Uint8Array(await response.arrayBuffer());
+ } catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ throw new SIEConnectionError(`Request timeout after ${this.timeout}ms`, "timeout");
+ }
+ if (error instanceof TypeError) {
+ throw new SIEConnectionError(`Connection failed: ${error.message}`, "connect");
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ }
+
+ private async fileUpload(
+ file: FileUploadInput,
+ options?: { purpose?: string; filename?: string },
+ ): Promise<SIEFile> {
+ const purpose = options?.purpose ?? "batch";
+ const filename = resolveUploadFilename(file, options?.filename);
+ const query = new URLSearchParams({ purpose, filename }).toString();
+ const body: FileUploadInput = file instanceof ArrayBuffer ? new Uint8Array(file) : file;
+ return this.rawPostJson<SIEFile>(
+ `/v1/files?${query}`,
+ body,
+ "application/jsonl",
+ Math.max(this.timeout, DEFAULT_LONG_RUNNING_TIMEOUT),
+ );
+ }
+
+ private async fileRetrieve(fileId: string): Promise<SIEFile> {
+ return this.jsonRequest<SIEFile>(`/v1/files/${encodeURIComponent(fileId)}`, "GET");
+ }
+
+ private async fileContent(fileId: string): Promise<Uint8Array> {
+ return this.rawGetBytes(`/v1/files/${encodeURIComponent(fileId)}/content`);
+ }
+
+ private async fileDelete(fileId: string): Promise<FileDeleted> {
+ return this.jsonRequest<FileDeleted>(`/v1/files/${encodeURIComponent(fileId)}`, "DELETE");
+ }
+
+ private async batchCreate(options: {
+ input_file_id: string;
+ endpoint?: string;
+ completion_window?: string;
+ metadata?: Record<string, unknown>;
+ }): Promise<Batch> {
+ const body: Record<string, unknown> = {
+ input_file_id: options.input_file_id,
+ endpoint: options.endpoint ?? "/v1/embeddings",
+ completion_window: options.completion_window ?? "24h",
+ };
+ if (options.metadata !== undefined) {
+ body.metadata = options.metadata;
+ }
+ return this.jsonRequest<Batch>(
+ "/v1/batches",
+ "POST",
+ body,
+ Math.max(this.timeout, DEFAULT_LONG_RUNNING_TIMEOUT),
+ );
+ }
+
+ private async batchRetrieve(batchId: string): Promise<Batch> {
+ return this.jsonRequest<Batch>(`/v1/batches/${encodeURIComponent(batchId)}`, "GET");
+ }
+
+ private async batchList(): Promise<Batch[]> {
+ const data = await this.jsonRequest<{ object?: string; data?: Batch[] }>("/v1/batches", "GET");
+ return Array.isArray(data) ? data : (data.data ?? []);
+ }
+
+ private async batchCancel(batchId: string): Promise<Batch> {
+ return this.jsonRequest<Batch>(`/v1/batches/${encodeURIComponent(batchId)}/cancel`, "POST");
+ }
+
private buildWsUrl(path: string): string {
const url = new URL(this.baseUrl);
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
diff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.ts
index a28ae48cf..1588e9da0 100644
--- a/packages/sie_ts_sdk/src/errors.ts
+++ b/packages/sie_ts_sdk/src/errors.ts
@@ -198,6 +198,34 @@ export class ModelLoadingError extends SIEError {
}
}
+/**
+ * Error when the server has exhausted its OOM-recovery strategies.
+ *
+ * Raised when:
+ * - Server returns 503 with RESOURCE_EXHAUSTED code
+ * - SDK retry limit is exceeded (or the next backoff would exhaust the
+ * provision-timeout budget)
+ *
+ * Subclass of {@link ServerError} so callers that already catch
+ * `ServerError` continue to behave correctly; new code can catch
+ * `ResourceExhaustedError` specifically to react to sustained GPU
+ * pressure (e.g., back off, route elsewhere, scale up). Mirrors the
+ * Python SDK's `ResourceExhaustedError`.
+ */
+export class ResourceExhaustedError extends ServerError {
+ /** The model that was requested */
+ readonly model: string | undefined;
+ /** Number of retry attempts made before giving up */
+ readonly retries: number;
+
+ constructor(message: string, options?: { model?: string; retries?: number }) {
+ super(message, "RESOURCE_EXHAUSTED", 503);
+ this.name = "ResourceExhaustedError";
+ this.model = options?.model;
+ this.retries = options?.retries ?? 0;
+ }
+}
+
/**
* Error surfaced mid-stream from `streamChatCompletions` / `streamGenerate`.
*
diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.ts
index 47e325938..dde3081e1 100644
--- a/packages/sie_ts_sdk/src/index.ts
+++ b/packages/sie_ts_sdk/src/index.ts
@@ -21,6 +21,29 @@
// Main client
export { SIEClient } from "./client.js";
+export type {
+ JobsNamespace,
+ ConnectionsNamespace,
+ FilesNamespace,
+ BatchesNamespace,
+ FileUploadInput,
+} from "./client.js";
+
+// Jobs surface (client.jobs) — pure helpers + wire types
+export { buildJobBody, connectionName, TERMINAL_JOB_STATES } from "./jobs.js";
+export type {
+ JobState,
+ JobItem,
+ JobSource,
+ JobFieldMap,
+ SubmitJobOptions,
+ JobPreflight,
+ JobChunk,
+ JobSubmitResult,
+ JobStatus,
+ JobResultItem,
+ JobResults,
+} from "./jobs.js";
// Version
export { SDK_VERSION } from "./version.js";
@@ -57,9 +80,21 @@ export type {
ClusterStatusMessage,
StatusMessage,
// Pool types
+ CreatePoolOptions,
PoolSpec,
PoolStatus,
PoolInfo,
+ // Connections (client.connections)
+ Connection,
+ ConnectionCreated,
+ ConnectionRevoked,
+ // Files (client.files) — OpenAI-compatible file objects
+ File as SIEFile,
+ FileDeleted,
+ // Batches (client.batches) — OpenAI-compatible batch objects
+ Batch,
+ BatchList,
+ BatchRequestCounts,
// Options
DType,
OutputType,
@@ -115,6 +150,7 @@ export {
LoraLoadingError,
ModelLoadingError,
ModelLoadFailedError,
+ ResourceExhaustedError,
SIEStreamError,
InputTooLongError,
} from "./errors.js";
diff --git a/packages/sie_ts_sdk/src/internal/constants.ts b/packages/sie_ts_sdk/src/internal/constants.ts
index 5e5221415..d99c67f1c 100644
--- a/packages/sie_ts_sdk/src/internal/constants.ts
+++ b/packages/sie_ts_sdk/src/internal/constants.ts
@@ -9,14 +9,23 @@ export const HTTP_CLIENT_ERROR_MIN = 400;
export const HTTP_CLIENT_ERROR_MAX = 499;
export const HTTP_SERVER_ERROR_MIN = 500;
export const HTTP_SERVER_ERROR_MAX = 599;
+export const HTTP_GATEWAY_TIMEOUT = 504;
// Default timeouts and delays
export const DEFAULT_TIMEOUT = 30_000; // 30 seconds
+// Floor for long-running POSTs (jobs.submit / files.upload / batches.create) so
+// a large upload / connector preflight / batch creation does not abort while the
+// server keeps working. Matches the Python SDK's 120s floor.
+export const DEFAULT_LONG_RUNNING_TIMEOUT = 120_000; // 2 minutes
export const DEFAULT_PROVISION_TIMEOUT = 300_000; // 5 minutes (300s matches Python SDK)
export const DEFAULT_RETRY_DELAY = 5_000; // 5 seconds (matches Python SDK)
export const DEFAULT_MAX_RETRY_DELAY = 30_000; // 30 seconds
export const DEFAULT_LEASE_RENEWAL_INTERVAL = 60_000; // 1 minute
+// jobs.wait() polling — mirrors the Python SDK's jobs.wait defaults.
+export const DEFAULT_JOB_WAIT_TIMEOUT = 600_000; // 10 minutes
+export const DEFAULT_JOB_WAIT_POLL = 2_000; // 2 seconds
+
// LoRA loading retry settings
export const LORA_LOADING_MAX_RETRIES = 10; // Max retries for LoRA loading
export const LORA_LOADING_DEFAULT_DELAY = 1_000; // 1 second default retry delay
@@ -28,6 +37,13 @@ export const MODEL_LOADING_DEFAULT_DELAY = 5_000; // 5 seconds default retry del
export const MODEL_LOADING_ERROR_CODE = "MODEL_LOADING"; // Error code from server
export const PROVISIONING_ERROR_CODE = "PROVISIONING"; // Error code from gateway provisioning
+// RESOURCE_EXHAUSTED (server-side OOM) retry settings — mirror the Python SDK
+// (packages/sie_sdk/src/sie_sdk/client/_shared.py).
+export const RESOURCE_EXHAUSTED_MAX_RETRIES = 3; // Max bounded retries
+export const RESOURCE_EXHAUSTED_DEFAULT_DELAY = 5_000; // Base backoff (ms)
+export const RESOURCE_EXHAUSTED_MAX_DELAY = 30_000; // Backoff ceiling (ms)
+export const RESOURCE_EXHAUSTED_ERROR_CODE = "RESOURCE_EXHAUSTED"; // Error code from server
+
// Version negotiation headers
export const SDK_VERSION_HEADER = "X-SIE-SDK-Version";
export const SERVER_VERSION_HEADER = "X-SIE-Server-Version";
diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.ts
index 443e16425..62e4479dd 100644
--- a/packages/sie_ts_sdk/src/internal/parsing.ts
+++ b/packages/sie_ts_sdk/src/internal/parsing.ts
@@ -527,8 +527,12 @@ export function parseGenerateResult(data: Record<string, unknown>): GenerateResu
interface WireWorkerInfo {
url: string;
gpu: string;
+ gpu_count?: number;
+ ready_gpu_slots?: number;
healthy: boolean;
queue_depth: number;
+ pending_cost?: number;
+ inflight_batches?: number;
loaded_models: string[];
}
@@ -561,8 +565,12 @@ export function parseCapacityInfo(data: unknown, gpuFilter?: string): CapacityIn
const parsedWorkers: WorkerInfo[] = workers.map((w) => ({
url: w.url,
gpu: w.gpu,
+ gpuCount: w.gpu_count ?? 0,
+ readyGpuSlots: w.ready_gpu_slots ?? w.gpu_count ?? (w.healthy ? 1 : 0),
healthy: w.healthy,
queueDepth: w.queue_depth,
+ pendingCost: w.pending_cost ?? 0,
+ inflightBatches: w.inflight_batches ?? 0,
loadedModels: w.loaded_models,
}));
diff --git a/packages/sie_ts_sdk/src/internal/provisioning.ts b/packages/sie_ts_sdk/src/internal/provisioning.ts
index 8333250e5..f2543db09 100644
--- a/packages/sie_ts_sdk/src/internal/provisioning.ts
+++ b/packages/sie_ts_sdk/src/internal/provisioning.ts
@@ -3,10 +3,11 @@
*
* Both {@link SIEClient.generate} and {@link SIEClient.chatCompletions}
* receive identical pre-execution capacity signals from the gateway —
- * `503` with a known error code (`PROVISIONING` or `MODEL_LOADING`).
- * They both need to retry those SAFE pre-execution signals while
- * honouring a caller-supplied `waitForCapacity` flag plus a
- * `provisionTimeout` budget.
+ * `503` with a known error code (`PROVISIONING`, `MODEL_LOADING` or
+ * `RESOURCE_EXHAUSTED`). They both need to retry those SAFE
+ * pre-execution signals while honouring a caller-supplied
+ * `waitForCapacity` flag plus a `provisionTimeout` budget. A `504` is
+ * post-publish and therefore terminal here (non-idempotent generation).
*
* This helper centralises that loop. Callers supply a `performFetch`
* callback that issues a fresh `fetch` per attempt (the request must be
@@ -19,15 +20,24 @@
* `consumeSseStream` in `client.ts`).
*/
-import { ModelLoadingError, ProvisioningError, RequestError } from "../errors.js";
+import {
+ ModelLoadingError,
+ ProvisioningError,
+ RequestError,
+ ResourceExhaustedError,
+ ServerError,
+} from "../errors.js";
import {
DEFAULT_RETRY_DELAY,
+ HTTP_GATEWAY_TIMEOUT,
MODEL_LOADING_DEFAULT_DELAY,
MODEL_LOADING_ERROR_CODE,
PROVISIONING_ERROR_CODE,
+ RESOURCE_EXHAUSTED_ERROR_CODE,
+ RESOURCE_EXHAUSTED_MAX_RETRIES,
} from "./constants.js";
import { getErrorCode, getRetryAfter, handleError, throwIfModelLoadFailed } from "./parsing.js";
-import { applyRetryJitter } from "./retry.js";
+import { applyRetryJitter, computeOomBackoff } from "./retry.js";
/** Options controlling the provisioning retry loop. */
export interface ProvisioningOptions {
@@ -54,6 +64,45 @@ function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+/**
+ * Budget check + backoff for one `503 RESOURCE_EXHAUSTED` retry.
+ *
+ * Mirrors the Python SDK's `_handle_oom_retry`: throws
+ * {@link ResourceExhaustedError} when the retry budget is exhausted
+ * (`oomRetries >= maxOomRetries`), the provision budget has elapsed, or
+ * the next backoff would consume the remaining budget without leaving
+ * room for the retried request to run (surfacing the *root cause* now
+ * instead of a later "provisioning timeout"). Otherwise returns the
+ * delay (ms) to sleep before the next attempt.
+ *
+ * Distinct from MODEL_LOADING: the model is already resident, the
+ * request just lost the race for compute resources. This is a SAFE
+ * pre-execution signal (the worker rejected the request before running
+ * it), so on the buffered paths it is retried regardless of
+ * `waitForCapacity`, matching the Python SDK.
+ *
+ * @internal
+ */
+export function nextOomRetryDelay(opts: {
+ retryAfter: number | undefined;
+ oomRetries: number;
+ maxOomRetries: number;
+ elapsedMs: number;
+ provisionTimeoutMs: number;
+ model: string;
+}): number {
+ const { retryAfter, oomRetries, maxOomRetries, elapsedMs, provisionTimeoutMs, model } = opts;
+ const message = `Server resource exhausted after ${oomRetries} retry attempt(s) for model '${model}'`;
+ if (oomRetries >= maxOomRetries || elapsedMs >= provisionTimeoutMs) {
+ throw new ResourceExhaustedError(message, { model, retries: oomRetries });
+ }
+ const delay = computeOomBackoff(retryAfter, oomRetries);
+ if (delay >= provisionTimeoutMs - elapsedMs) {
+ throw new ResourceExhaustedError(message, { model, retries: oomRetries });
+ }
+ return delay;
+}
+
/**
* Wrap a non-streaming POST attempt in the shared provisioning retry loop.
*
@@ -73,6 +122,7 @@ export async function withProvisioningRetry(
opts: ProvisioningOptions,
): Promise<Response> {
const startTime = Date.now();
+ let oomRetries = 0;
while (true) {
const response = await performFetch();
@@ -112,6 +162,37 @@ export async function withProvisioningRetry(
await sleep(Math.min(delay, opts.provisionTimeoutMs - elapsed));
continue;
}
+ if (errorCode === RESOURCE_EXHAUSTED_ERROR_CODE) {
+ // Retried regardless of `waitForCapacity` (bounded budget), matching
+ // the Python SDK: the signal fires before any generation starts.
+ const delay = nextOomRetryDelay({
+ retryAfter: getRetryAfter(response),
+ oomRetries,
+ maxOomRetries: RESOURCE_EXHAUSTED_MAX_RETRIES,
+ elapsedMs: Date.now() - startTime,
+ provisionTimeoutMs: opts.provisionTimeoutMs,
+ model: opts.model,
+ });
+ oomRetries += 1;
+ await sleep(delay);
+ continue;
+ }
+ }
+
+ // Do NOT retry 504. A 504 GATEWAY_TIMEOUT is a *post-publish* timeout:
+ // the work item is already on the queue and a worker may be — or have
+ // finished — generating. Generation is non-idempotent and carries no
+ // dedup key, so retrying could issue a SECOND billable generation.
+ // The pre-execution 503 signals above remain retryable because those
+ // fire before any generation can have started (Python SDK parity).
+ if (response.status === HTTP_GATEWAY_TIMEOUT) {
+ throw new ServerError(
+ "Gateway timed out (504) after the request was published to the queue; " +
+ "a worker may already be generating. Not retried because generation is " +
+ "non-idempotent (retrying could double-bill). Re-issue manually if needed.",
+ await getErrorCode(response.clone()),
+ HTTP_GATEWAY_TIMEOUT,
+ );
}
if (!response.ok) {
diff --git a/packages/sie_ts_sdk/src/internal/retry.ts b/packages/sie_ts_sdk/src/internal/retry.ts
index 79c122b0c..e6682df62 100644
--- a/packages/sie_ts_sdk/src/internal/retry.ts
+++ b/packages/sie_ts_sdk/src/internal/retry.ts
@@ -2,7 +2,12 @@
* Retry logic with exponential backoff and jitter
*/
-import { DEFAULT_MAX_RETRY_DELAY, DEFAULT_RETRY_DELAY } from "./constants.js";
+import {
+ DEFAULT_MAX_RETRY_DELAY,
+ DEFAULT_RETRY_DELAY,
+ RESOURCE_EXHAUSTED_DEFAULT_DELAY,
+ RESOURCE_EXHAUSTED_MAX_DELAY,
+} from "./constants.js";
const RETRY_JITTER_FRACTION = 0.25;
@@ -36,6 +41,40 @@ export function applyRetryJitter(delay: number): number {
return Math.max(0, low + Math.random() * (delay - low));
}
+/**
+ * Compute the next sleep interval (ms) for a `503 RESOURCE_EXHAUSTED` retry.
+ *
+ * Mirrors the Python SDK's `compute_oom_backoff`: a first-retry
+ * `Retry-After` hint is honoured verbatim (capped at `maxDelay`, no
+ * jitter — the server gave an explicit instruction); subsequent retries
+ * use bounded exponential backoff, `max(baseDelay, retryAfter) * 2**attempt`
+ * capped at `maxDelay`, with bounded downward jitter so a fleet of clients
+ * evicted by the same OOM event does not retry in lockstep. Always returns
+ * a value in `[0, maxDelay]`.
+ *
+ * @param retryAfter - Parsed `Retry-After` hint in milliseconds, if any
+ * @param attempt - 0-indexed retry number (0 = first retry)
+ */
+export function computeOomBackoff(
+ retryAfter: number | undefined,
+ attempt: number,
+ baseDelay: number = RESOURCE_EXHAUSTED_DEFAULT_DELAY,
+ maxDelay: number = RESOURCE_EXHAUSTED_MAX_DELAY,
+): number {
+ // Defensive floor: a negative Retry-After (malformed upstream) must not
+ // produce a negative sleep.
+ const safeRetryAfter = retryAfter !== undefined ? Math.max(retryAfter, 0) : undefined;
+ if (safeRetryAfter !== undefined && attempt === 0) {
+ return Math.min(safeRetryAfter, maxDelay);
+ }
+ // `max(...)`: a zero hint falls back to `baseDelay`, and a hint above
+ // `baseDelay` keeps the schedule non-decreasing (see the Python SDK's
+ // `compute_oom_backoff` for the full rationale).
+ const base = safeRetryAfter !== undefined ? Math.max(baseDelay, safeRetryAfter) : baseDelay;
+ const capped = Math.max(0, Math.min(base * 2 ** attempt, maxDelay));
+ return applyRetryJitter(capped);
+}
+
/**
* Parse Retry-After header value
* @param header - The Retry-After header value
diff --git a/packages/sie_ts_sdk/src/jobs.ts b/packages/sie_ts_sdk/src/jobs.ts
new file mode 100644
index 000000000..4d85f1e23
--- /dev/null
+++ b/packages/sie_ts_sdk/src/jobs.ts
@@ -0,0 +1,449 @@
+/**
+ * Jobs surface (`client.jobs`) — pure helpers + wire types.
+ *
+ * The jobs API is the gateway's batch class. `client.jobs.submit(...)` binds to
+ * `POST /v1/jobs`; this module owns the transport-free pieces (the
+ * `source → operation → sink / when` slot mapping and result decoding) so they
+ * mirror the Python SDK's `sie_sdk.jobs`.
+ */
+
+import { RequestError } from "./errors.js";
+import { unpackMessage } from "./msgpack.js";
+
+/** Job lifecycle state (queued → running → terminal). */
+export type JobState = "queued" | "running" | "succeeded" | "failed" | "suspended" | "cancelled";
+
+/** Terminal states with no further transitions (job lifecycle). */
+export const TERMINAL_JOB_STATES: ReadonlySet<JobState> = new Set([
+ "succeeded",
+ "failed",
+ "suspended",
+ "cancelled",
+]);
+
+/** One inline input item (the `/v1/encode` item contract: `{text}` / `{id,text}`). */
+export type JobItem = { text?: string; id?: string } & Record<string, unknown>;
+
+/**
+ * A job source: inline items (a list, or a bare string = one text item) or a
+ * connector `scheme://<connection>/…` URI.
+ */
+export type JobSource = string | Array<string | JobItem>;
+
+/**
+ * The uniform source-mapping slots (wire-shaped, mirroring the Python
+ * SDK's dict): `id_field` ≈ `custom_id`, `input_field` ≈ `body.input`,
+ * `carry` = source fields echoed to the sink keyed by id, `input_type` pins
+ * the item shape. The sink slot rides separately as `outputField`. All
+ * optional — per-connector URI params stay as aliases.
+ */
+export interface JobFieldMap {
+ id_field?: string;
+ input_field?: string;
+ carry?: string[];
+ input_type?: "text" | "document";
+}
+
+/** Options for `client.jobs.submit`. */
+export interface SubmitJobOptions {
+ /** Inline items or a connector URI (incl. `upload://<file-id>`). */
+ source: JobSource;
+ /** Model id (e.g. "BAAI/bge-m3"). */
+ model: string;
+ /** Job operation: encode | score | extract | parse | generate (default "encode"). */
+ operation?: string;
+ /** Sink: "return" (default), "inplace", or a connector URI. */
+ sink?: string | null;
+ /** Override the source connection name (default: derived from the URI). */
+ connection?: string | null;
+ /** Distinct connection name for the sink. */
+ sinkConnection?: string | null;
+ /** Uniform source mapping (connector jobs only). */
+ fieldMap?: JobFieldMap | null;
+ /** Sink target (≈ `response.body`; aliases PG `column` / object-store `suffix`). */
+ outputField?: string | null;
+ /** Trigger: "now" (default), "schedule:<cron>", or "watch:<source>". */
+ when?: string | null;
+ /** Encode output types (default: dense). */
+ outputTypes?: string[];
+ /**
+ * Per-item options plus the op inputs, forwarded as-is (operation
+ * matrix): score → `options.query`, extract → `options.labels` /
+ * `options.output_schema`, generate → sampling (e.g. `max_new_tokens`).
+ */
+ options?: Record<string, unknown> | null;
+}
+
+/** The preflight reservation echoed on submit / status. */
+export interface JobPreflight {
+ estimated_credits?: number;
+ estimate_basis?: string;
+}
+
+/** One spawned chunk's settle metadata (`output.chunks[]`; results-as-refs). */
+export interface JobChunk {
+ seq?: number;
+ items?: number;
+ state?: string;
+ ref?: string | null;
+ units?: number | null;
+ credits?: number | null;
+ error?: unknown;
+}
+
+/** The `201` envelope from `POST /v1/jobs` (inline or connector job). */
+export interface JobSubmitResult {
+ id: string;
+ object: string;
+ operation: string;
+ model: string;
+ state: JobState;
+ total_items?: number;
+ chunks?: number;
+ preflight?: JobPreflight;
+ input_source?: string;
+ source?: string;
+ sink?: string;
+}
+
+/** A job's public status doc from `GET /v1/jobs/{id}` (refs, never payloads). */
+export interface JobStatus {
+ id: string;
+ object: string;
+ operation: string;
+ model: string;
+ state: JobState;
+ total_items?: number;
+ completed_items?: number;
+ preflight?: JobPreflight;
+ settled_credits?: number;
+ created_at?: number;
+ finished_at?: number | null;
+ output?: { kind?: string; chunks?: JobChunk[] };
+}
+
+/** One decoded per-item result retrieved from a finished job's chunk refs. */
+export interface JobResultItem {
+ id: string | null;
+ success: boolean | null;
+ units: unknown;
+ dims: number | null;
+ dense: number[] | Float32Array | null;
+}
+
+/** A finished job's decoded results — the chunk refs read and unpacked. */
+export interface JobResults {
+ job_id: string;
+ state: JobState | undefined;
+ total_items: number | undefined;
+ settled_credits: number | undefined;
+ chunks: JobChunk[];
+ retrieved: number;
+ dims: number | null;
+ items: JobResultItem[];
+}
+
+const SINK_RETURN = new Set(["return", "default"]);
+const SINK_INPLACE = new Set(["inplace", "in_place", "in place"]);
+
+// Internal push-to-us schemes (OUR Files store): no org connection to
+// name, so no `connection`/`sink_connection` is derived from the URI.
+const INTERNAL_SCHEMES = new Set(["upload"]);
+
+// Uniform source-mapping slots (the sink slot is `output_field`).
+const FIELD_MAP_KEYS = new Set(["id_field", "input_field", "carry", "input_type"]);
+const INPUT_TYPES = new Set(["text", "document"]);
+
+function isConnectorUri(value: string): boolean {
+ return value.includes("://");
+}
+
+function isInternalUri(uri: string): boolean {
+ return INTERNAL_SCHEMES.has(uri.split("://", 1)[0] ?? "");
+}
+
+function normItem(item: string | JobItem, index: number): JobItem {
+ if (typeof item === "string") return { text: item };
+ if (item !== null && typeof item === "object") return item;
+ throw new RequestError(`item ${index} must be a string or an object`, "invalid_request", 400);
+}
+
+/**
+ * Derive a connection name from a connector URI's authority.
+ *
+ * `postgres://warehouse?query=…` → `warehouse`; `s3://customer-bucket/in/` →
+ * `customer-bucket`. Credentials never appear in the call — the job only names
+ * the connection; the runner resolves it org-scoped.
+ */
+export function connectionName(uri: string): string {
+ // URL can't parse custom schemes reliably; take the authority manually.
+ const afterScheme = uri.split("://", 2)[1] ?? "";
+ const authority = afterScheme.split(/[/?#]/, 1)[0] ?? "";
+ const name = authority.trim();
+ if (!name) {
+ throw new RequestError(
+ `connector URI ${JSON.stringify(uri)} names no connection (expected 'scheme://<connection>/…')`,
+ "invalid_request",
+ 400,
+ );
+ }
+ return name;
+}
+
+function resolveSource(source: JobSource, connection?: string | null): Record<string, unknown> {
+ if (Array.isArray(source)) {
+ if (source.length === 0) {
+ throw new RequestError("inline source has no items", "invalid_request", 400);
+ }
+ return { items: source.map((item, i) => normItem(item, i)) };
+ }
+ if (isConnectorUri(source)) {
+ if (isInternalUri(source)) {
+ // Internal scheme (upload:// = OUR Files store): no connection.
+ return connection ? { src: source, connection } : { src: source };
+ }
+ return { src: source, connection: connection ?? connectionName(source) };
+ }
+ if (typeof source === "string" && source.trim()) {
+ return { items: [{ text: source }] };
+ }
+ throw new RequestError(
+ "source must be inline items (a list/string) or a connector URI (scheme://<connection>/…)",
+ "invalid_request",
+ 400,
+ );
+}
+
+function resolveSink(
+ sink: string | null | undefined,
+ sourceConnection: string | undefined,
+ sinkConnection: string | null | undefined,
+): Record<string, unknown> {
+ if (sink === null || sink === undefined || SINK_RETURN.has(sink.trim().toLowerCase())) {
+ return {};
+ }
+ if (SINK_INPLACE.has(sink.trim().toLowerCase())) {
+ return { sink: "inplace" };
+ }
+ if (isConnectorUri(sink)) {
+ const body: Record<string, unknown> = { sink };
+ if (isInternalUri(sink)) {
+ // Internal scheme: OUR Files store, no connection to name.
+ if (sinkConnection != null) body.sink_connection = sinkConnection;
+ return body;
+ }
+ const resolved = sinkConnection ?? connectionName(sink);
+ // Thread the sink connection when explicitly overridden or distinct from
+ // the source's (the common "index my own store" case reuses the source).
+ if (sinkConnection != null || resolved !== sourceConnection) {
+ body.sink_connection = resolved;
+ }
+ return body;
+ }
+ throw new RequestError(
+ `sink must be 'return', 'inplace', or a connector URI (got ${JSON.stringify(sink)})`,
+ "invalid_request",
+ 400,
+ );
+}
+
+/**
+ * Validate + map the uniform slots onto the wire fields (`field_map` +
+ * `output_field`). Only set fields ride the wire (`/v1` additive-only).
+ */
+function resolveFieldMap(
+ fieldMap: JobFieldMap | null | undefined,
+ outputField: string | null | undefined,
+): Record<string, unknown> {
+ const body: Record<string, unknown> = {};
+ if (fieldMap != null) {
+ const unknown = Object.keys(fieldMap).filter((key) => !FIELD_MAP_KEYS.has(key));
+ if (unknown.length > 0) {
+ throw new RequestError(
+ `unknown field_map key(s) ${JSON.stringify(unknown)} (known: ${[...FIELD_MAP_KEYS].join(", ")})`,
+ "invalid_request",
+ 400,
+ );
+ }
+ if (
+ fieldMap.carry != null &&
+ (!Array.isArray(fieldMap.carry) || fieldMap.carry.some((c) => typeof c !== "string" || !c))
+ ) {
+ throw new RequestError(
+ `field_map.carry must be a list of field names (got ${JSON.stringify(fieldMap.carry)})`,
+ "invalid_request",
+ 400,
+ );
+ }
+ if (fieldMap.input_type != null && !INPUT_TYPES.has(fieldMap.input_type)) {
+ throw new RequestError(
+ `field_map.input_type must be one of ${[...INPUT_TYPES].join(", ")} (got ${JSON.stringify(fieldMap.input_type)})`,
+ "invalid_request",
+ 400,
+ );
+ }
+ const mapped: Record<string, unknown> = {};
+ if (fieldMap.id_field != null) mapped.id_field = fieldMap.id_field;
+ if (fieldMap.input_field != null) mapped.input_field = fieldMap.input_field;
+ if (fieldMap.input_type != null) mapped.input_type = fieldMap.input_type;
+ if (fieldMap.carry != null && fieldMap.carry.length > 0) mapped.carry = fieldMap.carry;
+ if (Object.keys(mapped).length > 0) body.field_map = mapped;
+ }
+ if (outputField != null) {
+ if (typeof outputField !== "string" || !outputField) {
+ throw new RequestError(
+ `output_field must be a non-empty string (got ${JSON.stringify(outputField)})`,
+ "invalid_request",
+ 400,
+ );
+ }
+ body.output_field = outputField;
+ }
+ return body;
+}
+
+function resolveWhen(when: string | null | undefined): Record<string, unknown> {
+ if (when == null || when.trim() === "" || when.trim().toLowerCase() === "now") {
+ return {};
+ }
+ const text = when.trim();
+ // Slice off the prefix (not `split(":")`, which would drop a value's own colons).
+ if (text.toLowerCase().startsWith("schedule:")) {
+ return { when: "schedule", schedule: text.slice("schedule:".length).trim() };
+ }
+ if (text.toLowerCase().startsWith("watch:")) {
+ return { when: "watch", watch: text.slice("watch:".length).trim() };
+ }
+ if (text.toLowerCase() === "schedule") {
+ throw new RequestError(
+ "schedule trigger needs a cron expr: when='schedule:<cron>'",
+ "invalid_request",
+ 400,
+ );
+ }
+ // A bare cron expression (5 whitespace-separated fields) is a schedule.
+ if (text.split(/\s+/).length === 5) {
+ return { when: "schedule", schedule: text };
+ }
+ throw new RequestError(
+ `unrecognized when ${JSON.stringify(when)}: use 'now', 'schedule:<cron>', or 'watch:<source>'`,
+ "invalid_request",
+ 400,
+ );
+}
+
+/**
+ * Compose the `POST /v1/jobs` body from the source/op/sink/when slots.
+ *
+ * A thin, pure mapping: inline `items` or connector `src`/`sink` +
+ * connection name, plus an optional trigger. Only the fields that are set ride
+ * the wire, so an inline submit is byte-for-byte the realtime POC body and the
+ * connector body is additive (`/v1` additive-only rule).
+ */
+export function buildJobBody(options: SubmitJobOptions): Record<string, unknown> {
+ const operation = options.operation ?? "encode";
+ const body: Record<string, unknown> = { operation, model: options.model };
+ const sourceFields = resolveSource(options.source, options.connection);
+ Object.assign(body, sourceFields);
+ Object.assign(
+ body,
+ resolveSink(
+ options.sink,
+ sourceFields.connection as string | undefined,
+ options.sinkConnection,
+ ),
+ );
+ const mappingFields = resolveFieldMap(options.fieldMap, options.outputField);
+ if (Object.keys(mappingFields).length > 0 && !("src" in body)) {
+ throw new RequestError(
+ "fieldMap/outputField apply to connector-src jobs; an inline items job maps nothing",
+ "invalid_request",
+ 400,
+ );
+ }
+ Object.assign(body, mappingFields);
+ Object.assign(body, resolveWhen(options.when));
+ if (options.outputTypes && options.outputTypes.length > 0) {
+ body.output_types = options.outputTypes;
+ }
+ // Per-item options + op inputs (score query / extract labels / generate
+ // sampling), forwarded as-is; an empty map stays off the wire (additive).
+ if (options.options && Object.keys(options.options).length > 0) {
+ body.options = options.options;
+ }
+ return body;
+}
+
+/** The chunk-ref metadata from a job status doc (`output.chunks` refs). */
+export function jobChunks(jobDoc: JobStatus): JobChunk[] {
+ const raw = jobDoc.output?.chunks ?? [];
+ return raw.map((chunk) => ({
+ seq: chunk.seq,
+ items: chunk.items,
+ state: chunk.state,
+ ref: chunk.ref,
+ units: chunk.units,
+ credits: chunk.credits,
+ error: chunk.error ?? null,
+ }));
+}
+
+function toNumberArrayLike(value: unknown): number[] | Float32Array | null {
+ if (value == null) return null;
+ if (value instanceof Float32Array) return value;
+ if (Array.isArray(value)) return value as number[];
+ if (ArrayBuffer.isView(value)) return value as unknown as Float32Array;
+ return null;
+}
+
+function denseInfo(dense: unknown): {
+ dims: number | null;
+ vector: number[] | Float32Array | null;
+} {
+ if (dense == null) return { dims: null, vector: null };
+ if (typeof dense === "object" && !Array.isArray(dense) && !ArrayBuffer.isView(dense)) {
+ const rec = dense as Record<string, unknown>;
+ let raw: unknown = null;
+ for (const key of ["values", "vector", "dense"]) {
+ if (rec[key] != null) {
+ raw = rec[key];
+ break;
+ }
+ }
+ const vector = toNumberArrayLike(raw);
+ let dims = typeof rec.dims === "number" ? rec.dims : null;
+ if (dims == null && vector != null) dims = vector.length;
+ return { dims, vector };
+ }
+ const vector = toNumberArrayLike(dense);
+ return { dims: vector != null ? vector.length : null, vector };
+}
+
+/** Decode one WorkResult map (from a chunk ref) into a per-item result. */
+export function decodeResultItem(result: Record<string, unknown>): JobResultItem {
+ const payload = result.result_msgpack;
+ let decoded: Record<string, unknown> | null = null;
+ if (payload instanceof Uint8Array) {
+ try {
+ decoded = unpackMessage<Record<string, unknown>>(payload);
+ } catch {
+ decoded = null;
+ }
+ }
+ const dense = decoded && typeof decoded === "object" ? decoded.dense : null;
+ const { dims, vector } = denseInfo(dense);
+ return {
+ id: (result.id as string) ?? null,
+ success: (result.success as boolean) ?? null,
+ units: result.units ?? null,
+ dims,
+ dense: vector,
+ };
+}
+
+/** Decode a chunk ref's msgpack `WorkResult` array into per-item results. */
+export function decodeChunkBytes(raw: Uint8Array): JobResultItem[] {
+ const results = unpackMessage<unknown>(raw);
+ if (!Array.isArray(results)) return [];
+ return results.map((r) => decodeResultItem(r as Record<string, unknown>));
+}
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index a4f1a05b3..ebcd507b8 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -271,10 +271,18 @@ export interface WorkerInfo {
url: string;
/** GPU type (e.g., "l4", "a100-80gb") */
gpu: string;
+ /** Number of GPUs on this worker */
+ gpuCount: number;
+ /** Number of worker GPU slots ready to receive work */
+ readyGpuSlots: number;
/** Whether the worker is healthy */
healthy: boolean;
/** Number of items in the worker's queue */
queueDepth: number;
+ /** Worker-local scheduler pending cost */
+ pendingCost: number;
+ /** Number of batches currently executing on the worker */
+ inflightBatches: number;
/** List of model names loaded on this worker */
loadedModels: string[];
}
@@ -313,6 +321,27 @@ export interface PoolCreateSpec {
gpuCaps?: Record<string, number>;
}
+/**
+ * Optional arguments for `SIEClient.createPool`, mirroring the Python SDK's
+ * `create_pool` keyword arguments (`bundle`, `minimum_worker_count`,
+ * `pinned_models`).
+ */
+export interface CreatePoolOptions {
+ /** Optional bundle filter. When set, only workers running this bundle will be assigned to the pool. */
+ bundle?: string;
+ /**
+ * Per-pool warm floor (minimum machines kept warm). The gateway publishes
+ * it as `sie_gateway_pool_warm_floor` for KEDA. Defaults to 0 (scale to zero).
+ */
+ minimumWorkerCount?: number;
+ /**
+ * Model ids to keep loaded so the first request to them pays no cold
+ * model-load. Each id must be a model the gateway already tracks and may be
+ * profile-qualified ("model-name:profile_name"); unknown ids are rejected.
+ */
+ pinnedModels?: string[];
+}
+
/**
* Pool specification returned by the gateway.
*/
@@ -365,7 +394,15 @@ export interface PoolInfo {
// WebSocket Status Types
// ---------------------------------------------------------------------------
-export type ModelState = "available" | "loading" | "loaded" | "unloading";
+/**
+ * Canonical model residency states. The runtime `MODEL_STATES` array is the
+ * single source the `ModelState` type is derived from, so it can be checked
+ * against the shared golden fixture (`packages/wire-fixtures/model_state.json`)
+ * in CI. Includes `"failed"` (a terminal load-failure state) to stay in parity
+ * with the Python SDK and server, which already carry it.
+ */
+export const MODEL_STATES = ["available", "loading", "loaded", "unloading", "failed"] as const;
+export type ModelState = (typeof MODEL_STATES)[number];
export interface ClusterSummary {
worker_count: number;
@@ -469,10 +506,118 @@ export interface SIEClientOptions {
gpu?: string;
/** API key for authentication (sent as Bearer token) */
apiKey?: string;
- /** Whether to auto-retry on 503 PROVISIONING responses */
+ /**
+ * Whether to auto-retry retryable capacity signals (503 PROVISIONING,
+ * idempotent 504 gateway timeouts, transient connect errors).
+ * Default: `true`, matching the Python SDK's `wait_for_capacity=True`.
+ * BREAKING (0.7): the default was previously `false` — pass `false`
+ * explicitly to fail fast.
+ */
waitForCapacity?: boolean;
/** Maximum time to wait for provisioning in milliseconds (default: 300000) */
provisionTimeout?: number;
+ /**
+ * Control-plane base URL for the `connections` namespace (connector
+ * auth lives on the control plane, not the keyed gateway). Required to call
+ * `client.connections.*`.
+ */
+ controlPlaneUrl?: string;
+ /** Org the `connections` namespace operates on (org-scoped by path in the POC). */
+ org?: string;
+}
+
+/**
+ * An org-scoped connection (connector auth by name). The secret is never
+ * returned by the list endpoint (only the job-runner resolve path sees it).
+ */
+export interface Connection {
+ id?: number;
+ type?: string;
+ name?: string;
+ created_at?: number;
+}
+
+/** The `201` envelope from creating a connection (org + connection, no secret). */
+export interface ConnectionCreated extends Connection {
+ org?: string;
+ account_id?: number;
+}
+
+/** The envelope from revoking (soft-deleting) a connection. */
+export interface ConnectionRevoked {
+ org?: string;
+ account_id?: number;
+ name?: string;
+ state?: string;
+}
+
+/**
+ * An OpenAI-shaped file object (`POST/GET /v1/files`). The
+ * gateway emits `{id, object:"file", bytes, created_at, filename, purpose}`;
+ * `status` / `expires_at` are the optional OpenAI fields surfaced
+ * when the TTL-GC lands. Byte-for-byte OpenAI's `FileObject`.
+ */
+export interface File {
+ id?: string;
+ object?: string;
+ bytes?: number;
+ created_at?: number;
+ filename?: string;
+ purpose?: string;
+ status?: string;
+ expires_at?: number;
+}
+
+/** The envelope from deleting a file (OpenAI `FileDeleted`). */
+export interface FileDeleted {
+ id?: string;
+ object?: string;
+ deleted?: boolean;
+}
+
+/** Per-batch request tally (OpenAI `request_counts`). */
+export interface BatchRequestCounts {
+ total?: number;
+ completed?: number;
+ failed?: number;
+}
+
+/**
+ * An OpenAI-shaped batch object (`POST/GET /v1/batches`).
+ * The gateway emits `{id, object:"batch", endpoint, input_file_id,
+ * completion_window, status, output_file_id, error_file_id, created_at,
+ * finished_at, request_counts, errors}`. The granular OpenAI
+ * timestamps (`completed_at` etc.) are optional — a strict OpenAI SDK reads them
+ * when the gateway surfaces them.
+ */
+export interface Batch {
+ id?: string;
+ object?: string;
+ endpoint?: string;
+ input_file_id?: string;
+ completion_window?: string;
+ status?: string;
+ output_file_id?: string | null;
+ error_file_id?: string | null;
+ created_at?: number;
+ finished_at?: number | null;
+ in_progress_at?: number | null;
+ completed_at?: number | null;
+ failed_at?: number | null;
+ expired_at?: number | null;
+ cancelled_at?: number | null;
+ request_counts?: BatchRequestCounts;
+ errors?: unknown;
+ metadata?: Record<string, unknown> | null;
+}
+
+/** The listing envelope from `GET /v1/batches` (OpenAI cursor page). */
+export interface BatchList {
+ object?: string;
+ data?: Batch[];
+ first_id?: string;
+ last_id?: string;
+ has_more?: boolean;
}
/**
@@ -802,11 +947,11 @@ export interface ChatCompletionChunk {
export interface ChatCompletionOptions {
/**
* When `true`, retry the SAFE pre-execution capacity signals
- * (`503 PROVISIONING`, `503 MODEL_LOADING`) until
- * `provisionTimeoutMs` elapses. When `false`, the first such signal
- * throws (`ProvisioningError` / `ModelLoadingError` / `ServerError`).
- * Defaults to the client's `waitForCapacity` (false unless the
- * constructor opted in).
+ * (`503 PROVISIONING`, `503 MODEL_LOADING`, `503 RESOURCE_EXHAUSTED`)
+ * until `provisionTimeoutMs` elapses. When `false`, the first
+ * provisioning signal throws (`ProvisioningError` / `ModelLoadingError`
+ * / `ServerError`). Defaults to the client's `waitForCapacity`
+ * (true unless the constructor opted out).
*/
waitForCapacity?: boolean;
/**
diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.ts
index 5d2251a83..a82bc198f 100644
--- a/packages/sie_ts_sdk/src/version.ts
+++ b/packages/sie_ts_sdk/src/version.ts
@@ -1 +1 @@
-export const SDK_VERSION = "0.6.16"; // x-release-please-version
+export const SDK_VERSION = "0.6.17"; // x-release-please-version
diff --git a/packages/sie_ts_sdk/tests/batches.test.ts b/packages/sie_ts_sdk/tests/batches.test.ts
new file mode 100644
index 000000000..5f3e4106b
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/batches.test.ts
@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+const GW = "http://gw:8080";
+const BATCH = {
+ id: "batch-1",
+ object: "batch",
+ endpoint: "/v1/embeddings",
+ input_file_id: "file-in",
+ completion_window: "24h",
+ status: "completed",
+ output_file_id: "file-out",
+ request_counts: { total: 2, completed: 2, failed: 0 },
+};
+
+describe("client.batches", () => {
+ beforeEach(() => mockFetch.mockClear());
+
+ it("create posts the OpenAI-shaped body to /v1/batches", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(BATCH, 200));
+ const client = new SIEClient(GW, { apiKey: "sk-sie-x" });
+ const out = await client.batches.create({
+ input_file_id: "file-in",
+ endpoint: "/v1/embeddings",
+ });
+ expect(out.id).toBe("batch-1");
+ expect(out.request_counts?.total).toBe(2);
+ const [url, init] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://gw:8080/v1/batches");
+ expect(init.method).toBe("POST");
+ expect(JSON.parse(init.body)).toEqual({
+ input_file_id: "file-in",
+ endpoint: "/v1/embeddings",
+ completion_window: "24h",
+ });
+ expect(init.headers.Authorization).toBe("Bearer sk-sie-x");
+ });
+
+ it("create includes metadata and defaults endpoint/completion_window", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(BATCH, 200));
+ const client = new SIEClient(GW);
+ await client.batches.create({ input_file_id: "file-in", metadata: { run: "eval-7" } });
+ expect(JSON.parse(mockFetch.mock.calls[0][1].body)).toEqual({
+ input_file_id: "file-in",
+ endpoint: "/v1/embeddings",
+ completion_window: "24h",
+ metadata: { run: "eval-7" },
+ });
+ });
+
+ it("retrieve and cancel hit the expected URLs", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(BATCH));
+ const client = new SIEClient(GW);
+ await client.batches.retrieve("batch-1");
+ expect(mockFetch.mock.calls[0][0]).toBe("http://gw:8080/v1/batches/batch-1");
+
+ mockFetch.mockResolvedValueOnce(jsonResponse({ id: "batch-1", status: "cancelling" }));
+ const out = await client.batches.cancel("batch-1");
+ expect(out.status).toBe("cancelling");
+ expect(mockFetch.mock.calls[1][0]).toBe("http://gw:8080/v1/batches/batch-1/cancel");
+ expect(mockFetch.mock.calls[1][1].method).toBe("POST");
+ });
+
+ it("list returns the data array", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({ object: "list", data: [{ id: "batch-1" }, { id: "batch-2" }] }),
+ );
+ const client = new SIEClient(GW);
+ const batches = await client.batches.list();
+ expect(batches.map((b) => b.id)).toEqual(["batch-1", "batch-2"]);
+ expect(mockFetch.mock.calls[0][0]).toBe("http://gw:8080/v1/batches");
+ });
+});
diff --git a/packages/sie_ts_sdk/tests/client.test.ts b/packages/sie_ts_sdk/tests/client.test.ts
index d1d19bd94..99a2788d2 100644
--- a/packages/sie_ts_sdk/tests/client.test.ts
+++ b/packages/sie_ts_sdk/tests/client.test.ts
@@ -12,7 +12,13 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SIEClient } from "../src/client.js";
-import { ProvisioningError, RequestError, SIEConnectionError, ServerError } from "../src/errors.js";
+import {
+ ProvisioningError,
+ RequestError,
+ ResourceExhaustedError,
+ SIEConnectionError,
+ ServerError,
+} from "../src/errors.js";
import { packMessage, unpackMessage } from "../src/msgpack.js";
// Mock fetch globally
@@ -510,10 +516,14 @@ describe("SIEClient error handling", () => {
});
it("should throw SIEConnectionError for fetch failures", async () => {
- // User scenario: "The server is down"
+ // User scenario: "The server is down". waitForCapacity now defaults to
+ // true (Python-SDK parity), so opt out to fail fast instead of retrying
+ // the connect error for the whole provision budget.
mockFetch.mockRejectedValueOnce(new TypeError("fetch failed"));
- await expect(client.encode("bge-m3", { text: "test" })).rejects.toThrow(SIEConnectionError);
+ await expect(
+ client.encode("bge-m3", { text: "test" }, { waitForCapacity: false }),
+ ).rejects.toThrow(SIEConnectionError);
});
it("should throw SIEConnectionError for timeout", async () => {
@@ -764,6 +774,269 @@ describe("SIEClient retry on connection errors and provisioning 503s", () => {
await client.close();
});
+
+ it("defaults waitForCapacity to true (Python-SDK parity)", async () => {
+ // No explicit waitForCapacity anywhere: the constructor default must
+ // now retry 503 PROVISIONING instead of failing fast.
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+
+ mockFetch
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ error: { code: "PROVISIONING", message: "provisioning" } }), {
+ status: 503,
+ headers: { "Content-Type": "application/json" },
+ }),
+ )
+ .mockResolvedValueOnce(
+ createMsgpackResponse({
+ items: [{ dense: { values: new Float32Array([0.1]) } }],
+ }),
+ );
+
+ const promise = client.encode("bge-m3", { text: "test" });
+
+ await vi.advanceTimersByTimeAsync(5_000);
+ const result = await promise;
+
+ expect(result.dense).toBeInstanceOf(Float32Array);
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+
+ await client.close();
+ });
+});
+
+describe("SIEClient retry on 503 RESOURCE_EXHAUSTED and 504 gateway timeout", () => {
+ beforeEach(() => {
+ mockFetch.mockClear();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function oomResponse(headers: Record<string, string> = {}): Response {
+ return new Response(
+ JSON.stringify({ error: { code: "RESOURCE_EXHAUSTED", message: "out of memory" } }),
+ { status: 503, headers: { "Content-Type": "application/json", ...headers } },
+ );
+ }
+
+ function gatewayTimeoutResponse(): Response {
+ return new Response(
+ JSON.stringify({ error: { code: "GATEWAY_TIMEOUT", message: "result deadline exceeded" } }),
+ { status: 504, headers: { "Content-Type": "application/json" } },
+ );
+ }
+
+ it("retries 503 RESOURCE_EXHAUSTED with backoff then succeeds", async () => {
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+
+ mockFetch.mockResolvedValueOnce(oomResponse()).mockResolvedValueOnce(
+ createMsgpackResponse({
+ items: [{ dense: { values: new Float32Array([0.1]) } }],
+ }),
+ );
+
+ const promise = client.encode("bge-m3", { text: "test" });
+
+ // First OOM backoff is jittered but never exceeds the 5s base.
+ await vi.advanceTimersByTimeAsync(5_000);
+ const result = await promise;
+
+ expect(result.dense).toBeInstanceOf(Float32Array);
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+
+ await client.close();
+ });
+
+ it("retries 503 RESOURCE_EXHAUSTED even when waitForCapacity is false", async () => {
+ // Python-SDK parity: the OOM budget is independent of waitForCapacity
+ // on the buffered paths (the worker already accepted the request).
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+
+ mockFetch.mockResolvedValueOnce(oomResponse()).mockResolvedValueOnce(
+ createMsgpackResponse({
+ items: [{ dense: { values: new Float32Array([0.1]) } }],
+ }),
+ );
+
+ const promise = client.encode("bge-m3", { text: "test" }, { waitForCapacity: false });
+
+ await vi.advanceTimersByTimeAsync(5_000);
+ const result = await promise;
+
+ expect(result.dense).toBeInstanceOf(Float32Array);
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+
+ await client.close();
+ });
+
+ it("throws ResourceExhaustedError after the bounded OOM retry budget", async () => {
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+
+ // Sustained OOM: every attempt returns RESOURCE_EXHAUSTED.
+ mockFetch.mockImplementation(() => Promise.resolve(oomResponse()));
+
+ const promise = client.encode("bge-m3", { text: "test" });
+ const expectation = expect(promise).rejects.toThrow(ResourceExhaustedError);
+
+ // Max backoff schedule (no Retry-After): ≤5s, ≤10s, ≤20s → ≤35s total.
+ await vi.advanceTimersByTimeAsync(35_000);
+ await expectation;
+
+ // RESOURCE_EXHAUSTED_MAX_RETRIES = 3 → 4 requests (initial + 3 retries).
+ expect(mockFetch).toHaveBeenCalledTimes(4);
+
+ await client.close();
+ });
+
+ it("honors Retry-After verbatim on the first OOM retry", async () => {
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+
+ mockFetch.mockResolvedValueOnce(oomResponse({ "Retry-After": "1" })).mockResolvedValueOnce(
+ createMsgpackResponse({
+ items: [{ dense: { values: new Float32Array([0.1]) } }],
+ }),
+ );
+
+ const promise = client.encode("bge-m3", { text: "test" });
+
+ // The first server hint (1s) is honored verbatim — no jitter, so the
+ // retry must not fire before the full second elapses.
+ await vi.advanceTimersByTimeAsync(999);
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(1);
+ const result = await promise;
+
+ expect(result.dense).toBeInstanceOf(Float32Array);
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+
+ await client.close();
+ });
+
+ it("retries 504 gateway timeouts on the idempotent encode path", async () => {
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+
+ mockFetch.mockResolvedValueOnce(gatewayTimeoutResponse()).mockResolvedValueOnce(
+ createMsgpackResponse({
+ items: [{ dense: { values: new Float32Array([0.1]) } }],
+ }),
+ );
+
+ const promise = client.encode("bge-m3", { text: "test" });
+
+ // 504 retry delay defaults to MODEL_LOADING_DEFAULT_DELAY (5s).
+ await vi.advanceTimersByTimeAsync(5_000);
+ const result = await promise;
+
+ expect(result.dense).toBeInstanceOf(Float32Array);
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+
+ await client.close();
+ });
+
+ it("does not retry 504 when waitForCapacity is false", async () => {
+ const client = new SIEClient("http://localhost:8080", { timeout: 1000 });
+
+ mockFetch.mockResolvedValueOnce(gatewayTimeoutResponse());
+
+ await expect(
+ client.encode("bge-m3", { text: "test" }, { waitForCapacity: false }),
+ ).rejects.toThrow(ServerError);
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+
+ await client.close();
+ });
+});
+
+describe("SIEClient.createPool() - bundle / warm-floor / pinned-model args", () => {
+ beforeEach(() => {
+ mockFetch.mockClear();
+ });
+
+ function poolCreatedResponse(): Response {
+ return createMockResponse({ name: "eval", spec: {}, status: { state: "pending" } });
+ }
+
+ it("sends bundle, minimum_worker_count and pinned_models on the wire", async () => {
+ const client = new SIEClient("http://localhost:8080");
+ mockFetch.mockResolvedValueOnce(poolCreatedResponse());
+
+ await client.createPool("eval", { l4: 2 }, { l4: 4 }, "batch", {
+ bundle: "default",
+ minimumWorkerCount: 1,
+ pinnedModels: ["bge-m3:default"],
+ });
+
+ const [url, init] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://localhost:8080/v1/pools");
+ expect(JSON.parse(init.body)).toEqual({
+ name: "eval",
+ gpus: { l4: 2 },
+ gpu_caps: { l4: 4 },
+ queue_pool: "batch",
+ bundle: "default",
+ minimum_worker_count: 1,
+ pinned_models: ["bge-m3:default"],
+ });
+
+ await client.close();
+ });
+
+ it("omits the optional fields from the wire body when not provided", async () => {
+ const client = new SIEClient("http://localhost:8080");
+ mockFetch.mockResolvedValueOnce(poolCreatedResponse());
+
+ await client.createPool("eval", { l4: 2 });
+
+ const [, init] = mockFetch.mock.calls[0];
+ expect(JSON.parse(init.body)).toEqual({ name: "eval", gpus: { l4: 2 } });
+
+ await client.close();
+ });
+
+ it("preserves an explicit zero warm floor (scale to zero)", async () => {
+ const client = new SIEClient("http://localhost:8080");
+ mockFetch.mockResolvedValueOnce(poolCreatedResponse());
+
+ await client.createPool("eval", { l4: 2 }, undefined, undefined, { minimumWorkerCount: 0 });
+
+ const [, init] = mockFetch.mock.calls[0];
+ expect(JSON.parse(init.body).minimum_worker_count).toBe(0);
+
+ await client.close();
+ });
+
+ it("rejects a negative warm floor without issuing a request", async () => {
+ const client = new SIEClient("http://localhost:8080");
+
+ await expect(
+ client.createPool("eval", undefined, undefined, undefined, { minimumWorkerCount: -1 }),
+ ).rejects.toThrow(RangeError);
+ expect(mockFetch).not.toHaveBeenCalled();
+
+ await client.close();
+ });
});
describe("Real-world usage patterns", () => {
diff --git a/packages/sie_ts_sdk/tests/connections.test.ts b/packages/sie_ts_sdk/tests/connections.test.ts
new file mode 100644
index 000000000..1c0e200f7
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/connections.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+const GW = "http://gw:8080";
+const CP = "http://cp:9000";
+
+describe("client.connections", () => {
+ beforeEach(() => mockFetch.mockClear());
+
+ it("add posts to the control plane with the secret in the body", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({ org: "acme", account_id: 7, id: 1, type: "postgres", name: "wh" }, 201),
+ );
+ const client = new SIEClient(GW, { apiKey: "sk-sie-x", controlPlaneUrl: CP, org: "acme" });
+ const out = await client.connections.add("wh", "postgres", "postgres://u:p@h/db");
+ expect(out.name).toBe("wh");
+ const [url, init] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://cp:9000/internal/orgs/acme/connections");
+ expect(init.method).toBe("POST");
+ expect(JSON.parse(init.body)).toEqual({
+ type: "postgres",
+ name: "wh",
+ secret: "postgres://u:p@h/db",
+ });
+ });
+
+ it("list returns the connections array", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({
+ org: "acme",
+ account_id: 7,
+ connections: [{ id: 1, type: "postgres", name: "wh" }],
+ }),
+ );
+ const client = new SIEClient(GW, { controlPlaneUrl: CP, org: "acme" });
+ const conns = await client.connections.list();
+ expect(conns.map((c) => c.name)).toEqual(["wh"]);
+ expect(mockFetch.mock.calls[0][0]).toBe("http://cp:9000/internal/orgs/acme/connections");
+ });
+
+ it("revoke deletes the named connection", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse({ org: "acme", name: "wh", state: "revoked" }));
+ const client = new SIEClient(GW, { controlPlaneUrl: CP, org: "acme" });
+ const out = await client.connections.revoke("wh");
+ expect(out.state).toBe("revoked");
+ const [url, init] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://cp:9000/internal/orgs/acme/connections/wh");
+ expect(init.method).toBe("DELETE");
+ });
+
+ it("throws when controlPlaneUrl is not configured", async () => {
+ const client = new SIEClient(GW, { apiKey: "sk-sie-x" });
+ await expect(client.connections.list()).rejects.toThrow(/controlPlaneUrl/);
+ });
+
+ it("throws when org is not configured", async () => {
+ const client = new SIEClient(GW, { controlPlaneUrl: CP });
+ await expect(client.connections.list()).rejects.toThrow(/org/);
+ });
+});
diff --git a/packages/sie_ts_sdk/tests/files.test.ts b/packages/sie_ts_sdk/tests/files.test.ts
new file mode 100644
index 000000000..13e285091
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/files.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+const GW = "http://gw:8080";
+const FILE = {
+ id: "file-abc",
+ object: "file",
+ bytes: 42,
+ created_at: 1,
+ filename: "in.jsonl",
+ purpose: "batch",
+};
+
+describe("client.files", () => {
+ beforeEach(() => mockFetch.mockClear());
+
+ it("upload posts a raw body to /v1/files with purpose + filename query", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(FILE, 200));
+ const client = new SIEClient(GW, { apiKey: "sk-sie-x" });
+ const bytes = new TextEncoder().encode('{"custom_id":"a"}\n');
+ const out = await client.files.upload(bytes, { purpose: "batch", filename: "in.jsonl" });
+ expect(out.id).toBe("file-abc");
+ const [url, init] = mockFetch.mock.calls[0];
+ expect(url).toContain("/v1/files?");
+ expect(url).toContain("purpose=batch");
+ expect(url).toContain("filename=in.jsonl");
+ expect(init.method).toBe("POST");
+ expect(init.headers["Content-Type"]).toBe("application/jsonl");
+ expect(init.headers.Authorization).toBe("Bearer sk-sie-x");
+ expect(init.body).toBe(bytes);
+ });
+
+ it("create is an OpenAI-exact alias ({ file, purpose })", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(FILE, 200));
+ const client = new SIEClient(GW);
+ const out = await client.files.create({ file: "line1\nline2\n", purpose: "batch" });
+ expect(out.id).toBe("file-abc");
+ expect(mockFetch.mock.calls[0][0]).toContain("purpose=batch");
+ expect(mockFetch.mock.calls[0][1].body).toBe("line1\nline2\n");
+ });
+
+ it("derives the filename from a File's .name", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(FILE, 200));
+ const client = new SIEClient(GW);
+ const blob = new File([new TextEncoder().encode("x")], "batch_input.jsonl");
+ await client.files.upload(blob);
+ expect(mockFetch.mock.calls[0][0]).toContain("filename=batch_input.jsonl");
+ });
+
+ it("retrieve and delete hit the expected URLs", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(FILE));
+ const client = new SIEClient(GW);
+ await client.files.retrieve("file-abc");
+ expect(mockFetch.mock.calls[0][0]).toBe("http://gw:8080/v1/files/file-abc");
+
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({ id: "file-abc", object: "file", deleted: true }),
+ );
+ const del = await client.files.delete("file-abc");
+ expect(del.deleted).toBe(true);
+ expect(mockFetch.mock.calls[1][0]).toBe("http://gw:8080/v1/files/file-abc");
+ expect(mockFetch.mock.calls[1][1].method).toBe("DELETE");
+ });
+
+ it("content returns the raw file bytes", async () => {
+ const payload = new TextEncoder().encode('{"custom_id":"a","response":{"status_code":200}}\n');
+ mockFetch.mockResolvedValueOnce(new Response(payload, { status: 200 }));
+ const client = new SIEClient(GW);
+ const out = await client.files.content("file-out");
+ expect(new TextDecoder().decode(out)).toBe(
+ '{"custom_id":"a","response":{"status_code":200}}\n',
+ );
+ expect(mockFetch.mock.calls[0][0]).toBe("http://gw:8080/v1/files/file-out/content");
+ });
+});
diff --git a/packages/sie_ts_sdk/tests/generate.test.ts b/packages/sie_ts_sdk/tests/generate.test.ts
index 22eb3174d..1ef52fbba 100644
--- a/packages/sie_ts_sdk/tests/generate.test.ts
+++ b/packages/sie_ts_sdk/tests/generate.test.ts
@@ -9,7 +9,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SIEClient } from "../src/client.js";
-import { RequestError, SIEConnectionError } from "../src/errors.js";
+import {
+ RequestError,
+ ResourceExhaustedError,
+ SIEConnectionError,
+ ServerError,
+} from "../src/errors.js";
const mockFetch = vi.fn();
vi.stubGlobal("fetch", mockFetch);
@@ -308,4 +313,90 @@ describe("SIEClient.generate retry semantics (B1c)", () => {
expect(result.text).toBe("loaded");
expect(mockFetch).toHaveBeenCalledTimes(2);
});
+
+ it("retries the safe 503 RESOURCE_EXHAUSTED pre-execution signal", async () => {
+ vi.useFakeTimers();
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+
+ mockFetch
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({ error: { code: "RESOURCE_EXHAUSTED", message: "out of memory" } }),
+ { status: 503, headers: { "Content-Type": "application/json" } },
+ ),
+ )
+ .mockResolvedValueOnce(
+ jsonResponse({
+ model: "m",
+ text: "recovered",
+ finish_reason: "stop",
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
+ attempt_id: "a",
+ }),
+ );
+
+ const promise = client.generate("m", "hi", { maxNewTokens: 8 });
+ // First OOM backoff is jittered but never exceeds the 5s base.
+ await vi.advanceTimersByTimeAsync(5_000);
+ const result = await promise;
+
+ expect(result.text).toBe("recovered");
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it("surfaces sustained RESOURCE_EXHAUSTED as ResourceExhaustedError", async () => {
+ vi.useFakeTimers();
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+
+ mockFetch.mockImplementation(() =>
+ Promise.resolve(
+ new Response(
+ JSON.stringify({ error: { code: "RESOURCE_EXHAUSTED", message: "out of memory" } }),
+ { status: 503, headers: { "Content-Type": "application/json" } },
+ ),
+ ),
+ );
+
+ const promise = client.generate("m", "hi", { maxNewTokens: 8 });
+ const expectation = expect(promise).rejects.toThrow(ResourceExhaustedError);
+
+ // Max backoff schedule (no Retry-After): ≤5s, ≤10s, ≤20s → ≤35s total.
+ await vi.advanceTimersByTimeAsync(35_000);
+ await expectation;
+
+ // RESOURCE_EXHAUSTED_MAX_RETRIES = 3 → 4 requests (initial + 3 retries).
+ expect(mockFetch).toHaveBeenCalledTimes(4);
+ });
+
+ it("does NOT retry a 504 gateway timeout even when waitForCapacity is true", async () => {
+ // 504 is post-publish: a worker may already be generating. Retrying
+ // could double-bill, so generate() must surface it terminally.
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+
+ mockFetch.mockResolvedValue(
+ new Response(
+ JSON.stringify({ error: { code: "GATEWAY_TIMEOUT", message: "result deadline" } }),
+ { status: 504, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+
+ await expect(
+ client.generate("m", "hi", { maxNewTokens: 8, waitForCapacity: true }),
+ ).rejects.toThrow(/non-idempotent/);
+ await expect(
+ client.generate("m", "hi", { maxNewTokens: 8, waitForCapacity: true }),
+ ).rejects.toBeInstanceOf(ServerError);
+
+ // Crucially: one call per generate() invocation, no retry.
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/packages/sie_ts_sdk/tests/internal.test.ts b/packages/sie_ts_sdk/tests/internal.test.ts
index fca65da9f..9eb16ff23 100644
--- a/packages/sie_ts_sdk/tests/internal.test.ts
+++ b/packages/sie_ts_sdk/tests/internal.test.ts
@@ -414,8 +414,12 @@ describe("Capacity info parsing", () => {
{
url: "http://worker1:8080",
gpu: "l4",
+ gpu_count: 4,
+ ready_gpu_slots: 3,
healthy: true,
queue_depth: 5,
+ pending_cost: 128,
+ inflight_batches: 2,
loaded_models: ["bge-m3", "e5-large"],
},
{
@@ -439,8 +443,12 @@ describe("Capacity info parsing", () => {
expect(result.workers).toHaveLength(2);
expect(result.workers[0]?.url).toBe("http://worker1:8080");
expect(result.workers[0]?.gpu).toBe("l4");
+ expect(result.workers[0]?.gpuCount).toBe(4);
+ expect(result.workers[0]?.readyGpuSlots).toBe(3);
expect(result.workers[0]?.healthy).toBe(true);
expect(result.workers[0]?.queueDepth).toBe(5);
+ expect(result.workers[0]?.pendingCost).toBe(128);
+ expect(result.workers[0]?.inflightBatches).toBe(2);
expect(result.workers[0]?.loadedModels).toEqual(["bge-m3", "e5-large"]);
});
diff --git a/packages/sie_ts_sdk/tests/jobs.test.ts b/packages/sie_ts_sdk/tests/jobs.test.ts
new file mode 100644
index 000000000..d31f0488a
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/jobs.test.ts
@@ -0,0 +1,325 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+import { buildJobBody, connectionName } from "../src/jobs.js";
+import { packMessage } from "../src/msgpack.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+const SUBMIT_RESP = {
+ id: "job-1",
+ object: "job",
+ operation: "encode",
+ model: "BAAI/bge-m3",
+ state: "queued",
+ total_items: 2,
+ chunks: 1,
+ preflight: { estimated_credits: 64 },
+};
+
+describe("buildJobBody (pure slot mapping)", () => {
+ it("maps an inline list to items", () => {
+ expect(buildJobBody({ source: ["a", "b"], model: "m" })).toEqual({
+ operation: "encode",
+ model: "m",
+ items: [{ text: "a" }, { text: "b" }],
+ });
+ });
+
+ it("routes a connector URI to src + derived connection", () => {
+ const body = buildJobBody({
+ source: "postgres://warehouse?query=x",
+ model: "m",
+ sink: "postgres://warehouse?table=t",
+ });
+ expect(body.src).toBe("postgres://warehouse?query=x");
+ expect(body.connection).toBe("warehouse");
+ expect(body.sink).toBe("postgres://warehouse?table=t");
+ expect(body.sink_connection).toBeUndefined();
+ });
+
+ it("threads a distinct sink connection", () => {
+ const body = buildJobBody({
+ source: "postgres://wh?query=x",
+ model: "m",
+ sink: "s3://out/vecs",
+ });
+ expect(body.sink_connection).toBe("out");
+ });
+
+ it("maps schedule / watch triggers", () => {
+ expect(buildJobBody({ source: ["a"], model: "m", when: "schedule:*/5 * * * *" })).toMatchObject(
+ {
+ when: "schedule",
+ schedule: "*/5 * * * *",
+ },
+ );
+ expect(buildJobBody({ source: ["a"], model: "m", when: "watch:s3://in" })).toMatchObject({
+ when: "watch",
+ watch: "s3://in",
+ });
+ });
+
+ it("derives connection names from URIs", () => {
+ expect(connectionName("postgres://warehouse?query=x")).toBe("warehouse");
+ expect(connectionName("s3://customer-bucket/in/")).toBe("customer-bucket");
+ });
+
+ // field_map / output_field + the internal upload:// scheme
+
+ it("rides field_map + output_field on connector jobs", () => {
+ const body = buildJobBody({
+ source: "postgres://wh?query=select id, body, source_url from docs",
+ model: "BAAI/bge-m3",
+ sink: "postgres://wh?table=doc_vectors",
+ fieldMap: {
+ id_field: "id",
+ input_field: "body",
+ carry: ["source_url"],
+ input_type: "text",
+ },
+ outputField: "embedding",
+ });
+ expect(body.field_map).toEqual({
+ id_field: "id",
+ input_field: "body",
+ input_type: "text",
+ carry: ["source_url"],
+ });
+ expect(body.output_field).toBe("embedding");
+ });
+
+ it("rejects field_map on inline items and bad slots", () => {
+ expect(() =>
+ buildJobBody({ source: ["a"], model: "m", fieldMap: { id_field: "id" } }),
+ ).toThrowError(/connector-src/);
+ expect(() =>
+ buildJobBody({
+ source: "postgres://wh?query=x",
+ model: "m",
+ sink: "postgres://wh?table=t",
+ fieldMap: { id_column: "id" } as never,
+ }),
+ ).toThrowError(/unknown field_map key/);
+ expect(() =>
+ buildJobBody({
+ source: "postgres://wh?query=x",
+ model: "m",
+ sink: "postgres://wh?table=t",
+ fieldMap: { input_type: "rows" } as never,
+ }),
+ ).toThrowError(/input_type/);
+ });
+
+ it("derives no connection for the internal upload:// scheme", () => {
+ const body = buildJobBody({
+ source: "upload://file-abc?format=csv",
+ model: "m",
+ sink: "upload://file-out",
+ fieldMap: { id_field: "doc_id", input_field: "text" },
+ });
+ expect(body.src).toBe("upload://file-abc?format=csv");
+ expect(body.sink).toBe("upload://file-out");
+ expect(body.connection).toBeUndefined();
+ expect(body.sink_connection).toBeUndefined();
+ // upload source → external sink still threads the sink's connection.
+ const cross = buildJobBody({
+ source: "upload://file-abc",
+ model: "m",
+ sink: "postgres://wh?table=doc_vectors",
+ sinkConnection: "wh",
+ });
+ expect(cross.connection).toBeUndefined();
+ expect(cross.sink_connection).toBe("wh");
+ });
+
+ it("forwards op inputs via options as-is (op matrix)", () => {
+ // score: options.query rides untouched (connector form).
+ const score = buildJobBody({
+ source: "postgres://wh?query=x",
+ model: "m",
+ operation: "score",
+ sink: "postgres://wh?table=scores",
+ options: { query: "rank these documents" },
+ });
+ expect(score.options).toEqual({ query: "rank these documents" });
+
+ // extract: labels + output_schema forwarded (inline form).
+ const extract = buildJobBody({
+ source: ["some text"],
+ model: "m",
+ operation: "extract",
+ options: { labels: ["PERSON", "ORG"], output_schema: { type: "object" } },
+ });
+ expect(extract.options).toEqual({
+ labels: ["PERSON", "ORG"],
+ output_schema: { type: "object" },
+ });
+
+ // Absent / empty options stay off the wire (additive-only).
+ expect(buildJobBody({ source: ["a"], model: "m" }).options).toBeUndefined();
+ expect(buildJobBody({ source: ["a"], model: "m", options: {} }).options).toBeUndefined();
+ });
+});
+
+describe("client.jobs", () => {
+ beforeEach(() => mockFetch.mockClear());
+
+ it("submit posts the inline body to /v1/jobs", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(SUBMIT_RESP, 201));
+ const client = new SIEClient("http://gw:8080", { apiKey: "sk-sie-x" });
+ const result = await client.jobs.submit({ source: ["a", "b"], model: "BAAI/bge-m3" });
+ expect(result.id).toBe("job-1");
+ const [url, init] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://gw:8080/v1/jobs");
+ expect(init.method).toBe("POST");
+ expect(JSON.parse(init.body)).toEqual({
+ operation: "encode",
+ model: "BAAI/bge-m3",
+ items: [{ text: "a" }, { text: "b" }],
+ });
+ expect(init.headers.Authorization).toBe("Bearer sk-sie-x");
+ });
+
+ it("submit maps a connector job body", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(SUBMIT_RESP, 201));
+ const client = new SIEClient("http://gw:8080");
+ await client.jobs.submit({
+ source: "postgres://warehouse?query=x",
+ model: "m",
+ sink: "s3://out/vecs",
+ });
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.src).toBe("postgres://warehouse?query=x");
+ expect(body.connection).toBe("warehouse");
+ expect(body.sink_connection).toBe("out");
+ });
+
+ it("submit forwards score query and extract labels via options", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(SUBMIT_RESP, 201));
+ const client = new SIEClient("http://gw:8080");
+ await client.jobs.submit({
+ source: "postgres://wh?query=x",
+ model: "BAAI/bge-m3",
+ operation: "score",
+ sink: "postgres://wh?table=scores",
+ options: { query: "rank these documents" },
+ });
+ const scoreBody = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(scoreBody.operation).toBe("score");
+ expect(scoreBody.options).toEqual({ query: "rank these documents" });
+
+ mockFetch.mockResolvedValueOnce(jsonResponse(SUBMIT_RESP, 201));
+ await client.jobs.submit({
+ source: ["some text"],
+ model: "urchade/gliner_small-v2.1",
+ operation: "extract",
+ options: { labels: ["PERSON", "ORG"] },
+ });
+ const extractBody = JSON.parse(mockFetch.mock.calls[1][1].body);
+ expect(extractBody.operation).toBe("extract");
+ expect(extractBody.options).toEqual({ labels: ["PERSON", "ORG"] });
+ });
+
+ it("get and cancel hit the expected URLs", async () => {
+ mockFetch.mockResolvedValueOnce(jsonResponse({ id: "job-1", state: "running" }));
+ const client = new SIEClient("http://gw:8080");
+ await client.jobs.get("job-1");
+ expect(mockFetch.mock.calls[0][0]).toBe("http://gw:8080/v1/jobs/job-1");
+
+ mockFetch.mockResolvedValueOnce(jsonResponse({ id: "job-1", state: "cancelled" }));
+ const out = await client.jobs.cancel("job-1");
+ expect(out.state).toBe("cancelled");
+ expect(mockFetch.mock.calls[1][0]).toBe("http://gw:8080/v1/jobs/job-1/cancel");
+ expect(mockFetch.mock.calls[1][1].method).toBe("POST");
+ });
+
+ it("list returns the data array", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({ object: "list", data: [{ id: "job-1" }, { id: "job-2" }] }),
+ );
+ const client = new SIEClient("http://gw:8080");
+ const jobs = await client.jobs.list();
+ expect(jobs.map((j) => j.id)).toEqual(["job-1", "job-2"]);
+ expect(mockFetch.mock.calls[0][0]).toBe("http://gw:8080/v1/jobs");
+ });
+
+ it("results reads http refs and decodes per-item embeddings", async () => {
+ const chunkBytes = packMessage([
+ {
+ success: true,
+ id: "0",
+ units: { input_tokens: 5 },
+ result_msgpack: packMessage({ dense: { dims: 4, values: [0.1, 0.2, 0.3, 0.4] } }),
+ },
+ ]);
+ const job = {
+ id: "job-1",
+ state: "succeeded",
+ total_items: 1,
+ settled_credits: 5,
+ output: {
+ kind: "refs",
+ chunks: [{ seq: 0, items: 1, state: "succeeded", ref: "http://refs.local/c0" }],
+ },
+ };
+ mockFetch
+ .mockResolvedValueOnce(jsonResponse(job))
+ .mockResolvedValueOnce(new Response(chunkBytes, { status: 200 }));
+
+ const client = new SIEClient("http://gw:8080");
+ const results = await client.jobs.results("job-1");
+ // snake_case throughout (matches the wire + the Python SDK + JobStatus).
+ expect(results.job_id).toBe("job-1");
+ expect(results.total_items).toBe(1);
+ expect(results.settled_credits).toBe(5);
+ expect(results.retrieved).toBe(1);
+ expect(results.dims).toBe(4);
+ expect(Array.from(results.items[0].dense as number[])).toEqual([0.1, 0.2, 0.3, 0.4]);
+ });
+
+ it("wait polls until the job reaches a terminal state", async () => {
+ mockFetch
+ .mockResolvedValueOnce(jsonResponse({ id: "job-1", state: "running" }))
+ .mockResolvedValueOnce(jsonResponse({ id: "job-1", state: "succeeded" }));
+ const client = new SIEClient("http://gw:8080");
+ const job = await client.jobs.wait("job-1", { pollMs: 0 });
+ expect(job.state).toBe("succeeded");
+ expect(mockFetch.mock.calls.length).toBe(2);
+ });
+
+ it("wait throws a job_wait_timeout RequestError when the deadline passes", async () => {
+ mockFetch.mockResolvedValue(jsonResponse({ id: "job-1", state: "running" }));
+ const client = new SIEClient("http://gw:8080");
+ await expect(client.jobs.wait("job-1", { timeoutMs: 0, pollMs: 0 })).rejects.toMatchObject({
+ code: "job_wait_timeout",
+ });
+ });
+
+ it("submit floors the abort timeout to 120s (survives the 30s default)", () => {
+ vi.useFakeTimers();
+ try {
+ let capturedInit: RequestInit | undefined;
+ mockFetch.mockImplementationOnce((_url: string, init: RequestInit) => {
+ capturedInit = init;
+ return new Promise<Response>(() => {}); // never settles; we only inspect the signal
+ });
+ const client = new SIEClient("http://gw:8080");
+ client.jobs.submit({ source: ["a"], model: "m" }).catch(() => {}); // swallow the eventual abort
+ expect(capturedInit?.signal?.aborted).toBe(false);
+ vi.advanceTimersByTime(30_000);
+ expect(capturedInit?.signal?.aborted).toBe(false); // past the 30s default, still alive
+ vi.advanceTimersByTime(90_001);
+ expect(capturedInit?.signal?.aborted).toBe(true); // aborts at the 120s floor
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/sie_ts_sdk/tests/wireContract.test.ts b/packages/sie_ts_sdk/tests/wireContract.test.ts
new file mode 100644
index 000000000..cec4b4003
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/wireContract.test.ts
@@ -0,0 +1,26 @@
+/**
+ * The TS SDK's wire enums must match the shared golden fixtures.
+ *
+ * Round-trips packages/wire-fixtures/model_state.json against the runtime
+ * MODEL_STATES array (the single source the ModelState type is derived from),
+ * so drift fails in CI rather than shipping. See
+ * packages/wire-fixtures/README.md.
+ */
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+import { MODEL_STATES } from "../src/types.js";
+
+const fixturesDir = fileURLToPath(new URL("../../wire-fixtures/", import.meta.url));
+
+function loadFixture(name: string): Record<string, unknown> {
+ return JSON.parse(readFileSync(`${fixturesDir}${name}`, "utf8"));
+}
+
+describe("wire contract golden fixtures", () => {
+ it("ModelState matches the golden fixture", () => {
+ const fixture = loadFixture("model_state.json");
+ const states = fixture.model_states as string[];
+ expect([...MODEL_STATES].sort()).toEqual([...states].sort());
+ });
+});
diff --git a/pyproject.toml b/pyproject.toml
index 549b40a24..ea6e4c601 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -237,6 +237,11 @@ ignore = [
"tools/loadtest/*.py" = [
"INP001", # Standalone loadtest CI scripts, not a package
]
+"packages/sie_tools/tests/test_auth.py" = [
+ "S105", # Hardcoded "password" strings — device-flow session tokens are test doubles
+ "S106", # Same, as function arguments (access_token=/refresh_token=)
+ "S107", # Same, as function defaults
+]
"**/tests/**/*" = [
"ANN", # Type annotations (tests don't need full typing)
"ARG", # Unused function arguments (fixtures)
@@ -454,6 +459,11 @@ exclude = [
# Test files - use mocks/fixtures that don't type-check well with ty
"packages/*/tests/**",
+ # Standalone uv sub-projects (own lockfile/venv, not workspace members)
+ # are type-checked inside their own projects; the root interpreter
+ # cannot resolve their imports.
+ "packages/sie_cloud/**",
+
# xformers/flash_attn optional (requires CUDA build)
"packages/sie_server/src/sie_server/adapters/bert_flash/**",
"packages/sie_server/src/sie_server/adapters/nomic_flash/**",
diff --git a/uv.lock b/uv.lock
index f49f99ecb..c2b6753ce 100644
--- a/uv.lock
+++ b/uv.lock
@@ -419,14 +419,14 @@ wheels = [
[[package]]
name = "bleach"
-version = "6.3.0"
+version = "6.4.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "webencodings" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/07/18/3c8523962314be6bf4c8989c79ad9531c825210dd13a8669f6b84336e8bd/bleach-6.3.0.tar.gz", hash = "sha256:6f3b91b1c0a02bb9a78b5a454c92506aa0fdf197e1d5e114d2e00c6f64306d22", size = 203533 }
+sdist = { url = "https://files.pythonhosted.org/packages/48/3c/e12ac860709702bd5ebeb9b56a4fe334f1001246ee1b8f2b7ee28912df7d/bleach-6.4.0.tar.gz", hash = "sha256:4202482733d85cedd04e59fcb2f89f4e4c7c385a78d3c3c23c30446843a37452", size = 204857 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/cd/3a/577b549de0cc09d95f11087ee63c739bba856cd3952697eec4c4bb91350a/bleach-6.3.0-py3-none-any.whl", hash = "sha256:fe10ec77c93ddf3d13a73b035abaac7a9f5e436513864ccdad516693213c65d6", size = 164437 },
+ { url = "https://files.pythonhosted.org/packages/58/9d/40b6267367182187139a4000b82a3b287d84d745bccd808e75d916920e9d/bleach-6.4.0-py3-none-any.whl", hash = "sha256:4b6b6a54fff2e69a3dde9d21cc6301220bee3c3cb792187d11403fd795031081", size = 165109 },
]
[package.optional-dependencies]
@@ -629,7 +629,7 @@ wheels = [
[[package]]
name = "chromadb"
-version = "1.1.1"
+version = "1.5.9"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "bcrypt" },
@@ -647,9 +647,9 @@ dependencies = [
{ name = "opentelemetry-sdk" },
{ name = "orjson" },
{ name = "overrides" },
- { name = "posthog" },
{ name = "pybase64" },
{ name = "pydantic" },
+ { name = "pydantic-settings" },
{ name = "pypika" },
{ name = "pyyaml" },
{ name = "rich" },
@@ -660,13 +660,13 @@ dependencies = [
{ name = "typing-extensions" },
{ name = "uvicorn", extra = ["standard"] },
]
-sdist = { url = "https://files.pythonhosted.org/packages/7f/48/11851dddeadad6abe36ee071fedc99b5bdd2c324df3afa8cb952ae02798b/chromadb-1.1.1.tar.gz", hash = "sha256:ebfce0122753e306a76f1e291d4ddaebe5f01b5979b97ae0bc80b1d4024ff223", size = 1338109 }
+sdist = { url = "https://files.pythonhosted.org/packages/92/d1/5e33b26985f0c7046a0be1cee2158ada1748ee700d2545057fde1468d74d/chromadb-1.5.9.tar.gz", hash = "sha256:5c20e62a455c28bacac927f26116a73fd8e1799e0d908be8e8a4f02197a54731", size = 2595635 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/39/59/0d881a9b7eb63d8d2446cf67fcbb53fb8ae34991759d2b6024a067e90a9a/chromadb-1.1.1-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:27fe0e25ef0f83fb09c30355ab084fe6f246808a7ea29e8c19e85cf45785b90d", size = 19175479 },
- { url = "https://files.pythonhosted.org/packages/94/4f/5a9fa317c84c98e70af48f74b00aa25589626c03a0428b4381b2095f3d73/chromadb-1.1.1-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:95aed58869683f12e7dcbf68b039fe5f576dbe9d1b86b8f4d014c9d077ccafd2", size = 18267188 },
- { url = "https://files.pythonhosted.org/packages/45/1a/02defe2f1c8d1daedb084bbe85f5b6083510a3ba192ed57797a3649a4310/chromadb-1.1.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:06776dad41389a00e7d63d936c3a15c179d502becaf99f75745ee11b062c9b6a", size = 18855754 },
- { url = "https://files.pythonhosted.org/packages/5a/0d/80be82717e5dc19839af24558494811b6f2af2b261a8f21c51b872193b09/chromadb-1.1.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bba0096a7f5e975875ead23a91c0d41d977fbd3767f60d3305a011b0ace7afd3", size = 19893681 },
- { url = "https://files.pythonhosted.org/packages/2d/6e/956e62975305a4e31daf6114a73b3b0683a8f36f8d70b20aabd466770edb/chromadb-1.1.1-cp39-abi3-win_amd64.whl", hash = "sha256:a77aa026a73a18181fd89bbbdb86191c9a82fd42aa0b549ff18d8cae56394c8b", size = 19844042 },
+ { url = "https://files.pythonhosted.org/packages/dd/5b/3cced915244f43ed14b53fe9f63a37f05f865064f4e4fe7d9448d3f2a352/chromadb-1.5.9-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:60701011b5e6409647fa40d12c7c5a66b2b0bfcf33a52db2ad53a30a2abc4957", size = 22564540 },
+ { url = "https://files.pythonhosted.org/packages/34/4c/adcef1f4e82a2ef69ccd3711d55fc289193d54c4c0ff7a0292a3631db46f/chromadb-1.5.9-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:814b9c95617377f6501e5757d63dfddb554a283a7739c87b9fa573850174e6f3", size = 21699698 },
+ { url = "https://files.pythonhosted.org/packages/38/4e/937bc4d2e6f8ab9664ec79931fbbd69efff47e513ec2924b071e4b0ff774/chromadb-1.5.9-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9192d111bd662241625867962333d99369a00769a50f8b2f58cb388731274d7e", size = 22680924 },
+ { url = "https://files.pythonhosted.org/packages/e6/ec/0c42039e80b9acc534f67b73b7a42471948042859b3a64867b50a4a77fa3/chromadb-1.5.9-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc09b3df76e5a5cb386aed2715a2eea152e3949f9e1ba93c7119505377749929", size = 23316203 },
+ { url = "https://files.pythonhosted.org/packages/eb/ce/0f7be6e5d0feafa2cda54b12e6542afeea7dea89d2d411e14da90f8abb96/chromadb-1.5.9-cp39-abi3-win_amd64.whl", hash = "sha256:4fd0b560e56761b7f3cb4d5c6205fd5f20814484b4a3e4e9af9038c2b428fc6c", size = 23542454 },
]
[[package]]
@@ -823,41 +823,41 @@ wheels = [
[[package]]
name = "cryptography"
-version = "46.0.7"
+version = "48.0.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cffi", marker = "platform_python_implementation != 'PyPy'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/47/93/ac8f3d5ff04d54bc814e961a43ae5b0b146154c89c61b47bb07557679b18/cryptography-46.0.7.tar.gz", hash = "sha256:e4cfd68c5f3e0bfdad0d38e023239b96a2fe84146481852dffbcca442c245aa5", size = 750652 }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/0b/5d/4a8f770695d73be252331e60e526291e3df0c9b27556a90a6b47bccca4c2/cryptography-46.0.7-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:ea42cbe97209df307fdc3b155f1b6fa2577c0defa8f1f7d3be7d31d189108ad4", size = 7179869 },
- { url = "https://files.pythonhosted.org/packages/5f/45/6d80dc379b0bbc1f9d1e429f42e4cb9e1d319c7a8201beffd967c516ea01/cryptography-46.0.7-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b36a4695e29fe69215d75960b22577197aca3f7a25b9cf9d165dcfe9d80bc325", size = 4275492 },
- { url = "https://files.pythonhosted.org/packages/4a/9a/1765afe9f572e239c3469f2cb429f3ba7b31878c893b246b4b2994ffe2fe/cryptography-46.0.7-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5ad9ef796328c5e3c4ceed237a183f5d41d21150f972455a9d926593a1dcb308", size = 4426670 },
- { url = "https://files.pythonhosted.org/packages/8f/3e/af9246aaf23cd4ee060699adab1e47ced3f5f7e7a8ffdd339f817b446462/cryptography-46.0.7-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:73510b83623e080a2c35c62c15298096e2a5dc8d51c3b4e1740211839d0dea77", size = 4280275 },
- { url = "https://files.pythonhosted.org/packages/0f/54/6bbbfc5efe86f9d71041827b793c24811a017c6ac0fd12883e4caa86b8ed/cryptography-46.0.7-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:cbd5fb06b62bd0721e1170273d3f4d5a277044c47ca27ee257025146c34cbdd1", size = 4928402 },
- { url = "https://files.pythonhosted.org/packages/2d/cf/054b9d8220f81509939599c8bdbc0c408dbd2bdd41688616a20731371fe0/cryptography-46.0.7-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:420b1e4109cc95f0e5700eed79908cef9268265c773d3a66f7af1eef53d409ef", size = 4459985 },
- { url = "https://files.pythonhosted.org/packages/f9/46/4e4e9c6040fb01c7467d47217d2f882daddeb8828f7df800cb806d8a2288/cryptography-46.0.7-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:24402210aa54baae71d99441d15bb5a1919c195398a87b563df84468160a65de", size = 3990652 },
- { url = "https://files.pythonhosted.org/packages/36/5f/313586c3be5a2fbe87e4c9a254207b860155a8e1f3cca99f9910008e7d08/cryptography-46.0.7-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:8a469028a86f12eb7d2fe97162d0634026d92a21f3ae0ac87ed1c4a447886c83", size = 4279805 },
- { url = "https://files.pythonhosted.org/packages/69/33/60dfc4595f334a2082749673386a4d05e4f0cf4df8248e63b2c3437585f2/cryptography-46.0.7-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:9694078c5d44c157ef3162e3bf3946510b857df5a3955458381d1c7cfc143ddb", size = 4892883 },
- { url = "https://files.pythonhosted.org/packages/c7/0b/333ddab4270c4f5b972f980adef4faa66951a4aaf646ca067af597f15563/cryptography-46.0.7-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:42a1e5f98abb6391717978baf9f90dc28a743b7d9be7f0751a6f56a75d14065b", size = 4459756 },
- { url = "https://files.pythonhosted.org/packages/d2/14/633913398b43b75f1234834170947957c6b623d1701ffc7a9600da907e89/cryptography-46.0.7-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:91bbcb08347344f810cbe49065914fe048949648f6bd5c2519f34619142bbe85", size = 4410244 },
- { url = "https://files.pythonhosted.org/packages/10/f2/19ceb3b3dc14009373432af0c13f46aa08e3ce334ec6eff13492e1812ccd/cryptography-46.0.7-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:5d1c02a14ceb9148cc7816249f64f623fbfee39e8c03b3650d842ad3f34d637e", size = 4674868 },
- { url = "https://files.pythonhosted.org/packages/1a/bb/a5c213c19ee94b15dfccc48f363738633a493812687f5567addbcbba9f6f/cryptography-46.0.7-cp311-abi3-win32.whl", hash = "sha256:d23c8ca48e44ee015cd0a54aeccdf9f09004eba9fc96f38c911011d9ff1bd457", size = 3026504 },
- { url = "https://files.pythonhosted.org/packages/2b/02/7788f9fefa1d060ca68717c3901ae7fffa21ee087a90b7f23c7a603c32ae/cryptography-46.0.7-cp311-abi3-win_amd64.whl", hash = "sha256:397655da831414d165029da9bc483bed2fe0e75dde6a1523ec2fe63f3c46046b", size = 3488363 },
- { url = "https://files.pythonhosted.org/packages/a7/7f/cd42fc3614386bc0c12f0cb3c4ae1fc2bbca5c9662dfed031514911d513d/cryptography-46.0.7-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:462ad5cb1c148a22b2e3bcc5ad52504dff325d17daf5df8d88c17dda1f75f2a4", size = 7165618 },
- { url = "https://files.pythonhosted.org/packages/a5/d0/36a49f0262d2319139d2829f773f1b97ef8aef7f97e6e5bd21455e5a8fb5/cryptography-46.0.7-cp38-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:84d4cced91f0f159a7ddacad249cc077e63195c36aac40b4150e7a57e84fffe7", size = 4270628 },
- { url = "https://files.pythonhosted.org/packages/8a/6c/1a42450f464dda6ffbe578a911f773e54dd48c10f9895a23a7e88b3e7db5/cryptography-46.0.7-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:128c5edfe5e5938b86b03941e94fac9ee793a94452ad1365c9fc3f4f62216832", size = 4415405 },
- { url = "https://files.pythonhosted.org/packages/9a/92/4ed714dbe93a066dc1f4b4581a464d2d7dbec9046f7c8b7016f5286329e2/cryptography-46.0.7-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:5e51be372b26ef4ba3de3c167cd3d1022934bc838ae9eaad7e644986d2a3d163", size = 4272715 },
- { url = "https://files.pythonhosted.org/packages/b7/e6/a26b84096eddd51494bba19111f8fffe976f6a09f132706f8f1bf03f51f7/cryptography-46.0.7-cp38-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:cdf1a610ef82abb396451862739e3fc93b071c844399e15b90726ef7470eeaf2", size = 4918400 },
- { url = "https://files.pythonhosted.org/packages/c7/08/ffd537b605568a148543ac3c2b239708ae0bd635064bab41359252ef88ed/cryptography-46.0.7-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:1d25aee46d0c6f1a501adcddb2d2fee4b979381346a78558ed13e50aa8a59067", size = 4450634 },
- { url = "https://files.pythonhosted.org/packages/16/01/0cd51dd86ab5b9befe0d031e276510491976c3a80e9f6e31810cce46c4ad/cryptography-46.0.7-cp38-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:cdfbe22376065ffcf8be74dc9a909f032df19bc58a699456a21712d6e5eabfd0", size = 3985233 },
- { url = "https://files.pythonhosted.org/packages/92/49/819d6ed3a7d9349c2939f81b500a738cb733ab62fbecdbc1e38e83d45e12/cryptography-46.0.7-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:abad9dac36cbf55de6eb49badd4016806b3165d396f64925bf2999bcb67837ba", size = 4271955 },
- { url = "https://files.pythonhosted.org/packages/80/07/ad9b3c56ebb95ed2473d46df0847357e01583f4c52a85754d1a55e29e4d0/cryptography-46.0.7-cp38-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:935ce7e3cfdb53e3536119a542b839bb94ec1ad081013e9ab9b7cfd478b05006", size = 4879888 },
- { url = "https://files.pythonhosted.org/packages/b8/c7/201d3d58f30c4c2bdbe9b03844c291feb77c20511cc3586daf7edc12a47b/cryptography-46.0.7-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:35719dc79d4730d30f1c2b6474bd6acda36ae2dfae1e3c16f2051f215df33ce0", size = 4449961 },
- { url = "https://files.pythonhosted.org/packages/a5/ef/649750cbf96f3033c3c976e112265c33906f8e462291a33d77f90356548c/cryptography-46.0.7-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7bbc6ccf49d05ac8f7d7b5e2e2c33830d4fe2061def88210a126d130d7f71a85", size = 4401696 },
- { url = "https://files.pythonhosted.org/packages/41/52/a8908dcb1a389a459a29008c29966c1d552588d4ae6d43f3a1a4512e0ebe/cryptography-46.0.7-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a1529d614f44b863a7b480c6d000fe93b59acee9c82ffa027cfadc77521a9f5e", size = 4664256 },
- { url = "https://files.pythonhosted.org/packages/4b/fa/f0ab06238e899cc3fb332623f337a7364f36f4bb3f2534c2bb95a35b132c/cryptography-46.0.7-cp38-abi3-win32.whl", hash = "sha256:f247c8c1a1fb45e12586afbb436ef21ff1e80670b2861a90353d9b025583d246", size = 3013001 },
- { url = "https://files.pythonhosted.org/packages/d2/f1/00ce3bde3ca542d1acd8f8cfa38e446840945aa6363f9b74746394b14127/cryptography-46.0.7-cp38-abi3-win_amd64.whl", hash = "sha256:506c4ff91eff4f82bdac7633318a526b1d1309fc07ca76a3ad182cb5b686d6d3", size = 3472985 },
+sdist = { url = "https://files.pythonhosted.org/packages/12/45/870e7f4bef50e5f53b9f51d4428aee5290eedf58ba443f16b1ebb7ab8e66/cryptography-48.0.1.tar.gz", hash = "sha256:266f4ee051abb2f725b74ef8072b521ce1feacf685a3364fa6a6b45548db791a", size = 832989 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1b/bc/ee4137cbbe105652c0ee4252792b78fc8e7afa4b8e61d9d5dc05a7f45731/cryptography-48.0.1-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:3e4a1a3232eef2e6c732827d5722db29a0cc8b27af2a4d865b094cf954be9ca1", size = 8008324 },
+ { url = "https://files.pythonhosted.org/packages/d5/85/6379d42181bfc713094f081360fc5784d6c816b599d45e7f082502d173ce/cryptography-48.0.1-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:32143b24adb918f078134e1e230f1eb8cc04886b92c28b5f0041aaf3e5699225", size = 4696243 },
+ { url = "https://files.pythonhosted.org/packages/9c/87/c85d147b53323c7eb4d850920c8901377323c2a0ff8d79c262d4fee89aa2/cryptography-48.0.1-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f0d27a5696721ef7a672b8c810f6aded391058e0b9486e63e6d93baf765da691", size = 4713235 },
+ { url = "https://files.pythonhosted.org/packages/79/58/67cbf8cf1ee7c54b439ca07bbecf8362c07afc11a3724fea70f745784add/cryptography-48.0.1-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:eb86ce1af36fe65041b6db9a8bb064ee621a7e5fded0f80d475ec243477cd242", size = 4702323 },
+ { url = "https://files.pythonhosted.org/packages/89/c6/24266ac10c47f6cd2a865f4446062b466da1d1f10b27189eac00e61bf0c9/cryptography-48.0.1-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:b024e784ad6c077ee0147b35ea9cbfc1e34e1fd4c1dcca214c2794d73a12df08", size = 5300085 },
+ { url = "https://files.pythonhosted.org/packages/d2/bb/cc4b78784f97efc8c5874c2a9743708d172be6663024b34a0467885ae0c8/cryptography-48.0.1-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:3752f2dbc8f07a30aad2932c986cea495b03bb554887828225da104f732852b6", size = 4746137 },
+ { url = "https://files.pythonhosted.org/packages/1f/52/0c44de3f5267f8fbe8e835138017522a333436166e406f0db9b9e6e3033f/cryptography-48.0.1-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:bd81490cd5801d755cf97bb68ac191f14b708470b1c7cf4580f669b9c9264cd8", size = 4333867 },
+ { url = "https://files.pythonhosted.org/packages/9a/2e/772d7adbfa931537bc401640b7cac9976bff689bda187833e5d63b428e49/cryptography-48.0.1-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:66fd0771e7b9c6dcd44cf1120690d2338d16d72795cf40cae2786a39eba65429", size = 4701805 },
+ { url = "https://files.pythonhosted.org/packages/f8/a3/b06844f303873493c963caf581c04df31c7035e0c1b0f02c4814d319ec80/cryptography-48.0.1-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:3fd2ca57062b241c856670b073487d2e86c4637937ca5601e48f97bf8e11fc8f", size = 5258461 },
+ { url = "https://files.pythonhosted.org/packages/9f/13/8b765e2e12b07c74941caadb9d1c8fdc006c4dfbf2b8f2d610519758954d/cryptography-48.0.1-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:0ee6ea481db1ab889cba043ec1eda17bb9c1ea79db6722f779c3667f9f70322f", size = 4745488 },
+ { url = "https://files.pythonhosted.org/packages/2e/aa/48972bce55049b32a94f4907eda4d75fa385aad8a39506cc2fc72196ecf0/cryptography-48.0.1-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:f2ceef93cb096aa3c4cc4b5c94ca6131f9196d28c64d6111533402a9b2054d41", size = 4830256 },
+ { url = "https://files.pythonhosted.org/packages/47/a2/e5079a032fb85cf6005046ca92bbd78b0c82dad2b5751ab8c311659da06f/cryptography-48.0.1-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9bd3f92d76217892b15df84ca256c2c113d386fdda7a7d8691aeeced976507c6", size = 4979117 },
+ { url = "https://files.pythonhosted.org/packages/b7/a0/8f50cae9c74e718ed769d63ed5c74bd0ea830c9550a74629cebd1b9c7bc7/cryptography-48.0.1-cp311-abi3-win32.whl", hash = "sha256:b9a32b876490d66c8bcc9963ef220199569748434ab01a9d6aaeabf88e7f5158", size = 3304154 },
+ { url = "https://files.pythonhosted.org/packages/c5/69/0572c77dbace6fef72f33755bd52ea399c71367250d366237f8691826b9e/cryptography-48.0.1-cp311-abi3-win_amd64.whl", hash = "sha256:39489bfca54c7a1f6b297efcd8bc608ab92d16c4ca631b0cad4da46724588b24", size = 3817138 },
+ { url = "https://files.pythonhosted.org/packages/ca/6c/00fa2a95997164c8b2072ce327c23d4ab20809ccc323ea5fab91e53a4bba/cryptography-48.0.1-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:4fdc69f8e4316bcf0c8c8ec1f26f285d12e8142d88d96c876a59a03be3f6ae67", size = 7987408 },
+ { url = "https://files.pythonhosted.org/packages/b0/d9/45f309a7e4e5f3f8f121d6d3be9e94024a7726ec598d6e08ae04edb2f04d/cryptography-48.0.1-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:48fe40804d4caa2288f24e70ca8c64c42dd826da0ad7e4f1b41b2128d679e6c8", size = 4690196 },
+ { url = "https://files.pythonhosted.org/packages/5f/9f/a1bc8bcc798811b8527eb374bbccf30a3f3e806829d967118222bf1125eb/cryptography-48.0.1-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:86be3b1b0b6bf09482fb50a979c508d2950ed95f5621ec77f4e385962006b83a", size = 4696782 },
+ { url = "https://files.pythonhosted.org/packages/66/c2/81a4fb4e4373c500bb526bc337ac5719dd31dd15b970b84a238168c6aa08/cryptography-48.0.1-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:4ab0a343c807bbcd90c971cd1ecf072937cd01847a9e002bef88fb47ac6be577", size = 4696618 },
+ { url = "https://files.pythonhosted.org/packages/e5/0b/aa68b221dde92d09cb29a024ede17550ee21e77a404e59fc093c82bb51e1/cryptography-48.0.1-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:9621de99d2da096006b629979efd8ae7eb2d8b822488d0c89ee4000c306c59b1", size = 5289970 },
+ { url = "https://files.pythonhosted.org/packages/78/13/fba657f958d2af66ea959a4ba01212632089249d34af1ae48054136344d7/cryptography-48.0.1-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:88c852a0ae366e262e5a1744b685e6a433dc8788dd2a277e418bf4904203609d", size = 4731873 },
+ { url = "https://files.pythonhosted.org/packages/4c/4c/9a964756d24a26b3e34dfcb16f961b89838786e6700b635b0d1e3adff4b6/cryptography-48.0.1-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:43c5835e2cb98c8733d86f57d6fc879b613f5c3478607281c3e36daffc6dd8a6", size = 4330804 },
+ { url = "https://files.pythonhosted.org/packages/4b/0f/a10f3a6eb12950a10e3a874070283aa2dd5875b2bfd15fad8a3e17b3f13e/cryptography-48.0.1-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:fe0180af5bf9236518a087e35bf2d9a347d5f5f51e63c579d683ddff424e3d46", size = 4696217 },
+ { url = "https://files.pythonhosted.org/packages/f3/6f/5cd12f951165ea73ef85266775d97e4c763b2474ccfd816dd69d3a18d6f8/cryptography-48.0.1-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:b7a2d1a937a738a881737cec135a38bb61470589b17515b9f73f571d0ae10401", size = 5245252 },
+ { url = "https://files.pythonhosted.org/packages/68/ab/8aaa12e4516ec4464033ab79b6f3b592bd5a92102467c4ace8a0d970203f/cryptography-48.0.1-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:b74ca3b8e5ecdd833bf6a002ca41b4793bb27fb8f1c06ffaf2643c9e9140e31b", size = 4731388 },
+ { url = "https://files.pythonhosted.org/packages/1b/24/50027ea4dca85ec1f40688f3c24fb32ccacd520583c9592c3cc95628e6fb/cryptography-48.0.1-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:2c37f2461406063b417837f5f3daab668652acd82423efcd7f0a9f04be972de1", size = 4824186 },
+ { url = "https://files.pythonhosted.org/packages/52/41/04cb5eb17085ade6f50cc611fb657df6a0f5885350de8764ece89c050197/cryptography-48.0.1-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:86fe77abb1bd87afb251d4d02ada7ecf53a32cee9b67d976abb2e45a13297475", size = 4964539 },
+ { url = "https://files.pythonhosted.org/packages/36/bf/ed70785c496e89d7e73b7cda2d21f2447fd6d4e821714b8d04ff217fed92/cryptography-48.0.1-cp39-abi3-win32.whl", hash = "sha256:6b2c0c3e6ccf3ade7750f836ef3ee36eea250cc467d45c256895573ac08cc6f1", size = 3282307 },
+ { url = "https://files.pythonhosted.org/packages/b3/ff/371ea7d252656ee1eb6d83eeeef3d1d0c6baf1d6497687d081ea03814670/cryptography-48.0.1-cp39-abi3-win_amd64.whl", hash = "sha256:9a49ca6c81417f6a5edb50375a60cccdd70fa0a91a5211829dbea74eba94d2ac", size = 3793408 },
]
[[package]]
@@ -2352,14 +2352,14 @@ wheels = [
[[package]]
name = "joserfc"
-version = "1.6.4"
+version = "1.6.8"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cryptography" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/de/c6/de8fdbdfa75c8ca04fead38a82d573df8a82906e984c349d58665f459558/joserfc-1.6.4.tar.gz", hash = "sha256:34ce5f499bfcc5e9ad4cc75077f9278ab3227b71da9aaf28f9ab705f8a560d3c", size = 231866 }
+sdist = { url = "https://files.pythonhosted.org/packages/5d/ac/d4fd5b30f82900eac60d765f179f0ba005825ac462cc8ced6e13ec685ab3/joserfc-1.6.8.tar.gz", hash = "sha256:878620c553a6ebdd76ccdc356782fee3f735f21a356d079a546b42a4670ace5f", size = 232930 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/b6/f7/210b27752e972edb36d239315b08d3eb6b14824cc4a590da2337d195260b/joserfc-1.6.4-py3-none-any.whl", hash = "sha256:3e4a22b509b41908989237a045e25c8308d5fd47ab96bdae2dd8057c6451003a", size = 70464 },
+ { url = "https://files.pythonhosted.org/packages/98/8c/5cdce2cf3ce8155849baf9a5e2ce77e89dc87ec3bdb38259e5d85fbc45bd/joserfc-1.6.8-py3-none-any.whl", hash = "sha256:22fb31a69094a5e6f44632002a9df2c30c941fc6c8ce1b037e92c03de954cf9f", size = 70927 },
]
[[package]]
@@ -3167,7 +3167,7 @@ wheels = [
[[package]]
name = "mlflow"
-version = "3.11.1"
+version = "3.14.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp" },
@@ -3191,14 +3191,14 @@ dependencies = [
{ name = "sqlalchemy" },
{ name = "waitress", marker = "sys_platform == 'win32'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/e9/34/e328c073cd32c186fb242a957e5bade82433c06bc45b7d1695bf4d02f166/mlflow-3.11.1.tar.gz", hash = "sha256:84e54c4be91b5b2a19039a2673fe688b1d7307ceddacc08af51f8df05b19ee56", size = 9797469 }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/0b/3404a057daceffe9ce18cd08868648a1e9b817270177bdf8a764576b988b/mlflow-3.14.0.tar.gz", hash = "sha256:5a1f818fa003035c724162096ce3ded7bc7bc47a1cae595df6173961983f4718", size = 11792369 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/2a/62/96826c340354638dfedcbdbcd35d67754566bd45f6592300e0c215c80e30/mlflow-3.11.1-py3-none-any.whl", hash = "sha256:8f6bf1238ac04f97664c229dd480380c5c254a78bdb3c0e433e3a0397508b1af", size = 10479141 },
+ { url = "https://files.pythonhosted.org/packages/de/b9/76dcdef7f7f856b36f18cfcd752c2717d9847812a0aaa36d50a7baed569d/mlflow-3.14.0-py3-none-any.whl", hash = "sha256:dbf77f7cdb5b5c0ec59b4671c61730b1b914b4dff7a2892e267a547cb5454f56", size = 12564161 },
]
[[package]]
name = "mlflow-skinny"
-version = "3.11.1"
+version = "3.14.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cachetools" },
@@ -3218,17 +3218,18 @@ dependencies = [
{ name = "pyyaml" },
{ name = "requests" },
{ name = "sqlparse" },
+ { name = "starlette" },
{ name = "typing-extensions" },
{ name = "uvicorn" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/40/77/fe2027ddad9e52ed1ac360fbc262169e6366f6678632e350cbd0d901bb9b/mlflow_skinny-3.11.1.tar.gz", hash = "sha256:86ce63491349f6713afc8a4ef0bf77a8314d0e79e03753cb150d6c860a0b0475", size = 2642799 }
+sdist = { url = "https://files.pythonhosted.org/packages/e8/4f/a054cd8860590e4e942aee1aab3c94307878159f945fa844acc9ea787721/mlflow_skinny-3.14.0.tar.gz", hash = "sha256:e50f4506422c7737157ae6643c165122af7898345f2e828fa93c4f10128653cf", size = 2901772 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/d1/a7/e61ec397b34dc3c9e91572f45e41617f429d5c524d38a4e1aa2316ee1b5e/mlflow_skinny-3.11.1-py3-none-any.whl", hash = "sha256:82ffd5f6980320b4ac19f741e7a754faa1d01707e632b002ea68e04fd25a0535", size = 3171551 },
+ { url = "https://files.pythonhosted.org/packages/58/e7/b80f76ce689b9d6f21cdb84abb2b02148a1149e63a6428dd2c629cefd061/mlflow_skinny-3.14.0-py3-none-any.whl", hash = "sha256:a4880e086365871ef9d78e727a34ea5fb1ce615689579998d48e8c65ee1665a9", size = 3462788 },
]
[[package]]
name = "mlflow-tracing"
-version = "3.11.1"
+version = "3.14.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cachetools" },
@@ -3240,9 +3241,9 @@ dependencies = [
{ name = "protobuf" },
{ name = "pydantic" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/1b/77/73af163432f3c66e2d213045250972e504a6683c76f63dd1abfba441a16a/mlflow_tracing-3.11.1.tar.gz", hash = "sha256:cb63cee16385d081467ec5bee4807fe1af59ddfdf04be4c79e7a7813b1002193", size = 1314550 }
+sdist = { url = "https://files.pythonhosted.org/packages/04/34/ff5e72919b4eec8fe65e6fc843978a1a512194e6fafbd1761deca48269ad/mlflow_tracing-3.14.0.tar.gz", hash = "sha256:c2f701e001d35964f23fbbdfdda36c818a76c157b912ae83781199fd714be09a", size = 1429017 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/62/ab/d980c84e7df4224ab8db2457afbe135b430f371ca081a37cf89f8ef18ca1/mlflow_tracing-3.11.1-py3-none-any.whl", hash = "sha256:fa82df64dacf8293b714ae666440fe7c1902c6470c024df389bb91e9de3106d9", size = 1575790 },
+ { url = "https://files.pythonhosted.org/packages/5f/4a/4658a9e514c8f079e40b608661844b9beb21c7530e6ee1e7f830cf81541e/mlflow_tracing-3.14.0-py3-none-any.whl", hash = "sha256:854488dd18068f15e2a56f1cc7b8868c611d09ea39068d0a691a3f07e0048cae", size = 1703863 },
]
[[package]]
@@ -3359,19 +3360,21 @@ wheels = [
[[package]]
name = "msgpack"
-version = "1.1.2"
+version = "1.2.1"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/4d/f2/bfb55a6236ed8725a96b0aa3acbd0ec17588e6a2c3b62a93eb513ed8783f/msgpack-1.1.2.tar.gz", hash = "sha256:3b60763c1373dd60f398488069bcdc703cd08a711477b5d480eecc9f9626f47e", size = 173581 }
+sdist = { url = "https://files.pythonhosted.org/packages/31/f9/c0a1c127f9049db9155afc316952ea571720dd01833ff5e4d7e8e6352dbb/msgpack-1.2.1.tar.gz", hash = "sha256:04c721c2c7448767e9e3f2520a475663d8ee0f09c31890f6d2bd70fd636a9647", size = 183960 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/ad/bd/8b0d01c756203fbab65d265859749860682ccd2a59594609aeec3a144efa/msgpack-1.1.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:70a0dff9d1f8da25179ffcf880e10cf1aad55fdb63cd59c9a49a1b82290062aa", size = 81939 },
- { url = "https://files.pythonhosted.org/packages/34/68/ba4f155f793a74c1483d4bdef136e1023f7bcba557f0db4ef3db3c665cf1/msgpack-1.1.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:446abdd8b94b55c800ac34b102dffd2f6aa0ce643c55dfc017ad89347db3dbdb", size = 85064 },
- { url = "https://files.pythonhosted.org/packages/f2/60/a064b0345fc36c4c3d2c743c82d9100c40388d77f0b48b2f04d6041dbec1/msgpack-1.1.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c63eea553c69ab05b6747901b97d620bb2a690633c77f23feb0c6a947a8a7b8f", size = 417131 },
- { url = "https://files.pythonhosted.org/packages/65/92/a5100f7185a800a5d29f8d14041f61475b9de465ffcc0f3b9fba606e4505/msgpack-1.1.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:372839311ccf6bdaf39b00b61288e0557916c3729529b301c52c2d88842add42", size = 427556 },
- { url = "https://files.pythonhosted.org/packages/f5/87/ffe21d1bf7d9991354ad93949286f643b2bb6ddbeab66373922b44c3b8cc/msgpack-1.1.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2929af52106ca73fcb28576218476ffbb531a036c2adbcf54a3664de124303e9", size = 404920 },
- { url = "https://files.pythonhosted.org/packages/ff/41/8543ed2b8604f7c0d89ce066f42007faac1eaa7d79a81555f206a5cdb889/msgpack-1.1.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:be52a8fc79e45b0364210eef5234a7cf8d330836d0a64dfbb878efa903d84620", size = 415013 },
- { url = "https://files.pythonhosted.org/packages/41/0d/2ddfaa8b7e1cee6c490d46cb0a39742b19e2481600a7a0e96537e9c22f43/msgpack-1.1.2-cp312-cp312-win32.whl", hash = "sha256:1fff3d825d7859ac888b0fbda39a42d59193543920eda9d9bea44d958a878029", size = 65096 },
- { url = "https://files.pythonhosted.org/packages/8c/ec/d431eb7941fb55a31dd6ca3404d41fbb52d99172df2e7707754488390910/msgpack-1.1.2-cp312-cp312-win_amd64.whl", hash = "sha256:1de460f0403172cff81169a30b9a92b260cb809c4cb7e2fc79ae8d0510c78b6b", size = 72708 },
- { url = "https://files.pythonhosted.org/packages/c5/31/5b1a1f70eb0e87d1678e9624908f86317787b536060641d6798e3cf70ace/msgpack-1.1.2-cp312-cp312-win_arm64.whl", hash = "sha256:be5980f3ee0e6bd44f3a9e9dea01054f175b50c3e6cdb692bc9424c0bbb8bf69", size = 64119 },
+ { url = "https://files.pythonhosted.org/packages/bc/dd/9e8cbd8f5582ca4b590336f2b91ee5662f6a6ca562b565abaf696a0f81ff/msgpack-1.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2ef59c659f289eddf8aa6623823f19fa2f40a4029266889eac7a2505dd210c35", size = 83531 },
+ { url = "https://files.pythonhosted.org/packages/50/2e/ebdb85a8da151397a2790363676b7ed7c125924fe618e4c6d8befb0cc62c/msgpack-1.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d3567748a5107cb40cdf66a275430c2f87c07777698f4bfd25c35f44d533258c", size = 82657 },
+ { url = "https://files.pythonhosted.org/packages/26/aa/753ad8b007b464e1d8aa0c8e650b9c5f4f725e658fc5ac8a7635c55b7f6e/msgpack-1.2.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:60926b75d00c8e816ef98f3034f484a8bc64242d66839cef4cf7e503142316a0", size = 410634 },
+ { url = "https://files.pythonhosted.org/packages/6a/fd/6adabd4f6d5e686f97dd02ce7fce3fe4cf672cbac36b8f67ff4040e8ad8b/msgpack-1.2.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:020e881a764b20d8d7ca1a54fc01b8175519d108e3c3f194fddc200bda95951a", size = 419989 },
+ { url = "https://files.pythonhosted.org/packages/5a/cc/85039b7b0eb168aaad7383a23c97e291a11f08351cb45a606ce865e4e3f1/msgpack-1.2.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4202c74688ca06591f78cb18988228bd4cca2cc75d57b60008372892d2f1e6e6", size = 377544 },
+ { url = "https://files.pythonhosted.org/packages/ed/bf/35963899493b32030c85fc513b723ae66144ac70c11ebc52e889e16e3d99/msgpack-1.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8b267ce94efb76fbd1b3373511420074ee3187f0f7811bf394531de13294735a", size = 400842 },
+ { url = "https://files.pythonhosted.org/packages/a6/df/8e2ac970c8f99264cd9997d1c73df5466bc19da3301d7dc5500862a9b089/msgpack-1.2.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e4f1d0f8f98ade9634e01fb704a408f9336c0a8f1117b369f5db83dc7551d8b1", size = 374108 },
+ { url = "https://files.pythonhosted.org/packages/17/dd/fa8bd265110dfa51c20cb529f9e6d240a16fafe7e645004c6af2d01353ba/msgpack-1.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f02cf17a6ca1abe29b5f980644f7551f94d71f2011509b26d8625ce038f0df64", size = 414939 },
+ { url = "https://files.pythonhosted.org/packages/2e/b9/8377a5ad8953fc0437c70cc98d9ae29f27fe5ac5109fbec0812085865735/msgpack-1.2.1-cp312-cp312-win32.whl", hash = "sha256:0c0d9802354507bcba62af19c17918e3eb437cc25e6f50657d511b5856a77aac", size = 64504 },
+ { url = "https://files.pythonhosted.org/packages/57/7f/ce1e377df7e62461fefd9eb23bfb93a4a523f40a517b377b8f844d836828/msgpack-1.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:5c24aa15d5963051e1a5c62b12c50cd705992502b5ec1f3bece6046f33c9fc24", size = 71421 },
+ { url = "https://files.pythonhosted.org/packages/8f/32/ebfe84c9929f08f188d56c7a2fd913406a9ddad76a634697c1c43b8112e6/msgpack-1.2.1-cp312-cp312-win_arm64.whl", hash = "sha256:4227224aaec8f7fbcbfbd4272319347b2bb4030366502600f8c45588c5187b07", size = 64775 },
]
[[package]]
@@ -3577,17 +3580,18 @@ wheels = [
[[package]]
name = "nltk"
-version = "3.9.4"
+version = "3.10.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "click" },
+ { name = "defusedxml" },
{ name = "joblib" },
{ name = "regex" },
{ name = "tqdm" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/74/a1/b3b4adf15585a5bc4c357adde150c01ebeeb642173ded4d871e89468767c/nltk-3.9.4.tar.gz", hash = "sha256:ed03bc098a40481310320808b2db712d95d13ca65b27372f8a403949c8b523d0", size = 2946864 }
+sdist = { url = "https://files.pythonhosted.org/packages/96/02/df4f105b28a7c16b0e41423bc09cf0f1b8a305df4ef0b10ca74a2e4c648c/nltk-3.10.0.tar.gz", hash = "sha256:4fbac1d98203cbcd1b5d94a2877fb822300072d80604a5e7fae49d2c5f84e8c1", size = 3089244 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/9d/91/04e965f8e717ba0ab4bdca5c112deeab11c9e750d94c4d4602f050295d39/nltk-3.9.4-py3-none-any.whl", hash = "sha256:f2fa301c3a12718ce4a0e9305c5675299da5ad9e26068218b69d692fda84828f", size = 1552087 },
+ { url = "https://files.pythonhosted.org/packages/6e/89/a0b0f35e2820d6a99d75ea1c11977ee6d5c9e6658eceb45b0c7620881faa/nltk-3.10.0-py3-none-any.whl", hash = "sha256:54ff84d4916d3ef127e8953bee0023f6a6b320b75d634a19e06ef056d3d244bf", size = 1716144 },
]
[[package]]
@@ -4740,16 +4744,16 @@ wheels = [
[[package]]
name = "pydantic-settings"
-version = "2.14.0"
+version = "2.14.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pydantic" },
{ name = "python-dotenv" },
{ name = "typing-inspection" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/42/98/c8345dccdc31de4228c039a98f6467a941e39558da41c1744fbe29fa5666/pydantic_settings-2.14.0.tar.gz", hash = "sha256:24285fd4b0e0c06507dd9fdfd331ee23794305352aaec8fc4eb92d4047aeb67d", size = 235709 }
+sdist = { url = "https://files.pythonhosted.org/packages/5c/b5/8f48e906c3e0205276e8bd8cb7512217a87b2685304d64be27cad5b3019f/pydantic_settings-2.14.2.tar.gz", hash = "sha256:c19dd64b19097f1de80184f0cc7b0272a13ae6e170cbf240a3e27e381ed14a5f", size = 237700 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/01/dd/bebff3040138f00ae8a102d426b27349b9a49acc310fcae7f92112d867e3/pydantic_settings-2.14.0-py3-none-any.whl", hash = "sha256:fc8d5d692eb7092e43c8647c1c35a3ecd00e040fcf02ed86f4cb5458ca62182e", size = 60940 },
+ { url = "https://files.pythonhosted.org/packages/77/c1/6e422f34e569cf8e18df68d1939c81c099d2b61e4f7d9621c8a77560799c/pydantic_settings-2.14.2-py3-none-any.whl", hash = "sha256:a20c97b37910b6550d5ea50fbcc2d4187defe58cd57070b73863d069419c9440", size = 61715 },
]
[[package]]
@@ -4865,11 +4869,11 @@ wheels = [
[[package]]
name = "pypdf"
-version = "6.10.2"
+version = "6.13.3"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/7b/3f/9f2167401c2e94833ca3b69535bad89e533b5de75fefe4197a2c224baec2/pypdf-6.10.2.tar.gz", hash = "sha256:7d09ce108eff6bf67465d461b6ef352dcb8d84f7a91befc02f904455c6eea11d", size = 5315679 }
+sdist = { url = "https://files.pythonhosted.org/packages/17/18/9947cc201af9ccf76720fd3347bf4f70eb882ce3fcf4cb05f7443e4cf871/pypdf-6.13.3.tar.gz", hash = "sha256:f3cb822769725f1bac658c406cfc9460399043f3750c2d3e4650e0a85eacabd7", size = 6484063 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/0c/d6/1d5c60cc17bbdf37c1552d9c03862fc6d32c5836732a0415b2d637edc2d0/pypdf-6.10.2-py3-none-any.whl", hash = "sha256:aa53be9826655b51c96741e5d7983ca224d898ac0a77896e64636810517624aa", size = 336308 },
+ { url = "https://files.pythonhosted.org/packages/94/56/2967e621598987905fb8cdfadd8f8de6b5c68c9351f0523c4df8409f28f1/pypdf-6.13.3-py3-none-any.whl", hash = "sha256:c6e3f86afb625791510b02ad5480e94b63970bb957df75d44657c282ecc52224", size = 347288 },
]
[[package]]
@@ -5719,7 +5723,7 @@ dev = [
[[package]]
name = "sie-admin"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "packages/sie_admin" }
dependencies = [
{ name = "httpx" },
@@ -5752,7 +5756,7 @@ requires-dist = [
[[package]]
name = "sie-bench"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "packages/sie_bench" }
dependencies = [
{ name = "aiohttp" },
@@ -5837,7 +5841,7 @@ requires-dist = [
[[package]]
name = "sie-chroma"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "integrations/sie_chroma" }
dependencies = [
{ name = "chromadb" },
@@ -5852,7 +5856,7 @@ dev = [
[package.metadata]
requires-dist = [
- { name = "chromadb", specifier = ">=0.4" },
+ { name = "chromadb", specifier = ">=1.5.9" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" },
{ name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.24" },
{ name = "sie-sdk", editable = "packages/sie_sdk" },
@@ -5909,7 +5913,7 @@ dev = [
[[package]]
name = "sie-crewai"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "integrations/sie_crewai" }
dependencies = [
{ name = "crewai" },
@@ -5934,7 +5938,7 @@ requires-dist = [
[[package]]
name = "sie-dspy"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "integrations/sie_dspy" }
dependencies = [
{ name = "dspy" },
@@ -5959,7 +5963,7 @@ requires-dist = [
[[package]]
name = "sie-haystack"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "integrations/sie_haystack" }
dependencies = [
{ name = "haystack-ai" },
@@ -5977,7 +5981,7 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "chroma-haystack", marker = "extra == 'dev'", specifier = ">=2.0.0" },
- { name = "chromadb", marker = "extra == 'dev'", specifier = ">=0.4.0" },
+ { name = "chromadb", marker = "extra == 'dev'", specifier = ">=1.5.9" },
{ name = "haystack-ai", specifier = ">=2.0.0" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" },
{ name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.23.0" },
@@ -5986,7 +5990,7 @@ requires-dist = [
[[package]]
name = "sie-lancedb"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "integrations/sie_lancedb" }
dependencies = [
{ name = "lancedb" },
@@ -6013,7 +6017,7 @@ requires-dist = [
[[package]]
name = "sie-langchain"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "integrations/sie_langchain" }
dependencies = [
{ name = "langchain-core" },
@@ -6030,7 +6034,7 @@ dev = [
[package.metadata]
requires-dist = [
- { name = "chromadb", marker = "extra == 'dev'", specifier = ">=0.4" },
+ { name = "chromadb", marker = "extra == 'dev'", specifier = ">=1.5.9" },
{ name = "langchain-chroma", marker = "extra == 'dev'", specifier = ">=0.1" },
{ name = "langchain-core", specifier = ">=0.2.0" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" },
@@ -6040,7 +6044,7 @@ requires-dist = [
[[package]]
name = "sie-llamaindex"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "integrations/sie_llamaindex" }
dependencies = [
{ name = "llama-index-core" },
@@ -6057,7 +6061,7 @@ dev = [
[package.metadata]
requires-dist = [
- { name = "chromadb", marker = "extra == 'dev'", specifier = ">=0.5" },
+ { name = "chromadb", marker = "extra == 'dev'", specifier = ">=1.5.9" },
{ name = "llama-index-core", specifier = ">=0.11" },
{ name = "llama-index-vector-stores-chroma", marker = "extra == 'dev'", specifier = ">=0.2" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" },
@@ -6093,7 +6097,7 @@ requires-dist = [
{ name = "pillow", specifier = ">=12.2.0" },
{ name = "pypdfium2", specifier = ">=5.6.0" },
{ name = "sie-sdk", editable = "packages/sie_sdk" },
- { name = "starlette", specifier = ">=0.40" },
+ { name = "starlette", specifier = ">=1.3.1" },
{ name = "typer", specifier = ">=0.14,<1" },
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32,<1" },
]
@@ -6106,7 +6110,7 @@ dev = [
[[package]]
name = "sie-qdrant"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "integrations/sie_qdrant" }
dependencies = [
{ name = "qdrant-client" },
@@ -6129,7 +6133,7 @@ requires-dist = [
[[package]]
name = "sie-sdk"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "packages/sie_sdk" }
dependencies = [
{ name = "aiohttp" },
@@ -6172,7 +6176,7 @@ requires-dist = [
{ name = "huggingface-hub", extras = ["hf-transfer"], marker = "extra == 'storage'", specifier = ">=0.26" },
{ name = "langchain-core", marker = "extra == 'langchain'", specifier = ">=0.3,<1" },
{ name = "llama-index-core", marker = "extra == 'llamaindex'", specifier = ">=0.12,<1" },
- { name = "msgpack", specifier = ">=1.1,<2" },
+ { name = "msgpack", specifier = ">=1.2.1,<2" },
{ name = "msgpack-numpy", specifier = ">=0.4,<1" },
{ name = "numpy", specifier = ">=2,<3" },
{ name = "pillow", specifier = ">=12.2.0" },
@@ -6182,7 +6186,7 @@ requires-dist = [
[[package]]
name = "sie-server"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "packages/sie_server" }
dependencies = [
{ name = "blake3" },
@@ -6207,6 +6211,7 @@ dependencies = [
{ name = "opentelemetry-sdk" },
{ name = "orjson" },
{ name = "packaging" },
+ { name = "peft" },
{ name = "pillow" },
{ name = "prometheus-client" },
{ name = "pydantic" },
@@ -6260,7 +6265,7 @@ requires-dist = [
{ name = "glirel", specifier = ">=1.0,<2" },
{ name = "httpx", specifier = ">=0.28.1" },
{ name = "loguru", specifier = ">=0.7,<1" },
- { name = "msgpack", specifier = ">=1.1,<2" },
+ { name = "msgpack", specifier = ">=1.2.1,<2" },
{ name = "msgpack-numpy", specifier = ">=0.4,<1" },
{ name = "msgspec", specifier = ">=0.20.0" },
{ name = "numpy", specifier = ">=2,<3" },
@@ -6273,6 +6278,7 @@ requires-dist = [
{ name = "opentelemetry-sdk", specifier = ">=1.28,<2" },
{ name = "orjson", specifier = ">=3.10,<4" },
{ name = "packaging", specifier = ">=24,<25" },
+ { name = "peft", specifier = ">=0.19,<1" },
{ name = "pillow", specifier = ">=12.2.0" },
{ name = "prometheus-client", specifier = ">=0.21,<1" },
{ name = "pydantic", specifier = ">=2.9,<3" },
@@ -6318,7 +6324,7 @@ requires-dist = [
[[package]]
name = "sie-weaviate"
-version = "0.6.16"
+version = "0.6.17"
source = { editable = "integrations/sie_weaviate" }
dependencies = [
{ name = "sie-sdk" },
@@ -6512,15 +6518,15 @@ wheels = [
[[package]]
name = "starlette"
-version = "1.0.1"
+version = "1.3.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
{ name = "typing-extensions" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/08/a3/84e821cc54b4ab50ae6dbc6ac3800a651b65ec35f045cc73785380654057/starlette-1.0.1.tar.gz", hash = "sha256:512399c5f1de7fac99c88572212ded9ddeddef2fb32afa82d724000e88b38f4f", size = 2659596 }
+sdist = { url = "https://files.pythonhosted.org/packages/eb/e3/7c1dc7381d9f8ab7d854328ebfa884e62cb3f3d8549ddfd37c7814f42afa/starlette-1.3.1.tar.gz", hash = "sha256:05d0213193f2fbaae60e2ecb593b4add4262ad4e46536b54abe36f11a71724e0", size = 2703240 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/ec/e1/b2df4bc09a1e51ff664c1e17018a4274b42e5e9352e4a478ea540512dc88/starlette-1.0.1-py3-none-any.whl", hash = "sha256:7c0e69b2ee1c848bd54669d908500117a3ee13de603a21427e5c6fc1adf98dcd", size = 72802 },
+ { url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632 },
]
[[package]]
@@ -6903,19 +6909,19 @@ wheels = [
[[package]]
name = "tornado"
-version = "6.5.5"
+version = "6.5.7"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/f8/f1/3173dfa4a18db4a9b03e5d55325559dab51ee653763bb8745a75af491286/tornado-6.5.5.tar.gz", hash = "sha256:192b8f3ea91bd7f1f50c06955416ed76c6b72f96779b962f07f911b91e8d30e9", size = 516006 }
+sdist = { url = "https://files.pythonhosted.org/packages/64/24/95ec527ad67b76d59299e5465b3935d05e4294b7e0290a3924b7487df30b/tornado-6.5.7.tar.gz", hash = "sha256:66c513a76cda70d53907bc27cf1447557699c2e95aa48ba27a442ff61c3ddfc2", size = 519252 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/59/8c/77f5097695f4dd8255ecbd08b2a1ed8ba8b953d337804dd7080f199e12bf/tornado-6.5.5-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:487dc9cc380e29f58c7ab88f9e27cdeef04b2140862e5076a66fb6bb68bb1bfa", size = 445983 },
- { url = "https://files.pythonhosted.org/packages/ab/5e/7625b76cd10f98f1516c36ce0346de62061156352353ef2da44e5c21523c/tornado-6.5.5-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:65a7f1d46d4bb41df1ac99f5fcb685fb25c7e61613742d5108b010975a9a6521", size = 444246 },
- { url = "https://files.pythonhosted.org/packages/b2/04/7b5705d5b3c0fab088f434f9c83edac1573830ca49ccf29fb83bf7178eec/tornado-6.5.5-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:e74c92e8e65086b338fd56333fb9a68b9f6f2fe7ad532645a290a464bcf46be5", size = 447229 },
- { url = "https://files.pythonhosted.org/packages/34/01/74e034a30ef59afb4097ef8659515e96a39d910b712a89af76f5e4e1f93c/tornado-6.5.5-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:435319e9e340276428bbdb4e7fa732c2d399386d1de5686cb331ec8eee754f07", size = 448192 },
- { url = "https://files.pythonhosted.org/packages/be/00/fe9e02c5a96429fce1a1d15a517f5d8444f9c412e0bb9eadfbe3b0fc55bf/tornado-6.5.5-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:3f54aa540bdbfee7b9eb268ead60e7d199de5021facd276819c193c0fb28ea4e", size = 448039 },
- { url = "https://files.pythonhosted.org/packages/82/9e/656ee4cec0398b1d18d0f1eb6372c41c6b889722641d84948351ae19556d/tornado-6.5.5-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:36abed1754faeb80fbd6e64db2758091e1320f6bba74a4cf8c09cd18ccce8aca", size = 447445 },
- { url = "https://files.pythonhosted.org/packages/5a/76/4921c00511f88af86a33de770d64141170f1cfd9c00311aea689949e274e/tornado-6.5.5-cp39-abi3-win32.whl", hash = "sha256:dd3eafaaeec1c7f2f8fdcd5f964e8907ad788fe8a5a32c4426fbbdda621223b7", size = 448582 },
- { url = "https://files.pythonhosted.org/packages/2c/23/f6c6112a04d28eed765e374435fb1a9198f73e1ec4b4024184f21faeb1ad/tornado-6.5.5-cp39-abi3-win_amd64.whl", hash = "sha256:6443a794ba961a9f619b1ae926a2e900ac20c34483eea67be4ed8f1e58d3ef7b", size = 448990 },
- { url = "https://files.pythonhosted.org/packages/b7/c8/876602cbc96469911f0939f703453c1157b0c826ecb05bdd32e023397d4e/tornado-6.5.5-cp39-abi3-win_arm64.whl", hash = "sha256:2c9a876e094109333f888539ddb2de4361743e5d21eece20688e3e351e4990a6", size = 448016 },
+ { url = "https://files.pythonhosted.org/packages/02/dc/c7043cab6fed8ae159fc1923ce829ada35c4dbd797d408a43858ffaf9639/tornado-6.5.7-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:148b2eb15c2c765a50796172c1e499649b35f30d2e3c3d3e15913cfa56bfb163", size = 448543 },
+ { url = "https://files.pythonhosted.org/packages/92/4f/090b1431e5a43df696feceffc268c5383cc079ecb5f08ce58f917109aafe/tornado-6.5.7-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9da38de27f1da3b78a966f0dae12b5a1ea9afe72ca805d84ff06508272ddf100", size = 446707 },
+ { url = "https://files.pythonhosted.org/packages/37/d8/ef374952fd5da67d4463122c2b8e5a96536ec10b4b339254c6dcde81d01c/tornado-6.5.7-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8d759e71906ee783f8867b93bf26a265743da4c1e2f4a018464c1ba019862972", size = 449774 },
+ { url = "https://files.pythonhosted.org/packages/35/37/d434c73f4c6e014b745b9b37085f34f40c022f007efff3d7fe65991899f3/tornado-6.5.7-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8a46347a18f23fb92b396beebe0fb78f61dda0cc302445202c16203d8a18848b", size = 450745 },
+ { url = "https://files.pythonhosted.org/packages/b6/2b/56b9aff361d7f1ab728a805ec7d7ea835f8807afa9f5cc690ea0e630efb9/tornado-6.5.7-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7778b30bef919231265e91c69963ce0f49a1e9c07ac900bbe75b19ce2575ba92", size = 450578 },
+ { url = "https://files.pythonhosted.org/packages/02/30/a7444fb23aa76860a14198fab96ac79f1866b0a6e19e26c4381b0938e50f/tornado-6.5.7-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e726f0c75da7726eec023aa62751ff8878bd2737e34fbdd33b1ae5897d2200f5", size = 449985 },
+ { url = "https://files.pythonhosted.org/packages/5c/42/5f0e56c01e8d9d36f4e23f367b85ae6cae0c1ecddd5e6977d8388ad27488/tornado-6.5.7-cp39-abi3-win32.whl", hash = "sha256:f8de3bf12d3efdd0cbe7c8887868198f8a91415e3f29fcf258d9b8eb7b1d9ae4", size = 451047 },
+ { url = "https://files.pythonhosted.org/packages/c9/a4/b393076ffb21b469eec5b328a0534cf03a3b90bfc6b1f09507cdd075d938/tornado-6.5.7-cp39-abi3-win_amd64.whl", hash = "sha256:de942f843533a039ef9fa3d9c88c7cd8a7c94553fb5ad0154270989b3d99a2c4", size = 451485 },
+ { url = "https://files.pythonhosted.org/packages/71/2e/7b1c769803121b809112cf9a00681c472eae1d80e32d7ec0e0bd61d0d0e1/tornado-6.5.7-cp39-abi3-win_arm64.whl", hash = "sha256:ff934fce95643af5f11efdae618eaa73d469dc588641e5c8d19295a0c65c4796", size = 450506 },
]
[[package]]
@@ -7182,21 +7188,23 @@ wheels = [
[[package]]
name = "ujson"
-version = "5.12.1"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/bc/78/937198ea8708182dd1edbf0237bf255a96feab3f511691ad08b84da98e5d/ujson-5.12.1.tar.gz", hash = "sha256:5b7e96406c301a1366534479a7352ec40ec68bb327c0c119091635acd5925e35", size = 7164538 }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/d7/40/dbb8e2fe6ee33769602fba203dacaa3963b6599f0d0aefdf2b8811af5f70/ujson-5.12.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:10f44bd08ae52ee23ca6e8b472692e5da1768af2d53ff1bad6f40b532e0bc7ee", size = 57951 },
- { url = "https://files.pythonhosted.org/packages/8d/db/627472e6b4ac34148ea52e6d3d15f6f366fc21c72fe7d6c7d3729d4b3ac5/ujson-5.12.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6cc6ea753b7303fa5629fa9ac9257ea4b001c4d72583b2bb36ff1855a07db49f", size = 55562 },
- { url = "https://files.pythonhosted.org/packages/be/59/1248c966da197ae7d2673542444a2d9a1ff7c46e3ec2a302c3caf902b922/ujson-5.12.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:289f13095764d03734adfa10107da9b530ceb64dc1b02a5f507588d978d5b7df", size = 59448 },
- { url = "https://files.pythonhosted.org/packages/d5/d7/60c1ca71a09c0654c3edca1192a18fc55e6cc06107be86d7d3f2b39fb29b/ujson-5.12.1-cp312-cp312-manylinux_2_24_i686.manylinux_2_28_i686.whl", hash = "sha256:427893168d074e59214b0ee058337c57f5bb80175cdd5b4799a9c931aae22022", size = 61608 },
- { url = "https://files.pythonhosted.org/packages/d5/0a/c619525576219bfc50084100117481b1a732a16716a3878355570995de4e/ujson-5.12.1-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a7a81724d5d90a2da7155d15d8b156ce57eaed7cdd622df813f36a8e612fd4c8", size = 59113 },
- { url = "https://files.pythonhosted.org/packages/18/4d/79c1674036085e8dfdb77f8d87c1fd2896e97e6affd117c5e8ecc40f0ae4/ujson-5.12.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3a6efff7dc6515416366819de4a1bc449b77107c5b48508b101fd40f7f8bec08", size = 1038914 },
- { url = "https://files.pythonhosted.org/packages/94/b1/9409bba17189ee282b6314cdf0ecdcc72e3d38cd565c870c0227d0494569/ujson-5.12.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:77a71fe53427a0cf49d56eafd801d9f7e203b784b7f99cc717783fd6f6f7b732", size = 1198408 },
- { url = "https://files.pythonhosted.org/packages/4b/ad/fafbce7ac59f1a10a83892d0a34add23cc06492308e1330493aab707dc20/ujson-5.12.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ea3bed53d2ea8e5642e814a9e41f3e29420a8067874ba03ace8c0462e160490c", size = 1091451 },
- { url = "https://files.pythonhosted.org/packages/5a/1f/76fc9d5b1dcb9eb73ed45fd56e5114391bd30808eb1cea7f8bc5c9a64324/ujson-5.12.1-cp312-cp312-win32.whl", hash = "sha256:758e5c8fbe4e6d483041e03b307b01fb5d2f2dd4452d4d4b927ab902e188939e", size = 41049 },
- { url = "https://files.pythonhosted.org/packages/35/2a/7ce3b6fda10d05b79a245db03405734b521ba3da6c377f173b018dce6d4e/ujson-5.12.1-cp312-cp312-win_amd64.whl", hash = "sha256:f6074d3d3267ba1914c624b6e1fa3d8152648ff36b0ab77ddf83b92db488c30d", size = 45330 },
- { url = "https://files.pythonhosted.org/packages/d7/66/5a37bba7a2e2ab36ae467521c4511e6593ad74c869f62ec4ba6330f3f71e/ujson-5.12.1-cp312-cp312-win_arm64.whl", hash = "sha256:7642a41520ac1b2bc25ea282b66b8da522cc43424442e6fb5e039be4d4f96530", size = 39828 },
+version = "5.13.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/89/7a/c8bb37c8f6f3623d60c33d15d18cd6d6655d0f9c3eb31a9969f76361b199/ujson-5.13.0.tar.gz", hash = "sha256:d62e3d7625384c08082abad81a077af587fdef2761bb14c3822f4234b8d07d75", size = 7166784 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ee/ae/b66deca15da1f7faf6952d8eddf55978482bcbfd294ed2afe2c526ea325f/ujson-5.13.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:bf81570ac056cb058f9117b52ca5dd800bfe9381d0076d0bb30a08a54591d654", size = 56743 },
+ { url = "https://files.pythonhosted.org/packages/88/4f/b03bcc9eaf4621ac9008dec90918d8fb4839d611666cb99eb255696c67fe/ujson-5.13.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7edf16359c52ed53406e216565d83e6b98c23c3cb9a0a01673f2493f8fb15edf", size = 54390 },
+ { url = "https://files.pythonhosted.org/packages/77/79/f98c6c1a4ed9d92d39d5d2d133f2b6fce5da11ea50c341117aedde8011c4/ujson-5.13.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:24539618fb3243cfdf27dab9a850acab80798a01501e9586b61fb9ecd016a891", size = 60047 },
+ { url = "https://files.pythonhosted.org/packages/bc/1d/f68e14cf476d149945211142f4c20782c1f232c489e8edcc4f4b58ce4997/ujson-5.13.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fdde6341d213b29f413b5fa9fad1392d5408074c75f0900ed949e97e546fa5df", size = 53437 },
+ { url = "https://files.pythonhosted.org/packages/7d/1a/5718237cf4141e5be46ff371387e90b01f27774cb6f0f79ff4803a2430ca/ujson-5.13.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:229faf041ef249ee3fd57bac1cedb123d2718ab63f6ccd50eca95ea902eb0dca", size = 55057 },
+ { url = "https://files.pythonhosted.org/packages/f6/6f/7f55c1e9e0be87beebaed553fa186ad5f6d5d639cbaa9d49f78f2f91c3a9/ujson-5.13.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1d02f31c2f59cc6a1c2c3633b377701fc2d8e876cc01950735d7a01132ccc233", size = 58186 },
+ { url = "https://files.pythonhosted.org/packages/bc/c4/9a34ade542426f56a0bc042f774073d1c247ae7575363c27587788cb2b2f/ujson-5.13.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ea7204e9fa7538bfbb1396e1ee8c2bbcd3818b3633ef5bb14d4fdea52994d14d", size = 57935 },
+ { url = "https://files.pythonhosted.org/packages/36/06/407633f0709e168107f56368bd5a0fa8fe07acd7f1d3000710bc0bb07470/ujson-5.13.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7c5a2478a3a1fa4421f7e035b87194eea0cf44c7971a3f32ad1b42a0dfd63c03", size = 1037685 },
+ { url = "https://files.pythonhosted.org/packages/c3/df/eb5bd92dc1b23254fea5b2022007baff5491a7478bfcf7e9260d3a10f1ac/ujson-5.13.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:b535e0970c96957e999cfe5ec89361f0e8d0bb987fb5d5144f6f495cb3ed9e19", size = 1197141 },
+ { url = "https://files.pythonhosted.org/packages/cb/1c/65f2ce1a0411ec9a87339db01f0d5d554a49c4248ec68ab52a1b7e14e9c4/ujson-5.13.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3d0ad1207694988498fca7e0bb28eba7564fa33261d2f9fdf66a3aaab376b803", size = 1090225 },
+ { url = "https://files.pythonhosted.org/packages/73/53/310aabff0704f9c7ef0d3f431ce8b8e3147c3cca25334a205615c511f65e/ujson-5.13.0-cp312-cp312-win32.whl", hash = "sha256:d6bc9fa43a49e403c68c7eb164eef0feee9dd29474a7c6e0d3b6267025371990", size = 40075 },
+ { url = "https://files.pythonhosted.org/packages/b5/23/d3536d8945d1bb00248d998c8dcbe678a884681ad181072daecfafe4eea6/ujson-5.13.0-cp312-cp312-win_amd64.whl", hash = "sha256:6692d49ff970aaa5008f4a6fe06974bc91fd957bf13173f765e46d8ba44906ea", size = 41097 },
+ { url = "https://files.pythonhosted.org/packages/72/a1/4b147c06ee5bb14bec6e26786358c8510c4d75e28b88146a6ac7620f1f71/ujson-5.13.0-cp312-cp312-win_arm64.whl", hash = "sha256:5737ffe0740a788b0e6255f0ffb281db49305fd6e6a587be44c73d9e92b554c4", size = 38875 },
]
[[package]]